LLVM 24.0.0git
ScalarEvolution.cpp
Go to the documentation of this file.
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
61#include "llvm/ADT/APInt.h"
62#include "llvm/ADT/ArrayRef.h"
63#include "llvm/ADT/DenseMap.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"
71#include "llvm/ADT/Statistic.h"
73#include "llvm/ADT/StringRef.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"
89#include "llvm/IR/Constants.h"
90#include "llvm/IR/DataLayout.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"
97#include "llvm/IR/InstrTypes.h"
98#include "llvm/IR/Instruction.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"
111#include "llvm/Pass.h"
112#include "llvm/Support/Casting.h"
115#include "llvm/Support/Debug.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
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(100));
159
161 "verify-scev", cl::Hidden, cl::location(VerifySCEV),
162 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
164 "verify-scev-strict", cl::Hidden,
165 cl::desc("Enable stricter verification with -verify-scev is passed"));
166
168 "scev-verify-ir", cl::Hidden,
169 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
170 cl::init(false));
171
173 "scev-mulops-inline-threshold", cl::Hidden,
174 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
175 cl::init(32));
176
178 "scev-addops-inline-threshold", cl::Hidden,
179 cl::desc("Threshold for inlining addition operands into a SCEV"),
180 cl::init(500));
181
183 "scalar-evolution-max-scev-compare-depth", cl::Hidden,
184 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
185 cl::init(32));
186
188 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
189 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
190 cl::init(2));
191
193 "scalar-evolution-max-value-compare-depth", cl::Hidden,
194 cl::desc("Maximum depth of recursive value complexity comparisons"),
195 cl::init(2));
196
198 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
199 cl::desc("Maximum depth of recursive arithmetics"),
200 cl::init(32));
201
203 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
204 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
205
207 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
208 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
209 cl::init(8));
210
212 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
213 cl::desc("Max coefficients in AddRec during evolving"),
214 cl::init(8));
215
217 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
218 cl::desc("Size of the expression which is considered huge"),
219 cl::init(4096));
220
222 "scev-range-iter-threshold", cl::Hidden,
223 cl::desc("Threshold for switching to iteratively computing SCEV ranges"),
224 cl::init(32));
225
227 "scalar-evolution-max-loop-guard-collection-depth", cl::Hidden,
228 cl::desc("Maximum depth for recursive loop guard collection"), cl::init(1));
229
230static cl::opt<bool>
231ClassifyExpressions("scalar-evolution-classify-expressions",
232 cl::Hidden, cl::init(true),
233 cl::desc("When printing analysis, include information on every instruction"));
234
236 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
237 cl::init(false),
238 cl::desc("Use more powerful methods of sharpening expression ranges. May "
239 "be costly in terms of compile time"));
240
241static cl::opt<bool>
242 EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
243 cl::desc("Handle <= and >= in finite loops"),
244 cl::init(true));
245
247 "scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden,
248 cl::desc("Infer nuw/nsw flags using context where suitable"),
249 cl::init(true));
250
251//===----------------------------------------------------------------------===//
252// SCEV class definitions
253//===----------------------------------------------------------------------===//
254
256 // Leaf nodes are always their own canonical.
257 switch (getSCEVType()) {
258 case scConstant:
259 case scVScale:
260 case scUnknown:
261 CanonicalSCEV = this;
262 return;
263 default:
264 break;
265 }
266
267 // For all other expressions, check whether any immediate operand has a
268 // different canonical. Since operands are always created before their parent,
269 // their canonical pointers are already set — no recursion needed.
270 bool Changed = false;
272 for (SCEVUse Op : operands()) {
273 CanonOps.push_back(Op->getCanonical());
274 Changed |= CanonOps.back() != Op;
275 }
276
277 if (!Changed) {
278 CanonicalSCEV = this;
279 return;
280 }
281
282 // Rebuild the expression from the canonical operands, stripping use flags.
283 CanonicalSCEV = SE.getWithOperands(this, CanonOps);
284}
285
286//===----------------------------------------------------------------------===//
287// Implementation of the SCEV class.
288//
289
290#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
292 print(dbgs());
293 dbgs() << '\n';
294}
295#endif
296
297void SCEV::print(raw_ostream &OS) const {
298 switch (getSCEVType()) {
299 case scConstant:
300 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
301 return;
302 case scVScale:
303 OS << "vscale";
304 return;
305 case scPtrToAddr: {
306 const SCEVCastExpr *PtrCast = cast<SCEVCastExpr>(this);
307 SCEVUse Op = PtrCast->getOperand();
308 OS << "(ptrtoaddr " << *Op->getType() << " " << Op << " to "
309 << *PtrCast->getType() << ")";
310 return;
311 }
312 case scTruncate: {
313 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
314 SCEVUse Op = Trunc->getOperand();
315 OS << "(trunc " << *Op->getType() << " " << Op << " to "
316 << *Trunc->getType() << ")";
317 return;
318 }
319 case scZeroExtend: {
321 SCEVUse Op = ZExt->getOperand();
322 OS << "(zext " << *Op->getType() << " " << Op << " to " << *ZExt->getType()
323 << ")";
324 return;
325 }
326 case scSignExtend: {
328 SCEVUse Op = SExt->getOperand();
329 OS << "(sext " << *Op->getType() << " " << Op << " to " << *SExt->getType()
330 << ")";
331 return;
332 }
333 case scAddRecExpr: {
334 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
335 OS << "{" << AR->getOperand(0);
336 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
337 OS << ",+," << AR->getOperand(i);
338 OS << "}<";
339 if (AR->hasNoUnsignedWrap())
340 OS << "nuw><";
341 if (AR->hasNoSignedWrap())
342 OS << "nsw><";
343 if (AR->hasNoSelfWrap() && !AR->hasNoUnsignedWrap() &&
344 !AR->hasNoSignedWrap())
345 OS << "nw><";
346 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
347 OS << ">";
348 return;
349 }
350 case scAddExpr:
351 case scMulExpr:
352 case scUMaxExpr:
353 case scSMaxExpr:
354 case scUMinExpr:
355 case scSMinExpr:
357 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
358 const char *OpStr = nullptr;
359 switch (NAry->getSCEVType()) {
360 case scAddExpr: OpStr = " + "; break;
361 case scMulExpr: OpStr = " * "; break;
362 case scUMaxExpr: OpStr = " umax "; break;
363 case scSMaxExpr: OpStr = " smax "; break;
364 case scUMinExpr:
365 OpStr = " umin ";
366 break;
367 case scSMinExpr:
368 OpStr = " smin ";
369 break;
371 OpStr = " umin_seq ";
372 break;
373 default:
374 llvm_unreachable("There are no other nary expression types.");
375 }
376 OS << "(" << llvm::interleaved(NAry->operands(), OpStr) << ")";
377 switch (NAry->getSCEVType()) {
378 case scAddExpr:
379 case scMulExpr:
380 if (NAry->hasNoUnsignedWrap())
381 OS << "<nuw>";
382 if (NAry->hasNoSignedWrap())
383 OS << "<nsw>";
384 break;
385 default:
386 // Nothing to print for other nary expressions.
387 break;
388 }
389 return;
390 }
391 case scUDivExpr: {
392 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
393 OS << "(" << UDiv->getLHS() << " /u " << UDiv->getRHS() << ")";
394 return;
395 }
396 case scUnknown:
397 cast<SCEVUnknown>(this)->getValue()->printAsOperand(OS, false);
398 return;
400 OS << "***COULDNOTCOMPUTE***";
401 return;
402 }
403 llvm_unreachable("Unknown SCEV kind!");
404}
405
407 switch (getSCEVType()) {
408 case scConstant:
409 case scVScale:
410 case scUnknown:
411 return {};
412 case scPtrToAddr:
413 case scTruncate:
414 case scZeroExtend:
415 case scSignExtend:
416 return cast<SCEVCastExpr>(this)->operands();
417 case scAddRecExpr:
418 case scAddExpr:
419 case scMulExpr:
420 case scUMaxExpr:
421 case scSMaxExpr:
422 case scUMinExpr:
423 case scSMinExpr:
425 return cast<SCEVNAryExpr>(this)->operands();
426 case scUDivExpr:
427 return cast<SCEVUDivExpr>(this)->operands();
429 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
430 }
431 llvm_unreachable("Unknown SCEV kind!");
432}
433
434bool SCEV::isZero() const { return match(this, m_scev_Zero()); }
435
436bool SCEV::isOne() const { return match(this, m_scev_One()); }
437
438bool SCEV::isAllOnesValue() const { return match(this, m_scev_AllOnes()); }
439
442 if (!Mul) return false;
443
444 // If there is a constant factor, it will be first.
445 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
446 if (!SC) return false;
447
448 // Return true if the value is negative, this matches things like (-42 * V).
449 return SC->getAPInt().isNegative();
450}
451
454
456 return S->getSCEVType() == scCouldNotCompute;
457}
458
460 auto &Entry = ConstantSCEVs[V];
461 if (Entry)
462 return Entry;
463
466 ID.AddPointer(V);
468 if (SCEVConstant *S =
469 static_cast<SCEVConstant *>(UniqueSCEVs.lookup(ID, Token)))
470 return Entry = S;
471 SCEVConstant *S =
472 new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
473 UniqueSCEVs.insert(S, Token);
474 S->computeAndSetCanonical(*this);
475 return Entry = S;
476}
477
479 return getConstant(ConstantInt::get(getContext(), Val));
480}
481
482const SCEV *
485 // TODO: Avoid implicit trunc?
486 // See https://github.com/llvm/llvm-project/issues/112510.
487 return getConstant(
488 ConstantInt::get(ITy, V, isSigned, /*ImplicitTrunc=*/true));
489}
490
494 ID.AddPointer(Ty);
496 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
497 return S;
498 SCEV *S = new (SCEVAllocator) SCEVVScale(ID.Intern(SCEVAllocator), Ty);
499 UniqueSCEVs.insert(S, Token);
500 S->computeAndSetCanonical(*this);
501 return S;
502}
503
505 SCEV::NoWrapFlags Flags) {
506 const SCEV *Res = getConstant(Ty, EC.getKnownMinValue());
507 if (EC.isScalable())
508 Res = getMulExpr(Res, getVScale(Ty), Flags);
509 return Res;
510}
511
513 SCEVUse op, Type *ty)
514 : SCEV(ID, SCEVTy, computeExpressionSize(op), ty), Op(op) {}
515
516SCEVPtrToAddrExpr::SCEVPtrToAddrExpr(const FoldingSetNodeIDRef ID,
517 const SCEV *Op, Type *ITy)
518 : SCEVCastExpr(ID, scPtrToAddr, Op, ITy) {
519 assert(getOperand()->getType()->isPointerTy() && getType()->isIntegerTy() &&
520 "Must be a non-bit-width-changing pointer-to-integer cast!");
521}
522
527
528SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
529 Type *ty)
531 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
532 "Cannot truncate non-integer value!");
533}
534
535SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
536 Type *ty)
538 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
539 "Cannot zero extend non-integer value!");
540}
541
542SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
543 Type *ty)
545 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
546 "Cannot sign extend non-integer value!");
547}
548
550 // Clear this SCEVUnknown from various maps.
551 SE->forgetMemoizedResults({this});
552
553 // Remove this SCEVUnknown from the uniquing map.
554 SE->UniqueSCEVs.erase(this);
555
556 // Release the value.
557 setValPtr(nullptr);
558}
559
560void SCEVUnknown::allUsesReplacedWith(Value *New) {
561 // Clear this SCEVUnknown from various maps.
562 SE->forgetMemoizedResults({this});
563
564 // Remove this SCEVUnknown from the uniquing map.
565 SE->UniqueSCEVs.erase(this);
566
567 // Replace the value pointer in case someone is still using this SCEVUnknown.
568 setValPtr(New);
569}
570
571//===----------------------------------------------------------------------===//
572// SCEV Utilities
573//===----------------------------------------------------------------------===//
574
575/// Compare the two values \p LV and \p RV in terms of their "complexity" where
576/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
577/// operands in SCEV expressions.
578static int CompareValueComplexity(const LoopInfo *const LI, Value *LV,
579 Value *RV, unsigned Depth) {
581 return 0;
582
583 // Order pointer values after integer values. This helps SCEVExpander form
584 // GEPs.
585 bool LIsPointer = LV->getType()->isPointerTy(),
586 RIsPointer = RV->getType()->isPointerTy();
587 if (LIsPointer != RIsPointer)
588 return (int)LIsPointer - (int)RIsPointer;
589
590 // Compare getValueID values.
591 unsigned LID = LV->getValueID(), RID = RV->getValueID();
592 if (LID != RID)
593 return (int)LID - (int)RID;
594
595 // Sort arguments by their position.
596 if (const auto *LA = dyn_cast<Argument>(LV)) {
597 const auto *RA = cast<Argument>(RV);
598 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
599 return (int)LArgNo - (int)RArgNo;
600 }
601
602 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
603 const auto *RGV = cast<GlobalValue>(RV);
604
605 if (auto L = LGV->getLinkage() - RGV->getLinkage())
606 return L;
607
608 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
609 auto LT = GV->getLinkage();
610 return !(GlobalValue::isPrivateLinkage(LT) ||
612 };
613
614 // Use the names to distinguish the two values, but only if the
615 // names are semantically important.
616 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
617 return LGV->getName().compare(RGV->getName());
618 }
619
620 // For instructions, compare their loop depth, and their operand count. This
621 // is pretty loose.
622 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
623 const auto *RInst = cast<Instruction>(RV);
624
625 // Compare loop depths.
626 const BasicBlock *LParent = LInst->getParent(),
627 *RParent = RInst->getParent();
628 if (LParent != RParent) {
629 unsigned LDepth = LI->getLoopDepth(LParent),
630 RDepth = LI->getLoopDepth(RParent);
631 if (LDepth != RDepth)
632 return (int)LDepth - (int)RDepth;
633 }
634
635 // Compare the number of operands.
636 unsigned LNumOps = LInst->getNumOperands(),
637 RNumOps = RInst->getNumOperands();
638 if (LNumOps != RNumOps)
639 return (int)LNumOps - (int)RNumOps;
640
641 for (unsigned Idx : seq(LNumOps)) {
642 int Result = CompareValueComplexity(LI, LInst->getOperand(Idx),
643 RInst->getOperand(Idx), Depth + 1);
644 if (Result != 0)
645 return Result;
646 }
647 }
648
649 return 0;
650}
651
652// Return negative, zero, or positive, if LHS is less than, equal to, or greater
653// than RHS, respectively. A three-way result allows recursive comparisons to be
654// more efficient.
655// If the max analysis depth was reached, return std::nullopt, assuming we do
656// not know if they are equivalent for sure.
657static std::optional<int>
658CompareSCEVComplexity(const LoopInfo *const LI, const SCEV *LHS,
659 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
660 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
661 if (LHS == RHS)
662 return 0;
663
664 // Primarily, sort the SCEVs by their getSCEVType().
665 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
666 if (LType != RType)
667 return (int)LType - (int)RType;
668
670 return std::nullopt;
671
672 // Aside from the getSCEVType() ordering, the particular ordering
673 // isn't very important except that it's beneficial to be consistent,
674 // so that (a + b) and (b + a) don't end up as different expressions.
675 switch (LType) {
676 case scUnknown: {
677 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
678 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
679
680 int X =
681 CompareValueComplexity(LI, LU->getValue(), RU->getValue(), Depth + 1);
682 return X;
683 }
684
685 case scConstant: {
688
689 // Compare constant values.
690 const APInt &LA = LC->getAPInt();
691 const APInt &RA = RC->getAPInt();
692 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
693 if (LBitWidth != RBitWidth)
694 return (int)LBitWidth - (int)RBitWidth;
695 return LA.ult(RA) ? -1 : 1;
696 }
697
698 case scVScale: {
699 const auto *LTy = cast<IntegerType>(cast<SCEVVScale>(LHS)->getType());
700 const auto *RTy = cast<IntegerType>(cast<SCEVVScale>(RHS)->getType());
701 return LTy->getBitWidth() - RTy->getBitWidth();
702 }
703
704 case scAddRecExpr: {
707
708 // There is always a dominance between two recs that are used by one SCEV,
709 // so we can safely sort recs by loop header dominance. We require such
710 // order in getAddExpr.
711 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
712 if (LLoop != RLoop) {
713 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
714 assert(LHead != RHead && "Two loops share the same header?");
715 if (DT.dominates(LHead, RHead))
716 return 1;
717 assert(DT.dominates(RHead, LHead) &&
718 "No dominance between recurrences used by one SCEV?");
719 return -1;
720 }
721
722 [[fallthrough]];
723 }
724
725 case scTruncate:
726 case scZeroExtend:
727 case scSignExtend:
728 case scPtrToAddr:
729 case scAddExpr:
730 case scMulExpr:
731 case scUDivExpr:
732 case scSMaxExpr:
733 case scUMaxExpr:
734 case scSMinExpr:
735 case scUMinExpr:
737 ArrayRef<SCEVUse> LOps = LHS->operands();
738 ArrayRef<SCEVUse> ROps = RHS->operands();
739
740 // Lexicographically compare n-ary-like expressions.
741 unsigned LNumOps = LOps.size(), RNumOps = ROps.size();
742 if (LNumOps != RNumOps)
743 return (int)LNumOps - (int)RNumOps;
744
745 for (unsigned i = 0; i != LNumOps; ++i) {
746 auto X = CompareSCEVComplexity(LI, LOps[i].getPointer(),
747 ROps[i].getPointer(), DT, Depth + 1);
748 if (X != 0)
749 return X;
750 }
751 return 0;
752 }
753
755 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
756 }
757 llvm_unreachable("Unknown SCEV kind!");
758}
759
760/// Given a list of SCEV objects, order them by their complexity, and group
761/// objects of the same complexity together by value. When this routine is
762/// finished, we know that any duplicates in the vector are consecutive and that
763/// complexity is monotonically increasing.
764///
765/// Note that we go take special precautions to ensure that we get deterministic
766/// results from this routine. In other words, we don't want the results of
767/// this to depend on where the addresses of various SCEV objects happened to
768/// land in memory.
770 DominatorTree &DT) {
771 if (Ops.size() < 2) return; // Noop
772
773 // Whether LHS has provably less complexity than RHS.
774 auto IsLessComplex = [&](SCEVUse LHS, SCEVUse RHS) {
775 auto Complexity = CompareSCEVComplexity(LI, LHS, RHS, DT);
776 return Complexity && *Complexity < 0;
777 };
778 if (Ops.size() == 2) {
779 // This is the common case, which also happens to be trivially simple.
780 // Special case it.
781 SCEVUse &LHS = Ops[0], &RHS = Ops[1];
782 if (IsLessComplex(RHS, LHS))
783 std::swap(LHS, RHS);
784 return;
785 }
786
787 // Do the rough sort by complexity.
789 Ops, [&](SCEVUse LHS, SCEVUse RHS) { return IsLessComplex(LHS, RHS); });
790
791 // Now that we are sorted by complexity, group elements of the same
792 // complexity. Note that this is, at worst, N^2, but the vector is likely to
793 // be extremely short in practice. Note that we take this approach because we
794 // do not want to depend on the addresses of the objects we are grouping.
795 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
796 const SCEV *S = Ops[i];
797 unsigned Complexity = S->getSCEVType();
798
799 // If there are any objects of the same complexity and same value as this
800 // one, group them.
801 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
802 if (Ops[j] == S) { // Found a duplicate.
803 // Move it to immediately after i'th element.
804 std::swap(Ops[i+1], Ops[j]);
805 ++i; // no need to rescan it.
806 if (i == e-2) return; // Done!
807 }
808 }
809 }
810}
811
812/// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
813/// least HugeExprThreshold nodes).
815 return any_of(Ops, [](const SCEV *S) {
817 });
818}
819
820/// Performs a number of common optimizations on the passed \p Ops. If the
821/// whole expression reduces down to a single operand, it will be returned.
822///
823/// The following optimizations are performed:
824/// * Fold constants using the \p Fold function.
825/// * Remove identity constants satisfying \p IsIdentity.
826/// * If a constant satisfies \p IsAbsorber, return it.
827/// * Sort operands by complexity.
828template <typename FoldT, typename IsIdentityT, typename IsAbsorberT>
829static const SCEV *
831 SmallVectorImpl<SCEVUse> &Ops, FoldT Fold,
832 IsIdentityT IsIdentity, IsAbsorberT IsAbsorber) {
833 const SCEVConstant *Folded = nullptr;
834 for (unsigned Idx = 0; Idx < Ops.size();) {
835 const SCEV *Op = Ops[Idx];
836 if (const auto *C = dyn_cast<SCEVConstant>(Op)) {
837 if (!Folded)
838 Folded = C;
839 else
840 Folded = cast<SCEVConstant>(
841 SE.getConstant(Fold(Folded->getAPInt(), C->getAPInt())));
842 Ops.erase(Ops.begin() + Idx);
843 continue;
844 }
845 ++Idx;
846 }
847
848 if (Ops.empty()) {
849 assert(Folded && "Must have folded value");
850 return Folded;
851 }
852
853 if (Folded && IsAbsorber(Folded->getAPInt()))
854 return Folded;
855
856 GroupByComplexity(Ops, &LI, DT);
857 if (Folded && !IsIdentity(Folded->getAPInt()))
858 Ops.insert(Ops.begin(), Folded);
859
860 return Ops.size() == 1 ? Ops[0] : nullptr;
861}
862
863//===----------------------------------------------------------------------===//
864// Simple SCEV method implementations
865//===----------------------------------------------------------------------===//
866
867/// Compute BC(It, K). The result has width W. Assume, K > 0.
868static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
869 ScalarEvolution &SE,
870 Type *ResultTy) {
871 // Handle the simplest case efficiently.
872 if (K == 1)
873 return SE.getTruncateOrZeroExtend(It, ResultTy);
874
875 // We are using the following formula for BC(It, K):
876 //
877 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
878 //
879 // Suppose, W is the bitwidth of the return value. We must be prepared for
880 // overflow. Hence, we must assure that the result of our computation is
881 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
882 // safe in modular arithmetic.
883 //
884 // However, this code doesn't use exactly that formula; the formula it uses
885 // is something like the following, where T is the number of factors of 2 in
886 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
887 // exponentiation:
888 //
889 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
890 //
891 // This formula is trivially equivalent to the previous formula. However,
892 // this formula can be implemented much more efficiently. The trick is that
893 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
894 // arithmetic. To do exact division in modular arithmetic, all we have
895 // to do is multiply by the inverse. Therefore, this step can be done at
896 // width W.
897 //
898 // The next issue is how to safely do the division by 2^T. The way this
899 // is done is by doing the multiplication step at a width of at least W + T
900 // bits. This way, the bottom W+T bits of the product are accurate. Then,
901 // when we perform the division by 2^T (which is equivalent to a right shift
902 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
903 // truncated out after the division by 2^T.
904 //
905 // In comparison to just directly using the first formula, this technique
906 // is much more efficient; using the first formula requires W * K bits,
907 // but this formula less than W + K bits. Also, the first formula requires
908 // a division step, whereas this formula only requires multiplies and shifts.
909 //
910 // It doesn't matter whether the subtraction step is done in the calculation
911 // width or the input iteration count's width; if the subtraction overflows,
912 // the result must be zero anyway. We prefer here to do it in the width of
913 // the induction variable because it helps a lot for certain cases; CodeGen
914 // isn't smart enough to ignore the overflow, which leads to much less
915 // efficient code if the width of the subtraction is wider than the native
916 // register width.
917 //
918 // (It's possible to not widen at all by pulling out factors of 2 before
919 // the multiplication; for example, K=2 can be calculated as
920 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
921 // extra arithmetic, so it's not an obvious win, and it gets
922 // much more complicated for K > 3.)
923
924 // Protection from insane SCEVs; this bound is conservative,
925 // but it probably doesn't matter.
926 if (K > 1000)
927 return SE.getCouldNotCompute();
928
929 unsigned W = SE.getTypeSizeInBits(ResultTy);
930
931 // Calculate K! / 2^T and T; we divide out the factors of two before
932 // multiplying for calculating K! / 2^T to avoid overflow.
933 // Other overflow doesn't matter because we only care about the bottom
934 // W bits of the result.
935 APInt OddFactorial(W, 1);
936 unsigned T = 1;
937 for (unsigned i = 3; i <= K; ++i) {
938 unsigned TwoFactors = countr_zero(i);
939 T += TwoFactors;
940 OddFactorial *= (i >> TwoFactors);
941 }
942
943 // We need at least W + T bits for the multiplication step
944 unsigned CalculationBits = W + T;
945
946 // Calculate 2^T, at width T+W.
947 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
948
949 // Calculate the multiplicative inverse of K! / 2^T;
950 // this multiplication factor will perform the exact division by
951 // K! / 2^T.
952 APInt MultiplyFactor = OddFactorial.multiplicativeInverse();
953
954 // Calculate the product, at width T+W
955 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
956 CalculationBits);
957 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
958 for (unsigned i = 1; i != K; ++i) {
959 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
960 Dividend = SE.getMulExpr(Dividend,
961 SE.getTruncateOrZeroExtend(S, CalculationTy));
962 }
963
964 // Divide by 2^T
965 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
966
967 // Truncate the result, and divide by K! / 2^T.
968
969 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
970 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
971}
972
973/// Return the value of this chain of recurrences at the specified iteration
974/// number. We can evaluate this recurrence by multiplying each element in the
975/// chain by the binomial coefficient corresponding to it. In other words, we
976/// can evaluate {A,+,B,+,C,+,D} as:
977///
978/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
979///
980/// where BC(It, k) stands for binomial coefficient.
982 ScalarEvolution &SE) const {
983 return evaluateAtIteration(operands(), It, SE);
984}
985
987 const SCEV *It, ScalarEvolution &SE,
988 SCEV::NoWrapFlags UseFlags) {
989 assert(Operands.size() > 0);
990 assert((Operands.size() == 2 || UseFlags == SCEV::FlagNone) &&
991 "use-specific flags only supported for affine AddRecs");
992 SCEVUse Result = Operands[0].getPointer();
993 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
994 // The computation is correct in the face of overflow provided that the
995 // multiplication is performed _after_ the evaluation of the binomial
996 // coefficient.
997 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
998 if (isa<SCEVCouldNotCompute>(Coeff))
999 return Coeff;
1000
1001 SCEVUse Mul = SE.getMulExpr(Operands[i].getPointer(), Coeff,
1002 {SCEV::FlagNone, UseFlags});
1003 Result = SE.getAddExpr(Result, Mul, {SCEV::FlagNone, UseFlags});
1004 }
1005 return Result;
1006}
1007
1009 const SCEV *BTC = SE.getBackedgeTakenCount(getLoop());
1010 if (isa<SCEVCouldNotCompute>(BTC))
1011 return BTC;
1012 // The loop reaches iteration BTC, so the value this recurrence computes there
1013 // is the value it had, and that did not wrap.
1014 return evaluateAtIteration(operands(), BTC, SE,
1016 : SCEV::FlagNone);
1017}
1018
1019//===----------------------------------------------------------------------===//
1020// SCEV Expression folder implementations
1021//===----------------------------------------------------------------------===//
1022
1023/// The SCEVCastSinkingRewriter takes a scalar evolution expression,
1024/// which computes a pointer-typed value, and rewrites the whole expression
1025/// tree so that *all* the computations are done on integers, and the only
1026/// pointer-typed operands in the expression are SCEVUnknown.
1027/// The CreatePtrCast callback is invoked to create the actual conversion
1028/// (ptrtoint or ptrtoaddr) at the SCEVUnknown leaves.
1030 : public SCEVRewriteVisitor<SCEVCastSinkingRewriter> {
1032 using ConversionFn = function_ref<const SCEV *(const SCEVUnknown *)>;
1033 Type *TargetTy;
1034 ConversionFn CreatePtrCast;
1035
1036public:
1038 ConversionFn CreatePtrCast)
1039 : Base(SE), TargetTy(TargetTy), CreatePtrCast(std::move(CreatePtrCast)) {}
1040
1041 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
1042 Type *TargetTy, ConversionFn CreatePtrCast) {
1043 SCEVCastSinkingRewriter Rewriter(SE, TargetTy, std::move(CreatePtrCast));
1044 return Rewriter.visit(Scev);
1045 }
1046
1047 const SCEV *visit(const SCEV *S) {
1048 Type *STy = S->getType();
1049 // If the expression is not pointer-typed, just keep it as-is.
1050 if (!STy->isPointerTy())
1051 return S;
1052 // Else, recursively sink the cast down into it.
1053 return Base::visit(S);
1054 }
1055
1056 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1057 // Preserve wrap flags on rewritten SCEVAddExpr, which the default
1058 // implementation drops.
1060 bool Changed = false;
1061 for (SCEVUse Op : Expr->operands()) {
1062 Operands.push_back(visit(Op.getPointer()));
1063 Changed |= Op.getPointer() != Operands.back();
1064 }
1065 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1066 }
1067
1068 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1069 assert(Expr->getType()->isPointerTy() &&
1070 "Should only reach pointer-typed SCEVUnknown's.");
1071 // Perform some basic constant folding. If the operand of the cast is a
1072 // null pointer, don't create a cast SCEV expression (that will be left
1073 // as-is), but produce a zero constant.
1075 return SE.getZero(TargetTy);
1076 return CreatePtrCast(Expr);
1077 }
1078};
1079
1081 assert(Op->getType()->isPointerTy() && "Op must be a pointer");
1082
1083 // Treat pointers with unstable representation conservatively, since the
1084 // address bits may change.
1085 if (DL.hasUnstableRepresentation(Op->getType()))
1086 return getCouldNotCompute();
1087
1088 Type *Ty = DL.getAddressType(Op->getType());
1089
1090 // Use the rewriter to sink the cast down to SCEVUnknown leaves.
1091 // The rewriter handles null pointer constant folding.
1093 Op, *this, Ty, [this, Ty](const SCEVUnknown *U) {
1096 ID.AddPointer(U);
1097 ID.AddPointer(Ty);
1099 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1100 return S;
1101 SCEV *S = new (SCEVAllocator)
1102 SCEVPtrToAddrExpr(ID.Intern(SCEVAllocator), U, Ty);
1103 UniqueSCEVs.insert(S, Token);
1104 S->computeAndSetCanonical(*this);
1105 registerUser(S, {U});
1106 return static_cast<const SCEV *>(S);
1107 });
1108 assert(IntOp->getType()->isIntegerTy() &&
1109 "We must have succeeded in sinking the cast, "
1110 "and ending up with an integer-typed expression!");
1111 return IntOp;
1112}
1113
1115 unsigned Depth) {
1116 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1117 "This is not a truncating conversion!");
1118 assert(isSCEVable(Ty) &&
1119 "This is not a conversion to a SCEVable type!");
1120 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1121 Ty = getEffectiveSCEVType(Ty);
1122
1125 ID.AddPointer(Op.getOpaqueValue());
1126 ID.AddPointer(Ty);
1128 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1129 return S;
1130
1131 // Fold if the operand is constant.
1132 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1133 return getConstant(
1134 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1135
1136 // trunc(trunc(x)) --> trunc(x)
1138 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1139
1140 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1142 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1143
1144 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1146 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1147
1148 if (Depth > MaxCastDepth) {
1149 SCEV *S =
1150 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1151 UniqueSCEVs.insert(S, Token);
1152 S->computeAndSetCanonical(*this);
1153 registerUser(S, Op);
1154 return S;
1155 }
1156
1157 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1158 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1159 // if after transforming we have at most one truncate, not counting truncates
1160 // that replace other casts.
1162 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1164 unsigned numTruncs = 0;
1165 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1166 ++i) {
1167 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1168 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1170 numTruncs++;
1171 Operands.push_back(S);
1172 }
1173 if (numTruncs < 2) {
1174 if (isa<SCEVAddExpr>(Op))
1175 return getAddExpr(Operands);
1176 if (isa<SCEVMulExpr>(Op))
1177 return getMulExpr(Operands);
1178 llvm_unreachable("Unexpected SCEV type for Op.");
1179 }
1180 // Although we checked in the beginning that ID is not in the cache, it is
1181 // possible that during recursion and different modification ID was inserted
1182 // into the cache. So if we find it, just return it.
1183 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1184 return S;
1185 }
1186
1187 // If the input value is a chrec scev, truncate the chrec's operands.
1188 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1190 for (const SCEV *Op : AddRec->operands())
1191 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1192 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagNone);
1193 }
1194
1195 // Return zero if truncating to known zeros.
1196 uint32_t MinTrailingZeros = getMinTrailingZeros(Op);
1197 if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1198 return getZero(Ty);
1199
1200 // The cast wasn't folded; create an explicit cast node. We can reuse
1201 // the existing insert position since if we get here, we won't have
1202 // made any changes which would invalidate it.
1203 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1204 Op, Ty);
1205 UniqueSCEVs.insert(S, Token);
1206 S->computeAndSetCanonical(*this);
1207 registerUser(S, Op);
1208 return S;
1209}
1210
1211// Get the limit of a recurrence such that incrementing by Step cannot cause
1212// signed overflow as long as the value of the recurrence within the
1213// loop does not exceed this limit before incrementing.
1214static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1215 ICmpInst::Predicate *Pred,
1216 ScalarEvolution *SE) {
1217 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1218 if (SE->isKnownPositive(Step)) {
1219 *Pred = ICmpInst::ICMP_SLT;
1221 SE->getSignedRangeMax(Step));
1222 }
1223 if (SE->isKnownNegative(Step)) {
1224 *Pred = ICmpInst::ICMP_SGT;
1226 SE->getSignedRangeMin(Step));
1227 }
1228 return nullptr;
1229}
1230
1231// Get the limit of a recurrence such that incrementing by Step cannot cause
1232// unsigned overflow as long as the value of the recurrence within the loop does
1233// not exceed this limit before incrementing.
1235 ICmpInst::Predicate *Pred,
1236 ScalarEvolution *SE) {
1237 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1238 *Pred = ICmpInst::ICMP_ULT;
1239
1241 SE->getUnsignedRangeMax(Step));
1242}
1243
1244namespace {
1245
1246struct ExtendOpTraitsBase {
1247 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(SCEVUse, Type *,
1248 unsigned);
1249};
1250
1251// Used to make code generic over signed and unsigned overflow.
1252template <typename ExtendOp> struct ExtendOpTraits {
1253 // Members present:
1254 //
1255 // static const SCEV::NoWrapFlags WrapType;
1256 //
1257 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1258 //
1259 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1260 // ICmpInst::Predicate *Pred,
1261 // ScalarEvolution *SE);
1262};
1263
1264template <>
1265struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1266 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1267
1268 static const GetExtendExprTy GetExtendExpr;
1269
1270 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1271 ICmpInst::Predicate *Pred,
1272 ScalarEvolution *SE) {
1273 return getSignedOverflowLimitForStep(Step, Pred, SE);
1274 }
1275};
1276
1277const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1279
1280template <>
1281struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1282 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1283
1284 static const GetExtendExprTy GetExtendExpr;
1285
1286 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1287 ICmpInst::Predicate *Pred,
1288 ScalarEvolution *SE) {
1289 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1290 }
1291};
1292
1293const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1295
1296} // end anonymous namespace
1297
1298// The recurrence AR has been shown to have no signed/unsigned wrap or something
1299// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1300// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1301// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1302// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1303// expression "Step + sext/zext(PreIncAR)" is congruent with
1304// "sext/zext(PostIncAR)"
1305template <typename ExtendOpTy>
1307 ScalarEvolution *SE, unsigned Depth) {
1308 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1309 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1310
1311 const Loop *L = AR->getLoop();
1312 const SCEV *Start = AR->getStart();
1313 const SCEV *Step = AR->getStepRecurrence(*SE);
1314
1315 // Check for a simple looking step prior to loop entry.
1316 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1317 if (!SA)
1318 return nullptr;
1319
1320 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1321 // subtraction is expensive. For this purpose, perform a quick and dirty
1322 // difference, by checking for Step in the operand list. Note, that
1323 // SA might have repeated ops, like %a + %a + ..., so only remove one.
1324 SmallVector<SCEVUse, 4> DiffOps(SA->operands());
1325 for (auto It = DiffOps.begin(); It != DiffOps.end(); ++It)
1326 if (*It == Step) {
1327 DiffOps.erase(It);
1328 break;
1329 }
1330
1331 if (DiffOps.size() == SA->getNumOperands())
1332 return nullptr;
1333
1334 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1335 // `Step`:
1336
1337 // 1. NSW/NUW flags on the step increment.
1338 auto PreStartFlags =
1340 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1342 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagNone));
1343
1344 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1345 // "S+X does not sign/unsign-overflow".
1346 //
1347
1348 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1349 if (PreAR && any(PreAR->getNoWrapFlags(WrapType)) &&
1350 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1351 return PreStart;
1352
1353 // 2. Direct overflow check on the step operation's expression.
1354 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1355 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1356 const SCEV *OperandExtendedStart =
1357 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1358 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1359 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1360 if (PreAR && any(AR->getNoWrapFlags(WrapType))) {
1361 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1362 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1363 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1364 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1365 }
1366 return PreStart;
1367 }
1368
1369 // 3. Loop precondition.
1371 const SCEV *OverflowLimit =
1372 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1373
1374 if (OverflowLimit &&
1375 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1376 return PreStart;
1377
1378 return nullptr;
1379}
1380
1381// Get the normalized zero or sign extended expression for this AddRec's Start.
1382template <typename ExtendOpTy>
1383static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1384 ScalarEvolution *SE,
1385 unsigned Depth) {
1386 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1387
1388 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, SE, Depth);
1389 if (!PreStart)
1390 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1391
1392 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1393 Depth),
1394 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1395}
1396
1397// Try to prove away overflow by looking at "nearby" add recurrences. A
1398// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1399// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1400//
1401// Formally:
1402//
1403// {S,+,X} == {S-T,+,X} + T
1404// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1405//
1406// If ({S-T,+,X} + T) does not overflow ... (1)
1407//
1408// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1409//
1410// If {S-T,+,X} does not overflow ... (2)
1411//
1412// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1413// == {Ext(S-T)+Ext(T),+,Ext(X)}
1414//
1415// If (S-T)+T does not overflow ... (3)
1416//
1417// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1418// == {Ext(S),+,Ext(X)} == LHS
1419//
1420// Thus, if (1), (2) and (3) are true for some T, then
1421// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1422//
1423// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1424// does not overflow" restricted to the 0th iteration. Therefore we only need
1425// to check for (1) and (2).
1426//
1427// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1428// is `Delta` (defined below).
1429template <typename ExtendOpTy>
1430bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1431 const SCEV *Step,
1432 const Loop *L) {
1433 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1434
1435 // We restrict `Start` to a constant to prevent SCEV from spending too much
1436 // time here. It is correct (but more expensive) to continue with a
1437 // non-constant `Start` and do a general SCEV subtraction to compute
1438 // `PreStart` below.
1439 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1440 if (!StartC)
1441 return false;
1442
1443 APInt StartAI = StartC->getAPInt();
1444
1445 for (unsigned Delta : {-2, -1, 1, 2}) {
1446 const SCEV *PreStart = getConstant(StartAI - Delta);
1447
1448 FoldingSetNodeID ID;
1449 ID.AddInteger(scAddRecExpr);
1450 ID.AddPointer(PreStart);
1451 ID.AddPointer(Step);
1452 ID.AddPointer(L);
1453 FoldingSetInsertToken Token;
1454 const auto *PreAR =
1455 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.lookup(ID, Token));
1456
1457 // Give up if we don't already have the add recurrence we need because
1458 // actually constructing an add recurrence is relatively expensive.
1459 if (PreAR && any(PreAR->getNoWrapFlags(WrapType))) { // proves (2)
1460 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1462 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1463 DeltaS, &Pred, this);
1464 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1465 return true;
1466 }
1467 }
1468
1469 return false;
1470}
1471
1472// Finds an integer D for an expression (C + x + y + ...) such that the top
1473// level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1474// unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1475// maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1476// the (C + x + y + ...) expression is \p WholeAddExpr.
1478 const SCEVConstant *ConstantTerm,
1479 const SCEVAddExpr *WholeAddExpr) {
1480 const APInt &C = ConstantTerm->getAPInt();
1481 const unsigned BitWidth = C.getBitWidth();
1482 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1483 uint32_t TZ = BitWidth;
1484 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1485 TZ = std::min(TZ, SE.getMinTrailingZeros(WholeAddExpr->getOperand(I)));
1486 if (TZ) {
1487 // Set D to be as many least significant bits of C as possible while still
1488 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1489 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1490 }
1491 return APInt(BitWidth, 0);
1492}
1493
1494// Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1495// level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1496// number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1497// ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1499 const APInt &ConstantStart,
1500 const SCEV *Step) {
1501 const unsigned BitWidth = ConstantStart.getBitWidth();
1502 const uint32_t TZ = SE.getMinTrailingZeros(Step);
1503 if (TZ)
1504 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1505 : ConstantStart;
1506 return APInt(BitWidth, 0);
1507}
1508
1510 const ScalarEvolution::FoldID &ID, const SCEV *S,
1513 &FoldCacheUser) {
1514 auto I = FoldCache.insert({ID, S});
1515 if (!I.second) {
1516 // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1517 // entry.
1518 auto &UserIDs = FoldCacheUser[I.first->second];
1519 assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
1520 for (unsigned I = 0; I != UserIDs.size(); ++I)
1521 if (UserIDs[I] == ID) {
1522 std::swap(UserIDs[I], UserIDs.back());
1523 break;
1524 }
1525 UserIDs.pop_back();
1526 I.first->second = S;
1527 }
1528 FoldCacheUser[S].push_back(ID);
1529}
1530
1532 unsigned Depth) {
1533 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1534 "This is not an extending conversion!");
1535 assert(isSCEVable(Ty) &&
1536 "This is not a conversion to a SCEVable type!");
1537 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1538 Ty = getEffectiveSCEVType(Ty);
1539
1540 FoldID ID(scZeroExtend, Op, Ty);
1541 if (const SCEV *S = FoldCache.lookup(ID))
1542 return S;
1543
1544 const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1546 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1547 return S;
1548}
1549
1551 unsigned Depth) {
1552 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1553 "This is not an extending conversion!");
1554 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1555 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1556
1557 // Fold if the operand is constant.
1558 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1559 return getConstant(SC->getAPInt().zext(getTypeSizeInBits(Ty)));
1560
1561 // zext(zext(x)) --> zext(x)
1563 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1564
1565 // If the operand is an affine AddRec with the no-unsigned-wrap flag, the
1566 // zero-extension distributes over the recurrence.
1567 const SCEV *Start, *Step;
1568 const Loop *L;
1569 if (Depth <= MaxCastDepth &&
1570 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1571 const auto *AR = cast<SCEVAddRecExpr>(Op);
1572 if (AR->hasNoUnsignedWrap()) {
1573 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1574 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1575 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1576 }
1577 }
1578
1579 // Before doing any expensive analysis, check to see if we've already
1580 // computed a SCEV for this Op and Ty.
1583 ID.AddPointer(Op.getOpaqueValue());
1584 ID.AddPointer(Ty);
1586 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1587 return S;
1588 if (Depth > MaxCastDepth) {
1589 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1590 Op, Ty);
1591 UniqueSCEVs.insert(S, Token);
1592 S->computeAndSetCanonical(*this);
1593 registerUser(S, Op);
1594 return S;
1595 }
1596
1597 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1599 // It's possible the bits taken off by the truncate were all zero bits. If
1600 // so, we should be able to simplify this further.
1601 const SCEV *X = ST->getOperand();
1603 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1604 unsigned NewBits = getTypeSizeInBits(Ty);
1605 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1606 CR.zextOrTrunc(NewBits)))
1607 return getTruncateOrZeroExtend(X, Ty, Depth);
1608 }
1609
1610 // If the input value is a chrec scev, and we can prove that the value
1611 // did not overflow the old, smaller, value, we can zero extend all of the
1612 // operands (often constants). This allows analysis of something like
1613 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1614 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1615 const auto *AR = cast<SCEVAddRecExpr>(Op);
1616 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1617
1618 // The no-unsigned-wrap case is handled before the uniquing lookup above.
1619
1620 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1621 // Note that this serves two purposes: It filters out loops that are
1622 // simply not analyzable, and it covers the case where this code is
1623 // being called from within backedge-taken count analysis, such that
1624 // attempting to ask for the backedge-taken count would likely result
1625 // in infinite recursion. In the later case, the analysis code will
1626 // cope with a conservative value, and it will take care to purge
1627 // that value once it has finished.
1628 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1629 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1630 // Manually compute the final value for AR, checking for overflow.
1631
1632 // Check whether the backedge-taken count can be losslessly casted to
1633 // the addrec's type. The count is always unsigned.
1634 const SCEV *CastedMaxBECount =
1635 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1636 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1637 CastedMaxBECount, MaxBECount->getType(), Depth);
1638 if (MaxBECount == RecastedMaxBECount) {
1639 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1640 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1641 const SCEV *ZMul =
1642 getMulExpr(CastedMaxBECount, Step, SCEV::FlagNone, Depth + 1);
1643 const SCEV *ZAdd = getZeroExtendExpr(
1644 getAddExpr(Start, ZMul, SCEV::FlagNone, Depth + 1), WideTy,
1645 Depth + 1);
1646 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1647 const SCEV *WideMaxBECount =
1648 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1649 const SCEV *OperandExtendedAdd =
1650 getAddExpr(WideStart,
1651 getMulExpr(WideMaxBECount,
1652 getZeroExtendExpr(Step, WideTy, Depth + 1),
1653 SCEV::FlagNone, Depth + 1),
1654 SCEV::FlagNone, Depth + 1);
1655 if (ZAdd == OperandExtendedAdd) {
1656 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1657 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1658 // Return the expression with the addrec on the outside.
1659 Start =
1661 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1662 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1663 }
1664 // Similar to above, only this time treat the step value as signed.
1665 // This covers loops that count down.
1666 OperandExtendedAdd =
1667 getAddExpr(WideStart,
1668 getMulExpr(WideMaxBECount,
1669 getSignExtendExpr(Step, WideTy, Depth + 1),
1670 SCEV::FlagNone, Depth + 1),
1671 SCEV::FlagNone, Depth + 1);
1672 if (ZAdd == OperandExtendedAdd) {
1673 // Cache knowledge of AR NW, which is propagated to this AddRec.
1674 // Negative step causes unsigned wrap, but it still can't self-wrap.
1675 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1676 // Return the expression with the addrec on the outside.
1677 Start =
1679 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1680 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1681 }
1682 }
1683 }
1684
1685 // Normally, in the cases we can prove no-overflow via a
1686 // backedge guarding condition, we can also compute a backedge
1687 // taken count for the loop. The exceptions are assumptions and
1688 // guards present in the loop -- SCEV is not great at exploiting
1689 // these to compute max backedge taken counts, but can still use
1690 // these to prove lack of overflow. Use this fact to avoid
1691 // doing extra work that may not pay off.
1692 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1693 !AC.assumptions().empty()) {
1694
1695 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1696 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1697 if (AR->hasNoUnsignedWrap()) {
1698 // Same as nuw case above - duplicated here to avoid a compile time
1699 // issue. It's not clear that the order of checks does matter, but
1700 // it's one of two issue possible causes for a change which was
1701 // reverted. Be conservative for the moment.
1702 Start =
1704 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1705 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1706 }
1707
1708 // For a negative step, we can extend the operands iff doing so only
1709 // traverses values in the range zext([0,UINT_MAX]).
1710 if (isKnownNegative(Step)) {
1711 const SCEV *N =
1715 // Cache knowledge of AR NW, which is propagated to this
1716 // AddRec. Negative step causes unsigned wrap, but it
1717 // still can't self-wrap.
1718 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1719 // Return the expression with the addrec on the outside.
1720 Start =
1722 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1723 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1724 }
1725 }
1726 }
1727
1728 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1729 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1730 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1731 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1732 const APInt &C = SC->getAPInt();
1733 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1734 if (D != 0) {
1735 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1736 const SCEV *SResidual =
1737 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1738 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1739 return getAddExpr(SZExtD, SZExtR, SCEV::FlagNSW | SCEV::FlagNUW,
1740 Depth + 1);
1741 }
1742 }
1743
1744 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1745 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1746 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1747 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1748 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1749 }
1750 }
1751
1752 // zext(A % B) --> zext(A) % zext(B)
1753 {
1754 const SCEV *LHS;
1755 const SCEV *RHS;
1756 if (match(Op, m_scev_URem(m_SCEV(LHS), m_SCEV(RHS), *this)))
1757 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1758 getZeroExtendExpr(RHS, Ty, Depth + 1));
1759 }
1760
1761 // zext(A / B) --> zext(A) / zext(B).
1762 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1763 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1764 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1765
1766 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1767 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1768 if (SA->hasNoUnsignedWrap()) {
1769 // If the addition does not unsign overflow then we can, by definition,
1770 // commute the zero extension with the addition operation.
1772 for (SCEVUse Op : SA->operands())
1773 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1774 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1775 }
1776
1777 const APInt *C, *C2;
1778 // zext (C + A)<nsw> -> (sext(C) + sext(A))<nsw> if zext (C + A)<nsw> >=s 0.
1779 // Currently the non-negative check is done manually, as isKnownNonNegative
1780 // is too expensive.
1781 if (SA->hasNoSignedWrap() &&
1783 m_scev_SMax(m_scev_APInt(C2), m_SCEV()))) &&
1784 C->isNegative() && !C->isMinSignedValue() && C2->sge(C->abs())) {
1785 assert(isKnownNonNegative(SA) && "incorrectly determined non-negative");
1786 return getAddExpr(getSignExtendExpr(SA->getOperand(0), Ty, Depth + 1),
1787 getSignExtendExpr(SA->getOperand(1), Ty, Depth + 1),
1788 SCEV::FlagNSW, Depth + 1);
1789 }
1790
1791 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1792 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1793 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1794 //
1795 // Often address arithmetics contain expressions like
1796 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1797 // This transformation is useful while proving that such expressions are
1798 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1799 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1800 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1801 if (D != 0) {
1802 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1803 const SCEV *SResidual =
1805 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1806 return getAddExpr(SZExtD, SZExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1807 Depth + 1);
1808 }
1809 }
1810 }
1811
1812 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1813 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1814 if (SM->hasNoUnsignedWrap()) {
1815 // If the multiply does not unsign overflow then we can, by definition,
1816 // commute the zero extension with the multiply operation.
1818 for (SCEVUse Op : SM->operands())
1819 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1820 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1821 }
1822
1823 // zext(2^K * (trunc X to iN)) to iM ->
1824 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1825 //
1826 // Proof:
1827 //
1828 // zext(2^K * (trunc X to iN)) to iM
1829 // = zext((trunc X to iN) << K) to iM
1830 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1831 // (because shl removes the top K bits)
1832 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1833 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1834 //
1835 const APInt *C;
1836 const SCEV *TruncRHS;
1837 if (match(SM,
1838 m_scev_Mul(m_scev_APInt(C), m_scev_Trunc(m_SCEV(TruncRHS)))) &&
1839 C->isPowerOf2()) {
1840 int NewTruncBits =
1841 getTypeSizeInBits(SM->getOperand(1)->getType()) - C->logBase2();
1842 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1843 return getMulExpr(
1844 getZeroExtendExpr(SM->getOperand(0), Ty),
1845 getZeroExtendExpr(getTruncateExpr(TruncRHS, NewTruncTy), Ty),
1846 SCEV::FlagNUW, Depth + 1);
1847 }
1848 }
1849
1850 // zext(umin(x, y)) -> umin(zext(x), zext(y))
1851 // zext(umax(x, y)) -> umax(zext(x), zext(y))
1855 for (SCEVUse Operand : MinMax->operands())
1856 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1858 return getUMinExpr(Operands);
1859 return getUMaxExpr(Operands);
1860 }
1861
1862 // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
1864 assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!");
1866 for (SCEVUse Operand : MinMax->operands())
1867 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1868 return getUMinExpr(Operands, /*Sequential*/ true);
1869 }
1870
1871 // The cast wasn't folded; create an explicit cast node.
1872 // Recompute the insert position, as it may have been invalidated.
1873 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1874 return S;
1875 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1876 Op, Ty);
1877 UniqueSCEVs.insert(S, Token);
1878 S->computeAndSetCanonical(*this);
1879 registerUser(S, Op);
1880 return S;
1881}
1882
1884 unsigned Depth) {
1885 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1886 "This is not an extending conversion!");
1887 assert(isSCEVable(Ty) &&
1888 "This is not a conversion to a SCEVable type!");
1889 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1890 Ty = getEffectiveSCEVType(Ty);
1891
1892 FoldID ID(scSignExtend, Op, Ty);
1893 if (const SCEV *S = FoldCache.lookup(ID))
1894 return S;
1895
1896 const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
1898 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1899 return S;
1900}
1901
1903 unsigned Depth) {
1904 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1905 "This is not an extending conversion!");
1906 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1907 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1908 Ty = getEffectiveSCEVType(Ty);
1909
1910 // Fold if the operand is constant.
1911 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1912 return getConstant(SC->getAPInt().sext(getTypeSizeInBits(Ty)));
1913
1914 // sext(sext(x)) --> sext(x)
1916 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1917
1918 // sext(zext(x)) --> zext(x)
1920 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1921
1922 // If the operand is an affine AddRec with the no-signed-wrap flag, the
1923 // sign-extension distributes over the recurrence.
1924 const SCEV *Start, *Step;
1925 const Loop *L;
1926 if (Depth <= MaxCastDepth &&
1927 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1928 const auto *AR = cast<SCEVAddRecExpr>(Op);
1929 if (AR->hasNoSignedWrap()) {
1930 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
1931 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1932 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1933 }
1934 }
1935
1936 // Before doing any expensive analysis, check to see if we've already
1937 // computed a SCEV for this Op and Ty.
1940 ID.AddPointer(Op.getOpaqueValue());
1941 ID.AddPointer(Ty);
1943 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1944 return S;
1945 // Limit recursion depth.
1946 if (Depth > MaxCastDepth) {
1947 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1948 Op, Ty);
1949 UniqueSCEVs.insert(S, Token);
1950 S->computeAndSetCanonical(*this);
1951 registerUser(S, Op);
1952 return S;
1953 }
1954
1955 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1957 // It's possible the bits taken off by the truncate were all sign bits. If
1958 // so, we should be able to simplify this further.
1959 const SCEV *X = ST->getOperand();
1961 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1962 unsigned NewBits = getTypeSizeInBits(Ty);
1963 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1964 CR.sextOrTrunc(NewBits)))
1965 return getTruncateOrSignExtend(X, Ty, Depth);
1966 }
1967
1968 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1969 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1970 if (SA->hasNoSignedWrap()) {
1971 // If the addition does not sign overflow then we can, by definition,
1972 // commute the sign extension with the addition operation.
1974 for (SCEVUse Op : SA->operands())
1975 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1976 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1977 }
1978
1979 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1980 // if D + (C - D + x + y + ...) could be proven to not signed wrap
1981 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1982 //
1983 // For instance, this will bring two seemingly different expressions:
1984 // 1 + sext(5 + 20 * %x + 24 * %y) and
1985 // sext(6 + 20 * %x + 24 * %y)
1986 // to the same form:
1987 // 2 + sext(4 + 20 * %x + 24 * %y)
1988 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1989 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1990 if (D != 0) {
1991 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1992 const SCEV *SResidual =
1994 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1995 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1996 Depth + 1);
1997 }
1998 }
1999 }
2000 // If the input value is a chrec scev, and we can prove that the value
2001 // did not overflow the old, smaller, value, we can sign extend all of the
2002 // operands (often constants). This allows analysis of something like
2003 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
2004 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
2005 const auto *AR = cast<SCEVAddRecExpr>(Op);
2006 unsigned BitWidth = getTypeSizeInBits(AR->getType());
2007
2008 // The no-signed-wrap case is handled before the uniquing lookup above.
2009
2010 // Check whether the backedge-taken count is SCEVCouldNotCompute.
2011 // Note that this serves two purposes: It filters out loops that are
2012 // simply not analyzable, and it covers the case where this code is
2013 // being called from within backedge-taken count analysis, such that
2014 // attempting to ask for the backedge-taken count would likely result
2015 // in infinite recursion. In the later case, the analysis code will
2016 // cope with a conservative value, and it will take care to purge
2017 // that value once it has finished.
2018 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2019 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2020 // Manually compute the final value for AR, checking for
2021 // overflow.
2022
2023 // Check whether the backedge-taken count can be losslessly casted to
2024 // the addrec's type. The count is always unsigned.
2025 const SCEV *CastedMaxBECount =
2026 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2027 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2028 CastedMaxBECount, MaxBECount->getType(), Depth);
2029 if (MaxBECount == RecastedMaxBECount) {
2030 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2031 // Check whether Start+Step*MaxBECount has no signed overflow.
2032 const SCEV *SMul =
2033 getMulExpr(CastedMaxBECount, Step, SCEV::FlagNone, Depth + 1);
2034 const SCEV *SAdd = getSignExtendExpr(
2035 getAddExpr(Start, SMul, SCEV::FlagNone, Depth + 1), WideTy,
2036 Depth + 1);
2037 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2038 const SCEV *WideMaxBECount =
2039 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2040 const SCEV *OperandExtendedAdd =
2041 getAddExpr(WideStart,
2042 getMulExpr(WideMaxBECount,
2043 getSignExtendExpr(Step, WideTy, Depth + 1),
2044 SCEV::FlagNone, Depth + 1),
2045 SCEV::FlagNone, Depth + 1);
2046 if (SAdd == OperandExtendedAdd) {
2047 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2048 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2049 // Return the expression with the addrec on the outside.
2050 Start =
2052 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2053 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2054 }
2055 // Similar to above, only this time treat the step value as unsigned.
2056 // This covers loops that count up with an unsigned step.
2057 OperandExtendedAdd =
2058 getAddExpr(WideStart,
2059 getMulExpr(WideMaxBECount,
2060 getZeroExtendExpr(Step, WideTy, Depth + 1),
2061 SCEV::FlagNone, Depth + 1),
2062 SCEV::FlagNone, Depth + 1);
2063 if (SAdd == OperandExtendedAdd) {
2064 // If AR wraps around then
2065 //
2066 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2067 // => SAdd != OperandExtendedAdd
2068 //
2069 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2070 // (SAdd == OperandExtendedAdd => AR is NW)
2071
2072 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2073
2074 // Return the expression with the addrec on the outside.
2075 Start =
2077 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
2078 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2079 }
2080 }
2081 }
2082
2083 auto NewFlags = proveNoSignedWrapViaInduction(AR);
2084 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2085 if (AR->hasNoSignedWrap()) {
2086 // Same as nsw case above - duplicated here to avoid a compile time
2087 // issue. It's not clear that the order of checks does matter, but
2088 // it's one of two issue possible causes for a change which was
2089 // reverted. Be conservative for the moment.
2090 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2091 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2092 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2093 }
2094
2095 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2096 // if D + (C - D + Step * n) could be proven to not signed wrap
2097 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2098 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2099 const APInt &C = SC->getAPInt();
2100 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2101 if (D != 0) {
2102 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2103 const SCEV *SResidual =
2104 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2105 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2106 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
2107 Depth + 1);
2108 }
2109 }
2110
2111 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2112 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2113 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2114 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2115 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2116 }
2117 }
2118
2119 // If the input value is provably positive and we could not simplify
2120 // away the sext build a zext instead.
2122 return getZeroExtendExpr(Op, Ty, Depth + 1);
2123
2124 // sext(smin(x, y)) -> smin(sext(x), sext(y))
2125 // sext(smax(x, y)) -> smax(sext(x), sext(y))
2129 for (SCEVUse Operand : MinMax->operands())
2130 Operands.push_back(getSignExtendExpr(Operand, Ty));
2132 return getSMinExpr(Operands);
2133 return getSMaxExpr(Operands);
2134 }
2135
2136 // The cast wasn't folded; create an explicit cast node.
2137 // Recompute the insert position, as it may have been invalidated.
2138 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
2139 return S;
2140 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2141 Op, Ty);
2142 UniqueSCEVs.insert(S, Token);
2143 S->computeAndSetCanonical(*this);
2144 registerUser(S, Op);
2145 return S;
2146}
2147
2149 switch (Kind) {
2150 case scTruncate:
2151 return getTruncateExpr(Op, Ty);
2152 case scZeroExtend:
2153 return getZeroExtendExpr(Op, Ty);
2154 case scSignExtend:
2155 return getSignExtendExpr(Op, Ty);
2156 case scPtrToAddr: {
2157 const SCEV *Expr = getPtrToAddrExpr(Op);
2158 assert(Expr->getType() == Ty && "requested type must match");
2159 return Expr;
2160 }
2161 default:
2162 llvm_unreachable("Not a SCEV cast expression!");
2163 }
2164}
2165
2166/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2167/// unspecified bits out to the given type.
2169 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2170 "This is not an extending conversion!");
2171 assert(isSCEVable(Ty) &&
2172 "This is not a conversion to a SCEVable type!");
2173 Ty = getEffectiveSCEVType(Ty);
2174
2175 // Sign-extend negative constants.
2176 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2177 if (SC->getAPInt().isNegative())
2178 return getSignExtendExpr(Op, Ty);
2179
2180 // Peel off a truncate cast.
2182 const SCEV *NewOp = T->getOperand();
2183 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2184 return getAnyExtendExpr(NewOp, Ty);
2185 return getTruncateOrNoop(NewOp, Ty);
2186 }
2187
2188 // Next try a zext cast. If the cast is folded, use it.
2189 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2190 if (!isa<SCEVZeroExtendExpr>(ZExt))
2191 return ZExt;
2192
2193 // Next try a sext cast. If the cast is folded, use it.
2194 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2195 if (!isa<SCEVSignExtendExpr>(SExt))
2196 return SExt;
2197
2198 // Force the cast to be folded into the operands of an addrec.
2199 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2201 for (const SCEV *Op : AR->operands())
2202 Ops.push_back(getAnyExtendExpr(Op, Ty));
2203 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2204 }
2205
2206 // If the expression is obviously signed, use the sext cast value.
2207 if (isa<SCEVSMaxExpr>(Op))
2208 return SExt;
2209
2210 // Absent any other information, use the zext cast value.
2211 return ZExt;
2212}
2213
2214/// Process the given Ops list, which is a list of operands to be added under
2215/// the given scale, update the given map. This is a helper function for
2216/// getAddRecExpr. As an example of what it does, given a sequence of operands
2217/// that would form an add expression like this:
2218///
2219/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2220///
2221/// where A and B are constants, update the map with these values:
2222///
2223/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2224///
2225/// and add 13 + A*B*29 to AccumulatedConstant.
2226/// This will allow getAddRecExpr to produce this:
2227///
2228/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2229///
2230/// This form often exposes folding opportunities that are hidden in
2231/// the original operand list.
2232///
2233/// Return true iff it appears that any interesting folding opportunities
2234/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2235/// the common case where no interesting opportunities are present, and
2236/// is also used as a check to avoid infinite recursion.
2239 APInt &AccumulatedConstant,
2241 const APInt &Scale,
2242 ScalarEvolution &SE) {
2243 bool Interesting = false;
2244
2245 // Iterate over the add operands. They are sorted, with constants first.
2246 unsigned i = 0;
2247 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2248 ++i;
2249 // Pull a buried constant out to the outside.
2250 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2251 Interesting = true;
2252 AccumulatedConstant += Scale * C->getAPInt();
2253 }
2254
2255 // Next comes everything else. We're especially interested in multiplies
2256 // here, but they're in the middle, so just visit the rest with one loop.
2257 for (; i != Ops.size(); ++i) {
2259 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2260 APInt NewScale =
2261 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2262 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2263 // A multiplication of a constant with another add; recurse.
2264 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2265 Interesting |= CollectAddOperandsWithScales(
2266 M, NewOps, AccumulatedConstant, Add->operands(), NewScale, SE);
2267 } else {
2268 // A multiplication of a constant with some other value. Update
2269 // the map.
2270 SmallVector<SCEVUse, 4> MulOps(drop_begin(Mul->operands()));
2271 const SCEV *Key = SE.getMulExpr(MulOps);
2272 auto Pair = M.insert({Key, NewScale});
2273 if (Pair.second) {
2274 NewOps.push_back(Pair.first->first);
2275 } else {
2276 Pair.first->second += NewScale;
2277 // The map already had an entry for this value, which may indicate
2278 // a folding opportunity.
2279 Interesting = true;
2280 }
2281 }
2282 } else {
2283 // An ordinary operand. Update the map.
2284 auto Pair = M.insert({Ops[i], Scale});
2285 if (Pair.second) {
2286 NewOps.push_back(Pair.first->first);
2287 } else {
2288 Pair.first->second += Scale;
2289 // The map already had an entry for this value, which may indicate
2290 // a folding opportunity.
2291 Interesting = true;
2292 }
2293 }
2294 }
2295
2296 return Interesting;
2297}
2298
2300 const SCEV *LHS, const SCEV *RHS,
2301 const Instruction *CtxI) {
2302 auto Operation = [this, BinOp](SCEVUse L, SCEVUse R) -> const SCEV * {
2303 switch (BinOp) {
2304 default:
2305 llvm_unreachable("Unsupported binary op");
2306 case Instruction::Add:
2307 return getAddExpr(L, R);
2308 case Instruction::Sub:
2309 return getMinusSCEV(L, R);
2310 case Instruction::Mul:
2311 return getMulExpr(L, R);
2312 }
2313 };
2314
2315 const SCEV *(ScalarEvolution::*Extension)(SCEVUse, Type *, unsigned) =
2318
2319 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2320 auto *NarrowTy = cast<IntegerType>(LHS->getType());
2321 auto *WideTy =
2322 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2323
2324 const SCEV *A = (this->*Extension)(Operation(LHS, RHS), WideTy, 0);
2325 const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2326 const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2327 const SCEV *B = Operation(LHSB, RHSB);
2328 if (A == B)
2329 return true;
2330 // Can we use context to prove the fact we need?
2331 if (!CtxI)
2332 return false;
2333 // TODO: Support mul.
2334 if (BinOp == Instruction::Mul)
2335 return false;
2336 auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2337 // TODO: Lift this limitation.
2338 if (!RHSC)
2339 return false;
2340 APInt C = RHSC->getAPInt();
2341 unsigned NumBits = C.getBitWidth();
2342 bool IsSub = (BinOp == Instruction::Sub);
2343 bool IsNegativeConst = (Signed && C.isNegative());
2344 // Compute the direction and magnitude by which we need to check overflow.
2345 bool OverflowDown = IsSub ^ IsNegativeConst;
2346 APInt Magnitude = C;
2347 if (IsNegativeConst) {
2348 if (C == APInt::getSignedMinValue(NumBits))
2349 // TODO: SINT_MIN on inversion gives the same negative value, we don't
2350 // want to deal with that.
2351 return false;
2352 Magnitude = -C;
2353 }
2354
2356 if (OverflowDown) {
2357 // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2358 APInt Min = Signed ? APInt::getSignedMinValue(NumBits)
2359 : APInt::getMinValue(NumBits);
2360 APInt Limit = Min + Magnitude;
2361 return isKnownPredicateAt(Pred, getConstant(Limit), LHS, CtxI);
2362 } else {
2363 // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2364 APInt Max = Signed ? APInt::getSignedMaxValue(NumBits)
2365 : APInt::getMaxValue(NumBits);
2366 APInt Limit = Max - Magnitude;
2367 return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2368 }
2369}
2370
2371std::optional<SCEV::NoWrapFlags>
2373 const OverflowingBinaryOperator *OBO) {
2374 // It cannot be done any better.
2375 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2376 return std::nullopt;
2377
2378 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagNone;
2379
2380 if (OBO->hasNoUnsignedWrap())
2382 if (OBO->hasNoSignedWrap())
2384
2385 bool Deduced = false;
2386
2388 const SCEV *LHS = getSCEV(OBO->getOperand(0));
2389 const SCEV *RHS = getSCEV(OBO->getOperand(1));
2390
2391 bool CanUseNSW = true;
2392 const APInt *ShiftAmt;
2393 // Treat `shl %a, C` as `mul %a, 1 << C`.
2394 if (match(OBO, m_Shl(m_Value(), m_APInt(ShiftAmt)))) {
2395 unsigned BitWidth = ShiftAmt->getBitWidth();
2396 if (ShiftAmt->uge(BitWidth))
2397 return std::nullopt;
2398 // NSW only transfers if the shift amount is < BitWidth - 1, as INT_MIN * -1
2399 // overflows.
2400 CanUseNSW = ShiftAmt->ult(BitWidth - 1);
2401 Opcode = Instruction::Mul;
2403 } else if (Opcode != Instruction::Add && Opcode != Instruction::Sub &&
2404 Opcode != Instruction::Mul) {
2405 return std::nullopt;
2406 }
2407
2408 const Instruction *CtxI =
2410 if (!OBO->hasNoUnsignedWrap() &&
2411 willNotOverflow(Opcode, /* Signed */ false, LHS, RHS, CtxI)) {
2413 Deduced = true;
2414 }
2415
2416 if (CanUseNSW && !OBO->hasNoSignedWrap() &&
2417 willNotOverflow(Opcode, /* Signed */ true, LHS, RHS, CtxI)) {
2419 Deduced = true;
2420 }
2421
2422 if (Deduced)
2423 return Flags;
2424 return std::nullopt;
2425}
2426
2427// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2428// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2429// can't-overflow flags for the operation if possible.
2433 SCEV::NoWrapFlags Flags) {
2434 using namespace std::placeholders;
2435
2436 using OBO = OverflowingBinaryOperator;
2437
2438 bool CanAnalyze =
2440 (void)CanAnalyze;
2441 assert(CanAnalyze && "don't call from other places!");
2442
2443 SCEV::NoWrapFlags SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2444 SCEV::NoWrapFlags SignOrUnsignWrap =
2445 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2446
2447 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2448 auto IsKnownNonNegative = [&](SCEVUse U) {
2449 return SE->isKnownNonNegative(U);
2450 };
2451
2452 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2453 Flags = ScalarEvolution::setFlags(Flags, SignOrUnsignMask);
2454
2455 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2456
2457 if (SignOrUnsignWrap != SignOrUnsignMask &&
2458 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2459 isa<SCEVConstant>(Ops[0])) {
2460
2461 auto Opcode = [&] {
2462 switch (Type) {
2463 case scAddExpr:
2464 return Instruction::Add;
2465 case scMulExpr:
2466 return Instruction::Mul;
2467 default:
2468 llvm_unreachable("Unexpected SCEV op.");
2469 }
2470 }();
2471
2472 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2473
2474 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2475 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2477 Opcode, C, OBO::NoSignedWrap);
2478 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2480 }
2481
2482 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2483 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2485 Opcode, C, OBO::NoUnsignedWrap);
2486 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2488 }
2489 }
2490
2491 // <0,+,nonnegative><nw> is also nuw
2492 // TODO: Add corresponding nsw case
2494 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2495 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2497
2498 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2500 Ops.size() == 2) {
2501 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2502 if (UDiv->getOperand(1) == Ops[1])
2504 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2505 if (UDiv->getOperand(1) == Ops[0])
2507 }
2508
2509 return Flags;
2510}
2511
2513 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2514}
2515
2516/// Get a canonical add expression, or something simpler if possible.
2518 SCEVFlags Flags, unsigned Depth) {
2519 SCEV::NoWrapFlags OrigFlags = Flags.ExprFlags;
2520 SCEV::NoWrapFlags UseFlags = Flags.UseFlags;
2521 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2522 "only nuw or nsw allowed");
2523 assert(!(UseFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2524 "only nuw or nsw allowed");
2525 assert(!Ops.empty() && "Cannot get empty add!");
2526 if (Ops.size() == 1) return Ops[0];
2527#ifndef NDEBUG
2528 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2529 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2530 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2531 "SCEVAddExpr operand types don't match!");
2532 unsigned NumPtrs = count_if(
2533 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2534 assert(NumPtrs <= 1 && "add has at most one pointer operand");
2535#endif
2536
2537 const SCEV *Folded = constantFoldAndGroupOps(
2538 *this, LI, DT, Ops,
2539 [](const APInt &C1, const APInt &C2) { return C1 + C2; },
2540 [](const APInt &C) { return C.isZero(); }, // identity
2541 [](const APInt &C) { return false; }); // absorber
2542 if (Folded)
2543 return Folded;
2544
2545#ifndef NDEBUG
2546 // Keep track of operands after constant folding, for verification when adding
2547 // use-specific flags.
2548 const SmallVector<SCEVUse, 8> OrigOps(Ops.begin(), Ops.end());
2549#endif
2550
2551 unsigned Idx = isa<SCEVConstant>(Ops[0]) ? 1 : 0;
2552
2553 // Delay expensive flag strengthening until necessary.
2554 auto ComputeFlags = [this, OrigFlags](ArrayRef<SCEVUse> Ops) {
2555 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2556 };
2557
2558 // Limit recursion calls depth.
2560 return {getOrCreateAddExpr(Ops, ComputeFlags(Ops)), UseFlags};
2561
2562 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2563 // Don't strengthen flags if we have no new information.
2564 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2565 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2566 Add->setNoWrapFlags(ComputeFlags(Ops));
2567 return {S, UseFlags};
2568 }
2569
2570 // Okay, check to see if the same value occurs in the operand list more than
2571 // once. If so, merge them together into an multiply expression. Since we
2572 // sorted the list, these values are required to be adjacent.
2573 Type *Ty = Ops[0]->getType();
2574 bool FoundMatch = false;
2575 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2576 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2577 // Scan ahead to count how many equal operands there are.
2578 unsigned Count = 2;
2579 while (i+Count != e && Ops[i+Count] == Ops[i])
2580 ++Count;
2581 // Merge the values into a multiply.
2582 SCEVUse Scale = getConstant(Ty, Count);
2583 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagNone, Depth + 1);
2584 if (Ops.size() == Count)
2585 return Mul;
2586 Ops[i] = Mul;
2587 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2588 --i; e -= Count - 1;
2589 FoundMatch = true;
2590 }
2591 if (FoundMatch)
2592 return getAddExpr(Ops, OrigFlags, Depth + 1);
2593
2594 // Check for truncates. If all the operands are truncated from the same
2595 // type, see if factoring out the truncate would permit the result to be
2596 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2597 // if the contents of the resulting outer trunc fold to something simple.
2598 auto FindTruncSrcType = [&]() -> Type * {
2599 // We're ultimately looking to fold an addrec of truncs and muls of only
2600 // constants and truncs, so if we find any other types of SCEV
2601 // as operands of the addrec then we bail and return nullptr here.
2602 // Otherwise, we return the type of the operand of a trunc that we find.
2603 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2604 return T->getOperand()->getType();
2605 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2606 SCEVUse LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2607 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2608 return T->getOperand()->getType();
2609 }
2610 return nullptr;
2611 };
2612 if (auto *SrcType = FindTruncSrcType()) {
2613 SmallVector<SCEVUse, 8> LargeOps;
2614 bool Ok = true;
2615 // Check all the operands to see if they can be represented in the
2616 // source type of the truncate.
2617 for (const SCEV *Op : Ops) {
2619 if (T->getOperand()->getType() != SrcType) {
2620 Ok = false;
2621 break;
2622 }
2623 LargeOps.push_back(T->getOperand());
2624 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Op)) {
2625 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2626 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Op)) {
2627 SmallVector<SCEVUse, 8> LargeMulOps;
2628 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2629 if (const SCEVTruncateExpr *T =
2630 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2631 if (T->getOperand()->getType() != SrcType) {
2632 Ok = false;
2633 break;
2634 }
2635 LargeMulOps.push_back(T->getOperand());
2636 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2637 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2638 } else {
2639 Ok = false;
2640 break;
2641 }
2642 }
2643 if (Ok)
2644 LargeOps.push_back(
2645 getMulExpr(LargeMulOps, SCEV::FlagNone, Depth + 1));
2646 } else {
2647 Ok = false;
2648 break;
2649 }
2650 }
2651 if (Ok) {
2652 // Evaluate the expression in the larger type.
2653 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagNone, Depth + 1);
2654 // If it folds to something simple, use it. Otherwise, don't.
2655 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2656 return getTruncateExpr(Fold, Ty);
2657 }
2658 }
2659
2660 if (Ops.size() == 2) {
2661 // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2662 // C2 can be folded in a way that allows retaining wrapping flags of (X +
2663 // C1).
2664 const SCEV *A = Ops[0];
2665 const SCEV *B = Ops[1];
2666 auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2667 auto *C = dyn_cast<SCEVConstant>(A);
2668 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2669 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2670 auto C2 = C->getAPInt();
2671 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagNone;
2672
2673 APInt ConstAdd = C1 + C2;
2674 auto AddFlags = AddExpr->getNoWrapFlags();
2675 // Adding a smaller constant is NUW if the original AddExpr was NUW.
2677 ConstAdd.ule(C1)) {
2678 PreservedFlags =
2680 }
2681
2682 // Adding a constant with the same sign and small magnitude is NSW, if the
2683 // original AddExpr was NSW.
2685 C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2686 ConstAdd.abs().ule(C1.abs())) {
2687 PreservedFlags =
2689 }
2690
2691 if (PreservedFlags != SCEV::FlagNone) {
2692 SmallVector<SCEVUse, 4> NewOps(AddExpr->operands());
2693 NewOps[0] = getConstant(ConstAdd);
2694 return getAddExpr(NewOps, PreservedFlags);
2695 }
2696 }
2697
2698 // Try to push the constant operand into a ZExt: A + zext (-A + B) -> zext
2699 // (B), if trunc (A) + -A + B does not unsigned-wrap.
2700 const SCEVAddExpr *InnerAdd;
2701 if (match(B, m_scev_ZExt(m_scev_Add(InnerAdd)))) {
2702 const SCEV *NarrowA = getTruncateExpr(A, InnerAdd->getType());
2703 if (NarrowA == getNegativeSCEV(InnerAdd->getOperand(0)) &&
2704 getZeroExtendExpr(NarrowA, B->getType()) == A &&
2705 hasFlags(StrengthenNoWrapFlags(this, scAddExpr, {NarrowA, InnerAdd},
2707 SCEV::FlagNUW)) {
2708 return getZeroExtendExpr(getAddExpr(NarrowA, InnerAdd), B->getType());
2709 }
2710 }
2711 }
2712
2713 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2714 const SCEV *Y;
2715 if (Ops.size() == 2 &&
2716 match(Ops[0],
2718 m_scev_URem(m_scev_Specific(Ops[1]), m_SCEV(Y), *this))))
2719 return getMulExpr(Y, getUDivExpr(Ops[1], Y));
2720
2721 // Skip past any other cast SCEVs.
2722 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2723 ++Idx;
2724
2725 // If there are add operands they would be next.
2726 if (Idx < Ops.size()) {
2727 bool DeletedAdd = false;
2728 // If the original flags and all inlined SCEVAddExprs are NUW, use the
2729 // common NUW flag for expression after inlining. Other flags cannot be
2730 // preserved, because they may depend on the original order of operations.
2731 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2732 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2733 if (Ops.size() > AddOpsInlineThreshold ||
2734 Add->getNumOperands() > AddOpsInlineThreshold)
2735 break;
2736 // If we have an add, expand the add operands onto the end of the operands
2737 // list.
2738 Ops.erase(Ops.begin()+Idx);
2739 append_range(Ops, Add->operands());
2740 DeletedAdd = true;
2741 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2742 }
2743
2744 // If we deleted at least one add, we added operands to the end of the list,
2745 // and they are not necessarily sorted. Recurse to resort and resimplify
2746 // any operands we just acquired.
2747 if (DeletedAdd)
2748 return getAddExpr(Ops, CommonFlags, Depth + 1);
2749 }
2750
2751 // Skip over the add expression until we get to a multiply.
2752 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2753 ++Idx;
2754
2755 // Check to see if there are any folding opportunities present with
2756 // operands multiplied by constant values.
2757 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2758 uint64_t BitWidth = getTypeSizeInBits(Ty);
2761 APInt AccumulatedConstant(BitWidth, 0);
2762 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2763 Ops, APInt(BitWidth, 1), *this)) {
2764 struct APIntCompare {
2765 bool operator()(const APInt &LHS, const APInt &RHS) const {
2766 return LHS.ult(RHS);
2767 }
2768 };
2769
2770 // Some interesting folding opportunity is present, so its worthwhile to
2771 // re-generate the operands list. Group the operands by constant scale,
2772 // to avoid multiplying by the same constant scale multiple times.
2773 std::map<APInt, SmallVector<SCEVUse, 4>, APIntCompare> MulOpLists;
2774 for (SCEVUse NewOp : NewOps)
2775 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2776 // Re-generate the operands list.
2777 Ops.clear();
2778 if (AccumulatedConstant != 0)
2779 Ops.push_back(getConstant(AccumulatedConstant));
2780 for (auto &MulOp : MulOpLists) {
2781 if (MulOp.first == 1) {
2782 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagNone, Depth + 1));
2783 } else if (MulOp.first != 0) {
2784 Ops.push_back(
2785 getMulExpr(getConstant(MulOp.first),
2786 getAddExpr(MulOp.second, SCEV::FlagNone, Depth + 1),
2787 SCEV::FlagNone, Depth + 1));
2788 }
2789 }
2790 if (Ops.empty())
2791 return getZero(Ty);
2792 if (Ops.size() == 1)
2793 return Ops[0];
2794 return getAddExpr(Ops, SCEV::FlagNone, Depth + 1);
2795 }
2796 }
2797
2798 // Given a SCEVMulExpr and an operand index, return the product of all
2799 // operands except the one at OpIdx.
2800 auto StripFactor = [&](const SCEVMulExpr *M, unsigned OpIdx) -> SCEVUse {
2801 if (M->getNumOperands() == 2)
2802 return M->getOperand(OpIdx == 0);
2803 SmallVector<SCEVUse, 4> Remaining(M->operands().take_front(OpIdx));
2804 append_range(Remaining, M->operands().drop_front(OpIdx + 1));
2805 return getMulExpr(Remaining, SCEV::FlagNone, Depth + 1);
2806 };
2807
2808 // If we are adding something to a multiply expression, make sure the
2809 // something is not already an operand of the multiply. If so, merge it into
2810 // the multiply.
2811 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2812 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2813 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2814 // Scan all terms to find every occurrence of common factor MulOpSCEV
2815 // and fold them in one shot:
2816 // A1*X + A2*X + ... + An*X --> X * (A1 + A2 + ... + An)
2817 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2818 if (isa<SCEVConstant>(MulOpSCEV))
2819 continue;
2820
2821 // Cofactors: 1 for bare addends matching MulOpSCEV, or the
2822 // remaining product for multiply terms containing MulOpSCEV.
2823 SmallVector<SCEVUse, 4> Cofactors;
2824 SmallVector<unsigned, 4> DeadIndices;
2825 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) {
2826 if (MulOpSCEV == Ops[AddOp]) {
2827 // W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2828 Cofactors.push_back(getOne(Ty));
2829 DeadIndices.push_back(AddOp);
2830 continue;
2831 }
2832
2833 if (AddOp <= Idx || !isa<SCEVMulExpr>(Ops[AddOp]))
2834 continue;
2835
2836 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[AddOp]);
2837 for (unsigned OMulOp = 0, OE = OtherMul->getNumOperands(); OMulOp != OE;
2838 ++OMulOp) {
2839 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2840 // (A*B*C) + (A*D*E) --> A * (B*C + D*E)
2841 Cofactors.push_back(StripFactor(OtherMul, OMulOp));
2842 DeadIndices.push_back(AddOp);
2843 break;
2844 }
2845 }
2846 }
2847
2848 // Fold all collected cofactors with the anchor multiply's cofactor:
2849 // MulOpSCEV * (Cofactor_1 + ... + Cofactor_n + AnchorCofactor)
2850 if (!Cofactors.empty()) {
2851 Cofactors.push_back(StripFactor(Mul, MulOp));
2852
2853 SCEVUse InnerSum = getAddExpr(Cofactors, SCEV::FlagNone, Depth + 1);
2854 SCEVUse OuterMul =
2855 getMulExpr(MulOpSCEV, InnerSum, SCEV::FlagNone, Depth + 1);
2856
2857 // DeadIndices does not include Idx (the anchor), hence +1.
2858 if (Ops.size() == DeadIndices.size() + 1)
2859 return OuterMul;
2860
2861 // Erase Ops[Idx] first, then erase DeadIndices in reverse order.
2862 // The -1 adjustment accounts for the shift from removing Idx;
2863 // reverse order means each erasure only shifts later positions,
2864 // which have already been processed.
2865 Ops.erase(Ops.begin() + Idx);
2866 for (unsigned Dead : reverse(DeadIndices))
2867 Ops.erase(Ops.begin() + (Dead > Idx ? Dead - 1 : Dead));
2868
2869 Ops.push_back(OuterMul);
2870 return getAddExpr(Ops, SCEV::FlagNone, Depth + 1);
2871 }
2872 }
2873 }
2874
2875 // If there are any add recurrences in the operands list, see if any other
2876 // added values are loop invariant. If so, we can fold them into the
2877 // recurrence.
2878 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2879 ++Idx;
2880
2881 // Scan over all recurrences, trying to fold loop invariants into them.
2882 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2883 // Scan all of the other operands to this add and add them to the vector if
2884 // they are loop invariant w.r.t. the recurrence.
2886 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2887 const Loop *AddRecLoop = AddRec->getLoop();
2888 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2889 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2890 LIOps.push_back(Ops[i]);
2891 Ops.erase(Ops.begin()+i);
2892 --i; --e;
2893 }
2894
2895 // If we found some loop invariants, fold them into the recurrence.
2896 if (!LIOps.empty()) {
2897 // Compute nowrap flags for the addition of the loop-invariant ops and
2898 // the addrec. Temporarily push it as an operand for that purpose. These
2899 // flags are valid in the scope of the addrec only.
2900 LIOps.push_back(AddRec);
2901 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2902 LIOps.pop_back();
2903
2904 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2905 LIOps.push_back(AddRec->getStart());
2906
2907 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2908
2909 // It is not in general safe to propagate flags valid on an add within
2910 // the addrec scope to one outside it. We must prove that the inner
2911 // scope is guaranteed to execute if the outer one does to be able to
2912 // safely propagate. We know the program is undefined if poison is
2913 // produced on the inner scoped addrec. We also know that *for this use*
2914 // the outer scoped add can't overflow (because of the flags we just
2915 // computed for the inner scoped add) without the program being undefined.
2916 // Proving that entry to the outer scope neccesitates entry to the inner
2917 // scope, thus proves the program undefined if the flags would be violated
2918 // in the outer scope.
2919 SCEV::NoWrapFlags AddFlags = Flags;
2920 if (AddFlags != SCEV::FlagNone) {
2921 auto *DefI = getDefiningScopeBound(LIOps);
2922 auto *ReachI = &*AddRecLoop->getHeader()->begin();
2923 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2924 AddFlags = SCEV::FlagNone;
2925 }
2926 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2927
2928 // Build the new addrec. Propagate the NUW and NSW flags if both the
2929 // outer add and the inner addrec are guaranteed to have no overflow.
2930 // Always propagate NW.
2931 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2932 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2933
2934 // If all of the other operands were loop invariant, we are done.
2935 if (Ops.size() == 1) return NewRec;
2936
2937 // Otherwise, add the folded AddRec by the non-invariant parts.
2938 for (unsigned i = 0;; ++i)
2939 if (Ops[i] == AddRec) {
2940 Ops[i] = NewRec;
2941 break;
2942 }
2943 return getAddExpr(Ops, SCEV::FlagNone, Depth + 1);
2944 }
2945
2946 // Okay, if there weren't any loop invariants to be folded, check to see if
2947 // there are multiple AddRec's with the same loop induction variable being
2948 // added together. If so, we can fold them.
2949 for (unsigned OtherIdx = Idx+1;
2950 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2951 ++OtherIdx) {
2952 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2953 // so that the 1st found AddRecExpr is dominated by all others.
2954 assert(DT.dominates(
2955 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2956 AddRec->getLoop()->getHeader()) &&
2957 "AddRecExprs are not sorted in reverse dominance order?");
2958 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2959 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2960 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2961 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2962 ++OtherIdx) {
2963 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2964 if (OtherAddRec->getLoop() == AddRecLoop) {
2965 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2966 i != e; ++i) {
2967 if (i >= AddRecOps.size()) {
2968 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
2969 break;
2970 }
2971 AddRecOps[i] =
2972 getAddExpr(AddRecOps[i], OtherAddRec->getOperand(i),
2973 SCEV::FlagNone, Depth + 1);
2974 }
2975 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2976 }
2977 }
2978 // Step size has changed, so we cannot guarantee no self-wraparound.
2979 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagNone);
2980 return getAddExpr(Ops, SCEV::FlagNone, Depth + 1);
2981 }
2982 }
2983
2984 // Otherwise couldn't fold anything into this recurrence. Move onto the
2985 // next one.
2986 }
2987
2988 // Okay, it looks like we really DO need an add expr. Check to see if we
2989 // already have one, otherwise create a new one.
2990 assert((UseFlags == SCEV::FlagNone || equal(OrigOps, Ops)) &&
2991 "Tried to add SCEVUse flags after operands changed");
2992 return {getOrCreateAddExpr(Ops, ComputeFlags(Ops)), UseFlags};
2993}
2994
2995const SCEV *ScalarEvolution::getOrCreateAddExpr(ArrayRef<SCEVUse> Ops,
2996 SCEV::NoWrapFlags Flags) {
2999 for (SCEVUse Op : Ops)
3000 ID.AddPointer(Op.getOpaqueValue());
3002 SCEVAddExpr *S = static_cast<SCEVAddExpr *>(UniqueSCEVs.lookup(ID, Token));
3003 if (!S) {
3004 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3006 S = new (SCEVAllocator)
3007 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
3008 UniqueSCEVs.insert(S, Token);
3009 S->computeAndSetCanonical(*this);
3010 registerUser(S, Ops);
3011 }
3012 S->setNoWrapFlags(Flags);
3013 return S;
3014}
3015
3016const SCEV *ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<SCEVUse> Ops,
3017 const Loop *L,
3018 SCEV::NoWrapFlags Flags) {
3019 FoldingSetNodeID ID;
3020 ID.AddInteger(scAddRecExpr);
3021 for (SCEVUse Op : Ops)
3022 ID.AddPointer(Op.getOpaqueValue());
3023 ID.AddPointer(L);
3024 FoldingSetInsertToken Token;
3025 SCEVAddRecExpr *S =
3026 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.lookup(ID, Token));
3027 if (!S) {
3028 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3030 S = new (SCEVAllocator)
3031 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
3032 UniqueSCEVs.insert(S, Token);
3033 S->computeAndSetCanonical(*this);
3034 LoopUsers[L].push_back(S);
3035 registerUser(S, Ops);
3036 }
3037 setNoWrapFlags(S, Flags);
3038 return S;
3039}
3040
3041const SCEV *ScalarEvolution::getOrCreateMulExpr(ArrayRef<SCEVUse> Ops,
3042 SCEV::NoWrapFlags Flags) {
3043 FoldingSetNodeID ID;
3044 ID.AddInteger(scMulExpr);
3045 for (SCEVUse Op : Ops)
3046 ID.AddPointer(Op.getOpaqueValue());
3047 FoldingSetInsertToken Token;
3048 SCEVMulExpr *S = static_cast<SCEVMulExpr *>(UniqueSCEVs.lookup(ID, Token));
3049 if (!S) {
3050 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3052 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
3053 O, Ops.size());
3054 UniqueSCEVs.insert(S, Token);
3055 S->computeAndSetCanonical(*this);
3056 registerUser(S, Ops);
3057 }
3058 S->setNoWrapFlags(Flags);
3059 return S;
3060}
3061
3062const SCEV *ScalarEvolution::getOrCreateUDivExpr(SCEVUse LHS, SCEVUse RHS) {
3063 FoldingSetNodeID ID;
3064 ID.AddInteger(scUDivExpr);
3065 ID.AddPointer(LHS.getOpaqueValue());
3066 ID.AddPointer(RHS.getOpaqueValue());
3067 FoldingSetInsertToken Token;
3068 SCEV *S = UniqueSCEVs.lookup(ID, Token);
3069 if (!S) {
3070 S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), LHS, RHS);
3071 UniqueSCEVs.insert(S, Token);
3072 S->computeAndSetCanonical(*this);
3073 registerUser(S, {LHS, RHS});
3074 }
3075 return S;
3076}
3077
3078static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
3079 uint64_t k = i*j;
3080 if (j > 1 && k / j != i) Overflow = true;
3081 return k;
3082}
3083
3084/// Compute the result of "n choose k", the binomial coefficient. If an
3085/// intermediate computation overflows, Overflow will be set and the return will
3086/// be garbage. Overflow is not cleared on absence of overflow.
3087static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3088 // We use the multiplicative formula:
3089 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3090 // At each iteration, we take the n-th term of the numeral and divide by the
3091 // (k-n)th term of the denominator. This division will always produce an
3092 // integral result, and helps reduce the chance of overflow in the
3093 // intermediate computations. However, we can still overflow even when the
3094 // final result would fit.
3095
3096 if (n == 0 || n == k) return 1;
3097 if (k > n) return 0;
3098
3099 if (k > n/2)
3100 k = n-k;
3101
3102 uint64_t r = 1;
3103 for (uint64_t i = 1; i <= k; ++i) {
3104 r = umul_ov(r, n-(i-1), Overflow);
3105 r /= i;
3106 }
3107 return r;
3108}
3109
3110/// Determine if any of the operands in this SCEV are a constant or if
3111/// any of the add or multiply expressions in this SCEV contain a constant.
3112static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3113 struct FindConstantInAddMulChain {
3114 bool FoundConstant = false;
3115
3116 bool follow(const SCEV *S) {
3117 FoundConstant |= isa<SCEVConstant>(S);
3118 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3119 }
3120
3121 bool isDone() const {
3122 return FoundConstant;
3123 }
3124 };
3125
3126 FindConstantInAddMulChain F;
3128 ST.visitAll(StartExpr);
3129 return F.FoundConstant;
3130}
3131
3132/// Get a canonical multiply expression, or something simpler if possible.
3134 SCEVFlags Flags, unsigned Depth) {
3135 SCEV::NoWrapFlags OrigFlags = Flags.ExprFlags;
3136 SCEV::NoWrapFlags UseFlags = Flags.UseFlags;
3137 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3138 "only nuw or nsw allowed");
3139 assert(UseFlags == maskFlags(UseFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3140 "only nuw or nsw allowed");
3141 assert(!Ops.empty() && "Cannot get empty mul!");
3142 if (Ops.size() == 1) return Ops[0];
3143#ifndef NDEBUG
3144 Type *ETy = Ops[0]->getType();
3145 assert(!ETy->isPointerTy());
3146 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3147 assert(Ops[i]->getType() == ETy &&
3148 "SCEVMulExpr operand types don't match!");
3149#endif
3150
3151 const SCEV *Folded = constantFoldAndGroupOps(
3152 *this, LI, DT, Ops,
3153 [](const APInt &C1, const APInt &C2) { return C1 * C2; },
3154 [](const APInt &C) { return C.isOne(); }, // identity
3155 [](const APInt &C) { return C.isZero(); }); // absorber
3156 if (Folded)
3157 return Folded;
3158
3159#ifndef NDEBUG
3160 // Keep track of operands after constant folding, for verification when adding
3161 // use-specific flags.
3162 const SmallVector<SCEVUse, 8> OrigOps(Ops.begin(), Ops.end());
3163#endif
3164
3165 // Delay expensive flag strengthening until necessary.
3166 auto ComputeFlags = [this, OrigFlags](const ArrayRef<SCEVUse> Ops) {
3167 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3168 };
3169
3170 // Limit recursion calls depth.
3172 return {getOrCreateMulExpr(Ops, ComputeFlags(Ops)), UseFlags};
3173
3174 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3175 // Don't strengthen flags if we have no new information.
3176 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3177 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3178 Mul->setNoWrapFlags(ComputeFlags(Ops));
3179 return {S, UseFlags};
3180 }
3181
3182 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3183 if (Ops.size() == 2) {
3184 // C1*(C2+V) -> C1*C2 + C1*V
3185 // If any of Add's ops are Adds or Muls with a constant, apply this
3186 // transformation as well.
3187 //
3188 // TODO: There are some cases where this transformation is not
3189 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
3190 // this transformation should be narrowed down.
3191 const SCEV *Op0, *Op1;
3192 if (match(Ops[1], m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))) &&
3194 const SCEV *LHS = getMulExpr(LHSC, Op0, SCEV::FlagNone, Depth + 1);
3195 const SCEV *RHS = getMulExpr(LHSC, Op1, SCEV::FlagNone, Depth + 1);
3196 return getAddExpr(LHS, RHS, SCEV::FlagNone, Depth + 1);
3197 }
3198
3199 if (Ops[0]->isAllOnesValue()) {
3200 // If we have a mul by -1 of an add, try distributing the -1 among the
3201 // add operands.
3202 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3204 bool AnyFolded = false;
3205 for (const SCEV *AddOp : Add->operands()) {
3206 const SCEV *Mul =
3207 getMulExpr(Ops[0], SCEVUse(AddOp), SCEV::FlagNone, Depth + 1);
3208 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3209 NewOps.push_back(Mul);
3210 }
3211 if (AnyFolded)
3212 return getAddExpr(NewOps, SCEV::FlagNone, Depth + 1);
3213 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3214 // Negation preserves a recurrence's no self-wrap property.
3216 for (const SCEV *AddRecOp : AddRec->operands())
3217 Operands.push_back(getMulExpr(Ops[0], SCEVUse(AddRecOp),
3218 SCEV::FlagNone, Depth + 1));
3219 // Let M be the minimum representable signed value. AddRec with nsw
3220 // multiplied by -1 can have signed overflow if and only if it takes a
3221 // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3222 // maximum signed value. In all other cases signed overflow is
3223 // impossible.
3224 auto FlagsMask = SCEV::FlagNW;
3225 if (AddRec->hasNoSignedWrap()) {
3226 auto MinInt =
3227 APInt::getSignedMinValue(getTypeSizeInBits(AddRec->getType()));
3228 if (getSignedRangeMin(AddRec) != MinInt)
3230 }
3231 return getAddRecExpr(Operands, AddRec->getLoop(),
3232 AddRec->getNoWrapFlags(FlagsMask));
3233 }
3234 }
3235
3236 // Try to push the constant operand into a ZExt: C * zext (A + B) ->
3237 // zext (C*A + C*B) if trunc (C) * (A + B) does not unsigned-wrap.
3238 const SCEVAddExpr *InnerAdd;
3239 if (match(Ops[1], m_scev_ZExt(m_scev_Add(InnerAdd)))) {
3240 const SCEV *NarrowC = getTruncateExpr(LHSC, InnerAdd->getType());
3241 if (isa<SCEVConstant>(InnerAdd->getOperand(0)) &&
3242 getZeroExtendExpr(NarrowC, Ops[1]->getType()) == LHSC &&
3243 hasFlags(StrengthenNoWrapFlags(this, scMulExpr, {NarrowC, InnerAdd},
3245 SCEV::FlagNUW)) {
3246 const SCEV *Res =
3247 getMulExpr(NarrowC, InnerAdd, SCEV::FlagNUW, Depth + 1);
3248 return getZeroExtendExpr(Res, Ops[1]->getType(), Depth + 1);
3249 };
3250 }
3251
3252 // Try to fold (C1 * D /u C2) -> C1/C2 * D, if C1 and C2 are powers-of-2,
3253 // D is a multiple of C2, and C1 is a multiple of C2. If C2 is a multiple
3254 // of C1, fold to (D /u (C2 /u C1)).
3255 const SCEV *D;
3256 APInt C1V = LHSC->getAPInt();
3257 // (C1 * D /u C2) == -1 * -C1 * D /u C2 when C1 != INT_MIN. Don't treat -1
3258 // as -1 * 1, as it won't enable additional folds.
3259 if (C1V.isNegative() && !C1V.isMinSignedValue() && !C1V.isAllOnes())
3260 C1V = C1V.abs();
3261 const SCEVConstant *C2;
3262 if (C1V.isPowerOf2() &&
3264 C2->getAPInt().isPowerOf2() &&
3265 C1V.logBase2() <= getMinTrailingZeros(D)) {
3266 const SCEV *NewMul = nullptr;
3267 if (C1V.uge(C2->getAPInt())) {
3268 NewMul = getMulExpr(getUDivExpr(getConstant(C1V), C2), D);
3269 } else if (C2->getAPInt().logBase2() <= getMinTrailingZeros(D)) {
3270 assert(C1V.ugt(1) && "C1 <= 1 should have been folded earlier");
3271 NewMul = getUDivExpr(D, getUDivExpr(C2, getConstant(C1V)));
3272 }
3273 if (NewMul)
3274 return C1V == LHSC->getAPInt() ? NewMul : getNegativeSCEV(NewMul);
3275 }
3276 }
3277 }
3278
3279 // Skip over the add expression until we get to a multiply.
3280 unsigned Idx = 0;
3281 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3282 ++Idx;
3283
3284 // If there are mul operands inline them all into this expression.
3285 if (Idx < Ops.size()) {
3286 bool DeletedMul = false;
3287 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3288 if (Ops.size() > MulOpsInlineThreshold)
3289 break;
3290 // If we have an mul, expand the mul operands onto the end of the
3291 // operands list.
3292 Ops.erase(Ops.begin()+Idx);
3293 append_range(Ops, Mul->operands());
3294 DeletedMul = true;
3295 }
3296
3297 // If we deleted at least one mul, we added operands to the end of the
3298 // list, and they are not necessarily sorted. Recurse to resort and
3299 // resimplify any operands we just acquired.
3300 if (DeletedMul)
3301 return getMulExpr(Ops, SCEV::FlagNone, Depth + 1);
3302 }
3303
3304 // If there are any add recurrences in the operands list, see if any other
3305 // added values are loop invariant. If so, we can fold them into the
3306 // recurrence.
3307 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3308 ++Idx;
3309
3310 // Scan over all recurrences, trying to fold loop invariants into them.
3311 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3312 // Scan all of the other operands to this mul and add them to the vector
3313 // if they are loop invariant w.r.t. the recurrence.
3315 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3316 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3317 if (isAvailableAtLoopEntry(Ops[i], AddRec->getLoop())) {
3318 LIOps.push_back(Ops[i]);
3319 Ops.erase(Ops.begin()+i);
3320 --i; --e;
3321 }
3322
3323 // If we found some loop invariants, fold them into the recurrence.
3324 if (!LIOps.empty()) {
3325 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3327 NewOps.reserve(AddRec->getNumOperands());
3328 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagNone, Depth + 1);
3329
3330 // If both the mul and addrec are nuw, we can preserve nuw.
3331 // If both the mul and addrec are nsw, we can only preserve nsw if either
3332 // a) they are also nuw, or
3333 // b) all multiplications of addrec operands with scale are nsw.
3334 SCEV::NoWrapFlags Flags =
3335 AddRec->getNoWrapFlags(ComputeFlags({Scale, AddRec}));
3336
3337 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3338 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3339 SCEV::FlagNone, Depth + 1));
3340
3341 if (hasFlags(Flags, SCEV::FlagNSW) && !hasFlags(Flags, SCEV::FlagNUW)) {
3343 Instruction::Mul, getSignedRange(Scale),
3345 if (!NSWRegion.contains(getSignedRange(AddRec->getOperand(i))))
3346 Flags = clearFlags(Flags, SCEV::FlagNSW);
3347 }
3348 }
3349
3350 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(), Flags);
3351
3352 // If all of the other operands were loop invariant, we are done.
3353 if (Ops.size() == 1) return NewRec;
3354
3355 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3356 for (unsigned i = 0;; ++i)
3357 if (Ops[i] == AddRec) {
3358 Ops[i] = NewRec;
3359 break;
3360 }
3361 return getMulExpr(Ops, SCEV::FlagNone, Depth + 1);
3362 }
3363
3364 // Okay, if there weren't any loop invariants to be folded, check to see
3365 // if there are multiple AddRec's with the same loop induction variable
3366 // being multiplied together. If so, we can fold them.
3367
3368 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3369 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3370 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3371 // ]]],+,...up to x=2n}.
3372 // Note that the arguments to choose() are always integers with values
3373 // known at compile time, never SCEV objects.
3374 //
3375 // The implementation avoids pointless extra computations when the two
3376 // addrec's are of different length (mathematically, it's equivalent to
3377 // an infinite stream of zeros on the right).
3378 bool OpsModified = false;
3379 for (unsigned OtherIdx = Idx+1;
3380 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3381 ++OtherIdx) {
3382 const SCEVAddRecExpr *OtherAddRec =
3383 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3384 if (!OtherAddRec || OtherAddRec->getLoop() != AddRec->getLoop())
3385 continue;
3386
3387 // Limit max number of arguments to avoid creation of unreasonably big
3388 // SCEVAddRecs with very complex operands.
3389 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3390 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3391 continue;
3392
3393 bool Overflow = false;
3394 Type *Ty = AddRec->getType();
3395 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3396 SmallVector<SCEVUse, 7> AddRecOps;
3397 for (int x = 0, xe = AddRec->getNumOperands() +
3398 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3400 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3401 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3402 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3403 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3404 z < ze && !Overflow; ++z) {
3405 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3406 uint64_t Coeff;
3407 if (LargerThan64Bits)
3408 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3409 else
3410 Coeff = Coeff1*Coeff2;
3411 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3412 const SCEV *Term1 = AddRec->getOperand(y-z);
3413 const SCEV *Term2 = OtherAddRec->getOperand(z);
3414 SumOps.push_back(
3415 getMulExpr(CoeffTerm, Term1, Term2, SCEV::FlagNone, Depth + 1));
3416 }
3417 }
3418 if (SumOps.empty())
3419 SumOps.push_back(getZero(Ty));
3420 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagNone, Depth + 1));
3421 }
3422 if (!Overflow) {
3423 const SCEV *NewAddRec =
3424 getAddRecExpr(AddRecOps, AddRec->getLoop(), SCEV::FlagNone);
3425 if (Ops.size() == 2) return NewAddRec;
3426 Ops[Idx] = NewAddRec;
3427 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3428 OpsModified = true;
3429 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3430 if (!AddRec)
3431 break;
3432 }
3433 }
3434 if (OpsModified)
3435 return getMulExpr(Ops, SCEV::FlagNone, Depth + 1);
3436
3437 // Otherwise couldn't fold anything into this recurrence. Move onto the
3438 // next one.
3439 }
3440
3441 // Okay, it looks like we really DO need an mul expr. Check to see if we
3442 // already have one, otherwise create a new one.
3443 assert((UseFlags == SCEV::FlagNone || equal(OrigOps, Ops)) &&
3444 "Tried to add SCEVUse flags after operands changed");
3445 return {getOrCreateMulExpr(Ops, ComputeFlags(Ops)), UseFlags};
3446}
3447
3448/// Represents an unsigned remainder expression based on unsigned division.
3450 assert(getEffectiveSCEVType(LHS->getType()) ==
3451 getEffectiveSCEVType(RHS->getType()) &&
3452 "SCEVURemExpr operand types don't match!");
3453
3454 // Short-circuit easy cases
3455 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3456 // If constant is one, the result is trivial
3457 if (RHSC->getValue()->isOne())
3458 return getZero(LHS->getType()); // X urem 1 --> 0
3459
3460 // If constant is a power of two, fold into a zext(trunc(LHS)).
3461 if (RHSC->getAPInt().isPowerOf2()) {
3462 Type *FullTy = LHS->getType();
3463 Type *TruncTy =
3464 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3465 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3466 }
3467 }
3468
3469 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3470 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3471 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3472 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3473}
3474
3475/// Get a canonical unsigned division expression, or something simpler if
3476/// possible.
3478 assert(!LHS->getType()->isPointerTy() &&
3479 "SCEVUDivExpr operand can't be pointer!");
3480 assert(LHS->getType() == RHS->getType() &&
3481 "SCEVUDivExpr operand types don't match!");
3482
3483 if (SCEV *S = findExistingSCEVInCache(scUDivExpr, {LHS, RHS}))
3484 return S;
3485
3486 // 0 udiv Y == 0
3487 if (match(LHS, m_scev_Zero()))
3488 return LHS;
3489
3490 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3491 if (RHSC->getValue()->isOne())
3492 return LHS; // X udiv 1 --> x
3493 // If the denominator is zero, the result of the udiv is undefined. Don't
3494 // try to analyze it, because the resolution chosen here may differ from
3495 // the resolution chosen in other parts of the compiler.
3496 if (!RHSC->getValue()->isZero()) {
3497 // Determine if the division can be folded into the operands of
3498 // its operands.
3499 // TODO: Generalize this to non-constants by using known-bits information.
3500 Type *Ty = LHS->getType();
3501 unsigned LZ = RHSC->getAPInt().countl_zero();
3502 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3503 // For non-power-of-two values, effectively round the value up to the
3504 // nearest power of two.
3505 if (!RHSC->getAPInt().isPowerOf2())
3506 ++MaxShiftAmt;
3507 IntegerType *ExtTy =
3508 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3509 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3510 if (const SCEVConstant *Step =
3511 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3512 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3513 const APInt &StepInt = Step->getAPInt();
3514 const APInt &DivInt = RHSC->getAPInt();
3515 if (!StepInt.urem(DivInt) &&
3516 getZeroExtendExpr(AR, ExtTy) ==
3517 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3518 getZeroExtendExpr(Step, ExtTy), AR->getLoop(),
3519 SCEV::FlagNone)) {
3521 for (const SCEV *Op : AR->operands())
3522 Operands.push_back(getUDivExpr(Op, RHS));
3523 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3524 }
3525 /// Get a canonical UDivExpr for a recurrence.
3526 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3527 const APInt *StartRem;
3528 if (!DivInt.urem(StepInt) && match(getURemExpr(AR->getStart(), Step),
3529 m_scev_APInt(StartRem))) {
3530 bool NoWrap =
3531 getZeroExtendExpr(AR, ExtTy) ==
3532 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3533 getZeroExtendExpr(Step, ExtTy), AR->getLoop(),
3535
3536 // With N <= C and both N, C as powers-of-2, the transformation
3537 // {X,+,N}/C => {(X - X%N),+,N}/C preserves division results even
3538 // if wrapping occurs, as the division results remain equivalent for
3539 // all offsets in [[(X - X%N), X).
3540 bool CanFoldWithWrap = StepInt.ule(DivInt) && // N <= C
3541 StepInt.isPowerOf2() && DivInt.isPowerOf2();
3542 // Only fold if the subtraction can be folded in the start
3543 // expression.
3544 const SCEV *NewStart =
3545 getMinusSCEV(AR->getStart(), getConstant(*StartRem));
3546 if (*StartRem != 0 && (NoWrap || CanFoldWithWrap) &&
3547 !isa<SCEVAddExpr>(NewStart)) {
3548 const SCEV *NewLHS =
3549 getAddRecExpr(NewStart, Step, AR->getLoop(),
3550 NoWrap ? SCEV::FlagNW : SCEV::FlagNone);
3551 if (LHS != NewLHS)
3552 return getUDivExpr(NewLHS, RHS);
3553 }
3554 }
3555 }
3556 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3557 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3558 if (M->hasNoUnsignedWrap()) {
3559 // Find an operand that's safely divisible.
3560 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3561 const SCEV *Op = M->getOperand(i);
3562 const SCEV *Div = getUDivExpr(Op, RHSC);
3563 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3564 SmallVector<SCEVUse, 4> Operands(M->operands());
3565 Operands[i] = Div;
3566 return getMulExpr(Operands);
3567 }
3568 }
3569
3570 // Even if it's not divisible, try to remove a common factor.
3571 if (const auto *LHSC = dyn_cast<SCEVConstant>(M->getOperand(0))) {
3572 APInt Factor = APIntOps::GreatestCommonDivisor(LHSC->getAPInt(),
3573 RHSC->getAPInt());
3574 if (!Factor.isIntN(1)) {
3575 SmallVector<SCEVUse, 2> NewOperands;
3576 NewOperands.push_back(getConstant(LHSC->getAPInt().udiv(Factor)));
3577 append_range(NewOperands, M->operands().drop_front());
3578 const SCEV *NewMul = getMulExpr(NewOperands);
3579 return getUDivExpr(NewMul,
3580 getConstant(RHSC->getAPInt().udiv(Factor)));
3581 }
3582 }
3583 }
3584 }
3585
3586 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3587 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3588 if (auto *DivisorConstant =
3589 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3590 bool Overflow = false;
3591 APInt NewRHS =
3592 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3593 if (Overflow) {
3594 return getConstant(RHSC->getType(), 0, false);
3595 }
3596 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3597 }
3598 }
3599
3600 // (A+B)/C --> (A/C + B/C) if the add does not unsigned wrap and A/C and
3601 // B/C can be folded.
3602 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3603 if (A->hasNoUnsignedWrap()) {
3605 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3606 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3607 if (isa<SCEVUDivExpr>(Op) ||
3608 getMulExpr(Op, RHS) != A->getOperand(i))
3609 break;
3610 Operands.push_back(Op);
3611 }
3612 if (Operands.size() == A->getNumOperands())
3613 return getAddExpr(Operands);
3614 }
3615 }
3616
3617 // ((N - M) + (M * A)) / N --> ((N - 1) + (M * A)) / N
3618 // This is an idiom for rounding A up to the next multiple of N, where A
3619 // is aready known to be a multiple of M. In this case, instcombine can
3620 // see that some low bits of the added constant are unused, so can clear
3621 // them, but we want to canonicalise to set the low bits. This makes the
3622 // pattern easier to match, without needing to check for known bits in
3623 // A*M.
3624 const APInt &N = RHSC->getAPInt();
3625 const APInt *NMinusM, *M;
3626 const SCEV *A;
3627 if (match(LHS, m_scev_Add(m_scev_APInt(NMinusM),
3628 m_scev_Mul(m_scev_APInt(M), m_SCEV(A))))) {
3629 if (N.isPowerOf2() && M->isPowerOf2() && M->ult(N) &&
3630 *NMinusM == N - *M) {
3631 return getUDivExpr(
3633 RHS);
3634 }
3635 }
3636
3637 // Fold if both operands are constant.
3638 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3639 return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3640 }
3641 }
3642
3643 // ((-C + (C smax %x)) /u %x) evaluates to zero, for any positive constant C.
3644 const APInt *NegC, *C;
3645 if (match(LHS,
3648 NegC->isNegative() && !NegC->isMinSignedValue() && *C == -*NegC)
3649 return getZero(LHS->getType());
3650
3651 // (%a * %b)<nuw> / %b -> %a
3652 const auto *Mul = dyn_cast<SCEVMulExpr>(LHS);
3653 if (Mul && Mul->hasNoUnsignedWrap()) {
3654 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3655 if (Mul->getOperand(i) == RHS) {
3657 append_range(Operands, Mul->operands().take_front(i));
3658 append_range(Operands, Mul->operands().drop_front(i + 1));
3659 return getMulExpr(Operands);
3660 }
3661 }
3662 }
3663
3664 // TODO: Generalize to handle any common factors.
3665 // udiv (mul nuw a, vscale), (mul nuw b, vscale) --> udiv a, b
3666 const SCEV *NewLHS, *NewRHS;
3667 if (match(LHS, m_scev_c_NUWMul(m_SCEV(NewLHS), m_SCEVVScale())) &&
3668 match(RHS, m_scev_c_NUWMul(m_SCEV(NewRHS), m_SCEVVScale())))
3669 return getUDivExpr(NewLHS, NewRHS);
3670
3671 return getOrCreateUDivExpr(LHS, RHS);
3672}
3673
3674/// Get a canonical unsigned division expression, or something simpler if
3675/// possible. There is no representation for an exact udiv in SCEV IR, but we
3676/// can attempt to optimize it prior to construction.
3678 // Currently there is no exact specific logic.
3679
3680 return getUDivExpr(LHS, RHS);
3681}
3682
3683/// Get an add recurrence expression for the specified loop. Simplify the
3684/// expression as much as possible.
3686 const Loop *L, SCEVFlags Flags) {
3688 Operands.push_back(Start);
3689 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3690 if (StepChrec->getLoop() == L) {
3691 append_range(Operands, StepChrec->operands());
3692 // The use flags describe the two-operand recurrence, not the flattened
3693 // one built here, so drop them just like the expression's NUW/NSW.
3694 return getAddRecExpr(Operands, L,
3695 maskFlags(Flags.ExprFlags, SCEV::FlagNW));
3696 }
3697
3698 Operands.push_back(Step);
3699 return getAddRecExpr(Operands, L, Flags);
3700}
3701
3702/// Get an add recurrence expression for the specified loop. Simplify the
3703/// expression as much as possible.
3705 const Loop *L, SCEVFlags NWFlags) {
3706 SCEV::NoWrapFlags Flags = NWFlags.ExprFlags;
3707 SCEV::NoWrapFlags UseFlags = NWFlags.UseFlags;
3708 assert(!(UseFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
3709 "only nuw or nsw allowed");
3710 if (Operands.size() == 1) return Operands[0];
3711#ifndef NDEBUG
3713 for (const SCEV *Op : llvm::drop_begin(Operands)) {
3714 assert(getEffectiveSCEVType(Op->getType()) == ETy &&
3715 "SCEVAddRecExpr operand types don't match!");
3716 assert(!Op->getType()->isPointerTy() && "Step must be integer");
3717 }
3718 for (const SCEV *Op : Operands)
3720 "SCEVAddRecExpr operand is not available at loop entry!");
3721
3722 // Keep track of the original operands, for verification when adding
3723 // use-specific flags.
3724 const SmallVector<SCEVUse, 4> OrigOperands(Operands.begin(), Operands.end());
3725#endif
3726
3727 if (Operands.back()->isZero()) {
3728 Operands.pop_back();
3729 return getAddRecExpr(Operands, L, SCEV::FlagNone); // {X,+,0} --> X
3730 }
3731
3732 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3733 // use that information to infer NUW and NSW flags. However, computing a
3734 // BE count requires calling getAddRecExpr, so we may not yet have a
3735 // meaningful BE count at this point (and if we don't, we'd be stuck
3736 // with a SCEVCouldNotCompute as the cached BE count).
3737
3738 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3739
3740 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3741 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3742 const Loop *NestedLoop = NestedAR->getLoop();
3743 if (L->contains(NestedLoop)
3744 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3745 : (!NestedLoop->contains(L) &&
3746 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3747 SmallVector<SCEVUse, 4> NestedOperands(NestedAR->operands());
3748 Operands[0] = NestedAR->getStart();
3749 // AddRecs require their operands be loop-invariant with respect to their
3750 // loops. Don't perform this transformation if it would break this
3751 // requirement.
3752 bool AllInvariant = all_of(
3753 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3754
3755 if (AllInvariant) {
3756 // Create a recurrence for the outer loop with the same step size.
3757 //
3758 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3759 // inner recurrence has the same property.
3760 SCEV::NoWrapFlags OuterFlags =
3761 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3762
3763 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3764 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3765 return isLoopInvariant(Op, NestedLoop);
3766 });
3767
3768 if (AllInvariant) {
3769 // Ok, both add recurrences are valid after the transformation.
3770 //
3771 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3772 // the outer recurrence has the same property.
3773 SCEV::NoWrapFlags InnerFlags =
3774 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3775 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3776 }
3777 }
3778 // Reset Operands to its original state.
3779 Operands[0] = NestedAR;
3780 }
3781 }
3782
3783 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3784 // already have one, otherwise create a new one.
3785 assert((UseFlags == SCEV::FlagNone || equal(OrigOperands, Operands)) &&
3786 "Tried to add SCEVUse flags after operands changed");
3787 return {getOrCreateAddRecExpr(Operands, L, Flags), UseFlags};
3788}
3789
3791 ArrayRef<SCEVUse> IndexExprs) {
3792 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3793 // getSCEV(Base)->getType() has the same address space as Base->getType()
3794 // because SCEV::getType() preserves the address space.
3795 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
3796 if (NW != GEPNoWrapFlags::none()) {
3797 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3798 // but to do that, we have to ensure that said flag is valid in the entire
3799 // defined scope of the SCEV.
3800 // TODO: non-instructions have global scope. We might be able to prove
3801 // some global scope cases
3802 auto *GEPI = dyn_cast<Instruction>(GEP);
3803 if (!GEPI || !isSCEVExprNeverPoison(GEPI))
3804 NW = GEPNoWrapFlags::none();
3805 }
3806
3807 return getGEPExpr(BaseExpr, IndexExprs, GEP->getSourceElementType(), NW);
3808}
3809
3811 ArrayRef<SCEVUse> IndexExprs,
3812 Type *SrcElementTy, GEPNoWrapFlags NW) {
3813 SCEV::NoWrapFlags OffsetWrap = SCEV::FlagNone;
3814 if (NW.hasNoUnsignedSignedWrap())
3815 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNSW);
3816 if (NW.hasNoUnsignedWrap())
3817 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNUW);
3818
3819 Type *CurTy = BaseExpr->getType();
3820 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3821 bool FirstIter = true;
3823 for (SCEVUse IndexExpr : IndexExprs) {
3824 // Compute the (potentially symbolic) offset in bytes for this index.
3825 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3826 // For a struct, add the member offset.
3827 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3828 unsigned FieldNo = Index->getZExtValue();
3829 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3830 Offsets.push_back(FieldOffset);
3831
3832 // Update CurTy to the type of the field at Index.
3833 CurTy = STy->getTypeAtIndex(Index);
3834 } else {
3835 // Update CurTy to its element type.
3836 if (FirstIter) {
3837 assert(isa<PointerType>(CurTy) &&
3838 "The first index of a GEP indexes a pointer");
3839 CurTy = SrcElementTy;
3840 FirstIter = false;
3841 } else {
3842 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3843 }
3844 // For an array, add the element offset, explicitly scaled.
3845 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3846 // Getelementptr indices are signed.
3847 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3848
3849 // Multiply the index by the element size to compute the element offset.
3850 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3851 Offsets.push_back(LocalOffset);
3852 }
3853 }
3854
3855 // Handle degenerate case of GEP without offsets.
3856 if (Offsets.empty())
3857 return BaseExpr;
3858
3859 // Add the offsets together, assuming nsw if inbounds.
3860 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3861 // Add the base address and the offset. We cannot use the nsw flag, as the
3862 // base address is unsigned. However, if we know that the offset is
3863 // non-negative, we can use nuw.
3864 bool NUW = NW.hasNoUnsignedWrap() ||
3867 const SCEV *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3868 assert(BaseExpr->getType() == GEPExpr->getType() &&
3869 "GEP should not change type mid-flight.");
3870 return GEPExpr;
3871}
3872
3873SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3876 ID.AddInteger(SCEVType);
3877 for (SCEVUse Op : Ops)
3878 ID.AddPointer(Op.getOpaqueValue());
3880 return UniqueSCEVs.lookup(ID, Token);
3881}
3882
3883const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3885 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3886}
3887
3890 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3891 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3892 if (Ops.size() == 1) return Ops[0];
3893#ifndef NDEBUG
3894 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3895 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3896 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3897 "Operand types don't match!");
3898 assert(Ops[0]->getType()->isPointerTy() ==
3899 Ops[i]->getType()->isPointerTy() &&
3900 "min/max should be consistently pointerish");
3901 }
3902#endif
3903
3904 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3905 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3906
3907 const SCEV *Folded = constantFoldAndGroupOps(
3908 *this, LI, DT, Ops,
3909 [&](const APInt &C1, const APInt &C2) {
3910 switch (Kind) {
3911 case scSMaxExpr:
3912 return APIntOps::smax(C1, C2);
3913 case scSMinExpr:
3914 return APIntOps::smin(C1, C2);
3915 case scUMaxExpr:
3916 return APIntOps::umax(C1, C2);
3917 case scUMinExpr:
3918 return APIntOps::umin(C1, C2);
3919 default:
3920 llvm_unreachable("Unknown SCEV min/max opcode");
3921 }
3922 },
3923 [&](const APInt &C) {
3924 // identity
3925 if (IsMax)
3926 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3927 else
3928 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3929 },
3930 [&](const APInt &C) {
3931 // absorber
3932 if (IsMax)
3933 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3934 else
3935 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3936 });
3937 if (Folded)
3938 return Folded;
3939
3940 // Check if we have created the same expression before.
3941 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3942 return S;
3943 }
3944
3945 // Find the first operation of the same kind
3946 unsigned Idx = 0;
3947 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3948 ++Idx;
3949
3950 // Check to see if one of the operands is of the same kind. If so, expand its
3951 // operands onto our operand list, and recurse to simplify.
3952 if (Idx < Ops.size()) {
3953 bool DeletedAny = false;
3954 while (Ops[Idx]->getSCEVType() == Kind) {
3955 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3956 Ops.erase(Ops.begin()+Idx);
3957 append_range(Ops, SMME->operands());
3958 DeletedAny = true;
3959 }
3960
3961 if (DeletedAny)
3962 return getMinMaxExpr(Kind, Ops);
3963 }
3964
3965 // Okay, check to see if the same value occurs in the operand list twice. If
3966 // so, delete one. Since we sorted the list, these values are required to
3967 // be adjacent.
3972 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3973 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3974 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3975 if (Ops[i] == Ops[i + 1] ||
3976 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3977 // X op Y op Y --> X op Y
3978 // X op Y --> X, if we know X, Y are ordered appropriately
3979 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3980 --i;
3981 --e;
3982 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3983 Ops[i + 1])) {
3984 // X op Y --> Y, if we know X, Y are ordered appropriately
3985 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3986 --i;
3987 --e;
3988 }
3989 }
3990
3991 if (Ops.size() == 1) return Ops[0];
3992
3993 assert(!Ops.empty() && "Reduced smax down to nothing!");
3994
3995 // Okay, it looks like we really DO need an expr. Check to see if we
3996 // already have one, otherwise create a new one.
3998 ID.AddInteger(Kind);
3999 for (SCEVUse Op : Ops)
4000 ID.AddPointer(Op.getOpaqueValue());
4002 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
4003 if (ExistingSCEV)
4004 return ExistingSCEV;
4005 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4007 SCEV *S = new (SCEVAllocator)
4008 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4009
4010 UniqueSCEVs.insert(S, Token);
4011 S->computeAndSetCanonical(*this);
4012 registerUser(S, Ops);
4013 return S;
4014}
4015
4016namespace {
4017
4018class SCEVSequentialMinMaxDeduplicatingVisitor final
4019 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
4020 std::optional<const SCEV *>> {
4021 using RetVal = std::optional<const SCEV *>;
4022
4023 ScalarEvolution &SE;
4024 const SCEVTypes RootKind; // Must be a sequential min/max expression.
4025 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
4027
4028 bool canRecurseInto(SCEVTypes Kind) const {
4029 // We can only recurse into the SCEV expression of the same effective type
4030 // as the type of our root SCEV expression.
4031 return RootKind == Kind || NonSequentialRootKind == Kind;
4032 };
4033
4034 RetVal visit(const SCEV *S) {
4035 // Has the whole operand been seen already?
4036 if (!SeenOps.insert(S).second)
4037 return std::nullopt;
4039 SCEVTypes Kind = S->getSCEVType();
4040
4041 if (!canRecurseInto(Kind))
4042 return S;
4043
4044 auto *NAry = cast<SCEVNAryExpr>(S);
4045 SmallVector<SCEVUse> NewOps;
4046 bool Changed = visit(Kind, NAry->operands(), NewOps);
4047
4048 if (!Changed)
4049 return S;
4050 if (NewOps.empty())
4051 return std::nullopt;
4052
4054 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
4055 : SE.getMinMaxExpr(Kind, NewOps);
4056 }
4057 return S;
4058 }
4059
4060public:
4061 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
4062 SCEVTypes RootKind)
4063 : SE(SE), RootKind(RootKind),
4064 NonSequentialRootKind(
4065 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4066 RootKind)) {}
4067
4068 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<SCEVUse> OrigOps,
4069 SmallVectorImpl<SCEVUse> &NewOps) {
4070 bool Changed = false;
4072 Ops.reserve(OrigOps.size());
4073
4074 for (const SCEV *Op : OrigOps) {
4075 RetVal NewOp = visit(Op);
4076 if (NewOp != Op)
4077 Changed = true;
4078 if (NewOp)
4079 Ops.emplace_back(*NewOp);
4080 }
4081
4082 if (Changed)
4083 NewOps = std::move(Ops);
4084 return Changed;
4085 }
4086};
4087
4088} // namespace
4089
4091 switch (Kind) {
4092 case scConstant:
4093 case scVScale:
4094 case scTruncate:
4095 case scZeroExtend:
4096 case scSignExtend:
4097 case scPtrToAddr:
4098 case scAddExpr:
4099 case scMulExpr:
4100 case scUDivExpr:
4101 case scAddRecExpr:
4102 case scUMaxExpr:
4103 case scSMaxExpr:
4104 case scUMinExpr:
4105 case scSMinExpr:
4106 case scUnknown:
4107 // If any operand is poison, the whole expression is poison.
4108 return true;
4110 // FIXME: if the *first* operand is poison, the whole expression is poison.
4111 return false; // Pessimistically, say that it does not propagate poison.
4112 case scCouldNotCompute:
4113 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4114 }
4115 llvm_unreachable("Unknown SCEV kind!");
4116}
4117
4118namespace {
4119// The only way poison may be introduced in a SCEV expression is from a
4120// poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4121// not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not*
4122// introduce poison -- they encode guaranteed, non-speculated knowledge.
4123//
4124// Additionally, all SCEV nodes propagate poison from inputs to outputs,
4125// with the notable exception of umin_seq, where only poison from the first
4126// operand is (unconditionally) propagated.
4127struct SCEVPoisonCollector {
4128 bool LookThroughMaybePoisonBlocking;
4129 SmallPtrSet<const SCEVUnknown *, 4> MaybePoison;
4130 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4131 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4132
4133 bool follow(const SCEV *S) {
4134 if (!LookThroughMaybePoisonBlocking &&
4136 return false;
4137
4138 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4139 if (!isGuaranteedNotToBePoison(SU->getValue()))
4140 MaybePoison.insert(SU);
4141 }
4142 return true;
4143 }
4144 bool isDone() const { return false; }
4145};
4146} // namespace
4147
4148/// Return true if V is poison given that AssumedPoison is already poison.
4149static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4150 // First collect all SCEVs that might result in AssumedPoison to be poison.
4151 // We need to look through potentially poison-blocking operations here,
4152 // because we want to find all SCEVs that *might* result in poison, not only
4153 // those that are *required* to.
4154 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4155 visitAll(AssumedPoison, PC1);
4156
4157 // AssumedPoison is never poison. As the assumption is false, the implication
4158 // is true. Don't bother walking the other SCEV in this case.
4159 if (PC1.MaybePoison.empty())
4160 return true;
4161
4162 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4163 // as well. We cannot look through potentially poison-blocking operations
4164 // here, as their arguments only *may* make the result poison.
4165 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4166 visitAll(S, PC2);
4167
4168 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4169 // it will also make S poison by being part of PC2.MaybePoison.
4170 return llvm::set_is_subset(PC1.MaybePoison, PC2.MaybePoison);
4171}
4172
4174 SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4175 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4176 visitAll(S, PC);
4177 for (const SCEVUnknown *SU : PC.MaybePoison)
4178 Result.insert(SU->getValue());
4179}
4180
4182 const SCEV *S, Instruction *I,
4183 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
4184 // If the instruction cannot be poison, it's always safe to reuse.
4186 return true;
4187
4188 // Otherwise, it is possible that I is more poisonous that S. Collect the
4189 // poison-contributors of S, and then check whether I has any additional
4190 // poison-contributors. Poison that is contributed through poison-generating
4191 // flags is handled by dropping those flags instead.
4193 getPoisonGeneratingValues(PoisonVals, S);
4194
4195 SmallVector<Value *> Worklist;
4197 Worklist.push_back(I);
4198 while (!Worklist.empty()) {
4199 Value *V = Worklist.pop_back_val();
4200 if (!Visited.insert(V).second)
4201 continue;
4202
4203 // Avoid walking large instruction graphs.
4204 if (Visited.size() > 16)
4205 return false;
4206
4207 // Either the value can't be poison, or the S would also be poison if it
4208 // is.
4209 if (PoisonVals.contains(V) || ::isGuaranteedNotToBePoison(V))
4210 continue;
4211
4212 auto *I = dyn_cast<Instruction>(V);
4213 if (!I)
4214 return false;
4215
4216 // Disjoint or instructions are interpreted as adds by SCEV. However, we
4217 // can't replace an arbitrary add with disjoint or, even if we drop the
4218 // flag. We would need to convert the or into an add.
4219 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
4220 if (PDI->isDisjoint())
4221 return false;
4222
4223 // FIXME: Ignore vscale, even though it technically could be poison. Do this
4224 // because SCEV currently assumes it can't be poison. Remove this special
4225 // case once we proper model when vscale can be poison.
4226 if (auto *II = dyn_cast<IntrinsicInst>(I);
4227 II && II->getIntrinsicID() == Intrinsic::vscale)
4228 continue;
4229
4230 if (canCreatePoison(cast<Operator>(I), /*ConsiderFlagsAndMetadata*/ false))
4231 return false;
4232
4233 // If the instruction can't create poison, we can recurse to its operands.
4234 if (I->hasPoisonGeneratingAnnotations())
4235 DropPoisonGeneratingInsts.push_back(I);
4236
4237 llvm::append_range(Worklist, I->operands());
4238 }
4239 return true;
4240}
4241
4242const SCEV *
4245 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4246 "Not a SCEVSequentialMinMaxExpr!");
4247 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4248 if (Ops.size() == 1)
4249 return Ops[0];
4250#ifndef NDEBUG
4251 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4252 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4253 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4254 "Operand types don't match!");
4255 assert(Ops[0]->getType()->isPointerTy() ==
4256 Ops[i]->getType()->isPointerTy() &&
4257 "min/max should be consistently pointerish");
4258 }
4259#endif
4260
4261 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4262 // so we can *NOT* do any kind of sorting of the expressions!
4263
4264 // Check if we have created the same expression before.
4265 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4266 return S;
4267
4268 // FIXME: there are *some* simplifications that we can do here.
4269
4270 // Keep only the first instance of an operand.
4271 {
4272 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4273 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4274 if (Changed)
4275 return getSequentialMinMaxExpr(Kind, Ops);
4276 }
4277
4278 // Check to see if one of the operands is of the same kind. If so, expand its
4279 // operands onto our operand list, and recurse to simplify.
4280 {
4281 unsigned Idx = 0;
4282 bool DeletedAny = false;
4283 while (Idx < Ops.size()) {
4284 if (Ops[Idx]->getSCEVType() != Kind) {
4285 ++Idx;
4286 continue;
4287 }
4288 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4289 Ops.erase(Ops.begin() + Idx);
4290 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4291 SMME->operands().end());
4292 DeletedAny = true;
4293 }
4294
4295 if (DeletedAny)
4296 return getSequentialMinMaxExpr(Kind, Ops);
4297 }
4298
4299 const SCEV *SaturationPoint;
4301 switch (Kind) {
4303 SaturationPoint = getZero(Ops[0]->getType());
4304 Pred = ICmpInst::ICMP_ULE;
4305 break;
4306 default:
4307 llvm_unreachable("Not a sequential min/max type.");
4308 }
4309
4310 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4311 if (!isGuaranteedNotToCauseUB(Ops[i]))
4312 continue;
4313 // We can replace %x umin_seq %y with %x umin %y if either:
4314 // * %y being poison implies %x is also poison.
4315 // * %x cannot be the saturating value (e.g. zero for umin).
4316 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4317 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4318 SaturationPoint)) {
4319 SmallVector<SCEVUse, 2> SeqOps = {Ops[i - 1], Ops[i]};
4320 Ops[i - 1] = getMinMaxExpr(
4322 SeqOps);
4323 Ops.erase(Ops.begin() + i);
4324 return getSequentialMinMaxExpr(Kind, Ops);
4325 }
4326 // Fold %x umin_seq %y to %x if %x ule %y.
4327 // TODO: We might be able to prove the predicate for a later operand.
4328 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4329 Ops.erase(Ops.begin() + i);
4330 return getSequentialMinMaxExpr(Kind, Ops);
4331 }
4332 }
4333
4334 // Okay, it looks like we really DO need an expr. Check to see if we
4335 // already have one, otherwise create a new one.
4337 ID.AddInteger(Kind);
4338 for (SCEVUse Op : Ops)
4339 ID.AddPointer(Op.getOpaqueValue());
4341 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
4342 if (ExistingSCEV)
4343 return ExistingSCEV;
4344
4345 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4347 SCEV *S = new (SCEVAllocator)
4348 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4349
4350 UniqueSCEVs.insert(S, Token);
4351 S->computeAndSetCanonical(*this);
4352 registerUser(S, Ops);
4353 return S;
4354}
4355
4360
4364
4369
4373
4378
4382
4384 bool Sequential) {
4385 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4386 return getUMinExpr(Ops, Sequential);
4387}
4388
4394
4395const SCEV *
4397 const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4398 if (Size.isScalable())
4399 Res = getMulExpr(Res, getVScale(IntTy));
4400 return Res;
4401}
4402
4404 return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4405}
4406
4408 return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4409}
4410
4412 StructType *STy,
4413 unsigned FieldNo) {
4414 // We can bypass creating a target-independent constant expression and then
4415 // folding it back into a ConstantInt. This is just a compile-time
4416 // optimization.
4417 const StructLayout *SL = getDataLayout().getStructLayout(STy);
4418 assert(!SL->getSizeInBits().isScalable() &&
4419 "Cannot get offset for structure containing scalable vector types");
4420 return getConstant(IntTy, SL->getElementOffset(FieldNo));
4421}
4422
4424 // Don't attempt to do anything other than create a SCEVUnknown object
4425 // here. createSCEV only calls getUnknown after checking for all other
4426 // interesting possibilities, and any other code that calls getUnknown
4427 // is doing so in order to hide a value from SCEV canonicalization.
4428
4431 ID.AddPointer(V);
4433 if (SCEV *S = UniqueSCEVs.lookup(ID, Token)) {
4434 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4435 "Stale SCEVUnknown in uniquing map!");
4436 return S;
4437 }
4438 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4439 FirstUnknown);
4440 FirstUnknown = cast<SCEVUnknown>(S);
4441 UniqueSCEVs.insert(S, Token);
4442 S->computeAndSetCanonical(*this);
4443 return S;
4444}
4445
4446//===----------------------------------------------------------------------===//
4447// Basic SCEV Analysis and PHI Idiom Recognition Code
4448//
4449
4450/// Test if values of the given type are analyzable within the SCEV
4451/// framework. This primarily includes integer types, and it can optionally
4452/// include pointer types if the ScalarEvolution class has access to
4453/// target-specific information.
4455 // Integers and pointers are always SCEVable.
4456 return Ty->isIntOrPtrTy();
4457}
4458
4459/// Return the size in bits of the specified type, for which isSCEVable must
4460/// return true.
4462 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4463 if (Ty->isPointerTy())
4465 return getDataLayout().getTypeSizeInBits(Ty);
4466}
4467
4468/// Return a type with the same bitwidth as the given type and which represents
4469/// how SCEV will treat the given type, for which isSCEVable must return
4470/// true. For pointer types, this is the pointer index sized integer type.
4472 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4473
4474 if (Ty->isIntegerTy())
4475 return Ty;
4476
4477 // The only other support type is pointer.
4478 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4479 return getDataLayout().getIndexType(Ty);
4480}
4481
4483 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4484}
4485
4487 const SCEV *B) {
4488 /// For a valid use point to exist, the defining scope of one operand
4489 /// must dominate the other.
4490 bool PreciseA, PreciseB;
4491 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4492 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4493 if (!PreciseA || !PreciseB)
4494 // Can't tell.
4495 return false;
4496 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4497 DT.dominates(ScopeB, ScopeA);
4498}
4499
4501 return CouldNotCompute.get();
4502}
4503
4504bool ScalarEvolution::checkValidity(const SCEV *S) const {
4505 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4506 auto *SU = dyn_cast<SCEVUnknown>(S);
4507 return SU && SU->getValue() == nullptr;
4508 });
4509
4510 return !ContainsNulls;
4511}
4512
4514 HasRecMapType::iterator I = HasRecMap.find(S);
4515 if (I != HasRecMap.end())
4516 return I->second;
4517
4518 bool FoundAddRec =
4519 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4520 HasRecMap.insert({S, FoundAddRec});
4521 return FoundAddRec;
4522}
4523
4524/// Return the ValueOffsetPair set for \p S. \p S can be represented
4525/// by the value and offset from any ValueOffsetPair in the set.
4526ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4527 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4528 if (SI == ExprValueMap.end())
4529 return {};
4530 return SI->second.getArrayRef();
4531}
4532
4533/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4534/// cannot be used separately. eraseValueFromMap should be used to remove
4535/// V from ValueExprMap and ExprValueMap at the same time.
4536void ScalarEvolution::eraseValueFromMap(Value *V) {
4537 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4538 if (I != ValueExprMap.end()) {
4539 auto EVIt = ExprValueMap.find(I->second);
4540 bool Removed = EVIt->second.remove(V);
4541 (void) Removed;
4542 assert(Removed && "Value not in ExprValueMap?");
4543 ValueExprMap.erase(I);
4544 }
4545}
4546
4547void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4548 // A recursive query may have already computed the SCEV. It should be
4549 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4550 // inferred nowrap flags.
4551 auto It = ValueExprMap.find_as(V);
4552 if (It == ValueExprMap.end()) {
4553 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4554 ExprValueMap[S].insert(V);
4555 }
4556}
4557
4558/// Return an existing SCEV if it exists, otherwise analyze the expression and
4559/// create a new one.
4561 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4562
4563 if (const SCEV *S = getExistingSCEV(V))
4564 return S;
4565 return createSCEVIter(V);
4566}
4567
4569 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4570
4571 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4572 if (I != ValueExprMap.end()) {
4573 const SCEV *S = I->second;
4574 assert(checkValidity(S) &&
4575 "existing SCEV has not been properly invalidated");
4576 return S;
4577 }
4578 return nullptr;
4579}
4580
4581/// Return a SCEV corresponding to -V = -1*V
4583 SCEV::NoWrapFlags Flags) {
4584 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4585 return getConstant(
4586 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4587
4588 Type *Ty = V->getType();
4589 Ty = getEffectiveSCEVType(Ty);
4590 return getMulExpr(V, getMinusOne(Ty), Flags);
4591}
4592
4593/// If Expr computes ~A, return A else return nullptr
4594static const SCEV *MatchNotExpr(const SCEV *Expr) {
4595 const SCEV *MulOp;
4596 if (match(Expr, m_scev_Add(m_scev_AllOnes(),
4597 m_scev_Mul(m_scev_AllOnes(), m_SCEV(MulOp)))))
4598 return MulOp;
4599 return nullptr;
4600}
4601
4602/// Return a SCEV corresponding to ~V = -1-V
4604 assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4605
4606 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4607 return getConstant(
4608 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4609
4610 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4611 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4612 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4613 SmallVector<SCEVUse, 2> MatchedOperands;
4614 for (const SCEV *Operand : MME->operands()) {
4615 const SCEV *Matched = MatchNotExpr(Operand);
4616 if (!Matched)
4617 return (const SCEV *)nullptr;
4618 MatchedOperands.push_back(Matched);
4619 }
4620 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4621 MatchedOperands);
4622 };
4623 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4624 return Replaced;
4625 }
4626
4627 Type *Ty = V->getType();
4628 Ty = getEffectiveSCEVType(Ty);
4629 return getMinusSCEV(getMinusOne(Ty), V);
4630}
4631
4633 assert(P->getType()->isPointerTy());
4634
4635 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4636 // The base of an AddRec is the first operand.
4637 SmallVector<SCEVUse> Ops{AddRec->operands()};
4638 Ops[0] = removePointerBase(Ops[0]);
4639 // Don't try to transfer nowrap flags for now. We could in some cases
4640 // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4641 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagNone);
4642 }
4643 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4644 // The base of an Add is the pointer operand.
4645 SmallVector<SCEVUse> Ops{Add->operands()};
4646 SCEVUse *PtrOp = nullptr;
4647 for (SCEVUse &AddOp : Ops) {
4648 if (AddOp->getType()->isPointerTy()) {
4649 assert(!PtrOp && "Cannot have multiple pointer ops");
4650 PtrOp = &AddOp;
4651 }
4652 }
4653 *PtrOp = removePointerBase(*PtrOp);
4654 // Don't try to transfer nowrap flags for now. We could in some cases
4655 // (for example, if the pointer operand of the Add is a SCEVUnknown).
4656 return getAddExpr(Ops);
4657 }
4658 // Any other expression must be a pointer base.
4659 return getZero(P->getType());
4660}
4661
4663 SCEV::NoWrapFlags Flags,
4664 unsigned Depth) {
4665 // Fast path: X - X --> 0.
4666 if (LHS == RHS)
4667 return getZero(LHS->getType());
4668
4669 // If we subtract two pointers with different pointer bases, bail.
4670 // Eventually, we're going to add an assertion to getMulExpr that we
4671 // can't multiply by a pointer.
4672 if (RHS->getType()->isPointerTy()) {
4673 if (!LHS->getType()->isPointerTy() ||
4674 getPointerBase(LHS) != getPointerBase(RHS))
4675 return getCouldNotCompute();
4676 LHS = removePointerBase(LHS);
4677 RHS = removePointerBase(RHS);
4678 }
4679
4680 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4681 // makes it so that we cannot make much use of NUW.
4682 auto AddFlags = SCEV::FlagNone;
4683 const bool RHSIsNotMinSigned =
4685 if (hasFlags(Flags, SCEV::FlagNSW)) {
4686 // Let M be the minimum representable signed value. Then (-1)*RHS
4687 // signed-wraps if and only if RHS is M. That can happen even for
4688 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4689 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4690 // (-1)*RHS, we need to prove that RHS != M.
4691 //
4692 // If LHS is non-negative and we know that LHS - RHS does not
4693 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4694 // either by proving that RHS > M or that LHS >= 0.
4695 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4696 AddFlags = SCEV::FlagNSW;
4697 }
4698 }
4699
4700 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4701 // RHS is NSW and LHS >= 0.
4702 //
4703 // The difficulty here is that the NSW flag may have been proven
4704 // relative to a loop that is to be found in a recurrence in LHS and
4705 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4706 // larger scope than intended.
4707 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagNone;
4708
4709 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4710}
4711
4713 unsigned Depth) {
4714 Type *SrcTy = V->getType();
4715 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4716 "Cannot truncate or zero extend with non-integer arguments!");
4717 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4718 return V; // No conversion
4719 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4720 return getTruncateExpr(V, Ty, Depth);
4721 return getZeroExtendExpr(V, Ty, Depth);
4722}
4723
4725 unsigned Depth) {
4726 Type *SrcTy = V->getType();
4727 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4728 "Cannot truncate or zero extend with non-integer arguments!");
4729 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4730 return V; // No conversion
4731 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4732 return getTruncateExpr(V, Ty, Depth);
4733 return getSignExtendExpr(V, Ty, Depth);
4734}
4735
4737 Type *SrcTy = V->getType();
4738 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4739 "Cannot noop or zero extend with non-integer arguments!");
4741 "getNoopOrZeroExtend cannot truncate!");
4742 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4743 return V; // No conversion
4744 return getZeroExtendExpr(V, Ty);
4745}
4746
4748 Type *SrcTy = V->getType();
4749 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4750 "Cannot noop or sign extend with non-integer arguments!");
4752 "getNoopOrSignExtend cannot truncate!");
4753 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4754 return V; // No conversion
4755 return getSignExtendExpr(V, Ty);
4756}
4757
4759 Type *SrcTy = V->getType();
4760 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4761 "Cannot noop or any extend with non-integer arguments!");
4763 "getNoopOrAnyExtend cannot truncate!");
4764 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4765 return V; // No conversion
4766 return getAnyExtendExpr(V, Ty);
4767}
4768
4770 Type *SrcTy = V->getType();
4771 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4772 "Cannot truncate or noop with non-integer arguments!");
4774 "getTruncateOrNoop cannot extend!");
4775 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4776 return V; // No conversion
4777 return getTruncateExpr(V, Ty);
4778}
4779
4781 const SCEV *RHS) {
4782 const SCEV *PromotedLHS = LHS;
4783 const SCEV *PromotedRHS = RHS;
4784
4785 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4786 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4787 else
4788 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4789
4790 return getUMaxExpr(PromotedLHS, PromotedRHS);
4791}
4792
4794 const SCEV *RHS,
4795 bool Sequential) {
4796 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4797 return getUMinFromMismatchedTypes(Ops, Sequential);
4798}
4799
4800const SCEV *
4802 bool Sequential) {
4803 assert(!Ops.empty() && "At least one operand must be!");
4804 // Trivial case.
4805 if (Ops.size() == 1)
4806 return Ops[0];
4807
4808 // Find the max type first.
4809 Type *MaxType = nullptr;
4810 for (SCEVUse S : Ops)
4811 if (MaxType)
4812 MaxType = getWiderType(MaxType, S->getType());
4813 else
4814 MaxType = S->getType();
4815 assert(MaxType && "Failed to find maximum type!");
4816
4817 // Extend all ops to max type.
4818 SmallVector<SCEVUse, 2> PromotedOps;
4819 for (SCEVUse S : Ops)
4820 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4821
4822 // Generate umin.
4823 return getUMinExpr(PromotedOps, Sequential);
4824}
4825
4827 // A pointer operand may evaluate to a nonpointer expression, such as null.
4828 if (!V->getType()->isPointerTy())
4829 return V;
4830
4831 while (true) {
4832 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4833 V = AddRec->getStart();
4834 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4835 const SCEV *PtrOp = nullptr;
4836 for (const SCEV *AddOp : Add->operands()) {
4837 if (AddOp->getType()->isPointerTy()) {
4838 assert(!PtrOp && "Cannot have multiple pointer ops");
4839 PtrOp = AddOp;
4840 }
4841 }
4842 assert(PtrOp && "Must have pointer op");
4843 V = PtrOp;
4844 } else // Not something we can look further into.
4845 return V;
4846 }
4847}
4848
4849/// Push users of the given Instruction onto the given Worklist.
4853 // Push the def-use children onto the Worklist stack.
4854 for (User *U : I->users()) {
4855 auto *UserInsn = cast<Instruction>(U);
4856 if (Visited.insert(UserInsn).second)
4857 Worklist.push_back(UserInsn);
4858 }
4859}
4860
4861namespace {
4862
4863/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4864/// expression in case its Loop is L. If it is not L then
4865/// if IgnoreOtherLoops is true then use AddRec itself
4866/// otherwise rewrite cannot be done.
4867/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4868class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4869public:
4870 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4871 bool IgnoreOtherLoops = true) {
4872 SCEVInitRewriter Rewriter(L, SE);
4873 const SCEV *Result = Rewriter.visit(S);
4874 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4875 return SE.getCouldNotCompute();
4876 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4877 ? SE.getCouldNotCompute()
4878 : Result;
4879 }
4880
4881 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4882 if (!SE.isLoopInvariant(Expr, L))
4883 SeenLoopVariantSCEVUnknown = true;
4884 return Expr;
4885 }
4886
4887 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4888 // Only re-write AddRecExprs for this loop.
4889 if (Expr->getLoop() == L)
4890 return Expr->getStart();
4891 SeenOtherLoops = true;
4892 return Expr;
4893 }
4894
4895 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4896
4897 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4898
4899private:
4900 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4901 : SCEVRewriteVisitor(SE), L(L) {}
4902
4903 const Loop *L;
4904 bool SeenLoopVariantSCEVUnknown = false;
4905 bool SeenOtherLoops = false;
4906};
4907
4908/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4909/// increment expression in case its Loop is L. If it is not L then
4910/// use AddRec itself.
4911/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4912class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4913public:
4914 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4915 SCEVPostIncRewriter Rewriter(L, SE);
4916 const SCEV *Result = Rewriter.visit(S);
4917 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4918 ? SE.getCouldNotCompute()
4919 : Result;
4920 }
4921
4922 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4923 if (!SE.isLoopInvariant(Expr, L))
4924 SeenLoopVariantSCEVUnknown = true;
4925 return Expr;
4926 }
4927
4928 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4929 // Only re-write AddRecExprs for this loop.
4930 if (Expr->getLoop() == L)
4931 return Expr->getPostIncExpr(SE);
4932 SeenOtherLoops = true;
4933 return Expr;
4934 }
4935
4936 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4937
4938 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4939
4940private:
4941 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4942 : SCEVRewriteVisitor(SE), L(L) {}
4943
4944 const Loop *L;
4945 bool SeenLoopVariantSCEVUnknown = false;
4946 bool SeenOtherLoops = false;
4947};
4948
4949/// This class evaluates the compare condition by matching it against the
4950/// condition of loop latch. If there is a match we assume a true value
4951/// for the condition while building SCEV nodes.
4952class SCEVBackedgeConditionFolder
4953 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4954public:
4955 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4956 ScalarEvolution &SE) {
4957 bool IsPosBECond = false;
4958 Value *BECond = nullptr;
4959 if (BasicBlock *Latch = L->getLoopLatch()) {
4960 if (CondBrInst *BI = dyn_cast<CondBrInst>(Latch->getTerminator())) {
4961 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4962 "Both outgoing branches should not target same header!");
4963 BECond = BI->getCondition();
4964 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4965 } else {
4966 return S;
4967 }
4968 }
4969 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4970 return Rewriter.visit(S);
4971 }
4972
4973 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4974 const SCEV *Result = Expr;
4975 bool InvariantF = SE.isLoopInvariant(Expr, L);
4976
4977 if (!InvariantF) {
4979 switch (I->getOpcode()) {
4980 case Instruction::Select: {
4981 SelectInst *SI = cast<SelectInst>(I);
4982 std::optional<const SCEV *> Res =
4983 compareWithBackedgeCondition(SI->getCondition());
4984 if (Res) {
4985 bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
4986 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4987 }
4988 break;
4989 }
4990 default: {
4991 std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4992 if (Res)
4993 Result = *Res;
4994 break;
4995 }
4996 }
4997 }
4998 return Result;
4999 }
5000
5001private:
5002 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
5003 bool IsPosBECond, ScalarEvolution &SE)
5004 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
5005 IsPositiveBECond(IsPosBECond) {}
5006
5007 std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
5008
5009 const Loop *L;
5010 /// Loop back condition.
5011 Value *BackedgeCond = nullptr;
5012 /// Set to true if loop back is on positive branch condition.
5013 bool IsPositiveBECond;
5014};
5015
5016std::optional<const SCEV *>
5017SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
5018
5019 // If value matches the backedge condition for loop latch,
5020 // then return a constant evolution node based on loopback
5021 // branch taken.
5022 if (BackedgeCond == IC)
5023 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
5025 return std::nullopt;
5026}
5027
5028class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
5029public:
5030 static const SCEV *rewrite(const SCEV *S, const Loop *L,
5031 ScalarEvolution &SE) {
5032 SCEVShiftRewriter Rewriter(L, SE);
5033 const SCEV *Result = Rewriter.visit(S);
5034 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
5035 }
5036
5037 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5038 // Only allow AddRecExprs for this loop.
5039 if (!SE.isLoopInvariant(Expr, L))
5040 Valid = false;
5041 return Expr;
5042 }
5043
5044 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5045 if (Expr->getLoop() == L && Expr->isAffine())
5046 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
5047 Valid = false;
5048 return Expr;
5049 }
5050
5051 bool isValid() { return Valid; }
5052
5053private:
5054 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
5055 : SCEVRewriteVisitor(SE), L(L) {}
5056
5057 const Loop *L;
5058 bool Valid = true;
5059};
5060
5061} // end anonymous namespace
5062
5063void ScalarEvolution::inferNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
5064 if (!AR->isAffine())
5065 return;
5066
5067 // Force computation of ranges, which will also perform range-based flag
5068 // inference.
5069 if (!AR->hasNoSignedWrap())
5070 (void)getSignedRange(AR);
5071
5072 if (!AR->hasNoUnsignedWrap())
5073 (void)getUnsignedRange(AR);
5074
5075 if (!AR->hasNoSelfWrap()) {
5076 const SCEV *BECount = getConstantMaxBackedgeTakenCount(AR->getLoop());
5077 if (const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(BECount)) {
5078 ConstantRange StepCR = getSignedRange(AR->getStepRecurrence(*this));
5079 const APInt &BECountAP = BECountMax->getAPInt();
5080 unsigned NoOverflowBitWidth =
5081 BECountAP.getActiveBits() + StepCR.getMinSignedBits();
5082 if (NoOverflowBitWidth <= getTypeSizeInBits(AR->getType()))
5083 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
5084 }
5085 }
5086}
5087
5089ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5091
5092 if (AR->hasNoSignedWrap())
5093 return Result;
5094
5095 if (!AR->isAffine())
5096 return Result;
5097
5098 // This function can be expensive, only try to prove NSW once per AddRec.
5099 if (!SignedWrapViaInductionTried.insert(AR).second)
5100 return Result;
5101
5102 const SCEV *Step = AR->getStepRecurrence(*this);
5103 const Loop *L = AR->getLoop();
5104
5105 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5106 // Note that this serves two purposes: It filters out loops that are
5107 // simply not analyzable, and it covers the case where this code is
5108 // being called from within backedge-taken count analysis, such that
5109 // attempting to ask for the backedge-taken count would likely result
5110 // in infinite recursion. In the later case, the analysis code will
5111 // cope with a conservative value, and it will take care to purge
5112 // that value once it has finished.
5113 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5114
5115 // Normally, in the cases we can prove no-overflow via a
5116 // backedge guarding condition, we can also compute a backedge
5117 // taken count for the loop. The exceptions are assumptions and
5118 // guards present in the loop -- SCEV is not great at exploiting
5119 // these to compute max backedge taken counts, but can still use
5120 // these to prove lack of overflow. Use this fact to avoid
5121 // doing extra work that may not pay off.
5122
5123 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5124 AC.assumptions().empty())
5125 return Result;
5126
5127 // If the backedge is guarded by a comparison with the pre-inc value the
5128 // addrec is safe. Also, if the entry is guarded by a comparison with the
5129 // start value and the backedge is guarded by a comparison with the post-inc
5130 // value, the addrec is safe.
5132 const SCEV *OverflowLimit =
5133 getSignedOverflowLimitForStep(Step, &Pred, this);
5134 if (OverflowLimit &&
5135 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5136 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
5137 Result = setFlags(Result, SCEV::FlagNSW);
5138 }
5139 return Result;
5140}
5142ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5144
5145 if (AR->hasNoUnsignedWrap())
5146 return Result;
5147
5148 if (!AR->isAffine())
5149 return Result;
5150
5151 // This function can be expensive, only try to prove NUW once per AddRec.
5152 if (!UnsignedWrapViaInductionTried.insert(AR).second)
5153 return Result;
5154
5155 const SCEV *Step = AR->getStepRecurrence(*this);
5156 const Loop *L = AR->getLoop();
5157
5158 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5159 // Note that this serves two purposes: It filters out loops that are
5160 // simply not analyzable, and it covers the case where this code is
5161 // being called from within backedge-taken count analysis, such that
5162 // attempting to ask for the backedge-taken count would likely result
5163 // in infinite recursion. In the later case, the analysis code will
5164 // cope with a conservative value, and it will take care to purge
5165 // that value once it has finished.
5166 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5167
5168 // Normally, in the cases we can prove no-overflow via a
5169 // backedge guarding condition, we can also compute a backedge
5170 // taken count for the loop. The exceptions are assumptions and
5171 // guards present in the loop -- SCEV is not great at exploiting
5172 // these to compute max backedge taken counts, but can still use
5173 // these to prove lack of overflow. Use this fact to avoid
5174 // doing extra work that may not pay off.
5175
5176 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5177 AC.assumptions().empty())
5178 return Result;
5179
5180 // If the backedge is guarded by a comparison with the pre-inc value the
5181 // addrec is safe. Also, if the entry is guarded by a comparison with the
5182 // start value and the backedge is guarded by a comparison with the post-inc
5183 // value, the addrec is safe.
5184 if (isKnownPositive(Step)) {
5186 const SCEV *OverflowLimit =
5187 getUnsignedOverflowLimitForStep(Step, &Pred, this);
5188 if (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5189 isKnownOnEveryIteration(Pred, AR, OverflowLimit))
5190 Result = setFlags(Result, SCEV::FlagNUW);
5191 }
5192 return Result;
5193}
5194
5195namespace {
5196
5197/// Represents an abstract binary operation. This may exist as a
5198/// normal instruction or constant expression, or may have been
5199/// derived from an expression tree.
5200struct BinaryOp {
5201 unsigned Opcode;
5202 Value *LHS;
5203 Value *RHS;
5204 bool IsNSW = false;
5205 bool IsNUW = false;
5206
5207 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5208 /// constant expression.
5209 Operator *Op = nullptr;
5210
5211 explicit BinaryOp(Operator *Op)
5212 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5213 Op(Op) {
5214 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5215 IsNSW = OBO->hasNoSignedWrap();
5216 IsNUW = OBO->hasNoUnsignedWrap();
5217 }
5218 }
5219
5220 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5221 bool IsNUW = false)
5222 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5223};
5224
5225} // end anonymous namespace
5226
5227/// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
5228static std::optional<BinaryOp> MatchBinaryOp(Value *V, const DataLayout &DL,
5229 AssumptionCache &AC,
5230 const DominatorTree &DT,
5231 const Instruction *CxtI) {
5232 auto *Op = dyn_cast<Operator>(V);
5233 if (!Op)
5234 return std::nullopt;
5235
5236 // Implementation detail: all the cleverness here should happen without
5237 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5238 // SCEV expressions when possible, and we should not break that.
5239
5240 switch (Op->getOpcode()) {
5241 case Instruction::Add:
5242 case Instruction::Sub:
5243 case Instruction::Mul:
5244 case Instruction::UDiv:
5245 case Instruction::URem:
5246 case Instruction::And:
5247 case Instruction::AShr:
5248 case Instruction::Shl:
5249 return BinaryOp(Op);
5250
5251 case Instruction::Or: {
5252 // Convert or disjoint into add nuw nsw.
5253 if (cast<PossiblyDisjointInst>(Op)->isDisjoint()) {
5254 BinaryOp BinOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
5255 /*IsNSW=*/true, /*IsNUW=*/true);
5256 // Keep the reference to the original instruction so that we can later
5257 // check whether it can produce poison value or not.
5258 BinOp.Op = Op;
5259 return BinOp;
5260 }
5261 return BinaryOp(Op);
5262 }
5263
5264 case Instruction::Xor:
5265 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5266 // If the RHS of the xor is a signmask, then this is just an add.
5267 // Instcombine turns add of signmask into xor as a strength reduction step.
5268 if (RHSC->getValue().isSignMask())
5269 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5270 // Binary `xor` is a bit-wise `add`.
5271 if (V->getType()->isIntegerTy(1))
5272 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5273 return BinaryOp(Op);
5274
5275 case Instruction::LShr:
5276 // Turn logical shift right of a constant into a unsigned divide.
5277 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5278 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5279
5280 // If the shift count is not less than the bitwidth, the result of
5281 // the shift is undefined. Don't try to analyze it, because the
5282 // resolution chosen here may differ from the resolution chosen in
5283 // other parts of the compiler.
5284 if (SA->getValue().ult(BitWidth)) {
5285 Constant *X =
5286 ConstantInt::get(SA->getContext(),
5287 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5288 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5289 }
5290 }
5291 return BinaryOp(Op);
5292
5293 case Instruction::ExtractValue: {
5294 auto *EVI = cast<ExtractValueInst>(Op);
5295 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5296 break;
5297
5298 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5299 if (!WO)
5300 break;
5301
5302 Instruction::BinaryOps BinOp = WO->getBinaryOp();
5303 bool Signed = WO->isSigned();
5304 // TODO: Should add nuw/nsw flags for mul as well.
5305 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5306 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5307
5308 // Now that we know that all uses of the arithmetic-result component of
5309 // CI are guarded by the overflow check, we can go ahead and pretend
5310 // that the arithmetic is non-overflowing.
5311 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5312 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5313 }
5314
5315 default:
5316 break;
5317 }
5318
5319 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5320 // semantics as a Sub, return a binary sub expression.
5321 if (auto *II = dyn_cast<IntrinsicInst>(V))
5322 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5323 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5324
5325 return std::nullopt;
5326}
5327
5328/// Helper function to createAddRecFromPHIWithCasts. We have a phi
5329/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5330/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5331/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5332/// follows one of the following patterns:
5333/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5334/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5335/// If the SCEV expression of \p Op conforms with one of the expected patterns
5336/// we return the type of the truncation operation, and indicate whether the
5337/// truncated type should be treated as signed/unsigned by setting
5338/// \p Signed to true/false, respectively.
5339static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5340 bool &Signed, ScalarEvolution &SE) {
5341 // The case where Op == SymbolicPHI (that is, with no type conversions on
5342 // the way) is handled by the regular add recurrence creating logic and
5343 // would have already been triggered in createAddRecForPHI. Reaching it here
5344 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5345 // because one of the other operands of the SCEVAddExpr updating this PHI is
5346 // not invariant).
5347 //
5348 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5349 // this case predicates that allow us to prove that Op == SymbolicPHI will
5350 // be added.
5351 if (Op == SymbolicPHI)
5352 return nullptr;
5353
5354 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5355 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5356 if (SourceBits != NewBits)
5357 return nullptr;
5358
5359 if (match(Op, m_scev_SExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5360 Signed = true;
5361 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5362 }
5363 if (match(Op, m_scev_ZExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5364 Signed = false;
5365 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5366 }
5367 return nullptr;
5368}
5369
5370static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5371 if (!PN->getType()->isIntegerTy())
5372 return nullptr;
5373 const Loop *L = LI.getLoopFor(PN->getParent());
5374 if (!L || L->getHeader() != PN->getParent())
5375 return nullptr;
5376 return L;
5377}
5378
5379// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5380// computation that updates the phi follows the following pattern:
5381// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5382// which correspond to a phi->trunc->sext/zext->add->phi update chain.
5383// If so, try to see if it can be rewritten as an AddRecExpr under some
5384// Predicates. If successful, return them as a pair. Also cache the results
5385// of the analysis.
5386//
5387// Example usage scenario:
5388// Say the Rewriter is called for the following SCEV:
5389// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5390// where:
5391// %X = phi i64 (%Start, %BEValue)
5392// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5393// and call this function with %SymbolicPHI = %X.
5394//
5395// The analysis will find that the value coming around the backedge has
5396// the following SCEV:
5397// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5398// Upon concluding that this matches the desired pattern, the function
5399// will return the pair {NewAddRec, SmallPredsVec} where:
5400// NewAddRec = {%Start,+,%Step}
5401// SmallPredsVec = {P1, P2, P3} as follows:
5402// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5403// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5404// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5405// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5406// under the predicates {P1,P2,P3}.
5407// This predicated rewrite will be cached in PredicatedSCEVRewrites:
5408// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5409//
5410// TODO's:
5411//
5412// 1) Extend the Induction descriptor to also support inductions that involve
5413// casts: When needed (namely, when we are called in the context of the
5414// vectorizer induction analysis), a Set of cast instructions will be
5415// populated by this method, and provided back to isInductionPHI. This is
5416// needed to allow the vectorizer to properly record them to be ignored by
5417// the cost model and to avoid vectorizing them (otherwise these casts,
5418// which are redundant under the runtime overflow checks, will be
5419// vectorized, which can be costly).
5420//
5421// 2) Support additional induction/PHISCEV patterns: We also want to support
5422// inductions where the sext-trunc / zext-trunc operations (partly) occur
5423// after the induction update operation (the induction increment):
5424//
5425// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5426// which correspond to a phi->add->trunc->sext/zext->phi update chain.
5427//
5428// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5429// which correspond to a phi->trunc->add->sext/zext->phi update chain.
5430//
5431// 3) Outline common code with createAddRecFromPHI to avoid duplication.
5432std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5433ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5435
5436 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5437 // return an AddRec expression under some predicate.
5438
5439 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5440 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5441 assert(L && "Expecting an integer loop header phi");
5442
5443 // The loop may have multiple entrances or multiple exits; we can analyze
5444 // this phi as an addrec if it has a unique entry value and a unique
5445 // backedge value.
5446 Value *BEValueV = nullptr, *StartValueV = nullptr;
5447 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5448 Value *V = PN->getIncomingValue(i);
5449 if (L->contains(PN->getIncomingBlock(i))) {
5450 if (!BEValueV) {
5451 BEValueV = V;
5452 } else if (BEValueV != V) {
5453 BEValueV = nullptr;
5454 break;
5455 }
5456 } else if (!StartValueV) {
5457 StartValueV = V;
5458 } else if (StartValueV != V) {
5459 StartValueV = nullptr;
5460 break;
5461 }
5462 }
5463 if (!BEValueV || !StartValueV)
5464 return std::nullopt;
5465
5466 const SCEV *BEValue = getSCEV(BEValueV);
5467
5468 // If the value coming around the backedge is an add with the symbolic
5469 // value we just inserted, possibly with casts that we can ignore under
5470 // an appropriate runtime guard, then we found a simple induction variable!
5471 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5472 if (!Add)
5473 return std::nullopt;
5474
5475 // If there is a single occurrence of the symbolic value, possibly
5476 // casted, replace it with a recurrence.
5477 unsigned FoundIndex = Add->getNumOperands();
5478 Type *TruncTy = nullptr;
5479 bool Signed;
5480 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5481 if ((TruncTy =
5482 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5483 if (FoundIndex == e) {
5484 FoundIndex = i;
5485 break;
5486 }
5487
5488 if (FoundIndex == Add->getNumOperands())
5489 return std::nullopt;
5490
5491 // Create an add with everything but the specified operand.
5493 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5494 if (i != FoundIndex)
5495 Ops.push_back(Add->getOperand(i));
5496 const SCEV *Accum = getAddExpr(Ops);
5497
5498 // The runtime checks will not be valid if the step amount is
5499 // varying inside the loop.
5500 if (!isLoopInvariant(Accum, L))
5501 return std::nullopt;
5502
5503 // *** Part2: Create the predicates
5504
5505 // Analysis was successful: we have a phi-with-cast pattern for which we
5506 // can return an AddRec expression under the following predicates:
5507 //
5508 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5509 // fits within the truncated type (does not overflow) for i = 0 to n-1.
5510 // P2: An Equal predicate that guarantees that
5511 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5512 // P3: An Equal predicate that guarantees that
5513 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5514 //
5515 // As we next prove, the above predicates guarantee that:
5516 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5517 //
5518 //
5519 // More formally, we want to prove that:
5520 // Expr(i+1) = Start + (i+1) * Accum
5521 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5522 //
5523 // Given that:
5524 // 1) Expr(0) = Start
5525 // 2) Expr(1) = Start + Accum
5526 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5527 // 3) Induction hypothesis (step i):
5528 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5529 //
5530 // Proof:
5531 // Expr(i+1) =
5532 // = Start + (i+1)*Accum
5533 // = (Start + i*Accum) + Accum
5534 // = Expr(i) + Accum
5535 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5536 // :: from step i
5537 //
5538 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5539 //
5540 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5541 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
5542 // + Accum :: from P3
5543 //
5544 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5545 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5546 //
5547 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5548 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5549 //
5550 // By induction, the same applies to all iterations 1<=i<n:
5551 //
5552
5553 // Create a truncated addrec for which we will add a no overflow check (P1).
5554 const SCEV *StartVal = getSCEV(StartValueV);
5555 const SCEV *PHISCEV =
5556 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5557 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagNone);
5558
5559 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5560 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5561 // will be constant.
5562 //
5563 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5564 // add P1.
5565 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5569 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5570 Predicates.push_back(AddRecPred);
5571 }
5572
5573 // Create the Equal Predicates P2,P3:
5574
5575 // It is possible that the predicates P2 and/or P3 are computable at
5576 // compile time due to StartVal and/or Accum being constants.
5577 // If either one is, then we can check that now and escape if either P2
5578 // or P3 is false.
5579
5580 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5581 // for each of StartVal and Accum
5582 auto getExtendedExpr = [&](const SCEV *Expr,
5583 bool CreateSignExtend) -> const SCEV * {
5584 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5585 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5586 const SCEV *ExtendedExpr =
5587 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5588 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5589 return ExtendedExpr;
5590 };
5591
5592 // Given:
5593 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5594 // = getExtendedExpr(Expr)
5595 // Determine whether the predicate P: Expr == ExtendedExpr
5596 // is known to be false at compile time
5597 auto PredIsKnownFalse = [&](const SCEV *Expr,
5598 const SCEV *ExtendedExpr) -> bool {
5599 return Expr != ExtendedExpr &&
5600 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5601 };
5602
5603 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5604 if (PredIsKnownFalse(StartVal, StartExtended)) {
5605 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5606 return std::nullopt;
5607 }
5608
5609 // The Step is always Signed (because the overflow checks are either
5610 // NSSW or NUSW)
5611 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5612 if (PredIsKnownFalse(Accum, AccumExtended)) {
5613 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5614 return std::nullopt;
5615 }
5616
5617 auto AppendPredicate = [&](const SCEV *Expr,
5618 const SCEV *ExtendedExpr) -> void {
5619 if (Expr != ExtendedExpr &&
5620 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5621 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5622 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5623 Predicates.push_back(Pred);
5624 }
5625 };
5626
5627 AppendPredicate(StartVal, StartExtended);
5628 AppendPredicate(Accum, AccumExtended);
5629
5630 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5631 // which the casts had been folded away. The caller can rewrite SymbolicPHI
5632 // into NewAR if it will also add the runtime overflow checks specified in
5633 // Predicates.
5634 const SCEV *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagNone);
5635
5636 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5637 std::make_pair(NewAR, Predicates);
5638 // Remember the result of the analysis for this SCEV at this locayyytion.
5639 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5640 return PredRewrite;
5641}
5642
5643std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5645 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5646 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5647 if (!L)
5648 return std::nullopt;
5649
5650 // Check to see if we already analyzed this PHI.
5651 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5652 if (I != PredicatedSCEVRewrites.end()) {
5653 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5654 I->second;
5655 // Analysis was done before and failed to create an AddRec:
5656 if (Rewrite.first == SymbolicPHI)
5657 return std::nullopt;
5658 // Analysis was done before and succeeded to create an AddRec under
5659 // a predicate:
5660 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5661 assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5662 return Rewrite;
5663 }
5664
5665 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5666 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5667
5668 // Record in the cache that the analysis failed
5669 if (!Rewrite) {
5671 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5672 return std::nullopt;
5673 }
5674
5675 return Rewrite;
5676}
5677
5678// FIXME: This utility is currently required because the Rewriter currently
5679// does not rewrite this expression:
5680// {0, +, (sext ix (trunc iy to ix) to iy)}
5681// into {0, +, %step},
5682// even when the following Equal predicate exists:
5683// "%step == (sext ix (trunc iy to ix) to iy)".
5685 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2,
5686 ArrayRef<const SCEVPredicate *> NoWrapPreds) const {
5687 if (AR1 == AR2)
5688 return true;
5689
5690 SCEVUnionPredicate NoWrapUnionPred(NoWrapPreds, SE);
5691 SCEVUnionPredicate AllPreds = Preds->getUnionWith(&NoWrapUnionPred, SE);
5692 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5693 if (Expr1 != Expr2 &&
5694 !AllPreds.implies(SE.getEqualPredicate(Expr1, Expr2), SE) &&
5695 !AllPreds.implies(SE.getEqualPredicate(Expr2, Expr1), SE))
5696 return false;
5697 return true;
5698 };
5699
5700 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5701 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5702 return false;
5703 return true;
5704}
5705
5706static SCEV::NoWrapFlags
5709 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
5710 // If the increment has any nowrap flags, then we know the address
5711 // space cannot be wrapped around.
5712 if (NW != GEPNoWrapFlags::none())
5714 // If the GEP is nuw or nusw with non-negative offset, we know that
5715 // no unsigned wrap occurs. We cannot set the nsw flag as only the
5716 // offset is treated as signed, while the base is unsigned.
5717 if (NW.hasNoUnsignedWrap() ||
5718 (NW.hasNoUnsignedSignedWrap() && SE.isKnownNonNegative(Accum)))
5720
5721 return Flags;
5722}
5723
5724/// A helper function for createAddRecFromPHI to handle simple cases.
5725///
5726/// This function tries to find an AddRec expression for the simplest (yet most
5727/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5728/// If it fails, createAddRecFromPHI will use a more general, but slow,
5729/// technique for finding the AddRec expression.
5730const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5731 Value *BEValueV,
5732 Value *StartValueV) {
5733 const Loop *L = LI.getLoopFor(PN->getParent());
5734 assert(L && L->getHeader() == PN->getParent());
5735 assert(BEValueV && StartValueV);
5736
5737 const SCEV *Accum = nullptr;
5739 if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
5740 if (BO->Opcode != Instruction::Add)
5741 return nullptr;
5742
5743 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5744 Accum = getSCEV(BO->RHS);
5745 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5746 Accum = getSCEV(BO->LHS);
5747
5748 if (!Accum)
5749 return nullptr;
5750
5751 if (BO->IsNUW)
5752 Flags = setFlags(Flags, SCEV::FlagNUW);
5753 if (BO->IsNSW)
5754 Flags = setFlags(Flags, SCEV::FlagNSW);
5755 } else {
5756 // Handle pointer induction variable: PN = PHI(Start, gep PN,
5757 // LoopInvariant).
5758 auto *GEP = dyn_cast<GEPOperator>(BEValueV);
5759 if (!GEP || GEP->getPointerOperand() != PN || GEP->getNumIndices() != 1)
5760 return nullptr;
5761 Value *Idx = *GEP->idx_begin();
5762 if (!L->isLoopInvariant(Idx))
5763 return nullptr;
5764
5765 Type *IntIdxTy = getEffectiveSCEVType(GEP->getType());
5766 Accum = getMulExpr(getTruncateOrSignExtend(getSCEV(Idx), IntIdxTy),
5767 getSizeOfExpr(IntIdxTy, GEP->getSourceElementType()));
5768 Flags = getNoWrapFlagsForGEP(GEP, Accum, *this);
5769 }
5770
5771 const SCEV *StartVal = getSCEV(StartValueV);
5772 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5773 insertValueToMap(PN, PHISCEV);
5774
5775 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5776 inferNoWrapViaConstantRanges(AR);
5777
5778 // We can add Flags to the post-inc expression only if we
5779 // know that it is *undefined behavior* for BEValueV to
5780 // overflow.
5781 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5782 assert(isLoopInvariant(Accum, L) &&
5783 "Accum is defined outside L, but is not invariant?");
5784 if (isAddRecNeverPoison(BEInst, L))
5785 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5786 }
5787
5788 return PHISCEV;
5789}
5790
5791const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5792 const Loop *L = LI.getLoopFor(PN->getParent());
5793 if (!L || L->getHeader() != PN->getParent())
5794 return nullptr;
5795
5796 // The loop may have multiple entrances or multiple exits; we can analyze
5797 // this phi as an addrec if it has a unique entry value and a unique
5798 // backedge value.
5799 Value *BEValueV = nullptr, *StartValueV = nullptr;
5800 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5801 Value *V = PN->getIncomingValue(i);
5802 if (L->contains(PN->getIncomingBlock(i))) {
5803 if (!BEValueV) {
5804 BEValueV = V;
5805 } else if (BEValueV != V) {
5806 BEValueV = nullptr;
5807 break;
5808 }
5809 } else if (!StartValueV) {
5810 StartValueV = V;
5811 } else if (StartValueV != V) {
5812 StartValueV = nullptr;
5813 break;
5814 }
5815 }
5816 if (!BEValueV || !StartValueV)
5817 return nullptr;
5818
5819 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5820 "PHI node already processed?");
5821
5822 // First, try to find AddRec expression without creating a fictituos symbolic
5823 // value for PN.
5824 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5825 return S;
5826
5827 // Handle PHI node value symbolically.
5828 const SCEV *SymbolicName = getUnknown(PN);
5829 insertValueToMap(PN, SymbolicName);
5830
5831 // Using this symbolic name for the PHI, analyze the value coming around
5832 // the back-edge.
5833 const SCEV *BEValue = getSCEV(BEValueV);
5834
5835 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5836 // has a special value for the first iteration of the loop.
5837
5838 // If the value coming around the backedge is an add with the symbolic
5839 // value we just inserted, then we found a simple induction variable!
5840 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5841 // If there is a single occurrence of the symbolic value, replace it
5842 // with a recurrence.
5843 unsigned FoundIndex = Add->getNumOperands();
5844 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5845 if (Add->getOperand(i) == SymbolicName)
5846 if (FoundIndex == e) {
5847 FoundIndex = i;
5848 break;
5849 }
5850
5851 if (FoundIndex != Add->getNumOperands()) {
5852 // Create an add with everything but the specified operand.
5854 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5855 if (i != FoundIndex)
5856 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5857 L, *this));
5858 const SCEV *Accum = getAddExpr(Ops);
5859
5860 // This is not a valid addrec if the step amount is varying each
5861 // loop iteration, but is not itself an addrec in this loop.
5862 if (isLoopInvariant(Accum, L) ||
5863 (isa<SCEVAddRecExpr>(Accum) &&
5864 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5866
5867 if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
5868 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5869 if (BO->IsNUW)
5870 Flags = setFlags(Flags, SCEV::FlagNUW);
5871 if (BO->IsNSW)
5872 Flags = setFlags(Flags, SCEV::FlagNSW);
5873 }
5874 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5875 if (GEP->getOperand(0) == PN)
5876 Flags = getNoWrapFlagsForGEP(GEP, Accum, *this);
5877
5878 // We cannot transfer nuw and nsw flags from subtraction
5879 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5880 // for instance.
5881 }
5882
5883 const SCEV *StartVal = getSCEV(StartValueV);
5884 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5885
5886 // Okay, for the entire analysis of this edge we assumed the PHI
5887 // to be symbolic. We now need to go back and purge all of the
5888 // entries for the scalars that use the symbolic expression.
5889 forgetMemoizedResults({SymbolicName});
5890 insertValueToMap(PN, PHISCEV);
5891
5892 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5893 inferNoWrapViaConstantRanges(AR);
5894
5895 // We can add Flags to the post-inc expression only if we
5896 // know that it is *undefined behavior* for BEValueV to
5897 // overflow.
5898 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5899 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5900 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5901
5902 return PHISCEV;
5903 }
5904 }
5905 } else {
5906 // Otherwise, this could be a loop like this:
5907 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5908 // In this case, j = {1,+,1} and BEValue is j.
5909 // Because the other in-value of i (0) fits the evolution of BEValue
5910 // i really is an addrec evolution.
5911 //
5912 // We can generalize this saying that i is the shifted value of BEValue
5913 // by one iteration:
5914 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5915
5916 // Do not allow refinement in rewriting of BEValue.
5917 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5918 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5919 if (Shifted != getCouldNotCompute() && Start != getCouldNotCompute() &&
5920 isGuaranteedNotToCauseUB(Shifted) && ::impliesPoison(Shifted, Start)) {
5921 const SCEV *StartVal = getSCEV(StartValueV);
5922 if (Start == StartVal) {
5923 // Okay, for the entire analysis of this edge we assumed the PHI
5924 // to be symbolic. We now need to go back and purge all of the
5925 // entries for the scalars that use the symbolic expression.
5926 forgetMemoizedResults({SymbolicName});
5927 insertValueToMap(PN, Shifted);
5928 return Shifted;
5929 }
5930 }
5931 }
5932
5933 // Remove the temporary PHI node SCEV that has been inserted while intending
5934 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5935 // as it will prevent later (possibly simpler) SCEV expressions to be added
5936 // to the ValueExprMap.
5937 eraseValueFromMap(PN);
5938
5939 return nullptr;
5940}
5941
5942// Try to match a control flow sequence that branches out at BI and merges back
5943// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5944// match.
5946 Value *&C, Value *&LHS, Value *&RHS) {
5947 C = BI->getCondition();
5948
5949 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5950 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5951
5952 Use &LeftUse = Merge->getOperandUse(0);
5953 Use &RightUse = Merge->getOperandUse(1);
5954
5955 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5956 LHS = LeftUse;
5957 RHS = RightUse;
5958 return true;
5959 }
5960
5961 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5962 LHS = RightUse;
5963 RHS = LeftUse;
5964 return true;
5965 }
5966
5967 return false;
5968}
5969
5971 Value *&Cond, Value *&LHS,
5972 Value *&RHS) {
5973 auto IsReachable =
5974 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5975 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5976 // Try to match
5977 //
5978 // br %cond, label %left, label %right
5979 // left:
5980 // br label %merge
5981 // right:
5982 // br label %merge
5983 // merge:
5984 // V = phi [ %x, %left ], [ %y, %right ]
5985 //
5986 // as "select %cond, %x, %y"
5987
5988 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5989 assert(IDom && "At least the entry block should dominate PN");
5990
5991 auto *BI = dyn_cast<CondBrInst>(IDom->getTerminator());
5992 return BI && BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS);
5993 }
5994 return false;
5995}
5996
5997const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5998 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5999 if (getOperandsForSelectLikePHI(DT, PN, Cond, LHS, RHS) &&
6002 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
6003
6004 return nullptr;
6005}
6006
6008 BinaryOperator *CommonInst = nullptr;
6009 // Check if instructions are identical.
6010 for (Value *Incoming : PN->incoming_values()) {
6011 auto *IncomingInst = dyn_cast<BinaryOperator>(Incoming);
6012 if (!IncomingInst)
6013 return nullptr;
6014 if (CommonInst) {
6015 if (!CommonInst->isIdenticalToWhenDefined(IncomingInst))
6016 return nullptr; // Not identical, give up
6017 } else {
6018 // Remember binary operator
6019 CommonInst = IncomingInst;
6020 }
6021 }
6022 return CommonInst;
6023}
6024
6025/// Returns SCEV for the first operand of a phi if all phi operands have
6026/// identical opcodes and operands
6027/// eg.
6028/// a: %add = %a + %b
6029/// br %c
6030/// b: %add1 = %a + %b
6031/// br %c
6032/// c: %phi = phi [%add, a], [%add1, b]
6033/// scev(%phi) => scev(%add)
6034const SCEV *
6035ScalarEvolution::createNodeForPHIWithIdenticalOperands(PHINode *PN) {
6036 BinaryOperator *CommonInst = getCommonInstForPHI(PN);
6037 if (!CommonInst)
6038 return nullptr;
6039
6040 // Check if SCEV exprs for instructions are identical.
6041 const SCEV *CommonSCEV = getSCEV(CommonInst);
6042 bool SCEVExprsIdentical =
6044 [this, CommonSCEV](Value *V) { return CommonSCEV == getSCEV(V); });
6045 return SCEVExprsIdentical ? CommonSCEV : nullptr;
6046}
6047
6048const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
6049 if (const SCEV *S = createAddRecFromPHI(PN))
6050 return S;
6051
6052 // We do not allow simplifying phi (undef, X) to X here, to avoid reusing the
6053 // phi node for X.
6054 if (Value *V = simplifyInstruction(
6055 PN, {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
6056 /*UseInstrInfo=*/true, /*CanUseUndef=*/false}))
6057 return getSCEV(V);
6058
6059 if (const SCEV *S = createNodeForPHIWithIdenticalOperands(PN))
6060 return S;
6061
6062 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
6063 return S;
6064
6065 // If it's not a loop phi, we can't handle it yet.
6066 return getUnknown(PN);
6067}
6068
6069bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
6070 SCEVTypes RootKind) {
6071 struct FindClosure {
6072 const SCEV *OperandToFind;
6073 const SCEVTypes RootKind; // Must be a sequential min/max expression.
6074 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
6075
6076 bool Found = false;
6077
6078 bool canRecurseInto(SCEVTypes Kind) const {
6079 // We can only recurse into the SCEV expression of the same effective type
6080 // as the type of our root SCEV expression, and into zero-extensions.
6081 return RootKind == Kind || NonSequentialRootKind == Kind ||
6082 scZeroExtend == Kind;
6083 };
6084
6085 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
6086 : OperandToFind(OperandToFind), RootKind(RootKind),
6087 NonSequentialRootKind(
6089 RootKind)) {}
6090
6091 bool follow(const SCEV *S) {
6092 Found = S == OperandToFind;
6093
6094 return !isDone() && canRecurseInto(S->getSCEVType());
6095 }
6096
6097 bool isDone() const { return Found; }
6098 };
6099
6100 FindClosure FC(OperandToFind, RootKind);
6101 visitAll(Root, FC);
6102 return FC.Found;
6103}
6104
6105std::optional<const SCEV *>
6106ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
6107 ICmpInst *Cond,
6108 Value *TrueVal,
6109 Value *FalseVal) {
6110 // Try to match some simple smax or umax patterns.
6111 auto *ICI = Cond;
6112
6113 Value *LHS = ICI->getOperand(0);
6114 Value *RHS = ICI->getOperand(1);
6115
6116 switch (ICI->getPredicate()) {
6117 case ICmpInst::ICMP_SLT:
6118 case ICmpInst::ICMP_SLE:
6119 case ICmpInst::ICMP_ULT:
6120 case ICmpInst::ICMP_ULE:
6121 std::swap(LHS, RHS);
6122 [[fallthrough]];
6123 case ICmpInst::ICMP_SGT:
6124 case ICmpInst::ICMP_SGE:
6125 case ICmpInst::ICMP_UGT:
6126 case ICmpInst::ICMP_UGE:
6127 // a > b ? a+x : b+x -> max(a, b)+x
6128 // a > b ? b+x : a+x -> min(a, b)+x
6130 bool Signed = ICI->isSigned();
6131 const SCEV *LA = getSCEV(TrueVal);
6132 const SCEV *RA = getSCEV(FalseVal);
6133 const SCEV *LS = getSCEV(LHS);
6134 const SCEV *RS = getSCEV(RHS);
6135 if (LA->getType()->isPointerTy()) {
6136 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6137 // Need to make sure we can't produce weird expressions involving
6138 // negated pointers.
6139 if (LA == LS && RA == RS)
6140 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6141 if (LA == RS && RA == LS)
6142 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6143 }
6144 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6145 if (Op->getType()->isPointerTy()) {
6148 return Op;
6149 }
6150 if (Signed)
6151 Op = getNoopOrSignExtend(Op, Ty);
6152 else
6153 Op = getNoopOrZeroExtend(Op, Ty);
6154 return Op;
6155 };
6156 LS = CoerceOperand(LS);
6157 RS = CoerceOperand(RS);
6159 break;
6160 const SCEV *LDiff = getMinusSCEV(LA, LS);
6161 const SCEV *RDiff = getMinusSCEV(RA, RS);
6162 if (LDiff == RDiff)
6163 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6164 LDiff);
6165 LDiff = getMinusSCEV(LA, RS);
6166 RDiff = getMinusSCEV(RA, LS);
6167 if (LDiff == RDiff)
6168 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6169 LDiff);
6170 }
6171 break;
6172 case ICmpInst::ICMP_NE:
6173 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
6174 std::swap(TrueVal, FalseVal);
6175 [[fallthrough]];
6176 case ICmpInst::ICMP_EQ:
6177 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
6180 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6181 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y
6182 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y
6183 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6184 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y
6185 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6186 return getAddExpr(getUMaxExpr(X, C), Y);
6187 }
6188 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
6189 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
6190 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
6191 // -> umin_seq(x, umin (..., umin_seq(...), ...))
6193 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6194 const SCEV *X = getSCEV(LHS);
6195 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6196 X = ZExt->getOperand();
6197 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6198 const SCEV *FalseValExpr = getSCEV(FalseVal);
6199 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6200 return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6201 /*Sequential=*/true);
6202 }
6203 }
6204 break;
6205 default:
6206 break;
6207 }
6208
6209 return std::nullopt;
6210}
6211
6212static std::optional<const SCEV *>
6214 const SCEV *TrueExpr, const SCEV *FalseExpr) {
6215 assert(CondExpr->getType()->isIntegerTy(1) &&
6216 TrueExpr->getType() == FalseExpr->getType() &&
6217 TrueExpr->getType()->isIntegerTy(1) &&
6218 "Unexpected operands of a select.");
6219
6220 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
6221 // --> C + (umin_seq cond, x - C)
6222 //
6223 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
6224 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6225 // --> C + (umin_seq ~cond, x - C)
6226
6227 // FIXME: while we can't legally model the case where both of the hands
6228 // are fully variable, we only require that the *difference* is constant.
6229 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6230 return std::nullopt;
6231
6232 const SCEV *X, *C;
6233 if (isa<SCEVConstant>(TrueExpr)) {
6234 CondExpr = SE->getNotSCEV(CondExpr);
6235 X = FalseExpr;
6236 C = TrueExpr;
6237 } else {
6238 X = TrueExpr;
6239 C = FalseExpr;
6240 }
6241 return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6242 /*Sequential=*/true));
6243}
6244
6245static std::optional<const SCEV *>
6247 Value *FalseVal) {
6248 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6249 return std::nullopt;
6250
6251 const auto *SECond = SE->getSCEV(Cond);
6252 const auto *SETrue = SE->getSCEV(TrueVal);
6253 const auto *SEFalse = SE->getSCEV(FalseVal);
6254 return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6255}
6256
6257const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6258 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6259 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6260 assert(TrueVal->getType() == FalseVal->getType() &&
6261 V->getType() == TrueVal->getType() &&
6262 "Types of select hands and of the result must match.");
6263
6264 // For now, only deal with i1-typed `select`s.
6265 if (!V->getType()->isIntegerTy(1))
6266 return getUnknown(V);
6267
6268 if (std::optional<const SCEV *> S =
6269 createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6270 return *S;
6271
6272 return getUnknown(V);
6273}
6274
6275const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6276 Value *TrueVal,
6277 Value *FalseVal) {
6278 // Handle "constant" branch or select. This can occur for instance when a
6279 // loop pass transforms an inner loop and moves on to process the outer loop.
6280 if (auto *CI = dyn_cast<ConstantInt>(Cond))
6281 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6282
6283 if (auto *I = dyn_cast<Instruction>(V)) {
6284 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6285 if (std::optional<const SCEV *> S =
6286 createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6287 TrueVal, FalseVal))
6288 return *S;
6289 }
6290 }
6291
6292 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6293}
6294
6295/// Expand GEP instructions into add and multiply operations. This allows them
6296/// to be analyzed by regular SCEV code.
6297const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6298 assert(GEP->getSourceElementType()->isSized() &&
6299 "GEP source element type must be sized");
6300
6301 SmallVector<SCEVUse, 4> IndexExprs;
6302 for (Value *Index : GEP->indices())
6303 IndexExprs.push_back(getSCEV(Index));
6304 return getGEPExpr(GEP, IndexExprs);
6305}
6306
6307APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S,
6308 const Instruction *CtxI) {
6310 auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6311 return TrailingZeros >= BitWidth
6313 : APInt::getOneBitSet(BitWidth, TrailingZeros);
6314 };
6315 auto GetGCDMultiple = [this, CtxI](const SCEVNAryExpr *N) {
6316 // The result is GCD of all operands results.
6317 APInt Res = getConstantMultiple(N->getOperand(0), CtxI);
6318 for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6320 Res, getConstantMultiple(N->getOperand(I), CtxI));
6321 return Res;
6322 };
6323
6324 switch (S->getSCEVType()) {
6325 case scConstant:
6326 return cast<SCEVConstant>(S)->getAPInt();
6327 case scPtrToAddr:
6328 return getConstantMultiple(cast<SCEVCastExpr>(S)->getOperand());
6329 case scUDivExpr:
6330 case scVScale:
6331 return APInt(BitWidth, 1);
6332 case scTruncate: {
6333 // Only multiples that are a power of 2 will hold after truncation.
6334 const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6335 uint32_t TZ = getMinTrailingZeros(T->getOperand(), CtxI);
6336 return GetShiftedByZeros(TZ);
6337 }
6338 case scZeroExtend: {
6339 const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(S);
6340 return getConstantMultiple(Z->getOperand(), CtxI).zext(BitWidth);
6341 }
6342 case scSignExtend: {
6343 // Only multiples that are a power of 2 will hold after sext.
6344 const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6345 uint32_t TZ = getMinTrailingZeros(E->getOperand(), CtxI);
6346 return GetShiftedByZeros(TZ);
6347 }
6348 case scMulExpr: {
6349 const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6350 if (M->hasNoUnsignedWrap()) {
6351 // The result is the product of all operand results.
6352 APInt Res = getConstantMultiple(M->getOperand(0), CtxI);
6353 for (const SCEV *Operand : M->operands().drop_front())
6354 Res = Res * getConstantMultiple(Operand, CtxI);
6355 return Res;
6356 }
6357
6358 // If there are no wrap guarentees, find the trailing zeros, which is the
6359 // sum of trailing zeros for all its operands.
6360 uint32_t TZ = 0;
6361 for (const SCEV *Operand : M->operands())
6362 TZ += getMinTrailingZeros(Operand, CtxI);
6363 return GetShiftedByZeros(TZ);
6364 }
6365 case scAddExpr:
6366 case scAddRecExpr: {
6367 const SCEVNAryExpr *N = cast<SCEVNAryExpr>(S);
6368 if (N->hasNoUnsignedWrap())
6369 return GetGCDMultiple(N);
6370 // Find the trailing bits, which is the minimum of its operands.
6371 uint32_t TZ = getMinTrailingZeros(N->getOperand(0), CtxI);
6372 for (const SCEV *Operand : N->operands().drop_front())
6373 TZ = std::min(TZ, getMinTrailingZeros(Operand, CtxI));
6374 return GetShiftedByZeros(TZ);
6375 }
6376 case scUMaxExpr:
6377 case scSMaxExpr:
6378 case scUMinExpr:
6379 case scSMinExpr:
6381 return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6382 case scUnknown: {
6383 // Ask ValueTracking for known bits. SCEVUnknown only become available at
6384 // the point their underlying IR instruction has been defined. If CtxI was
6385 // not provided, use:
6386 // * the first instruction in the entry block if it is an argument
6387 // * the instruction itself otherwise.
6388 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6389 if (!CtxI) {
6390 if (isa<Argument>(U->getValue()))
6391 CtxI = &*F.getEntryBlock().begin();
6392 else if (auto *I = dyn_cast<Instruction>(U->getValue()))
6393 CtxI = I;
6394 }
6395 unsigned Known =
6396 computeKnownBits(U->getValue(),
6397 SimplifyQuery(getDataLayout(), &DT, &AC, CtxI)
6398 .allowEphemerals(true))
6399 .countMinTrailingZeros();
6400 return GetShiftedByZeros(Known);
6401 }
6402 case scCouldNotCompute:
6403 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6404 }
6405 llvm_unreachable("Unknown SCEV kind!");
6406}
6407
6409 const Instruction *CtxI) {
6410 // Skip looking up and updating the cache if there is a context instruction,
6411 // as the result will only be valid in the specified context.
6412 if (CtxI)
6413 return getConstantMultipleImpl(S, CtxI);
6414
6415 auto I = ConstantMultipleCache.find(S);
6416 if (I != ConstantMultipleCache.end())
6417 return I->second;
6418
6419 APInt Result = getConstantMultipleImpl(S, CtxI);
6420 auto InsertPair = ConstantMultipleCache.insert({S, Result});
6421 assert(InsertPair.second && "Should insert a new key");
6422 return InsertPair.first->second;
6423}
6424
6426 APInt Multiple = getConstantMultiple(S);
6427 return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6428}
6429
6431 const Instruction *CtxI) {
6432 return std::min(getConstantMultiple(S, CtxI).countTrailingZeros(),
6433 (unsigned)getTypeSizeInBits(S->getType()));
6434}
6435
6436/// Helper method to assign a range to V from metadata present in the IR.
6437static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6439 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6440 return getConstantRangeFromMetadata(*MD);
6441 if (const auto *CB = dyn_cast<CallBase>(V))
6442 if (std::optional<ConstantRange> Range = CB->getRange())
6443 return Range;
6444 }
6445 if (auto *A = dyn_cast<Argument>(V))
6446 if (std::optional<ConstantRange> Range = A->getRange())
6447 return Range;
6448
6449 return std::nullopt;
6450}
6451
6453 SCEV::NoWrapFlags Flags) {
6454 if (AddRec->getNoWrapFlags(Flags) != Flags) {
6455 AddRec->setNoWrapFlags(Flags);
6456 UnsignedRanges.erase(AddRec);
6457 SignedRanges.erase(AddRec);
6458 ConstantMultipleCache.erase(AddRec);
6459 }
6460}
6461
6462ConstantRange ScalarEvolution::
6463getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6464 const DataLayout &DL = getDataLayout();
6465
6466 unsigned BitWidth = getTypeSizeInBits(U->getType());
6467 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6468
6469 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6470 // use information about the trip count to improve our available range. Note
6471 // that the trip count independent cases are already handled by known bits.
6472 // WARNING: The definition of recurrence used here is subtly different than
6473 // the one used by AddRec (and thus most of this file). Step is allowed to
6474 // be arbitrarily loop varying here, where AddRec allows only loop invariant
6475 // and other addrecs in the same loop (for non-affine addrecs). The code
6476 // below intentionally handles the case where step is not loop invariant.
6477 auto *P = dyn_cast<PHINode>(U->getValue());
6478 if (!P)
6479 return FullSet;
6480
6481 // Make sure that no Phi input comes from an unreachable block. Otherwise,
6482 // even the values that are not available in these blocks may come from them,
6483 // and this leads to false-positive recurrence test.
6484 for (auto *Pred : predecessors(P->getParent()))
6485 if (!DT.isReachableFromEntry(Pred))
6486 return FullSet;
6487
6488 BinaryOperator *BO;
6489 Value *Start, *Step;
6490 if (!matchSimpleRecurrence(P, BO, Start, Step))
6491 return FullSet;
6492
6493 // If we found a recurrence in reachable code, we must be in a loop. Note
6494 // that BO might be in some subloop of L, and that's completely okay.
6495 auto *L = LI.getLoopFor(P->getParent());
6496 assert(L && L->getHeader() == P->getParent());
6497 if (!L->contains(BO->getParent()))
6498 // NOTE: This bailout should be an assert instead. However, asserting
6499 // the condition here exposes a case where LoopFusion is querying SCEV
6500 // with malformed loop information during the midst of the transform.
6501 // There doesn't appear to be an obvious fix, so for the moment bailout
6502 // until the caller issue can be fixed. PR49566 tracks the bug.
6503 return FullSet;
6504
6505 // TODO: Extend to other opcodes such as mul, and div
6506 switch (BO->getOpcode()) {
6507 default:
6508 return FullSet;
6509 case Instruction::AShr:
6510 case Instruction::LShr:
6511 case Instruction::Shl:
6512 break;
6513 };
6514
6515 if (BO->getOperand(0) != P)
6516 // TODO: Handle the power function forms some day.
6517 return FullSet;
6518
6519 unsigned TC = getSmallConstantMaxTripCount(L);
6520 if (!TC || TC >= BitWidth)
6521 return FullSet;
6522
6523 auto KnownStart = computeKnownBits(Start, DL, &AC, nullptr, &DT);
6524 auto KnownStep = computeKnownBits(Step, DL, &AC, nullptr, &DT);
6525 assert(KnownStart.getBitWidth() == BitWidth &&
6526 KnownStep.getBitWidth() == BitWidth);
6527
6528 // Compute total shift amount, being careful of overflow and bitwidths.
6529 auto MaxShiftAmt = KnownStep.getMaxValue();
6530 APInt TCAP(BitWidth, TC-1);
6531 bool Overflow = false;
6532 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6533 if (Overflow)
6534 return FullSet;
6535
6536 switch (BO->getOpcode()) {
6537 default:
6538 llvm_unreachable("filtered out above");
6539 case Instruction::AShr: {
6540 // For each ashr, three cases:
6541 // shift = 0 => unchanged value
6542 // saturation => 0 or -1
6543 // other => a value closer to zero (of the same sign)
6544 // Thus, the end value is closer to zero than the start.
6545 auto KnownEnd = KnownBits::ashr(KnownStart,
6546 KnownBits::makeConstant(TotalShift));
6547 if (KnownStart.isNonNegative())
6548 // Analogous to lshr (simply not yet canonicalized)
6549 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6550 KnownStart.getMaxValue() + 1);
6551 if (KnownStart.isNegative())
6552 // End >=u Start && End <=s Start
6553 return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6554 KnownEnd.getMaxValue() + 1);
6555 break;
6556 }
6557 case Instruction::LShr: {
6558 // For each lshr, three cases:
6559 // shift = 0 => unchanged value
6560 // saturation => 0
6561 // other => a smaller positive number
6562 // Thus, the low end of the unsigned range is the last value produced.
6563 auto KnownEnd = KnownBits::lshr(KnownStart,
6564 KnownBits::makeConstant(TotalShift));
6565 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6566 KnownStart.getMaxValue() + 1);
6567 }
6568 case Instruction::Shl: {
6569 // Iff no bits are shifted out, value increases on every shift.
6570 auto KnownEnd = KnownBits::shl(KnownStart,
6571 KnownBits::makeConstant(TotalShift));
6572 if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6573 return ConstantRange(KnownStart.getMinValue(),
6574 KnownEnd.getMaxValue() + 1);
6575 break;
6576 }
6577 };
6578 return FullSet;
6579}
6580
6581// The goal of this function is to check if recursively visiting the operands
6582// of this PHI might lead to an infinite loop. If we do see such a loop,
6583// there's no good way to break it, so we avoid analyzing such cases.
6584//
6585// getRangeRef previously used a visited set to avoid infinite loops, but this
6586// caused other issues: the result was dependent on the order of getRangeRef
6587// calls, and the interaction with createSCEVIter could cause a stack overflow
6588// in some cases (see issue #148253).
6589//
6590// FIXME: The way this is implemented is overly conservative; this checks
6591// for a few obviously safe patterns, but anything that doesn't lead to
6592// recursion is fine.
6594 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6596 return true;
6597
6598 if (all_of(PHI->operands(),
6599 [&](Value *Operand) { return DT.dominates(Operand, PHI); }))
6600 return true;
6601
6602 return false;
6603}
6604
6605const ConstantRange &
6606ScalarEvolution::getRangeRefIter(const SCEV *S,
6607 ScalarEvolution::RangeSignHint SignHint) {
6608 DenseMap<const SCEV *, ConstantRange> &Cache =
6609 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6610 : SignedRanges;
6611 SmallVector<SCEVUse> WorkList;
6612 SmallPtrSet<const SCEV *, 8> Seen;
6613
6614 // Add Expr to the worklist, if Expr is either an N-ary expression or a
6615 // SCEVUnknown PHI node.
6616 auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6617 if (!Seen.insert(Expr).second)
6618 return;
6619 if (Cache.contains(Expr))
6620 return;
6621 switch (Expr->getSCEVType()) {
6622 case scUnknown:
6624 break;
6625 [[fallthrough]];
6626 case scConstant:
6627 case scVScale:
6628 case scTruncate:
6629 case scZeroExtend:
6630 case scSignExtend:
6631 case scPtrToAddr:
6632 case scAddExpr:
6633 case scMulExpr:
6634 case scUDivExpr:
6635 case scAddRecExpr:
6636 case scUMaxExpr:
6637 case scSMaxExpr:
6638 case scUMinExpr:
6639 case scSMinExpr:
6641 WorkList.push_back(Expr);
6642 break;
6643 case scCouldNotCompute:
6644 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6645 }
6646 };
6647 AddToWorklist(S);
6648
6649 // Build worklist by queuing operands of N-ary expressions and phi nodes.
6650 for (unsigned I = 0; I != WorkList.size(); ++I) {
6651 const SCEV *P = WorkList[I];
6652 auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6653 // If it is not a `SCEVUnknown`, just recurse into operands.
6654 if (!UnknownS) {
6655 for (const SCEV *Op : P->operands())
6656 AddToWorklist(Op);
6657 continue;
6658 }
6659 // `SCEVUnknown`'s require special treatment.
6660 if (PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6661 if (!RangeRefPHIAllowedOperands(DT, P))
6662 continue;
6663 for (auto &Op : reverse(P->operands()))
6664 AddToWorklist(getSCEV(Op));
6665 }
6666 }
6667
6668 if (!WorkList.empty()) {
6669 // Use getRangeRef to compute ranges for items in the worklist in reverse
6670 // order. This will force ranges for earlier operands to be computed before
6671 // their users in most cases.
6672 for (const SCEV *P : reverse(drop_begin(WorkList))) {
6673 getRangeRef(P, SignHint);
6674 }
6675 }
6676
6677 return getRangeRef(S, SignHint, 0);
6678}
6679
6680const APInt *ScalarEvolution::getConstantAPIntOrNull(const SCEV *S) {
6681 if (const auto *C = dyn_cast<SCEVConstant>(S))
6682 return &C->getAPInt();
6683 return nullptr;
6684}
6685
6686/// Determine the range for a particular SCEV. If SignHint is
6687/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6688/// with a "cleaner" unsigned (resp. signed) representation.
6689const ConstantRange &ScalarEvolution::getRangeRef(
6690 const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6691 DenseMap<const SCEV *, ConstantRange> &Cache =
6692 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6693 : SignedRanges;
6695 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6697
6698 // See if we've computed this range already.
6699 auto I = Cache.find(S);
6700 if (I != Cache.end())
6701 return I->second;
6702
6703 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6704 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6705
6706 // Switch to iteratively computing the range for S, if it is part of a deeply
6707 // nested expression.
6709 return getRangeRefIter(S, SignHint);
6710
6711 unsigned BitWidth = getTypeSizeInBits(S->getType());
6712 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6713 using OBO = OverflowingBinaryOperator;
6714
6715 // If the value has known zeros, the maximum value will have those known zeros
6716 // as well.
6717 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6718 APInt Multiple = getNonZeroConstantMultiple(S);
6719 APInt Remainder = APInt::getMaxValue(BitWidth).urem(Multiple);
6720 if (!Remainder.isZero())
6721 ConservativeResult =
6722 ConstantRange(APInt::getMinValue(BitWidth),
6723 APInt::getMaxValue(BitWidth) - Remainder + 1);
6724 }
6725 else {
6726 uint32_t TZ = getMinTrailingZeros(S);
6727 if (TZ != 0) {
6728 ConservativeResult = ConstantRange(
6730 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6731 }
6732 }
6733
6734 switch (S->getSCEVType()) {
6735 case scConstant:
6736 llvm_unreachable("Already handled above.");
6737 case scVScale:
6738 return setRange(S, SignHint, getVScaleRange(&F, BitWidth));
6739 case scTruncate: {
6740 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6741 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6742 return setRange(
6743 Trunc, SignHint,
6744 ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6745 }
6746 case scZeroExtend: {
6747 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6748 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6749 return setRange(
6750 ZExt, SignHint,
6751 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6752 }
6753 case scSignExtend: {
6754 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6755 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6756 return setRange(
6757 SExt, SignHint,
6758 ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6759 }
6760 case scPtrToAddr: {
6761 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6762 ConstantRange X = getRangeRef(Cast->getOperand(), SignHint, Depth + 1);
6763 return setRange(Cast, SignHint, X);
6764 }
6765 case scAddExpr: {
6766 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6767 // Check if this is a URem pattern: A - (A / B) * B, which is always < B.
6768 const SCEV *URemLHS = nullptr, *URemRHS = nullptr;
6769 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED &&
6770 match(S, m_scev_URem(m_SCEV(URemLHS), m_SCEV(URemRHS), *this))) {
6771 ConstantRange LHSRange = getRangeRef(URemLHS, SignHint, Depth + 1);
6772 ConstantRange RHSRange = getRangeRef(URemRHS, SignHint, Depth + 1);
6773 ConservativeResult =
6774 ConservativeResult.intersectWith(LHSRange.urem(RHSRange), RangeType);
6775 }
6776 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6777 unsigned WrapType = OBO::AnyWrap;
6778 if (Add->hasNoSignedWrap())
6779 WrapType |= OBO::NoSignedWrap;
6780 if (Add->hasNoUnsignedWrap())
6781 WrapType |= OBO::NoUnsignedWrap;
6782 for (const SCEV *Op : drop_begin(Add->operands()))
6783 X = X.addWithNoWrap(getRangeRef(Op, SignHint, Depth + 1), WrapType,
6784 RangeType);
6785 return setRange(Add, SignHint,
6786 ConservativeResult.intersectWith(X, RangeType));
6787 }
6788 case scMulExpr: {
6789 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6790 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6791 for (const SCEV *Op : drop_begin(Mul->operands()))
6792 X = X.multiply(getRangeRef(Op, SignHint, Depth + 1));
6793 return setRange(Mul, SignHint,
6794 ConservativeResult.intersectWith(X, RangeType));
6795 }
6796 case scUDivExpr: {
6797 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6798 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6799 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6800 return setRange(UDiv, SignHint,
6801 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6802 }
6803 case scAddRecExpr: {
6804 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6805 // If there's no unsigned wrap, the value will never be less than its
6806 // initial value.
6807 if (AddRec->hasNoUnsignedWrap()) {
6808 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6809 if (!UnsignedMinValue.isZero())
6810 ConservativeResult = ConservativeResult.intersectWith(
6811 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6812 }
6813
6814 // If there's no signed wrap, and all the operands except initial value have
6815 // the same sign or zero, the value won't ever be:
6816 // 1: smaller than initial value if operands are non negative,
6817 // 2: bigger than initial value if operands are non positive.
6818 // For both cases, value can not cross signed min/max boundary.
6819 if (AddRec->hasNoSignedWrap()) {
6820 bool AllNonNeg = true;
6821 bool AllNonPos = true;
6822 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6823 if (!isKnownNonNegative(AddRec->getOperand(i)))
6824 AllNonNeg = false;
6825 if (!isKnownNonPositive(AddRec->getOperand(i)))
6826 AllNonPos = false;
6827 }
6828 if (AllNonNeg)
6829 ConservativeResult = ConservativeResult.intersectWith(
6832 RangeType);
6833 else if (AllNonPos)
6834 ConservativeResult = ConservativeResult.intersectWith(
6836 getSignedRangeMax(AddRec->getStart()) +
6837 1),
6838 RangeType);
6839 }
6840
6841 // TODO: non-affine addrec
6842 if (AddRec->isAffine()) {
6843 const SCEV *MaxBEScev =
6845 if (!isa<SCEVCouldNotCompute>(MaxBEScev)) {
6846 APInt MaxBECount = cast<SCEVConstant>(MaxBEScev)->getAPInt();
6847
6848 // Adjust MaxBECount to the same bitwidth as AddRec. We can truncate if
6849 // MaxBECount's active bits are all <= AddRec's bit width.
6850 if (MaxBECount.getBitWidth() > BitWidth &&
6851 MaxBECount.getActiveBits() <= BitWidth)
6852 MaxBECount = MaxBECount.trunc(BitWidth);
6853 else if (MaxBECount.getBitWidth() < BitWidth)
6854 MaxBECount = MaxBECount.zext(BitWidth);
6855
6856 if (MaxBECount.getBitWidth() == BitWidth) {
6857 auto [RangeFromAffine, Flags] = getRangeForAffineAR(
6858 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6859 ConservativeResult =
6860 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6861 const_cast<SCEVAddRecExpr *>(AddRec)->setNoWrapFlags(Flags);
6862
6863 auto RangeFromFactoring = getRangeViaFactoring(
6864 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6865 ConservativeResult =
6866 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6867 }
6868 }
6869
6870 // Now try symbolic BE count and more powerful methods.
6872 const SCEV *SymbolicMaxBECount =
6874 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6875 getTypeSizeInBits(MaxBEScev->getType()) <= BitWidth &&
6876 AddRec->hasNoSelfWrap()) {
6877 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6878 AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6879 ConservativeResult =
6880 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6881 }
6882 }
6883 }
6884
6885 return setRange(AddRec, SignHint, std::move(ConservativeResult));
6886 }
6887 case scUMaxExpr:
6888 case scSMaxExpr:
6889 case scUMinExpr:
6890 case scSMinExpr:
6891 case scSequentialUMinExpr: {
6893 switch (S->getSCEVType()) {
6894 case scUMaxExpr:
6895 ID = Intrinsic::umax;
6896 break;
6897 case scSMaxExpr:
6898 ID = Intrinsic::smax;
6899 break;
6900 case scUMinExpr:
6902 ID = Intrinsic::umin;
6903 break;
6904 case scSMinExpr:
6905 ID = Intrinsic::smin;
6906 break;
6907 default:
6908 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6909 }
6910
6911 const auto *NAry = cast<SCEVNAryExpr>(S);
6912 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
6913 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6914 X = X.intrinsic(
6915 ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
6916 return setRange(S, SignHint,
6917 ConservativeResult.intersectWith(X, RangeType));
6918 }
6919 case scUnknown: {
6920 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6921 Value *V = U->getValue();
6922
6923 // Check if the IR explicitly contains !range metadata.
6924 std::optional<ConstantRange> MDRange = GetRangeFromMetadata(V);
6925 if (MDRange)
6926 ConservativeResult =
6927 ConservativeResult.intersectWith(*MDRange, RangeType);
6928
6929 // Use facts about recurrences in the underlying IR. Note that add
6930 // recurrences are AddRecExprs and thus don't hit this path. This
6931 // primarily handles shift recurrences.
6932 auto CR = getRangeForUnknownRecurrence(U);
6933 ConservativeResult = ConservativeResult.intersectWith(CR);
6934
6935 // See if ValueTracking can give us a useful range.
6936 const DataLayout &DL = getDataLayout();
6937 KnownBits Known = computeKnownBits(V, DL, &AC, nullptr, &DT);
6938 if (Known.getBitWidth() != BitWidth)
6939 Known = Known.zextOrTrunc(BitWidth);
6940
6941 // ValueTracking may be able to compute a tighter result for the number of
6942 // sign bits than for the value of those sign bits.
6943 unsigned NS = ComputeNumSignBits(V, DL, &AC, nullptr, &DT);
6944 if (U->getType()->isPointerTy()) {
6945 // NS counts the sign bits of the whole pointer; drop those above the
6946 // index bits.
6947 unsigned PtrIdxDiff =
6948 DL.getPointerTypeSizeInBits(U->getType()) - BitWidth;
6949 NS = NS > PtrIdxDiff ? NS - PtrIdxDiff : 1;
6950 }
6951
6952 if (NS > 1) {
6953 // If we know any of the sign bits, we know all of the sign bits.
6954 if (!Known.Zero.getHiBits(NS).isZero())
6955 Known.Zero.setHighBits(NS);
6956 if (!Known.One.getHiBits(NS).isZero())
6957 Known.One.setHighBits(NS);
6958 }
6959
6960 if (Known.getMinValue() != Known.getMaxValue() + 1)
6961 ConservativeResult = ConservativeResult.intersectWith(
6962 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6963 RangeType);
6964 if (NS > 1)
6965 ConservativeResult = ConservativeResult.intersectWith(
6966 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6967 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6968 RangeType);
6969
6970 if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
6971 // Strengthen the range if the underlying IR value is a
6972 // global/alloca/heap allocation using the size of the object.
6973 bool CanBeNull;
6974 uint64_t DerefBytes = V->getPointerDereferenceableBytes(
6975 DL, CanBeNull, /*CanBeFreed=*/nullptr);
6976 if (DerefBytes > 1 && isUIntN(BitWidth, DerefBytes)) {
6977 // The highest address the object can start is DerefBytes bytes before
6978 // the end (unsigned max value). If this value is not a multiple of the
6979 // alignment, the last possible start value is the next lowest multiple
6980 // of the alignment. Note: The computations below cannot overflow,
6981 // because if they would there's no possible start address for the
6982 // object.
6983 APInt MaxVal =
6984 APInt::getMaxValue(BitWidth) - APInt(BitWidth, DerefBytes);
6985 uint64_t Align = U->getValue()->getPointerAlignment(DL).value();
6986 uint64_t Rem = MaxVal.urem(Align);
6987 MaxVal -= APInt(BitWidth, Rem);
6988 APInt MinVal = APInt::getZero(BitWidth);
6989 if (llvm::isKnownNonZero(V, DL))
6990 MinVal = Align;
6991 ConservativeResult = ConservativeResult.intersectWith(
6992 ConstantRange::getNonEmpty(MinVal, MaxVal + 1), RangeType);
6993 }
6994 }
6995
6996 // A range of Phi is a subset of union of all ranges of its input.
6997 if (PHINode *Phi = dyn_cast<PHINode>(V)) {
6998 // SCEVExpander sometimes creates SCEVUnknowns that are secretly
6999 // AddRecs; return the range for the corresponding AddRec.
7000 if (auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V)))
7001 return getRangeRef(AR, SignHint, Depth + 1);
7002
7003 // Make sure that we do not run over cycled Phis.
7004 if (RangeRefPHIAllowedOperands(DT, Phi)) {
7005 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
7006
7007 for (const auto &Op : Phi->operands()) {
7008 auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
7009 RangeFromOps = RangeFromOps.unionWith(OpRange);
7010 // No point to continue if we already have a full set.
7011 if (RangeFromOps.isFullSet())
7012 break;
7013 }
7014 ConservativeResult =
7015 ConservativeResult.intersectWith(RangeFromOps, RangeType);
7016 }
7017 }
7018
7019 // vscale can't be equal to zero
7020 if (const auto *II = dyn_cast<IntrinsicInst>(V))
7021 if (II->getIntrinsicID() == Intrinsic::vscale) {
7022 ConstantRange Disallowed = APInt::getZero(BitWidth);
7023 ConservativeResult = ConservativeResult.difference(Disallowed);
7024 }
7025
7026 return setRange(U, SignHint, std::move(ConservativeResult));
7027 }
7028 case scCouldNotCompute:
7029 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
7030 }
7031
7032 return setRange(S, SignHint, std::move(ConservativeResult));
7033}
7034
7035// Given a StartRange, Step and MaxBECount for an expression compute a range of
7036// values that the expression can take. Initially, the expression has a value
7037// from StartRange and then is changed by Step up to MaxBECount times. Signed
7038// argument defines if we treat Step as signed or unsigned. The second return
7039// value indicates that no wrapping occurred.
7040static std::pair<ConstantRange, bool>
7042 const APInt &MaxBECount, bool Signed) {
7043 unsigned BitWidth = Step.getBitWidth();
7044 assert(BitWidth == StartRange.getBitWidth() &&
7045 BitWidth == MaxBECount.getBitWidth() && "mismatched bit widths");
7046 // If either Step or MaxBECount is 0, then the expression won't change, and we
7047 // just need to return the initial range.
7048 if (Step == 0 || MaxBECount == 0)
7049 return {StartRange, true};
7050
7051 // If we don't know anything about the initial value (i.e. StartRange is
7052 // FullRange), then we don't know anything about the final range either.
7053 // Return FullRange.
7054 if (StartRange.isFullSet())
7055 return {ConstantRange::getFull(BitWidth), false};
7056
7057 // If Step is signed and negative, then we use its absolute value, but we also
7058 // note that we're moving in the opposite direction.
7059 bool Descending = Signed && Step.isNegative();
7060
7061 if (Signed)
7062 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
7063 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
7064 // This equations hold true due to the well-defined wrap-around behavior of
7065 // APInt.
7066 Step = Step.abs();
7067
7068 // Check if Offset is more than full span of BitWidth. If it is, the
7069 // expression is guaranteed to overflow.
7070 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
7071 return {ConstantRange::getFull(BitWidth), false};
7072
7073 // Offset is by how much the expression can change. Checks above guarantee no
7074 // overflow here.
7075 APInt Offset = Step * MaxBECount;
7076
7077 // Minimum value of the final range will match the minimal value of StartRange
7078 // if the expression is increasing and will be decreased by Offset otherwise.
7079 // Maximum value of the final range will match the maximal value of StartRange
7080 // if the expression is decreasing and will be increased by Offset otherwise.
7081 APInt StartLower = StartRange.getLower();
7082 APInt StartUpper = StartRange.getUpper() - 1;
7083 bool Overflow;
7084 APInt MovedBoundary;
7085 if (Signed) {
7086 // This does not use sadd_ov, as we want to check overflow for a signed
7087 // start with an unsigned offset.
7088 if (Descending) {
7089 MovedBoundary = StartLower - std::move(Offset);
7090 Overflow = MovedBoundary.sgt(StartLower) || StartRange.isSignWrappedSet();
7091 } else {
7092 MovedBoundary = StartUpper + std::move(Offset);
7093 Overflow = MovedBoundary.slt(StartUpper) || StartRange.isSignWrappedSet();
7094 }
7095 } else {
7096 MovedBoundary = StartUpper.uadd_ov(std::move(Offset), Overflow);
7097 Overflow |= StartRange.isWrappedSet();
7098 }
7099
7100 // It's possible that the new minimum/maximum value will fall into the initial
7101 // range (due to wrap around). This means that the expression can take any
7102 // value in this bitwidth, and we have to return full range.
7103 if (StartRange.contains(MovedBoundary))
7104 return {ConstantRange::getFull(BitWidth), false};
7105
7106 APInt NewLower =
7107 Descending ? std::move(MovedBoundary) : std::move(StartLower);
7108 APInt NewUpper =
7109 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
7110 NewUpper += 1;
7111
7112 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
7113 return {ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)),
7114 !Overflow};
7115}
7116
7117std::pair<ConstantRange, SCEV::NoWrapFlags>
7118ScalarEvolution::getRangeForAffineAR(const SCEV *Start, const SCEV *Step,
7119 const APInt &MaxBECount) {
7120 assert(getTypeSizeInBits(Start->getType()) ==
7121 getTypeSizeInBits(Step->getType()) &&
7122 getTypeSizeInBits(Start->getType()) == MaxBECount.getBitWidth() &&
7123 "mismatched bit widths");
7124
7125 // First, consider step signed.
7126 ConstantRange StartSRange = getSignedRange(Start);
7127 ConstantRange StepSRange = getSignedRange(Step);
7128
7129 // If Step can be both positive and negative, we need to find ranges for the
7130 // maximum absolute step values in both directions and union them.
7131 auto [SR1, NSW1] = getRangeForAffineARHelper(
7132 StepSRange.getSignedMin(), StartSRange, MaxBECount, /*Signed=*/true);
7133 auto [SR2, NSW2] = getRangeForAffineARHelper(StepSRange.getSignedMax(),
7134 StartSRange, MaxBECount,
7135 /*Signed=*/true);
7136 ConstantRange SR = SR1.unionWith(SR2);
7137
7138 // Next, consider step unsigned.
7139 auto [UR, NUW] = getRangeForAffineARHelper(
7140 getUnsignedRangeMax(Step), getUnsignedRange(Start), MaxBECount,
7141 /*Signed=*/false);
7142
7144 if (NUW)
7146 if (NSW1 && NSW2)
7148
7149 // Finally, intersect signed and unsigned ranges.
7151}
7152
7153ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
7154 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
7155 ScalarEvolution::RangeSignHint SignHint) {
7156 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
7157 assert(AddRec->hasNoSelfWrap() &&
7158 "This only works for non-self-wrapping AddRecs!");
7159 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
7160 const SCEV *Step = AddRec->getStepRecurrence(*this);
7161 // Only deal with constant step to save compile time.
7162 if (!isa<SCEVConstant>(Step))
7163 return ConstantRange::getFull(BitWidth);
7164 // Let's make sure that we can prove that we do not self-wrap during
7165 // MaxBECount iterations. We need this because MaxBECount is a maximum
7166 // iteration count estimate, and we might infer nw from some exit for which we
7167 // do not know max exit count (or any other side reasoning).
7168 // TODO: Turn into assert at some point.
7169 if (getTypeSizeInBits(MaxBECount->getType()) >
7170 getTypeSizeInBits(AddRec->getType()))
7171 return ConstantRange::getFull(BitWidth);
7172 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
7173 const SCEV *RangeWidth = getMinusOne(AddRec->getType());
7174 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
7175 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
7176 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
7177 MaxItersWithoutWrap))
7178 return ConstantRange::getFull(BitWidth);
7179
7180 ICmpInst::Predicate LEPred =
7182 ICmpInst::Predicate GEPred =
7184 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7185
7186 // We know that there is no self-wrap. Let's take Start and End values and
7187 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7188 // the iteration. They either lie inside the range [Min(Start, End),
7189 // Max(Start, End)] or outside it:
7190 //
7191 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
7192 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
7193 //
7194 // No self wrap flag guarantees that the intermediate values cannot be BOTH
7195 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7196 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7197 // Start <= End and step is positive, or Start >= End and step is negative.
7198 const SCEV *Start = applyLoopGuards(AddRec->getStart(), AddRec->getLoop());
7199 ConstantRange StartRange = getRangeRef(Start, SignHint);
7200 ConstantRange EndRange = getRangeRef(End, SignHint);
7201 ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7202 // If they already cover full iteration space, we will know nothing useful
7203 // even if we prove what we want to prove.
7204 if (RangeBetween.isFullSet())
7205 return RangeBetween;
7206 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7207 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7208 : RangeBetween.isWrappedSet();
7209 if (IsWrappedSet)
7210 return ConstantRange::getFull(BitWidth);
7211
7212 if (isKnownPositive(Step) &&
7213 isKnownPredicateViaConstantRanges(LEPred, Start, End))
7214 return RangeBetween;
7215 if (isKnownNegative(Step) &&
7216 isKnownPredicateViaConstantRanges(GEPred, Start, End))
7217 return RangeBetween;
7218 return ConstantRange::getFull(BitWidth);
7219}
7220
7221ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7222 const SCEV *Step,
7223 const APInt &MaxBECount) {
7224 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7225 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7226
7227 unsigned BitWidth = MaxBECount.getBitWidth();
7228 assert(getTypeSizeInBits(Start->getType()) == BitWidth &&
7229 getTypeSizeInBits(Step->getType()) == BitWidth &&
7230 "mismatched bit widths");
7231
7232 struct SelectPattern {
7233 Value *Condition = nullptr;
7234 APInt TrueValue;
7235 APInt FalseValue;
7236
7237 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7238 const SCEV *S) {
7239 std::optional<unsigned> CastOp;
7240 APInt Offset(BitWidth, 0);
7241
7243 "Should be!");
7244
7245 // Peel off a constant offset. In the future we could consider being
7246 // smarter here and handle {Start+Step,+,Step} too.
7247 const APInt *Off;
7248 if (match(S, m_scev_Add(m_scev_APInt(Off), m_SCEV(S))))
7249 Offset = *Off;
7250
7251 // Peel off a cast operation
7252 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7253 CastOp = SCast->getSCEVType();
7254 S = SCast->getOperand();
7255 }
7256
7257 using namespace llvm::PatternMatch;
7258
7259 auto *SU = dyn_cast<SCEVUnknown>(S);
7260 const APInt *TrueVal, *FalseVal;
7261 if (!SU ||
7262 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7263 m_APInt(FalseVal)))) {
7264 Condition = nullptr;
7265 return;
7266 }
7267
7268 TrueValue = *TrueVal;
7269 FalseValue = *FalseVal;
7270
7271 // Re-apply the cast we peeled off earlier
7272 if (CastOp)
7273 switch (*CastOp) {
7274 default:
7275 llvm_unreachable("Unknown SCEV cast type!");
7276
7277 case scTruncate:
7278 TrueValue = TrueValue.trunc(BitWidth);
7279 FalseValue = FalseValue.trunc(BitWidth);
7280 break;
7281 case scZeroExtend:
7282 TrueValue = TrueValue.zext(BitWidth);
7283 FalseValue = FalseValue.zext(BitWidth);
7284 break;
7285 case scSignExtend:
7286 TrueValue = TrueValue.sext(BitWidth);
7287 FalseValue = FalseValue.sext(BitWidth);
7288 break;
7289 }
7290
7291 // Re-apply the constant offset we peeled off earlier
7292 TrueValue += Offset;
7293 FalseValue += Offset;
7294 }
7295
7296 bool isRecognized() { return Condition != nullptr; }
7297 };
7298
7299 SelectPattern StartPattern(*this, BitWidth, Start);
7300 if (!StartPattern.isRecognized())
7301 return ConstantRange::getFull(BitWidth);
7302
7303 SelectPattern StepPattern(*this, BitWidth, Step);
7304 if (!StepPattern.isRecognized())
7305 return ConstantRange::getFull(BitWidth);
7306
7307 if (StartPattern.Condition != StepPattern.Condition) {
7308 // We don't handle this case today; but we could, by considering four
7309 // possibilities below instead of two. I'm not sure if there are cases where
7310 // that will help over what getRange already does, though.
7311 return ConstantRange::getFull(BitWidth);
7312 }
7313
7314 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7315 // construct arbitrary general SCEV expressions here. This function is called
7316 // from deep in the call stack, and calling getSCEV (on a sext instruction,
7317 // say) can end up caching a suboptimal value.
7318
7319 // FIXME: without the explicit `this` receiver below, MSVC errors out with
7320 // C2352 and C2512 (otherwise it isn't needed).
7321
7322 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7323 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7324 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7325 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7326
7327 ConstantRange TrueRange =
7328 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount).first;
7329 ConstantRange FalseRange =
7330 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount).first;
7331
7332 return TrueRange.unionWith(FalseRange);
7333}
7334
7335SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7336 if (isa<ConstantExpr>(V))
7337 return SCEV::FlagNone;
7338 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7339
7340 // Return early if there are no flags to propagate to the SCEV.
7342 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(BinOp);
7343 PDI && PDI->isDisjoint()) {
7345 } else {
7346 if (BinOp->hasNoUnsignedWrap())
7348 if (BinOp->hasNoSignedWrap())
7350 }
7351 if (Flags == SCEV::FlagNone)
7352 return SCEV::FlagNone;
7353
7354 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagNone;
7355}
7356
7357const Instruction *
7358ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7359 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7360 return &*AddRec->getLoop()->getHeader()->begin();
7361 if (auto *U = dyn_cast<SCEVUnknown>(S))
7362 if (auto *I = dyn_cast<Instruction>(U->getValue()))
7363 return I;
7364 return nullptr;
7365}
7366
7367const Instruction *ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops,
7368 bool &Precise) {
7369 Precise = true;
7370 // Do a bounded search of the def relation of the requested SCEVs.
7371 SmallPtrSet<const SCEV *, 16> Visited;
7372 SmallVector<SCEVUse> Worklist;
7373 auto pushOp = [&](const SCEV *S) {
7374 if (!Visited.insert(S).second)
7375 return;
7376 // Threshold of 30 here is arbitrary.
7377 if (Visited.size() > 30) {
7378 Precise = false;
7379 return;
7380 }
7381 Worklist.push_back(S);
7382 };
7383
7384 for (SCEVUse S : Ops)
7385 pushOp(S);
7386
7387 const Instruction *Bound = nullptr;
7388 while (!Worklist.empty()) {
7389 SCEVUse S = Worklist.pop_back_val();
7390 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7391 if (!Bound || DT.dominates(Bound, DefI))
7392 Bound = DefI;
7393 } else {
7394 for (SCEVUse Op : S->operands())
7395 pushOp(Op);
7396 }
7397 }
7398 return Bound ? Bound : &*F.getEntryBlock().begin();
7399}
7400
7401const Instruction *
7402ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops) {
7403 bool Discard;
7404 return getDefiningScopeBound(Ops, Discard);
7405}
7406
7407bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7408 const Instruction *B) {
7409 if (A->getParent() == B->getParent() &&
7411 B->getIterator()))
7412 return true;
7413
7414 auto *BLoop = LI.getLoopFor(B->getParent());
7415 if (BLoop && BLoop->getHeader() == B->getParent() &&
7416 BLoop->getLoopPreheader() == A->getParent() &&
7418 A->getParent()->end()) &&
7419 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7420 B->getIterator()))
7421 return true;
7422 return false;
7423}
7424
7426 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ true);
7427 visitAll(Op, PC);
7428 return PC.MaybePoison.empty();
7429}
7430
7431bool ScalarEvolution::isGuaranteedNotToCauseUB(const SCEV *Op) {
7432 return !SCEVExprContains(Op, [this](const SCEV *S) {
7433 const SCEV *Op1;
7434 bool M = match(S, m_scev_UDiv(m_SCEV(), m_SCEV(Op1)));
7435 // The UDiv may be UB if the divisor is poison or zero. Unless the divisor
7436 // is a non-zero constant, we have to assume the UDiv may be UB.
7437 return M && (!isKnownNonZero(Op1) || !isGuaranteedNotToBePoison(Op1));
7438 });
7439}
7440
7441bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7442 // Only proceed if we can prove that I does not yield poison.
7444 return false;
7445
7446 // At this point we know that if I is executed, then it does not wrap
7447 // according to at least one of NSW or NUW. If I is not executed, then we do
7448 // not know if the calculation that I represents would wrap. Multiple
7449 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7450 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7451 // derived from other instructions that map to the same SCEV. We cannot make
7452 // that guarantee for cases where I is not executed. So we need to find a
7453 // upper bound on the defining scope for the SCEV, and prove that I is
7454 // executed every time we enter that scope. When the bounding scope is a
7455 // loop (the common case), this is equivalent to proving I executes on every
7456 // iteration of that loop.
7457 SmallVector<SCEVUse> SCEVOps;
7458 for (const Use &Op : I->operands()) {
7459 // I could be an extractvalue from a call to an overflow intrinsic.
7460 // TODO: We can do better here in some cases.
7461 if (isSCEVable(Op->getType()))
7462 SCEVOps.push_back(getSCEV(Op));
7463 }
7464 auto *DefI = getDefiningScopeBound(SCEVOps);
7465 return isGuaranteedToTransferExecutionTo(DefI, I);
7466}
7467
7468bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7469 // If we know that \c I can never be poison period, then that's enough.
7470 if (isSCEVExprNeverPoison(I))
7471 return true;
7472
7473 // If the loop only has one exit, then we know that, if the loop is entered,
7474 // any instruction dominating that exit will be executed. If any such
7475 // instruction would result in UB, the addrec cannot be poison.
7476 //
7477 // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7478 // also handles uses outside the loop header (they just need to dominate the
7479 // single exit).
7480
7481 auto *ExitingBB = L->getExitingBlock();
7482 if (!ExitingBB || !loopHasNoAbnormalExits(L))
7483 return false;
7484
7485 SmallPtrSet<const Value *, 16> KnownPoison;
7487
7488 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
7489 // things that are known to be poison under that assumption go on the
7490 // Worklist.
7491 KnownPoison.insert(I);
7492 Worklist.push_back(I);
7493
7494 while (!Worklist.empty()) {
7495 const Instruction *Poison = Worklist.pop_back_val();
7496
7497 for (const Use &U : Poison->uses()) {
7498 const Instruction *PoisonUser = cast<Instruction>(U.getUser());
7499 if (mustTriggerUB(PoisonUser, KnownPoison) &&
7500 DT.dominates(PoisonUser->getParent(), ExitingBB))
7501 return true;
7502
7503 if (propagatesPoison(U) && L->contains(PoisonUser))
7504 if (KnownPoison.insert(PoisonUser).second)
7505 Worklist.push_back(PoisonUser);
7506 }
7507 }
7508
7509 return false;
7510}
7511
7512ScalarEvolution::LoopProperties
7513ScalarEvolution::getLoopProperties(const Loop *L) {
7514 using LoopProperties = ScalarEvolution::LoopProperties;
7515
7516 auto Itr = LoopPropertiesCache.find(L);
7517 if (Itr == LoopPropertiesCache.end()) {
7518 auto HasSideEffects = [](Instruction *I) {
7519 if (auto *SI = dyn_cast<StoreInst>(I))
7520 return !SI->isSimple();
7521
7522 if (I->mayThrow())
7523 return true;
7524
7525 // Non-volatile memset / memcpy do not count as side-effect for forward
7526 // progress.
7527 if (isa<MemIntrinsic>(I) && !I->isVolatile())
7528 return false;
7529
7530 return I->mayWriteToMemory();
7531 };
7532
7533 LoopProperties LP = {/* HasNoAbnormalExits */ true,
7534 /*HasNoSideEffects*/ true};
7535
7536 for (auto *BB : L->getBlocks())
7537 for (auto &I : *BB) {
7539 LP.HasNoAbnormalExits = false;
7540 if (HasSideEffects(&I))
7541 LP.HasNoSideEffects = false;
7542 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7543 break; // We're already as pessimistic as we can get.
7544 }
7545
7546 auto InsertPair = LoopPropertiesCache.insert({L, LP});
7547 assert(InsertPair.second && "We just checked!");
7548 Itr = InsertPair.first;
7549 }
7550
7551 return Itr->second;
7552}
7553
7555 // A mustprogress loop without side effects must be finite.
7556 // TODO: The check used here is very conservative. It's only *specific*
7557 // side effects which are well defined in infinite loops.
7558 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7559}
7560
7561const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7562 // Worklist item with a Value and a bool indicating whether all operands have
7563 // been visited already.
7566
7567 Stack.emplace_back(V, false);
7568 while (!Stack.empty()) {
7569 auto E = Stack.back();
7570 Value *CurV = E.getPointer();
7571
7572 if (getExistingSCEV(CurV)) {
7573 Stack.pop_back();
7574 continue;
7575 }
7576
7578 const SCEV *CreatedSCEV = nullptr;
7579 // If all operands have been visited already, create the SCEV.
7580 if (E.getInt()) {
7581 CreatedSCEV = createSCEV(CurV);
7582 } else {
7583 // Otherwise get the operands we need to create SCEV's for before creating
7584 // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7585 // just use it.
7586 CreatedSCEV = getOperandsToCreate(CurV, Ops);
7587 }
7588
7589 if (CreatedSCEV) {
7590 insertValueToMap(CurV, CreatedSCEV);
7591 Stack.pop_back();
7592 } else {
7593 Stack.back().setInt(true);
7594 // Queue its operands which need to be constructed.
7595 for (Value *Op : Ops)
7596 Stack.emplace_back(Op, false);
7597 }
7598 }
7599
7600 return getExistingSCEV(V);
7601}
7602
7603const SCEV *
7604ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7605 if (!isSCEVable(V->getType()))
7606 return getUnknown(V);
7607
7608 if (Instruction *I = dyn_cast<Instruction>(V)) {
7609 // Don't attempt to analyze instructions in blocks that aren't
7610 // reachable. Such instructions don't matter, and they aren't required
7611 // to obey basic rules for definitions dominating uses which this
7612 // analysis depends on.
7613 if (!DT.isReachableFromEntry(I->getParent()))
7614 return getUnknown(PoisonValue::get(V->getType()));
7615 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7616 return getConstant(CI);
7617 else if (isa<GlobalAlias>(V))
7618 return getUnknown(V);
7619 else if (!isa<ConstantExpr>(V))
7620 return getUnknown(V);
7621
7623 if (auto BO =
7625 bool IsConstArg = isa<ConstantInt>(BO->RHS);
7626 switch (BO->Opcode) {
7627 case Instruction::Add:
7628 case Instruction::Mul: {
7629 // For additions and multiplications, traverse add/mul chains for which we
7630 // can potentially create a single SCEV, to reduce the number of
7631 // get{Add,Mul}Expr calls.
7632 do {
7633 if (BO->Op) {
7634 if (BO->Op != V && getExistingSCEV(BO->Op)) {
7635 Ops.push_back(BO->Op);
7636 break;
7637 }
7638 }
7639 Ops.push_back(BO->RHS);
7640 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7642 if (!NewBO ||
7643 (BO->Opcode == Instruction::Add &&
7644 (NewBO->Opcode != Instruction::Add &&
7645 NewBO->Opcode != Instruction::Sub)) ||
7646 (BO->Opcode == Instruction::Mul &&
7647 NewBO->Opcode != Instruction::Mul)) {
7648 Ops.push_back(BO->LHS);
7649 break;
7650 }
7651 // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7652 // requires a SCEV for the LHS.
7653 if (BO->Op && (BO->IsNSW || BO->IsNUW)) {
7654 auto *I = dyn_cast<Instruction>(BO->Op);
7655 if (I && programUndefinedIfPoison(I)) {
7656 Ops.push_back(BO->LHS);
7657 break;
7658 }
7659 }
7660 BO = NewBO;
7661 } while (true);
7662 return nullptr;
7663 }
7664 case Instruction::Sub:
7665 case Instruction::UDiv:
7666 case Instruction::URem:
7667 break;
7668 case Instruction::AShr:
7669 case Instruction::Shl:
7670 case Instruction::Xor:
7671 if (!IsConstArg)
7672 return nullptr;
7673 break;
7674 case Instruction::And:
7675 case Instruction::Or:
7676 if (!IsConstArg && !BO->LHS->getType()->isIntegerTy(1))
7677 return nullptr;
7678 break;
7679 case Instruction::LShr:
7680 return getUnknown(V);
7681 default:
7682 llvm_unreachable("Unhandled binop");
7683 break;
7684 }
7685
7686 Ops.push_back(BO->LHS);
7687 Ops.push_back(BO->RHS);
7688 return nullptr;
7689 }
7690
7691 switch (U->getOpcode()) {
7692 case Instruction::Trunc:
7693 case Instruction::ZExt:
7694 case Instruction::SExt:
7695 case Instruction::PtrToAddr:
7696 case Instruction::PtrToInt:
7697 Ops.push_back(U->getOperand(0));
7698 return nullptr;
7699
7700 case Instruction::BitCast:
7701 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
7702 Ops.push_back(U->getOperand(0));
7703 return nullptr;
7704 }
7705 return getUnknown(V);
7706
7707 case Instruction::SDiv:
7708 case Instruction::SRem:
7709 Ops.push_back(U->getOperand(0));
7710 Ops.push_back(U->getOperand(1));
7711 return nullptr;
7712
7713 case Instruction::GetElementPtr:
7714 assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7715 "GEP source element type must be sized");
7716 llvm::append_range(Ops, U->operands());
7717 return nullptr;
7718
7719 case Instruction::IntToPtr:
7720 return getUnknown(V);
7721
7722 case Instruction::PHI:
7723 // getNodeForPHI has four ways to turn a PHI into a SCEV; retrieve the
7724 // relevant nodes for each of them.
7725 //
7726 // The first is just to call simplifyInstruction, and get something back
7727 // that isn't a PHI.
7728 if (Value *V = simplifyInstruction(
7729 cast<PHINode>(U),
7730 {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
7731 /*UseInstrInfo=*/true, /*CanUseUndef=*/false})) {
7732 assert(V);
7733 Ops.push_back(V);
7734 return nullptr;
7735 }
7736 // The second is createNodeForPHIWithIdenticalOperands: this looks for
7737 // operands which all perform the same operation, but haven't been
7738 // CSE'ed for whatever reason.
7739 if (BinaryOperator *BO = getCommonInstForPHI(cast<PHINode>(U))) {
7740 assert(BO);
7741 Ops.push_back(BO);
7742 return nullptr;
7743 }
7744 // The third is createNodeFromSelectLikePHI; this takes a PHI which
7745 // is equivalent to a select, and analyzes it like a select.
7746 {
7747 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
7749 assert(Cond);
7750 assert(LHS);
7751 assert(RHS);
7752 if (auto *CondICmp = dyn_cast<ICmpInst>(Cond)) {
7753 Ops.push_back(CondICmp->getOperand(0));
7754 Ops.push_back(CondICmp->getOperand(1));
7755 }
7756 Ops.push_back(Cond);
7757 Ops.push_back(LHS);
7758 Ops.push_back(RHS);
7759 return nullptr;
7760 }
7761 }
7762 // The fourth way is createAddRecFromPHI. It's complicated to handle here,
7763 // so just construct it recursively.
7764 //
7765 // In addition to getNodeForPHI, also construct nodes which might be needed
7766 // by getRangeRef.
7768 for (Value *V : cast<PHINode>(U)->operands())
7769 Ops.push_back(V);
7770 return nullptr;
7771 }
7772 return nullptr;
7773
7774 case Instruction::Select: {
7775 // Check if U is a select that can be simplified to a SCEVUnknown.
7776 auto CanSimplifyToUnknown = [this, U]() {
7777 if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
7778 return false;
7779
7780 auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
7781 if (!ICI)
7782 return false;
7783 Value *LHS = ICI->getOperand(0);
7784 Value *RHS = ICI->getOperand(1);
7785 if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7786 ICI->getPredicate() == CmpInst::ICMP_NE) {
7788 return true;
7789 } else if (getTypeSizeInBits(LHS->getType()) >
7790 getTypeSizeInBits(U->getType()))
7791 return true;
7792 return false;
7793 };
7794 if (CanSimplifyToUnknown())
7795 return getUnknown(U);
7796
7797 llvm::append_range(Ops, U->operands());
7798 return nullptr;
7799 break;
7800 }
7801 case Instruction::Call:
7802 case Instruction::Invoke:
7803 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7804 Ops.push_back(RV);
7805 return nullptr;
7806 }
7807
7808 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7809 switch (II->getIntrinsicID()) {
7810 case Intrinsic::abs:
7811 Ops.push_back(II->getArgOperand(0));
7812 return nullptr;
7813 case Intrinsic::umax:
7814 case Intrinsic::umin:
7815 case Intrinsic::smax:
7816 case Intrinsic::smin:
7817 case Intrinsic::usub_sat:
7818 case Intrinsic::uadd_sat:
7819 Ops.push_back(II->getArgOperand(0));
7820 Ops.push_back(II->getArgOperand(1));
7821 return nullptr;
7822 case Intrinsic::start_loop_iterations:
7823 case Intrinsic::annotation:
7824 case Intrinsic::ptr_annotation:
7825 Ops.push_back(II->getArgOperand(0));
7826 return nullptr;
7827 default:
7828 break;
7829 }
7830 }
7831 break;
7832 }
7833
7834 return nullptr;
7835}
7836
7837const SCEV *ScalarEvolution::createSCEV(Value *V) {
7838 if (!isSCEVable(V->getType()))
7839 return getUnknown(V);
7840
7841 if (Instruction *I = dyn_cast<Instruction>(V)) {
7842 // Don't attempt to analyze instructions in blocks that aren't
7843 // reachable. Such instructions don't matter, and they aren't required
7844 // to obey basic rules for definitions dominating uses which this
7845 // analysis depends on.
7846 if (!DT.isReachableFromEntry(I->getParent()))
7847 return getUnknown(PoisonValue::get(V->getType()));
7848 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7849 return getConstant(CI);
7850 else if (isa<GlobalAlias>(V))
7851 return getUnknown(V);
7852 else if (!isa<ConstantExpr>(V))
7853 return getUnknown(V);
7854
7855 const SCEV *LHS;
7856 const SCEV *RHS;
7857
7859 if (auto BO =
7861 switch (BO->Opcode) {
7862 case Instruction::Add: {
7863 // The simple thing to do would be to just call getSCEV on both operands
7864 // and call getAddExpr with the result. However if we're looking at a
7865 // bunch of things all added together, this can be quite inefficient,
7866 // because it leads to N-1 getAddExpr calls for N ultimate operands.
7867 // Instead, gather up all the operands and make a single getAddExpr call.
7868 // LLVM IR canonical form means we need only traverse the left operands.
7870 do {
7871 if (BO->Op) {
7872 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7873 AddOps.push_back(OpSCEV);
7874 break;
7875 }
7876
7877 // If a NUW or NSW flag can be applied to the SCEV for this
7878 // addition, then compute the SCEV for this addition by itself
7879 // with a separate call to getAddExpr. We need to do that
7880 // instead of pushing the operands of the addition onto AddOps,
7881 // since the flags are only known to apply to this particular
7882 // addition - they may not apply to other additions that can be
7883 // formed with operands from AddOps.
7884 const SCEV *RHS = getSCEV(BO->RHS);
7885 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7886 if (Flags != SCEV::FlagNone) {
7887 const SCEV *LHS = getSCEV(BO->LHS);
7888 if (BO->Opcode == Instruction::Sub)
7889 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7890 else
7891 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7892 break;
7893 }
7894 }
7895
7896 if (BO->Opcode == Instruction::Sub)
7897 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7898 else
7899 AddOps.push_back(getSCEV(BO->RHS));
7900
7901 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7903 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7904 NewBO->Opcode != Instruction::Sub)) {
7905 AddOps.push_back(getSCEV(BO->LHS));
7906 break;
7907 }
7908 BO = NewBO;
7909 } while (true);
7910
7911 return getAddExpr(AddOps);
7912 }
7913
7914 case Instruction::Mul: {
7916 do {
7917 if (BO->Op) {
7918 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7919 MulOps.push_back(OpSCEV);
7920 break;
7921 }
7922
7923 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7924 if (Flags != SCEV::FlagNone) {
7925 LHS = getSCEV(BO->LHS);
7926 RHS = getSCEV(BO->RHS);
7927 MulOps.push_back(getMulExpr(LHS, RHS, Flags));
7928 break;
7929 }
7930 }
7931
7932 MulOps.push_back(getSCEV(BO->RHS));
7933 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7935 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7936 MulOps.push_back(getSCEV(BO->LHS));
7937 break;
7938 }
7939 BO = NewBO;
7940 } while (true);
7941
7942 return getMulExpr(MulOps);
7943 }
7944 case Instruction::UDiv:
7945 LHS = getSCEV(BO->LHS);
7946 RHS = getSCEV(BO->RHS);
7947 return getUDivExpr(LHS, RHS);
7948 case Instruction::URem:
7949 LHS = getSCEV(BO->LHS);
7950 RHS = getSCEV(BO->RHS);
7951 return getURemExpr(LHS, RHS);
7952 case Instruction::Sub: {
7954 if (BO->Op)
7955 Flags = getNoWrapFlagsFromUB(BO->Op);
7956
7957 // Try to use ptrtoaddr for subtracts with at least one ptrtoint
7958 // operand. While we don't model ptrtoint directly in SCEV, the
7959 // difference between two pointer addresses is well-defined.
7960 Value *PtrLHS = nullptr, *PtrRHS = nullptr;
7961 bool HasPtrLHS = match(BO->LHS, m_PtrToInt(m_Value(PtrLHS)));
7962 bool HasPtrRHS = match(BO->RHS, m_PtrToInt(m_Value(PtrRHS)));
7963 if (HasPtrLHS || HasPtrRHS) {
7964 // Convert a ptrtoint operand (OrigOp) to ptrtoaddr of its pointer
7965 // PtrOp. When only one side is ptrtoint (BothPtr is false), skip
7966 // SCEVUnknown pointers since wrapping them in ptrtoaddr adds no
7967 // useful structure.
7968 auto GetOp = [&](bool HasPtr, Value *PtrOp, Value *OrigOp,
7969 bool BothPtr) -> const SCEV * {
7970 if (!HasPtr)
7971 return getSCEV(OrigOp);
7972 const SCEV *PtrSCEV = getSCEV(PtrOp);
7973 if (BothPtr || !isa<SCEVUnknown>(PtrSCEV)) {
7974 const SCEV *Addr = getPtrToAddrExpr(PtrSCEV);
7975 if (!isa<SCEVCouldNotCompute>(Addr) &&
7976 getTypeSizeInBits(OrigOp->getType()) <=
7977 getTypeSizeInBits(Addr->getType()))
7978 return getTruncateOrNoop(Addr, OrigOp->getType());
7979 }
7980 return getSCEV(OrigOp);
7981 };
7982 const SCEV *L = GetOp(HasPtrLHS, PtrLHS, BO->LHS, HasPtrRHS);
7983 const SCEV *R = GetOp(HasPtrRHS, PtrRHS, BO->RHS, HasPtrLHS);
7984 return getMinusSCEV(L, R, Flags);
7985 }
7986
7987 LHS = getSCEV(BO->LHS);
7988 RHS = getSCEV(BO->RHS);
7989 return getMinusSCEV(LHS, RHS, Flags);
7990 }
7991 case Instruction::And:
7992 // For an expression like x&255 that merely masks off the high bits,
7993 // use zext(trunc(x)) as the SCEV expression.
7994 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7995 if (CI->isZero())
7996 return getSCEV(BO->RHS);
7997 if (CI->isMinusOne())
7998 return getSCEV(BO->LHS);
7999 const APInt &A = CI->getValue();
8000
8001 // Instcombine's ShrinkDemandedConstant may strip bits out of
8002 // constants, obscuring what would otherwise be a low-bits mask.
8003 // Use computeKnownBits to compute what ShrinkDemandedConstant
8004 // knew about to reconstruct a low-bits mask value.
8005 unsigned LZ = A.countl_zero();
8006 unsigned TZ = A.countr_zero();
8007 unsigned BitWidth = A.getBitWidth();
8008 KnownBits Known(BitWidth);
8009 computeKnownBits(BO->LHS, Known, getDataLayout(), &AC, nullptr, &DT);
8010
8011 APInt EffectiveMask =
8012 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
8013 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
8014 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
8015 const SCEV *LHS = getSCEV(BO->LHS);
8016 const SCEV *ShiftedLHS = nullptr;
8017 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
8018 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
8019 // For an expression like (x * 8) & 8, simplify the multiply.
8020 unsigned MulZeros = OpC->getAPInt().countr_zero();
8021 unsigned GCD = std::min(MulZeros, TZ);
8022 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
8024 MulOps.push_back(getConstant(OpC->getAPInt().ashr(GCD)));
8025 append_range(MulOps, LHSMul->operands().drop_front());
8026 const SCEV *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
8027 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
8028 }
8029 }
8030 if (!ShiftedLHS)
8031 ShiftedLHS = getUDivExpr(LHS, MulCount);
8032 return getMulExpr(
8034 getTruncateExpr(ShiftedLHS,
8035 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
8036 BO->LHS->getType()),
8037 MulCount);
8038 }
8039 }
8040 // Binary `and` is a bit-wise `umin`.
8041 if (BO->LHS->getType()->isIntegerTy(1)) {
8042 LHS = getSCEV(BO->LHS);
8043 RHS = getSCEV(BO->RHS);
8044 return getUMinExpr(LHS, RHS);
8045 }
8046 break;
8047
8048 case Instruction::Or:
8049 // Binary `or` is a bit-wise `umax`.
8050 if (BO->LHS->getType()->isIntegerTy(1)) {
8051 LHS = getSCEV(BO->LHS);
8052 RHS = getSCEV(BO->RHS);
8053 return getUMaxExpr(LHS, RHS);
8054 }
8055 break;
8056
8057 case Instruction::Xor:
8058 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
8059 // If the RHS of xor is -1, then this is a not operation.
8060 if (CI->isMinusOne())
8061 return getNotSCEV(getSCEV(BO->LHS));
8062
8063 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
8064 // This is a variant of the check for xor with -1, and it handles
8065 // the case where instcombine has trimmed non-demanded bits out
8066 // of an xor with -1.
8067 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
8068 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
8069 if (LBO->getOpcode() == Instruction::And &&
8070 LCI->getValue() == CI->getValue())
8071 if (const SCEVZeroExtendExpr *Z =
8073 Type *UTy = BO->LHS->getType();
8074 const SCEV *Z0 = Z->getOperand();
8075 Type *Z0Ty = Z0->getType();
8076 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
8077
8078 // If C is a low-bits mask, the zero extend is serving to
8079 // mask off the high bits. Complement the operand and
8080 // re-apply the zext.
8081 if (CI->getValue().isMask(Z0TySize))
8082 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
8083
8084 // If C is a single bit, it may be in the sign-bit position
8085 // before the zero-extend. In this case, represent the xor
8086 // using an add, which is equivalent, and re-apply the zext.
8087 APInt Trunc = CI->getValue().trunc(Z0TySize);
8088 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
8089 Trunc.isSignMask())
8090 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
8091 UTy);
8092 }
8093 }
8094 break;
8095
8096 case Instruction::Shl:
8097 // Turn shift left of a constant amount into a multiply.
8098 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
8099 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
8100
8101 // If the shift count is not less than the bitwidth, the result of
8102 // the shift is undefined. Don't try to analyze it, because the
8103 // resolution chosen here may differ from the resolution chosen in
8104 // other parts of the compiler.
8105 if (SA->getValue().uge(BitWidth))
8106 break;
8107
8108 // We can safely preserve the nuw flag in all cases. It's also safe to
8109 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
8110 // requires special handling. It can be preserved as long as we're not
8111 // left shifting by bitwidth - 1.
8112 auto Flags = SCEV::FlagNone;
8113 if (BO->Op) {
8114 auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
8115 if (any(MulFlags & SCEV::FlagNSW) &&
8116 (any(MulFlags & SCEV::FlagNUW) ||
8117 SA->getValue().ult(BitWidth - 1)))
8119 if (any(MulFlags & SCEV::FlagNUW))
8121 }
8122
8123 ConstantInt *X = ConstantInt::get(
8124 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
8125 return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
8126 }
8127 break;
8128
8129 case Instruction::AShr:
8130 // AShr X, C, where C is a constant.
8131 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
8132 if (!CI)
8133 break;
8134
8135 Type *OuterTy = BO->LHS->getType();
8137 // If the shift count is not less than the bitwidth, the result of
8138 // the shift is undefined. Don't try to analyze it, because the
8139 // resolution chosen here may differ from the resolution chosen in
8140 // other parts of the compiler.
8141 if (CI->getValue().uge(BitWidth))
8142 break;
8143
8144 if (CI->isZero())
8145 return getSCEV(BO->LHS); // shift by zero --> noop
8146
8147 uint64_t AShrAmt = CI->getZExtValue();
8148 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
8149
8150 Operator *L = dyn_cast<Operator>(BO->LHS);
8151 const SCEV *AddTruncateExpr = nullptr;
8152 ConstantInt *ShlAmtCI = nullptr;
8153 const SCEV *AddConstant = nullptr;
8154
8155 if (L && L->getOpcode() == Instruction::Add) {
8156 // X = Shl A, n
8157 // Y = Add X, c
8158 // Z = AShr Y, m
8159 // n, c and m are constants.
8160
8161 Operator *LShift = dyn_cast<Operator>(L->getOperand(0));
8162 ConstantInt *AddOperandCI = dyn_cast<ConstantInt>(L->getOperand(1));
8163 if (LShift && LShift->getOpcode() == Instruction::Shl) {
8164 if (AddOperandCI) {
8165 const SCEV *ShlOp0SCEV = getSCEV(LShift->getOperand(0));
8166 ShlAmtCI = dyn_cast<ConstantInt>(LShift->getOperand(1));
8167 // since we truncate to TruncTy, the AddConstant should be of the
8168 // same type, so create a new Constant with type same as TruncTy.
8169 // Also, the Add constant should be shifted right by AShr amount.
8170 APInt AddOperand = AddOperandCI->getValue().ashr(AShrAmt);
8171 AddConstant = getConstant(AddOperand.trunc(BitWidth - AShrAmt));
8172 // we model the expression as sext(add(trunc(A), c << n)), since the
8173 // sext(trunc) part is already handled below, we create a
8174 // AddExpr(TruncExp) which will be used later.
8175 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8176 }
8177 }
8178 } else if (L && L->getOpcode() == Instruction::Shl) {
8179 // X = Shl A, n
8180 // Y = AShr X, m
8181 // Both n and m are constant.
8182
8183 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
8184 ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
8185 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8186 }
8187
8188 if (AddTruncateExpr && ShlAmtCI) {
8189 // We can merge the two given cases into a single SCEV statement,
8190 // incase n = m, the mul expression will be 2^0, so it gets resolved to
8191 // a simpler case. The following code handles the two cases:
8192 //
8193 // 1) For a two-shift sext-inreg, i.e. n = m,
8194 // use sext(trunc(x)) as the SCEV expression.
8195 //
8196 // 2) When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
8197 // expression. We already checked that ShlAmt < BitWidth, so
8198 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
8199 // ShlAmt - AShrAmt < Amt.
8200 const APInt &ShlAmt = ShlAmtCI->getValue();
8201 if (ShlAmt.ult(BitWidth) && ShlAmt.uge(AShrAmt)) {
8202 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
8203 ShlAmtCI->getZExtValue() - AShrAmt);
8204 const SCEV *CompositeExpr =
8205 getMulExpr(AddTruncateExpr, getConstant(Mul));
8206 if (L->getOpcode() != Instruction::Shl)
8207 CompositeExpr = getAddExpr(CompositeExpr, AddConstant);
8208
8209 return getSignExtendExpr(CompositeExpr, OuterTy);
8210 }
8211 }
8212 break;
8213 }
8214 }
8215
8216 switch (U->getOpcode()) {
8217 case Instruction::Trunc:
8218 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
8219
8220 case Instruction::ZExt:
8221 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8222
8223 case Instruction::SExt:
8224 if (auto BO = MatchBinaryOp(U->getOperand(0), getDataLayout(), AC, DT,
8226 // The NSW flag of a subtract does not always survive the conversion to
8227 // A + (-1)*B. By pushing sign extension onto its operands we are much
8228 // more likely to preserve NSW and allow later AddRec optimisations.
8229 //
8230 // NOTE: This is effectively duplicating this logic from getSignExtend:
8231 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
8232 // but by that point the NSW information has potentially been lost.
8233 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
8234 Type *Ty = U->getType();
8235 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
8236 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
8237 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
8238 }
8239 }
8240 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8241
8242 case Instruction::BitCast:
8243 // BitCasts are no-op casts so we just eliminate the cast.
8244 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
8245 return getSCEV(U->getOperand(0));
8246 break;
8247
8248 case Instruction::PtrToAddr: {
8249 const SCEV *IntOp = getPtrToAddrExpr(getSCEV(U->getOperand(0)));
8250 if (isa<SCEVCouldNotCompute>(IntOp))
8251 return getUnknown(V);
8252 return IntOp;
8253 }
8254
8255 case Instruction::PtrToInt:
8256 // SCEV only models ptrtoaddr.
8257 return getUnknown(V);
8258
8259 case Instruction::IntToPtr:
8260 // Just don't deal with inttoptr casts.
8261 return getUnknown(V);
8262
8263 case Instruction::SDiv:
8264 // If both operands are non-negative, this is just an udiv.
8265 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8266 isKnownNonNegative(getSCEV(U->getOperand(1))))
8267 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8268 break;
8269
8270 case Instruction::SRem:
8271 // If both operands are non-negative, this is just an urem.
8272 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8273 isKnownNonNegative(getSCEV(U->getOperand(1))))
8274 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8275 break;
8276
8277 case Instruction::GetElementPtr:
8278 return createNodeForGEP(cast<GEPOperator>(U));
8279
8280 case Instruction::PHI:
8281 return createNodeForPHI(cast<PHINode>(U));
8282
8283 case Instruction::Select:
8284 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
8285 U->getOperand(2));
8286
8287 case Instruction::Call:
8288 case Instruction::Invoke:
8289 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
8290 return getSCEV(RV);
8291
8292 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
8293 switch (II->getIntrinsicID()) {
8294 case Intrinsic::abs:
8295 return getAbsExpr(
8296 getSCEV(II->getArgOperand(0)),
8297 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
8298 case Intrinsic::umax:
8299 LHS = getSCEV(II->getArgOperand(0));
8300 RHS = getSCEV(II->getArgOperand(1));
8301 return getUMaxExpr(LHS, RHS);
8302 case Intrinsic::umin:
8303 LHS = getSCEV(II->getArgOperand(0));
8304 RHS = getSCEV(II->getArgOperand(1));
8305 return getUMinExpr(LHS, RHS);
8306 case Intrinsic::smax:
8307 LHS = getSCEV(II->getArgOperand(0));
8308 RHS = getSCEV(II->getArgOperand(1));
8309 return getSMaxExpr(LHS, RHS);
8310 case Intrinsic::smin:
8311 LHS = getSCEV(II->getArgOperand(0));
8312 RHS = getSCEV(II->getArgOperand(1));
8313 return getSMinExpr(LHS, RHS);
8314 case Intrinsic::usub_sat: {
8315 const SCEV *X = getSCEV(II->getArgOperand(0));
8316 const SCEV *Y = getSCEV(II->getArgOperand(1));
8317 const SCEV *ClampedY = getUMinExpr(X, Y);
8318 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
8319 }
8320 case Intrinsic::uadd_sat: {
8321 const SCEV *X = getSCEV(II->getArgOperand(0));
8322 const SCEV *Y = getSCEV(II->getArgOperand(1));
8323 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
8324 return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
8325 }
8326 case Intrinsic::start_loop_iterations:
8327 case Intrinsic::annotation:
8328 case Intrinsic::ptr_annotation:
8329 // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8330 // just eqivalent to the first operand for SCEV purposes.
8331 return getSCEV(II->getArgOperand(0));
8332 case Intrinsic::vscale:
8333 return getVScale(II->getType());
8334 default:
8335 break;
8336 }
8337 }
8338 break;
8339 }
8340
8341 return getUnknown(V);
8342}
8343
8344//===----------------------------------------------------------------------===//
8345// Iteration Count Computation Code
8346//
8347
8349 if (isa<SCEVCouldNotCompute>(ExitCount))
8350 return getCouldNotCompute();
8351
8352 auto *ExitCountType = ExitCount->getType();
8353 assert(ExitCountType->isIntegerTy());
8354 auto *EvalTy = Type::getIntNTy(ExitCountType->getContext(),
8355 1 + ExitCountType->getScalarSizeInBits());
8356 return getTripCountFromExitCount(ExitCount, EvalTy, nullptr);
8357}
8358
8360 Type *EvalTy,
8361 const Loop *L) {
8362 if (isa<SCEVCouldNotCompute>(ExitCount))
8363 return getCouldNotCompute();
8364
8365 unsigned ExitCountSize = getTypeSizeInBits(ExitCount->getType());
8366 unsigned EvalSize = EvalTy->getPrimitiveSizeInBits();
8367
8368 auto CanAddOneWithoutOverflow = [&]() {
8369 ConstantRange ExitCountRange =
8370 getRangeRef(ExitCount, RangeSignHint::HINT_RANGE_UNSIGNED);
8371 if (!ExitCountRange.contains(APInt::getMaxValue(ExitCountSize)))
8372 return true;
8373
8374 return L && isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
8375 getMinusOne(ExitCount->getType()));
8376 };
8377
8378 // If we need to zero extend the backedge count, check if we can add one to
8379 // it prior to zero extending without overflow. Provided this is safe, it
8380 // allows better simplification of the +1.
8381 if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8382 return getZeroExtendExpr(
8383 getAddExpr(ExitCount, getOne(ExitCount->getType())), EvalTy);
8384
8385 // Get the total trip count from the count by adding 1. This may wrap.
8386 return getAddExpr(getTruncateOrZeroExtend(ExitCount, EvalTy), getOne(EvalTy));
8387}
8388
8389static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8390 if (!ExitCount)
8391 return 0;
8392
8393 ConstantInt *ExitConst = ExitCount->getValue();
8394
8395 // Guard against huge trip counts.
8396 if (ExitConst->getValue().getActiveBits() > 32)
8397 return 0;
8398
8399 // In case of integer overflow, this returns 0, which is correct.
8400 return ((unsigned)ExitConst->getZExtValue()) + 1;
8401}
8402
8404 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
8405 return getConstantTripCount(ExitCount);
8406}
8407
8408unsigned
8410 const BasicBlock *ExitingBlock) {
8411 assert(ExitingBlock && "Must pass a non-null exiting block!");
8412 assert(L->isLoopExiting(ExitingBlock) &&
8413 "Exiting block must actually branch out of the loop!");
8414 const SCEVConstant *ExitCount =
8415 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
8416 return getConstantTripCount(ExitCount);
8417}
8418
8420 const Loop *L, SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8421
8422 const auto *MaxExitCount =
8423 Predicates ? getPredicatedConstantMaxBackedgeTakenCount(L, *Predicates)
8425 return getConstantTripCount(dyn_cast<SCEVConstant>(MaxExitCount));
8426}
8427
8429 SmallVector<BasicBlock *, 8> ExitingBlocks;
8430 L->getExitingBlocks(ExitingBlocks);
8431
8432 // An exit with an uncomputable exit count makes the result 1.
8433 if (ExitingBlocks.empty() ||
8434 any_of(ExitingBlocks, [this, L](BasicBlock *ExitingBB) {
8435 return isa<SCEVCouldNotCompute>(getExitCount(L, ExitingBB));
8436 }))
8437 return 1;
8438
8439 LoopGuards Guards = LoopGuards::collect(L, *this);
8440 unsigned Res = 0;
8441 for (BasicBlock *ExitingBB : ExitingBlocks)
8442 Res = std::gcd(
8443 Res, getSmallConstantTripMultiple(getExitCount(L, ExitingBB), Guards));
8444 return Res;
8445}
8446
8447unsigned
8449 const LoopGuards &Guards) {
8450 assert(!isa<SCEVCouldNotCompute>(ExitCount) && "Must be computable!");
8451
8452 // Get the trip count
8453 const SCEV *TCExpr =
8454 getTripCountFromExitCount(applyLoopGuards(ExitCount, Guards));
8455
8456 APInt Multiple = getNonZeroConstantMultiple(TCExpr);
8457 // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8458 // the greatest power of 2 divisor less than 2^32.
8459 return Multiple.getActiveBits() > 32
8460 ? 1U << std::min(31U, Multiple.countTrailingZeros())
8461 : (unsigned)Multiple.getZExtValue();
8462}
8463
8465 const SCEV *ExitCount) {
8466 if (isa<SCEVCouldNotCompute>(ExitCount))
8467 return 1;
8468
8469 return getSmallConstantTripMultiple(ExitCount, LoopGuards::collect(L, *this));
8470}
8471
8472/// Returns the largest constant divisor of the trip count of this loop as a
8473/// normal unsigned value, if possible. This means that the actual trip count is
8474/// always a multiple of the returned value (don't forget the trip count could
8475/// very well be zero as well!).
8476///
8477/// Returns 1 if the trip count is unknown or not guaranteed to be the
8478/// multiple of a constant (which is also the case if the trip count is simply
8479/// constant, use getSmallConstantTripCount for that case), Will also return 1
8480/// if the trip count is very large (>= 2^32).
8481///
8482/// As explained in the comments for getSmallConstantTripCount, this assumes
8483/// that control exits the loop via ExitingBlock.
8484unsigned
8486 const BasicBlock *ExitingBlock) {
8487 assert(ExitingBlock && "Must pass a non-null exiting block!");
8488 assert(L->isLoopExiting(ExitingBlock) &&
8489 "Exiting block must actually branch out of the loop!");
8490 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8491 return getSmallConstantTripMultiple(L, ExitCount);
8492}
8493
8495 const BasicBlock *ExitingBlock,
8496 ExitCountKind Kind) {
8497 switch (Kind) {
8498 case Exact:
8499 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8500 case SymbolicMaximum:
8501 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8502 case ConstantMaximum:
8503 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8504 };
8505 llvm_unreachable("Invalid ExitCountKind!");
8506}
8507
8509 const Loop *L, const BasicBlock *ExitingBlock,
8511 switch (Kind) {
8512 case Exact:
8513 return getPredicatedBackedgeTakenInfo(L).getExact(ExitingBlock, this,
8514 Predicates);
8515 case SymbolicMaximum:
8516 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this,
8517 Predicates);
8518 case ConstantMaximum:
8519 return getPredicatedBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this,
8520 Predicates);
8521 };
8522 llvm_unreachable("Invalid ExitCountKind!");
8523}
8524
8527 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8528}
8529
8531 ExitCountKind Kind) {
8532 switch (Kind) {
8533 case Exact:
8534 return getBackedgeTakenInfo(L).getExact(L, this);
8535 case ConstantMaximum:
8536 return getBackedgeTakenInfo(L).getConstantMax(this);
8537 case SymbolicMaximum:
8538 return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8539 };
8540 llvm_unreachable("Invalid ExitCountKind!");
8541}
8542
8545 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(L, this, &Preds);
8546}
8547
8550 return getPredicatedBackedgeTakenInfo(L).getConstantMax(this, &Preds);
8551}
8552
8554 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8555}
8556
8557/// Push PHI nodes in the header of the given loop onto the given Worklist.
8558static void PushLoopPHIs(const Loop *L,
8561 BasicBlock *Header = L->getHeader();
8562
8563 // Push all Loop-header PHIs onto the Worklist stack.
8564 for (PHINode &PN : Header->phis())
8565 if (Visited.insert(&PN).second)
8566 Worklist.push_back(&PN);
8567}
8568
8569ScalarEvolution::BackedgeTakenInfo &
8570ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8571 auto &BTI = getBackedgeTakenInfo(L);
8572 if (BTI.hasFullInfo())
8573 return BTI;
8574
8575 auto Pair = PredicatedBackedgeTakenCounts.try_emplace(L);
8576
8577 if (!Pair.second)
8578 return Pair.first->second;
8579
8580 BackedgeTakenInfo Result =
8581 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8582
8583 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8584}
8585
8586ScalarEvolution::BackedgeTakenInfo &
8587ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8588 // Initially insert an invalid entry for this loop. If the insertion
8589 // succeeds, proceed to actually compute a backedge-taken count and
8590 // update the value. The temporary CouldNotCompute value tells SCEV
8591 // code elsewhere that it shouldn't attempt to request a new
8592 // backedge-taken count, which could result in infinite recursion.
8593 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8594 BackedgeTakenCounts.try_emplace(L);
8595 if (!Pair.second)
8596 return Pair.first->second;
8597
8598 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8599 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8600 // must be cleared in this scope.
8601 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8602
8603 // Now that we know more about the trip count for this loop, forget any
8604 // existing SCEV values for PHI nodes in this loop since they are only
8605 // conservative estimates made without the benefit of trip count
8606 // information. This invalidation is not necessary for correctness, and is
8607 // only done to produce more precise results.
8608 if (Result.hasAnyInfo()) {
8609 // Invalidate any expression using an addrec in this loop.
8610 SmallVector<SCEVUse, 8> ToForget;
8611 auto LoopUsersIt = LoopUsers.find(L);
8612 if (LoopUsersIt != LoopUsers.end())
8613 append_range(ToForget, LoopUsersIt->second);
8614 forgetMemoizedResults(ToForget);
8615
8616 // Invalidate constant-evolved loop header phis.
8617 for (PHINode &PN : L->getHeader()->phis())
8618 ConstantEvolutionLoopExitValue.erase(&PN);
8619 }
8620
8621 // Re-lookup the insert position, since the call to
8622 // computeBackedgeTakenCount above could result in a
8623 // recusive call to getBackedgeTakenInfo (on a different
8624 // loop), which would invalidate the iterator computed
8625 // earlier.
8626 return BackedgeTakenCounts.find(L)->second = std::move(Result);
8627}
8628
8630 // This method is intended to forget all info about loops. It should
8631 // invalidate caches as if the following happened:
8632 // - The trip counts of all loops have changed arbitrarily
8633 // - Every llvm::Value has been updated in place to produce a different
8634 // result.
8635 BackedgeTakenCounts.clear();
8636 PredicatedBackedgeTakenCounts.clear();
8637 BECountUsers.clear();
8638 LoopPropertiesCache.clear();
8639 ConstantEvolutionLoopExitValue.clear();
8640 ValueExprMap.clear();
8641 ValuesAtScopes.clear();
8642 ValuesAtScopesUsers.clear();
8643 LoopDispositions.clear();
8644 BlockDispositions.clear();
8645 UnsignedRanges.clear();
8646 SignedRanges.clear();
8647 ExprValueMap.clear();
8648 HasRecMap.clear();
8649 ConstantMultipleCache.clear();
8650 PredicatedSCEVRewrites.clear();
8651 FoldCache.clear();
8652 FoldCacheUser.clear();
8653}
8654void ScalarEvolution::visitAndClearUsers(
8657 SmallVectorImpl<SCEVUse> &ToForget) {
8658 while (!Worklist.empty()) {
8659 Instruction *I = Worklist.pop_back_val();
8660 if (!isSCEVable(I->getType()) && !isa<WithOverflowInst>(I))
8661 continue;
8662
8664 ValueExprMap.find_as(static_cast<Value *>(I));
8665 if (It != ValueExprMap.end()) {
8666 ToForget.push_back(It->second);
8667 eraseValueFromMap(It->first);
8668 if (PHINode *PN = dyn_cast<PHINode>(I))
8669 ConstantEvolutionLoopExitValue.erase(PN);
8670 }
8671
8672 PushDefUseChildren(I, Worklist, Visited);
8673 }
8674}
8675
8677 SmallVector<const Loop *, 16> LoopWorklist(1, L);
8680 SmallVector<SCEVUse, 16> ToForget;
8681
8682 // Iterate over all the loops and sub-loops to drop SCEV information.
8683 while (!LoopWorklist.empty()) {
8684 auto *CurrL = LoopWorklist.pop_back_val();
8685
8686 // Drop any stored trip count value.
8687 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8688 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8689
8690 // Drop information about predicated SCEV rewrites for this loop.
8691 PredicatedSCEVRewrites.remove_if(
8692 [&](const auto &Entry) { return Entry.first.second == CurrL; });
8693
8694 auto LoopUsersItr = LoopUsers.find(CurrL);
8695 if (LoopUsersItr != LoopUsers.end())
8696 llvm::append_range(ToForget, LoopUsersItr->second);
8697
8698 // Drop information about expressions based on loop-header PHIs.
8699 PushLoopPHIs(CurrL, Worklist, Visited);
8700 visitAndClearUsers(Worklist, Visited, ToForget);
8701
8702 LoopPropertiesCache.erase(CurrL);
8703 // Forget all contained loops too, to avoid dangling entries in the
8704 // ValuesAtScopes map.
8705 LoopWorklist.append(CurrL->begin(), CurrL->end());
8706 }
8707 forgetMemoizedResults(ToForget);
8708}
8709
8711 forgetLoop(L->getOutermostLoop());
8712}
8713
8716 if (!I) return;
8717
8718 // Drop information about expressions based on loop-header PHIs.
8721 SmallVector<SCEVUse, 8> ToForget;
8722 Worklist.push_back(I);
8723 Visited.insert(I);
8724 visitAndClearUsers(Worklist, Visited, ToForget);
8725
8726 forgetMemoizedResults(ToForget);
8727}
8728
8732 SmallVector<SCEVUse, 8> ToForget;
8733 for (Value *V : Values)
8734 if (auto *I = dyn_cast<Instruction>(V))
8735 if (Visited.insert(I).second)
8736 Worklist.push_back(I);
8737 visitAndClearUsers(Worklist, Visited, ToForget);
8738
8739 forgetMemoizedResults(ToForget);
8740}
8741
8743 // If SCEV looked through a trivial LCSSA phi node, we might have SCEV's
8744 // directly using a SCEVUnknown/SCEVAddRec defined in the loop. After an
8745 // extra predecessor is added, this is no longer valid. Find all Unknowns and
8746 // AddRecs defined in the loop and invalidate any SCEV's making use of them.
8747 auto InvalidateValue = [&](Value *Val) {
8748 if (!isSCEVable(Val->getType()))
8749 return;
8750 if (const SCEV *S = getExistingSCEV(Val)) {
8751 struct InvalidationRootCollector {
8752 Loop *L;
8754
8755 InvalidationRootCollector(Loop *L) : L(L) {}
8756
8757 bool follow(const SCEV *S) {
8758 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
8759 if (auto *I = dyn_cast<Instruction>(SU->getValue()))
8760 if (L->contains(I))
8761 Roots.push_back(S);
8762 } else if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
8763 if (L->contains(AddRec->getLoop()))
8764 Roots.push_back(S);
8765 }
8766 return true;
8767 }
8768 bool isDone() const { return false; }
8769 };
8770
8771 InvalidationRootCollector C(L);
8772 visitAll(S, C);
8773 forgetMemoizedResults(C.Roots);
8774 }
8775 };
8776
8777 InvalidateValue(V);
8778
8779 // If V has a non-SCEV-able type (e.g. {i64, i1} from a with.overflow
8780 // intrinsic), its users (e.g. extractvalue) may have stale SCEV
8781 // expressions referencing loop-internal values.
8782 if (!isSCEVable(V->getType()) &&
8783 any_of(V->incoming_values(), IsaPred<WithOverflowInst>))
8784 for (User *U : V->users())
8785 InvalidateValue(U);
8786 // Also perform the normal invalidation.
8787 forgetValue(V);
8788}
8789
8790void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8791
8793 // Unless a specific value is passed to invalidation, completely clear both
8794 // caches.
8795 if (!V) {
8796 BlockDispositions.clear();
8797 LoopDispositions.clear();
8798 return;
8799 }
8800
8801 if (!isSCEVable(V->getType()))
8802 return;
8803
8804 const SCEV *S = getExistingSCEV(V);
8805 if (!S)
8806 return;
8807
8808 // Invalidate the block and loop dispositions cached for S. Dispositions of
8809 // S's users may change if S's disposition changes (i.e. a user may change to
8810 // loop-invariant, if S changes to loop invariant), so also invalidate
8811 // dispositions of S's users recursively.
8812 SmallVector<SCEVUse, 8> Worklist = {S};
8814 while (!Worklist.empty()) {
8815 const SCEV *Curr = Worklist.pop_back_val();
8816 bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8817 bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8818 if (!LoopDispoRemoved && !BlockDispoRemoved)
8819 continue;
8820 auto Users = SCEVUsers.find(Curr);
8821 if (Users != SCEVUsers.end())
8822 for (const auto *User : Users->second)
8823 if (Seen.insert(User).second)
8824 Worklist.push_back(User);
8825 }
8826}
8827
8828/// Get the exact loop backedge taken count considering all loop exits. A
8829/// computable result can only be returned for loops with all exiting blocks
8830/// dominating the latch. howFarToZero assumes that the limit of each loop test
8831/// is never skipped. This is a valid assumption as long as the loop exits via
8832/// that test. For precise results, it is the caller's responsibility to specify
8833/// the relevant loop exiting block using getExact(ExitingBlock, SE).
8834const SCEV *ScalarEvolution::BackedgeTakenInfo::getExact(
8835 const Loop *L, ScalarEvolution *SE,
8837 // If any exits were not computable, the loop is not computable.
8838 if (!isComplete() || ExitNotTaken.empty())
8839 return SE->getCouldNotCompute();
8840
8841 const BasicBlock *Latch = L->getLoopLatch();
8842 // All exiting blocks we have collected must dominate the only backedge.
8843 if (!Latch)
8844 return SE->getCouldNotCompute();
8845
8846 // All exiting blocks we have gathered dominate loop's latch, so exact trip
8847 // count is simply a minimum out of all these calculated exit counts.
8849 for (const auto &ENT : ExitNotTaken) {
8850 const SCEV *BECount = ENT.ExactNotTaken;
8851 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8852 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8853 "We should only have known counts for exiting blocks that dominate "
8854 "latch!");
8855
8856 Ops.push_back(BECount);
8857
8858 if (Preds)
8859 append_range(*Preds, ENT.Predicates);
8860
8861 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8862 "Predicate should be always true!");
8863 }
8864
8865 // If an earlier exit exits on the first iteration (exit count zero), then
8866 // a later poison exit count should not propagate into the result. This are
8867 // exactly the semantics provided by umin_seq.
8868 return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8869}
8870
8871const ScalarEvolution::ExitNotTakenInfo *
8872ScalarEvolution::BackedgeTakenInfo::getExitNotTaken(
8873 const BasicBlock *ExitingBlock,
8874 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8875 for (const auto &ENT : ExitNotTaken)
8876 if (ENT.ExitingBlock == ExitingBlock) {
8877 if (ENT.hasAlwaysTruePredicate())
8878 return &ENT;
8879 else if (Predicates) {
8880 append_range(*Predicates, ENT.Predicates);
8881 return &ENT;
8882 }
8883 }
8884
8885 return nullptr;
8886}
8887
8888/// getConstantMax - Get the constant max backedge taken count for the loop.
8889const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8890 ScalarEvolution *SE,
8891 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8892 if (!getConstantMax())
8893 return SE->getCouldNotCompute();
8894
8895 for (const auto &ENT : ExitNotTaken)
8896 if (!ENT.hasAlwaysTruePredicate()) {
8897 if (!Predicates)
8898 return SE->getCouldNotCompute();
8899 append_range(*Predicates, ENT.Predicates);
8900 }
8901
8902 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8903 isa<SCEVConstant>(getConstantMax())) &&
8904 "No point in having a non-constant max backedge taken count!");
8905 return getConstantMax();
8906}
8907
8908const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8909 const Loop *L, ScalarEvolution *SE,
8910 SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8911 if (!SymbolicMax) {
8912 // Form an expression for the maximum exit count possible for this loop. We
8913 // merge the max and exact information to approximate a version of
8914 // getConstantMaxBackedgeTakenCount which isn't restricted to just
8915 // constants.
8916 SmallVector<SCEVUse, 4> ExitCounts;
8917
8918 for (const auto &ENT : ExitNotTaken) {
8919 const SCEV *ExitCount = ENT.SymbolicMaxNotTaken;
8920 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
8921 assert(SE->DT.dominates(ENT.ExitingBlock, L->getLoopLatch()) &&
8922 "We should only have known counts for exiting blocks that "
8923 "dominate latch!");
8924 ExitCounts.push_back(ExitCount);
8925 if (Predicates)
8926 append_range(*Predicates, ENT.Predicates);
8927
8928 assert((Predicates || ENT.hasAlwaysTruePredicate()) &&
8929 "Predicate should be always true!");
8930 }
8931 }
8932 if (ExitCounts.empty())
8933 SymbolicMax = SE->getCouldNotCompute();
8934 else
8935 SymbolicMax =
8936 SE->getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
8937 }
8938 return SymbolicMax;
8939}
8940
8941bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8942 ScalarEvolution *SE) const {
8943 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8944 return !ENT.hasAlwaysTruePredicate();
8945 };
8946 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8947}
8948
8951
8953 const SCEV *E, const SCEV *ConstantMaxNotTaken,
8954 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8958 // If we prove the max count is zero, so is the symbolic bound. This happens
8959 // in practice due to differences in a) how context sensitive we've chosen
8960 // to be and b) how we reason about bounds implied by UB.
8961 if (ConstantMaxNotTaken->isZero()) {
8962 this->ExactNotTaken = E = ConstantMaxNotTaken;
8963 this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
8964 }
8965
8968 "Exact is not allowed to be less precise than Constant Max");
8971 "Exact is not allowed to be less precise than Symbolic Max");
8974 "Symbolic Max is not allowed to be less precise than Constant Max");
8977 "No point in having a non-constant max backedge taken count!");
8979 for (const auto PredList : PredLists)
8980 for (const auto *P : PredList) {
8981 if (SeenPreds.contains(P))
8982 continue;
8983 assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!");
8984 SeenPreds.insert(P);
8985 Predicates.push_back(P);
8986 }
8987 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8988 "Backedge count should be int");
8990 !ConstantMaxNotTaken->getType()->isPointerTy()) &&
8991 "Max backedge count should be int");
8992}
8993
9001
9002/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
9003/// computable exit into a persistent ExitNotTakenInfo array.
9004ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
9006 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
9007 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
9008 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
9009
9010 ExitNotTaken.reserve(ExitCounts.size());
9011 std::transform(ExitCounts.begin(), ExitCounts.end(),
9012 std::back_inserter(ExitNotTaken),
9013 [&](const EdgeExitInfo &EEI) {
9014 BasicBlock *ExitBB = EEI.first;
9015 const ExitLimit &EL = EEI.second;
9016 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
9017 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
9018 EL.Predicates);
9019 });
9020 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
9021 isa<SCEVConstant>(ConstantMax)) &&
9022 "No point in having a non-constant max backedge taken count!");
9023}
9024
9025/// Compute the number of times the backedge of the specified loop will execute.
9026ScalarEvolution::BackedgeTakenInfo
9027ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
9028 bool AllowPredicates) {
9029 SmallVector<BasicBlock *, 8> ExitingBlocks;
9030 L->getExitingBlocks(ExitingBlocks);
9031
9032 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
9033
9035 bool CouldComputeBECount = true;
9036 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
9037 const SCEV *MustExitMaxBECount = nullptr;
9038 const SCEV *MayExitMaxBECount = nullptr;
9039 bool MustExitMaxOrZero = false;
9040 bool IsOnlyExit = ExitingBlocks.size() == 1;
9041
9042 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
9043 // and compute maxBECount.
9044 // Do a union of all the predicates here.
9045 for (BasicBlock *ExitBB : ExitingBlocks) {
9046 // We canonicalize untaken exits to br (constant), ignore them so that
9047 // proving an exit untaken doesn't negatively impact our ability to reason
9048 // about the loop as whole.
9049 if (auto *BI = dyn_cast<CondBrInst>(ExitBB->getTerminator()))
9050 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
9051 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9052 if (ExitIfTrue == CI->isZero())
9053 continue;
9054 }
9055
9056 ExitLimit EL = computeExitLimit(L, ExitBB, IsOnlyExit, AllowPredicates);
9057
9058 assert((AllowPredicates || EL.Predicates.empty()) &&
9059 "Predicated exit limit when predicates are not allowed!");
9060
9061 // 1. For each exit that can be computed, add an entry to ExitCounts.
9062 // CouldComputeBECount is true only if all exits can be computed.
9063 if (EL.ExactNotTaken != getCouldNotCompute())
9064 ++NumExitCountsComputed;
9065 else
9066 // We couldn't compute an exact value for this exit, so
9067 // we won't be able to compute an exact value for the loop.
9068 CouldComputeBECount = false;
9069 // Remember exit count if either exact or symbolic is known. Because
9070 // Exact always implies symbolic, only check symbolic.
9071 if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
9072 ExitCounts.emplace_back(ExitBB, EL);
9073 else {
9074 assert(EL.ExactNotTaken == getCouldNotCompute() &&
9075 "Exact is known but symbolic isn't?");
9076 ++NumExitCountsNotComputed;
9077 }
9078
9079 // 2. Derive the loop's MaxBECount from each exit's max number of
9080 // non-exiting iterations. Partition the loop exits into two kinds:
9081 // LoopMustExits and LoopMayExits.
9082 //
9083 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
9084 // is a LoopMayExit. If any computable LoopMustExit is found, then
9085 // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
9086 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
9087 // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
9088 // any
9089 // computable EL.ConstantMaxNotTaken.
9090 if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
9091 DT.dominates(ExitBB, Latch)) {
9092 if (!MustExitMaxBECount) {
9093 MustExitMaxBECount = EL.ConstantMaxNotTaken;
9094 MustExitMaxOrZero = EL.MaxOrZero;
9095 } else {
9096 MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
9097 EL.ConstantMaxNotTaken);
9098 }
9099 } else if (MayExitMaxBECount != getCouldNotCompute()) {
9100 if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
9101 MayExitMaxBECount = EL.ConstantMaxNotTaken;
9102 else {
9103 MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
9104 EL.ConstantMaxNotTaken);
9105 }
9106 }
9107 }
9108 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
9109 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
9110 // The loop backedge will be taken the maximum or zero times if there's
9111 // a single exit that must be taken the maximum or zero times.
9112 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
9113
9114 // Remember which SCEVs are used in exit limits for invalidation purposes.
9115 // We only care about non-constant SCEVs here, so we can ignore
9116 // EL.ConstantMaxNotTaken
9117 // and MaxBECount, which must be SCEVConstant.
9118 for (const auto &Pair : ExitCounts) {
9119 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
9120 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
9121 if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
9122 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
9123 {L, AllowPredicates});
9124 }
9125 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
9126 MaxBECount, MaxOrZero);
9127}
9128
9129ScalarEvolution::ExitLimit
9130ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
9131 bool IsOnlyExit, bool AllowPredicates) {
9132 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
9133 // If our exiting block does not dominate the latch, then its connection with
9134 // loop's exit limit may be far from trivial.
9135 const BasicBlock *Latch = L->getLoopLatch();
9136 if (!Latch || !DT.dominates(ExitingBlock, Latch))
9137 return getCouldNotCompute();
9138
9139 Instruction *Term = ExitingBlock->getTerminator();
9140 if (CondBrInst *BI = dyn_cast<CondBrInst>(Term)) {
9141 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9142 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
9143 "It should have one successor in loop and one exit block!");
9144 // Proceed to the next level to examine the exit condition expression.
9145 return computeExitLimitFromCond(L, BI->getCondition(), ExitIfTrue,
9146 /*ControlsOnlyExit=*/IsOnlyExit,
9147 AllowPredicates);
9148 }
9149
9150 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
9151 // For switch, make sure that there is a single exit from the loop.
9152 BasicBlock *Exit = nullptr;
9153 for (auto *SBB : successors(ExitingBlock))
9154 if (!L->contains(SBB)) {
9155 if (Exit) // Multiple exit successors.
9156 return getCouldNotCompute();
9157 Exit = SBB;
9158 }
9159 assert(Exit && "Exiting block must have at least one exit");
9160 return computeExitLimitFromSingleExitSwitch(
9161 L, SI, Exit, /*ControlsOnlyExit=*/IsOnlyExit);
9162 }
9163
9164 return getCouldNotCompute();
9165}
9166
9168 const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9169 bool AllowPredicates) {
9170 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
9171 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
9172 ControlsOnlyExit, AllowPredicates);
9173}
9174
9175std::optional<ScalarEvolution::ExitLimit>
9176ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
9177 bool ExitIfTrue, bool ControlsOnlyExit,
9178 bool AllowPredicates) {
9179 (void)this->L;
9180 (void)this->ExitIfTrue;
9181 (void)this->AllowPredicates;
9182
9183 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9184 this->AllowPredicates == AllowPredicates &&
9185 "Variance in assumed invariant key components!");
9186 auto Itr = TripCountMap.find({ExitCond, ControlsOnlyExit});
9187 if (Itr == TripCountMap.end())
9188 return std::nullopt;
9189 return Itr->second;
9190}
9191
9192void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
9193 bool ExitIfTrue,
9194 bool ControlsOnlyExit,
9195 bool AllowPredicates,
9196 const ExitLimit &EL) {
9197 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9198 this->AllowPredicates == AllowPredicates &&
9199 "Variance in assumed invariant key components!");
9200
9201 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsOnlyExit}, EL});
9202 assert(InsertResult.second && "Expected successful insertion!");
9203 (void)InsertResult;
9204 (void)ExitIfTrue;
9205}
9206
9207ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
9208 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9209 bool ControlsOnlyExit, bool AllowPredicates) {
9210
9211 if (auto MaybeEL = Cache.find(L, ExitCond, ExitIfTrue, ControlsOnlyExit,
9212 AllowPredicates))
9213 return *MaybeEL;
9214
9215 ExitLimit EL = computeExitLimitFromCondImpl(
9216 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates);
9217 Cache.insert(L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates, EL);
9218 return EL;
9219}
9220
9221ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
9222 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9223 bool ControlsOnlyExit, bool AllowPredicates) {
9224 // Handle BinOp conditions (And, Or).
9225 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
9226 Cache, L, ExitCond, ExitIfTrue, AllowPredicates))
9227 return *LimitFromBinOp;
9228
9229 // With an icmp, it may be feasible to compute an exact backedge-taken count.
9230 // Proceed to the next level to examine the icmp.
9231 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
9232 ExitLimit EL =
9233 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsOnlyExit);
9234 if (EL.hasFullInfo() || !AllowPredicates)
9235 return EL;
9236
9237 // Try again, but use SCEV predicates this time.
9238 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue,
9239 ControlsOnlyExit,
9240 /*AllowPredicates=*/true);
9241 }
9242
9243 // Check for a constant condition. These are normally stripped out by
9244 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
9245 // preserve the CFG and is temporarily leaving constant conditions
9246 // in place.
9247 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
9248 if (ExitIfTrue == !CI->getZExtValue())
9249 // The backedge is always taken.
9250 return getCouldNotCompute();
9251 // The backedge is never taken.
9252 return getZero(CI->getType());
9253 }
9254
9255 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
9256 // with a constant step, we can form an equivalent icmp predicate and figure
9257 // out how many iterations will be taken before we exit.
9258 const WithOverflowInst *WO;
9259 const APInt *C;
9260 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
9261 match(WO->getRHS(), m_APInt(C))) {
9262 ConstantRange NWR =
9264 WO->getNoWrapKind());
9265 CmpInst::Predicate Pred;
9266 APInt NewRHSC, Offset;
9267 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
9268 if (!ExitIfTrue)
9269 Pred = ICmpInst::getInversePredicate(Pred);
9270 auto *LHS = getSCEV(WO->getLHS());
9271 if (Offset != 0)
9273 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
9274 ControlsOnlyExit, AllowPredicates);
9275 if (EL.hasAnyInfo())
9276 return EL;
9277 }
9278
9279 // If it's not an integer or pointer comparison then compute it the hard way.
9280 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9281}
9282
9283std::optional<ScalarEvolution::ExitLimit>
9284ScalarEvolution::computeExitLimitFromCondFromBinOp(ExitLimitCacheTy &Cache,
9285 const Loop *L,
9286 Value *ExitCond,
9287 bool ExitIfTrue,
9288 bool AllowPredicates) {
9289 // Check if the controlling expression for this loop is an And or Or.
9290 Value *Op0, *Op1;
9291 bool IsAnd;
9292 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
9293 IsAnd = true;
9294 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
9295 IsAnd = false;
9296 else
9297 return std::nullopt;
9298
9299 // A sub-condition of a non-trivial binop never solely controls the exit,
9300 // whether we exit always depends on both conditions.
9301 ExitLimit EL0 = computeExitLimitFromCondCached(
9302 Cache, L, Op0, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9303 ExitLimit EL1 = computeExitLimitFromCondCached(
9304 Cache, L, Op1, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9305
9306 // EitherMayExit is true in these two cases:
9307 // br (and Op0 Op1), loop, exit
9308 // br (or Op0 Op1), exit, loop
9309 bool EitherMayExit = IsAnd ^ ExitIfTrue;
9310
9311 const SCEV *BECount = getCouldNotCompute();
9312 const SCEV *ConstantMaxBECount = getCouldNotCompute();
9313 const SCEV *SymbolicMaxBECount = getCouldNotCompute();
9314 if (EitherMayExit) {
9315 bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
9316 // Both conditions must be same for the loop to continue executing.
9317 // Choose the less conservative count.
9318 if (EL0.ExactNotTaken != getCouldNotCompute() &&
9319 EL1.ExactNotTaken != getCouldNotCompute()) {
9320 BECount = getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken,
9321 UseSequentialUMin);
9322 }
9323 if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
9324 ConstantMaxBECount = EL1.ConstantMaxNotTaken;
9325 else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
9326 ConstantMaxBECount = EL0.ConstantMaxNotTaken;
9327 else
9328 ConstantMaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
9329 EL1.ConstantMaxNotTaken);
9330 if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
9331 SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
9332 else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
9333 SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
9334 else
9335 SymbolicMaxBECount = getUMinFromMismatchedTypes(
9336 EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
9337 } else {
9338 // Both conditions must be same at the same time for the loop to exit.
9339 // For now, be conservative.
9340 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
9341 BECount = EL0.ExactNotTaken;
9342 }
9343
9344 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
9345 // to be more aggressive when computing BECount than when computing
9346 // ConstantMaxBECount. In these cases it is possible for EL0.ExactNotTaken
9347 // and
9348 // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
9349 // EL1.ConstantMaxNotTaken to not.
9350 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
9351 !isa<SCEVCouldNotCompute>(BECount))
9352 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
9353 if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
9354 SymbolicMaxBECount =
9355 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
9356 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
9357 {ArrayRef(EL0.Predicates), ArrayRef(EL1.Predicates)});
9358}
9359
9360ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9361 const Loop *L, ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9362 bool AllowPredicates) {
9363 // If the condition was exit on true, convert the condition to exit on false
9364 CmpPredicate Pred;
9365 if (!ExitIfTrue)
9366 Pred = ExitCond->getCmpPredicate();
9367 else
9368 Pred = ExitCond->getInverseCmpPredicate();
9369 const ICmpInst::Predicate OriginalPred = Pred;
9370
9371 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
9372 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
9373
9374 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsOnlyExit,
9375 AllowPredicates);
9376 if (EL.hasAnyInfo())
9377 return EL;
9378
9379 auto *ExhaustiveCount =
9380 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9381
9382 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
9383 return ExhaustiveCount;
9384
9385 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
9386 ExitCond->getOperand(1), L, OriginalPred);
9387}
9388ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9389 const Loop *L, CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS,
9390 bool ControlsOnlyExit, bool AllowPredicates) {
9391
9392 // Try to evaluate any dependencies out of the loop.
9393 LHS = getSCEVAtScope(LHS, L);
9394 RHS = getSCEVAtScope(RHS, L);
9395
9396 // At this point, we would like to compute how many iterations of the
9397 // loop the predicate will return true for these inputs.
9398 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
9399 // If there is a loop-invariant, force it into the RHS.
9400 std::swap(LHS, RHS);
9402 }
9403
9404 bool ControllingFiniteLoop = ControlsOnlyExit && loopHasNoAbnormalExits(L) &&
9406 // Simplify the operands before analyzing them.
9407 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0);
9408
9409 // If we have a comparison of a chrec against a constant, try to use value
9410 // ranges to answer this query.
9411 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
9412 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
9413 if (AddRec->getLoop() == L) {
9414 // Form the constant range.
9415 ConstantRange CompRange =
9416 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
9417
9418 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
9419 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
9420 }
9421
9422 // If this loop must exit based on this condition (or execute undefined
9423 // behaviour), see if we can improve wrap flags. This is essentially
9424 // a must execute style proof.
9425 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
9426 // If we can prove the test sequence produced must repeat the same values
9427 // on self-wrap of the IV, then we can infer that IV doesn't self wrap
9428 // because if it did, we'd have an infinite (undefined) loop.
9429 // TODO: We can peel off any functions which are invertible *in L*. Loop
9430 // invariant terms are effectively constants for our purposes here.
9431 SCEVUse InnerLHS = LHS;
9432 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
9433 InnerLHS = ZExt->getOperand();
9434 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS);
9435 AR && !AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
9436 isKnownToBeAPowerOfTwo(AR->getStepRecurrence(*this), /*OrZero=*/true,
9437 /*OrNegative=*/true)) {
9438 auto Flags = AR->getNoWrapFlags();
9439 Flags = setFlags(Flags, SCEV::FlagNW);
9442 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9443 }
9444
9445 // For a slt/ult condition with a positive step, can we prove nsw/nuw?
9446 // From no-self-wrap, this follows trivially from the fact that every
9447 // (un)signed-wrapped, but not self-wrapped value must be LT than the
9448 // last value before (un)signed wrap. Since we know that last value
9449 // didn't exit, nor will any smaller one.
9450 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT) {
9451 auto WrapType = Pred == ICmpInst::ICMP_SLT ? SCEV::FlagNSW : SCEV::FlagNUW;
9452 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9453 AR && AR->getLoop() == L && AR->isAffine() &&
9454 !AR->getNoWrapFlags(WrapType) && AR->hasNoSelfWrap() &&
9455 isKnownPositive(AR->getStepRecurrence(*this))) {
9456 auto Flags = AR->getNoWrapFlags();
9457 Flags = setFlags(Flags, WrapType);
9460 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9461 }
9462 }
9463 }
9464
9465 switch (Pred) {
9466 case ICmpInst::ICMP_NE: { // while (X != Y)
9467 // Convert to: while (X-Y != 0)
9468 if (LHS->getType()->isPointerTy()) {
9471 return LHS;
9472 }
9473 if (RHS->getType()->isPointerTy()) {
9476 return RHS;
9477 }
9478 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit,
9479 AllowPredicates);
9480 if (EL.hasAnyInfo())
9481 return EL;
9482 break;
9483 }
9484 case ICmpInst::ICMP_EQ: { // while (X == Y)
9485 // Convert to: while (X-Y == 0)
9486 if (LHS->getType()->isPointerTy()) {
9489 return LHS;
9490 }
9491 if (RHS->getType()->isPointerTy()) {
9494 return RHS;
9495 }
9496 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
9497 if (EL.hasAnyInfo()) return EL;
9498 break;
9499 }
9500 case ICmpInst::ICMP_SLE:
9501 case ICmpInst::ICMP_ULE:
9502 // Since the loop is finite, an invariant RHS cannot include the boundary
9503 // value, otherwise it would loop forever.
9504 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9505 !isLoopInvariant(RHS, L)) {
9506 // Otherwise, perform the addition in a wider type, to avoid overflow.
9507 // If the LHS is an addrec with the appropriate nowrap flag, the
9508 // extension will be sunk into it and the exit count can be analyzed.
9509 auto *OldType = dyn_cast<IntegerType>(LHS->getType());
9510 if (!OldType)
9511 break;
9512 // Prefer doubling the bitwidth over adding a single bit to make it more
9513 // likely that we use a legal type.
9514 auto *NewType =
9515 Type::getIntNTy(OldType->getContext(), OldType->getBitWidth() * 2);
9516 if (ICmpInst::isSigned(Pred)) {
9517 LHS = getSignExtendExpr(LHS, NewType);
9518 RHS = getSignExtendExpr(RHS, NewType);
9519 } else {
9520 LHS = getZeroExtendExpr(LHS, NewType);
9521 RHS = getZeroExtendExpr(RHS, NewType);
9522 }
9523 }
9525 [[fallthrough]];
9526 case ICmpInst::ICMP_SLT:
9527 case ICmpInst::ICMP_ULT: { // while (X < Y)
9528 bool IsSigned = ICmpInst::isSigned(Pred);
9529 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9530 AllowPredicates);
9531 if (EL.hasAnyInfo())
9532 return EL;
9533 break;
9534 }
9535 case ICmpInst::ICMP_SGE:
9536 case ICmpInst::ICMP_UGE:
9537 // Since the loop is finite, an invariant RHS cannot include the boundary
9538 // value, otherwise it would loop forever.
9539 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9540 !isLoopInvariant(RHS, L))
9541 break;
9543 [[fallthrough]];
9544 case ICmpInst::ICMP_SGT:
9545 case ICmpInst::ICMP_UGT: { // while (X > Y)
9546 bool IsSigned = ICmpInst::isSigned(Pred);
9547 ExitLimit EL = howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9548 AllowPredicates);
9549 if (EL.hasAnyInfo())
9550 return EL;
9551 break;
9552 }
9553 default:
9554 break;
9555 }
9556
9557 return getCouldNotCompute();
9558}
9559
9560ScalarEvolution::ExitLimit
9561ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
9562 SwitchInst *Switch,
9563 BasicBlock *ExitingBlock,
9564 bool ControlsOnlyExit) {
9565 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
9566
9567 // Give up if the exit is the default dest of a switch.
9568 if (Switch->getDefaultDest() == ExitingBlock)
9569 return getCouldNotCompute();
9570
9571 assert(L->contains(Switch->getDefaultDest()) &&
9572 "Default case must not exit the loop!");
9573 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
9574 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
9575
9576 // while (X != Y) --> while (X-Y != 0)
9577 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit);
9578 if (EL.hasAnyInfo())
9579 return EL;
9580
9581 return getCouldNotCompute();
9582}
9583
9584static ConstantInt *
9586 ScalarEvolution &SE) {
9587 const SCEV *InVal = SE.getConstant(C);
9588 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
9590 "Evaluation of SCEV at constant didn't fold correctly?");
9591 return cast<SCEVConstant>(Val)->getValue();
9592}
9593
9594ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
9595 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
9596 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
9597 if (!RHS)
9598 return getCouldNotCompute();
9599
9600 const BasicBlock *Latch = L->getLoopLatch();
9601 if (!Latch)
9602 return getCouldNotCompute();
9603
9604 const BasicBlock *Predecessor = L->getLoopPredecessor();
9605 if (!Predecessor)
9606 return getCouldNotCompute();
9607
9608 // Return true if V is of the form "LHS `shift_op` <positive constant>".
9609 // Return LHS in OutLHS, shift_op in OutOpCode, and the shift amount in
9610 // OutShiftAmt.
9611 auto MatchPositiveShift = [](Value *V, Value *&OutLHS,
9612 Instruction::BinaryOps &OutOpCode,
9613 unsigned &OutShiftAmt) {
9614 using namespace PatternMatch;
9615
9616 ConstantInt *ShiftAmt;
9617 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9618 OutOpCode = Instruction::LShr;
9619 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9620 OutOpCode = Instruction::AShr;
9621 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9622 OutOpCode = Instruction::Shl;
9623 else
9624 return false;
9625
9626 uint64_t Amt = ShiftAmt->getValue().getLimitedValue();
9627 if (Amt == 0 || Amt >= OutLHS->getType()->getScalarSizeInBits())
9628 return false;
9629 OutShiftAmt = Amt;
9630 return true;
9631 };
9632
9633 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
9634 //
9635 // loop:
9636 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
9637 // %iv.shifted = lshr i32 %iv, <positive constant>
9638 //
9639 // Return true on a successful match. Return the corresponding PHI node (%iv
9640 // above) in PNOut, the opcode of the shift operation in OpCodeOut, and the
9641 // shift amount in ShiftAmtOut.
9642 auto MatchShiftRecurrence = [&](Value *V, PHINode *&PNOut,
9643 Instruction::BinaryOps &OpCodeOut,
9644 unsigned &ShiftAmtOut) {
9645 std::optional<Instruction::BinaryOps> PostShiftOpCode;
9646
9647 {
9649 Value *V;
9650 unsigned Amt;
9651
9652 // If we encounter a shift instruction, "peel off" the shift operation,
9653 // and remember that we did so. Later when we inspect %iv's backedge
9654 // value, we will make sure that the backedge value uses the same
9655 // operation.
9656 //
9657 // Note: the peeled shift operation does not have to be the same
9658 // instruction as the one feeding into the PHI's backedge value. We only
9659 // really care about it being the same *kind* of shift instruction --
9660 // that's all that is required for our later inferences to hold.
9661 if (MatchPositiveShift(LHS, V, OpC, Amt)) {
9662 PostShiftOpCode = OpC;
9663 LHS = V;
9664 }
9665 }
9666
9667 PNOut = dyn_cast<PHINode>(LHS);
9668 if (!PNOut || PNOut->getParent() != L->getHeader())
9669 return false;
9670
9671 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
9672 Value *OpLHS;
9673
9674 return
9675 // The backedge value for the PHI node must be a shift by a positive
9676 // amount
9677 MatchPositiveShift(BEValue, OpLHS, OpCodeOut, ShiftAmtOut) &&
9678
9679 // of the PHI node itself
9680 OpLHS == PNOut &&
9681
9682 // and the kind of shift should be match the kind of shift we peeled
9683 // off, if any.
9684 (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9685 };
9686
9687 PHINode *PN;
9689 unsigned ShiftAmt;
9690 if (!MatchShiftRecurrence(LHS, PN, OpCode, ShiftAmt))
9691 return getCouldNotCompute();
9692
9693 const DataLayout &DL = getDataLayout();
9694
9695 // The key rationale for this optimization is that for some kinds of shift
9696 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
9697 // within a finite number of iterations. If the condition guarding the
9698 // backedge (in the sense that the backedge is taken if the condition is true)
9699 // is false for the value the shift recurrence stabilizes to, then we know
9700 // that the backedge is taken only a finite number of times.
9701
9702 ConstantInt *StableValue = nullptr;
9703 switch (OpCode) {
9704 default:
9705 llvm_unreachable("Impossible case!");
9706
9707 case Instruction::AShr: {
9708 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
9709 // bitwidth(K) iterations.
9710 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
9711 KnownBits Known = computeKnownBits(FirstValue, DL, &AC,
9712 Predecessor->getTerminator(), &DT);
9713 auto *Ty = cast<IntegerType>(RHS->getType());
9714 if (Known.isNonNegative())
9715 StableValue = ConstantInt::get(Ty, 0);
9716 else if (Known.isNegative())
9717 StableValue = ConstantInt::get(Ty, -1, true);
9718 else
9719 return getCouldNotCompute();
9720
9721 break;
9722 }
9723 case Instruction::LShr:
9724 case Instruction::Shl:
9725 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
9726 // stabilize to 0 in at most bitwidth(K) iterations.
9727 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
9728 break;
9729 }
9730
9731 auto *Result =
9732 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
9733 assert(Result->getType()->isIntegerTy(1) &&
9734 "Otherwise cannot be an operand to a branch instruction");
9735
9736 if (Result->isNullValue()) {
9737 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9738 unsigned MaxBTC = BitWidth;
9739
9740 // For right-shift recurrences (lshr/ashr with non-negative start), we can
9741 // compute a tighter max backedge-taken count from the range of the start
9742 // value. After k shifts of ShiftAmt, value = start >> (k * ShiftAmt).
9743 // The value reaches 0 (the stable value) when k * ShiftAmt >=
9744 // activeBits(start), so max BTC = ceil(activeBits(maxStart) / ShiftAmt).
9745 if (OpCode == Instruction::LShr || OpCode == Instruction::AShr) {
9746 Value *StartValue = PN->getIncomingValueForBlock(Predecessor);
9747 const SCEV *StartSCEV = getSCEV(StartValue);
9748 APInt MaxStart = getUnsignedRangeMax(StartSCEV);
9749 if (MaxStart.isStrictlyPositive()) {
9750 unsigned ActiveBits = MaxStart.getActiveBits();
9751 unsigned RangeBTC = divideCeil(ActiveBits, ShiftAmt);
9752 MaxBTC = std::min(MaxBTC, RangeBTC);
9753 }
9754 }
9755
9756 const SCEV *UpperBound =
9758 return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
9759 }
9760
9761 return getCouldNotCompute();
9762}
9763
9764/// Return true if we can constant fold an instruction of the specified type,
9765/// assuming that all operands were constants.
9766static bool canConstantFold(const Instruction *I,
9767 const TargetLibraryInfo *TLI) {
9771 return true;
9772
9773 if (const CallInst *CI = dyn_cast<CallInst>(I))
9774 if (const Function *F = CI->getCalledFunction())
9775 return canConstantFoldCallTo(CI, F, TLI);
9776 return false;
9777}
9778
9779/// Determine whether this instruction can constant evolve within this loop
9780/// assuming its operands can all constant evolve.
9781static bool canConstantEvolve(Instruction *I, const Loop *L,
9782 const TargetLibraryInfo *TLI) {
9783 // An instruction outside of the loop can't be derived from a loop PHI.
9784 if (!L->contains(I)) return false;
9785
9786 if (isa<PHINode>(I)) {
9787 // We don't currently keep track of the control flow needed to evaluate
9788 // PHIs, so we cannot handle PHIs inside of loops.
9789 return L->getHeader() == I->getParent();
9790 }
9791
9792 // If we won't be able to constant fold this expression even if the operands
9793 // are constants, bail early.
9794 return canConstantFold(I, TLI);
9795}
9796
9797/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
9798/// recursing through each instruction operand until reaching a loop header phi.
9799static PHINode *
9802 const TargetLibraryInfo *TLI, unsigned Depth) {
9804 return nullptr;
9805
9806 // Otherwise, we can evaluate this instruction if all of its operands are
9807 // constant or derived from a PHI node themselves.
9808 PHINode *PHI = nullptr;
9809 for (Value *Op : UseInst->operands()) {
9810 if (isa<Constant>(Op)) continue;
9811
9813 if (!OpInst || !canConstantEvolve(OpInst, L, TLI))
9814 return nullptr;
9815
9816 PHINode *P = dyn_cast<PHINode>(OpInst);
9817 if (!P)
9818 // If this operand is already visited, reuse the prior result.
9819 // We may have P != PHI if this is the deepest point at which the
9820 // inconsistent paths meet.
9821 P = PHIMap.lookup(OpInst);
9822 if (!P) {
9823 // Recurse and memoize the results, whether a phi is found or not.
9824 // This recursive call invalidates pointers into PHIMap.
9825 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, TLI, Depth + 1);
9826 PHIMap[OpInst] = P;
9827 }
9828 if (!P)
9829 return nullptr; // Not evolving from PHI
9830 if (PHI && PHI != P)
9831 return nullptr; // Evolving from multiple different PHIs.
9832 PHI = P;
9833 }
9834 // This is a expression evolving from a constant PHI!
9835 return PHI;
9836}
9837
9838/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9839/// in the loop that V is derived from. We allow arbitrary operations along the
9840/// way, but the operands of an operation must either be constants or a value
9841/// derived from a constant PHI. If this expression does not fit with these
9842/// constraints, return null.
9844 const TargetLibraryInfo *TLI) {
9846 if (!I || !canConstantEvolve(I, L, TLI))
9847 return nullptr;
9848
9849 if (PHINode *PN = dyn_cast<PHINode>(I))
9850 return PN;
9851
9852 // Record non-constant instructions contained by the loop.
9854 return getConstantEvolvingPHIOperands(I, L, PHIMap, TLI, 0);
9855}
9856
9857/// EvaluateExpression - Given an expression that passes the
9858/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9859/// in the loop has the value PHIVal. If we can't fold this expression for some
9860/// reason, return null.
9863 const DataLayout &DL,
9864 const TargetLibraryInfo *TLI) {
9865 // Convenient constant check, but redundant for recursive calls.
9866 if (Constant *C = dyn_cast<Constant>(V)) return C;
9868 if (!I) return nullptr;
9869
9870 if (Constant *C = Vals.lookup(I)) return C;
9871
9872 // An instruction inside the loop depends on a value outside the loop that we
9873 // weren't given a mapping for, or a value such as a call inside the loop.
9874 if (!canConstantEvolve(I, L, TLI))
9875 return nullptr;
9876
9877 // An unmapped PHI can be due to a branch or another loop inside this loop,
9878 // or due to this not being the initial iteration through a loop where we
9879 // couldn't compute the evolution of this particular PHI last time.
9880 if (isa<PHINode>(I)) return nullptr;
9881
9882 std::vector<Constant*> Operands(I->getNumOperands());
9883
9884 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9885 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9886 if (!Operand) {
9887 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9888 if (!Operands[i]) return nullptr;
9889 continue;
9890 }
9891 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9892 Vals[Operand] = C;
9893 if (!C) return nullptr;
9894 Operands[i] = C;
9895 }
9896
9897 return ConstantFoldInstOperands(I, Operands, DL, TLI,
9898 /*AllowNonDeterministic=*/false);
9899}
9900
9901
9902// If every incoming value to PN except the one for BB is a specific Constant,
9903// return that, else return nullptr.
9905 Constant *IncomingVal = nullptr;
9906
9907 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9908 if (PN->getIncomingBlock(i) == BB)
9909 continue;
9910
9911 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
9912 if (!CurrentVal)
9913 return nullptr;
9914
9915 if (IncomingVal != CurrentVal) {
9916 if (IncomingVal)
9917 return nullptr;
9918 IncomingVal = CurrentVal;
9919 }
9920 }
9921
9922 return IncomingVal;
9923}
9924
9925/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9926/// in the header of its containing loop, we know the loop executes a
9927/// constant number of times, and the PHI node is just a recurrence
9928/// involving constants, fold it.
9929Constant *
9930ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9931 const APInt &BEs,
9932 const Loop *L) {
9933 auto [I, Inserted] = ConstantEvolutionLoopExitValue.try_emplace(PN);
9934 if (!Inserted)
9935 return I->second;
9936
9938 return nullptr; // Not going to evaluate it.
9939
9940 Constant *&RetVal = I->second;
9941
9942 DenseMap<Instruction *, Constant *> CurrentIterVals;
9943 BasicBlock *Header = L->getHeader();
9944 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9945
9946 BasicBlock *Latch = L->getLoopLatch();
9947 if (!Latch)
9948 return nullptr;
9949
9950 for (PHINode &PHI : Header->phis()) {
9951 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9952 CurrentIterVals[&PHI] = StartCST;
9953 }
9954 if (!CurrentIterVals.count(PN))
9955 return RetVal = nullptr;
9956
9957 Value *BEValue = PN->getIncomingValueForBlock(Latch);
9958
9959 // Execute the loop symbolically to determine the exit value.
9960 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
9961 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
9962
9963 unsigned NumIterations = BEs.getZExtValue(); // must be in range
9964 unsigned IterationNum = 0;
9965 const DataLayout &DL = getDataLayout();
9966 for (; ; ++IterationNum) {
9967 if (IterationNum == NumIterations)
9968 return RetVal = CurrentIterVals[PN]; // Got exit value!
9969
9970 // Compute the value of the PHIs for the next iteration.
9971 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9972 DenseMap<Instruction *, Constant *> NextIterVals;
9973 Constant *NextPHI =
9974 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9975 if (!NextPHI)
9976 return nullptr; // Couldn't evaluate!
9977 NextIterVals[PN] = NextPHI;
9978
9979 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9980
9981 // Also evaluate the other PHI nodes. However, we don't get to stop if we
9982 // cease to be able to evaluate one of them or if they stop evolving,
9983 // because that doesn't necessarily prevent us from computing PN.
9985 for (const auto &I : CurrentIterVals) {
9986 PHINode *PHI = dyn_cast<PHINode>(I.first);
9987 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
9988 PHIsToCompute.emplace_back(PHI, I.second);
9989 }
9990 // We use two distinct loops because EvaluateExpression may invalidate any
9991 // iterators into CurrentIterVals.
9992 for (const auto &I : PHIsToCompute) {
9993 PHINode *PHI = I.first;
9994 Constant *&NextPHI = NextIterVals[PHI];
9995 if (!NextPHI) { // Not already computed.
9996 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9997 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9998 }
9999 if (NextPHI != I.second)
10000 StoppedEvolving = false;
10001 }
10002
10003 // If all entries in CurrentIterVals == NextIterVals then we can stop
10004 // iterating, the loop can't continue to change.
10005 if (StoppedEvolving)
10006 return RetVal = CurrentIterVals[PN];
10007
10008 CurrentIterVals.swap(NextIterVals);
10009 }
10010}
10011
10012const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
10013 Value *Cond,
10014 bool ExitWhen) {
10015 PHINode *PN = getConstantEvolvingPHI(Cond, L, &TLI);
10016 if (!PN) return getCouldNotCompute();
10017
10018 // If the loop is canonicalized, the PHI will have exactly two entries.
10019 // That's the only form we support here.
10020 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
10021
10022 DenseMap<Instruction *, Constant *> CurrentIterVals;
10023 BasicBlock *Header = L->getHeader();
10024 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
10025
10026 BasicBlock *Latch = L->getLoopLatch();
10027 assert(Latch && "Should follow from NumIncomingValues == 2!");
10028
10029 for (PHINode &PHI : Header->phis()) {
10030 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
10031 CurrentIterVals[&PHI] = StartCST;
10032 }
10033 if (!CurrentIterVals.count(PN))
10034 return getCouldNotCompute();
10035
10036 // Okay, we find a PHI node that defines the trip count of this loop. Execute
10037 // the loop symbolically to determine when the condition gets a value of
10038 // "ExitWhen".
10039 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
10040 const DataLayout &DL = getDataLayout();
10041 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
10042 auto *CondVal = dyn_cast_or_null<ConstantInt>(
10043 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
10044
10045 // Couldn't symbolically evaluate.
10046 if (!CondVal) return getCouldNotCompute();
10047
10048 if (CondVal->getValue() == uint64_t(ExitWhen)) {
10049 ++NumBruteForceTripCountsComputed;
10050 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
10051 }
10052
10053 // Update all the PHI nodes for the next iteration.
10054 DenseMap<Instruction *, Constant *> NextIterVals;
10055
10056 // Create a list of which PHIs we need to compute. We want to do this before
10057 // calling EvaluateExpression on them because that may invalidate iterators
10058 // into CurrentIterVals.
10059 SmallVector<PHINode *, 8> PHIsToCompute;
10060 for (const auto &I : CurrentIterVals) {
10061 PHINode *PHI = dyn_cast<PHINode>(I.first);
10062 if (!PHI || PHI->getParent() != Header) continue;
10063 PHIsToCompute.push_back(PHI);
10064 }
10065 for (PHINode *PHI : PHIsToCompute) {
10066 Constant *&NextPHI = NextIterVals[PHI];
10067 if (NextPHI) continue; // Already computed!
10068
10069 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
10070 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
10071 }
10072 CurrentIterVals.swap(NextIterVals);
10073 }
10074
10075 // Too many iterations were needed to evaluate.
10076 return getCouldNotCompute();
10077}
10078
10080 auto &Values = ValuesAtScopes[V];
10081 // Check to see if we've folded this expression at this loop before.
10082 for (auto &LS : Values)
10083 if (LS.first == L)
10084 return LS.second ? LS.second : SCEVUse(V);
10085
10086 Values.emplace_back(L, nullptr);
10087
10088 // Otherwise compute it.
10089 SCEVUse C = computeSCEVAtScope(V, L);
10090 for (auto &LS : reverse(ValuesAtScopes[V]))
10091 if (LS.first == L) {
10092 LS.second = C;
10093 // Record the dependency under the bare expression: invalidation walks
10094 // expressions, and any use flags on C do not change which expression
10095 // this is the value at scope of.
10096 if (!isa<SCEVConstant>(C))
10097 ValuesAtScopesUsers[C.getPointer()].push_back({L, V});
10098 break;
10099 }
10100 return C;
10101}
10102
10104 const BasicBlock *ExitingBlock) {
10105 SCEVUse ExitValue = getSCEVAtScope(V, L->getParentLoop());
10106 if (!isLoopInvariant(ExitValue, L)) {
10107 // If we failed to evaluate it in the outer scope, try to evaluate an
10108 // addrec for the specific exit.
10109 // TODO: Generalize this to other expressions.
10110 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
10111 if (!isa<SCEVCouldNotCompute>(ExitCount))
10112 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V))
10113 if (AddRec->getLoop() == L)
10114 ExitValue = AddRec->evaluateAtIteration(ExitCount, *this);
10115 }
10116 return ExitValue;
10117}
10118
10119/// This builds up a Constant using the ConstantExpr interface. That way, we
10120/// will return Constants for objects which aren't represented by a
10121/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
10122/// Returns NULL if the SCEV isn't representable as a Constant.
10124 switch (V->getSCEVType()) {
10125 case scCouldNotCompute:
10126 case scAddRecExpr:
10127 case scVScale:
10128 return nullptr;
10129 case scConstant:
10130 return cast<SCEVConstant>(V)->getValue();
10131 case scUnknown:
10133 case scPtrToAddr: {
10135 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
10136 return ConstantExpr::getPtrToAddr(CastOp, P2I->getType());
10137
10138 return nullptr;
10139 }
10140 case scTruncate: {
10142 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
10143 return ConstantExpr::getTrunc(CastOp, ST->getType());
10144 return nullptr;
10145 }
10146 case scAddExpr: {
10147 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
10148 Constant *C = nullptr;
10149 for (const SCEV *Op : SA->operands()) {
10151 if (!OpC)
10152 return nullptr;
10153 if (!C) {
10154 C = OpC;
10155 continue;
10156 }
10157 assert(!C->getType()->isPointerTy() &&
10158 "Can only have one pointer, and it must be last");
10159 if (OpC->getType()->isPointerTy()) {
10160 // The offsets have been converted to bytes. We can add bytes using
10161 // an i8 GEP.
10162 C = ConstantExpr::getPtrAdd(OpC, C);
10163 } else {
10164 C = ConstantExpr::getAdd(C, OpC);
10165 }
10166 }
10167 return C;
10168 }
10169 case scMulExpr:
10170 case scSignExtend:
10171 case scZeroExtend:
10172 case scUDivExpr:
10173 case scSMaxExpr:
10174 case scUMaxExpr:
10175 case scSMinExpr:
10176 case scUMinExpr:
10178 return nullptr;
10179 }
10180 llvm_unreachable("Unknown SCEV kind!");
10181}
10182
10183const SCEV *ScalarEvolution::getWithOperands(const SCEV *S,
10184 SmallVectorImpl<SCEVUse> &NewOps) {
10185 switch (S->getSCEVType()) {
10186 case scTruncate:
10187 case scZeroExtend:
10188 case scSignExtend:
10189 case scPtrToAddr:
10190 return getCastExpr(S->getSCEVType(), NewOps[0], S->getType());
10191 case scAddRecExpr: {
10192 auto *AddRec = cast<SCEVAddRecExpr>(S);
10193 return getAddRecExpr(NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags());
10194 }
10195 case scAddExpr:
10196 return getAddExpr(NewOps, cast<SCEVAddExpr>(S)->getNoWrapFlags());
10197 case scMulExpr:
10198 return getMulExpr(NewOps, cast<SCEVMulExpr>(S)->getNoWrapFlags());
10199 case scUDivExpr:
10200 return getUDivExpr(NewOps[0], NewOps[1]);
10201 case scUMaxExpr:
10202 case scSMaxExpr:
10203 case scUMinExpr:
10204 case scSMinExpr:
10205 return getMinMaxExpr(S->getSCEVType(), NewOps);
10207 return getSequentialMinMaxExpr(S->getSCEVType(), NewOps);
10208 case scConstant:
10209 case scVScale:
10210 case scUnknown:
10211 return S;
10212 case scCouldNotCompute:
10213 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10214 }
10215 llvm_unreachable("Unknown SCEV kind!");
10216}
10217
10218SCEVUse ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
10219 switch (V->getSCEVType()) {
10220 case scConstant:
10221 case scVScale:
10222 return V;
10223 case scAddRecExpr: {
10224 // If this is a loop recurrence for a loop that does not contain L, then we
10225 // are dealing with the final value computed by the loop.
10226 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(V);
10227 // First, attempt to evaluate each operand.
10228 // Avoid performing the look-up in the common case where the specified
10229 // expression has no loop-variant portions.
10230 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
10231 SCEVUse OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
10232 if (OpAtScope == AddRec->getOperand(i))
10233 continue;
10234
10235 // Okay, at least one of these operands is loop variant but might be
10236 // foldable. Build a new instance of the folded commutative expression.
10238 NewOps.reserve(AddRec->getNumOperands());
10239 append_range(NewOps, AddRec->operands().take_front(i));
10240 NewOps.push_back(OpAtScope);
10241 for (++i; i != e; ++i)
10242 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
10243
10244 const SCEV *FoldedRec = getAddRecExpr(
10245 NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags(SCEV::FlagNW));
10246 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
10247 // The addrec may be folded to a nonrecurrence, for example, if the
10248 // induction variable is multiplied by zero after constant folding. Go
10249 // ahead and return the folded value.
10250 if (!AddRec)
10251 return FoldedRec;
10252 break;
10253 }
10254
10255 // If the scope is outside the addrec's loop, evaluate it by using the
10256 // loop exit value of the addrec.
10257 if (!AddRec->getLoop()->contains(L)) {
10258 SCEVUse ExitValue = AddRec->getExitValue(*this);
10259 if (isa<SCEVCouldNotCompute>(ExitValue))
10260 return AddRec;
10261 return ExitValue;
10262 }
10263
10264 return AddRec;
10265 }
10266 case scTruncate:
10267 case scZeroExtend:
10268 case scSignExtend:
10269 case scPtrToAddr:
10270 case scAddExpr:
10271 case scMulExpr:
10272 case scUDivExpr:
10273 case scUMaxExpr:
10274 case scSMaxExpr:
10275 case scUMinExpr:
10276 case scSMinExpr:
10277 case scSequentialUMinExpr: {
10278 ArrayRef<SCEVUse> Ops = V->operands();
10279 // Avoid performing the look-up in the common case where the specified
10280 // expression has no loop-variant portions.
10281 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
10282 SCEVUse OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10283 if (OpAtScope != Ops[i].getPointer()) {
10284 // Okay, at least one of these operands is loop variant but might be
10285 // foldable. Build a new instance of the folded commutative expression.
10287 NewOps.reserve(Ops.size());
10288 append_range(NewOps, Ops.take_front(i));
10289 NewOps.push_back(OpAtScope);
10290
10291 for (++i; i != e; ++i) {
10292 OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10293 NewOps.push_back(OpAtScope);
10294 }
10295
10296 return getWithOperands(V, NewOps);
10297 }
10298 }
10299 // If we got here, all operands are loop invariant.
10300 return V;
10301 }
10302 case scUnknown: {
10303 // If this instruction is evolved from a constant-evolving PHI, compute the
10304 // exit value from the loop without using SCEVs.
10305 const SCEVUnknown *SU = cast<SCEVUnknown>(V);
10307 if (!I)
10308 return V; // This is some other type of SCEVUnknown, just return it.
10309
10310 if (PHINode *PN = dyn_cast<PHINode>(I)) {
10311 const Loop *CurrLoop = this->LI[I->getParent()];
10312 // Looking for loop exit value.
10313 if (CurrLoop && CurrLoop->getParentLoop() == L &&
10314 PN->getParent() == CurrLoop->getHeader()) {
10315 // Okay, there is no closed form solution for the PHI node. Check
10316 // to see if the loop that contains it has a known backedge-taken
10317 // count. If so, we may be able to force computation of the exit
10318 // value.
10319 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
10320 // This trivial case can show up in some degenerate cases where
10321 // the incoming IR has not yet been fully simplified.
10322 if (BackedgeTakenCount->isZero()) {
10323 Value *InitValue = nullptr;
10324 bool MultipleInitValues = false;
10325 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
10326 if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
10327 if (!InitValue)
10328 InitValue = PN->getIncomingValue(i);
10329 else if (InitValue != PN->getIncomingValue(i)) {
10330 MultipleInitValues = true;
10331 break;
10332 }
10333 }
10334 }
10335 if (!MultipleInitValues && InitValue)
10336 return getSCEV(InitValue);
10337 }
10338 // Do we have a loop invariant value flowing around the backedge
10339 // for a loop which must execute the backedge?
10340 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
10341 isKnownNonZero(BackedgeTakenCount) &&
10342 PN->getNumIncomingValues() == 2) {
10343
10344 unsigned InLoopPred =
10345 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
10346 Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
10347 if (CurrLoop->isLoopInvariant(BackedgeVal))
10348 return getSCEV(BackedgeVal);
10349 }
10350 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
10351 // Okay, we know how many times the containing loop executes. If
10352 // this is a constant evolving PHI node, get the final value at
10353 // the specified iteration number.
10354 Constant *RV =
10355 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
10356 if (RV)
10357 return getSCEV(RV);
10358 }
10359 }
10360 }
10361
10362 // Okay, this is an expression that we cannot symbolically evaluate
10363 // into a SCEV. Check to see if it's possible to symbolically evaluate
10364 // the arguments into constants, and if so, try to constant propagate the
10365 // result. This is particularly useful for computing loop exit values.
10366 if (!canConstantFold(I, &TLI))
10367 return V; // This is some other type of SCEVUnknown, just return it.
10368
10369 SmallVector<Constant *, 4> Operands;
10370 Operands.reserve(I->getNumOperands());
10371 bool MadeImprovement = false;
10372 for (Value *Op : I->operands()) {
10373 if (Constant *C = dyn_cast<Constant>(Op)) {
10374 Operands.push_back(C);
10375 continue;
10376 }
10377
10378 // If any of the operands is non-constant and if they are
10379 // non-integer and non-pointer, don't even try to analyze them
10380 // with scev techniques.
10381 if (!isSCEVable(Op->getType()))
10382 return V;
10383
10384 const SCEV *OrigV = getSCEV(Op);
10385 const SCEV *OpV = getSCEVAtScope(OrigV, L);
10386 MadeImprovement |= OrigV != OpV;
10387
10389 if (!C)
10390 return V;
10391 assert(C->getType() == Op->getType() && "Type mismatch");
10392 Operands.push_back(C);
10393 }
10394
10395 // Check to see if getSCEVAtScope actually made an improvement.
10396 if (!MadeImprovement)
10397 return V; // This is some other type of SCEVUnknown, just return it.
10398
10399 Constant *C = nullptr;
10400 const DataLayout &DL = getDataLayout();
10401 C = ConstantFoldInstOperands(I, Operands, DL, &TLI,
10402 /*AllowNonDeterministic=*/false);
10403 if (!C)
10404 return V;
10405 return getSCEV(C);
10406 }
10407 case scCouldNotCompute:
10408 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10409 }
10410 llvm_unreachable("Unknown SCEV type!");
10411}
10412
10414 return getSCEVAtScope(getSCEV(V), L);
10415}
10416
10417const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
10419 return stripInjectiveFunctions(ZExt->getOperand());
10421 return stripInjectiveFunctions(SExt->getOperand());
10422 return S;
10423}
10424
10425/// Finds the minimum unsigned root of the following equation:
10426///
10427/// A * X = B (mod N)
10428///
10429/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
10430/// A and B isn't important.
10431///
10432/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
10433static const SCEV *
10436 ScalarEvolution &SE, const Loop *L) {
10437 uint32_t BW = A.getBitWidth();
10438 assert(BW == SE.getTypeSizeInBits(B->getType()));
10439 assert(A != 0 && "A must be non-zero.");
10440
10441 // 1. D = gcd(A, N)
10442 //
10443 // The gcd of A and N may have only one prime factor: 2. The number of
10444 // trailing zeros in A is its multiplicity
10445 uint32_t Mult2 = A.countr_zero();
10446 // D = 2^Mult2
10447
10448 // 2. Check if B is divisible by D.
10449 //
10450 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
10451 // is not less than multiplicity of this prime factor for D.
10452 unsigned MinTZ = SE.getMinTrailingZeros(B);
10453 // Try again with the terminator of the loop predecessor for context-specific
10454 // result, if MinTZ s too small.
10455 if (MinTZ < Mult2 && L->getLoopPredecessor())
10456 MinTZ = SE.getMinTrailingZeros(B, L->getLoopPredecessor()->getTerminator());
10457 if (MinTZ < Mult2) {
10458 // Check if we can prove there's no remainder using URem.
10459 const SCEV *URem =
10460 SE.getURemExpr(B, SE.getConstant(APInt::getOneBitSet(BW, Mult2)));
10461 const SCEV *Zero = SE.getZero(B->getType());
10462 if (!SE.isKnownPredicate(CmpInst::ICMP_EQ, URem, Zero)) {
10463 // Try to add a predicate ensuring B is a multiple of 1 << Mult2.
10464 if (!Predicates)
10465 return SE.getCouldNotCompute();
10466
10467 // Avoid adding a predicate that is known to be false.
10468 if (SE.isKnownPredicate(CmpInst::ICMP_NE, URem, Zero))
10469 return SE.getCouldNotCompute();
10470 Predicates->push_back(SE.getEqualPredicate(URem, Zero));
10471 }
10472 }
10473
10474 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
10475 // modulo (N / D).
10476 //
10477 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
10478 // (N / D) in general. The inverse itself always fits into BW bits, though,
10479 // so we immediately truncate it.
10480 APInt AD = A.lshr(Mult2).trunc(BW - Mult2); // AD = A / D
10481 APInt I = AD.multiplicativeInverse().zext(BW);
10482
10483 // 4. Compute the minimum unsigned root of the equation:
10484 // I * (B / D) mod (N / D)
10485 // To simplify the computation, we factor out the divide by D:
10486 // (I * B mod N) / D
10487 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
10488 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
10489}
10490
10491/// For a given quadratic addrec, generate coefficients of the corresponding
10492/// quadratic equation, multiplied by a common value to ensure that they are
10493/// integers.
10494/// The returned value is a tuple { A, B, C, M, BitWidth }, where
10495/// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
10496/// were multiplied by, and BitWidth is the bit width of the original addrec
10497/// coefficients.
10498/// This function returns std::nullopt if the addrec coefficients are not
10499/// compile- time constants.
10500static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
10502 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
10503 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
10504 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
10505 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
10506 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
10507 << *AddRec << '\n');
10508
10509 // We currently can only solve this if the coefficients are constants.
10510 if (!LC || !MC || !NC) {
10511 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
10512 return std::nullopt;
10513 }
10514
10515 APInt L = LC->getAPInt();
10516 APInt M = MC->getAPInt();
10517 APInt N = NC->getAPInt();
10518 assert(!N.isZero() && "This is not a quadratic addrec");
10519
10520 unsigned BitWidth = LC->getAPInt().getBitWidth();
10521 unsigned NewWidth = BitWidth + 1;
10522 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
10523 << BitWidth << '\n');
10524 // The sign-extension (as opposed to a zero-extension) here matches the
10525 // extension used in SolveQuadraticEquationWrap (with the same motivation).
10526 N = N.sext(NewWidth);
10527 M = M.sext(NewWidth);
10528 L = L.sext(NewWidth);
10529
10530 // The increments are M, M+N, M+2N, ..., so the accumulated values are
10531 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
10532 // L+M, L+2M+N, L+3M+3N, ...
10533 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
10534 //
10535 // The equation Acc = 0 is then
10536 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
10537 // In a quadratic form it becomes:
10538 // N n^2 + (2M-N) n + 2L = 0.
10539
10540 APInt A = N;
10541 APInt B = 2 * M - A;
10542 APInt C = 2 * L;
10543 APInt T = APInt(NewWidth, 2);
10544 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
10545 << "x + " << C << ", coeff bw: " << NewWidth
10546 << ", multiplied by " << T << '\n');
10547 return std::make_tuple(A, B, C, T, BitWidth);
10548}
10549
10550/// Helper function to compare optional APInts:
10551/// (a) if X and Y both exist, return min(X, Y),
10552/// (b) if neither X nor Y exist, return std::nullopt,
10553/// (c) if exactly one of X and Y exists, return that value.
10554static std::optional<APInt> MinOptional(std::optional<APInt> X,
10555 std::optional<APInt> Y) {
10556 if (X && Y) {
10557 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
10558 APInt XW = X->sext(W);
10559 APInt YW = Y->sext(W);
10560 return XW.slt(YW) ? *X : *Y;
10561 }
10562 if (!X && !Y)
10563 return std::nullopt;
10564 return X ? *X : *Y;
10565}
10566
10567/// Helper function to truncate an optional APInt to a given BitWidth.
10568/// When solving addrec-related equations, it is preferable to return a value
10569/// that has the same bit width as the original addrec's coefficients. If the
10570/// solution fits in the original bit width, truncate it (except for i1).
10571/// Returning a value of a different bit width may inhibit some optimizations.
10572///
10573/// In general, a solution to a quadratic equation generated from an addrec
10574/// may require BW+1 bits, where BW is the bit width of the addrec's
10575/// coefficients. The reason is that the coefficients of the quadratic
10576/// equation are BW+1 bits wide (to avoid truncation when converting from
10577/// the addrec to the equation).
10578static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
10579 unsigned BitWidth) {
10580 if (!X)
10581 return std::nullopt;
10582 unsigned W = X->getBitWidth();
10584 return X->trunc(BitWidth);
10585 return X;
10586}
10587
10588/// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
10589/// iterations. The values L, M, N are assumed to be signed, and they
10590/// should all have the same bit widths.
10591/// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
10592/// where BW is the bit width of the addrec's coefficients.
10593/// If the calculated value is a BW-bit integer (for BW > 1), it will be
10594/// returned as such, otherwise the bit width of the returned value may
10595/// be greater than BW.
10596///
10597/// This function returns std::nullopt if
10598/// (a) the addrec coefficients are not constant, or
10599/// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
10600/// like x^2 = 5, no integer solutions exist, in other cases an integer
10601/// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
10602static std::optional<APInt>
10604 APInt A, B, C, M;
10605 unsigned BitWidth;
10606 auto T = GetQuadraticEquation(AddRec);
10607 if (!T)
10608 return std::nullopt;
10609
10610 std::tie(A, B, C, M, BitWidth) = *T;
10611 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
10612 std::optional<APInt> X =
10614 if (!X)
10615 return std::nullopt;
10616
10617 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
10618 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
10619 if (!V->isZero())
10620 return std::nullopt;
10621
10622 return TruncIfPossible(X, BitWidth);
10623}
10624
10625/// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
10626/// iterations. The values M, N are assumed to be signed, and they
10627/// should all have the same bit widths.
10628/// Find the least n such that c(n) does not belong to the given range,
10629/// while c(n-1) does.
10630///
10631/// This function returns std::nullopt if
10632/// (a) the addrec coefficients are not constant, or
10633/// (b) SolveQuadraticEquationWrap was unable to find a solution for the
10634/// bounds of the range.
10635static std::optional<APInt>
10637 const ConstantRange &Range, ScalarEvolution &SE) {
10638 assert(AddRec->getOperand(0)->isZero() &&
10639 "Starting value of addrec should be 0");
10640 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
10641 << Range << ", addrec " << *AddRec << '\n');
10642 // This case is handled in getNumIterationsInRange. Here we can assume that
10643 // we start in the range.
10644 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
10645 "Addrec's initial value should be in range");
10646
10647 APInt A, B, C, M;
10648 unsigned BitWidth;
10649 auto T = GetQuadraticEquation(AddRec);
10650 if (!T)
10651 return std::nullopt;
10652
10653 // Be careful about the return value: there can be two reasons for not
10654 // returning an actual number. First, if no solutions to the equations
10655 // were found, and second, if the solutions don't leave the given range.
10656 // The first case means that the actual solution is "unknown", the second
10657 // means that it's known, but not valid. If the solution is unknown, we
10658 // cannot make any conclusions.
10659 // Return a pair: the optional solution and a flag indicating if the
10660 // solution was found.
10661 auto SolveForBoundary =
10662 [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
10663 // Solve for signed overflow and unsigned overflow, pick the lower
10664 // solution.
10665 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
10666 << Bound << " (before multiplying by " << M << ")\n");
10667 Bound *= M; // The quadratic equation multiplier.
10668
10669 std::optional<APInt> SO;
10670 if (BitWidth > 1) {
10671 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10672 "signed overflow\n");
10674 }
10675 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10676 "unsigned overflow\n");
10677 std::optional<APInt> UO =
10679
10680 auto LeavesRange = [&] (const APInt &X) {
10681 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
10682 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
10683 if (Range.contains(V0->getValue()))
10684 return false;
10685 // X should be at least 1, so X-1 is non-negative.
10686 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
10688 if (Range.contains(V1->getValue()))
10689 return true;
10690 return false;
10691 };
10692
10693 // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
10694 // can be a solution, but the function failed to find it. We cannot treat it
10695 // as "no solution".
10696 if (!SO || !UO)
10697 return {std::nullopt, false};
10698
10699 // Check the smaller value first to see if it leaves the range.
10700 // At this point, both SO and UO must have values.
10701 std::optional<APInt> Min = MinOptional(SO, UO);
10702 if (LeavesRange(*Min))
10703 return { Min, true };
10704 std::optional<APInt> Max = Min == SO ? UO : SO;
10705 if (LeavesRange(*Max))
10706 return { Max, true };
10707
10708 // Solutions were found, but were eliminated, hence the "true".
10709 return {std::nullopt, true};
10710 };
10711
10712 std::tie(A, B, C, M, BitWidth) = *T;
10713 // Lower bound is inclusive, subtract 1 to represent the exiting value.
10714 APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
10715 APInt Upper = Range.getUpper().sext(A.getBitWidth());
10716 auto SL = SolveForBoundary(Lower);
10717 auto SU = SolveForBoundary(Upper);
10718 // If any of the solutions was unknown, no meaninigful conclusions can
10719 // be made.
10720 if (!SL.second || !SU.second)
10721 return std::nullopt;
10722
10723 // Claim: The correct solution is not some value between Min and Max.
10724 //
10725 // Justification: Assuming that Min and Max are different values, one of
10726 // them is when the first signed overflow happens, the other is when the
10727 // first unsigned overflow happens. Crossing the range boundary is only
10728 // possible via an overflow (treating 0 as a special case of it, modeling
10729 // an overflow as crossing k*2^W for some k).
10730 //
10731 // The interesting case here is when Min was eliminated as an invalid
10732 // solution, but Max was not. The argument is that if there was another
10733 // overflow between Min and Max, it would also have been eliminated if
10734 // it was considered.
10735 //
10736 // For a given boundary, it is possible to have two overflows of the same
10737 // type (signed/unsigned) without having the other type in between: this
10738 // can happen when the vertex of the parabola is between the iterations
10739 // corresponding to the overflows. This is only possible when the two
10740 // overflows cross k*2^W for the same k. In such case, if the second one
10741 // left the range (and was the first one to do so), the first overflow
10742 // would have to enter the range, which would mean that either we had left
10743 // the range before or that we started outside of it. Both of these cases
10744 // are contradictions.
10745 //
10746 // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
10747 // solution is not some value between the Max for this boundary and the
10748 // Min of the other boundary.
10749 //
10750 // Justification: Assume that we had such Max_A and Min_B corresponding
10751 // to range boundaries A and B and such that Max_A < Min_B. If there was
10752 // a solution between Max_A and Min_B, it would have to be caused by an
10753 // overflow corresponding to either A or B. It cannot correspond to B,
10754 // since Min_B is the first occurrence of such an overflow. If it
10755 // corresponded to A, it would have to be either a signed or an unsigned
10756 // overflow that is larger than both eliminated overflows for A. But
10757 // between the eliminated overflows and this overflow, the values would
10758 // cover the entire value space, thus crossing the other boundary, which
10759 // is a contradiction.
10760
10761 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
10762}
10763
10764ScalarEvolution::ExitLimit ScalarEvolution::howFarToZero(const SCEV *V,
10765 const Loop *L,
10766 bool ControlsOnlyExit,
10767 bool AllowPredicates) {
10768
10769 // This is only used for loops with a "x != y" exit test. The exit condition
10770 // is now expressed as a single expression, V = x-y. So the exit test is
10771 // effectively V != 0. We know and take advantage of the fact that this
10772 // expression only being used in a comparison by zero context.
10773
10775 // If the value is a constant
10776 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10777 // If the value is already zero, the branch will execute zero times.
10778 if (C->getValue()->isZero()) return C;
10779 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10780 }
10781
10782 const SCEVAddRecExpr *AddRec =
10783 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
10784
10785 if (!AddRec && AllowPredicates)
10786 // Try to make this an AddRec using runtime tests, in the first X
10787 // iterations of this loop, where X is the SCEV expression found by the
10788 // algorithm below.
10789 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
10790
10791 if (!AddRec || AddRec->getLoop() != L)
10792 return getCouldNotCompute();
10793
10794 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
10795 // the quadratic equation to solve it.
10796 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
10797 // We can only use this value if the chrec ends up with an exact zero
10798 // value at this index. When solving for "X*X != 5", for example, we
10799 // should not accept a root of 2.
10800 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
10801 const auto *R = cast<SCEVConstant>(getConstant(*S));
10802 return ExitLimit(R, R, R, false, Predicates);
10803 }
10804 return getCouldNotCompute();
10805 }
10806
10807 // Otherwise we can only handle this if it is affine.
10808 if (!AddRec->isAffine())
10809 return getCouldNotCompute();
10810
10811 // If this is an affine expression, the execution count of this branch is
10812 // the minimum unsigned root of the following equation:
10813 //
10814 // Start + Step*N = 0 (mod 2^BW)
10815 //
10816 // equivalent to:
10817 //
10818 // Step*N = -Start (mod 2^BW)
10819 //
10820 // where BW is the common bit width of Start and Step.
10821
10822 // Get the initial value for the loop.
10823 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
10824 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
10825
10826 if (!isLoopInvariant(Step, L))
10827 return getCouldNotCompute();
10828
10829 LoopGuards Guards = LoopGuards::collect(L, *this);
10830 // Specialize step for this loop so we get context sensitive facts below.
10831 const SCEV *StepWLG = applyLoopGuards(Step, Guards);
10832
10833 // For positive steps (counting up until unsigned overflow):
10834 // N = -Start/Step (as unsigned)
10835 // For negative steps (counting down to zero):
10836 // N = Start/-Step
10837 // First compute the unsigned distance from zero in the direction of Step.
10838 bool CountDown = isKnownNegative(StepWLG);
10839 if (!CountDown && !isKnownNonNegative(StepWLG))
10840 return getCouldNotCompute();
10841
10842 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
10843 // Handle unitary steps, which cannot wraparound.
10844 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10845 // N = Distance (as unsigned)
10846
10847 if (match(Step, m_CombineOr(m_scev_One(), m_scev_AllOnes()))) {
10848 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, Guards));
10849 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
10850
10851 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10852 // we end up with a loop whose backedge-taken count is n - 1. Detect this
10853 // case, and see if we can improve the bound.
10854 //
10855 // Explicitly handling this here is necessary because getUnsignedRange
10856 // isn't context-sensitive; it doesn't know that we only care about the
10857 // range inside the loop.
10858 const SCEV *Zero = getZero(Distance->getType());
10859 const SCEV *One = getOne(Distance->getType());
10860 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
10861 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
10862 // If Distance + 1 doesn't overflow, we can compute the maximum distance
10863 // as "unsigned_max(Distance + 1) - 1". Also apply the loop guards to
10864 // Distance + 1; the range of Distance itself may be a wrapped set even
10865 // when the guards bound Distance + 1 tightly.
10866 APInt Max = APIntOps::umin(
10867 getUnsignedRangeMax(applyLoopGuards(DistancePlusOne, Guards)),
10868 getUnsignedRangeMax(DistancePlusOne));
10869 MaxBECount = APIntOps::umin(MaxBECount, Max - 1);
10870 }
10871 return ExitLimit(Distance, getConstant(MaxBECount), Distance, false,
10872 Predicates);
10873 }
10874
10875 // If the condition controls loop exit (the loop exits only if the expression
10876 // is true) and the addition is no-wrap we can use unsigned divide to
10877 // compute the backedge count. In this case, the step may not divide the
10878 // distance, but we don't care because if the condition is "missed" the loop
10879 // will have undefined behavior due to wrapping.
10880 if (ControlsOnlyExit && AddRec->hasNoSelfWrap() &&
10881 loopHasNoAbnormalExits(AddRec->getLoop())) {
10882
10883 // If the stride is zero and the start is non-zero, the loop must be
10884 // infinite. In C++, most loops are finite by assumption, in which case the
10885 // step being zero implies UB must execute if the loop is entered.
10886 if (!(loopIsFiniteByAssumption(L) && isKnownNonZero(Start)) &&
10887 !isKnownNonZero(StepWLG))
10888 return getCouldNotCompute();
10889
10890 const SCEV *Exact =
10891 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10892 const SCEV *ConstantMax = getCouldNotCompute();
10893 if (Exact != getCouldNotCompute()) {
10894 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, Guards));
10895 ConstantMax =
10897 }
10898 const SCEV *SymbolicMax =
10899 isa<SCEVCouldNotCompute>(Exact) ? ConstantMax : Exact;
10900 return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
10901 }
10902
10903 // Solve the general equation.
10904 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
10905 if (!StepC || StepC->getValue()->isZero())
10906 return getCouldNotCompute();
10907 const SCEV *E = SolveLinEquationWithOverflow(
10908 StepC->getAPInt(), getNegativeSCEV(Start),
10909 AllowPredicates ? &Predicates : nullptr, *this, L);
10910
10911 const SCEV *M = E;
10912 if (E != getCouldNotCompute()) {
10913 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, Guards));
10914 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
10915 }
10916 auto *S = isa<SCEVCouldNotCompute>(E) ? M : E;
10917 return ExitLimit(E, M, S, false, Predicates);
10918}
10919
10920ScalarEvolution::ExitLimit
10921ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10922 // Loops that look like: while (X == 0) are very strange indeed. We don't
10923 // handle them yet except for the trivial case. This could be expanded in the
10924 // future as needed.
10925
10926 // If the value is a constant, check to see if it is known to be non-zero
10927 // already. If so, the backedge will execute zero times.
10928 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10929 if (!C->getValue()->isZero())
10930 return getZero(C->getType());
10931 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10932 }
10933
10934 // We could implement others, but I really doubt anyone writes loops like
10935 // this, and if they did, they would already be constant folded.
10936 return getCouldNotCompute();
10937}
10938
10939std::pair<const BasicBlock *, const BasicBlock *>
10940ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10941 const {
10942 // If the block has a unique predecessor, then there is no path from the
10943 // predecessor to the block that does not go through the direct edge
10944 // from the predecessor to the block.
10945 if (const BasicBlock *Pred = BB->getSinglePredecessor())
10946 return {Pred, BB};
10947
10948 // A loop's header is defined to be a block that dominates the loop.
10949 // If the header has a unique predecessor outside the loop, it must be
10950 // a block that has exactly one successor that can reach the loop.
10951 if (const Loop *L = LI.getLoopFor(BB))
10952 return {L->getLoopPredecessor(), L->getHeader()};
10953
10954 return {nullptr, BB};
10955}
10956
10957/// SCEV structural equivalence is usually sufficient for testing whether two
10958/// expressions are equal, however for the purposes of looking for a condition
10959/// guarding a loop, it can be useful to be a little more general, since a
10960/// front-end may have replicated the controlling expression.
10961static bool HasSameValue(const SCEV *A, const SCEV *B) {
10962 // Quick check to see if they are the same SCEV.
10963 if (A == B) return true;
10964
10965 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10966 // Not all instructions that are "identical" compute the same value. For
10967 // instance, two distinct alloca instructions allocating the same type are
10968 // identical and do not read memory; but compute distinct values.
10969 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
10970 };
10971
10972 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10973 // two different instructions with the same value. Check for this case.
10974 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
10975 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
10976 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
10977 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
10978 if (ComputesEqualValues(AI, BI))
10979 return true;
10980
10981 // Otherwise assume they may have a different value.
10982 return false;
10983}
10984
10985static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS) {
10986 const SCEV *Op0, *Op1;
10987 if (!match(S, m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))))
10988 return false;
10989 if (match(Op0, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10990 LHS = Op1;
10991 return true;
10992 }
10993 if (match(Op1, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10994 LHS = Op0;
10995 return true;
10996 }
10997 return false;
10998}
10999
11001 SCEVUse &RHS, unsigned Depth) {
11002 bool Changed = false;
11003 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
11004 // '0 != 0'.
11005 auto TrivialCase = [&](bool TriviallyTrue) {
11007 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
11008 return true;
11009 };
11010 // If we hit the max recursion limit bail out.
11011 if (Depth >= 3)
11012 return false;
11013
11014 const SCEV *NewLHS, *NewRHS;
11015 if (match(LHS, m_scev_c_Mul(m_SCEV(NewLHS), m_SCEVVScale())) &&
11016 match(RHS, m_scev_c_Mul(m_SCEV(NewRHS), m_SCEVVScale()))) {
11017 const SCEVMulExpr *LMul = cast<SCEVMulExpr>(LHS);
11018 const SCEVMulExpr *RMul = cast<SCEVMulExpr>(RHS);
11019
11020 // (X * vscale) pred (Y * vscale) ==> X pred Y
11021 // when both multiples are NSW.
11022 // (X * vscale) uicmp/eq/ne (Y * vscale) ==> X uicmp/eq/ne Y
11023 // when both multiples are NUW.
11024 if ((LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap()) ||
11025 (LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap() &&
11026 !ICmpInst::isSigned(Pred))) {
11027 LHS = NewLHS;
11028 RHS = NewRHS;
11029 Changed = true;
11030 }
11031 }
11032
11033 // Canonicalize a constant to the right side.
11034 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
11035 // Check for both operands constant.
11036 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
11037 if (!ICmpInst::compare(LHSC->getAPInt(), RHSC->getAPInt(), Pred))
11038 return TrivialCase(false);
11039 return TrivialCase(true);
11040 }
11041 // Otherwise swap the operands to put the constant on the right.
11042 std::swap(LHS, RHS);
11044 Changed = true;
11045 }
11046
11047 // (K + A) pred (K + B) --> A pred B
11048 // For equality, no flags are needed.
11049 // For signed, both adds must be NSW. For unsigned, both must be NUW.
11050 {
11051 const SCEVConstant *C = nullptr;
11052 if (match(LHS, m_scev_Add(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11053 match(RHS, m_scev_Add(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11054 const auto *LAdd = cast<SCEVAddExpr>(LHS);
11055 const auto *RAdd = cast<SCEVAddExpr>(RHS);
11056 if (ICmpInst::isEquality(Pred) ||
11057 (ICmpInst::isSigned(Pred) && LAdd->hasNoSignedWrap() &&
11058 RAdd->hasNoSignedWrap()) ||
11059 (ICmpInst::isUnsigned(Pred) && LAdd->hasNoUnsignedWrap() &&
11060 RAdd->hasNoUnsignedWrap())) {
11061 LHS = NewLHS;
11062 RHS = NewRHS;
11063 Changed = true;
11064 }
11065 }
11066 }
11067
11068 // (C * A) pred (C * B) --> A pred B
11069 // For equality predicates, both muls must be NUW or both must be NSW
11070 // (either suffices to make multiplication by C injective; C == 0 is
11071 // impossible because SCEV folds 0 * X to 0).
11072 // For signed ordering, C must be positive and both muls must be NSW.
11073 // For unsigned ordering, both muls must be NUW.
11074 {
11075 const SCEVConstant *C = nullptr;
11076 if (match(LHS, m_scev_Mul(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11077 match(RHS, m_scev_Mul(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11078 const auto *LMul = cast<SCEVMulExpr>(LHS);
11079 const auto *RMul = cast<SCEVMulExpr>(RHS);
11080 bool BothNUW = LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap();
11081 bool BothNSW = LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap();
11082 if ((ICmpInst::isEquality(Pred) && (BothNUW || BothNSW)) ||
11083 (ICmpInst::isSigned(Pred) && BothNSW &&
11084 C->getAPInt().isStrictlyPositive()) ||
11085 (ICmpInst::isUnsigned(Pred) && BothNUW)) {
11086 LHS = NewLHS;
11087 RHS = NewRHS;
11088 Changed = true;
11089 }
11090 }
11091 }
11092
11093 // If we're comparing an addrec with a value which is loop-invariant in the
11094 // addrec's loop, put the addrec on the left. Also make a dominance check,
11095 // as both operands could be addrecs loop-invariant in each other's loop.
11096 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
11097 const Loop *L = AR->getLoop();
11098 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
11099 std::swap(LHS, RHS);
11101 Changed = true;
11102 }
11103 }
11104
11105 // If there's a constant operand, canonicalize comparisons with boundary
11106 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
11107 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
11108 const APInt &RA = RC->getAPInt();
11109
11110 bool SimplifiedByConstantRange = false;
11111
11112 if (!ICmpInst::isEquality(Pred)) {
11114 if (ExactCR.isFullSet())
11115 return TrivialCase(true);
11116 if (ExactCR.isEmptySet())
11117 return TrivialCase(false);
11118
11119 APInt NewRHS;
11120 CmpInst::Predicate NewPred;
11121 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
11122 ICmpInst::isEquality(NewPred)) {
11123 // We were able to convert an inequality to an equality.
11124 Pred = NewPred;
11125 RHS = getConstant(NewRHS);
11126 Changed = SimplifiedByConstantRange = true;
11127 }
11128 }
11129
11130 if (!SimplifiedByConstantRange) {
11131 switch (Pred) {
11132 default:
11133 break;
11134 case ICmpInst::ICMP_EQ:
11135 case ICmpInst::ICMP_NE:
11136 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
11137 if (RA.isZero() && MatchBinarySub(LHS, LHS, RHS))
11138 Changed = true;
11139 break;
11140
11141 // The "Should have been caught earlier!" messages refer to the fact
11142 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
11143 // should have fired on the corresponding cases, and canonicalized the
11144 // check to trivial case.
11145
11146 case ICmpInst::ICMP_UGE:
11147 assert(!RA.isMinValue() && "Should have been caught earlier!");
11148 Pred = ICmpInst::ICMP_UGT;
11149 RHS = getConstant(RA - 1);
11150 Changed = true;
11151 break;
11152 case ICmpInst::ICMP_ULE:
11153 assert(!RA.isMaxValue() && "Should have been caught earlier!");
11154 Pred = ICmpInst::ICMP_ULT;
11155 RHS = getConstant(RA + 1);
11156 Changed = true;
11157 break;
11158 case ICmpInst::ICMP_SGE:
11159 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
11160 Pred = ICmpInst::ICMP_SGT;
11161 RHS = getConstant(RA - 1);
11162 Changed = true;
11163 break;
11164 case ICmpInst::ICMP_SLE:
11165 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
11166 Pred = ICmpInst::ICMP_SLT;
11167 RHS = getConstant(RA + 1);
11168 Changed = true;
11169 break;
11170 }
11171 }
11172 }
11173
11174 // a /u b == 0 => a < b
11175 // a /u b != 0 => a >= b
11176 if (ICmpInst::isEquality(Pred) && RHS->isZero() &&
11177 match(LHS, m_scev_UDiv(m_SCEV(LHS), m_SCEV(RHS)))) {
11179 Changed = true;
11180 }
11181
11182 // Check for obvious equality.
11183 if (HasSameValue(LHS, RHS)) {
11184 if (ICmpInst::isTrueWhenEqual(Pred))
11185 return TrivialCase(true);
11187 return TrivialCase(false);
11188 }
11189
11190 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
11191 // adding or subtracting 1 from one of the operands.
11192 switch (Pred) {
11193 case ICmpInst::ICMP_SLE:
11194 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
11195 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11197 Pred = ICmpInst::ICMP_SLT;
11198 Changed = true;
11199 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
11200 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
11202 Pred = ICmpInst::ICMP_SLT;
11203 Changed = true;
11204 }
11205 break;
11206 case ICmpInst::ICMP_SGE:
11207 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
11208 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
11210 Pred = ICmpInst::ICMP_SGT;
11211 Changed = true;
11212 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
11213 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11215 Pred = ICmpInst::ICMP_SGT;
11216 Changed = true;
11217 }
11218 break;
11219 case ICmpInst::ICMP_ULE:
11220 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
11221 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11223 Pred = ICmpInst::ICMP_ULT;
11224 Changed = true;
11225 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
11226 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
11227 Pred = ICmpInst::ICMP_ULT;
11228 Changed = true;
11229 }
11230 break;
11231 case ICmpInst::ICMP_UGE:
11232 // If RHS is an op we can fold the -1, try that first.
11233 // Otherwise prefer LHS to preserve the nuw flag.
11234 if ((isa<SCEVConstant>(RHS) ||
11236 isa<SCEVConstant>(cast<SCEVNAryExpr>(RHS)->getOperand(0)))) &&
11237 !getUnsignedRangeMin(RHS).isMinValue()) {
11238 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11239 Pred = ICmpInst::ICMP_UGT;
11240 Changed = true;
11241 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
11242 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11244 Pred = ICmpInst::ICMP_UGT;
11245 Changed = true;
11246 } else if (!getUnsignedRangeMin(RHS).isMinValue()) {
11247 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11248 Pred = ICmpInst::ICMP_UGT;
11249 Changed = true;
11250 }
11251 break;
11252 default:
11253 break;
11254 }
11255
11256 // TODO: More simplifications are possible here.
11257
11258 // Recursively simplify until we either hit a recursion limit or nothing
11259 // changes.
11260 if (Changed)
11261 (void)SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1);
11262
11263 return Changed;
11264}
11265
11267 return getSignedRangeMax(S).isNegative();
11268}
11269
11273
11275 return !getSignedRangeMin(S).isNegative();
11276}
11277
11281
11283 // Query push down for cases where the unsigned range is
11284 // less than sufficient.
11285 if (const auto *SExt = dyn_cast<SCEVSignExtendExpr>(S))
11286 return isKnownNonZero(SExt->getOperand(0));
11287 return getUnsignedRangeMin(S) != 0;
11288}
11289
11291 bool OrNegative) {
11292 auto NonRecursive = [OrNegative](const SCEV *S) {
11293 if (auto *C = dyn_cast<SCEVConstant>(S))
11294 return C->getAPInt().isPowerOf2() ||
11295 (OrNegative && C->getAPInt().isNegatedPowerOf2());
11296
11297 // vscale is a power-of-two.
11298 return isa<SCEVVScale>(S);
11299 };
11300
11301 if (NonRecursive(S))
11302 return true;
11303
11304 auto *Mul = dyn_cast<SCEVMulExpr>(S);
11305 if (!Mul)
11306 return false;
11307 return all_of(Mul->operands(), NonRecursive) && (OrZero || isKnownNonZero(S));
11308}
11309
11311 const SCEV *S, uint64_t M,
11313 if (M == 0)
11314 return false;
11315 if (M == 1)
11316 return true;
11317
11318 // For a constant, check that "S % M == 0".
11319 if (auto *Cst = dyn_cast<SCEVConstant>(S)) {
11320 APInt C = Cst->getAPInt();
11321 return C.urem(M) == 0;
11322 }
11323
11324 // Basic tests have failed.
11325 // Check "S % M == 0" at compile time and record runtime Assumptions.
11326 auto *STy = dyn_cast<IntegerType>(S->getType());
11327 const SCEV *SmodM =
11328 getURemExpr(S, getConstant(ConstantInt::get(STy, M, false)));
11329 const SCEV *Zero = getZero(STy);
11330
11331 // Check whether "S % M == 0" is known at compile time.
11332 if (isKnownPredicate(ICmpInst::ICMP_EQ, SmodM, Zero))
11333 return true;
11334
11335 // Check whether "S % M != 0" is known at compile time.
11336 if (isKnownPredicate(ICmpInst::ICMP_NE, SmodM, Zero))
11337 return false;
11338
11339 if (!Predicates)
11340 return false;
11341
11342 // Look through Add and AddRec expressions with nuw to improve the
11343 // precision of added predicates. S is a multiple of M if S starts with a
11344 // multiple of M and at every iteration step S only adds multiples of M.
11347 all_of(S->operands(),
11348 [&](SCEVUse Op) { return isKnownMultipleOf(Op, M, Predicates); }))
11349 return true;
11350
11351 // Similarly, look through Mul with nuw, where any operand being a
11352 // known-multiple is sufficient.
11353 if (auto *Mul = dyn_cast<SCEVMulExpr>(S))
11354 if (Mul->hasNoUnsignedWrap() && any_of(S->operands(), [&](SCEVUse Op) {
11355 return isKnownMultipleOf(Op, M, Predicates);
11356 }))
11357 return true;
11358
11359 // Similarly, look through MinMax, with no wrapping arithmetic to consider.
11360 if (isa<SCEVMinMaxExpr>(S) && all_of(S->operands(), [&](SCEVUse Op) {
11361 return isKnownMultipleOf(Op, M, Predicates);
11362 }))
11363 return true;
11364
11366
11367 // Detect redundant predicates.
11368 for (auto *A : *Predicates)
11369 if (A->implies(P, *this))
11370 return true;
11371
11372 // Only record non-redundant predicates.
11373 Predicates->push_back(P);
11374 return true;
11375}
11376
11378 return ((isKnownNonNegative(S1) && isKnownNonNegative(S2)) ||
11380}
11381
11382std::pair<const SCEV *, const SCEV *>
11384 // Compute SCEV on entry of loop L.
11385 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
11386 if (Start == getCouldNotCompute())
11387 return { Start, Start };
11388 // Compute post increment SCEV for loop L.
11389 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
11390 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
11391 return { Start, PostInc };
11392}
11393
11395 SCEVUse RHS) {
11396 // First collect all loops.
11398 getUsedLoops(LHS, LoopsUsed);
11399 getUsedLoops(RHS, LoopsUsed);
11400
11401 if (LoopsUsed.empty())
11402 return false;
11403
11404 // Domination relationship must be a linear order on collected loops.
11405#ifndef NDEBUG
11406 for (const auto *L1 : LoopsUsed)
11407 for (const auto *L2 : LoopsUsed)
11408 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
11409 DT.dominates(L2->getHeader(), L1->getHeader())) &&
11410 "Domination relationship is not a linear order");
11411#endif
11412
11413 const Loop *MDL =
11414 *llvm::max_element(LoopsUsed, [&](const Loop *L1, const Loop *L2) {
11415 return DT.properlyDominates(L1->getHeader(), L2->getHeader());
11416 });
11417
11418 // Get init and post increment value for LHS.
11419 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
11420 // if LHS contains unknown non-invariant SCEV then bail out.
11421 if (SplitLHS.first == getCouldNotCompute())
11422 return false;
11423 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
11424 // Get init and post increment value for RHS.
11425 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
11426 // if RHS contains unknown non-invariant SCEV then bail out.
11427 if (SplitRHS.first == getCouldNotCompute())
11428 return false;
11429 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
11430 // It is possible that init SCEV contains an invariant load but it does
11431 // not dominate MDL and is not available at MDL loop entry, so we should
11432 // check it here.
11433 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
11434 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
11435 return false;
11436
11437 // It seems backedge guard check is faster than entry one so in some cases
11438 // it can speed up whole estimation by short circuit
11439 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
11440 SplitRHS.second) &&
11441 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
11442}
11443
11445 SCEVUse RHS) {
11446 // Canonicalize the inputs first.
11447 (void)SimplifyICmpOperands(Pred, LHS, RHS);
11448
11449 return isKnownViaInduction(Pred, LHS, RHS) ||
11450 isKnownPredicateViaSplitting(Pred, LHS, RHS) ||
11451 isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
11452}
11453
11455 const SCEV *LHS,
11456 const SCEV *RHS) {
11457 if (isKnownPredicate(Pred, LHS, RHS))
11458 return true;
11460 return false;
11461 return std::nullopt;
11462}
11463
11465 const SCEV *RHS,
11466 const Instruction *CtxI) {
11467 // TODO: Analyze guards and assumes from Context's block.
11468 return isKnownPredicate(Pred, LHS, RHS) ||
11469 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
11470}
11471
11472std::optional<bool>
11474 const SCEV *RHS, const Instruction *CtxI) {
11475 std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
11476 if (KnownWithoutContext)
11477 return KnownWithoutContext;
11478
11479 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
11480 return true;
11482 CtxI->getParent(), ICmpInst::getInverseCmpPredicate(Pred), LHS, RHS))
11483 return false;
11484 return std::nullopt;
11485}
11486
11488 const SCEVAddRecExpr *LHS,
11489 const SCEV *RHS) {
11490 const Loop *L = LHS->getLoop();
11491 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
11492 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
11493}
11494
11495std::optional<ScalarEvolution::MonotonicPredicateType>
11497 ICmpInst::Predicate Pred) {
11498 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
11499
11500#ifndef NDEBUG
11501 // Verify an invariant: inverting the predicate should turn a monotonically
11502 // increasing change to a monotonically decreasing one, and vice versa.
11503 if (Result) {
11504 auto ResultSwapped =
11505 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
11506
11507 assert(*ResultSwapped != *Result &&
11508 "monotonicity should flip as we flip the predicate");
11509 }
11510#endif
11511
11512 return Result;
11513}
11514
11515std::optional<ScalarEvolution::MonotonicPredicateType>
11516ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
11517 ICmpInst::Predicate Pred) {
11518 // A zero step value for LHS means the induction variable is essentially a
11519 // loop invariant value. We don't really depend on the predicate actually
11520 // flipping from false to true (for increasing predicates, and the other way
11521 // around for decreasing predicates), all we care about is that *if* the
11522 // predicate changes then it only changes from false to true.
11523 //
11524 // A zero step value in itself is not very useful, but there may be places
11525 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
11526 // as general as possible.
11527
11528 // Only handle LE/LT/GE/GT predicates.
11529 if (!ICmpInst::isRelational(Pred))
11530 return std::nullopt;
11531
11532 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
11533 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
11534 "Should be greater or less!");
11535
11536 // Check that AR does not wrap.
11537 if (ICmpInst::isUnsigned(Pred)) {
11538 if (!LHS->hasNoUnsignedWrap())
11539 return std::nullopt;
11541 }
11542 assert(ICmpInst::isSigned(Pred) &&
11543 "Relational predicate is either signed or unsigned!");
11544 if (!LHS->hasNoSignedWrap())
11545 return std::nullopt;
11546
11547 const SCEV *Step = LHS->getStepRecurrence(*this);
11548
11549 if (isKnownNonNegative(Step))
11551
11552 if (isKnownNonPositive(Step))
11554
11555 return std::nullopt;
11556}
11557
11558std::optional<ScalarEvolution::LoopInvariantPredicate>
11560 const SCEV *RHS, const Loop *L,
11561 const Instruction *CtxI) {
11562 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11563 if (!isLoopInvariant(RHS, L)) {
11564 if (!isLoopInvariant(LHS, L))
11565 return std::nullopt;
11566
11567 std::swap(LHS, RHS);
11569 }
11570
11571 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11572 if (!ArLHS || ArLHS->getLoop() != L)
11573 return std::nullopt;
11574
11575 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
11576 if (!MonotonicType)
11577 return std::nullopt;
11578 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
11579 // true as the loop iterates, and the backedge is control dependent on
11580 // "ArLHS `Pred` RHS" == true then we can reason as follows:
11581 //
11582 // * if the predicate was false in the first iteration then the predicate
11583 // is never evaluated again, since the loop exits without taking the
11584 // backedge.
11585 // * if the predicate was true in the first iteration then it will
11586 // continue to be true for all future iterations since it is
11587 // monotonically increasing.
11588 //
11589 // For both the above possibilities, we can replace the loop varying
11590 // predicate with its value on the first iteration of the loop (which is
11591 // loop invariant).
11592 //
11593 // A similar reasoning applies for a monotonically decreasing predicate, by
11594 // replacing true with false and false with true in the above two bullets.
11596 auto P = Increasing ? Pred : ICmpInst::getInverseCmpPredicate(Pred);
11597
11598 if (isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
11600 RHS);
11601
11602 if (!CtxI)
11603 return std::nullopt;
11604 // Try to prove via context.
11605 // TODO: Support other cases.
11606 switch (Pred) {
11607 default:
11608 break;
11609 case ICmpInst::ICMP_ULE:
11610 case ICmpInst::ICMP_ULT: {
11611 assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!");
11612 // Given preconditions
11613 // (1) ArLHS does not cross the border of positive and negative parts of
11614 // range because of:
11615 // - Positive step; (TODO: lift this limitation)
11616 // - nuw - does not cross zero boundary;
11617 // - nsw - does not cross SINT_MAX boundary;
11618 // (2) ArLHS <s RHS
11619 // (3) RHS >=s 0
11620 // we can replace the loop variant ArLHS <u RHS condition with loop
11621 // invariant Start(ArLHS) <u RHS.
11622 //
11623 // Because of (1) there are two options:
11624 // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
11625 // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
11626 // It means that ArLHS <s RHS <=> ArLHS <u RHS.
11627 // Because of (2) ArLHS <u RHS is trivially true.
11628 // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
11629 // We can strengthen this to Start(ArLHS) <u RHS.
11630 auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
11631 if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
11632 isKnownPositive(ArLHS->getStepRecurrence(*this)) &&
11633 isKnownNonNegative(RHS) &&
11634 isKnownPredicateAt(SignFlippedPred, ArLHS, RHS, CtxI))
11636 RHS);
11637 }
11638 }
11639
11640 return std::nullopt;
11641}
11642
11643std::optional<ScalarEvolution::LoopInvariantPredicate>
11645 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11646 const Instruction *CtxI, const SCEV *MaxIter) {
11648 Pred, LHS, RHS, L, CtxI, MaxIter))
11649 return LIP;
11650 if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
11651 // Number of iterations expressed as UMIN isn't always great for expressing
11652 // the value on the last iteration. If the straightforward approach didn't
11653 // work, try the following trick: if the a predicate is invariant for X, it
11654 // is also invariant for umin(X, ...). So try to find something that works
11655 // among subexpressions of MaxIter expressed as umin.
11656 for (SCEVUse Op : UMin->operands())
11658 Pred, LHS, RHS, L, CtxI, Op))
11659 return LIP;
11660 return std::nullopt;
11661}
11662
11663std::optional<ScalarEvolution::LoopInvariantPredicate>
11665 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11666 const Instruction *CtxI, const SCEV *MaxIter) {
11667 // Try to prove the following set of facts:
11668 // - The predicate is monotonic in the iteration space.
11669 // - If the check does not fail on the 1st iteration:
11670 // - No overflow will happen during first MaxIter iterations;
11671 // - It will not fail on the MaxIter'th iteration.
11672 // If the check does fail on the 1st iteration, we leave the loop and no
11673 // other checks matter.
11674
11675 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11676 if (!isLoopInvariant(RHS, L)) {
11677 if (!isLoopInvariant(LHS, L))
11678 return std::nullopt;
11679
11680 std::swap(LHS, RHS);
11682 }
11683
11684 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
11685 if (!AR || AR->getLoop() != L)
11686 return std::nullopt;
11687
11688 // Even if both are valid, we need to consistently chose the unsigned or the
11689 // signed predicate below, not mixtures of both. For now, prefer the unsigned
11690 // predicate.
11691 Pred = Pred.dropSameSign();
11692
11693 // The predicate must be relational (i.e. <, <=, >=, >).
11694 if (!ICmpInst::isRelational(Pred))
11695 return std::nullopt;
11696
11697 // TODO: Support steps other than +/- 1.
11698 const SCEV *Step = AR->getStepRecurrence(*this);
11699 auto *One = getOne(Step->getType());
11700 auto *MinusOne = getNegativeSCEV(One);
11701 if (Step != One && Step != MinusOne)
11702 return std::nullopt;
11703
11704 // Type mismatch here means that MaxIter is potentially larger than max
11705 // unsigned value in start type, which mean we cannot prove no wrap for the
11706 // indvar.
11707 if (AR->getType() != MaxIter->getType())
11708 return std::nullopt;
11709
11710 // Value of IV on suggested last iteration.
11711 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
11712 // Does it still meet the requirement?
11713 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
11714 return std::nullopt;
11715 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
11716 // not exceed max unsigned value of this type), this effectively proves
11717 // that there is no wrap during the iteration. To prove that there is no
11718 // signed/unsigned wrap, we need to check that
11719 // Start <= Last for step = 1 or Start >= Last for step = -1.
11720 ICmpInst::Predicate NoOverflowPred =
11722 if (Step == MinusOne)
11723 NoOverflowPred = ICmpInst::getSwappedPredicate(NoOverflowPred);
11724 const SCEV *Start = AR->getStart();
11725 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
11726 return std::nullopt;
11727
11728 // Everything is fine.
11729 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
11730}
11731
11732bool ScalarEvolution::isKnownPredicateViaConstantRanges(CmpPredicate Pred,
11733 SCEVUse LHS,
11734 SCEVUse RHS) {
11735 if (HasSameValue(LHS, RHS))
11736 return ICmpInst::isTrueWhenEqual(Pred);
11737
11738 auto CheckRange = [&](bool IsSigned) {
11739 auto RangeLHS = IsSigned ? getSignedRange(LHS) : getUnsignedRange(LHS);
11740 auto RangeRHS = IsSigned ? getSignedRange(RHS) : getUnsignedRange(RHS);
11741 return RangeLHS.icmp(Pred, RangeRHS);
11742 };
11743
11744 // The check at the top of the function catches the case where the values are
11745 // known to be equal.
11746 if (Pred == CmpInst::ICMP_EQ)
11747 return false;
11748
11749 if (Pred == CmpInst::ICMP_NE) {
11750 if (CheckRange(true) || CheckRange(false))
11751 return true;
11752 auto *Diff = getMinusSCEV(LHS, RHS);
11753 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
11754 }
11755
11756 return CheckRange(CmpInst::isSigned(Pred));
11757}
11758
11759bool ScalarEvolution::isKnownPredicateViaNoOverflow(CmpPredicate Pred,
11761 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
11762 // C1 and C2 are constant integers. If either X or Y are not add expressions,
11763 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
11764 // OutC1 and OutC2.
11765 auto MatchBinaryAddToConst = [this](SCEVUse X, SCEVUse Y, APInt &OutC1,
11766 APInt &OutC2,
11767 SCEV::NoWrapFlags ExpectedFlags) {
11768 SCEVUse XNonConstOp, XConstOp;
11769 SCEVUse YNonConstOp, YConstOp;
11770 SCEV::NoWrapFlags XFlagsPresent;
11771 SCEV::NoWrapFlags YFlagsPresent;
11772
11773 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
11774 XConstOp = getZero(X->getType());
11775 XNonConstOp = X;
11776 XFlagsPresent = ExpectedFlags;
11777 }
11778 if (!isa<SCEVConstant>(XConstOp))
11779 return false;
11780
11781 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
11782 YConstOp = getZero(Y->getType());
11783 YNonConstOp = Y;
11784 YFlagsPresent = ExpectedFlags;
11785 }
11786
11787 if (YNonConstOp != XNonConstOp)
11788 return false;
11789
11790 if (!isa<SCEVConstant>(YConstOp))
11791 return false;
11792
11793 // When matching ADDs with NUW flags (and unsigned predicates), only the
11794 // second ADD (with the larger constant) requires NUW.
11795 if ((YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11796 return false;
11797 if (ExpectedFlags != SCEV::FlagNUW &&
11798 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) {
11799 return false;
11800 }
11801
11802 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
11803 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
11804
11805 return true;
11806 };
11807
11808 APInt C1;
11809 APInt C2;
11810
11811 switch (Pred) {
11812 default:
11813 break;
11814
11815 case ICmpInst::ICMP_SGE:
11816 std::swap(LHS, RHS);
11817 [[fallthrough]];
11818 case ICmpInst::ICMP_SLE:
11819 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
11820 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
11821 return true;
11822
11823 break;
11824
11825 case ICmpInst::ICMP_SGT:
11826 std::swap(LHS, RHS);
11827 [[fallthrough]];
11828 case ICmpInst::ICMP_SLT:
11829 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
11830 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
11831 return true;
11832
11833 break;
11834
11835 case ICmpInst::ICMP_UGE:
11836 std::swap(LHS, RHS);
11837 [[fallthrough]];
11838 case ICmpInst::ICMP_ULE:
11839 // (X + C1) u<= (X + C2)<nuw> for C1 u<= C2.
11840 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ule(C2))
11841 return true;
11842
11843 break;
11844
11845 case ICmpInst::ICMP_UGT:
11846 std::swap(LHS, RHS);
11847 [[fallthrough]];
11848 case ICmpInst::ICMP_ULT:
11849 // (X + C1) u< (X + C2)<nuw> if C1 u< C2.
11850 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ult(C2))
11851 return true;
11852 break;
11853 }
11854
11855 return false;
11856}
11857
11858bool ScalarEvolution::isKnownPredicateViaSplitting(CmpPredicate Pred,
11860 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
11861 return false;
11862
11863 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
11864 // the stack can result in exponential time complexity.
11865 SaveAndRestore Restore(ProvingSplitPredicate, true);
11866
11867 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
11868 //
11869 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
11870 // isKnownPredicate. isKnownPredicate is more powerful, but also more
11871 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
11872 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
11873 // use isKnownPredicate later if needed.
11874 return isKnownNonNegative(RHS) &&
11877}
11878
11879bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, CmpPredicate Pred,
11880 const SCEV *LHS, const SCEV *RHS) {
11881 // No need to even try if we know the module has no guards.
11882 if (!HasGuards)
11883 return false;
11884
11885 return any_of(*BB, [&](const Instruction &I) {
11886 using namespace llvm::PatternMatch;
11887
11888 Value *Condition;
11890 m_Value(Condition))) &&
11891 isImpliedCond(Pred, LHS, RHS, Condition, false);
11892 });
11893}
11894
11895/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
11896/// protected by a conditional between LHS and RHS. This is used to
11897/// to eliminate casts.
11899 CmpPredicate Pred,
11900 const SCEV *LHS,
11901 const SCEV *RHS) {
11902 // Interpret a null as meaning no loop, where there is obviously no guard
11903 // (interprocedural conditions notwithstanding). Do not bother about
11904 // unreachable loops.
11905 if (!L || !DT.isReachableFromEntry(L->getHeader()))
11906 return true;
11907
11908 if (VerifyIR)
11909 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
11910 "This cannot be done on broken IR!");
11911
11912
11913 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11914 return true;
11915
11916 BasicBlock *Latch = L->getLoopLatch();
11917 if (!Latch)
11918 return false;
11919
11920 CondBrInst *LoopContinuePredicate =
11922 if (LoopContinuePredicate &&
11923 isImpliedCond(Pred, LHS, RHS, LoopContinuePredicate->getCondition(),
11924 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
11925 return true;
11926
11927 // We don't want more than one activation of the following loops on the stack
11928 // -- that can lead to O(n!) time complexity.
11929 if (WalkingBEDominatingConds)
11930 return false;
11931
11932 SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
11933
11934 // See if we can exploit a trip count to prove the predicate.
11935 const auto &BETakenInfo = getBackedgeTakenInfo(L);
11936 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
11937 if (LatchBECount != getCouldNotCompute()) {
11938 // We know that Latch branches back to the loop header exactly
11939 // LatchBECount times. This means the backdege condition at Latch is
11940 // equivalent to "{0,+,1} u< LatchBECount".
11941 Type *Ty = LatchBECount->getType();
11942 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
11943 const SCEV *LoopCounter =
11944 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
11945 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
11946 LatchBECount))
11947 return true;
11948 }
11949
11950 // Check conditions due to any @llvm.assume intrinsics.
11951 for (auto &AssumeVH : AC.assumptions()) {
11952 if (!AssumeVH)
11953 continue;
11954 auto *CI = cast<CallInst>(AssumeVH);
11955 if (!DT.dominates(CI, Latch->getTerminator()))
11956 continue;
11957
11958 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
11959 return true;
11960 }
11961
11962 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
11963 return true;
11964
11965 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
11966 DTN != HeaderDTN; DTN = DTN->getIDom()) {
11967 assert(DTN && "should reach the loop header before reaching the root!");
11968
11969 BasicBlock *BB = DTN->getBlock();
11970 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
11971 return true;
11972
11973 BasicBlock *PBB = BB->getSinglePredecessor();
11974 if (!PBB)
11975 continue;
11976
11978 if (!ContBr || ContBr->getSuccessor(0) == ContBr->getSuccessor(1))
11979 continue;
11980
11981 // If we have an edge `E` within the loop body that dominates the only
11982 // latch, the condition guarding `E` also guards the backedge. This
11983 // reasoning works only for loops with a single latch.
11984 // We're constructively (and conservatively) enumerating edges within the
11985 // loop body that dominate the latch. The dominator tree better agree
11986 // with us on this:
11987 assert(DT.dominates(BasicBlockEdge(PBB, BB), Latch) && "should be!");
11988 if (isImpliedCond(Pred, LHS, RHS, ContBr->getCondition(),
11989 BB != ContBr->getSuccessor(0)))
11990 return true;
11991 }
11992
11993 return false;
11994}
11995
11997 CmpPredicate Pred,
11998 const SCEV *LHS,
11999 const SCEV *RHS) {
12000 // Do not bother proving facts for unreachable code.
12001 if (!DT.isReachableFromEntry(BB))
12002 return true;
12003 if (VerifyIR)
12004 assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
12005 "This cannot be done on broken IR!");
12006
12007 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
12008 // the facts (a >= b && a != b) separately. A typical situation is when the
12009 // non-strict comparison is known from ranges and non-equality is known from
12010 // dominating predicates. If we are proving strict comparison, we always try
12011 // to prove non-equality and non-strict comparison separately.
12012 CmpPredicate NonStrictPredicate = ICmpInst::getNonStrictCmpPredicate(Pred);
12013 const bool ProvingStrictComparison =
12014 Pred != NonStrictPredicate.dropSameSign();
12015 bool ProvedNonStrictComparison = false;
12016 bool ProvedNonEquality = false;
12017
12018 auto SplitAndProve = [&](std::function<bool(CmpPredicate)> Fn) -> bool {
12019 if (!ProvedNonStrictComparison)
12020 ProvedNonStrictComparison = Fn(NonStrictPredicate);
12021 if (!ProvedNonEquality)
12022 ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
12023 if (ProvedNonStrictComparison && ProvedNonEquality)
12024 return true;
12025 return false;
12026 };
12027
12028 if (ProvingStrictComparison) {
12029 auto ProofFn = [&](CmpPredicate P) {
12030 return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
12031 };
12032 if (SplitAndProve(ProofFn))
12033 return true;
12034 }
12035
12036 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
12037 auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
12038 const Instruction *CtxI = &BB->front();
12039 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
12040 return true;
12041 if (ProvingStrictComparison) {
12042 auto ProofFn = [&](CmpPredicate P) {
12043 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
12044 };
12045 if (SplitAndProve(ProofFn))
12046 return true;
12047 }
12048 return false;
12049 };
12050
12051 // Starting at the block's predecessor, climb up the predecessor chain, as long
12052 // as there are predecessors that can be found that have unique successors
12053 // leading to the original block.
12054 const Loop *ContainingLoop = LI.getLoopFor(BB);
12055 const BasicBlock *PredBB;
12056 if (ContainingLoop && ContainingLoop->getHeader() == BB)
12057 PredBB = ContainingLoop->getLoopPredecessor();
12058 else
12059 PredBB = BB->getSinglePredecessor();
12060 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
12061 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
12062 const CondBrInst *BlockEntryPredicate =
12063 dyn_cast<CondBrInst>(Pair.first->getTerminator());
12064 if (!BlockEntryPredicate)
12065 continue;
12066
12067 if (ProveViaCond(BlockEntryPredicate->getCondition(),
12068 BlockEntryPredicate->getSuccessor(0) != Pair.second))
12069 return true;
12070 }
12071
12072 // Check conditions due to any @llvm.assume intrinsics.
12073 for (auto &AssumeVH : AC.assumptions()) {
12074 if (!AssumeVH)
12075 continue;
12076 auto *CI = cast<CallInst>(AssumeVH);
12077 if (!DT.dominates(CI, BB))
12078 continue;
12079
12080 if (ProveViaCond(CI->getArgOperand(0), false))
12081 return true;
12082 }
12083
12084 // Check conditions due to any @llvm.experimental.guard intrinsics.
12085 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
12086 F.getParent(), Intrinsic::experimental_guard);
12087 if (GuardDecl)
12088 for (const auto *GU : GuardDecl->users())
12089 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
12090 if (Guard->getFunction() == BB->getParent() && DT.dominates(Guard, BB))
12091 if (ProveViaCond(Guard->getArgOperand(0), false))
12092 return true;
12093 return false;
12094}
12095
12097 const SCEV *LHS,
12098 const SCEV *RHS) {
12099 // Interpret a null as meaning no loop, where there is obviously no guard
12100 // (interprocedural conditions notwithstanding).
12101 if (!L)
12102 return false;
12103
12104 // Both LHS and RHS must be available at loop entry.
12106 "LHS is not available at Loop Entry");
12108 "RHS is not available at Loop Entry");
12109
12110 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
12111 return true;
12112
12113 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
12114}
12115
12116bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12117 const SCEV *RHS,
12118 const Value *FoundCondValue, bool Inverse,
12119 const Instruction *CtxI) {
12120 // False conditions implies anything. Do not bother analyzing it further.
12121 if (FoundCondValue ==
12122 ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
12123 return true;
12124
12125 if (!PendingLoopPredicates.insert(FoundCondValue).second)
12126 return false;
12127
12128 llvm::scope_exit ClearOnExit(
12129 [&]() { PendingLoopPredicates.erase(FoundCondValue); });
12130
12131 // Recursively handle And and Or conditions.
12132 const Value *Op0, *Op1;
12133 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
12134 if (!Inverse)
12135 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12136 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12137 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
12138 if (Inverse)
12139 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12140 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12141 }
12142
12143 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
12144 if (!ICI) return false;
12145
12146 // Now that we found a conditional branch that dominates the loop or controls
12147 // the loop latch. Check to see if it is the comparison we are looking for.
12148 CmpPredicate FoundPred;
12149 if (Inverse)
12150 FoundPred = ICI->getInverseCmpPredicate();
12151 else
12152 FoundPred = ICI->getCmpPredicate();
12153
12154 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
12155 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
12156
12157 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
12158}
12159
12160bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12161 const SCEV *RHS, CmpPredicate FoundPred,
12162 const SCEV *FoundLHS, const SCEV *FoundRHS,
12163 const Instruction *CtxI) {
12164 // Balance the types.
12165 if (getTypeSizeInBits(LHS->getType()) <
12166 getTypeSizeInBits(FoundLHS->getType())) {
12167 // For unsigned and equality predicates, try to prove that both found
12168 // operands fit into narrow unsigned range. If so, try to prove facts in
12169 // narrow types.
12170 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
12171 !FoundRHS->getType()->isPointerTy()) {
12172 auto *NarrowType = LHS->getType();
12173 auto *WideType = FoundLHS->getType();
12174 auto BitWidth = getTypeSizeInBits(NarrowType);
12175 const SCEV *MaxValue = getZeroExtendExpr(
12177 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
12178 MaxValue) &&
12179 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
12180 MaxValue)) {
12181 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
12182 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
12183 // We cannot preserve samesign after truncation.
12184 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred.dropSameSign(),
12185 TruncFoundLHS, TruncFoundRHS, CtxI))
12186 return true;
12187 }
12188 }
12189
12190 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
12191 return false;
12192 if (CmpInst::isSigned(Pred)) {
12193 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
12194 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
12195 } else {
12196 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
12197 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
12198 }
12199 } else if (getTypeSizeInBits(LHS->getType()) >
12200 getTypeSizeInBits(FoundLHS->getType())) {
12201 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
12202 return false;
12203 if (CmpInst::isSigned(FoundPred)) {
12204 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
12205 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
12206 } else {
12207 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
12208 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
12209 }
12210 }
12211 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
12212 FoundRHS, CtxI);
12213}
12214
12215bool ScalarEvolution::isImpliedCondBalancedTypes(
12216 CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, CmpPredicate FoundPred,
12217 SCEVUse FoundLHS, SCEVUse FoundRHS, const Instruction *CtxI) {
12219 getTypeSizeInBits(FoundLHS->getType()) &&
12220 "Types should be balanced!");
12221 // Canonicalize the query to match the way instcombine will have
12222 // canonicalized the comparison.
12223 if (SimplifyICmpOperands(Pred, LHS, RHS))
12224 if (LHS == RHS)
12225 return CmpInst::isTrueWhenEqual(Pred);
12226 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
12227 if (FoundLHS == FoundRHS)
12228 return CmpInst::isFalseWhenEqual(FoundPred);
12229
12230 // Check to see if we can make the LHS or RHS match.
12231 if (LHS == FoundRHS || RHS == FoundLHS) {
12232 if (isa<SCEVConstant>(RHS)) {
12233 std::swap(FoundLHS, FoundRHS);
12234 FoundPred = ICmpInst::getSwappedCmpPredicate(FoundPred);
12235 } else {
12236 std::swap(LHS, RHS);
12238 }
12239 }
12240
12241 // Check whether the found predicate is the same as the desired predicate.
12242 if (auto P = CmpPredicate::getMatching(FoundPred, Pred))
12243 return isImpliedCondOperands(*P, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12244
12245 // Check whether swapping the found predicate makes it the same as the
12246 // desired predicate.
12247 if (auto P = CmpPredicate::getMatching(
12248 ICmpInst::getSwappedCmpPredicate(FoundPred), Pred)) {
12249 // We can write the implication
12250 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS
12251 // using one of the following ways:
12252 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS
12253 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS
12254 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS
12255 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS
12256 // Forms 1. and 2. require swapping the operands of one condition. Don't
12257 // do this if it would break canonical constant/addrec ordering.
12259 return isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P), RHS,
12260 LHS, FoundLHS, FoundRHS, CtxI);
12261 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
12262 return isImpliedCondOperands(*P, LHS, RHS, FoundRHS, FoundLHS, CtxI);
12263
12264 // There's no clear preference between forms 3. and 4., try both. Avoid
12265 // forming getNotSCEV of pointer values as the resulting subtract is
12266 // not legal.
12267 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() &&
12268 isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P),
12269 getNotSCEV(LHS), getNotSCEV(RHS), FoundLHS,
12270 FoundRHS, CtxI))
12271 return true;
12272
12273 if (!FoundLHS->getType()->isPointerTy() &&
12274 !FoundRHS->getType()->isPointerTy() &&
12275 isImpliedCondOperands(*P, LHS, RHS, getNotSCEV(FoundLHS),
12276 getNotSCEV(FoundRHS), CtxI))
12277 return true;
12278
12279 return false;
12280 }
12281
12282 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
12284 assert(P1 != P2 && "Handled earlier!");
12285 return CmpInst::isRelational(P2) &&
12287 };
12288 if (IsSignFlippedPredicate(Pred, FoundPred)) {
12289 // Unsigned comparison is the same as signed comparison when both the
12290 // operands are non-negative or negative.
12291 if (haveSameSign(FoundLHS, FoundRHS))
12292 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12293 // Create local copies that we can freely swap and canonicalize our
12294 // conditions to "le/lt".
12295 CmpPredicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
12296 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
12297 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
12298 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
12299 CanonicalPred = ICmpInst::getSwappedCmpPredicate(CanonicalPred);
12300 CanonicalFoundPred = ICmpInst::getSwappedCmpPredicate(CanonicalFoundPred);
12301 std::swap(CanonicalLHS, CanonicalRHS);
12302 std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
12303 }
12304 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
12305 "Must be!");
12306 assert((ICmpInst::isLT(CanonicalFoundPred) ||
12307 ICmpInst::isLE(CanonicalFoundPred)) &&
12308 "Must be!");
12309 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
12310 // Use implication:
12311 // x <u y && y >=s 0 --> x <s y.
12312 // If we can prove the left part, the right part is also proven.
12313 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
12314 CanonicalRHS, CanonicalFoundLHS,
12315 CanonicalFoundRHS);
12316 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
12317 // Use implication:
12318 // x <s y && y <s 0 --> x <u y.
12319 // If we can prove the left part, the right part is also proven.
12320 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
12321 CanonicalRHS, CanonicalFoundLHS,
12322 CanonicalFoundRHS);
12323 }
12324
12325 // Check if we can make progress by sharpening ranges.
12326 if (FoundPred == ICmpInst::ICMP_NE &&
12327 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
12328
12329 const SCEVConstant *C = nullptr;
12330 const SCEV *V = nullptr;
12331
12332 if (isa<SCEVConstant>(FoundLHS)) {
12333 C = cast<SCEVConstant>(FoundLHS);
12334 V = FoundRHS;
12335 } else {
12336 C = cast<SCEVConstant>(FoundRHS);
12337 V = FoundLHS;
12338 }
12339
12340 // The guarding predicate tells us that C != V. If the known range
12341 // of V is [C, t), we can sharpen the range to [C + 1, t). The
12342 // range we consider has to correspond to same signedness as the
12343 // predicate we're interested in folding.
12344
12345 APInt Min = ICmpInst::isSigned(Pred) ?
12347
12348 if (Min == C->getAPInt()) {
12349 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
12350 // This is true even if (Min + 1) wraps around -- in case of
12351 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
12352
12353 APInt SharperMin = Min + 1;
12354
12355 switch (Pred) {
12356 case ICmpInst::ICMP_SGE:
12357 case ICmpInst::ICMP_UGE:
12358 // We know V `Pred` SharperMin. If this implies LHS `Pred`
12359 // RHS, we're done.
12360 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
12361 CtxI))
12362 return true;
12363 [[fallthrough]];
12364
12365 case ICmpInst::ICMP_SGT:
12366 case ICmpInst::ICMP_UGT:
12367 // We know from the range information that (V `Pred` Min ||
12368 // V == Min). We know from the guarding condition that !(V
12369 // == Min). This gives us
12370 //
12371 // V `Pred` Min || V == Min && !(V == Min)
12372 // => V `Pred` Min
12373 //
12374 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
12375
12376 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
12377 return true;
12378 break;
12379
12380 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
12381 case ICmpInst::ICMP_SLE:
12382 case ICmpInst::ICMP_ULE:
12383 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12384 LHS, V, getConstant(SharperMin), CtxI))
12385 return true;
12386 [[fallthrough]];
12387
12388 case ICmpInst::ICMP_SLT:
12389 case ICmpInst::ICMP_ULT:
12390 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12391 LHS, V, getConstant(Min), CtxI))
12392 return true;
12393 break;
12394
12395 default:
12396 // No change
12397 break;
12398 }
12399 }
12400 }
12401
12402 // Check whether the actual condition is beyond sufficient.
12403 if (FoundPred == ICmpInst::ICMP_EQ)
12404 if (ICmpInst::isTrueWhenEqual(Pred))
12405 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12406 return true;
12407 if (Pred == ICmpInst::ICMP_NE)
12408 if (!ICmpInst::isTrueWhenEqual(FoundPred))
12409 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12410 return true;
12411
12412 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS))
12413 return true;
12414
12415 // Otherwise assume the worst.
12416 return false;
12417}
12418
12419bool ScalarEvolution::splitBinaryAdd(SCEVUse Expr, SCEVUse &L, SCEVUse &R,
12420 SCEV::NoWrapFlags &Flags) {
12421 if (!match(Expr, m_scev_Add(m_SCEV(L), m_SCEV(R))))
12422 return false;
12423
12424 Flags = cast<SCEVAddExpr>(Expr)->getNoWrapFlags();
12425 return true;
12426}
12427
12428std::optional<APInt>
12430 // We avoid subtracting expressions here because this function is usually
12431 // fairly deep in the call stack (i.e. is called many times).
12432
12433 unsigned BW = getTypeSizeInBits(More->getType());
12434 APInt Diff(BW, 0);
12435 APInt DiffMul(BW, 1);
12436 // Try various simplifications to reduce the difference to a constant. Limit
12437 // the number of allowed simplifications to keep compile-time low.
12438 for (unsigned I = 0; I < 8; ++I) {
12439 if (More == Less)
12440 return Diff;
12441
12442 // Reduce addrecs with identical steps to their start value.
12444 const auto *LAR = cast<SCEVAddRecExpr>(Less);
12445 const auto *MAR = cast<SCEVAddRecExpr>(More);
12446
12447 if (LAR->getLoop() != MAR->getLoop())
12448 return std::nullopt;
12449
12450 // We look at affine expressions only; not for correctness but to keep
12451 // getStepRecurrence cheap.
12452 if (!LAR->isAffine() || !MAR->isAffine())
12453 return std::nullopt;
12454
12455 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
12456 return std::nullopt;
12457
12458 Less = LAR->getStart();
12459 More = MAR->getStart();
12460 continue;
12461 }
12462
12463 // Try to match a common constant multiply.
12464 auto MatchConstMul =
12465 [](const SCEV *S) -> std::optional<std::pair<const SCEV *, APInt>> {
12466 const APInt *C;
12467 const SCEV *Op;
12468 if (match(S, m_scev_Mul(m_scev_APInt(C), m_SCEV(Op))))
12469 return {{Op, *C}};
12470 return std::nullopt;
12471 };
12472 if (auto MatchedMore = MatchConstMul(More)) {
12473 if (auto MatchedLess = MatchConstMul(Less)) {
12474 if (MatchedMore->second == MatchedLess->second) {
12475 More = MatchedMore->first;
12476 Less = MatchedLess->first;
12477 DiffMul *= MatchedMore->second;
12478 continue;
12479 }
12480 }
12481 }
12482
12483 // Try to cancel out common factors in two add expressions.
12485 auto Add = [&](const SCEV *S, int Mul) {
12486 if (auto *C = dyn_cast<SCEVConstant>(S)) {
12487 if (Mul == 1) {
12488 Diff += C->getAPInt() * DiffMul;
12489 } else {
12490 assert(Mul == -1);
12491 Diff -= C->getAPInt() * DiffMul;
12492 }
12493 } else
12494 Multiplicity[S] += Mul;
12495 };
12496 auto Decompose = [&](const SCEV *S, int Mul) {
12497 if (isa<SCEVAddExpr>(S)) {
12498 for (const SCEV *Op : S->operands())
12499 Add(Op, Mul);
12500 } else
12501 Add(S, Mul);
12502 };
12503 Decompose(More, 1);
12504 Decompose(Less, -1);
12505
12506 // Check whether all the non-constants cancel out, or reduce to new
12507 // More/Less values.
12508 const SCEV *NewMore = nullptr, *NewLess = nullptr;
12509 for (const auto &[S, Mul] : Multiplicity) {
12510 if (Mul == 0)
12511 continue;
12512 if (Mul == 1) {
12513 if (NewMore)
12514 return std::nullopt;
12515 NewMore = S;
12516 } else if (Mul == -1) {
12517 if (NewLess)
12518 return std::nullopt;
12519 NewLess = S;
12520 } else
12521 return std::nullopt;
12522 }
12523
12524 // Values stayed the same, no point in trying further.
12525 if (NewMore == More || NewLess == Less)
12526 return std::nullopt;
12527
12528 More = NewMore;
12529 Less = NewLess;
12530
12531 // Reduced to constant.
12532 if (!More && !Less)
12533 return Diff;
12534
12535 // Left with variable on only one side, bail out.
12536 if (!More || !Less)
12537 return std::nullopt;
12538 }
12539
12540 // Did not reduce to constant.
12541 return std::nullopt;
12542}
12543
12544bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
12545 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12546 const SCEV *FoundRHS, const Instruction *CtxI) {
12547 // Try to recognize the following pattern:
12548 //
12549 // FoundRHS = ...
12550 // ...
12551 // loop:
12552 // FoundLHS = {Start,+,W}
12553 // context_bb: // Basic block from the same loop
12554 // known(Pred, FoundLHS, FoundRHS)
12555 //
12556 // If some predicate is known in the context of a loop, it is also known on
12557 // each iteration of this loop, including the first iteration. Therefore, in
12558 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
12559 // prove the original pred using this fact.
12560 if (!CtxI)
12561 return false;
12562 const BasicBlock *ContextBB = CtxI->getParent();
12563 // Make sure AR varies in the context block.
12564 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
12565 const Loop *L = AR->getLoop();
12566 const auto *Latch = L->getLoopLatch();
12567 // Make sure that context belongs to the loop and executes on 1st iteration
12568 // (if it ever executes at all).
12569 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12570 return false;
12571 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
12572 return false;
12573 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
12574 }
12575
12576 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
12577 const Loop *L = AR->getLoop();
12578 const auto *Latch = L->getLoopLatch();
12579 // Make sure that context belongs to the loop and executes on 1st iteration
12580 // (if it ever executes at all).
12581 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12582 return false;
12583 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
12584 return false;
12585 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
12586 }
12587
12588 return false;
12589}
12590
12591bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(CmpPredicate Pred,
12592 const SCEV *LHS,
12593 const SCEV *RHS,
12594 const SCEV *FoundLHS,
12595 const SCEV *FoundRHS) {
12596 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
12597 return false;
12598
12599 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
12600 if (!AddRecLHS)
12601 return false;
12602
12603 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12604 if (!AddRecFoundLHS)
12605 return false;
12606
12607 // We'd like to let SCEV reason about control dependencies, so we constrain
12608 // both the inequalities to be about add recurrences on the same loop. This
12609 // way we can use isLoopEntryGuardedByCond later.
12610
12611 const Loop *L = AddRecFoundLHS->getLoop();
12612 if (L != AddRecLHS->getLoop())
12613 return false;
12614
12615 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
12616 //
12617 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
12618 // ... (2)
12619 //
12620 // Informal proof for (2), assuming (1) [*]:
12621 //
12622 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
12623 //
12624 // Then
12625 //
12626 // FoundLHS s< FoundRHS s< INT_MIN - C
12627 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
12628 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
12629 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
12630 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
12631 // <=> FoundLHS + C s< FoundRHS + C
12632 //
12633 // [*]: (1) can be proved by ruling out overflow.
12634 //
12635 // [**]: This can be proved by analyzing all the four possibilities:
12636 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
12637 // (A s>= 0, B s>= 0).
12638 //
12639 // Note:
12640 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
12641 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
12642 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
12643 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
12644 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
12645 // C)".
12646
12647 std::optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
12648 if (!LDiff)
12649 return false;
12650 std::optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
12651 if (!RDiff || *LDiff != *RDiff)
12652 return false;
12653
12654 if (LDiff->isMinValue())
12655 return true;
12656
12657 APInt FoundRHSLimit;
12658
12659 if (Pred == CmpInst::ICMP_ULT) {
12660 FoundRHSLimit = -(*RDiff);
12661 } else {
12662 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
12663 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
12664 }
12665
12666 // Try to prove (1) or (2), as needed.
12667 return isAvailableAtLoopEntry(FoundRHS, L) &&
12668 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
12669 getConstant(FoundRHSLimit));
12670}
12671
12672bool ScalarEvolution::isImpliedViaMerge(CmpPredicate Pred, const SCEV *LHS,
12673 const SCEV *RHS, const SCEV *FoundLHS,
12674 const SCEV *FoundRHS, unsigned Depth) {
12675 const PHINode *LPhi = nullptr, *RPhi = nullptr;
12676
12677 llvm::scope_exit ClearOnExit([&]() {
12678 if (LPhi) {
12679 bool Erased = PendingMerges.erase(LPhi);
12680 assert(Erased && "Failed to erase LPhi!");
12681 (void)Erased;
12682 }
12683 if (RPhi) {
12684 bool Erased = PendingMerges.erase(RPhi);
12685 assert(Erased && "Failed to erase RPhi!");
12686 (void)Erased;
12687 }
12688 });
12689
12690 // Find respective Phis and check that they are not being pending.
12691 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
12692 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
12693 if (!PendingMerges.insert(Phi).second)
12694 return false;
12695 LPhi = Phi;
12696 }
12697 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
12698 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
12699 // If we detect a loop of Phi nodes being processed by this method, for
12700 // example:
12701 //
12702 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
12703 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
12704 //
12705 // we don't want to deal with a case that complex, so return conservative
12706 // answer false.
12707 if (!PendingMerges.insert(Phi).second)
12708 return false;
12709 RPhi = Phi;
12710 }
12711
12712 // If none of LHS, RHS is a Phi, nothing to do here.
12713 if (!LPhi && !RPhi)
12714 return false;
12715
12716 // If there is a SCEVUnknown Phi we are interested in, make it left.
12717 if (!LPhi) {
12718 std::swap(LHS, RHS);
12719 std::swap(FoundLHS, FoundRHS);
12720 std::swap(LPhi, RPhi);
12722 }
12723
12724 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
12725 const BasicBlock *LBB = LPhi->getParent();
12726 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12727
12728 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
12729 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
12730 isImpliedCondOperandsViaRanges(Pred, S1, S2, Pred, FoundLHS, FoundRHS) ||
12731 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
12732 };
12733
12734 if (RPhi && RPhi->getParent() == LBB) {
12735 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
12736 // If we compare two Phis from the same block, and for each entry block
12737 // the predicate is true for incoming values from this block, then the
12738 // predicate is also true for the Phis.
12739 for (const BasicBlock *IncBB : predecessors(LBB)) {
12740 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12741 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
12742 if (!ProvedEasily(L, R))
12743 return false;
12744 }
12745 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
12746 // Case two: RHS is also a Phi from the same basic block, and it is an
12747 // AddRec. It means that there is a loop which has both AddRec and Unknown
12748 // PHIs, for it we can compare incoming values of AddRec from above the loop
12749 // and latch with their respective incoming values of LPhi.
12750 // TODO: Generalize to handle loops with many inputs in a header.
12751 if (LPhi->getNumIncomingValues() != 2) return false;
12752
12753 auto *RLoop = RAR->getLoop();
12754 auto *Predecessor = RLoop->getLoopPredecessor();
12755 assert(Predecessor && "Loop with AddRec with no predecessor?");
12756 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
12757 if (!ProvedEasily(L1, RAR->getStart()))
12758 return false;
12759 auto *Latch = RLoop->getLoopLatch();
12760 assert(Latch && "Loop with AddRec with no latch?");
12761 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
12762 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
12763 return false;
12764 } else {
12765 // In all other cases go over inputs of LHS and compare each of them to RHS,
12766 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
12767 // At this point RHS is either a non-Phi, or it is a Phi from some block
12768 // different from LBB.
12769 for (const BasicBlock *IncBB : predecessors(LBB)) {
12770 // Check that RHS is available in this block.
12771 if (!dominates(RHS, IncBB))
12772 return false;
12773 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12774 // Make sure L does not refer to a value from a potentially previous
12775 // iteration of a loop.
12776 if (!properlyDominates(L, LBB))
12777 return false;
12778 // Addrecs are considered to properly dominate their loop, so are missed
12779 // by the previous check. Discard any values that have computable
12780 // evolution in this loop.
12781 if (auto *Loop = LI.getLoopFor(LBB))
12783 return false;
12784 if (!ProvedEasily(L, RHS))
12785 return false;
12786 }
12787 }
12788 return true;
12789}
12790
12791bool ScalarEvolution::isImpliedCondOperandsViaShift(CmpPredicate Pred,
12792 const SCEV *LHS,
12793 const SCEV *RHS,
12794 const SCEV *FoundLHS,
12795 const SCEV *FoundRHS) {
12796 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make
12797 // sure that we are dealing with same LHS.
12798 if (RHS == FoundRHS) {
12799 std::swap(LHS, RHS);
12800 std::swap(FoundLHS, FoundRHS);
12802 }
12803 if (LHS != FoundLHS)
12804 return false;
12805
12806 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
12807 if (!SUFoundRHS)
12808 return false;
12809
12810 Value *Shiftee, *ShiftValue;
12811
12812 using namespace PatternMatch;
12813 if (match(SUFoundRHS->getValue(),
12814 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
12815 auto *ShifteeS = getSCEV(Shiftee);
12816 // Prove one of the following:
12817 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
12818 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
12819 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12820 // ---> LHS <s RHS
12821 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12822 // ---> LHS <=s RHS
12823 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
12824 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
12825 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
12826 if (isKnownNonNegative(ShifteeS))
12827 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
12828 }
12829
12830 return false;
12831}
12832
12833bool ScalarEvolution::isImpliedCondOperandsViaMatchingDiff(
12834 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12835 const SCEV *FoundRHS) {
12836 // Only valid for equality predicates: (A == B) implies (C == D) when
12837 // the SCEV difference A - B equals C - D (they check the same
12838 // underlying relationship at every iteration).
12839 if (!ICmpInst::isEquality(Pred))
12840 return false;
12841
12842 // Restrict to cases involving loop recurrences - that's where this
12843 // pattern arises (correlated IV comparisons). This avoids calling
12844 // getMinusSCEV on arbitrary non-loop expressions.
12846 (!isa<SCEVAddRecExpr>(FoundLHS) && !isa<SCEVAddRecExpr>(FoundRHS)))
12847 return false;
12848
12849 // AddRecs from different loops can never produce matching differences.
12850 const SCEVAddRecExpr *QueryAddRec = dyn_cast<SCEVAddRecExpr>(LHS);
12851 if (!QueryAddRec)
12852 QueryAddRec = cast<SCEVAddRecExpr>(RHS);
12853 const SCEVAddRecExpr *FoundAddRec = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12854 if (!FoundAddRec)
12855 FoundAddRec = cast<SCEVAddRecExpr>(FoundRHS);
12856 if (QueryAddRec->getLoop() != FoundAddRec->getLoop())
12857 return false;
12858
12859 // If the strides differ, the differences can never match.
12860 if (QueryAddRec->getStepRecurrence(*this) !=
12861 FoundAddRec->getStepRecurrence(*this))
12862 return false;
12863
12864 // Compute differences. For pointer-typed operands sharing the same base,
12865 // getMinusSCEV strips the common base and returns an integer SCEV.
12866 // For example, {base,+,8} - (base+8*n) = {-8n,+,8}
12867 const SCEV *FoundDiff = getMinusSCEV(FoundLHS, FoundRHS);
12868 if (isa<SCEVCouldNotCompute>(FoundDiff))
12869 return false;
12870
12871 const SCEV *Diff = getMinusSCEV(LHS, RHS);
12872 if (isa<SCEVCouldNotCompute>(Diff))
12873 return false;
12874
12875 return Diff == FoundDiff;
12876}
12877
12878bool ScalarEvolution::isImpliedCondOperands(CmpPredicate Pred, const SCEV *LHS,
12879 const SCEV *RHS,
12880 const SCEV *FoundLHS,
12881 const SCEV *FoundRHS,
12882 const Instruction *CtxI) {
12883 return isImpliedCondOperandsViaRanges(Pred, LHS, RHS, Pred, FoundLHS,
12884 FoundRHS) ||
12885 isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS,
12886 FoundRHS) ||
12887 isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS) ||
12888 isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12889 CtxI) ||
12890 isImpliedCondOperandsViaMatchingDiff(Pred, LHS, RHS, FoundLHS,
12891 FoundRHS) ||
12892 isImpliedCondOperandsHelper(Pred, LHS, RHS, FoundLHS, FoundRHS);
12893}
12894
12895/// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
12896template <typename MinMaxExprType>
12897static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
12898 const SCEV *Candidate) {
12899 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12900 if (!MinMaxExpr)
12901 return false;
12902
12903 return is_contained(MinMaxExpr->operands(), Candidate);
12904}
12905
12907 CmpPredicate Pred, const SCEV *LHS,
12908 const SCEV *RHS) {
12909 // If both sides are affine addrecs for the same loop, with equal
12910 // steps, and we know the recurrences don't wrap, then we only
12911 // need to check the predicate on the starting values.
12912
12913 if (!ICmpInst::isRelational(Pred))
12914 return false;
12915
12916 const SCEV *LStart, *RStart, *Step;
12917 const Loop *L;
12918 if (!match(LHS,
12919 m_scev_AffineAddRec(m_SCEV(LStart), m_SCEV(Step), m_Loop(L))) ||
12921 m_SpecificLoop(L))))
12922 return false;
12927 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
12928 return false;
12929
12930 return SE.isKnownPredicate(Pred, LStart, RStart);
12931}
12932
12933/// Is LHS `Pred` RHS true because one of them is an AddRec that is known not to
12934/// go below its own start value?
12936 CmpPredicate Pred,
12937 const SCEV *LHS,
12938 const SCEV *RHS) {
12939 // Normalize to (AddRec Pred Start).
12942 std::swap(LHS, RHS);
12943 }
12944
12945 // The recurrence is equal to Start in the first iteration, so only the
12946 // non-strict predicate holds.
12947 if (Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE)
12948 return false;
12949
12950 const auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
12951 if (!AR || AR->getStart() != RHS)
12952 return false;
12953
12954 return SE.getMonotonicPredicateType(AR, Pred) ==
12956}
12957
12958/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
12959/// expression?
12961 const SCEV *LHS, const SCEV *RHS) {
12962 switch (Pred) {
12963 default:
12964 return false;
12965
12966 case ICmpInst::ICMP_SGE:
12967 std::swap(LHS, RHS);
12968 [[fallthrough]];
12969 case ICmpInst::ICMP_SLE:
12970 return
12971 // min(A, ...) <= A
12973 // A <= max(A, ...)
12975
12976 case ICmpInst::ICMP_UGE:
12977 std::swap(LHS, RHS);
12978 [[fallthrough]];
12979 case ICmpInst::ICMP_ULE:
12980 return
12981 // min(A, ...) <= A
12982 // FIXME: what about umin_seq?
12984 // A <= max(A, ...)
12986
12987 case ICmpInst::ICMP_UGT:
12988 std::swap(LHS, RHS);
12989 [[fallthrough]];
12990 case ICmpInst::ICMP_ULT:
12991 // umin(Ops) u<= each Op, so proving Op u< RHS for any Op proves
12992 // umin(Ops) u< RHS.
12993 //
12994 // Use computeConstantDifference instead of the more powerful
12995 // isKnownPredicate to keep this check cheap: isKnownPredicateViaMinOrMax
12996 // is called from isKnownViaNonRecursiveReasoning, so recursing into
12997 // the full predicate prover would be expensive.
12998 if (const auto *Min = dyn_cast<SCEVUMinExpr>(LHS)) {
12999 for (SCEVUse Op : Min->operands()) {
13000 std::optional<APInt> Diff = SE.computeConstantDifference(RHS, Op);
13001 // When Op and RHS share a common base differing by a
13002 // constant offset D (RHS - Op = D), Op u< RHS holds iff D != 0 and
13003 // RHS >= D (unsigned), i.e. the subtraction doesn't underflow.
13004 if (Diff && !Diff->isZero() && SE.getUnsignedRangeMin(RHS).uge(*Diff))
13005 return true;
13006 }
13007 }
13008 return false;
13009 }
13010
13011 llvm_unreachable("covered switch fell through?!");
13012}
13013
13014bool ScalarEvolution::isImpliedViaOperations(CmpPredicate Pred, const SCEV *LHS,
13015 const SCEV *RHS,
13016 const SCEV *FoundLHS,
13017 const SCEV *FoundRHS,
13018 unsigned Depth) {
13021 "LHS and RHS have different sizes?");
13022 assert(getTypeSizeInBits(FoundLHS->getType()) ==
13023 getTypeSizeInBits(FoundRHS->getType()) &&
13024 "FoundLHS and FoundRHS have different sizes?");
13025 // We want to avoid hurting the compile time with analysis of too big trees.
13027 return false;
13028
13029 // We only want to work with GT comparison so far.
13030 if (ICmpInst::isLT(Pred)) {
13032 std::swap(LHS, RHS);
13033 std::swap(FoundLHS, FoundRHS);
13034 }
13035
13037
13038 // For unsigned, try to reduce it to corresponding signed comparison.
13039 if (P == ICmpInst::ICMP_UGT)
13040 // We can replace unsigned predicate with its signed counterpart if all
13041 // involved values are non-negative.
13042 // TODO: We could have better support for unsigned.
13043 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
13044 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
13045 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
13046 // use this fact to prove that LHS and RHS are non-negative.
13047 const SCEV *MinusOne = getMinusOne(LHS->getType());
13048 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
13049 FoundRHS) &&
13050 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
13051 FoundRHS))
13053 }
13054
13055 if (P != ICmpInst::ICMP_SGT)
13056 return false;
13057
13058 auto GetOpFromSExt = [&](const SCEV *S) -> const SCEV * {
13059 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
13060 return Ext->getOperand();
13061 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
13062 // the constant in some cases.
13063 return S;
13064 };
13065
13066 // Acquire values from extensions.
13067 auto *OrigLHS = LHS;
13068 auto *OrigFoundLHS = FoundLHS;
13069 LHS = GetOpFromSExt(LHS);
13070 FoundLHS = GetOpFromSExt(FoundLHS);
13071
13072 // Is the SGT predicate can be proved trivially or using the found context.
13073 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
13074 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
13075 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
13076 FoundRHS, Depth + 1);
13077 };
13078
13079 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
13080 // We want to avoid creation of any new non-constant SCEV. Since we are
13081 // going to compare the operands to RHS, we should be certain that we don't
13082 // need any size extensions for this. So let's decline all cases when the
13083 // sizes of types of LHS and RHS do not match.
13084 // TODO: Maybe try to get RHS from sext to catch more cases?
13086 return false;
13087
13088 // Should not overflow.
13089 if (!LHSAddExpr->hasNoSignedWrap())
13090 return false;
13091
13092 SCEVUse LL = LHSAddExpr->getOperand(0);
13093 SCEVUse LR = LHSAddExpr->getOperand(1);
13094 auto *MinusOne = getMinusOne(RHS->getType());
13095
13096 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
13097 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
13098 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
13099 };
13100 // Try to prove the following rule:
13101 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
13102 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
13103 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
13104 return true;
13105 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
13106 Value *LL, *LR;
13107 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
13108
13109 using namespace llvm::PatternMatch;
13110
13111 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
13112 // Rules for division.
13113 // We are going to perform some comparisons with Denominator and its
13114 // derivative expressions. In general case, creating a SCEV for it may
13115 // lead to a complex analysis of the entire graph, and in particular it
13116 // can request trip count recalculation for the same loop. This would
13117 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
13118 // this, we only want to create SCEVs that are constants in this section.
13119 // So we bail if Denominator is not a constant.
13120 if (!isa<ConstantInt>(LR))
13121 return false;
13122
13123 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
13124
13125 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
13126 // then a SCEV for the numerator already exists and matches with FoundLHS.
13127 auto *Numerator = getExistingSCEV(LL);
13128 if (!Numerator || Numerator->getType() != FoundLHS->getType())
13129 return false;
13130
13131 // Make sure that the numerator matches with FoundLHS and the denominator
13132 // is positive.
13133 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
13134 return false;
13135
13136 auto *DTy = Denominator->getType();
13137 auto *FRHSTy = FoundRHS->getType();
13138 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
13139 // One of types is a pointer and another one is not. We cannot extend
13140 // them properly to a wider type, so let us just reject this case.
13141 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
13142 // to avoid this check.
13143 return false;
13144
13145 // Given that:
13146 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
13147 auto *WTy = getWiderType(DTy, FRHSTy);
13148 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
13149 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
13150
13151 // Try to prove the following rule:
13152 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
13153 // For example, given that FoundLHS > 2. It means that FoundLHS is at
13154 // least 3. If we divide it by Denominator < 4, we will have at least 1.
13155 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
13156 if (isKnownNonPositive(RHS) &&
13157 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
13158 return true;
13159
13160 // Try to prove the following rule:
13161 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
13162 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
13163 // If we divide it by Denominator > 2, then:
13164 // 1. If FoundLHS is negative, then the result is 0.
13165 // 2. If FoundLHS is non-negative, then the result is non-negative.
13166 // Anyways, the result is non-negative.
13167 auto *MinusOne = getMinusOne(WTy);
13168 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
13169 if (isKnownNegative(RHS) &&
13170 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
13171 return true;
13172 }
13173 }
13174
13175 // If our expression contained SCEVUnknown Phis, and we split it down and now
13176 // need to prove something for them, try to prove the predicate for every
13177 // possible incoming values of those Phis.
13178 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
13179 return true;
13180
13181 return false;
13182}
13183
13185 const SCEV *RHS) {
13186 // zext x u<= sext x, sext x s<= zext x
13187 const SCEV *Op;
13188 switch (Pred) {
13189 case ICmpInst::ICMP_SGE:
13190 std::swap(LHS, RHS);
13191 [[fallthrough]];
13192 case ICmpInst::ICMP_SLE: {
13193 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt.
13194 return match(LHS, m_scev_SExt(m_SCEV(Op))) &&
13196 }
13197 case ICmpInst::ICMP_UGE:
13198 std::swap(LHS, RHS);
13199 [[fallthrough]];
13200 case ICmpInst::ICMP_ULE: {
13201 // If operand >=u 0 then ZExt == SExt. If operand <u 0 then ZExt <u SExt.
13202 return match(LHS, m_scev_ZExt(m_SCEV(Op))) &&
13204 }
13205 default:
13206 return false;
13207 };
13208 llvm_unreachable("unhandled case");
13209}
13210
13211bool ScalarEvolution::isKnownViaNonRecursiveReasoning(CmpPredicate Pred,
13212 SCEVUse LHS,
13213 SCEVUse RHS) {
13214 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
13215 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
13216 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
13217 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
13219 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
13220}
13221
13222bool ScalarEvolution::isImpliedCondOperandsHelper(CmpPredicate Pred,
13223 const SCEV *LHS,
13224 const SCEV *RHS,
13225 const SCEV *FoundLHS,
13226 const SCEV *FoundRHS) {
13227 switch (Pred) {
13228 default:
13229 llvm_unreachable("Unexpected CmpPredicate value!");
13230 case ICmpInst::ICMP_EQ:
13231 case ICmpInst::ICMP_NE:
13232 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
13233 return true;
13234 break;
13235 case ICmpInst::ICMP_SLT:
13236 case ICmpInst::ICMP_SLE:
13237 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
13238 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
13239 return true;
13240 break;
13241 case ICmpInst::ICMP_SGT:
13242 case ICmpInst::ICMP_SGE:
13243 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
13244 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
13245 return true;
13246 break;
13247 case ICmpInst::ICMP_ULT:
13248 case ICmpInst::ICMP_ULE:
13249 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
13250 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
13251 return true;
13252 break;
13253 case ICmpInst::ICMP_UGT:
13254 case ICmpInst::ICMP_UGE:
13255 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
13256 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
13257 return true;
13258 break;
13259 }
13260
13261 // Maybe it can be proved via operations?
13262 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
13263 return true;
13264
13265 return false;
13266}
13267
13268bool ScalarEvolution::isImpliedCondOperandsViaRanges(
13269 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, CmpPredicate FoundPred,
13270 const SCEV *FoundLHS, const SCEV *FoundRHS) {
13271 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
13272 // The restriction on `FoundRHS` be lifted easily -- it exists only to
13273 // reduce the compile time impact of this optimization.
13274 return false;
13275
13276 std::optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
13277 if (!Addend)
13278 return false;
13279
13280 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
13281
13282 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
13283 // antecedent "`FoundLHS` `FoundPred` `FoundRHS`".
13284 ConstantRange FoundLHSRange =
13285 ConstantRange::makeExactICmpRegion(FoundPred, ConstFoundRHS);
13286
13287 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
13288 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
13289
13290 // We can also compute the range of values for `LHS` that satisfy the
13291 // consequent, "`LHS` `Pred` `RHS`":
13292 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
13293 // The antecedent implies the consequent if every value of `LHS` that
13294 // satisfies the antecedent also satisfies the consequent.
13295 return LHSRange.icmp(Pred, ConstRHS);
13296}
13297
13298bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
13299 bool IsSigned, bool Invert) {
13300 assert(isKnownPositive(Stride) && "Positive stride expected!");
13301
13302 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13303 const SCEV *One = getOne(Stride->getType());
13304
13305 if (IsSigned) {
13306 APInt MaxRHS = getRangeMax(RHS, /*IsSigned=*/true, Invert);
13307 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
13308 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13309
13310 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
13311 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
13312 }
13313
13314 APInt MaxRHS = getRangeMax(RHS, /*IsSigned=*/false, Invert);
13315 APInt MaxValue = APInt::getMaxValue(BitWidth);
13316 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13317
13318 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
13319 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
13320}
13321
13323 // umin(N, 1) + floor((N - umin(N, 1)) / D)
13324 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
13325 // expression fixes the case of N=0.
13326 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
13327 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
13328 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
13329}
13330
13331const SCEV *
13332ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, const SCEV *Stride,
13333 const SCEV *End, unsigned BitWidth,
13334 bool IsSigned, bool Invert) {
13335 // The logic in this function assumes we can represent a positive stride.
13336 // If we can't, the backedge-taken count must be zero.
13337 if (IsSigned && BitWidth == 1)
13338 return getZero(Stride->getType());
13339
13340 // This code below only been closely audited for negative strides in the
13341 // unsigned comparison case, it may be correct for signed comparison, but
13342 // that needs to be established.
13343 if (IsSigned && isKnownNegative(Stride))
13344 return getCouldNotCompute();
13345
13346 // Calculate the maximum backedge count based on the range of values
13347 // permitted by Start, End, and Stride. If Invert is true, both Start and End
13348 // need inverting. Stride was already negated by the caller.
13349 APInt MinStart = getRangeMin(Start, IsSigned, Invert);
13350
13351 APInt MinStride =
13352 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
13353
13354 // We assume either the stride is positive, or the backedge-taken count
13355 // is zero. So force StrideForMaxBECount to be at least one.
13356 APInt One(BitWidth, 1);
13357 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
13358 : APIntOps::umax(One, MinStride);
13359
13360 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
13361 : APInt::getMaxValue(BitWidth);
13362 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
13363
13364 // Although End can be a MAX expression we estimate MaxEnd considering only
13365 // the case End = RHS of the loop termination condition. This is safe because
13366 // in the other case (End - Start) is zero, leading to a zero maximum backedge
13367 // taken count.
13368 APInt MaxEnd = getRangeMax(End, IsSigned, Invert);
13369 MaxEnd =
13370 IsSigned ? APIntOps::smin(MaxEnd, Limit) : APIntOps::umin(MaxEnd, Limit);
13371
13372 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
13373 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
13374 : APIntOps::umax(MaxEnd, MinStart);
13375
13376 APInt Delta = MaxEnd - MinStart;
13377
13378 // Try to refine Delta in case End - Start (or Start - End if Invert) gives a
13379 // tighter bound after folding.
13380 const SCEV *DeltaExpr =
13381 Invert ? getMinusSCEV(Start, End) : getMinusSCEV(End, Start);
13382 Delta = APIntOps::umin(Delta, getUnsignedRangeMax(DeltaExpr));
13383
13384 return getUDivCeilSCEV(getConstant(Delta), getConstant(StrideForMaxBECount));
13385}
13386
13388ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
13389 const Loop *L, bool IsSigned,
13390 bool ControlsOnlyExit, bool AllowPredicates) {
13392
13394 bool PredicatedIV = false;
13395 if (!IV) {
13396 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
13397 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
13398 if (AR && AR->getLoop() == L && AR->isAffine()) {
13399 auto canProveNUW = [&]() {
13400 // We can use the comparison to infer no-wrap flags only if it fully
13401 // controls the loop exit.
13402 if (!ControlsOnlyExit)
13403 return false;
13404
13405 if (!isLoopInvariant(RHS, L))
13406 return false;
13407
13408 if (!isKnownNonZero(AR->getStepRecurrence(*this)))
13409 // We need the sequence defined by AR to strictly increase in the
13410 // unsigned integer domain for the logic below to hold.
13411 return false;
13412
13413 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
13414 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
13415 // If RHS <=u Limit, then there must exist a value V in the sequence
13416 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
13417 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned
13418 // overflow occurs. This limit also implies that a signed comparison
13419 // (in the wide bitwidth) is equivalent to an unsigned comparison as
13420 // the high bits on both sides must be zero.
13421 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
13422 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
13423 Limit = Limit.zext(OuterBitWidth);
13424 return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit);
13425 };
13426 auto Flags = AR->getNoWrapFlags();
13427 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
13428 Flags = setFlags(Flags, SCEV::FlagNUW);
13429
13430 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
13431 if (AR->hasNoUnsignedWrap()) {
13432 // Emulate what getZeroExtendExpr would have done during construction
13433 // if we'd been able to infer the fact just above at that time.
13434 const SCEV *Step = AR->getStepRecurrence(*this);
13435 Type *Ty = ZExt->getType();
13436 const SCEV *S = getAddRecExpr(
13438 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
13440 }
13441 }
13442 }
13443 }
13444
13445
13446 if (!IV && AllowPredicates) {
13447 // Try to make this an AddRec using runtime tests, in the first X
13448 // iterations of this loop, where X is the SCEV expression found by the
13449 // algorithm below.
13450 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13451 PredicatedIV = true;
13452 }
13453
13454 // Avoid weird loops
13455 if (!IV || IV->getLoop() != L || !IV->isAffine())
13456 return getCouldNotCompute();
13457
13458 // A precondition of this method is that the condition being analyzed
13459 // reaches an exiting branch which dominates the latch. Given that, we can
13460 // assume that an increment which violates the nowrap specification and
13461 // produces poison must cause undefined behavior when the resulting poison
13462 // value is branched upon and thus we can conclude that the backedge is
13463 // taken no more often than would be required to produce that poison value.
13464 // Note that a well defined loop can exit on the iteration which violates
13465 // the nowrap specification if there is another exit (either explicit or
13466 // implicit/exceptional) which causes the loop to execute before the
13467 // exiting instruction we're analyzing would trigger UB.
13468 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13469 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13471
13472 const SCEV *Stride = IV->getStepRecurrence(*this);
13473 const SCEV *GuardedStride = Stride;
13474
13475 // Whether the IV may reach the maximum value before the exit is taken.
13476 bool IVMayOverflow = true;
13477
13478 bool PositiveStride = isKnownPositive(Stride);
13479 // A dominating guard may prove the stride positive.
13480 if (!PositiveStride) {
13481 const SCEV *LoopGuardedStride = applyLoopGuards(Stride, L);
13482 if (isKnownPositive(LoopGuardedStride)) {
13483 GuardedStride = LoopGuardedStride;
13484 PositiveStride = true;
13485 // Encode the context-sensitive stride > 0 fact into the expression
13486 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13487 }
13488 }
13489
13490 // Avoid negative or zero stride values.
13491 if (!PositiveStride) {
13492 // We can compute the correct backedge taken count for loops with unknown
13493 // strides if we can prove that the loop is not an infinite loop with side
13494 // effects. Here's the loop structure we are trying to handle -
13495 //
13496 // i = start
13497 // do {
13498 // A[i] = i;
13499 // i += s;
13500 // } while (i < end);
13501 //
13502 // The backedge taken count for such loops is evaluated as -
13503 // (max(end, start + stride) - start - 1) /u stride
13504 //
13505 // The additional preconditions that we need to check to prove correctness
13506 // of the above formula is as follows -
13507 //
13508 // a) IV is either nuw or nsw depending upon signedness (indicated by the
13509 // NoWrap flag).
13510 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13511 // no side effects within the loop)
13512 // c) loop has a single static exit (with no abnormal exits)
13513 //
13514 // Precondition a) implies that if the stride is negative, this is a single
13515 // trip loop. The backedge taken count formula reduces to zero in this case.
13516 //
13517 // Precondition b) and c) combine to imply that if rhs is invariant in L,
13518 // then a zero stride means the backedge can't be taken without executing
13519 // undefined behavior.
13520 //
13521 // The positive stride case is the same as isKnownPositive(Stride) returning
13522 // true (original behavior of the function).
13523 //
13524 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
13526 return getCouldNotCompute();
13527
13528 if (!isKnownNonZero(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(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(IV->getStart(), Stride);
13553 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
13554 };
13555 if (!wouldZeroStrideBeUB()) {
13556 Stride = getUMaxExpr(Stride, getOne(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, GuardedStride, IsSigned);
13563 if (IVMayOverflow && !NoWrap)
13564 return getCouldNotCompute();
13565 }
13566
13567 // On all paths just preceeding, we established the following invariant:
13568 // IV can be assumed not to overflow up to and including the exiting
13569 // iteration. We proved this in one of two ways:
13570 // 1) We can show overflow doesn't occur before the exiting iteration
13571 // 1a) canIVOverflowOnLT, and b) step of one
13572 // 2) We can show that if overflow occurs, the loop must execute UB
13573 // before any possible exit.
13574 // Note that we have not yet proved RHS invariant (in general).
13575
13576 const SCEV *Start = IV->getStart();
13577
13578 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
13579 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
13580 // Use integer-typed versions for actual computation; we can't subtract
13581 // pointers in general.
13582 const SCEV *OrigStart = Start;
13583 const SCEV *OrigRHS = RHS;
13584 if (Start->getType()->isPointerTy()) {
13585 Start = getPtrToAddrExpr(Start);
13586 if (isa<SCEVCouldNotCompute>(Start))
13587 return Start;
13588 }
13589 if (RHS->getType()->isPointerTy()) {
13592 return RHS;
13593 }
13594
13595 const SCEV *End = nullptr, *BECount = getCouldNotCompute(),
13596 *BECountIfBackedgeTaken = getCouldNotCompute();
13597 if (!isLoopInvariant(RHS, L)) {
13598 const auto *RHSAddRec = dyn_cast<SCEVAddRecExpr>(RHS);
13599 if (PositiveStride && RHSAddRec != nullptr && RHSAddRec->getLoop() == L &&
13600 any(RHSAddRec->getNoWrapFlags())) {
13601 // The structure of loop we are trying to calculate backedge count of:
13602 //
13603 // left = left_start
13604 // right = right_start
13605 //
13606 // while(left < right){
13607 // ... do something here ...
13608 // left += s1; // stride of left is s1 (s1 > 0)
13609 // right += s2; // stride of right is s2 (s2 < 0)
13610 // }
13611 //
13612
13613 const SCEV *RHSStart = RHSAddRec->getStart();
13614 const SCEV *RHSStride = RHSAddRec->getStepRecurrence(*this);
13615
13616 // If Stride - RHSStride is positive and does not overflow, we can write
13617 // backedge count as ->
13618 // ceil((End - Start) /u (Stride - RHSStride))
13619 // Where, End = max(RHSStart, Start)
13620
13621 // Check if RHSStride < 0 and Stride - RHSStride will not overflow.
13622 if (isKnownNegative(RHSStride) &&
13623 willNotOverflow(Instruction::Sub, /*Signed=*/true, Stride,
13624 RHSStride)) {
13625
13626 const SCEV *Denominator = getMinusSCEV(Stride, RHSStride);
13627 if (isKnownPositive(Denominator)) {
13628 End = IsSigned ? getSMaxExpr(RHSStart, Start)
13629 : getUMaxExpr(RHSStart, Start);
13630
13631 // We can do this because End >= Start, as End = max(RHSStart, Start)
13632 const SCEV *Delta = getMinusSCEV(End, Start);
13633
13634 BECount = getUDivCeilSCEV(Delta, Denominator);
13635 BECountIfBackedgeTaken =
13636 getUDivCeilSCEV(getMinusSCEV(RHSStart, Start), Denominator);
13637 }
13638 }
13639 }
13640 } else {
13641 // Let End = max(RHS,Start). We use the expression (End-Start)/Stride to
13642 // describe the backedge count: if the backedge is taken at least once then
13643 // End is RHS, and if not End is Start so we get a backedge count of zero.
13644 //
13645 // AddingStrideMinusOneMayOverflow has the following preconditions:
13646 //
13647 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
13648 // 2. The index variable doesn't overflow.
13649 //
13650 // Therefore, we know N exists such that
13651 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
13652 // doesn't overflow.
13653 //
13654 // Using this information, try to prove whether the addition in
13655 // "(End - Start) + (Stride - 1)" has unsigned overflow.
13656 //
13657 // If the IV cannot overflow, RHS is at least Stride - 1 below the maximum
13658 // value, so the distance End - Start is at most UMAX - (Stride - 1) and
13659 // the (Stride - 1) addition below cannot overflow.
13660 const SCEV *One = getOne(Stride->getType());
13661 bool AddingStrideMinusOneMayOverflow = IVMayOverflow && [&] {
13662 if (isKnownToBeAPowerOfTwo(Stride)) {
13663 // Suppose Stride is a power of two, and Start/End are unsigned
13664 // integers. Let UMAX be the largest representable unsigned
13665 // integer.
13666 //
13667 // By the preconditions of this function, we know
13668 // "(Start + Stride * N) >= End", and this doesn't overflow.
13669 // As a formula:
13670 //
13671 // End <= (Start + Stride * N) <= UMAX
13672 //
13673 // Subtracting Start from all the terms:
13674 //
13675 // End - Start <= Stride * N <= UMAX - Start
13676 //
13677 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore:
13678 //
13679 // End - Start <= Stride * N <= UMAX
13680 //
13681 // Stride * N is a multiple of Stride. Therefore,
13682 //
13683 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
13684 //
13685 // Since Stride is a power of two, UMAX + 1 is divisible by
13686 // Stride. Therefore, UMAX mod Stride == Stride - 1. So we can
13687 // write:
13688 //
13689 // End - Start <= Stride * N <= UMAX - Stride - 1
13690 //
13691 // Dropping the middle term:
13692 //
13693 // End - Start <= UMAX - Stride - 1
13694 //
13695 // Adding Stride - 1 to both sides:
13696 //
13697 // (End - Start) + (Stride - 1) <= UMAX
13698 //
13699 // In other words, the addition doesn't have unsigned overflow.
13700 //
13701 // A similar proof works if we treat Start/End as signed values.
13702 // Just rewrite steps before "End - Start <= Stride * N <= UMAX"
13703 // to use signed max instead of unsigned max. Note that we're
13704 // trying to prove a lack of unsigned overflow in either case.
13705 return false;
13706 }
13707 if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
13708 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End
13709 // - 1. If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1
13710 // <u End. If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End -
13711 // 1 <s End.
13712 //
13713 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 ==
13714 // End.
13715 return false;
13716 }
13717 return true;
13718 }();
13719
13720 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
13721 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!");
13722 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
13723 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
13724 // Can we prove Start - Stride < RHS, and either Start - Stride < Start or
13725 // (via !AddingStrideMinusOneMayOverflow) that (RHS - Start) + (Stride - 1)
13726 // does not overflow?
13727 if ((!AddingStrideMinusOneMayOverflow ||
13728 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart)) &&
13729 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
13730 // In this case, we can use a refined formula for computing backedge
13731 // taken count. The general formula remains:
13732 // "End-Start /uceiling Stride"
13733 // We want to use the alternate formula:
13734 // "((RHS - 1) - (Start - Stride)) /u Stride"
13735 // Let's do a quick case analysis to show these are equivalent under
13736 // our preconditions.
13737 // * For RHS <= Start (End is Start), the backedge-taken count must be
13738 // zero. Together with the precondition "Start - Stride < RHS", we have
13739 // "Start - Stride < RHS <= Start". Subtracting Start - Stride from
13740 // all sides we get "0 < RHS - (Start - Stride) <= Stride".
13741 // Subtracting 1 we get "0 <= (RHS - 1) - (Start - Stride) < Stride".
13742 // So dividing that by Stride gives zero.
13743 //
13744 // * For RHS > Start (End is RHS), the backedge count must be
13745 // "RHS-Start /uceil Stride", so it is sufficient to show that the
13746 // numerator "((RHS - 1) - (Start - Stride))" does not overflow.
13747 //
13748 // If "Start - Stride < Start" holds, we have
13749 // "RHS > Start > Start - Stride". As such
13750 // "RHS - (Start - Stride) - 1" does not overflow, which is the
13751 // reassociated numerator.
13752 //
13753 // Otherwise !AddingStrideMinusOneMayOverflow guarantees that
13754 // "(End - Start) + (Stride - 1)" does not overflow unsigned. Here
13755 // "End" is "RHS", as "RHS > Start", so this is the reassociated
13756 // numerator. Neither sub-term wraps unsigned: "RHS - Start"
13757 // due to "RHS > Start", and "Stride - 1", as Stride is non-zero.
13758 const SCEV *MinusOne = getMinusOne(Stride->getType());
13759 const SCEV *Numerator =
13760 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
13761 BECount = getUDivExpr(Numerator, Stride);
13762 }
13763
13764 if (isa<SCEVCouldNotCompute>(BECount)) {
13765 auto canProveRHSGreaterThanEqualStart = [&]() {
13766 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
13767 const SCEV *GuardedRHS = applyLoopGuards(OrigRHS, L);
13768 const SCEV *GuardedStart = applyLoopGuards(OrigStart, L);
13769
13770 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart) ||
13771 isKnownPredicate(CondGE, GuardedRHS, GuardedStart))
13772 return true;
13773
13774 // (RHS > Start - 1) implies RHS >= Start.
13775 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
13776 // "Start - 1" doesn't overflow.
13777 // * For signed comparison, if Start - 1 does overflow, it's equal
13778 // to INT_MAX, and "RHS >s INT_MAX" is trivially false.
13779 // * For unsigned comparison, if Start - 1 does overflow, it's equal
13780 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
13781 //
13782 // FIXME: Should isLoopEntryGuardedByCond do this for us?
13783 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13784 const SCEV *StartMinusOne =
13785 getAddExpr(OrigStart, getMinusOne(OrigStart->getType()));
13786 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
13787 };
13788
13789 // If we know that RHS >= Start in the context of loop, then we know
13790 // that max(RHS, Start) = RHS at this point.
13791 if (canProveRHSGreaterThanEqualStart()) {
13792 End = RHS;
13793 } else {
13794 // If RHS < Start, the backedge will be taken zero times. So in
13795 // general, we can write the backedge-taken count as:
13796 //
13797 // RHS >= Start ? ceil(RHS - Start) / Stride : 0
13798 //
13799 // We convert it to the following to make it more convenient for SCEV:
13800 //
13801 // ceil(max(RHS, Start) - Start) / Stride
13802 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
13803
13804 // See what would happen if we assume the backedge is taken. This is
13805 // used to compute MaxBECount.
13806 BECountIfBackedgeTaken =
13807 getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
13808 }
13809
13810 const SCEV *Delta = getMinusSCEV(End, Start);
13811 if (!AddingStrideMinusOneMayOverflow) {
13812 // floor((D + (S - 1)) / S)
13813 // We prefer this formulation if it's legal because it's fewer
13814 // operations.
13815 BECount =
13816 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13817 } else {
13818 BECount = getUDivCeilSCEV(Delta, Stride);
13819 }
13820 }
13821 }
13822
13823 const SCEV *ConstantMaxBECount;
13824 bool MaxOrZero = false;
13825 if (isa<SCEVConstant>(BECount)) {
13826 ConstantMaxBECount = BECount;
13827 } else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
13828 // If we know exactly how many times the backedge will be taken if it's
13829 // taken at least once, then the backedge count will either be that or
13830 // zero.
13831 ConstantMaxBECount = BECountIfBackedgeTaken;
13832 MaxOrZero = true;
13833 } else {
13834 ConstantMaxBECount = computeMaxBECountForLT(
13835 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned,
13836 /*Invert=*/false);
13837 }
13838
13839 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
13840 !isa<SCEVCouldNotCompute>(BECount))
13841 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
13842
13843 const SCEV *SymbolicMaxBECount =
13844 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13845 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
13846 Predicates);
13847}
13848
13849ScalarEvolution::ExitLimit ScalarEvolution::howManyGreaterThans(
13850 const SCEV *LHS, const SCEV *RHS, const Loop *L, bool IsSigned,
13851 bool ControlsOnlyExit, bool AllowPredicates) {
13853 // We handle only IV > Invariant
13854 if (!isLoopInvariant(RHS, L))
13855 return getCouldNotCompute();
13856
13857 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
13858 if (!IV && AllowPredicates)
13859 // Try to make this an AddRec using runtime tests, in the first X
13860 // iterations of this loop, where X is the SCEV expression found by the
13861 // algorithm below.
13862 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13863
13864 // Avoid weird loops
13865 if (!IV || IV->getLoop() != L || !IV->isAffine())
13866 return getCouldNotCompute();
13867
13868 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13869 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13871
13872 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
13873
13874 // Avoid negative or zero stride values
13875 if (!isKnownPositive(Stride))
13876 return getCouldNotCompute();
13877
13878 // Avoid proven overflow cases: this will ensure that the backedge taken count
13879 // will not generate any unsigned overflow. Relaxed no-overflow conditions
13880 // exploit NoWrapFlags, allowing to optimize in presence of undefined
13881 // behaviors like the case of C language.
13882 bool MayAddOverflow = false;
13883 const SCEV *Start = IV->getStart();
13884 const SCEV *End = RHS;
13885 if (!Stride->isOne() &&
13886 canIVOverflowOnLT(RHS, Stride, IsSigned, /*Invert=*/true)) {
13887 if (!NoWrap)
13888 return getCouldNotCompute();
13889 MayAddOverflow = true;
13890 }
13891
13892 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
13893 // If we know that Start >= RHS in the context of loop, then we know that
13894 // min(RHS, Start) = RHS at this point.
13896 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
13897 End = RHS;
13898 else
13899 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
13900 }
13901
13902 if (Start->getType()->isPointerTy()) {
13903 assert(End->getType()->isPointerTy() && RHS->getType()->isPointerTy() &&
13904 "Start, End and RHS all must be pointers");
13905 Start = getPtrToAddrExpr(Start);
13906 if (isa<SCEVCouldNotCompute>(Start))
13907 return Start;
13908
13909 End = getPtrToAddrExpr(End);
13910 if (isa<SCEVCouldNotCompute>(End))
13911 return End;
13912
13915 return RHS;
13916 }
13917
13918 const SCEV *Delta = getMinusSCEV(Start, End);
13919 const SCEV *BECount;
13920 if (MayAddOverflow) {
13921 // The ceiling division instead needs Start >= End, so that (Start - End) is
13922 // the exact unsigned distance between them.
13924 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, End))
13925 return getCouldNotCompute();
13926 BECount = getUDivCeilSCEV(Delta, Stride);
13927 } else {
13928 // Compute ((Start - End) + (Stride - 1)) / Stride, if the IV cannot
13929 // overflow as it requires fewer operations.
13930 const SCEV *One = getOne(Stride->getType());
13931 BECount = getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13932 }
13933
13934 // "IV > RHS" is analyzed as the equivalent "~IV < ~RHS"; Stride is already
13935 // the negated step.
13936 const SCEV *ConstantMaxBECount =
13937 isa<SCEVConstant>(BECount)
13938 ? BECount
13939 : computeMaxBECountForLT(Start, Stride, RHS,
13940 getTypeSizeInBits(LHS->getType()), IsSigned,
13941 /*Invert=*/true);
13942
13943 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount))
13944 ConstantMaxBECount = BECount;
13945 const SCEV *SymbolicMaxBECount =
13946 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13947
13948 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
13949 Predicates);
13950}
13951
13953 ScalarEvolution &SE) const {
13954 if (Range.isFullSet()) // Infinite loop.
13955 return SE.getCouldNotCompute();
13956
13957 // If the start is a non-zero constant, shift the range to simplify things.
13958 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
13959 if (!SC->getValue()->isZero()) {
13961 Operands[0] = SE.getZero(SC->getType());
13962 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
13964 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
13965 return ShiftedAddRec->getNumIterationsInRange(
13966 Range.subtract(SC->getAPInt()), SE);
13967 // This is strange and shouldn't happen.
13968 return SE.getCouldNotCompute();
13969 }
13970
13971 // The only time we can solve this is when we have all constant indices.
13972 // Otherwise, we cannot determine the overflow conditions.
13974 return SE.getCouldNotCompute();
13975
13976 // Okay at this point we know that all elements of the chrec are constants and
13977 // that the start element is zero.
13978
13979 // First check to see if the range contains zero. If not, the first
13980 // iteration exits.
13981 unsigned BitWidth = SE.getTypeSizeInBits(getType());
13982 if (!Range.contains(APInt(BitWidth, 0)))
13983 return SE.getZero(getType());
13984
13985 if (isAffine()) {
13986 // If this is an affine expression then we have this situation:
13987 // Solve {0,+,A} in Range === Ax in Range
13988
13989 // We know that zero is in the range. If A is positive then we know that
13990 // the upper value of the range must be the first possible exit value.
13991 // If A is negative then the lower of the range is the last possible loop
13992 // value. Also note that we already checked for a full range.
13993 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
13994 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
13995
13996 // The exit value should be (End+A)/A.
13997 APInt ExitVal = (End + A).udiv(A);
13998 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
13999
14000 // Evaluate at the exit value. If we really did fall out of the valid
14001 // range, then we computed our trip count, otherwise wrap around or other
14002 // things must have happened.
14003 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
14004 if (Range.contains(Val->getValue()))
14005 return SE.getCouldNotCompute(); // Something strange happened
14006
14007 // Ensure that the previous value is in the range.
14008 assert(Range.contains(
14010 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
14011 "Linear scev computation is off in a bad way!");
14012 return SE.getConstant(ExitValue);
14013 }
14014
14015 if (isQuadratic()) {
14016 if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
14017 return SE.getConstant(*S);
14018 }
14019
14020 return SE.getCouldNotCompute();
14021}
14022
14023const SCEVAddRecExpr *
14025 assert(getNumOperands() > 1 && "AddRec with zero step?");
14026 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
14027 // but in this case we cannot guarantee that the value returned will be an
14028 // AddRec because SCEV does not have a fixed point where it stops
14029 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
14030 // may happen if we reach arithmetic depth limit while simplifying. So we
14031 // construct the returned value explicitly.
14033 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
14034 // (this + Step) is {A+B,+,B+C,+...,+,N}.
14035 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
14036 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
14037 // We know that the last operand is not a constant zero (otherwise it would
14038 // have been popped out earlier). This guarantees us that if the result has
14039 // the same last operand, then it will also not be popped out, meaning that
14040 // the returned value will be an AddRec.
14041 const SCEV *Last = getOperand(getNumOperands() - 1);
14042 assert(!Last->isZero() && "Recurrency with zero step?");
14043 Ops.push_back(Last);
14045}
14046
14047// Return true when S contains at least an undef value.
14049 return SCEVExprContains(
14050 S, [](const SCEV *S) { return match(S, m_scev_UndefOrPoison()); });
14051}
14052
14053// Return true when S contains a value that is a nullptr.
14055 return SCEVExprContains(S, [](const SCEV *S) {
14056 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
14057 return SU->getValue() == nullptr;
14058 return false;
14059 });
14060}
14061
14062/// Return the size of an element read or written by Inst.
14064 if (!isa<LoadInst, StoreInst>(Inst))
14065 return nullptr;
14067 return getSizeOfExpr(ETy, getLoadStoreType(Inst));
14068}
14069
14070//===----------------------------------------------------------------------===//
14071// SCEVCallbackVH Class Implementation
14072//===----------------------------------------------------------------------===//
14073
14075 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14076 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
14077 SE->ConstantEvolutionLoopExitValue.erase(PN);
14078 SE->eraseValueFromMap(getValPtr());
14079 // this now dangles!
14080}
14081
14082void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
14083 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14084
14085 // Forget all the expressions associated with users of the old value,
14086 // so that future queries will recompute the expressions using the new
14087 // value.
14088 SE->forgetValue(getValPtr());
14089 // this now dangles!
14090}
14091
14092ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
14093 : CallbackVH(V), SE(se) {}
14094
14095//===----------------------------------------------------------------------===//
14096// ScalarEvolution Class Implementation
14097//===----------------------------------------------------------------------===//
14098
14101 LoopInfo &LI)
14102 : F(F), DL(F.getDataLayout()), TLI(TLI), AC(AC), DT(DT), LI(LI),
14103 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
14104 LoopDispositions(64), BlockDispositions(64) {
14105 // To use guards for proving predicates, we need to scan every instruction in
14106 // relevant basic blocks, and not just terminators. Doing this is a waste of
14107 // time if the IR does not actually contain any calls to
14108 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
14109 //
14110 // This pessimizes the case where a pass that preserves ScalarEvolution wants
14111 // to _add_ guards to the module when there weren't any before, and wants
14112 // ScalarEvolution to optimize based on those guards. For now we prefer to be
14113 // efficient in lieu of being smart in that rather obscure case.
14114
14115 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
14116 F.getParent(), Intrinsic::experimental_guard);
14117 HasGuards = GuardDecl && !GuardDecl->use_empty();
14118}
14119
14121 : F(Arg.F), DL(Arg.DL), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC),
14122 DT(Arg.DT), LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
14123 ValueExprMap(std::move(Arg.ValueExprMap)),
14124 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
14125 PendingMerges(std::move(Arg.PendingMerges)),
14126 ConstantMultipleCache(std::move(Arg.ConstantMultipleCache)),
14127 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
14128 PredicatedBackedgeTakenCounts(
14129 std::move(Arg.PredicatedBackedgeTakenCounts)),
14130 BECountUsers(std::move(Arg.BECountUsers)),
14131 ConstantEvolutionLoopExitValue(
14132 std::move(Arg.ConstantEvolutionLoopExitValue)),
14133 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
14134 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
14135 LoopDispositions(std::move(Arg.LoopDispositions)),
14136 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
14137 BlockDispositions(std::move(Arg.BlockDispositions)),
14138 SCEVUsers(std::move(Arg.SCEVUsers)),
14139 UnsignedRanges(std::move(Arg.UnsignedRanges)),
14140 SignedRanges(std::move(Arg.SignedRanges)),
14141 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
14142 UniquePreds(std::move(Arg.UniquePreds)),
14143 SCEVAllocator(std::move(Arg.SCEVAllocator)),
14144 ConstantSCEVs(std::move(Arg.ConstantSCEVs)),
14145 LoopUsers(std::move(Arg.LoopUsers)),
14146 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
14147 FirstUnknown(Arg.FirstUnknown) {
14148 Arg.FirstUnknown = nullptr;
14149}
14150
14152 // Iterate through all the SCEVUnknown instances and call their
14153 // destructors, so that they release their references to their values.
14154 for (SCEVUnknown *U = FirstUnknown; U;) {
14155 SCEVUnknown *Tmp = U;
14156 U = U->Next;
14157 Tmp->~SCEVUnknown();
14158 }
14159 FirstUnknown = nullptr;
14160
14161 ExprValueMap.clear();
14162 ValueExprMap.clear();
14163 HasRecMap.clear();
14164 BackedgeTakenCounts.clear();
14165 PredicatedBackedgeTakenCounts.clear();
14166
14167 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
14168 assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
14169 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
14170 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
14171}
14172
14176
14177/// When printing a top-level SCEV for trip counts, it's helpful to include
14178/// a type for constants which are otherwise hard to disambiguate.
14179static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV* S) {
14180 if (isa<SCEVConstant>(S))
14181 OS << *S->getType() << " ";
14182 OS << *S;
14183}
14184
14186 const Loop *L) {
14187 // Print all inner loops first
14188 for (Loop *I : *L)
14189 PrintLoopInfo(OS, SE, I);
14190
14191 OS << "Loop ";
14192 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14193 OS << ": ";
14194
14195 SmallVector<BasicBlock *, 8> ExitingBlocks;
14196 L->getExitingBlocks(ExitingBlocks);
14197 if (ExitingBlocks.size() != 1)
14198 OS << "<multiple exits> ";
14199
14200 auto *BTC = SE->getBackedgeTakenCount(L);
14201 if (!isa<SCEVCouldNotCompute>(BTC)) {
14202 OS << "backedge-taken count is ";
14203 PrintSCEVWithTypeHint(OS, BTC);
14204 } else
14205 OS << "Unpredictable backedge-taken count.";
14206 OS << "\n";
14207
14208 if (ExitingBlocks.size() > 1)
14209 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14210 OS << " exit count for " << ExitingBlock->getName() << ": ";
14211 const SCEV *EC = SE->getExitCount(L, ExitingBlock);
14212 PrintSCEVWithTypeHint(OS, EC);
14213 if (isa<SCEVCouldNotCompute>(EC)) {
14214 // Retry with predicates.
14216 EC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates);
14217 if (!isa<SCEVCouldNotCompute>(EC)) {
14218 OS << "\n predicated exit count for " << ExitingBlock->getName()
14219 << ": ";
14220 PrintSCEVWithTypeHint(OS, EC);
14221 OS << "\n Predicates:\n";
14222 for (const auto *P : Predicates)
14223 P->print(OS, 4);
14224 }
14225 }
14226 OS << "\n";
14227 }
14228
14229 OS << "Loop ";
14230 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14231 OS << ": ";
14232
14233 auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
14234 if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
14235 OS << "constant max backedge-taken count is ";
14236 PrintSCEVWithTypeHint(OS, ConstantBTC);
14238 OS << ", actual taken count either this or zero.";
14239 } else {
14240 OS << "Unpredictable constant max backedge-taken count. ";
14241 }
14242
14243 OS << "\n"
14244 "Loop ";
14245 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14246 OS << ": ";
14247
14248 auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
14249 if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
14250 OS << "symbolic max backedge-taken count is ";
14251 PrintSCEVWithTypeHint(OS, SymbolicBTC);
14253 OS << ", actual taken count either this or zero.";
14254 } else {
14255 OS << "Unpredictable symbolic max backedge-taken count. ";
14256 }
14257 OS << "\n";
14258
14259 if (ExitingBlocks.size() > 1)
14260 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14261 OS << " symbolic max exit count for " << ExitingBlock->getName() << ": ";
14262 auto *ExitBTC = SE->getExitCount(L, ExitingBlock,
14264 PrintSCEVWithTypeHint(OS, ExitBTC);
14265 if (isa<SCEVCouldNotCompute>(ExitBTC)) {
14266 // Retry with predicates.
14268 ExitBTC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates,
14270 if (!isa<SCEVCouldNotCompute>(ExitBTC)) {
14271 OS << "\n predicated symbolic max exit count for "
14272 << ExitingBlock->getName() << ": ";
14273 PrintSCEVWithTypeHint(OS, ExitBTC);
14274 OS << "\n Predicates:\n";
14275 for (const auto *P : Predicates)
14276 P->print(OS, 4);
14277 }
14278 }
14279 OS << "\n";
14280 }
14281
14283 auto *PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
14284 if (PBT != BTC) {
14285 OS << "Loop ";
14286 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14287 OS << ": ";
14288 if (!isa<SCEVCouldNotCompute>(PBT)) {
14289 OS << "Predicated backedge-taken count is ";
14290 PrintSCEVWithTypeHint(OS, PBT);
14291 } else
14292 OS << "Unpredictable predicated backedge-taken count.";
14293 OS << "\n";
14294 OS << " Predicates:\n";
14295 for (const auto *P : Preds)
14296 P->print(OS, 4);
14297 }
14298 Preds.clear();
14299
14300 auto *PredConstantMax =
14302 if (PredConstantMax != ConstantBTC) {
14303 OS << "Loop ";
14304 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14305 OS << ": ";
14306 if (!isa<SCEVCouldNotCompute>(PredConstantMax)) {
14307 OS << "Predicated constant max backedge-taken count is ";
14308 PrintSCEVWithTypeHint(OS, PredConstantMax);
14309 } else
14310 OS << "Unpredictable predicated constant max backedge-taken count.";
14311 OS << "\n";
14312 OS << " Predicates:\n";
14313 for (const auto *P : Preds)
14314 P->print(OS, 4);
14315 }
14316 Preds.clear();
14317
14318 auto *PredSymbolicMax =
14320 if (SymbolicBTC != PredSymbolicMax) {
14321 OS << "Loop ";
14322 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14323 OS << ": ";
14324 if (!isa<SCEVCouldNotCompute>(PredSymbolicMax)) {
14325 OS << "Predicated symbolic max backedge-taken count is ";
14326 PrintSCEVWithTypeHint(OS, PredSymbolicMax);
14327 } else
14328 OS << "Unpredictable predicated symbolic max backedge-taken count.";
14329 OS << "\n";
14330 OS << " Predicates:\n";
14331 for (const auto *P : Preds)
14332 P->print(OS, 4);
14333 }
14334
14336 OS << "Loop ";
14337 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14338 OS << ": ";
14339 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
14340 }
14341}
14342
14343namespace llvm {
14344// Note: these overloaded operators need to be in the llvm namespace for them
14345// to be resolved correctly. If we put them outside the llvm namespace, the
14346//
14347// OS << ": " << SE.getLoopDisposition(SV, InnerL);
14348//
14349// code below "breaks" and start printing raw enum values as opposed to the
14350// string values.
14353 switch (LD) {
14355 OS << "Variant";
14356 break;
14358 OS << "Invariant";
14359 break;
14361 OS << "Uniform";
14362 break;
14364 OS << "Computable";
14365 break;
14366 }
14367 return OS;
14368}
14369
14372 switch (BD) {
14374 OS << "DoesNotDominate";
14375 break;
14377 OS << "Dominates";
14378 break;
14380 OS << "ProperlyDominates";
14381 break;
14382 }
14383 return OS;
14384}
14385} // namespace llvm
14386
14388 // ScalarEvolution's implementation of the print method is to print
14389 // out SCEV values of all instructions that are interesting. Doing
14390 // this potentially causes it to create new SCEV objects though,
14391 // which technically conflicts with the const qualifier. This isn't
14392 // observable from outside the class though, so casting away the
14393 // const isn't dangerous.
14394 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14395
14396 if (ClassifyExpressions) {
14397 OS << "Classifying expressions for: ";
14398 F.printAsOperand(OS, /*PrintType=*/false);
14399 OS << "\n";
14400 for (Instruction &I : instructions(F))
14401 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
14402 OS << I << '\n';
14403 OS << " --> ";
14404 const SCEV *SV = SE.getSCEV(&I);
14405 SV->print(OS);
14406 if (!isa<SCEVCouldNotCompute>(SV)) {
14407 OS << " U: ";
14408 SE.getUnsignedRange(SV).print(OS);
14409 OS << " S: ";
14410 SE.getSignedRange(SV).print(OS);
14411 }
14412
14413 const Loop *L = LI.getLoopFor(I.getParent());
14414
14415 SCEVUse AtUse = SE.getSCEVAtScope(SV, L);
14416 if (AtUse != SV) {
14417 OS << " --> ";
14418 OS << AtUse;
14419 if (!isa<SCEVCouldNotCompute>(AtUse)) {
14420 OS << " U: ";
14421 SE.getUnsignedRange(AtUse).print(OS);
14422 OS << " S: ";
14423 SE.getSignedRange(AtUse).print(OS);
14424 }
14425 }
14426
14427 if (L) {
14428 OS << "\t\t" "Exits: ";
14429 SCEVUse ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
14430 if (!SE.isLoopInvariant(ExitValue, L)) {
14431 OS << "<<Unknown>>";
14432 } else {
14433 OS << ExitValue;
14434 }
14435
14436 ListSeparator LS(", ", "\t\tLoopDispositions: { ");
14437 for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
14438 OS << LS;
14439 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14440 OS << ": " << SE.getLoopDisposition(SV, Iter);
14441 }
14442
14443 for (const auto *InnerL : depth_first(L)) {
14444 if (InnerL == L)
14445 continue;
14446 OS << LS;
14447 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14448 OS << ": " << SE.getLoopDisposition(SV, InnerL);
14449 }
14450
14451 OS << " }";
14452 }
14453
14454 OS << "\n";
14455 }
14456 }
14457
14458 OS << "Determining loop execution counts for: ";
14459 F.printAsOperand(OS, /*PrintType=*/false);
14460 OS << "\n";
14461 for (Loop *I : LI)
14462 PrintLoopInfo(OS, &SE, I);
14463}
14464
14467 auto &Values = LoopDispositions[S];
14468 for (auto &V : Values) {
14469 if (V.getPointer() == L)
14470 return V.getInt();
14471 }
14472 Values.emplace_back(L, LoopVariant);
14473 LoopDisposition D = computeLoopDisposition(S, L);
14474 auto &Values2 = LoopDispositions[S];
14475 for (auto &V : llvm::reverse(Values2)) {
14476 if (V.getPointer() == L) {
14477 V.setInt(D);
14478 break;
14479 }
14480 }
14481 return D;
14482}
14483
14485ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
14486 switch (S->getSCEVType()) {
14487 case scConstant:
14488 case scVScale:
14489 return LoopInvariant;
14490 case scAddRecExpr: {
14491 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14492
14493 // If L is the addrec's loop, it's computable.
14494 if (AR->getLoop() == L)
14495 return LoopComputable;
14496
14497 // Add recurrences are never invariant in the function-body (null loop).
14498 if (!L)
14499 return LoopVariant;
14500
14501 // Everything that is not defined at loop entry is variant.
14502 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) {
14503 if (L->contains(AR->getLoop()) &&
14504 llvm::all_of(AR->operands(),
14505 [&](const SCEV *Op) { return isLoopUniform(Op, L); }))
14506 return LoopUniform;
14507
14508 return LoopVariant;
14509 }
14510 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
14511 " dominate the contained loop's header?");
14512
14513 // This recurrence is invariant w.r.t. L if AR's loop contains L.
14514 if (AR->getLoop()->contains(L))
14515 return LoopInvariant;
14516
14517 // This recurrence is variant w.r.t. L if any of its operands
14518 // are variant.
14519 for (SCEVUse Op : AR->operands())
14520 if (!isLoopInvariant(Op, L))
14521 return LoopVariant;
14522
14523 // Otherwise it's loop-invariant.
14524 return LoopInvariant;
14525 }
14526 case scTruncate:
14527 case scZeroExtend:
14528 case scSignExtend:
14529 case scPtrToAddr:
14530 case scAddExpr:
14531 case scMulExpr:
14532 case scUDivExpr:
14533 case scUMaxExpr:
14534 case scSMaxExpr:
14535 case scUMinExpr:
14536 case scSMinExpr:
14537 case scSequentialUMinExpr: {
14538 bool HasVarying = false;
14539 bool HasUniform = false;
14540 for (SCEVUse Op : S->operands()) {
14542 if (D == LoopVariant)
14543 return LoopVariant;
14544 if (D == LoopComputable)
14545 HasVarying = true;
14546 if (D == LoopUniform)
14547 HasUniform = true;
14548 }
14549 return HasVarying ? (HasUniform ? LoopVariant : LoopComputable)
14550 : (HasUniform ? LoopUniform : LoopInvariant);
14551 }
14552 case scUnknown:
14553 // All non-instruction values are loop invariant. All instructions are loop
14554 // invariant if they are not contained in the specified loop.
14555 // Instructions are never considered invariant in the function body
14556 // (null loop) because they are defined within the "loop".
14558 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
14559 return LoopInvariant;
14560 case scCouldNotCompute:
14561 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14562 }
14563 llvm_unreachable("Unknown SCEV kind!");
14564}
14565
14566bool ScalarEvolution::isLoopUniform(const SCEV *S, const Loop *L) {
14568 return D == LoopUniform || D == LoopInvariant;
14569}
14570
14572 return getLoopDisposition(S, L) == LoopInvariant;
14573}
14574
14576 return getLoopDisposition(S, L) == LoopComputable;
14577}
14578
14581 auto &Values = BlockDispositions[S];
14582 for (auto &V : Values) {
14583 if (V.getPointer() == BB)
14584 return V.getInt();
14585 }
14586 Values.emplace_back(BB, DoesNotDominateBlock);
14587 BlockDisposition D = computeBlockDisposition(S, BB);
14588 auto &Values2 = BlockDispositions[S];
14589 for (auto &V : llvm::reverse(Values2)) {
14590 if (V.getPointer() == BB) {
14591 V.setInt(D);
14592 break;
14593 }
14594 }
14595 return D;
14596}
14597
14599ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
14600 switch (S->getSCEVType()) {
14601 case scConstant:
14602 case scVScale:
14604 case scAddRecExpr: {
14605 // This uses a "dominates" query instead of "properly dominates" query
14606 // to test for proper dominance too, because the instruction which
14607 // produces the addrec's value is a PHI, and a PHI effectively properly
14608 // dominates its entire containing block.
14609 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14610 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
14611 return DoesNotDominateBlock;
14612
14613 // Fall through into SCEVNAryExpr handling.
14614 [[fallthrough]];
14615 }
14616 case scTruncate:
14617 case scZeroExtend:
14618 case scSignExtend:
14619 case scPtrToAddr:
14620 case scAddExpr:
14621 case scMulExpr:
14622 case scUDivExpr:
14623 case scUMaxExpr:
14624 case scSMaxExpr:
14625 case scUMinExpr:
14626 case scSMinExpr:
14627 case scSequentialUMinExpr: {
14628 bool Proper = true;
14629 for (const SCEV *NAryOp : S->operands()) {
14631 if (D == DoesNotDominateBlock)
14632 return DoesNotDominateBlock;
14633 if (D == DominatesBlock)
14634 Proper = false;
14635 }
14636 return Proper ? ProperlyDominatesBlock : DominatesBlock;
14637 }
14638 case scUnknown:
14639 if (Instruction *I =
14641 if (I->getParent() == BB)
14642 return DominatesBlock;
14643 if (DT.properlyDominates(I->getParent(), BB))
14645 return DoesNotDominateBlock;
14646 }
14648 case scCouldNotCompute:
14649 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14650 }
14651 llvm_unreachable("Unknown SCEV kind!");
14652}
14653
14654bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
14655 return getBlockDisposition(S, BB) >= DominatesBlock;
14656}
14657
14660}
14661
14662bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
14663 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
14664}
14665
14666void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
14667 bool Predicated) {
14668 auto &BECounts =
14669 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14670 auto It = BECounts.find(L);
14671 if (It != BECounts.end()) {
14672 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
14673 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14674 if (!isa<SCEVConstant>(S)) {
14675 auto UserIt = BECountUsers.find(S);
14676 assert(UserIt != BECountUsers.end());
14677 UserIt->second.erase({L, Predicated});
14678 }
14679 }
14680 }
14681 BECounts.erase(It);
14682 }
14683}
14684
14685void ScalarEvolution::forgetMemoizedResults(ArrayRef<SCEVUse> SCEVs) {
14686 SmallPtrSet<const SCEV *, 8> ToForget(llvm::from_range, SCEVs);
14687 SmallVector<SCEVUse, 8> Worklist(ToForget.begin(), ToForget.end());
14688
14689 while (!Worklist.empty()) {
14690 const SCEV *Curr = Worklist.pop_back_val();
14691 auto Users = SCEVUsers.find(Curr);
14692 if (Users != SCEVUsers.end())
14693 for (const auto *User : Users->second)
14694 if (ToForget.insert(User).second)
14695 Worklist.push_back(User);
14696 }
14697
14698 for (const auto *S : ToForget)
14699 forgetMemoizedResultsImpl(S);
14700
14701 PredicatedSCEVRewrites.remove_if(
14702 [&](const auto &Entry) { return ToForget.count(Entry.first.first); });
14703}
14704
14705void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
14706 LoopDispositions.erase(S);
14707 BlockDispositions.erase(S);
14708 UnsignedRanges.erase(S);
14709 SignedRanges.erase(S);
14710 HasRecMap.erase(S);
14711 ConstantMultipleCache.erase(S);
14712
14713 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
14714 UnsignedWrapViaInductionTried.erase(AR);
14715 SignedWrapViaInductionTried.erase(AR);
14716 }
14717
14718 auto ExprIt = ExprValueMap.find(S);
14719 if (ExprIt != ExprValueMap.end()) {
14720 for (Value *V : ExprIt->second) {
14721 auto ValueIt = ValueExprMap.find_as(V);
14722 if (ValueIt != ValueExprMap.end())
14723 ValueExprMap.erase(ValueIt);
14724 }
14725 ExprValueMap.erase(ExprIt);
14726 }
14727
14728 auto ScopeIt = ValuesAtScopes.find(S);
14729 if (ScopeIt != ValuesAtScopes.end()) {
14730 for (const auto &Pair : ScopeIt->second)
14731 if (!isa_and_nonnull<SCEVConstant>(Pair.second))
14732 llvm::erase(ValuesAtScopesUsers[Pair.second.getPointer()],
14733 std::make_pair(Pair.first, S));
14734 ValuesAtScopes.erase(ScopeIt);
14735 }
14736
14737 auto ScopeUserIt = ValuesAtScopesUsers.find(S);
14738 if (ScopeUserIt != ValuesAtScopesUsers.end()) {
14739 for (const auto &Pair : ScopeUserIt->second)
14740 // The recorded value at scope is a use of S, which may carry no-wrap
14741 // flags that are not part of this key.
14742 llvm::erase_if(ValuesAtScopes[Pair.second], [&](const auto &LS) {
14743 return LS.first == Pair.first && LS.second.getPointer() == S;
14744 });
14745 ValuesAtScopesUsers.erase(ScopeUserIt);
14746 }
14747
14748 auto BEUsersIt = BECountUsers.find(S);
14749 if (BEUsersIt != BECountUsers.end()) {
14750 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
14751 auto Copy = BEUsersIt->second;
14752 for (const auto &Pair : Copy)
14753 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
14754 BECountUsers.erase(BEUsersIt);
14755 }
14756
14757 auto FoldUser = FoldCacheUser.find(S);
14758 if (FoldUser != FoldCacheUser.end())
14759 for (auto &KV : FoldUser->second)
14760 FoldCache.erase(KV);
14761 FoldCacheUser.erase(S);
14762}
14763
14764void
14765ScalarEvolution::getUsedLoops(const SCEV *S,
14766 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
14767 struct FindUsedLoops {
14768 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
14769 : LoopsUsed(LoopsUsed) {}
14770 SmallPtrSetImpl<const Loop *> &LoopsUsed;
14771 bool follow(const SCEV *S) {
14772 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
14773 LoopsUsed.insert(AR->getLoop());
14774 return true;
14775 }
14776
14777 bool isDone() const { return false; }
14778 };
14779
14780 FindUsedLoops F(LoopsUsed);
14781 SCEVTraversal<FindUsedLoops>(F).visitAll(S);
14782}
14783
14784void ScalarEvolution::getReachableBlocks(
14787 Worklist.push_back(&F.getEntryBlock());
14788 while (!Worklist.empty()) {
14789 BasicBlock *BB = Worklist.pop_back_val();
14790 if (!Reachable.insert(BB).second)
14791 continue;
14792
14793 Value *Cond;
14794 BasicBlock *TrueBB, *FalseBB;
14795 if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
14796 m_BasicBlock(FalseBB)))) {
14797 if (auto *C = dyn_cast<ConstantInt>(Cond)) {
14798 Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
14799 continue;
14800 }
14801
14802 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14803 const SCEV *L = getSCEV(Cmp->getOperand(0));
14804 const SCEV *R = getSCEV(Cmp->getOperand(1));
14805 if (isKnownPredicateViaConstantRanges(Cmp->getCmpPredicate(), L, R)) {
14806 Worklist.push_back(TrueBB);
14807 continue;
14808 }
14809 if (isKnownPredicateViaConstantRanges(Cmp->getInverseCmpPredicate(), L,
14810 R)) {
14811 Worklist.push_back(FalseBB);
14812 continue;
14813 }
14814 }
14815 }
14816
14817 append_range(Worklist, successors(BB));
14818 }
14819}
14820
14822 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14823 ScalarEvolution SE2(F, TLI, AC, DT, LI);
14824
14825 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
14826
14827 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
14828 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
14829 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
14830
14831 const SCEV *visitConstant(const SCEVConstant *Constant) {
14832 return SE.getConstant(Constant->getAPInt());
14833 }
14834
14835 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14836 return SE.getUnknown(Expr->getValue());
14837 }
14838
14839 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
14840 return SE.getCouldNotCompute();
14841 }
14842 };
14843
14844 SCEVMapper SCM(SE2);
14845 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
14846 SE2.getReachableBlocks(ReachableBlocks, F);
14847
14848 auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
14849 if (containsUndefs(Old) || containsUndefs(New)) {
14850 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
14851 // not propagate undef aggressively). This means we can (and do) fail
14852 // verification in cases where a transform makes a value go from "undef"
14853 // to "undef+1" (say). The transform is fine, since in both cases the
14854 // result is "undef", but SCEV thinks the value increased by 1.
14855 return nullptr;
14856 }
14857
14858 // Unless VerifySCEVStrict is set, we only compare constant deltas.
14859 const SCEV *Delta = SE2.getMinusSCEV(Old, New);
14860 if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
14861 return nullptr;
14862
14863 return Delta;
14864 };
14865
14866 while (!LoopStack.empty()) {
14867 auto *L = LoopStack.pop_back_val();
14868 llvm::append_range(LoopStack, *L);
14869
14870 // Only verify BECounts in reachable loops. For an unreachable loop,
14871 // any BECount is legal.
14872 if (!ReachableBlocks.contains(L->getHeader()))
14873 continue;
14874
14875 // Only verify cached BECounts. Computing new BECounts may change the
14876 // results of subsequent SCEV uses.
14877 auto It = BackedgeTakenCounts.find(L);
14878 if (It == BackedgeTakenCounts.end())
14879 continue;
14880
14881 auto *CurBECount =
14882 SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
14883 auto *NewBECount = SE2.getBackedgeTakenCount(L);
14884
14885 if (CurBECount == SE2.getCouldNotCompute() ||
14886 NewBECount == SE2.getCouldNotCompute()) {
14887 // NB! This situation is legal, but is very suspicious -- whatever pass
14888 // change the loop to make a trip count go from could not compute to
14889 // computable or vice-versa *should have* invalidated SCEV. However, we
14890 // choose not to assert here (for now) since we don't want false
14891 // positives.
14892 continue;
14893 }
14894
14895 if (SE.getTypeSizeInBits(CurBECount->getType()) >
14896 SE.getTypeSizeInBits(NewBECount->getType()))
14897 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
14898 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
14899 SE.getTypeSizeInBits(NewBECount->getType()))
14900 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
14901
14902 const SCEV *Delta = GetDelta(CurBECount, NewBECount);
14903 if (Delta && !Delta->isZero()) {
14904 dbgs() << "Trip Count for " << *L << " Changed!\n";
14905 dbgs() << "Old: " << *CurBECount << "\n";
14906 dbgs() << "New: " << *NewBECount << "\n";
14907 dbgs() << "Delta: " << *Delta << "\n";
14908 std::abort();
14909 }
14910 }
14911
14912 // Collect all valid loops currently in LoopInfo.
14913 SmallPtrSet<Loop *, 32> ValidLoops;
14914 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
14915 while (!Worklist.empty()) {
14916 Loop *L = Worklist.pop_back_val();
14917 if (ValidLoops.insert(L).second)
14918 Worklist.append(L->begin(), L->end());
14919 }
14920 for (const auto &KV : ValueExprMap) {
14921#ifndef NDEBUG
14922 // Check for SCEV expressions referencing invalid/deleted loops.
14923 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14924 assert(ValidLoops.contains(AR->getLoop()) &&
14925 "AddRec references invalid loop");
14926 }
14927#endif
14928
14929 // Check that the value is also part of the reverse map.
14930 auto It = ExprValueMap.find(KV.second);
14931 if (It == ExprValueMap.end() || !It->second.contains(KV.first)) {
14932 dbgs() << "Value " << *KV.first
14933 << " is in ValueExprMap but not in ExprValueMap\n";
14934 std::abort();
14935 }
14936
14937 if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
14938 if (!ReachableBlocks.contains(I->getParent()))
14939 continue;
14940 const SCEV *OldSCEV = SCM.visit(KV.second);
14941 const SCEV *NewSCEV = SE2.getSCEV(I);
14942 const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14943 if (Delta && !Delta->isZero()) {
14944 dbgs() << "SCEV for value " << *I << " changed!\n"
14945 << "Old: " << *OldSCEV << "\n"
14946 << "New: " << *NewSCEV << "\n"
14947 << "Delta: " << *Delta << "\n";
14948 std::abort();
14949 }
14950 }
14951 }
14952
14953 for (const auto &KV : ExprValueMap) {
14954 for (Value *V : KV.second) {
14955 const SCEV *S = ValueExprMap.lookup(V);
14956 if (!S) {
14957 dbgs() << "Value " << *V
14958 << " is in ExprValueMap but not in ValueExprMap\n";
14959 std::abort();
14960 }
14961 if (S != KV.first) {
14962 dbgs() << "Value " << *V << " mapped to " << *S << " rather than "
14963 << *KV.first << "\n";
14964 std::abort();
14965 }
14966 }
14967 }
14968
14969 // Verify integrity of SCEV users.
14970 for (const auto &S : UniqueSCEVs) {
14971 for (SCEVUse Op : S.operands()) {
14972 // We do not store dependencies of constants.
14973 if (isa<SCEVConstant>(Op))
14974 continue;
14975 auto It = SCEVUsers.find(Op);
14976 if (It != SCEVUsers.end() && It->second.count(&S))
14977 continue;
14978 dbgs() << "Use of operand " << *Op << " by user " << S
14979 << " is not being tracked!\n";
14980 std::abort();
14981 }
14982 }
14983
14984 // Verify integrity of ValuesAtScopes users.
14985 for (const auto &ValueAndVec : ValuesAtScopes) {
14986 const SCEV *Value = ValueAndVec.first;
14987 for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
14988 const Loop *L = LoopAndValueAtScope.first;
14989 SCEVUse ValueAtScope = LoopAndValueAtScope.second;
14990 if (!isa<SCEVConstant>(ValueAtScope)) {
14991 auto It = ValuesAtScopesUsers.find(ValueAtScope.getPointer());
14992 if (It != ValuesAtScopesUsers.end() &&
14993 is_contained(It->second, std::make_pair(L, Value)))
14994 continue;
14995 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14996 << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
14997 std::abort();
14998 }
14999 }
15000 }
15001
15002 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
15003 const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
15004 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
15005 const Loop *L = LoopAndValue.first;
15006 const SCEV *Value = LoopAndValue.second;
15008 auto It = ValuesAtScopes.find(Value);
15009 // The recorded value at scope may carry no-wrap flags that are not part
15010 // of the key it is recorded under.
15011 if (It != ValuesAtScopes.end() && any_of(It->second, [&](const auto &LS) {
15012 return LS.first == L && LS.second.getPointer() == ValueAtScope;
15013 }))
15014 continue;
15015 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
15016 << *ValueAtScope << " missing in ValuesAtScopes\n";
15017 std::abort();
15018 }
15019 }
15020
15021 // Verify integrity of BECountUsers.
15022 auto VerifyBECountUsers = [&](bool Predicated) {
15023 auto &BECounts =
15024 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
15025 for (const auto &LoopAndBEInfo : BECounts) {
15026 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
15027 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
15028 if (!isa<SCEVConstant>(S)) {
15029 auto UserIt = BECountUsers.find(S);
15030 if (UserIt != BECountUsers.end() &&
15031 UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
15032 continue;
15033 dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
15034 << " missing from BECountUsers\n";
15035 std::abort();
15036 }
15037 }
15038 }
15039 }
15040 };
15041 VerifyBECountUsers(/* Predicated */ false);
15042 VerifyBECountUsers(/* Predicated */ true);
15043
15044 // Verify intergity of loop disposition cache.
15045 for (auto &[S, Values] : LoopDispositions) {
15046 for (auto [Loop, CachedDisposition] : Values) {
15047 const auto RecomputedDisposition = SE2.getLoopDisposition(S, Loop);
15048 if (CachedDisposition != RecomputedDisposition) {
15049 dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
15050 << " is incorrect: cached " << CachedDisposition << ", actual "
15051 << RecomputedDisposition << "\n";
15052 std::abort();
15053 }
15054 }
15055 }
15056
15057 // Verify integrity of the block disposition cache.
15058 for (auto &[S, Values] : BlockDispositions) {
15059 for (auto [BB, CachedDisposition] : Values) {
15060 const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
15061 if (CachedDisposition != RecomputedDisposition) {
15062 dbgs() << "Cached disposition of " << *S << " for block %"
15063 << BB->getName() << " is incorrect: cached " << CachedDisposition
15064 << ", actual " << RecomputedDisposition << "\n";
15065 std::abort();
15066 }
15067 }
15068 }
15069
15070 // Verify FoldCache/FoldCacheUser caches.
15071 for (auto [FoldID, Expr] : FoldCache) {
15072 auto I = FoldCacheUser.find(Expr);
15073 if (I == FoldCacheUser.end()) {
15074 dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
15075 << "!\n";
15076 std::abort();
15077 }
15078 if (!is_contained(I->second, FoldID)) {
15079 dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
15080 std::abort();
15081 }
15082 }
15083 for (auto [Expr, IDs] : FoldCacheUser) {
15084 for (auto &FoldID : IDs) {
15085 const SCEV *S = FoldCache.lookup(FoldID);
15086 if (!S) {
15087 dbgs() << "Missing entry in FoldCache for expression " << *Expr
15088 << "!\n";
15089 std::abort();
15090 }
15091 if (S != Expr) {
15092 dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: " << *S
15093 << " != " << *Expr << "!\n";
15094 std::abort();
15095 }
15096 }
15097 }
15098
15099 // Verify that ConstantMultipleCache computations are correct. We check that
15100 // cached multiples and recomputed multiples are multiples of each other to
15101 // verify correctness. It is possible that a recomputed multiple is different
15102 // from the cached multiple due to strengthened no wrap flags or changes in
15103 // KnownBits computations.
15104 for (auto [S, Multiple] : ConstantMultipleCache) {
15105 APInt RecomputedMultiple = SE2.getConstantMultiple(S);
15106 if ((Multiple != 0 && RecomputedMultiple != 0 &&
15107 Multiple.urem(RecomputedMultiple) != 0 &&
15108 RecomputedMultiple.urem(Multiple) != 0)) {
15109 dbgs() << "Incorrect cached computation in ConstantMultipleCache for "
15110 << *S << " : Computed " << RecomputedMultiple
15111 << " but cache contains " << Multiple << "!\n";
15112 std::abort();
15113 }
15114 }
15115}
15116
15118 Function &F, const PreservedAnalyses &PA,
15119 FunctionAnalysisManager::Invalidator &Inv) {
15120 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
15121 // of its dependencies is invalidated.
15122 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
15123 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
15124 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
15125 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
15126 Inv.invalidate<LoopAnalysis>(F, PA);
15127}
15128
15129AnalysisKey ScalarEvolutionAnalysis::Key;
15130
15133 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
15134 auto &AC = AM.getResult<AssumptionAnalysis>(F);
15135 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
15136 auto &LI = AM.getResult<LoopAnalysis>(F);
15137 return ScalarEvolution(F, TLI, AC, DT, LI);
15138}
15139
15145
15148 // For compatibility with opt's -analyze feature under legacy pass manager
15149 // which was not ported to NPM. This keeps tests using
15150 // update_analyze_test_checks.py working.
15151 OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
15152 << F.getName() << "':\n";
15154 return PreservedAnalyses::all();
15155}
15156
15158 "Scalar Evolution Analysis", false, true)
15164 "Scalar Evolution Analysis", false, true)
15165
15166char ScalarEvolutionWrapperPass::ID = 0;
15167
15169
15171 SE.reset(new ScalarEvolution(
15173 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
15175 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
15176 return false;
15177}
15178
15180
15182 SE->print(OS);
15183}
15184
15186 if (!VerifySCEV)
15187 return;
15188
15189 SE->verify();
15190}
15191
15199
15201 const SCEV *RHS) {
15202 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
15203}
15204
15205const SCEVPredicate *
15207 const SCEV *LHS, const SCEV *RHS) {
15209 assert(LHS->getType() == RHS->getType() &&
15210 "Type mismatch between LHS and RHS");
15211 // Unique this node based on the arguments
15212 ID.AddInteger(SCEVPredicate::P_Compare);
15213 ID.AddInteger(Pred);
15214 ID.AddPointer(LHS);
15215 ID.AddPointer(RHS);
15217 if (const auto *S = UniquePreds.lookup(ID, Token))
15218 return S;
15219 SCEVComparePredicate *Eq = new (SCEVAllocator)
15220 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
15221 UniquePreds.insert(Eq, Token);
15222 return Eq;
15223}
15224
15226 const SCEVAddRecExpr *AR,
15229 // Unique this node based on the arguments
15231 ID.AddPointer(AR);
15232 ID.AddInteger(AddedFlags);
15234 if (const auto *S = UniquePreds.lookup(ID, Token))
15235 return S;
15236 auto *OF = new (SCEVAllocator)
15237 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
15238 UniquePreds.insert(OF, Token);
15239 return OF;
15240}
15241
15242namespace {
15243
15244class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
15245public:
15246
15247 /// Rewrites \p S in the context of a loop L and the SCEV predication
15248 /// infrastructure.
15249 ///
15250 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
15251 /// equivalences present in \p Pred.
15252 ///
15253 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
15254 /// \p NewPreds such that the result will be an AddRecExpr.
15255 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
15257 const SCEVPredicate *Pred) {
15258 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
15259 return Rewriter.visit(S);
15260 }
15261
15262 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
15263 if (Pred) {
15264 if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
15265 for (const auto *Pred : U->getPredicates())
15266 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
15267 if (IPred->getLHS() == Expr &&
15268 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15269 return IPred->getRHS();
15270 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
15271 if (IPred->getLHS() == Expr &&
15272 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15273 return IPred->getRHS();
15274 }
15275 }
15276 return convertToAddRecWithPreds(Expr);
15277 }
15278
15279 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
15280 const SCEV *Operand = visit(Expr->getOperand());
15281 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15282 if (AR && AR->getLoop() == L && AR->isAffine()) {
15283 // This couldn't be folded because the operand didn't have the nuw
15284 // flag. Add the nusw flag as an assumption that we could make.
15285 const SCEV *Step = AR->getStepRecurrence(SE);
15286 Type *Ty = Expr->getType();
15287 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
15288 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
15289 SE.getSignExtendExpr(Step, Ty), L,
15290 AR->getNoWrapFlags());
15291 }
15292 return SE.getZeroExtendExpr(Operand, Expr->getType());
15293 }
15294
15295 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
15296 const SCEV *Operand = visit(Expr->getOperand());
15297 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15298 if (AR && AR->getLoop() == L && AR->isAffine()) {
15299 // This couldn't be folded because the operand didn't have the nsw
15300 // flag. Add the nssw flag as an assumption that we could make.
15301 const SCEV *Step = AR->getStepRecurrence(SE);
15302 Type *Ty = Expr->getType();
15303 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
15304 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
15305 SE.getSignExtendExpr(Step, Ty), L,
15306 AR->getNoWrapFlags());
15307 }
15308 return SE.getSignExtendExpr(Operand, Expr->getType());
15309 }
15310
15311private:
15312 explicit SCEVPredicateRewriter(
15313 const Loop *L, ScalarEvolution &SE,
15314 SmallVectorImpl<const SCEVPredicate *> *NewPreds,
15315 const SCEVPredicate *Pred)
15316 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
15317
15318 bool addOverflowAssumption(const SCEVPredicate *P) {
15319 if (!NewPreds) {
15320 // Check if we've already made this assumption.
15321 return Pred && Pred->implies(P, SE);
15322 }
15323 NewPreds->push_back(P);
15324 return true;
15325 }
15326
15327 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
15329 auto *A = SE.getWrapPredicate(AR, AddedFlags);
15330 return addOverflowAssumption(A);
15331 }
15332
15333 // If \p Expr represents a PHINode, we try to see if it can be represented
15334 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
15335 // to add this predicate as a runtime overflow check, we return the AddRec.
15336 // If \p Expr does not meet these conditions (is not a PHI node, or we
15337 // couldn't create an AddRec for it, or couldn't add the predicate), we just
15338 // return \p Expr.
15339 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
15340 if (!isa<PHINode>(Expr->getValue()))
15341 return Expr;
15342 std::optional<
15343 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
15344 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
15345 if (!PredicatedRewrite)
15346 return Expr;
15347 for (const auto *P : PredicatedRewrite->second){
15348 // Wrap predicates from outer loops are not supported.
15349 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
15350 if (L != WP->getExpr()->getLoop())
15351 return Expr;
15352 }
15353 if (!addOverflowAssumption(P))
15354 return Expr;
15355 }
15356 return PredicatedRewrite->first;
15357 }
15358
15359 SmallVectorImpl<const SCEVPredicate *> *NewPreds;
15360 const SCEVPredicate *Pred;
15361 const Loop *L;
15362};
15363
15364} // end anonymous namespace
15365
15366const SCEV *
15368 const SCEVPredicate &Preds) {
15369 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
15370}
15371
15373 const SCEV *S, const Loop *L,
15376 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
15377 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
15378
15379 if (!AddRec)
15380 return nullptr;
15381
15382 // Check if any of the transformed predicates is known to be false. In that
15383 // case, it doesn't make sense to convert to a predicated AddRec, as the
15384 // versioned loop will never execute.
15385 for (const SCEVPredicate *Pred : TransformPreds) {
15386 auto *WrapPred = dyn_cast<SCEVWrapPredicate>(Pred);
15387 if (!WrapPred || WrapPred->getFlags() != SCEVWrapPredicate::IncrementNSSW)
15388 continue;
15389
15390 const SCEVAddRecExpr *AddRecToCheck = WrapPred->getExpr();
15391 const SCEV *ExitCount = getBackedgeTakenCount(AddRecToCheck->getLoop());
15392 if (isa<SCEVCouldNotCompute>(ExitCount))
15393 continue;
15394
15395 const SCEV *Step = AddRecToCheck->getStepRecurrence(*this);
15396 if (!Step->isOne())
15397 continue;
15398
15399 ExitCount = getTruncateOrSignExtend(ExitCount, Step->getType());
15400 const SCEV *Add = getAddExpr(AddRecToCheck->getStart(), ExitCount);
15401 if (isKnownPredicate(CmpInst::ICMP_SLT, Add, AddRecToCheck->getStart()))
15402 return nullptr;
15403 }
15404
15405 // Since the transformation was successful, we can now transfer the SCEV
15406 // predicates.
15407 Preds.append(TransformPreds.begin(), TransformPreds.end());
15408
15409 return AddRec;
15410}
15411
15412/// SCEV predicates
15416
15418 const ICmpInst::Predicate Pred,
15419 const SCEV *LHS, const SCEV *RHS)
15420 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
15421 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
15422 assert(LHS != RHS && "LHS and RHS are the same SCEV");
15423}
15424
15426 ScalarEvolution &SE) const {
15427 const auto *Op = dyn_cast<SCEVComparePredicate>(N);
15428
15429 if (!Op)
15430 return false;
15431
15432 if (Pred != ICmpInst::ICMP_EQ)
15433 return false;
15434
15435 return Op->LHS == LHS && Op->RHS == RHS;
15436}
15437
15438bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
15439
15441 if (Pred == ICmpInst::ICMP_EQ)
15442 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
15443 else
15444 OS.indent(Depth) << "Compare predicate: " << *LHS << " " << Pred << ") "
15445 << *RHS << "\n";
15446
15447}
15448
15450 const SCEVAddRecExpr *AR,
15451 IncrementWrapFlags Flags)
15452 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
15453
15454const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
15455
15457 ScalarEvolution &SE) const {
15458 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
15459 if (!Op || setFlags(Flags, Op->Flags) != Flags)
15460 return false;
15461
15462 if (Op->AR == AR)
15463 return true;
15464
15465 if (Flags != SCEVWrapPredicate::IncrementNSSW &&
15467 return false;
15468
15469 const SCEV *Start = AR->getStart();
15470 const SCEV *OpStart = Op->AR->getStart();
15471 if (Start->getType()->isPointerTy() != OpStart->getType()->isPointerTy())
15472 return false;
15473
15474 // Reject pointers to different address spaces.
15475 if (Start->getType()->isPointerTy() && Start->getType() != OpStart->getType())
15476 return false;
15477
15478 // NUSW/NSSW on a wider-type AddRec does not imply the same on a
15479 // narrower-type AddRec.
15480 if (SE.getTypeSizeInBits(AR->getType()) >
15481 SE.getTypeSizeInBits(Op->AR->getType()))
15482 return false;
15483
15484 const SCEV *Step = AR->getStepRecurrence(SE);
15485 const SCEV *OpStep = Op->AR->getStepRecurrence(SE);
15486 if (!SE.isKnownPositive(Step) || !SE.isKnownPositive(OpStep))
15487 return false;
15488
15489 // If both steps are positive, this implies N, if N's start and step are
15490 // ULE/SLE (for NSUW/NSSW) than this'.
15491 Type *WiderTy = SE.getWiderType(Step->getType(), OpStep->getType());
15492 Step = SE.getNoopOrZeroExtend(Step, WiderTy);
15493 OpStep = SE.getNoopOrZeroExtend(OpStep, WiderTy);
15494
15495 bool IsNUW = Flags == SCEVWrapPredicate::IncrementNUSW;
15496 OpStart = IsNUW ? SE.getNoopOrZeroExtend(OpStart, WiderTy)
15497 : SE.getNoopOrSignExtend(OpStart, WiderTy);
15498 Start = IsNUW ? SE.getNoopOrZeroExtend(Start, WiderTy)
15499 : SE.getNoopOrSignExtend(Start, WiderTy);
15501 return SE.isKnownPredicate(Pred, OpStep, Step) &&
15502 SE.isKnownPredicate(Pred, OpStart, Start);
15503}
15504
15506 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
15507 IncrementWrapFlags IFlags = Flags;
15508
15509 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
15510 IFlags = clearFlags(IFlags, IncrementNSSW);
15511
15512 return IFlags == IncrementAnyWrap;
15513}
15514
15515void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
15516 OS.indent(Depth) << *getExpr() << " Added Flags: ";
15518 OS << "<nusw>";
15520 OS << "<nssw>";
15521 OS << "\n";
15522}
15523
15524/// Union predicates don't get cached so create a dummy set ID for it.
15526 ScalarEvolution &SE)
15528 for (const auto *P : Preds)
15529 add(P, SE);
15530}
15531
15533 return all_of(Preds,
15534 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
15535}
15536
15538 ScalarEvolution &SE) const {
15539 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
15540 return all_of(Set->Preds, [this, &SE](const SCEVPredicate *I) {
15541 return this->implies(I, SE);
15542 });
15543
15544 if (any_of(Preds,
15545 [N, &SE](const SCEVPredicate *I) { return I->implies(N, SE); }))
15546 return true;
15547
15548 // A wrap predicate may be implied by a wrap predicate in Preds after applying
15549 // equal predicates.
15550 const auto *NWrap = dyn_cast<SCEVWrapPredicate>(N);
15551 if (!NWrap)
15552 return false;
15553 const Loop *L = NWrap->getExpr()->getLoop();
15554 return any_of(Preds, [&](const SCEVPredicate *I) {
15555 const auto *IWrap = dyn_cast<SCEVWrapPredicate>(I);
15556 if (!IWrap)
15557 return false;
15558 const auto *RewrittenAR = dyn_cast<SCEVAddRecExpr>(
15559 SE.rewriteUsingPredicate(IWrap->getExpr(), L, *this));
15560 return RewrittenAR &&
15561 SE.getWrapPredicate(RewrittenAR, IWrap->getFlags())->implies(N, SE);
15562 });
15563}
15564
15566 for (const auto *Pred : Preds)
15567 Pred->print(OS, Depth);
15568}
15569
15570void SCEVUnionPredicate::add(const SCEVPredicate *N, ScalarEvolution &SE) {
15571 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
15572 for (const auto *Pred : Set->Preds)
15573 add(Pred, SE);
15574 return;
15575 }
15576
15577 // Implication checks are quadratic in the number of predicates. Stop doing
15578 // them if there are many predicates, as they should be too expensive to use
15579 // anyway at that point.
15580 bool CheckImplies = Preds.size() < 16;
15581
15582 // Only add predicate if it is not already implied by this union predicate.
15583 if (CheckImplies && implies(N, SE))
15584 return;
15585
15586 // Build a new vector containing the current predicates, except the ones that
15587 // are implied by the new predicate N.
15589 for (auto *P : Preds) {
15590 if (CheckImplies && N->implies(P, SE))
15591 continue;
15592 PrunedPreds.push_back(P);
15593 }
15594 Preds = std::move(PrunedPreds);
15595 Preds.push_back(N);
15596}
15597
15599 Loop &L)
15600 : SE(SE), L(L) {
15602 Preds = std::make_unique<SCEVUnionPredicate>(Empty, SE);
15603}
15604
15606 for (const SCEV *Op : Ops)
15607 // We do not expect that forgetting cached data for SCEVConstants will ever
15608 // open any prospects for sharpening or introduce any correctness issues,
15609 // so we don't bother storing their dependencies.
15610 if (!isa<SCEVConstant>(Op))
15611 SCEVUsers[Op].insert(User);
15612}
15613
15615 const SCEV *Expr = SE.getSCEV(V);
15616 return getPredicatedSCEV(Expr);
15617}
15618
15620 RewriteEntry &Entry = RewriteMap[Expr];
15621
15622 // If we already have an entry and the version matches, return it.
15623 if (Entry.second && Generation == Entry.first)
15624 return Entry.second;
15625
15626 // We found an entry but it's stale. Rewrite the stale entry
15627 // according to the current predicate.
15628 if (Entry.second)
15629 Expr = Entry.second;
15630
15631 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
15632 Entry = {Generation, NewSCEV};
15633
15634 return NewSCEV;
15635}
15636
15638 if (!BackedgeCount) {
15640 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
15641 for (const auto *P : Preds)
15642 addPredicate(*P);
15643 }
15644 return BackedgeCount;
15645}
15646
15648 if (!SymbolicMaxBackedgeCount) {
15650 SymbolicMaxBackedgeCount =
15651 SE.getPredicatedSymbolicMaxBackedgeTakenCount(&L, Preds);
15652 for (const auto *P : Preds)
15653 addPredicate(*P);
15654 }
15655 return SymbolicMaxBackedgeCount;
15656}
15657
15659 if (!SmallConstantMaxTripCount) {
15661 SmallConstantMaxTripCount = SE.getSmallConstantMaxTripCount(&L, &Preds);
15662 for (const auto *P : Preds)
15663 addPredicate(*P);
15664 }
15665 return *SmallConstantMaxTripCount;
15666}
15667
15669 if (Preds->implies(&Pred, SE))
15670 return;
15671
15672 SmallVector<const SCEVPredicate *, 4> NewPreds(Preds->getPredicates());
15673 NewPreds.push_back(&Pred);
15674 Preds = std::make_unique<SCEVUnionPredicate>(NewPreds, SE);
15675 updateGeneration();
15676}
15677
15680 for (const SCEVPredicate *P : Preds)
15681 addPredicate(*P);
15682}
15683
15685 return *Preds;
15686}
15687
15688void PredicatedScalarEvolution::updateGeneration() {
15689 // If the generation number wrapped recompute everything.
15690 if (++Generation == 0) {
15691 for (auto &II : RewriteMap) {
15692 const SCEV *Rewritten = II.second.second;
15693 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
15694 }
15695 }
15696}
15697
15700 const SCEV *Expr = this->getSCEV(V);
15702 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
15703
15704 if (!New)
15705 return nullptr;
15706
15707 if (ExtraPreds) {
15708 ExtraPreds->append(NewPreds);
15709 return New;
15710 }
15711
15712 addPredicates(NewPreds);
15713
15714 RewriteMap[SE.getSCEV(V)] = {Generation, New};
15715 return New;
15716}
15717
15720 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
15721 Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates(),
15722 SE)),
15723 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {}
15724
15726 // For each block.
15727 for (auto *BB : L.getBlocks())
15728 for (auto &I : *BB) {
15729 if (!SE.isSCEVable(I.getType()))
15730 continue;
15731
15732 auto *Expr = SE.getSCEV(&I);
15733 auto II = RewriteMap.find(Expr);
15734
15735 if (II == RewriteMap.end())
15736 continue;
15737
15738 // Don't print things that are not interesting.
15739 if (II->second.second == Expr)
15740 continue;
15741
15742 OS.indent(Depth) << "[PSE]" << I << ":\n";
15743 OS.indent(Depth + 2) << *Expr << "\n";
15744 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
15745 }
15746}
15747
15750 BasicBlock *Header = L->getHeader();
15751 BasicBlock *Pred = L->getLoopPredecessor();
15752 LoopGuards Guards(SE);
15753 if (!Pred)
15754 return Guards;
15756 collectFromBlock(SE, Guards, Header, Pred, VisitedBlocks);
15757 return Guards;
15758}
15759
15760void ScalarEvolution::LoopGuards::collectFromPHI(
15764 unsigned Depth) {
15765 if (!SE.isSCEVable(Phi.getType()))
15766 return;
15767
15768 using MinMaxPattern = std::pair<const SCEVConstant *, SCEVTypes>;
15769 auto GetMinMaxConst = [&](unsigned IncomingIdx) -> MinMaxPattern {
15770 const BasicBlock *InBlock = Phi.getIncomingBlock(IncomingIdx);
15771 if (!VisitedBlocks.insert(InBlock).second)
15772 return {nullptr, scCouldNotCompute};
15773
15774 // Avoid analyzing unreachable blocks so that we don't get trapped
15775 // traversing cycles with ill-formed dominance or infinite cycles
15776 if (!SE.DT.isReachableFromEntry(InBlock))
15777 return {nullptr, scCouldNotCompute};
15778
15779 auto [G, Inserted] = IncomingGuards.try_emplace(InBlock, LoopGuards(SE));
15780 if (Inserted)
15781 collectFromBlock(SE, G->second, Phi.getParent(), InBlock, VisitedBlocks,
15782 Depth + 1);
15783 auto &RewriteMap = G->second.RewriteMap;
15784 if (RewriteMap.empty())
15785 return {nullptr, scCouldNotCompute};
15786 auto S = RewriteMap.find(SE.getSCEV(Phi.getIncomingValue(IncomingIdx)));
15787 if (S == RewriteMap.end())
15788 return {nullptr, scCouldNotCompute};
15789 auto *SM = dyn_cast_if_present<SCEVMinMaxExpr>(S->second);
15790 if (!SM)
15791 return {nullptr, scCouldNotCompute};
15792 if (const SCEVConstant *C0 = dyn_cast<SCEVConstant>(SM->getOperand(0)))
15793 return {C0, SM->getSCEVType()};
15794 return {nullptr, scCouldNotCompute};
15795 };
15796 auto MergeMinMaxConst = [](MinMaxPattern P1,
15797 MinMaxPattern P2) -> MinMaxPattern {
15798 auto [C1, T1] = P1;
15799 auto [C2, T2] = P2;
15800 if (!C1 || !C2 || T1 != T2)
15801 return {nullptr, scCouldNotCompute};
15802 switch (T1) {
15803 case scUMaxExpr:
15804 return {C1->getAPInt().ult(C2->getAPInt()) ? C1 : C2, T1};
15805 case scSMaxExpr:
15806 return {C1->getAPInt().slt(C2->getAPInt()) ? C1 : C2, T1};
15807 case scUMinExpr:
15808 return {C1->getAPInt().ugt(C2->getAPInt()) ? C1 : C2, T1};
15809 case scSMinExpr:
15810 return {C1->getAPInt().sgt(C2->getAPInt()) ? C1 : C2, T1};
15811 default:
15812 llvm_unreachable("Trying to merge non-MinMaxExpr SCEVs.");
15813 }
15814 };
15815 auto P = GetMinMaxConst(0);
15816 for (unsigned int In = 1; In < Phi.getNumIncomingValues(); In++) {
15817 if (!P.first)
15818 break;
15819 P = MergeMinMaxConst(P, GetMinMaxConst(In));
15820 }
15821 if (P.first) {
15822 const SCEV *LHS = SE.getSCEV(const_cast<PHINode *>(&Phi));
15823 SmallVector<SCEVUse, 2> Ops({P.first, LHS});
15824 const SCEV *RHS = SE.getMinMaxExpr(P.second, Ops);
15825 Guards.RewriteMap.insert({LHS, RHS});
15826 }
15827}
15828
15829// Return a new SCEV that modifies \p Expr to the closest number divides by
15830// \p Divisor and less or equal than Expr. For now, only handle constant
15831// Expr.
15833 const APInt &DivisorVal,
15834 ScalarEvolution &SE) {
15835 const APInt *ExprVal;
15836 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15837 DivisorVal.isNonPositive())
15838 return Expr;
15839 APInt Rem = ExprVal->urem(DivisorVal);
15840 // return the SCEV: Expr - Expr % Divisor
15841 return SE.getConstant(*ExprVal - Rem);
15842}
15843
15844// Return a new SCEV that modifies \p Expr to the closest number divides by
15845// \p Divisor and greater or equal than Expr. For now, only handle constant
15846// Expr.
15847static const SCEV *getNextSCEVDivisibleByDivisor(const SCEV *Expr,
15848 const APInt &DivisorVal,
15849 ScalarEvolution &SE) {
15850 const APInt *ExprVal;
15851 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15852 DivisorVal.isNonPositive())
15853 return Expr;
15854 APInt Rem = ExprVal->urem(DivisorVal);
15855 if (Rem.isZero())
15856 return Expr;
15857 // return the SCEV: Expr + Divisor - Expr % Divisor
15858 return SE.getConstant(*ExprVal + DivisorVal - Rem);
15859}
15860
15862 ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS,
15865 // If we have LHS == 0, check if LHS is computing a property of some unknown
15866 // SCEV %v which we can rewrite %v to express explicitly.
15868 return false;
15869 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
15870 // explicitly express that.
15871 const SCEVUnknown *URemLHS = nullptr;
15872 const SCEV *URemRHS = nullptr;
15873 if (!match(LHS, m_scev_URem(m_SCEVUnknown(URemLHS), m_SCEV(URemRHS), SE)))
15874 return false;
15875
15876 const SCEV *Multiple =
15877 SE.getMulExpr(SE.getUDivExpr(URemLHS, URemRHS), URemRHS);
15878 DivInfo[URemLHS] = Multiple;
15879 if (auto *C = dyn_cast<SCEVConstant>(URemRHS))
15880 Multiples[URemLHS] = C->getAPInt();
15881 return true;
15882}
15883
15884// Check if the condition is a divisibility guard (A % B == 0).
15885static bool isDivisibilityGuard(const SCEV *LHS, const SCEV *RHS,
15886 ScalarEvolution &SE) {
15887 const SCEV *X, *Y;
15888 return match(LHS, m_scev_URem(m_SCEV(X), m_SCEV(Y), SE)) && RHS->isZero();
15889}
15890
15891// Apply divisibility by \p Divisor on MinMaxExpr with constant values,
15892// recursively. This is done by aligning up/down the constant value to the
15893// Divisor.
15894static const SCEV *applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr,
15895 APInt Divisor,
15896 ScalarEvolution &SE) {
15897 // Return true if \p Expr is a MinMax SCEV expression with a non-negative
15898 // constant operand. If so, return in \p SCTy the SCEV type and in \p RHS
15899 // the non-constant operand and in \p LHS the constant operand.
15900 auto IsMinMaxSCEVWithNonNegativeConstant =
15901 [&](const SCEV *Expr, SCEVTypes &SCTy, const SCEV *&LHS,
15902 const SCEV *&RHS) {
15903 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr)) {
15904 if (MinMax->getNumOperands() != 2)
15905 return false;
15906 if (auto *C = dyn_cast<SCEVConstant>(MinMax->getOperand(0))) {
15907 if (C->getAPInt().isNegative())
15908 return false;
15909 SCTy = MinMax->getSCEVType();
15910 LHS = MinMax->getOperand(0);
15911 RHS = MinMax->getOperand(1);
15912 return true;
15913 }
15914 }
15915 return false;
15916 };
15917
15918 const SCEV *MinMaxLHS = nullptr, *MinMaxRHS = nullptr;
15919 SCEVTypes SCTy;
15920 if (!IsMinMaxSCEVWithNonNegativeConstant(MinMaxExpr, SCTy, MinMaxLHS,
15921 MinMaxRHS))
15922 return MinMaxExpr;
15923 auto IsMin = isa<SCEVSMinExpr>(MinMaxExpr) || isa<SCEVUMinExpr>(MinMaxExpr);
15924 assert(SE.isKnownNonNegative(MinMaxLHS) && "Expected non-negative operand!");
15925 auto *DivisibleExpr =
15926 IsMin ? getPreviousSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE)
15927 : getNextSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE);
15929 applyDivisibilityOnMinMaxExpr(MinMaxRHS, Divisor, SE), DivisibleExpr};
15930 return SE.getMinMaxExpr(SCTy, Ops);
15931}
15932
15933void ScalarEvolution::LoopGuards::collectFromBlock(
15934 ScalarEvolution &SE, ScalarEvolution::LoopGuards &Guards,
15935 const BasicBlock *Block, const BasicBlock *Pred,
15936 SmallPtrSetImpl<const BasicBlock *> &VisitedBlocks, unsigned Depth) {
15937
15939
15940 SmallVector<SCEVUse> ExprsToRewrite;
15941 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
15942 const SCEV *RHS,
15943 DenseMap<const SCEV *, const SCEV *> &RewriteMap,
15944 const LoopGuards &DivGuards) {
15945 // WARNING: It is generally unsound to apply any wrap flags to the proposed
15946 // replacement SCEV which isn't directly implied by the structure of that
15947 // SCEV. In particular, using contextual facts to imply flags is *NOT*
15948 // legal. See the scoping rules for flags in the header to understand why.
15949
15950 // Puts rewrite rule \p From -> \p To into the rewrite map. Also if \p From
15951 // and \p FromRewritten are the same (i.e. there has been no rewrite
15952 // registered for \p From), then puts this value in the list of rewritten
15953 // expressions.
15954 auto AddRewrite = [&](const SCEV *From, const SCEV *FromRewritten,
15955 const SCEV *To) {
15956 if (From == FromRewritten)
15957 ExprsToRewrite.push_back(From);
15958 RewriteMap[From] = To;
15959 };
15960
15961 // Checks whether \p S has already been rewritten. In that case returns the
15962 // existing rewrite because we want to chain further rewrites onto the
15963 // already rewritten value. Otherwise returns \p S.
15964 auto GetMaybeRewritten = [&](const SCEV *S) {
15965 return RewriteMap.lookup_or(S, S);
15966 };
15967
15968 // Check for a condition of the form (-C1 + X < C2). InstCombine will
15969 // create this form when combining two checks of the form (X u< C2 + C1) and
15970 // (X >=u C1).
15971 auto MatchRangeCheckIdiom = [&](ICmpInst::Predicate Pred,
15972 const SCEV *MatchLHS,
15973 const SCEV *MatchRHS) {
15974 const SCEVConstant *C1;
15975 const SCEVUnknown *LHSUnknown;
15976 auto *C2 = dyn_cast<SCEVConstant>(MatchRHS);
15977 if (!match(MatchLHS,
15978 m_scev_Add(m_SCEVConstant(C1), m_SCEVUnknown(LHSUnknown))) ||
15979 !C2)
15980 return false;
15981
15982 auto ExactRegion =
15983 ConstantRange::makeExactICmpRegion(Pred, C2->getAPInt())
15984 .sub(C1->getAPInt());
15985
15986 // Tighten the raw range with what we already know about LHSUnknown
15987 // from prior guards recorded in RewriteMap, or from SCEV's own range
15988 // analysis.
15989 const SCEV *RewrittenLHS = GetMaybeRewritten(LHSUnknown);
15990 ExactRegion = ExactRegion.intersectWith(SE.getUnsignedRange(RewrittenLHS),
15992
15993 // Bail if the guard is inconsistent with prior facts, or if the range
15994 // is still not a monotonic non-wrapping interval after tightening.
15995 if (ExactRegion.isEmptySet() || ExactRegion.isWrappedSet() ||
15996 ExactRegion.isFullSet())
15997 return false;
15998
15999 const SCEV *RegionMin = SE.getConstant(ExactRegion.getUnsignedMin());
16000 const SCEV *RegionMax = SE.getConstant(ExactRegion.getUnsignedMax());
16001 const SCEV *ClampedLHS =
16002 SE.getUMaxExpr(RegionMin, SE.getUMinExpr(RewrittenLHS, RegionMax));
16003 AddRewrite(LHSUnknown, RewrittenLHS, ClampedLHS);
16004 return true;
16005 };
16006 if (MatchRangeCheckIdiom(Predicate, LHS, RHS))
16007 return;
16008
16009 // Do not apply information for constants or if RHS contains an AddRec.
16011 return;
16012
16013 // If RHS is SCEVUnknown, make sure the information is applied to it.
16015 std::swap(LHS, RHS);
16017 }
16018
16019 const SCEV *RewrittenLHS = GetMaybeRewritten(LHS);
16020 // Apply divisibility information when computing the constant multiple.
16021 const APInt &DividesBy =
16022 SE.getConstantMultiple(DivGuards.rewrite(RewrittenLHS));
16023
16024 // Collect rewrites for LHS and its transitive operands based on the
16025 // condition.
16026 // For min/max expressions, also apply the guard to its operands:
16027 // 'min(a, b) >= c' -> '(a >= c) and (b >= c)',
16028 // 'min(a, b) > c' -> '(a > c) and (b > c)',
16029 // 'max(a, b) <= c' -> '(a <= c) and (b <= c)',
16030 // 'max(a, b) < c' -> '(a < c) and (b < c)'.
16031
16032 // We cannot express strict predicates in SCEV, so instead we replace them
16033 // with non-strict ones against plus or minus one of RHS depending on the
16034 // predicate.
16035 const SCEV *One = SE.getOne(RHS->getType());
16036 switch (Predicate) {
16037 case CmpInst::ICMP_ULT:
16038 if (RHS->getType()->isPointerTy())
16039 return;
16040 RHS = SE.getUMaxExpr(RHS, One);
16041 [[fallthrough]];
16042 case CmpInst::ICMP_SLT: {
16043 RHS = SE.getMinusSCEV(RHS, One);
16044 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16045 break;
16046 }
16047 case CmpInst::ICMP_UGT:
16048 case CmpInst::ICMP_SGT:
16049 RHS = SE.getAddExpr(RHS, One);
16050 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16051 break;
16052 case CmpInst::ICMP_ULE:
16053 case CmpInst::ICMP_SLE:
16054 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16055 break;
16056 case CmpInst::ICMP_UGE:
16057 case CmpInst::ICMP_SGE:
16058 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16059 break;
16060 default:
16061 break;
16062 }
16063
16064 SmallVector<SCEVUse, 16> Worklist(1, LHS);
16065 SmallPtrSet<const SCEV *, 16> Visited;
16066
16067 auto EnqueueOperands = [&Worklist](const SCEVNAryExpr *S) {
16068 append_range(Worklist, S->operands());
16069 };
16070
16071 while (!Worklist.empty()) {
16072 const SCEV *From = Worklist.pop_back_val();
16073 if (isa<SCEVConstant>(From))
16074 continue;
16075 if (!Visited.insert(From).second)
16076 continue;
16077 const SCEV *FromRewritten = GetMaybeRewritten(From);
16078 const SCEV *To = nullptr;
16079
16080 switch (Predicate) {
16081 case CmpInst::ICMP_ULT:
16082 case CmpInst::ICMP_ULE:
16083 To = SE.getUMinExpr(FromRewritten, RHS);
16084 if (auto *UMax = dyn_cast<SCEVUMaxExpr>(FromRewritten))
16085 EnqueueOperands(UMax);
16086 break;
16087 case CmpInst::ICMP_SLT:
16088 case CmpInst::ICMP_SLE:
16089 To = SE.getSMinExpr(FromRewritten, RHS);
16090 if (auto *SMax = dyn_cast<SCEVSMaxExpr>(FromRewritten))
16091 EnqueueOperands(SMax);
16092 break;
16093 case CmpInst::ICMP_UGT:
16094 case CmpInst::ICMP_UGE:
16095 To = SE.getUMaxExpr(FromRewritten, RHS);
16096 if (auto *UMin = dyn_cast<SCEVUMinExpr>(FromRewritten))
16097 EnqueueOperands(UMin);
16098 break;
16099 case CmpInst::ICMP_SGT:
16100 case CmpInst::ICMP_SGE:
16101 To = SE.getSMaxExpr(FromRewritten, RHS);
16102 if (auto *SMin = dyn_cast<SCEVSMinExpr>(FromRewritten))
16103 EnqueueOperands(SMin);
16104 break;
16105 case CmpInst::ICMP_EQ:
16107 To = RHS;
16108 break;
16109 case CmpInst::ICMP_NE:
16110 if (match(RHS, m_scev_Zero())) {
16111 const SCEV *OneAlignedUp =
16112 getNextSCEVDivisibleByDivisor(One, DividesBy, SE);
16113 To = SE.getUMaxExpr(FromRewritten, OneAlignedUp);
16114 } else {
16115 // LHS != RHS can be rewritten as (LHS - RHS) = UMax(1, LHS - RHS),
16116 // but creating the subtraction eagerly is expensive. Track the
16117 // inequalities in a separate map, and materialize the rewrite lazily
16118 // when encountering a suitable subtraction while re-writing.
16119 if (LHS->getType()->isPointerTy()) {
16120 LHS = SE.getPtrToAddrExpr(LHS);
16121 RHS = SE.getPtrToAddrExpr(RHS);
16123 break;
16124 }
16125 const SCEVConstant *C;
16126 const SCEV *A, *B;
16129 RHS = A;
16130 LHS = B;
16131 }
16132 if (LHS > RHS)
16133 std::swap(LHS, RHS);
16134 Guards.NotEqual.insert({LHS, RHS});
16135 continue;
16136 }
16137 break;
16138 default:
16139 break;
16140 }
16141
16142 if (To)
16143 AddRewrite(From, FromRewritten, To);
16144 }
16145 };
16146
16148 // First, collect information from assumptions dominating the loop.
16149 for (auto &AssumeVH : SE.AC.assumptions()) {
16150 if (!AssumeVH)
16151 continue;
16152 auto *AssumeI = cast<CallInst>(AssumeVH);
16153 if (!SE.DT.dominates(AssumeI, Block))
16154 continue;
16155 Terms.emplace_back(AssumeI->getOperand(0), true);
16156 }
16157
16158 // Second, collect information from llvm.experimental.guards dominating the loop.
16159 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
16160 SE.F.getParent(), Intrinsic::experimental_guard);
16161 if (GuardDecl)
16162 for (const auto *GU : GuardDecl->users())
16163 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
16164 if (Guard->getFunction() == Block->getParent() &&
16165 SE.DT.dominates(Guard, Block))
16166 Terms.emplace_back(Guard->getArgOperand(0), true);
16167
16168 // Third, collect conditions from dominating branches. Starting at the loop
16169 // predecessor, climb up the predecessor chain, as long as there are
16170 // predecessors that can be found that have unique successors leading to the
16171 // original header.
16172 // TODO: share this logic with isLoopEntryGuardedByCond.
16173 unsigned NumCollectedConditions = 0;
16175 std::pair<const BasicBlock *, const BasicBlock *> Pair(Pred, Block);
16176 for (; Pair.first;
16177 Pair = SE.getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
16178 VisitedBlocks.insert(Pair.second);
16179 const CondBrInst *LoopEntryPredicate =
16180 dyn_cast<CondBrInst>(Pair.first->getTerminator());
16181 if (!LoopEntryPredicate)
16182 continue;
16183
16184 Terms.emplace_back(LoopEntryPredicate->getCondition(),
16185 LoopEntryPredicate->getSuccessor(0) == Pair.second);
16186 NumCollectedConditions++;
16187
16188 // If we are recursively collecting guards stop after 2
16189 // conditions to limit compile-time impact for now.
16190 if (Depth > 0 && NumCollectedConditions == 2)
16191 break;
16192 }
16193 // Finally, if we stopped climbing the predecessor chain because
16194 // there wasn't a unique one to continue, try to collect conditions
16195 // for PHINodes by recursively following all of their incoming
16196 // blocks and try to merge the found conditions to build a new one
16197 // for the Phi.
16198 if (Pair.second->hasNPredecessorsOrMore(2) &&
16200 SmallDenseMap<const BasicBlock *, LoopGuards> IncomingGuards;
16201 for (auto &Phi : Pair.second->phis())
16202 collectFromPHI(SE, Guards, Phi, VisitedBlocks, IncomingGuards, Depth);
16203 }
16204
16205 // Now apply the information from the collected conditions to
16206 // Guards.RewriteMap. Conditions are processed in reverse order, so the
16207 // earliest conditions is processed first, except guards with divisibility
16208 // information, which are moved to the back. This ensures the SCEVs with the
16209 // shortest dependency chains are constructed first.
16211 GuardsToProcess;
16212 for (auto [Term, EnterIfTrue] : reverse(Terms)) {
16213 SmallVector<Value *, 8> Worklist;
16214 SmallPtrSet<Value *, 8> Visited;
16215 Worklist.push_back(Term);
16216 while (!Worklist.empty()) {
16217 Value *Cond = Worklist.pop_back_val();
16218 if (!Visited.insert(Cond).second)
16219 continue;
16220
16221 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
16222 auto Predicate =
16223 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
16224 const auto *LHS = SE.getSCEV(Cmp->getOperand(0));
16225 const auto *RHS = SE.getSCEV(Cmp->getOperand(1));
16226 // If LHS is a constant, apply information to the other expression.
16227 // TODO: If LHS is not a constant, check if using CompareSCEVComplexity
16228 // can improve results.
16229 if (isa<SCEVConstant>(LHS)) {
16230 std::swap(LHS, RHS);
16232 }
16233 GuardsToProcess.emplace_back(Predicate, LHS, RHS);
16234 continue;
16235 }
16236
16237 Value *L, *R;
16238 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
16239 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
16240 Worklist.push_back(L);
16241 Worklist.push_back(R);
16242 }
16243 }
16244 }
16245
16246 // Process divisibility guards in reverse order to populate DivGuards early.
16247 DenseMap<const SCEV *, APInt> Multiples;
16248 LoopGuards DivGuards(SE);
16249 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess) {
16250 if (!isDivisibilityGuard(LHS, RHS, SE))
16251 continue;
16252 collectDivisibilityInformation(Predicate, LHS, RHS, DivGuards.RewriteMap,
16253 Multiples, SE);
16254 }
16255
16256 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess)
16257 CollectCondition(Predicate, LHS, RHS, Guards.RewriteMap, DivGuards);
16258
16259 // Apply divisibility information last. This ensures it is applied to the
16260 // outermost expression after other rewrites for the given value.
16261 for (const auto &[K, Divisor] : Multiples) {
16262 const SCEV *DivisorSCEV = SE.getConstant(Divisor);
16263 Guards.RewriteMap[K] =
16265 Guards.rewrite(K), Divisor, SE),
16266 DivisorSCEV),
16267 DivisorSCEV);
16268 ExprsToRewrite.push_back(K);
16269 }
16270
16271 // Let the rewriter preserve NUW/NSW flags if the unsigned/signed ranges of
16272 // the replacement expressions are contained in the ranges of the replaced
16273 // expressions.
16274 Guards.PreserveNUW = true;
16275 Guards.PreserveNSW = true;
16276 for (const SCEV *Expr : ExprsToRewrite) {
16277 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16278 Guards.PreserveNUW &=
16279 SE.getUnsignedRange(Expr).contains(SE.getUnsignedRange(RewriteTo));
16280 Guards.PreserveNSW &=
16281 SE.getSignedRange(Expr).contains(SE.getSignedRange(RewriteTo));
16282 }
16283
16284 // Now that all rewrite information is collect, rewrite the collected
16285 // expressions with the information in the map. This applies information to
16286 // sub-expressions.
16287 if (ExprsToRewrite.size() > 1) {
16288 for (const SCEV *Expr : ExprsToRewrite) {
16289 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16290 Guards.RewriteMap.erase(Expr);
16291 Guards.RewriteMap.insert({Expr, Guards.rewrite(RewriteTo)});
16292 }
16293 }
16294}
16295
16297 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
16298 /// in the map. It skips AddRecExpr because we cannot guarantee that the
16299 /// replacement is loop invariant in the loop of the AddRec.
16300 class SCEVLoopGuardRewriter
16301 : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
16304
16306
16307 public:
16308 SCEVLoopGuardRewriter(ScalarEvolution &SE,
16309 const ScalarEvolution::LoopGuards &Guards)
16310 : SCEVRewriteVisitor(SE), Map(Guards.RewriteMap),
16311 NotEqual(Guards.NotEqual) {
16312 if (Guards.PreserveNUW)
16313 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNUW);
16314 if (Guards.PreserveNSW)
16315 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNSW);
16316 }
16317
16318 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
16319
16320 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
16321 return Map.lookup_or(Expr, Expr);
16322 }
16323
16324 const SCEV *visitPtrToAddrExpr(const SCEVPtrToAddrExpr *Expr) {
16325 if (const SCEV *S = Map.lookup(Expr))
16326 return S;
16328 Expr);
16329 }
16330
16331 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
16332 if (const SCEV *S = Map.lookup(Expr))
16333 return S;
16334
16335 // If we didn't find the extact ZExt expr in the map, check if there's
16336 // an entry for a smaller ZExt we can use instead.
16337 Type *Ty = Expr->getType();
16338 const SCEV *Op = Expr->getOperand(0);
16339 unsigned Bitwidth = Ty->getScalarSizeInBits() / 2;
16340 while (Bitwidth % 8 == 0 && Bitwidth >= 8 &&
16341 Bitwidth > Op->getType()->getScalarSizeInBits()) {
16342 Type *NarrowTy = IntegerType::get(SE.getContext(), Bitwidth);
16343 auto *NarrowExt = SE.getZeroExtendExpr(Op, NarrowTy);
16344 if (const SCEV *S = Map.lookup(NarrowExt))
16345 return SE.getZeroExtendExpr(S, Ty);
16346 Bitwidth = Bitwidth / 2;
16347 }
16348
16350 Expr);
16351 }
16352
16353 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
16354 if (const SCEV *S = Map.lookup(Expr))
16355 return S;
16357 Expr);
16358 }
16359
16360 const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
16361 if (const SCEV *S = Map.lookup(Expr))
16362 return S;
16364 }
16365
16366 const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
16367 if (const SCEV *S = Map.lookup(Expr))
16368 return S;
16370 }
16371
16372 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
16373 if (const SCEV *S = Map.lookup(Expr))
16374 return S;
16375
16376 // Helper to check if S is a subtraction (A - B) where A != B, and if so,
16377 // return UMax(S, 1).
16378 auto RewriteSubtraction = [&](const SCEV *S) -> const SCEV * {
16379 SCEVUse LHS, RHS;
16380 if (MatchBinarySub(S, LHS, RHS)) {
16381 if (LHS > RHS)
16382 std::swap(LHS, RHS);
16383 if (NotEqual.contains({LHS, RHS})) {
16384 const SCEV *OneAlignedUp = getNextSCEVDivisibleByDivisor(
16385 SE.getOne(S->getType()), SE.getConstantMultiple(S), SE);
16386 return SE.getUMaxExpr(OneAlignedUp, S);
16387 }
16388 }
16389 return nullptr;
16390 };
16391
16392 // Check if Expr itself is a subtraction pattern with guard info.
16393 if (const SCEV *Rewritten = RewriteSubtraction(Expr))
16394 return Rewritten;
16395
16396 // Trip count expressions sometimes consist of adding 3 operands, i.e.
16397 // (Const + A + B). There may be guard info for A + B, and if so, apply
16398 // it.
16399 // TODO: Could more generally apply guards to Add sub-expressions.
16400 if (isa<SCEVConstant>(Expr->getOperand(0))) {
16401 if (Expr->getNumOperands() == 3) {
16402 const SCEV *Add =
16403 SE.getAddExpr(Expr->getOperand(1), Expr->getOperand(2));
16404 if (const SCEV *Rewritten = RewriteSubtraction(Add))
16405 return SE.getAddExpr(
16406 Expr->getOperand(0), Rewritten,
16407 ScalarEvolution::maskFlags(Expr->getNoWrapFlags(), FlagMask));
16408 if (const SCEV *S = Map.lookup(Add))
16409 return SE.getAddExpr(Expr->getOperand(0), S);
16410 }
16411
16412 // For expressions of the form (Const + A), check if we have guard info
16413 // for (Const + 1 + A), and rewrite to ((Const + 1 + A) - 1). This makes
16414 // sure we don't lose information when rewriting expressions based on
16415 // back-edge taken counts in some cases.
16416 if (Expr->getNumOperands() == 2) {
16417 const SCEV *S = nullptr;
16418 // Handle (-1 + 1 + A) without constructing SCEVs.
16419 if (match(Expr->getOperand(0), m_scev_AllOnes())) {
16420 S = Map.lookup(Expr->getOperand(1));
16421 } else {
16422 const SCEV *NewC =
16423 SE.getAddExpr(Expr->getOperand(0), SE.getOne(Expr->getType()));
16424 S = Map.lookup(SE.getAddExpr(NewC, Expr->getOperand(1)));
16425 }
16426 if (S)
16427 return SE.getAddExpr(S, SE.getMinusOne(Expr->getType()));
16428 }
16429 }
16431 bool Changed = false;
16432 for (SCEVUse Op : Expr->operands()) {
16433 Operands.push_back(
16435 Changed |= Op != Operands.back();
16436 }
16437 // We are only replacing operands with equivalent values, so transfer the
16438 // flags from the original expression.
16439 return !Changed ? Expr
16440 : SE.getAddExpr(Operands,
16442 Expr->getNoWrapFlags(), FlagMask));
16443 }
16444
16445 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
16447 bool Changed = false;
16448 for (SCEVUse Op : Expr->operands()) {
16449 Operands.push_back(
16451 Changed |= Op != Operands.back();
16452 }
16453 // We are only replacing operands with equivalent values, so transfer the
16454 // flags from the original expression.
16455 return !Changed ? Expr
16456 : SE.getMulExpr(Operands,
16458 Expr->getNoWrapFlags(), FlagMask));
16459 }
16460 };
16461
16462 if (RewriteMap.empty() && NotEqual.empty())
16463 return Expr;
16464
16465 SCEVLoopGuardRewriter Rewriter(SE, *this);
16466 return Rewriter.visit(Expr);
16467}
16468
16469const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
16470 return applyLoopGuards(Expr, LoopGuards::collect(L, *this));
16471}
16472
16474 const LoopGuards &Guards) {
16475 return Guards.rewrite(Expr);
16476}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
constexpr LLT S1
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
@ PostInc
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:678
This file contains the declarations for the subclasses of Constant, which represent the different fla...
SmallPtrSet< const BasicBlock *, 8 > VisitedBlocks
This file defines the DenseMap class.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
static bool isSigned(unsigned Opcode)
This file defines a hash set that can be used to remove duplication of nodes in a graph.
#define op(i)
Hexagon Common GEP
Value * getPointer(Value *Ptr)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This defines the Use class.
iv Induction Variable Users
Definition IVUsers.cpp:48
static bool hasNoUnsignedWrap(BinaryOperator &I)
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:540
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define T
#define T1
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
ppc ctr loops verify
PowerPC Reduce CR logical Operation
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
R600 Clause Merge
const SmallVectorImpl< MachineOperand > & Cond
static DominatorTree getDomTree(Function &F)
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
SI Fold Operands
SI optimize exec mask operations pre RA
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
This file contains some templates that are useful if you are working with the STL at all.
This file provides utility classes that use RAII to save and restore values.
bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind, SCEVTypes RootKind)
static cl::opt< unsigned > MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, cl::desc("Max coefficients in AddRec during evolving"), cl::init(8))
static cl::opt< unsigned > RangeIterThreshold("scev-range-iter-threshold", cl::Hidden, cl::desc("Threshold for switching to iteratively computing SCEV ranges"), cl::init(32))
static const Loop * isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI)
static unsigned getConstantTripCount(const SCEVConstant *ExitCount)
static int CompareValueComplexity(const LoopInfo *const LI, Value *LV, Value *RV, unsigned Depth)
Compare the two values LV and RV in terms of their "complexity" where "complexity" is a partial (and ...
static const SCEV * getNextSCEVDivisibleByDivisor(const SCEV *Expr, const APInt &DivisorVal, ScalarEvolution &SE)
static void PushLoopPHIs(const Loop *L, SmallVectorImpl< Instruction * > &Worklist, SmallPtrSetImpl< Instruction * > &Visited)
Push PHI nodes in the header of the given loop onto the given Worklist.
static void insertFoldCacheEntry(const ScalarEvolution::FoldID &ID, const SCEV *S, DenseMap< ScalarEvolution::FoldID, const SCEV * > &FoldCache, DenseMap< const SCEV *, SmallVector< ScalarEvolution::FoldID, 2 > > &FoldCacheUser)
static cl::opt< bool > ClassifyExpressions("scalar-evolution-classify-expressions", cl::Hidden, cl::init(true), cl::desc("When printing analysis, include information on every instruction"))
static bool hasHugeExpression(ArrayRef< SCEVUse > Ops)
Returns true if Ops contains a huge SCEV (the subtree of S contains at least HugeExprThreshold nodes)...
static cl::opt< unsigned > AddOpsInlineThreshold("scev-addops-inline-threshold", cl::Hidden, cl::desc("Threshold for inlining addition operands into a SCEV"), cl::init(500))
static cl::opt< unsigned > MaxLoopGuardCollectionDepth("scalar-evolution-max-loop-guard-collection-depth", cl::Hidden, cl::desc("Maximum depth for recursive loop guard collection"), cl::init(1))
static SCEV::NoWrapFlags getNoWrapFlagsForGEP(GEPOperator *GEP, const SCEV *Accum, ScalarEvolution &SE)
static cl::opt< bool > VerifyIR("scev-verify-ir", cl::Hidden, cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), cl::init(false))
static bool RangeRefPHIAllowedOperands(DominatorTree &DT, PHINode *PHI)
static bool IsKnownPredicateViaAddRecMonotonicity(ScalarEvolution &SE, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Is LHS Pred RHS true because one of them is an AddRec that is known not to go below its own start val...
static std::optional< APInt > MinOptional(std::optional< APInt > X, std::optional< APInt > Y)
Helper function to compare optional APInts: (a) if X and Y both exist, return min(X,...
static PHINode * getConstantEvolvingPHI(Value *V, const Loop *L, const TargetLibraryInfo *TLI)
getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node in the loop that V is deri...
static bool canConstantFold(const Instruction *I, const TargetLibraryInfo *TLI)
Return true if we can constant fold an instruction of the specified type, assuming that all operands ...
static cl::opt< unsigned > MulOpsInlineThreshold("scev-mulops-inline-threshold", cl::Hidden, cl::desc("Threshold for inlining multiplication operands into a SCEV"), cl::init(32))
static BinaryOperator * getCommonInstForPHI(PHINode *PN)
static PHINode * getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, DenseMap< Instruction *, PHINode * > &PHIMap, const TargetLibraryInfo *TLI, unsigned Depth)
getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by recursing through each instructi...
static bool isDivisibilityGuard(const SCEV *LHS, const SCEV *RHS, ScalarEvolution &SE)
static std::optional< const SCEV * > createNodeForSelectViaUMinSeq(ScalarEvolution *SE, const SCEV *CondExpr, const SCEV *TrueExpr, const SCEV *FalseExpr)
static Constant * BuildConstantFromSCEV(const SCEV *V)
This builds up a Constant using the ConstantExpr interface.
static ConstantInt * EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, ScalarEvolution &SE)
static const SCEV * BinomialCoefficient(const SCEV *It, unsigned K, ScalarEvolution &SE, Type *ResultTy)
Compute BC(It, K). The result has width W. Assume, K > 0.
static cl::opt< unsigned > MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), cl::init(8))
static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, const SCEV *Candidate)
Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
static const SCEV * SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, SmallVectorImpl< const SCEVPredicate * > *Predicates, ScalarEvolution &SE, const Loop *L)
Finds the minimum unsigned root of the following equation:
static cl::opt< unsigned > MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, cl::desc("Maximum number of iterations SCEV will " "symbolically execute a constant " "derived loop"), cl::init(100))
static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow)
static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV *S)
When printing a top-level SCEV for trip counts, it's helpful to include a type for constants which ar...
static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, const Loop *L)
static SCEV::NoWrapFlags StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, ArrayRef< SCEVUse > Ops, SCEV::NoWrapFlags Flags)
static bool containsConstantInAddMulChain(const SCEV *StartExpr)
Determine if any of the operands in this SCEV are a constant or if any of the add or multiply express...
static const SCEV * getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, ScalarEvolution *SE, unsigned Depth)
static bool CollectAddOperandsWithScales(SmallDenseMap< SCEVUse, APInt, 16 > &M, SmallVectorImpl< SCEVUse > &NewOps, APInt &AccumulatedConstant, ArrayRef< SCEVUse > Ops, const APInt &Scale, ScalarEvolution &SE)
Process the given Ops list, which is a list of operands to be added under the given scale,...
static const SCEV * constantFoldAndGroupOps(ScalarEvolution &SE, LoopInfo &LI, DominatorTree &DT, SmallVectorImpl< SCEVUse > &Ops, FoldT Fold, IsIdentityT IsIdentity, IsAbsorberT IsAbsorber)
Performs a number of common optimizations on the passed Ops.
static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
static const SCEV * getPreStartForExtend(const SCEVAddRecExpr *AR, ScalarEvolution *SE, unsigned Depth)
static void GroupByComplexity(SmallVectorImpl< SCEVUse > &Ops, LoopInfo *LI, DominatorTree &DT)
Given a list of SCEV objects, order them by their complexity, and group objects of the same complexit...
static bool collectDivisibilityInformation(ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS, DenseMap< const SCEV *, const SCEV * > &DivInfo, DenseMap< const SCEV *, APInt > &Multiples, ScalarEvolution &SE)
static cl::opt< unsigned > MaxSCEVOperationsImplicationDepth("scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, cl::desc("Maximum depth of recursive SCEV operations implication analysis"), cl::init(2))
static void PushDefUseChildren(Instruction *I, SmallVectorImpl< Instruction * > &Worklist, SmallPtrSetImpl< Instruction * > &Visited)
Push users of the given Instruction onto the given Worklist.
static std::optional< APInt > SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, const ConstantRange &Range, ScalarEvolution &SE)
Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n iterations.
static cl::opt< bool > UseContextForNoWrapFlagInference("scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden, cl::desc("Infer nuw/nsw flags using context where suitable"), cl::init(true))
static cl::opt< bool > EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden, cl::desc("Handle <= and >= in finite loops"), cl::init(true))
static bool getOperandsForSelectLikePHI(DominatorTree &DT, PHINode *PN, Value *&Cond, Value *&LHS, Value *&RHS)
static std::optional< std::tuple< APInt, APInt, APInt, APInt, unsigned > > GetQuadraticEquation(const SCEVAddRecExpr *AddRec)
For a given quadratic addrec, generate coefficients of the corresponding quadratic equation,...
static bool isKnownPredicateExtendIdiom(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
static std::optional< BinaryOp > MatchBinaryOp(Value *V, const DataLayout &DL, AssumptionCache &AC, const DominatorTree &DT, const Instruction *CxtI)
Try to map V into a BinaryOp, and return std::nullopt on failure.
static std::optional< APInt > SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE)
Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n iterations.
static std::optional< APInt > TruncIfPossible(std::optional< APInt > X, unsigned BitWidth)
Helper function to truncate an optional APInt to a given BitWidth.
static cl::opt< unsigned > MaxSCEVCompareDepth("scalar-evolution-max-scev-compare-depth", cl::Hidden, cl::desc("Maximum depth of recursive SCEV complexity comparisons"), cl::init(32))
static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, const SCEVConstant *ConstantTerm, const SCEVAddExpr *WholeAddExpr)
static cl::opt< unsigned > MaxConstantEvolvingDepth("scalar-evolution-max-constant-evolving-depth", cl::Hidden, cl::desc("Maximum depth of recursive constant evolving"), cl::init(32))
static bool canConstantEvolve(Instruction *I, const Loop *L, const TargetLibraryInfo *TLI)
Determine whether this instruction can constant evolve within this loop assuming its operands can all...
static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS)
static std::optional< ConstantRange > GetRangeFromMetadata(Value *V)
Helper method to assign a range to V from metadata present in the IR.
static cl::opt< unsigned > HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, cl::desc("Size of the expression which is considered huge"), cl::init(4096))
static Type * isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, bool &Signed, ScalarEvolution &SE)
Helper function to createAddRecFromPHIWithCasts.
static Constant * EvaluateExpression(Value *V, const Loop *L, DenseMap< Instruction *, Constant * > &Vals, const DataLayout &DL, const TargetLibraryInfo *TLI)
EvaluateExpression - Given an expression that passes the getConstantEvolvingPHI predicate,...
static const SCEV * getPreviousSCEVDivisibleByDivisor(const SCEV *Expr, const APInt &DivisorVal, ScalarEvolution &SE)
static const SCEV * MatchNotExpr(const SCEV *Expr)
If Expr computes ~A, return A else return nullptr.
static std::pair< ConstantRange, bool > getRangeForAffineARHelper(APInt Step, const ConstantRange &StartRange, const APInt &MaxBECount, bool Signed)
static cl::opt< unsigned > MaxValueCompareDepth("scalar-evolution-max-value-compare-depth", cl::Hidden, cl::desc("Maximum depth of recursive value complexity comparisons"), cl::init(2))
static const SCEV * applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr, APInt Divisor, ScalarEvolution &SE)
static cl::opt< bool, true > VerifySCEVOpt("verify-scev", cl::Hidden, cl::location(VerifySCEV), cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"))
static const SCEV * getSignedOverflowLimitForStep(const SCEV *Step, ICmpInst::Predicate *Pred, ScalarEvolution *SE)
static cl::opt< unsigned > MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, cl::desc("Maximum depth of recursive arithmetics"), cl::init(32))
static bool HasSameValue(const SCEV *A, const SCEV *B)
SCEV structural equivalence is usually sufficient for testing whether two expressions are equal,...
static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow)
Compute the result of "n choose k", the binomial coefficient.
static std::optional< int > CompareSCEVComplexity(const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, DominatorTree &DT, unsigned Depth=0)
static bool scevUnconditionallyPropagatesPoisonFromOperands(SCEVTypes Kind)
static cl::opt< bool > VerifySCEVStrict("verify-scev-strict", cl::Hidden, cl::desc("Enable stricter verification with -verify-scev is passed"))
static Constant * getOtherIncomingValue(PHINode *PN, BasicBlock *BB)
static cl::opt< bool > UseExpensiveRangeSharpening("scalar-evolution-use-expensive-range-sharpening", cl::Hidden, cl::init(false), cl::desc("Use more powerful methods of sharpening expression ranges. May " "be costly in terms of compile time"))
static const SCEV * getUnsignedOverflowLimitForStep(const SCEV *Step, ICmpInst::Predicate *Pred, ScalarEvolution *SE)
static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Is LHS Pred RHS true on the virtue of LHS or RHS being a Min or Max expression?
static bool BrPHIToSelect(DominatorTree &DT, CondBrInst *BI, PHINode *Merge, Value *&C, Value *&LHS, Value *&RHS)
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
static bool InBlock(const Value *V, const BasicBlock *BB)
Provides some synthesis utilities to produce sequences of values.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
static std::optional< bool > isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS, const Value *ARHS, const Value *BLHS, const Value *BRHS)
Return true if "icmp Pred BLHS BRHS" is true whenever "icmp PredALHS ARHS" is true.
Virtual Register Rewriter
Value * RHS
Value * LHS
BinaryOperator * Mul
static const uint32_t IV[8]
Definition blake3_impl.h:83
SCEVCastSinkingRewriter(ScalarEvolution &SE, Type *TargetTy, ConversionFn CreatePtrCast)
static const SCEV * rewrite(const SCEV *Scev, ScalarEvolution &SE, Type *TargetTy, ConversionFn CreatePtrCast)
const SCEV * visitUnknown(const SCEVUnknown *Expr)
const SCEV * visitAddExpr(const SCEVAddExpr *Expr)
const SCEV * visit(const SCEV *S)
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2009
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
APInt abs() const
Get the absolute value.
Definition APInt.h:1815
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition APInt.h:462
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:212
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1170
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1973
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
bool isNonPositive() const
Determine if this APInt Value is non-positive (<= 0).
Definition APInt.h:357
unsigned countTrailingZeros() const
Definition APInt.h:1667
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:352
unsigned logBase2() const
Definition APInt.h:1781
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:471
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1303
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
bool isSignBitSet() const
Determine if sign bit of this APInt is set.
Definition APInt.h:337
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1134
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition APInt.h:428
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
AnalysisUsage & addRequiredTransitive()
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
MutableArrayRef< WeakVH > assumptions()
Access the list of assumption handles currently tracked for this function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction & front() const
Definition BasicBlock.h:469
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI unsigned getNoWrapKind() const
Returns one of OBO::NoSignedWrap or OBO::NoUnsignedWrap.
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
This class represents a function call, abstracting a target machine's calling convention.
virtual void deleted()
Callback for Value destruction.
void setValPtr(Value *P)
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
bool isFalseWhenEqual() const
This is just a convenience.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
bool isSigned() const
Definition InstrTypes.h:993
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
bool isUnsigned() const
Definition InstrTypes.h:999
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Definition InstrTypes.h:989
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
LLVM_ABI CmpInst::Predicate getPreferredSignedPredicate() const
Attempts to return a signed CmpInst::Predicate from the CmpPredicate.
CmpInst::Predicate dropSameSign() const
Drops samesign information.
Conditional Branch instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static LLVM_ABI Constant * getNot(Constant *C)
static Constant * getPtrAdd(Constant *Ptr, Constant *Offset, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReduced=nullptr)
Create a getelementptr i8, ptr, offset constant expression.
Definition Constants.h:1513
static LLVM_ABI Constant * getPtrToAddr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
This class represents a range of values.
LLVM_ABI ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
LLVM_ABI ConstantRange zextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
LLVM_ABI bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const
Set up Pred and RHS such that ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.
const APInt & getLower() const
Return the lower value for this range.
LLVM_ABI ConstantRange urem(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned remainder operation of...
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI ConstantRange zeroExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
LLVM_ABI bool isSignWrappedSet() const
Return true if this set wraps around the signed domain.
LLVM_ABI APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
LLVM_ABI bool isWrappedSet() const
Return true if this set wraps around the unsigned domain.
LLVM_ABI void print(raw_ostream &OS) const
Print out the bounds to a stream.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
LLVM_ABI ConstantRange signExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
const APInt & getUpper() const
Return the upper value for this range.
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static LLVM_ABI ConstantRange makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp, const ConstantRange &Other, unsigned NoWrapKind)
Produce the largest range containing all X such that "X BinOp Y" is guaranteed not to wrap (overflow)...
LLVM_ABI unsigned getMinSignedBits() const
Compute the maximal number of bits needed to represent every value in this signed range.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
LLVM_ABI ConstantRange sextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
static LLVM_ABI ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp, const APInt &Other, unsigned NoWrapKind)
Produce the range that contains X if and only if "X BinOp Other" does not wrap.
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
LLVM_ABI IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:791
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:285
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:258
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:348
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition DenseMap.h:168
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive,...
Definition DenseMap.h:271
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:254
iterator end()
Definition DenseMap.h:176
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:249
void swap(DerivedT &RHS)
Definition DenseMap.h:486
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:319
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction extracts a single (scalar) element from a VectorType value.
This instruction extracts a struct member or array element value from an aggregate value.
Insertion token: a failed lookup fills it in, the matching insert consumes it.
Definition FoldingSet.h:284
This class describes a reference to an interned FoldingSetNodeID, which can be a useful to store node...
Definition FoldingSet.h:123
This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:162
void AddInteger(signed I)
Definition FoldingSet.h:190
This class represents a freeze function that returns random concrete value if an operand is either a ...
FunctionPass(char &pid)
Definition Pass.h:316
Represents flags for the getelementptr instruction/expression.
bool hasNoUnsignedSignedWrap() const
bool hasNoUnsignedWrap() const
static GEPNoWrapFlags none()
static LLVM_ABI Type * getTypeAtIndex(Type *Ty, Value *Idx)
Return the type of the element at the given index of an indexable type.
Module * getParent()
Get the module that this global value is contained inside of...
static bool isPrivateLinkage(LinkageTypes Linkage)
static bool isInternalLinkage(LinkageTypes Linkage)
This instruction compares its operands according to the predicate given to the constructor.
CmpPredicate getCmpPredicate() const
static bool isGE(Predicate P)
Return true if the predicate is SGE or UGE.
CmpPredicate getSwappedCmpPredicate() const
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
static bool isLT(Predicate P)
Return true if the predicate is SLT or ULT.
CmpPredicate getInverseCmpPredicate() const
Predicate getNonStrictCmpPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
static bool isGT(Predicate P)
Return true if the predicate is SGT or UGT.
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
static CmpPredicate getInverseCmpPredicate(CmpPredicate Pred)
bool isEquality() const
Return true if this predicate is either EQ or NE.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
static bool isLE(Predicate P)
Return true if the predicate is SLE or ULE.
This instruction inserts a single (scalar) element into a VectorType value.
This instruction inserts a struct field of array element value into an aggregate value.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI bool isIdenticalToWhenDefined(const Instruction *I, bool IntersectAttrs=false) const LLVM_READONLY
This is like isIdenticalTo, except that it ignores the SubclassOptionalData flags,...
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
A helper class to return the specified delimiter string after the first invocation of operator String...
An instruction for reading from memory.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
BlockT * getHeader() const
unsigned getLoopDepth() const
Return the nesting level of this loop.
BlockT * getLoopPredecessor() const
If the given loop's header has exactly one unique predecessor outside the loop, return it.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
unsigned getLoopDepth(const BlockT *BB) const
Return the loop nesting level of the specified block.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:619
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:67
Metadata node.
Definition Metadata.h:1081
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition Operator.h:113
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition Operator.h:107
iterator_range< const_block_iterator > blocks() const
op_range incoming_values()
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
PointerIntPair - This class implements a pair of a pointer and small integer.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
LLVM_ABI void addPredicate(const SCEVPredicate &Pred)
Adds a new predicate.
LLVM_ABI const SCEVPredicate & getPredicate() const
LLVM_ABI const SCEV * getPredicatedSCEV(const SCEV *Expr)
Returns the rewritten SCEV for Expr in the context of the current SCEV predicate.
LLVM_ABI bool areAddRecsEqualWithPreds(const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2, ArrayRef< const SCEVPredicate * > ExtraPreds={}) const
Check if AR1 and AR2 are equal, while taking into account Equal predicates in Preds and ExtraPreds.
LLVM_ABI const SCEVAddRecExpr * getAsAddRec(Value *V, SmallVectorImpl< const SCEVPredicate * > *WrapPredsAdded=nullptr)
Attempts to produce an AddRecExpr for V by adding additional SCEV predicates.
LLVM_ABI void print(raw_ostream &OS, unsigned Depth) const
Print the SCEV mappings done by the Predicated Scalar Evolution.
LLVM_ABI PredicatedScalarEvolution(ScalarEvolution &SE, Loop &L)
LLVM_ABI unsigned getSmallConstantMaxTripCount()
Returns the upper bound of the loop trip count as a normal unsigned value, or 0 if the trip count is ...
LLVM_ABI void addPredicates(ArrayRef< const SCEVPredicate * > Preds)
Adds all predicates in Preds.
LLVM_ABI const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSymbolicMaxBackedgeTakenCount()
Get the (predicated) symbolic max backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
constexpr bool isValid() const
Definition Register.h:112
This node represents an addition of some number of SCEVs.
This node represents a polynomial recurrence on the trip count of the specified loop.
LLVM_ABI SCEVUse getExitValue(ScalarEvolution &SE) const
Return the value of this recurrences when its loop exits, i.e.
LLVM_ABI const SCEV * evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const
Return the value of this chain of recurrences at the specified iteration number.
void setNoWrapFlags(NoWrapFlags Flags)
Set flags for a recurrence without clearing any previously set flags.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
bool isQuadratic() const
Return true if this represents an expression A + B*x + C*x^2 where A, B and C are loop invariant valu...
LLVM_ABI const SCEV * getNumIterationsInRange(const ConstantRange &Range, ScalarEvolution &SE) const
Return the number of iterations of this loop that produce values in the specified constant range.
LLVM_ABI const SCEVAddRecExpr * getPostIncExpr(ScalarEvolution &SE) const
Return an expression representing the value of this expression one iteration of the loop ahead.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This is the base class for unary cast operator classes.
LLVM_ABI SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, SCEVUse op, Type *ty)
void setNoWrapFlags(NoWrapFlags Flags)
Set flags for a non-recurrence without clearing previously set flags.
This class represents an assumption that the expression LHS Pred RHS evaluates to true,...
SCEVComparePredicate(const FoldingSetNodeIDRef ID, const ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
bool isAlwaysTrue() const override
Returns true if the predicate is always true.
void print(raw_ostream &OS, unsigned Depth=0) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Implementation of the SCEVPredicate interface.
This class represents a constant integer value.
ConstantInt * getValue() const
const APInt & getAPInt() const
This is the base class for unary integral cast operator classes.
LLVM_ABI SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, SCEVUse op, Type *ty)
This node is the base class min/max selections.
static enum SCEVTypes negate(enum SCEVTypes T)
This node represents multiplication of some number of SCEVs.
This node is a base class providing common functionality for n'ary operators.
ArrayRef< SCEVUse > operands() const
NoWrapFlags getNoWrapFlags(NoWrapFlags Mask=FlagsMask) const
SCEVUse getOperand(unsigned i) const
This class represents an assumption made using SCEV expressions which can be checked at run-time.
SCEVPredicate(const SCEVPredicate &)=default
virtual bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const =0
Returns true if this predicate implies N.
SCEVPredicateKind Kind
This class represents a cast from a pointer to a pointer-sized integer value, without capturing the p...
This visitor recursively visits a SCEV expression and re-writes it.
const SCEV * visitPtrToAddrExpr(const SCEVPtrToAddrExpr *Expr)
const SCEV * visitSignExtendExpr(const SCEVSignExtendExpr *Expr)
const SCEV * visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr)
const SCEV * visitSMinExpr(const SCEVSMinExpr *Expr)
const SCEV * visitUMinExpr(const SCEVUMinExpr *Expr)
This class represents a signed minimum selection.
This node is the base class for sequential/in-order min/max selections.
static SCEVTypes getEquivalentNonSequentialSCEVType(SCEVTypes Ty)
This class represents a sign extension of a small integer value to a larger integer value.
Visit all nodes in the expression tree using worklist traversal.
This class represents a truncation of an integer value to a smaller integer value.
This class represents a binary unsigned division operation.
This class represents an unsigned minimum selection.
This class represents a composition of other SCEV predicates, and is the class that most clients will...
void print(raw_ostream &OS, unsigned Depth) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Returns true if this predicate implies N.
SCEVUnionPredicate(ArrayRef< const SCEVPredicate * > Preds, ScalarEvolution &SE)
Union predicates don't get cached so create a dummy set ID for it.
bool isAlwaysTrue() const override
Implementation of the SCEVPredicate interface.
SCEVUnionPredicate getUnionWith(const SCEVPredicate *N, ScalarEvolution &SE) const
Returns a new SCEVUnionPredicate that is the union of this predicate and the given predicate N.
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
This class represents the value of vscale, as used when defining the length of a scalable vector or r...
This class represents an assumption made on an AddRec expression.
IncrementWrapFlags
Similar to SCEV::NoWrapFlags, but with slightly different semantics for FlagNUSW.
SCEVWrapPredicate(const FoldingSetNodeIDRef ID, const SCEVAddRecExpr *AR, IncrementWrapFlags Flags)
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Returns true if this predicate implies N.
static SCEVWrapPredicate::IncrementWrapFlags setFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OnFlags)
void print(raw_ostream &OS, unsigned Depth=0) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool isAlwaysTrue() const override
Returns true if the predicate is always true.
const SCEVAddRecExpr * getExpr() const
Implementation of the SCEVPredicate interface.
static SCEVWrapPredicate::IncrementWrapFlags clearFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OffFlags)
Convenient IncrementWrapFlags manipulation methods.
IncrementWrapFlags getFlags() const
Returns the set assumed no overflow flags.
This class represents a zero extension of a small integer value to a larger integer value.
This class represents an analyzed expression in the program.
unsigned short getExpressionSize() const
SCEVNoWrapFlags NoWrapFlags
LLVM_ABI bool isOne() const
Return true if the expression is a constant one.
SCEV(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, unsigned short ExpressionSize, Type *Ty)
static constexpr auto FlagNUW
LLVM_ABI void computeAndSetCanonical(ScalarEvolution &SE)
Compute and set the canonical SCEV, by constructing a SCEV with the same operands,...
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
const SCEV * CanonicalSCEV
Pointer to the canonical version of the SCEV, i.e.
LLVM_ABI void dump() const
This method is used for debugging.
LLVM_ABI bool isAllOnesValue() const
Return true if the expression is a constant all-ones value.
LLVM_ABI bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
static constexpr auto FlagNSW
LLVM_ABI ArrayRef< SCEVUse > operands() const
Return operands of this SCEV expression.
Type * getType() const
Return the LLVM type of this SCEV expression.
static constexpr auto FlagNone
LLVM_ABI void print(raw_ostream &OS) const
Print out the internal representation of this scalar to the specified stream.
SCEVTypes getSCEVType() const
static constexpr auto FlagNW
Analysis pass that exposes the ScalarEvolution for a function.
LLVM_ABI ScalarEvolution run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void print(raw_ostream &OS, const Module *=nullptr) const override
print - Print out the internal state of the pass.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
static LLVM_ABI LoopGuards collect(const Loop *L, ScalarEvolution &SE)
Collect rewrite map for loop guards for loop L, together with flags indicating if NUW and NSW can be ...
LLVM_ABI const SCEV * rewrite(const SCEV *Expr) const
Try to apply the collected loop guards to Expr.
The main scalar evolution driver.
LLVM_ABI const SCEV * getUDivExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
const SCEV * getConstantMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
static bool hasFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags TestFlags)
const DataLayout & getDataLayout() const
Return the DataLayout associated with the module this SCEV instance is operating on.
LLVM_ABI bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
LLVM_ABI bool isKnownOnEveryIteration(CmpPredicate Pred, const SCEVAddRecExpr *LHS, const SCEV *RHS)
Test if the condition described by Pred, LHS, RHS is known to be true on every iteration of the loop ...
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantExitCondDuringFirstIterationsImpl(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI, const SCEV *MaxIter)
LLVM_ABI const SCEV * getZeroExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getUDivCeilSCEV(const SCEV *N, const SCEV *D)
Compute ceil(N / D).
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantExitCondDuringFirstIterations(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI, const SCEV *MaxIter)
If the result of the predicate LHS Pred RHS is loop invariant with respect to L at given Context duri...
LLVM_ABI Type * getWiderType(Type *Ty1, Type *Ty2) const
LLVM_ABI const SCEV * getAbsExpr(const SCEV *Op, bool IsNSW)
LLVM_ABI bool isKnownNonPositive(const SCEV *S)
Test if the given expression is known to be non-positive.
LLVM_ABI bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
LLVM_ABI const SCEV * getPredicatedConstantMaxBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getConstantMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
LLVM_ABI const SCEV * removePointerBase(const SCEV *S)
Compute an expression equivalent to S - getPointerBase(S).
LLVM_ABI bool isLoopEntryGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the loop is protected by a conditional between LHS and RHS.
LLVM_ABI bool isKnownNonZero(const SCEV *S)
Test if the given expression is known to be non-zero.
LLVM_ABI const SCEV * getURemExpr(SCEVUse LHS, SCEVUse RHS)
Represents an unsigned remainder expression based on unsigned division.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LLVM_ABI const SCEV * getSMinExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI void setNoWrapFlags(SCEVAddRecExpr *AddRec, SCEV::NoWrapFlags Flags)
Update no-wrap flags of an AddRec.
LLVM_ABI const SCEV * getUMaxFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS)
Promote the operands to the wider of the types using zero-extension, and then perform a umax operatio...
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
LLVM_ABI bool willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI=nullptr)
Is operation BinOp between LHS and RHS provably does not have a signed/unsigned overflow (Signed)?
LLVM_ABI ExitLimit computeExitLimitFromCond(const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit, bool AllowPredicates=false)
Compute the number of times the backedge of the specified loop will execute if its exit condition wer...
LLVM_ABI const SCEV * getMinMaxExpr(SCEVTypes Kind, SmallVectorImpl< SCEVUse > &Operands)
LLVM_ABI const SCEVPredicate * getEqualPredicate(const SCEV *LHS, const SCEV *RHS)
LLVM_ABI unsigned getSmallConstantTripMultiple(const Loop *L, const SCEV *ExitCount)
Returns the largest constant divisor of the trip count as a normal unsigned value,...
LLVM_ABI SCEVUse getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
LLVM_ABI uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
LLVM_ABI void registerUser(const SCEV *User, ArrayRef< SCEVUse > Ops)
Notify this ScalarEvolution that User directly uses SCEVs in Ops.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getPredicatedBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getBackedgeTakenCount, except it will add a set of SCEV predicates to Predicates that are ...
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
ConstantRange getSignedRange(const SCEV *S)
Determine the signed range for a particular SCEV.
LLVM_ABI const SCEV * getNoopOrSignExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
static LLVM_ABI bool isGuaranteedNotToBePoison(const SCEV *Op)
Returns true if Op is guaranteed to not be poison.
bool loopHasNoAbnormalExits(const Loop *L)
Return true if the loop has no abnormal exits.
LLVM_ABI const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
LLVM_ABI ScalarEvolution(Function &F, TargetLibraryInfo &TLI, AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI)
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI const SCEV * getTruncateOrNoop(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI void forgetValues(ArrayRef< Value * > Values)
Batched forgetValue: invalidates all Values in one shared def-use walk, avoiding the redundant re-tra...
LLVM_ABI const SCEV * getSequentialMinMaxExpr(SCEVTypes Kind, SmallVectorImpl< SCEVUse > &Operands)
LLVM_ABI const SCEV * getCastExpr(SCEVTypes Kind, SCEVUse Op, Type *Ty)
LLVM_ABI std::optional< bool > evaluatePredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Check whether the condition described by Pred, LHS, and RHS is true or false in the given Context.
LLVM_ABI unsigned getSmallConstantMaxTripCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Returns the upper bound of the loop trip count as a normal unsigned value.
LLVM_ABI bool isKnownMultipleOf(const SCEV *S, uint64_t M, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Check that S is a multiple of M.
LLVM_ABI bool isBackedgeTakenCountMaxOrZero(const Loop *L)
Return true if the backedge taken count is either the value returned by getConstantMaxBackedgeTakenCo...
LLVM_ABI void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI bool isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
LLVM_ABI bool SimplifyICmpOperands(CmpPredicate &Pred, SCEVUse &LHS, SCEVUse &RHS, unsigned Depth=0)
Simplify LHS and RHS in a comparison with predicate Pred.
APInt getUnsignedRangeMin(const SCEV *S)
Determine the min of the unsigned range for a particular SCEV.
LLVM_ABI const SCEV * getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo)
Return an expression for offsetof on the given field with type IntTy.
LLVM_ABI LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L)
Return the "disposition" of the given SCEV with respect to the given loop.
LLVM_ABI bool containsAddRecurrence(const SCEV *S)
Return true if the SCEV is a scAddRecExpr or it contains scAddRecExpr.
LLVM_ABI const SCEV * getTruncateExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool hasOperand(const SCEV *S, const SCEV *Op) const
Test whether the given SCEV has Op as a direct or indirect operand.
LLVM_ABI const SCEV * getZeroExtendExprImpl(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI Type * getEffectiveSCEVType(Type *Ty) const
Return a type with the same bitwidth as the given type and which represents how SCEV will treat the g...
LLVM_ABI const SCEVPredicate * getComparePredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
LLVM_ABI bool haveSameSign(const SCEV *S1, const SCEV *S2)
Return true if we know that S1 and S2 must have the same sign.
LLVM_ABI const SCEV * getNotSCEV(const SCEV *V)
Return the SCEV object corresponding to ~V.
LLVM_ABI bool instructionCouldExistWithOperands(const SCEV *A, const SCEV *B)
Return true if there exists a point in the program at which both A and B could be operands to the sam...
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
LLVM_ABI void print(raw_ostream &OS) const
LLVM_ABI const SCEV * getAnyExtendExpr(SCEVUse Op, Type *Ty)
getAnyExtendExpr - Return a SCEV for the given operand extended with unspecified bits out to the give...
LLVM_ABI const SCEV * getPredicatedExitCount(const Loop *L, const BasicBlock *ExitingBlock, SmallVectorImpl< const SCEVPredicate * > *Predicates, ExitCountKind Kind=Exact)
Same as above except this uses the predicated backedge taken info and may require predicates.
static SCEV::NoWrapFlags clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags)
LLVM_ABI void forgetTopmostLoop(const Loop *L)
LLVM_ABI void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
APInt getSignedRangeMin(const SCEV *S)
Determine the min of the signed range for a particular SCEV.
LLVM_ABI bool isLoopUniform(const SCEV *S, const Loop *L)
Returns true if the given SCEV is loop-uniform with respect to the specified loop L.
LLVM_ABI const SCEV * getNoopOrAnyExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
LLVM_ABI const SCEV * getSignExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getUMaxExpr(SCEVUse LHS, SCEVUse RHS)
static SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags Mask)
Convenient NoWrapFlags manipulation.
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantPredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI=nullptr)
If the result of the predicate LHS Pred RHS is loop invariant with respect to L, return a LoopInvaria...
LLVM_ABI const SCEV * getStoreSizeOfExpr(Type *IntTy, Type *StoreTy)
Return an expression for the store size of StoreTy that is type IntTy.
LLVM_ABI const SCEVPredicate * getWrapPredicate(const SCEVAddRecExpr *AR, SCEVWrapPredicate::IncrementWrapFlags AddedFlags)
LLVM_ABI bool isLoopBackedgeGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether the backedge of the loop is protected by a conditional between LHS and RHS.
LLVM_ABI APInt getNonZeroConstantMultiple(const SCEV *S)
const SCEV * getMinusOne(Type *Ty)
Return a SCEV for the constant -1 of a specific type.
static SCEV::NoWrapFlags setFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OnFlags)
LLVM_ABI bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count.
LLVM_ABI BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB)
Return the "disposition" of the given SCEV with respect to the given block.
LLVM_ABI const SCEV * getNoopOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
LLVM_ABI const SCEV * getUMinFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS, bool Sequential=false)
Promote the operands to the wider of the types using zero-extension, and then perform a umin operatio...
LLVM_ABI bool loopIsFiniteByAssumption(const Loop *L)
Return true if this loop is finite by assumption.
LLVM_ABI SCEVUse getSCEVAtExit(const SCEV *S, const Loop *L, const BasicBlock *ExitingBlock)
Return the SCEV expression at the specified loop exit.
LLVM_ABI const SCEV * getExistingSCEV(Value *V)
Return an existing SCEV for V if there is one, otherwise return nullptr.
LLVM_ABI APInt getConstantMultiple(const SCEV *S, const Instruction *CtxI=nullptr)
Returns the max constant multiple of S.
LoopDisposition
An enum describing the relationship between a SCEV and a loop.
@ LoopComputable
The SCEV varies predictably with the loop.
@ LoopVariant
The SCEV is loop-variant (unknown).
@ LoopInvariant
The SCEV is loop-invariant.
@ LoopUniform
The SCEV is loop-uniform.
LLVM_ABI bool isKnownToBeAPowerOfTwo(const SCEV *S, bool OrZero=false, bool OrNegative=false)
Test if the given expression is known to be a power of 2.
LLVM_ABI std::optional< SCEV::NoWrapFlags > getStrengthenedNoWrapFlagsFromBinOp(const OverflowingBinaryOperator *OBO)
Parse NSW/NUW flags from add/sub/mul IR binary operation Op into SCEV no-wrap flags,...
LLVM_ABI void forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V)
Forget LCSSA phi node V of loop L to which a new predecessor was added, such that it may no longer be...
LLVM_ABI bool containsUndefs(const SCEV *S) const
Return true if the SCEV expression contains an undef value.
LLVM_ABI std::optional< MonotonicPredicateType > getMonotonicPredicateType(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred)
If, for all loop invariant X, the predicate "LHS `Pred` X" is monotonically increasing or decreasing,...
LLVM_ABI const SCEV * getCouldNotCompute()
LLVM_ABI bool isAvailableAtLoopEntry(const SCEV *S, const Loop *L)
Determine if the SCEV can be evaluated at loop's entry.
LLVM_ABI uint32_t getMinTrailingZeros(const SCEV *S, const Instruction *CtxI=nullptr)
Determine the minimum number of zero bits that S is guaranteed to end in (at every loop iteration).
BlockDisposition
An enum describing the relationship between a SCEV and a basic block.
@ DominatesBlock
The SCEV dominates the block.
@ ProperlyDominatesBlock
The SCEV properly dominates the block.
@ DoesNotDominateBlock
The SCEV does not dominate the block.
LLVM_ABI const SCEV * getExitCount(const Loop *L, const BasicBlock *ExitingBlock, ExitCountKind Kind=Exact)
Return the number of times the backedge executes before the given exit would be taken; if not exactly...
LLVM_ABI void getPoisonGeneratingValues(SmallPtrSetImpl< const Value * > &Result, const SCEV *S)
Return the set of Values that, if poison, will definitively result in S being poison as well.
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagNone)
Return the SCEV object corresponding to -V.
LLVM_ABI void forgetLoopDispositions()
Called when the client has changed the disposition of values in this loop.
LLVM_ABI const SCEV * getVScale(Type *Ty)
LLVM_ABI unsigned getSmallConstantTripCount(const Loop *L)
Returns the exact trip count of the loop if we can compute it, and the result is a small constant.
LLVM_ABI bool hasComputableLoopEvolution(const SCEV *S, const Loop *L)
Return true if the given SCEV changes value in a known way in the specified loop.
LLVM_ABI const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
LLVM_ABI void forgetAllLoops()
LLVM_ABI const SCEV * getSignExtendExprImpl(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool dominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV dominate the specified basic block.
APInt getUnsignedRangeMax(const SCEV *S)
Determine the max of the unsigned range for a particular SCEV.
ExitCountKind
The terms "backedge taken count" and "exit count" are used interchangeably to refer to the number of ...
@ SymbolicMaximum
An expression which provides an upper bound on the exact trip count.
@ ConstantMaximum
A constant which provides an upper bound on the exact trip count.
@ Exact
An expression exactly describing the number of times the backedge has executed when a loop is exited.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
LLVM_ABI const SCEV * getPtrToAddrExpr(const SCEV *Op)
LLVM_ABI const SCEVAddRecExpr * convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Preds)
Tries to convert the S expression to an AddRec expression, adding additional predicates to Preds as r...
LLVM_ABI const SCEV * getSMaxExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI const SCEV * getElementSize(Instruction *Inst)
Return the size of an element read or written by Inst.
LLVM_ABI const SCEV * getSizeOfExpr(Type *IntTy, TypeSize Size)
Return an expression for a TypeSize.
LLVM_ABI std::optional< bool > evaluatePredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Check whether the condition described by Pred, LHS, and RHS is true or false.
LLVM_ABI const SCEV * getUnknown(Value *V)
LLVM_ABI std::optional< std::pair< const SCEV *, SmallVector< const SCEVPredicate *, 3 > > > createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI)
Checks if SymbolicPHI can be rewritten as an AddRecExpr under some Predicates.
LLVM_ABI const SCEV * getTruncateOrZeroExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool isKnownViaInduction(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
We'd like to check the predicate on every iteration of the most dominated loop between loops used in ...
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEV::NoWrapFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI std::optional< APInt > computeConstantDifference(const SCEV *LHS, const SCEV *RHS)
Compute LHS - RHS and returns the result as an APInt if it is a constant, and std::nullopt if it isn'...
LLVM_ABI bool properlyDominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV properly dominate the specified basic block.
LLVM_ABI const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEV::NoWrapFlags Flags=SCEV::FlagNone)
LLVM_ABI const SCEV * getUDivExactExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
LLVM_ABI const SCEV * rewriteUsingPredicate(const SCEV *S, const Loop *L, const SCEVPredicate &A)
Re-writes the SCEV according to the Predicates in A.
LLVM_ABI std::pair< const SCEV *, const SCEV * > SplitIntoInitAndPostInc(const Loop *L, const SCEV *S)
Splits SCEV expression S into two SCEVs.
LLVM_ABI bool canReuseInstruction(const SCEV *S, Instruction *I, SmallVectorImpl< Instruction * > &DropPoisonGeneratingInsts)
Check whether it is poison-safe to represent the expression S using the instruction I.
LLVM_ABI bool isKnownPredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * getPredicatedSymbolicMaxBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getSymbolicMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
LLVM_ABI SCEVUse getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlags Flags={}, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
LLVM_ABI const SCEV * getGEPExpr(GEPOperator *GEP, ArrayRef< SCEVUse > IndexExprs)
Returns an expression for a GEP.
LLVM_ABI const SCEV * getUMinExpr(SCEVUse LHS, SCEVUse RHS, bool Sequential=false)
LLVM_ABI bool isBasicBlockEntryGuardedByCond(const BasicBlock *BB, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the basic block is protected by a conditional between LHS and RHS.
LLVM_ABI const SCEV * getTruncateOrSignExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool containsErasedValue(const SCEV *S) const
Return true if the SCEV expression contains a Value that has been optimised out and is now a nullptr.
LLVM_ABI SCEVUse getAddRecExpr(SCEVUse Start, SCEVUse Step, const Loop *L, SCEVFlags Flags)
Get an add recurrence expression for the specified loop.
LLVM_ABI SCEVUse getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlags Flags={}, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
const SCEV * getSymbolicMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEV that is greater than or equal to (i.e.
APInt getSignedRangeMax(const SCEV *S)
Determine the max of the signed range for a particular SCEV.
LLVM_ABI void verify() const
LLVMContext & getContext() const
This class represents the LLVM 'select' instruction.
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:293
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:743
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
TypeSize getSizeInBits() const
Definition DataLayout.h:754
Class to represent struct types.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
Use & Op()
Definition User.h:171
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition Value.h:545
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition APInt.h:2274
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition APInt.h:2279
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition APInt.h:2284
LLVM_ABI std::optional< APInt > SolveQuadraticEquationWrap(APInt A, APInt B, APInt C, unsigned RangeWidth)
Let q(n) = An^2 + Bn + C, and BW = bit width of the value range (e.g.
Definition APInt.cpp:2850
LLVM_ABI APInt GreatestCommonDivisor(APInt A, APInt B, bool IsSigned=false)
Compute GCD of two APInt values.
Definition APInt.cpp:826
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2289
constexpr bool any(E Val)
@ Entry
Definition COFF.h:862
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
bind_cst_ty m_scev_APInt(const APInt *&C)
Match an SCEV constant and bind it to an APInt.
cst_pred_ty< is_all_ones > m_scev_AllOnes()
Match an integer with all bits set.
SCEVUnaryExpr_match< SCEVZeroExtendExpr, Op0_t > m_scev_ZExt(const Op0_t &Op0)
is_undef_or_poison m_scev_UndefOrPoison()
Match an SCEVUnknown wrapping undef or poison.
cst_pred_ty< is_one > m_scev_One()
Match an integer 1.
specificloop_ty m_SpecificLoop(const Loop *L)
SCEVUnaryExpr_match< SCEVSignExtendExpr, Op0_t > m_scev_SExt(const Op0_t &Op0)
match_bind< const SCEVMulExpr > m_scev_Mul(const SCEVMulExpr *&V)
cst_pred_ty< is_zero > m_scev_Zero()
Match an integer 0.
SCEVUnaryExpr_match< SCEVTruncateExpr, Op0_t > m_scev_Trunc(const Op0_t &Op0)
bool match(const SCEV *S, const Pattern &P)
SCEVBinaryExpr_match< SCEVUDivExpr, Op0_t, Op1_t > m_scev_UDiv(const Op0_t &Op0, const Op1_t &Op1)
specificscev_ty m_scev_Specific(const SCEV *S)
Match if we have a specific specified SCEV.
SCEVAffineAddRec_match< Op0_t, Op1_t, match_isa< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
match_bind< const SCEVUnknown > m_SCEVUnknown(const SCEVUnknown *&V)
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t, SCEV::FlagNUW, true > m_scev_c_NUWMul(const Op0_t &Op0, const Op1_t &Op1)
SCEVBinaryExpr_match< SCEVSMaxExpr, Op0_t, Op1_t, SCEV::FlagNone, true > m_scev_SMax(const Op0_t &Op0, const Op1_t &Op1)
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t, SCEV::FlagNone, true > m_scev_c_Mul(const Op0_t &Op0, const Op1_t &Op1)
match_bind< const SCEVAddExpr > m_scev_Add(const SCEVAddExpr *&V)
SCEVURem_match< Op0_t, Op1_t > m_scev_URem(Op0_t LHS, Op1_t RHS, ScalarEvolution &SE)
Match the mathematical pattern A - (A / B) * B, where A and B can be arbitrary expressions.
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
Definition CoroShape.h:32
constexpr double e
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
void visitAll(const SCEV *Root, SV &Visitor)
Use SCEVTraversal to visit all nodes in the given expression tree.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
void stable_sort(R &&Range)
Definition STLExtras.h:2132
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
SaveAndRestore(T &) -> SaveAndRestore< T >
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
LLVM_ABI bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
LLVM_ABI bool mustTriggerUB(const Instruction *I, const SmallPtrSetImpl< const Value * > &KnownPoison)
Return true if the given instruction must trigger undefined behavior when I is executed with any oper...
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
@ Known
Known to have no common set bits.
@ Dead
Unused definition.
InterleavedRange< Range > interleaved(const Range &R, StringRef Separator=", ", StringRef Prefix="", StringRef Suffix="")
Output range R as a sequence of interleaved elements.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
auto successors(const MachineBasicBlock *BB)
scope_exit(Callable) -> scope_exit< Callable >
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
@ BinaryOp
One of the operands is a binary op.
constexpr from_range_t from_range
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
bool set_is_subset(const S1Ty &S1, const S2Ty &S2)
set_is_subset(A, B) - Return true iff A in B
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
void * PointerTy
LLVM_ABI bool VerifySCEV
auto uninitialized_copy(R &&Src, IterTy Dst)
Definition STLExtras.h:2127
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
LLVM_ABI bool canConstantFoldCallTo(const CallBase *Call, const Function *F, const TargetLibraryInfo *TLI=nullptr)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, const DominatorTree &DT)
Returns true if the arithmetic part of the WO 's result is used only along the paths control dependen...
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2216
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI bool isMustProgress(const Loop *L)
Return true if this loop can be assumed to make progress.
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
LLVM_ABI bool isFinite(const Loop *L)
Return true if this loop can be assumed to run for a finite number of iterations.
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
unsigned short computeExpressionSize(ArrayRef< SCEVUse > Args)
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:383
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
LLVM_ABI bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ Mul
Product of integers.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ Add
Sum of integers.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
DWARFExpression::Operation Op
auto max_element(R &&Range)
Provide wrappers to std::max_element which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2104
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:249
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
iterator_range< df_iterator< T > > depth_first(const T &G)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2162
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Function *CxtF=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
SCEVUseT< const SCEV * > SCEVUse
bool SCEVExprContains(const SCEV *Root, PredTy Pred)
Return true if any node in Root satisfies the predicate Pred.
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
#define NC
Definition regutils.h:42
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
An object of this class is returned by queries that could not be answered.
static LLVM_ABI bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
The no-wrap flags to apply when creating a SCEV expression, to the expression and use respectively.
SCEVNoWrapFlags UseFlags
Flags only applied to a SCEVUse.
SCEVNoWrapFlags ExprFlags
Flags applied directly to a SCEV expression, must be valid wherever the expression is valid.
SCEVPtrT getPointer() const
This class defines a simple visitor class that may be used for various SCEV analysis purposes.
A utility class that uses RAII to save and restore the value of a variable.
Information about the number of loop iterations for which a loop exit's branch condition evaluates to...
LLVM_ABI ExitLimit(const SCEV *E)
Construct either an exact exit limit from a constant, or an unknown one from a SCEVCouldNotCompute.
SmallVector< const SCEVPredicate *, 4 > Predicates
A vector of predicate guards for this ExitLimit.