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/// Attach \p UseFlags to \p Res as use-specific flags, but only if \p Res
974/// really is the two-operand \p ExprT over \p LHS and \p RHS - in either order,
975/// as operands get sorted by complexity.
976///
977/// Flags established for that operation say nothing about any other expression:
978/// a folded-away operand, a flattened nested expression or a distributed
979/// constant all give a different computation. They must not be attached to it,
980/// because an n-ary expression's no-wrap flags have to hold for all subsets and
981/// orders of its operands, and SCEVExpander relies on that when it stamps them
982/// on every partial sum or product it builds.
983template <typename ExprT>
985 SCEVUse RHS,
986 SCEV::NoWrapFlags UseFlags) {
987 auto *E = dyn_cast<ExprT>(Res);
988 if (E && (equal(E->operands(), ArrayRef<SCEVUse>({LHS, RHS})) ||
989 equal(E->operands(), ArrayRef<SCEVUse>({RHS, LHS}))))
990 return {Res, UseFlags};
991 return Res;
992}
993
994/// Return the value of this chain of recurrences at the specified iteration
995/// number. We can evaluate this recurrence by multiplying each element in the
996/// chain by the binomial coefficient corresponding to it. In other words, we
997/// can evaluate {A,+,B,+,C,+,D} as:
998///
999/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1000///
1001/// where BC(It, k) stands for binomial coefficient.
1003 ScalarEvolution &SE) const {
1004 return evaluateAtIteration(operands(), It, SE);
1005}
1006
1008 const SCEV *It, ScalarEvolution &SE,
1009 SCEV::NoWrapFlags UseFlags) {
1010 assert(Operands.size() > 0);
1011 assert((Operands.size() == 2 || UseFlags == SCEV::FlagAnyWrap) &&
1012 "use-specific flags only supported for affine AddRecs");
1013 SCEVUse Result = Operands[0].getPointer();
1014 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1015 // The computation is correct in the face of overflow provided that the
1016 // multiplication is performed _after_ the evaluation of the binomial
1017 // coefficient.
1018 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
1019 if (isa<SCEVCouldNotCompute>(Coeff))
1020 return Coeff;
1021
1022 const SCEV *Mul = SE.getMulExpr(Operands[i].getPointer(), Coeff);
1024 Result, Mul, UseFlags);
1025 }
1026 return Result;
1027}
1028
1030 const SCEV *BTC = SE.getBackedgeTakenCount(getLoop());
1031 if (isa<SCEVCouldNotCompute>(BTC))
1032 return BTC;
1033 // The loop reaches iteration BTC, so the value this recurrence computes there
1034 // is the value it had, and that did not wrap.
1035 return evaluateAtIteration(operands(), BTC, SE,
1038}
1039
1040//===----------------------------------------------------------------------===//
1041// SCEV Expression folder implementations
1042//===----------------------------------------------------------------------===//
1043
1044/// The SCEVCastSinkingRewriter takes a scalar evolution expression,
1045/// which computes a pointer-typed value, and rewrites the whole expression
1046/// tree so that *all* the computations are done on integers, and the only
1047/// pointer-typed operands in the expression are SCEVUnknown.
1048/// The CreatePtrCast callback is invoked to create the actual conversion
1049/// (ptrtoint or ptrtoaddr) at the SCEVUnknown leaves.
1051 : public SCEVRewriteVisitor<SCEVCastSinkingRewriter> {
1053 using ConversionFn = function_ref<const SCEV *(const SCEVUnknown *)>;
1054 Type *TargetTy;
1055 ConversionFn CreatePtrCast;
1056
1057public:
1059 ConversionFn CreatePtrCast)
1060 : Base(SE), TargetTy(TargetTy), CreatePtrCast(std::move(CreatePtrCast)) {}
1061
1062 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
1063 Type *TargetTy, ConversionFn CreatePtrCast) {
1064 SCEVCastSinkingRewriter Rewriter(SE, TargetTy, std::move(CreatePtrCast));
1065 return Rewriter.visit(Scev);
1066 }
1067
1068 const SCEV *visit(const SCEV *S) {
1069 Type *STy = S->getType();
1070 // If the expression is not pointer-typed, just keep it as-is.
1071 if (!STy->isPointerTy())
1072 return S;
1073 // Else, recursively sink the cast down into it.
1074 return Base::visit(S);
1075 }
1076
1077 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1078 // Preserve wrap flags on rewritten SCEVAddExpr, which the default
1079 // implementation drops.
1081 bool Changed = false;
1082 for (SCEVUse Op : Expr->operands()) {
1083 Operands.push_back(visit(Op.getPointer()));
1084 Changed |= Op.getPointer() != Operands.back();
1085 }
1086 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1087 }
1088
1089 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1090 assert(Expr->getType()->isPointerTy() &&
1091 "Should only reach pointer-typed SCEVUnknown's.");
1092 // Perform some basic constant folding. If the operand of the cast is a
1093 // null pointer, don't create a cast SCEV expression (that will be left
1094 // as-is), but produce a zero constant.
1096 return SE.getZero(TargetTy);
1097 return CreatePtrCast(Expr);
1098 }
1099};
1100
1102 assert(Op->getType()->isPointerTy() && "Op must be a pointer");
1103
1104 // Treat pointers with unstable representation conservatively, since the
1105 // address bits may change.
1106 if (DL.hasUnstableRepresentation(Op->getType()))
1107 return getCouldNotCompute();
1108
1109 Type *Ty = DL.getAddressType(Op->getType());
1110
1111 // Use the rewriter to sink the cast down to SCEVUnknown leaves.
1112 // The rewriter handles null pointer constant folding.
1114 Op, *this, Ty, [this, Ty](const SCEVUnknown *U) {
1117 ID.AddPointer(U);
1118 ID.AddPointer(Ty);
1120 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1121 return S;
1122 SCEV *S = new (SCEVAllocator)
1123 SCEVPtrToAddrExpr(ID.Intern(SCEVAllocator), U, Ty);
1124 UniqueSCEVs.insert(S, Token);
1125 S->computeAndSetCanonical(*this);
1126 registerUser(S, {U});
1127 return static_cast<const SCEV *>(S);
1128 });
1129 assert(IntOp->getType()->isIntegerTy() &&
1130 "We must have succeeded in sinking the cast, "
1131 "and ending up with an integer-typed expression!");
1132 return IntOp;
1133}
1134
1136 unsigned Depth) {
1137 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1138 "This is not a truncating conversion!");
1139 assert(isSCEVable(Ty) &&
1140 "This is not a conversion to a SCEVable type!");
1141 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1142 Ty = getEffectiveSCEVType(Ty);
1143
1146 ID.AddPointer(Op.getOpaqueValue());
1147 ID.AddPointer(Ty);
1149 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1150 return S;
1151
1152 // Fold if the operand is constant.
1153 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1154 return getConstant(
1155 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1156
1157 // trunc(trunc(x)) --> trunc(x)
1159 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1160
1161 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1163 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1164
1165 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1167 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1168
1169 if (Depth > MaxCastDepth) {
1170 SCEV *S =
1171 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1172 UniqueSCEVs.insert(S, Token);
1173 S->computeAndSetCanonical(*this);
1174 registerUser(S, Op);
1175 return S;
1176 }
1177
1178 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1179 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1180 // if after transforming we have at most one truncate, not counting truncates
1181 // that replace other casts.
1183 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1185 unsigned numTruncs = 0;
1186 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1187 ++i) {
1188 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1189 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1191 numTruncs++;
1192 Operands.push_back(S);
1193 }
1194 if (numTruncs < 2) {
1195 if (isa<SCEVAddExpr>(Op))
1196 return getAddExpr(Operands);
1197 if (isa<SCEVMulExpr>(Op))
1198 return getMulExpr(Operands);
1199 llvm_unreachable("Unexpected SCEV type for Op.");
1200 }
1201 // Although we checked in the beginning that ID is not in the cache, it is
1202 // possible that during recursion and different modification ID was inserted
1203 // into the cache. So if we find it, just return it.
1204 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1205 return S;
1206 }
1207
1208 // If the input value is a chrec scev, truncate the chrec's operands.
1209 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1211 for (const SCEV *Op : AddRec->operands())
1212 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1213 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1214 }
1215
1216 // Return zero if truncating to known zeros.
1217 uint32_t MinTrailingZeros = getMinTrailingZeros(Op);
1218 if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1219 return getZero(Ty);
1220
1221 // The cast wasn't folded; create an explicit cast node. We can reuse
1222 // the existing insert position since if we get here, we won't have
1223 // made any changes which would invalidate it.
1224 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1225 Op, Ty);
1226 UniqueSCEVs.insert(S, Token);
1227 S->computeAndSetCanonical(*this);
1228 registerUser(S, Op);
1229 return S;
1230}
1231
1232// Get the limit of a recurrence such that incrementing by Step cannot cause
1233// signed overflow as long as the value of the recurrence within the
1234// loop does not exceed this limit before incrementing.
1235static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1236 ICmpInst::Predicate *Pred,
1237 ScalarEvolution *SE) {
1238 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1239 if (SE->isKnownPositive(Step)) {
1240 *Pred = ICmpInst::ICMP_SLT;
1242 SE->getSignedRangeMax(Step));
1243 }
1244 if (SE->isKnownNegative(Step)) {
1245 *Pred = ICmpInst::ICMP_SGT;
1247 SE->getSignedRangeMin(Step));
1248 }
1249 return nullptr;
1250}
1251
1252// Get the limit of a recurrence such that incrementing by Step cannot cause
1253// unsigned overflow as long as the value of the recurrence within the loop does
1254// not exceed this limit before incrementing.
1256 ICmpInst::Predicate *Pred,
1257 ScalarEvolution *SE) {
1258 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1259 *Pred = ICmpInst::ICMP_ULT;
1260
1262 SE->getUnsignedRangeMax(Step));
1263}
1264
1265namespace {
1266
1267struct ExtendOpTraitsBase {
1268 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(SCEVUse, Type *,
1269 unsigned);
1270};
1271
1272// Used to make code generic over signed and unsigned overflow.
1273template <typename ExtendOp> struct ExtendOpTraits {
1274 // Members present:
1275 //
1276 // static const SCEV::NoWrapFlags WrapType;
1277 //
1278 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1279 //
1280 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1281 // ICmpInst::Predicate *Pred,
1282 // ScalarEvolution *SE);
1283};
1284
1285template <>
1286struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1287 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1288
1289 static const GetExtendExprTy GetExtendExpr;
1290
1291 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1292 ICmpInst::Predicate *Pred,
1293 ScalarEvolution *SE) {
1294 return getSignedOverflowLimitForStep(Step, Pred, SE);
1295 }
1296};
1297
1298const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1300
1301template <>
1302struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1303 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1304
1305 static const GetExtendExprTy GetExtendExpr;
1306
1307 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1308 ICmpInst::Predicate *Pred,
1309 ScalarEvolution *SE) {
1310 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1311 }
1312};
1313
1314const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1316
1317} // end anonymous namespace
1318
1319// The recurrence AR has been shown to have no signed/unsigned wrap or something
1320// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1321// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1322// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1323// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1324// expression "Step + sext/zext(PreIncAR)" is congruent with
1325// "sext/zext(PostIncAR)"
1326template <typename ExtendOpTy>
1328 ScalarEvolution *SE, unsigned Depth) {
1329 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1330 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1331
1332 const Loop *L = AR->getLoop();
1333 const SCEV *Start = AR->getStart();
1334 const SCEV *Step = AR->getStepRecurrence(*SE);
1335
1336 // Check for a simple looking step prior to loop entry.
1337 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1338 if (!SA)
1339 return nullptr;
1340
1341 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1342 // subtraction is expensive. For this purpose, perform a quick and dirty
1343 // difference, by checking for Step in the operand list. Note, that
1344 // SA might have repeated ops, like %a + %a + ..., so only remove one.
1345 SmallVector<SCEVUse, 4> DiffOps(SA->operands());
1346 for (auto It = DiffOps.begin(); It != DiffOps.end(); ++It)
1347 if (*It == Step) {
1348 DiffOps.erase(It);
1349 break;
1350 }
1351
1352 if (DiffOps.size() == SA->getNumOperands())
1353 return nullptr;
1354
1355 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1356 // `Step`:
1357
1358 // 1. NSW/NUW flags on the step increment.
1359 auto PreStartFlags =
1361 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1363 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1364
1365 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1366 // "S+X does not sign/unsign-overflow".
1367 //
1368
1369 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1370 if (PreAR && any(PreAR->getNoWrapFlags(WrapType)) &&
1371 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1372 return PreStart;
1373
1374 // 2. Direct overflow check on the step operation's expression.
1375 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1376 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1377 const SCEV *OperandExtendedStart =
1378 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1379 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1380 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1381 if (PreAR && any(AR->getNoWrapFlags(WrapType))) {
1382 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1383 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1384 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1385 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1386 }
1387 return PreStart;
1388 }
1389
1390 // 3. Loop precondition.
1392 const SCEV *OverflowLimit =
1393 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1394
1395 if (OverflowLimit &&
1396 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1397 return PreStart;
1398
1399 return nullptr;
1400}
1401
1402// Get the normalized zero or sign extended expression for this AddRec's Start.
1403template <typename ExtendOpTy>
1404static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1405 ScalarEvolution *SE,
1406 unsigned Depth) {
1407 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1408
1409 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, SE, Depth);
1410 if (!PreStart)
1411 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1412
1413 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1414 Depth),
1415 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1416}
1417
1418// Try to prove away overflow by looking at "nearby" add recurrences. A
1419// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1420// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1421//
1422// Formally:
1423//
1424// {S,+,X} == {S-T,+,X} + T
1425// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1426//
1427// If ({S-T,+,X} + T) does not overflow ... (1)
1428//
1429// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1430//
1431// If {S-T,+,X} does not overflow ... (2)
1432//
1433// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1434// == {Ext(S-T)+Ext(T),+,Ext(X)}
1435//
1436// If (S-T)+T does not overflow ... (3)
1437//
1438// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1439// == {Ext(S),+,Ext(X)} == LHS
1440//
1441// Thus, if (1), (2) and (3) are true for some T, then
1442// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1443//
1444// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1445// does not overflow" restricted to the 0th iteration. Therefore we only need
1446// to check for (1) and (2).
1447//
1448// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1449// is `Delta` (defined below).
1450template <typename ExtendOpTy>
1451bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1452 const SCEV *Step,
1453 const Loop *L) {
1454 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1455
1456 // We restrict `Start` to a constant to prevent SCEV from spending too much
1457 // time here. It is correct (but more expensive) to continue with a
1458 // non-constant `Start` and do a general SCEV subtraction to compute
1459 // `PreStart` below.
1460 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1461 if (!StartC)
1462 return false;
1463
1464 APInt StartAI = StartC->getAPInt();
1465
1466 for (unsigned Delta : {-2, -1, 1, 2}) {
1467 const SCEV *PreStart = getConstant(StartAI - Delta);
1468
1469 FoldingSetNodeID ID;
1470 ID.AddInteger(scAddRecExpr);
1471 ID.AddPointer(PreStart);
1472 ID.AddPointer(Step);
1473 ID.AddPointer(L);
1474 FoldingSetInsertToken Token;
1475 const auto *PreAR =
1476 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.lookup(ID, Token));
1477
1478 // Give up if we don't already have the add recurrence we need because
1479 // actually constructing an add recurrence is relatively expensive.
1480 if (PreAR && any(PreAR->getNoWrapFlags(WrapType))) { // proves (2)
1481 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1483 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1484 DeltaS, &Pred, this);
1485 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1486 return true;
1487 }
1488 }
1489
1490 return false;
1491}
1492
1493// Finds an integer D for an expression (C + x + y + ...) such that the top
1494// level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1495// unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1496// maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1497// the (C + x + y + ...) expression is \p WholeAddExpr.
1499 const SCEVConstant *ConstantTerm,
1500 const SCEVAddExpr *WholeAddExpr) {
1501 const APInt &C = ConstantTerm->getAPInt();
1502 const unsigned BitWidth = C.getBitWidth();
1503 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1504 uint32_t TZ = BitWidth;
1505 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1506 TZ = std::min(TZ, SE.getMinTrailingZeros(WholeAddExpr->getOperand(I)));
1507 if (TZ) {
1508 // Set D to be as many least significant bits of C as possible while still
1509 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1510 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1511 }
1512 return APInt(BitWidth, 0);
1513}
1514
1515// Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1516// level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1517// number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1518// ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1520 const APInt &ConstantStart,
1521 const SCEV *Step) {
1522 const unsigned BitWidth = ConstantStart.getBitWidth();
1523 const uint32_t TZ = SE.getMinTrailingZeros(Step);
1524 if (TZ)
1525 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1526 : ConstantStart;
1527 return APInt(BitWidth, 0);
1528}
1529
1531 const ScalarEvolution::FoldID &ID, const SCEV *S,
1534 &FoldCacheUser) {
1535 auto I = FoldCache.insert({ID, S});
1536 if (!I.second) {
1537 // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1538 // entry.
1539 auto &UserIDs = FoldCacheUser[I.first->second];
1540 assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
1541 for (unsigned I = 0; I != UserIDs.size(); ++I)
1542 if (UserIDs[I] == ID) {
1543 std::swap(UserIDs[I], UserIDs.back());
1544 break;
1545 }
1546 UserIDs.pop_back();
1547 I.first->second = S;
1548 }
1549 FoldCacheUser[S].push_back(ID);
1550}
1551
1553 unsigned Depth) {
1554 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1555 "This is not an extending conversion!");
1556 assert(isSCEVable(Ty) &&
1557 "This is not a conversion to a SCEVable type!");
1558 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1559 Ty = getEffectiveSCEVType(Ty);
1560
1561 FoldID ID(scZeroExtend, Op, Ty);
1562 if (const SCEV *S = FoldCache.lookup(ID))
1563 return S;
1564
1565 const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1567 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1568 return S;
1569}
1570
1572 unsigned Depth) {
1573 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1574 "This is not an extending conversion!");
1575 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1576 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1577
1578 // Fold if the operand is constant.
1579 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1580 return getConstant(SC->getAPInt().zext(getTypeSizeInBits(Ty)));
1581
1582 // zext(zext(x)) --> zext(x)
1584 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1585
1586 // If the operand is an affine AddRec with the no-unsigned-wrap flag, the
1587 // zero-extension distributes over the recurrence.
1588 const SCEV *Start, *Step;
1589 const Loop *L;
1590 if (Depth <= MaxCastDepth &&
1591 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1592 const auto *AR = cast<SCEVAddRecExpr>(Op);
1593 if (AR->hasNoUnsignedWrap()) {
1594 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1595 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1596 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1597 }
1598 }
1599
1600 // Before doing any expensive analysis, check to see if we've already
1601 // computed a SCEV for this Op and Ty.
1604 ID.AddPointer(Op.getOpaqueValue());
1605 ID.AddPointer(Ty);
1607 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1608 return S;
1609 if (Depth > MaxCastDepth) {
1610 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1611 Op, Ty);
1612 UniqueSCEVs.insert(S, Token);
1613 S->computeAndSetCanonical(*this);
1614 registerUser(S, Op);
1615 return S;
1616 }
1617
1618 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1620 // It's possible the bits taken off by the truncate were all zero bits. If
1621 // so, we should be able to simplify this further.
1622 const SCEV *X = ST->getOperand();
1624 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1625 unsigned NewBits = getTypeSizeInBits(Ty);
1626 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1627 CR.zextOrTrunc(NewBits)))
1628 return getTruncateOrZeroExtend(X, Ty, Depth);
1629 }
1630
1631 // If the input value is a chrec scev, and we can prove that the value
1632 // did not overflow the old, smaller, value, we can zero extend all of the
1633 // operands (often constants). This allows analysis of something like
1634 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1635 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1636 const auto *AR = cast<SCEVAddRecExpr>(Op);
1637 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1638
1639 // The no-unsigned-wrap case is handled before the uniquing lookup above.
1640
1641 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1642 // Note that this serves two purposes: It filters out loops that are
1643 // simply not analyzable, and it covers the case where this code is
1644 // being called from within backedge-taken count analysis, such that
1645 // attempting to ask for the backedge-taken count would likely result
1646 // in infinite recursion. In the later case, the analysis code will
1647 // cope with a conservative value, and it will take care to purge
1648 // that value once it has finished.
1649 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1650 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1651 // Manually compute the final value for AR, checking for overflow.
1652
1653 // Check whether the backedge-taken count can be losslessly casted to
1654 // the addrec's type. The count is always unsigned.
1655 const SCEV *CastedMaxBECount =
1656 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1657 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1658 CastedMaxBECount, MaxBECount->getType(), Depth);
1659 if (MaxBECount == RecastedMaxBECount) {
1660 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1661 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1662 const SCEV *ZMul =
1663 getMulExpr(CastedMaxBECount, Step, SCEV::FlagAnyWrap, Depth + 1);
1664 const SCEV *ZAdd = getZeroExtendExpr(
1665 getAddExpr(Start, ZMul, SCEV::FlagAnyWrap, Depth + 1), WideTy,
1666 Depth + 1);
1667 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1668 const SCEV *WideMaxBECount =
1669 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1670 const SCEV *OperandExtendedAdd =
1671 getAddExpr(WideStart,
1672 getMulExpr(WideMaxBECount,
1673 getZeroExtendExpr(Step, WideTy, Depth + 1),
1676 if (ZAdd == OperandExtendedAdd) {
1677 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1678 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1679 // Return the expression with the addrec on the outside.
1680 Start =
1682 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1683 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1684 }
1685 // Similar to above, only this time treat the step value as signed.
1686 // This covers loops that count down.
1687 OperandExtendedAdd =
1688 getAddExpr(WideStart,
1689 getMulExpr(WideMaxBECount,
1690 getSignExtendExpr(Step, WideTy, Depth + 1),
1693 if (ZAdd == OperandExtendedAdd) {
1694 // Cache knowledge of AR NW, which is propagated to this AddRec.
1695 // Negative step causes unsigned wrap, but it still can't self-wrap.
1696 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1697 // Return the expression with the addrec on the outside.
1698 Start =
1700 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1701 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1702 }
1703 }
1704 }
1705
1706 // Normally, in the cases we can prove no-overflow via a
1707 // backedge guarding condition, we can also compute a backedge
1708 // taken count for the loop. The exceptions are assumptions and
1709 // guards present in the loop -- SCEV is not great at exploiting
1710 // these to compute max backedge taken counts, but can still use
1711 // these to prove lack of overflow. Use this fact to avoid
1712 // doing extra work that may not pay off.
1713 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1714 !AC.assumptions().empty()) {
1715
1716 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1717 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1718 if (AR->hasNoUnsignedWrap()) {
1719 // Same as nuw case above - duplicated here to avoid a compile time
1720 // issue. It's not clear that the order of checks does matter, but
1721 // it's one of two issue possible causes for a change which was
1722 // reverted. Be conservative for the moment.
1723 Start =
1725 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1726 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1727 }
1728
1729 // For a negative step, we can extend the operands iff doing so only
1730 // traverses values in the range zext([0,UINT_MAX]).
1731 if (isKnownNegative(Step)) {
1732 const SCEV *N =
1736 // Cache knowledge of AR NW, which is propagated to this
1737 // AddRec. Negative step causes unsigned wrap, but it
1738 // still can't self-wrap.
1739 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1740 // Return the expression with the addrec on the outside.
1741 Start =
1743 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1744 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1745 }
1746 }
1747 }
1748
1749 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1750 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1751 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1752 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1753 const APInt &C = SC->getAPInt();
1754 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1755 if (D != 0) {
1756 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1757 const SCEV *SResidual =
1758 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1759 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1760 return getAddExpr(SZExtD, SZExtR, SCEV::FlagNSW | SCEV::FlagNUW,
1761 Depth + 1);
1762 }
1763 }
1764
1765 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1766 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1767 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1768 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1769 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1770 }
1771 }
1772
1773 // zext(A % B) --> zext(A) % zext(B)
1774 {
1775 const SCEV *LHS;
1776 const SCEV *RHS;
1777 if (match(Op, m_scev_URem(m_SCEV(LHS), m_SCEV(RHS), *this)))
1778 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1779 getZeroExtendExpr(RHS, Ty, Depth + 1));
1780 }
1781
1782 // zext(A / B) --> zext(A) / zext(B).
1783 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1784 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1785 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1786
1787 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1788 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1789 if (SA->hasNoUnsignedWrap()) {
1790 // If the addition does not unsign overflow then we can, by definition,
1791 // commute the zero extension with the addition operation.
1793 for (SCEVUse Op : SA->operands())
1794 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1795 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1796 }
1797
1798 const APInt *C, *C2;
1799 // zext (C + A)<nsw> -> (sext(C) + sext(A))<nsw> if zext (C + A)<nsw> >=s 0.
1800 // Currently the non-negative check is done manually, as isKnownNonNegative
1801 // is too expensive.
1802 if (SA->hasNoSignedWrap() &&
1804 m_scev_SMax(m_scev_APInt(C2), m_SCEV()))) &&
1805 C->isNegative() && !C->isMinSignedValue() && C2->sge(C->abs())) {
1806 assert(isKnownNonNegative(SA) && "incorrectly determined non-negative");
1807 return getAddExpr(getSignExtendExpr(SA->getOperand(0), Ty, Depth + 1),
1808 getSignExtendExpr(SA->getOperand(1), Ty, Depth + 1),
1809 SCEV::FlagNSW, Depth + 1);
1810 }
1811
1812 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1813 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1814 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1815 //
1816 // Often address arithmetics contain expressions like
1817 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1818 // This transformation is useful while proving that such expressions are
1819 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1820 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1821 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1822 if (D != 0) {
1823 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1824 const SCEV *SResidual =
1826 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1827 return getAddExpr(SZExtD, SZExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1828 Depth + 1);
1829 }
1830 }
1831 }
1832
1833 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1834 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1835 if (SM->hasNoUnsignedWrap()) {
1836 // If the multiply does not unsign overflow then we can, by definition,
1837 // commute the zero extension with the multiply operation.
1839 for (SCEVUse Op : SM->operands())
1840 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1841 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1842 }
1843
1844 // zext(2^K * (trunc X to iN)) to iM ->
1845 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1846 //
1847 // Proof:
1848 //
1849 // zext(2^K * (trunc X to iN)) to iM
1850 // = zext((trunc X to iN) << K) to iM
1851 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1852 // (because shl removes the top K bits)
1853 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1854 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1855 //
1856 const APInt *C;
1857 const SCEV *TruncRHS;
1858 if (match(SM,
1859 m_scev_Mul(m_scev_APInt(C), m_scev_Trunc(m_SCEV(TruncRHS)))) &&
1860 C->isPowerOf2()) {
1861 int NewTruncBits =
1862 getTypeSizeInBits(SM->getOperand(1)->getType()) - C->logBase2();
1863 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1864 return getMulExpr(
1865 getZeroExtendExpr(SM->getOperand(0), Ty),
1866 getZeroExtendExpr(getTruncateExpr(TruncRHS, NewTruncTy), Ty),
1867 SCEV::FlagNUW, Depth + 1);
1868 }
1869 }
1870
1871 // zext(umin(x, y)) -> umin(zext(x), zext(y))
1872 // zext(umax(x, y)) -> umax(zext(x), zext(y))
1876 for (SCEVUse Operand : MinMax->operands())
1877 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1879 return getUMinExpr(Operands);
1880 return getUMaxExpr(Operands);
1881 }
1882
1883 // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
1885 assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!");
1887 for (SCEVUse Operand : MinMax->operands())
1888 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1889 return getUMinExpr(Operands, /*Sequential*/ true);
1890 }
1891
1892 // The cast wasn't folded; create an explicit cast node.
1893 // Recompute the insert position, as it may have been invalidated.
1894 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1895 return S;
1896 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1897 Op, Ty);
1898 UniqueSCEVs.insert(S, Token);
1899 S->computeAndSetCanonical(*this);
1900 registerUser(S, Op);
1901 return S;
1902}
1903
1905 unsigned Depth) {
1906 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1907 "This is not an extending conversion!");
1908 assert(isSCEVable(Ty) &&
1909 "This is not a conversion to a SCEVable type!");
1910 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1911 Ty = getEffectiveSCEVType(Ty);
1912
1913 FoldID ID(scSignExtend, Op, Ty);
1914 if (const SCEV *S = FoldCache.lookup(ID))
1915 return S;
1916
1917 const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
1919 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1920 return S;
1921}
1922
1924 unsigned Depth) {
1925 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1926 "This is not an extending conversion!");
1927 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1928 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1929 Ty = getEffectiveSCEVType(Ty);
1930
1931 // Fold if the operand is constant.
1932 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1933 return getConstant(SC->getAPInt().sext(getTypeSizeInBits(Ty)));
1934
1935 // sext(sext(x)) --> sext(x)
1937 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1938
1939 // sext(zext(x)) --> zext(x)
1941 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1942
1943 // If the operand is an affine AddRec with the no-signed-wrap flag, the
1944 // sign-extension distributes over the recurrence.
1945 const SCEV *Start, *Step;
1946 const Loop *L;
1947 if (Depth <= MaxCastDepth &&
1948 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1949 const auto *AR = cast<SCEVAddRecExpr>(Op);
1950 if (AR->hasNoSignedWrap()) {
1951 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
1952 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1953 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1954 }
1955 }
1956
1957 // Before doing any expensive analysis, check to see if we've already
1958 // computed a SCEV for this Op and Ty.
1961 ID.AddPointer(Op.getOpaqueValue());
1962 ID.AddPointer(Ty);
1964 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1965 return S;
1966 // Limit recursion depth.
1967 if (Depth > MaxCastDepth) {
1968 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1969 Op, Ty);
1970 UniqueSCEVs.insert(S, Token);
1971 S->computeAndSetCanonical(*this);
1972 registerUser(S, Op);
1973 return S;
1974 }
1975
1976 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1978 // It's possible the bits taken off by the truncate were all sign bits. If
1979 // so, we should be able to simplify this further.
1980 const SCEV *X = ST->getOperand();
1982 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1983 unsigned NewBits = getTypeSizeInBits(Ty);
1984 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1985 CR.sextOrTrunc(NewBits)))
1986 return getTruncateOrSignExtend(X, Ty, Depth);
1987 }
1988
1989 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1990 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1991 if (SA->hasNoSignedWrap()) {
1992 // If the addition does not sign overflow then we can, by definition,
1993 // commute the sign extension with the addition operation.
1995 for (SCEVUse Op : SA->operands())
1996 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1997 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1998 }
1999
2000 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
2001 // if D + (C - D + x + y + ...) could be proven to not signed wrap
2002 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
2003 //
2004 // For instance, this will bring two seemingly different expressions:
2005 // 1 + sext(5 + 20 * %x + 24 * %y) and
2006 // sext(6 + 20 * %x + 24 * %y)
2007 // to the same form:
2008 // 2 + sext(4 + 20 * %x + 24 * %y)
2009 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
2010 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
2011 if (D != 0) {
2012 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2013 const SCEV *SResidual =
2015 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2016 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
2017 Depth + 1);
2018 }
2019 }
2020 }
2021 // If the input value is a chrec scev, and we can prove that the value
2022 // did not overflow the old, smaller, value, we can sign extend all of the
2023 // operands (often constants). This allows analysis of something like
2024 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
2025 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
2026 const auto *AR = cast<SCEVAddRecExpr>(Op);
2027 unsigned BitWidth = getTypeSizeInBits(AR->getType());
2028
2029 // The no-signed-wrap case is handled before the uniquing lookup above.
2030
2031 // Check whether the backedge-taken count is SCEVCouldNotCompute.
2032 // Note that this serves two purposes: It filters out loops that are
2033 // simply not analyzable, and it covers the case where this code is
2034 // being called from within backedge-taken count analysis, such that
2035 // attempting to ask for the backedge-taken count would likely result
2036 // in infinite recursion. In the later case, the analysis code will
2037 // cope with a conservative value, and it will take care to purge
2038 // that value once it has finished.
2039 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2040 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2041 // Manually compute the final value for AR, checking for
2042 // overflow.
2043
2044 // Check whether the backedge-taken count can be losslessly casted to
2045 // the addrec's type. The count is always unsigned.
2046 const SCEV *CastedMaxBECount =
2047 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2048 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2049 CastedMaxBECount, MaxBECount->getType(), Depth);
2050 if (MaxBECount == RecastedMaxBECount) {
2051 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2052 // Check whether Start+Step*MaxBECount has no signed overflow.
2053 const SCEV *SMul =
2054 getMulExpr(CastedMaxBECount, Step, SCEV::FlagAnyWrap, Depth + 1);
2055 const SCEV *SAdd = getSignExtendExpr(
2056 getAddExpr(Start, SMul, SCEV::FlagAnyWrap, Depth + 1), WideTy,
2057 Depth + 1);
2058 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2059 const SCEV *WideMaxBECount =
2060 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2061 const SCEV *OperandExtendedAdd =
2062 getAddExpr(WideStart,
2063 getMulExpr(WideMaxBECount,
2064 getSignExtendExpr(Step, WideTy, Depth + 1),
2067 if (SAdd == OperandExtendedAdd) {
2068 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2069 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2070 // Return the expression with the addrec on the outside.
2071 Start =
2073 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2074 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2075 }
2076 // Similar to above, only this time treat the step value as unsigned.
2077 // This covers loops that count up with an unsigned step.
2078 OperandExtendedAdd =
2079 getAddExpr(WideStart,
2080 getMulExpr(WideMaxBECount,
2081 getZeroExtendExpr(Step, WideTy, Depth + 1),
2084 if (SAdd == OperandExtendedAdd) {
2085 // If AR wraps around then
2086 //
2087 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2088 // => SAdd != OperandExtendedAdd
2089 //
2090 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2091 // (SAdd == OperandExtendedAdd => AR is NW)
2092
2093 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2094
2095 // Return the expression with the addrec on the outside.
2096 Start =
2098 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
2099 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2100 }
2101 }
2102 }
2103
2104 auto NewFlags = proveNoSignedWrapViaInduction(AR);
2105 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2106 if (AR->hasNoSignedWrap()) {
2107 // Same as nsw case above - duplicated here to avoid a compile time
2108 // issue. It's not clear that the order of checks does matter, but
2109 // it's one of two issue possible causes for a change which was
2110 // reverted. Be conservative for the moment.
2111 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2112 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2113 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2114 }
2115
2116 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2117 // if D + (C - D + Step * n) could be proven to not signed wrap
2118 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2119 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2120 const APInt &C = SC->getAPInt();
2121 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2122 if (D != 0) {
2123 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2124 const SCEV *SResidual =
2125 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2126 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2127 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
2128 Depth + 1);
2129 }
2130 }
2131
2132 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2133 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2134 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2135 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2136 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2137 }
2138 }
2139
2140 // If the input value is provably positive and we could not simplify
2141 // away the sext build a zext instead.
2143 return getZeroExtendExpr(Op, Ty, Depth + 1);
2144
2145 // sext(smin(x, y)) -> smin(sext(x), sext(y))
2146 // sext(smax(x, y)) -> smax(sext(x), sext(y))
2150 for (SCEVUse Operand : MinMax->operands())
2151 Operands.push_back(getSignExtendExpr(Operand, Ty));
2153 return getSMinExpr(Operands);
2154 return getSMaxExpr(Operands);
2155 }
2156
2157 // The cast wasn't folded; create an explicit cast node.
2158 // Recompute the insert position, as it may have been invalidated.
2159 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
2160 return S;
2161 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2162 Op, Ty);
2163 UniqueSCEVs.insert(S, Token);
2164 S->computeAndSetCanonical(*this);
2165 registerUser(S, Op);
2166 return S;
2167}
2168
2170 switch (Kind) {
2171 case scTruncate:
2172 return getTruncateExpr(Op, Ty);
2173 case scZeroExtend:
2174 return getZeroExtendExpr(Op, Ty);
2175 case scSignExtend:
2176 return getSignExtendExpr(Op, Ty);
2177 case scPtrToAddr: {
2178 const SCEV *Expr = getPtrToAddrExpr(Op);
2179 assert(Expr->getType() == Ty && "requested type must match");
2180 return Expr;
2181 }
2182 default:
2183 llvm_unreachable("Not a SCEV cast expression!");
2184 }
2185}
2186
2187/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2188/// unspecified bits out to the given type.
2190 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2191 "This is not an extending conversion!");
2192 assert(isSCEVable(Ty) &&
2193 "This is not a conversion to a SCEVable type!");
2194 Ty = getEffectiveSCEVType(Ty);
2195
2196 // Sign-extend negative constants.
2197 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2198 if (SC->getAPInt().isNegative())
2199 return getSignExtendExpr(Op, Ty);
2200
2201 // Peel off a truncate cast.
2203 const SCEV *NewOp = T->getOperand();
2204 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2205 return getAnyExtendExpr(NewOp, Ty);
2206 return getTruncateOrNoop(NewOp, Ty);
2207 }
2208
2209 // Next try a zext cast. If the cast is folded, use it.
2210 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2211 if (!isa<SCEVZeroExtendExpr>(ZExt))
2212 return ZExt;
2213
2214 // Next try a sext cast. If the cast is folded, use it.
2215 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2216 if (!isa<SCEVSignExtendExpr>(SExt))
2217 return SExt;
2218
2219 // Force the cast to be folded into the operands of an addrec.
2220 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2222 for (const SCEV *Op : AR->operands())
2223 Ops.push_back(getAnyExtendExpr(Op, Ty));
2224 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2225 }
2226
2227 // If the expression is obviously signed, use the sext cast value.
2228 if (isa<SCEVSMaxExpr>(Op))
2229 return SExt;
2230
2231 // Absent any other information, use the zext cast value.
2232 return ZExt;
2233}
2234
2235/// Process the given Ops list, which is a list of operands to be added under
2236/// the given scale, update the given map. This is a helper function for
2237/// getAddRecExpr. As an example of what it does, given a sequence of operands
2238/// that would form an add expression like this:
2239///
2240/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2241///
2242/// where A and B are constants, update the map with these values:
2243///
2244/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2245///
2246/// and add 13 + A*B*29 to AccumulatedConstant.
2247/// This will allow getAddRecExpr to produce this:
2248///
2249/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2250///
2251/// This form often exposes folding opportunities that are hidden in
2252/// the original operand list.
2253///
2254/// Return true iff it appears that any interesting folding opportunities
2255/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2256/// the common case where no interesting opportunities are present, and
2257/// is also used as a check to avoid infinite recursion.
2260 APInt &AccumulatedConstant,
2262 const APInt &Scale,
2263 ScalarEvolution &SE) {
2264 bool Interesting = false;
2265
2266 // Iterate over the add operands. They are sorted, with constants first.
2267 unsigned i = 0;
2268 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2269 ++i;
2270 // Pull a buried constant out to the outside.
2271 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2272 Interesting = true;
2273 AccumulatedConstant += Scale * C->getAPInt();
2274 }
2275
2276 // Next comes everything else. We're especially interested in multiplies
2277 // here, but they're in the middle, so just visit the rest with one loop.
2278 for (; i != Ops.size(); ++i) {
2280 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2281 APInt NewScale =
2282 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2283 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2284 // A multiplication of a constant with another add; recurse.
2285 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2286 Interesting |= CollectAddOperandsWithScales(
2287 M, NewOps, AccumulatedConstant, Add->operands(), NewScale, SE);
2288 } else {
2289 // A multiplication of a constant with some other value. Update
2290 // the map.
2291 SmallVector<SCEVUse, 4> MulOps(drop_begin(Mul->operands()));
2292 const SCEV *Key = SE.getMulExpr(MulOps);
2293 auto Pair = M.insert({Key, NewScale});
2294 if (Pair.second) {
2295 NewOps.push_back(Pair.first->first);
2296 } else {
2297 Pair.first->second += NewScale;
2298 // The map already had an entry for this value, which may indicate
2299 // a folding opportunity.
2300 Interesting = true;
2301 }
2302 }
2303 } else {
2304 // An ordinary operand. Update the map.
2305 auto Pair = M.insert({Ops[i], Scale});
2306 if (Pair.second) {
2307 NewOps.push_back(Pair.first->first);
2308 } else {
2309 Pair.first->second += Scale;
2310 // The map already had an entry for this value, which may indicate
2311 // a folding opportunity.
2312 Interesting = true;
2313 }
2314 }
2315 }
2316
2317 return Interesting;
2318}
2319
2321 const SCEV *LHS, const SCEV *RHS,
2322 const Instruction *CtxI) {
2324 unsigned);
2325 switch (BinOp) {
2326 default:
2327 llvm_unreachable("Unsupported binary op");
2328 case Instruction::Add:
2330 break;
2331 case Instruction::Sub:
2333 break;
2334 case Instruction::Mul:
2336 break;
2337 }
2338
2339 const SCEV *(ScalarEvolution::*Extension)(SCEVUse, Type *, unsigned) =
2342
2343 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2344 auto *NarrowTy = cast<IntegerType>(LHS->getType());
2345 auto *WideTy =
2346 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2347
2348 const SCEV *A = (this->*Extension)(
2349 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2350 const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2351 const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2352 const SCEV *B = (this->*Operation)(LHSB, RHSB, SCEV::FlagAnyWrap, 0);
2353 if (A == B)
2354 return true;
2355 // Can we use context to prove the fact we need?
2356 if (!CtxI)
2357 return false;
2358 // TODO: Support mul.
2359 if (BinOp == Instruction::Mul)
2360 return false;
2361 auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2362 // TODO: Lift this limitation.
2363 if (!RHSC)
2364 return false;
2365 APInt C = RHSC->getAPInt();
2366 unsigned NumBits = C.getBitWidth();
2367 bool IsSub = (BinOp == Instruction::Sub);
2368 bool IsNegativeConst = (Signed && C.isNegative());
2369 // Compute the direction and magnitude by which we need to check overflow.
2370 bool OverflowDown = IsSub ^ IsNegativeConst;
2371 APInt Magnitude = C;
2372 if (IsNegativeConst) {
2373 if (C == APInt::getSignedMinValue(NumBits))
2374 // TODO: SINT_MIN on inversion gives the same negative value, we don't
2375 // want to deal with that.
2376 return false;
2377 Magnitude = -C;
2378 }
2379
2381 if (OverflowDown) {
2382 // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2383 APInt Min = Signed ? APInt::getSignedMinValue(NumBits)
2384 : APInt::getMinValue(NumBits);
2385 APInt Limit = Min + Magnitude;
2386 return isKnownPredicateAt(Pred, getConstant(Limit), LHS, CtxI);
2387 } else {
2388 // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2389 APInt Max = Signed ? APInt::getSignedMaxValue(NumBits)
2390 : APInt::getMaxValue(NumBits);
2391 APInt Limit = Max - Magnitude;
2392 return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2393 }
2394}
2395
2396std::optional<SCEV::NoWrapFlags>
2398 const OverflowingBinaryOperator *OBO) {
2399 // It cannot be done any better.
2400 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2401 return std::nullopt;
2402
2403 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2404
2405 if (OBO->hasNoUnsignedWrap())
2407 if (OBO->hasNoSignedWrap())
2409
2410 bool Deduced = false;
2411
2413 const SCEV *LHS = getSCEV(OBO->getOperand(0));
2414 const SCEV *RHS = getSCEV(OBO->getOperand(1));
2415
2416 bool CanUseNSW = true;
2417 const APInt *ShiftAmt;
2418 // Treat `shl %a, C` as `mul %a, 1 << C`.
2419 if (match(OBO, m_Shl(m_Value(), m_APInt(ShiftAmt)))) {
2420 unsigned BitWidth = ShiftAmt->getBitWidth();
2421 if (ShiftAmt->uge(BitWidth))
2422 return std::nullopt;
2423 // NSW only transfers if the shift amount is < BitWidth - 1, as INT_MIN * -1
2424 // overflows.
2425 CanUseNSW = ShiftAmt->ult(BitWidth - 1);
2426 Opcode = Instruction::Mul;
2428 } else if (Opcode != Instruction::Add && Opcode != Instruction::Sub &&
2429 Opcode != Instruction::Mul) {
2430 return std::nullopt;
2431 }
2432
2433 const Instruction *CtxI =
2435 if (!OBO->hasNoUnsignedWrap() &&
2436 willNotOverflow(Opcode, /* Signed */ false, LHS, RHS, CtxI)) {
2438 Deduced = true;
2439 }
2440
2441 if (CanUseNSW && !OBO->hasNoSignedWrap() &&
2442 willNotOverflow(Opcode, /* Signed */ true, LHS, RHS, CtxI)) {
2444 Deduced = true;
2445 }
2446
2447 if (Deduced)
2448 return Flags;
2449 return std::nullopt;
2450}
2451
2452// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2453// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2454// can't-overflow flags for the operation if possible.
2458 SCEV::NoWrapFlags Flags) {
2459 using namespace std::placeholders;
2460
2461 using OBO = OverflowingBinaryOperator;
2462
2463 bool CanAnalyze =
2465 (void)CanAnalyze;
2466 assert(CanAnalyze && "don't call from other places!");
2467
2468 SCEV::NoWrapFlags SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2469 SCEV::NoWrapFlags SignOrUnsignWrap =
2470 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2471
2472 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2473 auto IsKnownNonNegative = [&](SCEVUse U) {
2474 return SE->isKnownNonNegative(U);
2475 };
2476
2477 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2478 Flags = ScalarEvolution::setFlags(Flags, SignOrUnsignMask);
2479
2480 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2481
2482 if (SignOrUnsignWrap != SignOrUnsignMask &&
2483 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2484 isa<SCEVConstant>(Ops[0])) {
2485
2486 auto Opcode = [&] {
2487 switch (Type) {
2488 case scAddExpr:
2489 return Instruction::Add;
2490 case scMulExpr:
2491 return Instruction::Mul;
2492 default:
2493 llvm_unreachable("Unexpected SCEV op.");
2494 }
2495 }();
2496
2497 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2498
2499 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2500 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2502 Opcode, C, OBO::NoSignedWrap);
2503 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2505 }
2506
2507 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2508 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2510 Opcode, C, OBO::NoUnsignedWrap);
2511 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2513 }
2514 }
2515
2516 // <0,+,nonnegative><nw> is also nuw
2517 // TODO: Add corresponding nsw case
2519 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2520 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2522
2523 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2525 Ops.size() == 2) {
2526 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2527 if (UDiv->getOperand(1) == Ops[1])
2529 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2530 if (UDiv->getOperand(1) == Ops[0])
2532 }
2533
2534 return Flags;
2535}
2536
2538 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2539}
2540
2541/// Get a canonical add expression, or something simpler if possible.
2543 SCEV::NoWrapFlags OrigFlags,
2544 unsigned Depth) {
2545 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2546 "only nuw or nsw allowed");
2547 assert(!Ops.empty() && "Cannot get empty add!");
2548 if (Ops.size() == 1) return Ops[0];
2549#ifndef NDEBUG
2550 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2551 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2552 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2553 "SCEVAddExpr operand types don't match!");
2554 unsigned NumPtrs = count_if(
2555 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2556 assert(NumPtrs <= 1 && "add has at most one pointer operand");
2557#endif
2558
2559 const SCEV *Folded = constantFoldAndGroupOps(
2560 *this, LI, DT, Ops,
2561 [](const APInt &C1, const APInt &C2) { return C1 + C2; },
2562 [](const APInt &C) { return C.isZero(); }, // identity
2563 [](const APInt &C) { return false; }); // absorber
2564 if (Folded)
2565 return Folded;
2566
2567 unsigned Idx = isa<SCEVConstant>(Ops[0]) ? 1 : 0;
2568
2569 // Delay expensive flag strengthening until necessary.
2570 auto ComputeFlags = [this, OrigFlags](ArrayRef<SCEVUse> Ops) {
2571 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2572 };
2573
2574 // Limit recursion calls depth.
2576 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2577
2578 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2579 // Don't strengthen flags if we have no new information.
2580 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2581 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2582 Add->setNoWrapFlags(ComputeFlags(Ops));
2583 return S;
2584 }
2585
2586 // Okay, check to see if the same value occurs in the operand list more than
2587 // once. If so, merge them together into an multiply expression. Since we
2588 // sorted the list, these values are required to be adjacent.
2589 Type *Ty = Ops[0]->getType();
2590 bool FoundMatch = false;
2591 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2592 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2593 // Scan ahead to count how many equal operands there are.
2594 unsigned Count = 2;
2595 while (i+Count != e && Ops[i+Count] == Ops[i])
2596 ++Count;
2597 // Merge the values into a multiply.
2598 SCEVUse Scale = getConstant(Ty, Count);
2599 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2600 if (Ops.size() == Count)
2601 return Mul;
2602 Ops[i] = Mul;
2603 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2604 --i; e -= Count - 1;
2605 FoundMatch = true;
2606 }
2607 if (FoundMatch)
2608 return getAddExpr(Ops, OrigFlags, Depth + 1);
2609
2610 // Check for truncates. If all the operands are truncated from the same
2611 // type, see if factoring out the truncate would permit the result to be
2612 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2613 // if the contents of the resulting outer trunc fold to something simple.
2614 auto FindTruncSrcType = [&]() -> Type * {
2615 // We're ultimately looking to fold an addrec of truncs and muls of only
2616 // constants and truncs, so if we find any other types of SCEV
2617 // as operands of the addrec then we bail and return nullptr here.
2618 // Otherwise, we return the type of the operand of a trunc that we find.
2619 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2620 return T->getOperand()->getType();
2621 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2622 SCEVUse LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2623 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2624 return T->getOperand()->getType();
2625 }
2626 return nullptr;
2627 };
2628 if (auto *SrcType = FindTruncSrcType()) {
2629 SmallVector<SCEVUse, 8> LargeOps;
2630 bool Ok = true;
2631 // Check all the operands to see if they can be represented in the
2632 // source type of the truncate.
2633 for (const SCEV *Op : Ops) {
2635 if (T->getOperand()->getType() != SrcType) {
2636 Ok = false;
2637 break;
2638 }
2639 LargeOps.push_back(T->getOperand());
2640 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Op)) {
2641 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2642 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Op)) {
2643 SmallVector<SCEVUse, 8> LargeMulOps;
2644 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2645 if (const SCEVTruncateExpr *T =
2646 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2647 if (T->getOperand()->getType() != SrcType) {
2648 Ok = false;
2649 break;
2650 }
2651 LargeMulOps.push_back(T->getOperand());
2652 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2653 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2654 } else {
2655 Ok = false;
2656 break;
2657 }
2658 }
2659 if (Ok)
2660 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2661 } else {
2662 Ok = false;
2663 break;
2664 }
2665 }
2666 if (Ok) {
2667 // Evaluate the expression in the larger type.
2668 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2669 // If it folds to something simple, use it. Otherwise, don't.
2670 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2671 return getTruncateExpr(Fold, Ty);
2672 }
2673 }
2674
2675 if (Ops.size() == 2) {
2676 // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2677 // C2 can be folded in a way that allows retaining wrapping flags of (X +
2678 // C1).
2679 const SCEV *A = Ops[0];
2680 const SCEV *B = Ops[1];
2681 auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2682 auto *C = dyn_cast<SCEVConstant>(A);
2683 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2684 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2685 auto C2 = C->getAPInt();
2686 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2687
2688 APInt ConstAdd = C1 + C2;
2689 auto AddFlags = AddExpr->getNoWrapFlags();
2690 // Adding a smaller constant is NUW if the original AddExpr was NUW.
2692 ConstAdd.ule(C1)) {
2693 PreservedFlags =
2695 }
2696
2697 // Adding a constant with the same sign and small magnitude is NSW, if the
2698 // original AddExpr was NSW.
2700 C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2701 ConstAdd.abs().ule(C1.abs())) {
2702 PreservedFlags =
2704 }
2705
2706 if (PreservedFlags != SCEV::FlagAnyWrap) {
2707 SmallVector<SCEVUse, 4> NewOps(AddExpr->operands());
2708 NewOps[0] = getConstant(ConstAdd);
2709 return getAddExpr(NewOps, PreservedFlags);
2710 }
2711 }
2712
2713 // Try to push the constant operand into a ZExt: A + zext (-A + B) -> zext
2714 // (B), if trunc (A) + -A + B does not unsigned-wrap.
2715 const SCEVAddExpr *InnerAdd;
2716 if (match(B, m_scev_ZExt(m_scev_Add(InnerAdd)))) {
2717 const SCEV *NarrowA = getTruncateExpr(A, InnerAdd->getType());
2718 if (NarrowA == getNegativeSCEV(InnerAdd->getOperand(0)) &&
2719 getZeroExtendExpr(NarrowA, B->getType()) == A &&
2720 hasFlags(StrengthenNoWrapFlags(this, scAddExpr, {NarrowA, InnerAdd},
2722 SCEV::FlagNUW)) {
2723 return getZeroExtendExpr(getAddExpr(NarrowA, InnerAdd), B->getType());
2724 }
2725 }
2726 }
2727
2728 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2729 const SCEV *Y;
2730 if (Ops.size() == 2 &&
2731 match(Ops[0],
2733 m_scev_URem(m_scev_Specific(Ops[1]), m_SCEV(Y), *this))))
2734 return getMulExpr(Y, getUDivExpr(Ops[1], Y));
2735
2736 // Skip past any other cast SCEVs.
2737 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2738 ++Idx;
2739
2740 // If there are add operands they would be next.
2741 if (Idx < Ops.size()) {
2742 bool DeletedAdd = false;
2743 // If the original flags and all inlined SCEVAddExprs are NUW, use the
2744 // common NUW flag for expression after inlining. Other flags cannot be
2745 // preserved, because they may depend on the original order of operations.
2746 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2747 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2748 if (Ops.size() > AddOpsInlineThreshold ||
2749 Add->getNumOperands() > AddOpsInlineThreshold)
2750 break;
2751 // If we have an add, expand the add operands onto the end of the operands
2752 // list.
2753 Ops.erase(Ops.begin()+Idx);
2754 append_range(Ops, Add->operands());
2755 DeletedAdd = true;
2756 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2757 }
2758
2759 // If we deleted at least one add, we added operands to the end of the list,
2760 // and they are not necessarily sorted. Recurse to resort and resimplify
2761 // any operands we just acquired.
2762 if (DeletedAdd)
2763 return getAddExpr(Ops, CommonFlags, Depth + 1);
2764 }
2765
2766 // Skip over the add expression until we get to a multiply.
2767 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2768 ++Idx;
2769
2770 // Check to see if there are any folding opportunities present with
2771 // operands multiplied by constant values.
2772 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2773 uint64_t BitWidth = getTypeSizeInBits(Ty);
2776 APInt AccumulatedConstant(BitWidth, 0);
2777 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2778 Ops, APInt(BitWidth, 1), *this)) {
2779 struct APIntCompare {
2780 bool operator()(const APInt &LHS, const APInt &RHS) const {
2781 return LHS.ult(RHS);
2782 }
2783 };
2784
2785 // Some interesting folding opportunity is present, so its worthwhile to
2786 // re-generate the operands list. Group the operands by constant scale,
2787 // to avoid multiplying by the same constant scale multiple times.
2788 std::map<APInt, SmallVector<SCEVUse, 4>, APIntCompare> MulOpLists;
2789 for (const SCEV *NewOp : NewOps)
2790 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2791 // Re-generate the operands list.
2792 Ops.clear();
2793 if (AccumulatedConstant != 0)
2794 Ops.push_back(getConstant(AccumulatedConstant));
2795 for (auto &MulOp : MulOpLists) {
2796 if (MulOp.first == 1) {
2797 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2798 } else if (MulOp.first != 0) {
2799 Ops.push_back(getMulExpr(
2800 getConstant(MulOp.first),
2801 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2802 SCEV::FlagAnyWrap, Depth + 1));
2803 }
2804 }
2805 if (Ops.empty())
2806 return getZero(Ty);
2807 if (Ops.size() == 1)
2808 return Ops[0];
2809 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2810 }
2811 }
2812
2813 // Given a SCEVMulExpr and an operand index, return the product of all
2814 // operands except the one at OpIdx.
2815 auto StripFactor = [&](const SCEVMulExpr *M, unsigned OpIdx) -> SCEVUse {
2816 if (M->getNumOperands() == 2)
2817 return M->getOperand(OpIdx == 0);
2818 SmallVector<SCEVUse, 4> Remaining(M->operands().take_front(OpIdx));
2819 append_range(Remaining, M->operands().drop_front(OpIdx + 1));
2820 return getMulExpr(Remaining, SCEV::FlagAnyWrap, Depth + 1);
2821 };
2822
2823 // If we are adding something to a multiply expression, make sure the
2824 // something is not already an operand of the multiply. If so, merge it into
2825 // the multiply.
2826 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2827 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2828 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2829 // Scan all terms to find every occurrence of common factor MulOpSCEV
2830 // and fold them in one shot:
2831 // A1*X + A2*X + ... + An*X --> X * (A1 + A2 + ... + An)
2832 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2833 if (isa<SCEVConstant>(MulOpSCEV))
2834 continue;
2835
2836 // Cofactors: 1 for bare addends matching MulOpSCEV, or the
2837 // remaining product for multiply terms containing MulOpSCEV.
2838 SmallVector<SCEVUse, 4> Cofactors;
2839 SmallVector<unsigned, 4> DeadIndices;
2840 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) {
2841 if (MulOpSCEV == Ops[AddOp]) {
2842 // W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2843 Cofactors.push_back(getOne(Ty));
2844 DeadIndices.push_back(AddOp);
2845 continue;
2846 }
2847
2848 if (AddOp <= Idx || !isa<SCEVMulExpr>(Ops[AddOp]))
2849 continue;
2850
2851 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[AddOp]);
2852 for (unsigned OMulOp = 0, OE = OtherMul->getNumOperands(); OMulOp != OE;
2853 ++OMulOp) {
2854 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2855 // (A*B*C) + (A*D*E) --> A * (B*C + D*E)
2856 Cofactors.push_back(StripFactor(OtherMul, OMulOp));
2857 DeadIndices.push_back(AddOp);
2858 break;
2859 }
2860 }
2861 }
2862
2863 // Fold all collected cofactors with the anchor multiply's cofactor:
2864 // MulOpSCEV * (Cofactor_1 + ... + Cofactor_n + AnchorCofactor)
2865 if (!Cofactors.empty()) {
2866 Cofactors.push_back(StripFactor(Mul, MulOp));
2867
2868 SCEVUse InnerSum = getAddExpr(Cofactors, SCEV::FlagAnyWrap, Depth + 1);
2869 SCEVUse OuterMul =
2870 getMulExpr(MulOpSCEV, InnerSum, SCEV::FlagAnyWrap, Depth + 1);
2871
2872 // DeadIndices does not include Idx (the anchor), hence +1.
2873 if (Ops.size() == DeadIndices.size() + 1)
2874 return OuterMul;
2875
2876 // Erase Ops[Idx] first, then erase DeadIndices in reverse order.
2877 // The -1 adjustment accounts for the shift from removing Idx;
2878 // reverse order means each erasure only shifts later positions,
2879 // which have already been processed.
2880 Ops.erase(Ops.begin() + Idx);
2881 for (unsigned Dead : reverse(DeadIndices))
2882 Ops.erase(Ops.begin() + (Dead > Idx ? Dead - 1 : Dead));
2883
2884 Ops.push_back(OuterMul);
2885 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2886 }
2887 }
2888 }
2889
2890 // If there are any add recurrences in the operands list, see if any other
2891 // added values are loop invariant. If so, we can fold them into the
2892 // recurrence.
2893 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2894 ++Idx;
2895
2896 // Scan over all recurrences, trying to fold loop invariants into them.
2897 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2898 // Scan all of the other operands to this add and add them to the vector if
2899 // they are loop invariant w.r.t. the recurrence.
2901 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2902 const Loop *AddRecLoop = AddRec->getLoop();
2903 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2904 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2905 LIOps.push_back(Ops[i]);
2906 Ops.erase(Ops.begin()+i);
2907 --i; --e;
2908 }
2909
2910 // If we found some loop invariants, fold them into the recurrence.
2911 if (!LIOps.empty()) {
2912 // Compute nowrap flags for the addition of the loop-invariant ops and
2913 // the addrec. Temporarily push it as an operand for that purpose. These
2914 // flags are valid in the scope of the addrec only.
2915 LIOps.push_back(AddRec);
2916 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2917 LIOps.pop_back();
2918
2919 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2920 LIOps.push_back(AddRec->getStart());
2921
2922 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2923
2924 // It is not in general safe to propagate flags valid on an add within
2925 // the addrec scope to one outside it. We must prove that the inner
2926 // scope is guaranteed to execute if the outer one does to be able to
2927 // safely propagate. We know the program is undefined if poison is
2928 // produced on the inner scoped addrec. We also know that *for this use*
2929 // the outer scoped add can't overflow (because of the flags we just
2930 // computed for the inner scoped add) without the program being undefined.
2931 // Proving that entry to the outer scope neccesitates entry to the inner
2932 // scope, thus proves the program undefined if the flags would be violated
2933 // in the outer scope.
2934 SCEV::NoWrapFlags AddFlags = Flags;
2935 if (AddFlags != SCEV::FlagAnyWrap) {
2936 auto *DefI = getDefiningScopeBound(LIOps);
2937 auto *ReachI = &*AddRecLoop->getHeader()->begin();
2938 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2939 AddFlags = SCEV::FlagAnyWrap;
2940 }
2941 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2942
2943 // Build the new addrec. Propagate the NUW and NSW flags if both the
2944 // outer add and the inner addrec are guaranteed to have no overflow.
2945 // Always propagate NW.
2946 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2947 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2948
2949 // If all of the other operands were loop invariant, we are done.
2950 if (Ops.size() == 1) return NewRec;
2951
2952 // Otherwise, add the folded AddRec by the non-invariant parts.
2953 for (unsigned i = 0;; ++i)
2954 if (Ops[i] == AddRec) {
2955 Ops[i] = NewRec;
2956 break;
2957 }
2958 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2959 }
2960
2961 // Okay, if there weren't any loop invariants to be folded, check to see if
2962 // there are multiple AddRec's with the same loop induction variable being
2963 // added together. If so, we can fold them.
2964 for (unsigned OtherIdx = Idx+1;
2965 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2966 ++OtherIdx) {
2967 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2968 // so that the 1st found AddRecExpr is dominated by all others.
2969 assert(DT.dominates(
2970 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2971 AddRec->getLoop()->getHeader()) &&
2972 "AddRecExprs are not sorted in reverse dominance order?");
2973 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2974 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2975 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2976 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2977 ++OtherIdx) {
2978 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2979 if (OtherAddRec->getLoop() == AddRecLoop) {
2980 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2981 i != e; ++i) {
2982 if (i >= AddRecOps.size()) {
2983 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
2984 break;
2985 }
2986 AddRecOps[i] =
2987 getAddExpr(AddRecOps[i], OtherAddRec->getOperand(i),
2989 }
2990 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2991 }
2992 }
2993 // Step size has changed, so we cannot guarantee no self-wraparound.
2994 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2995 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2996 }
2997 }
2998
2999 // Otherwise couldn't fold anything into this recurrence. Move onto the
3000 // next one.
3001 }
3002
3003 // Okay, it looks like we really DO need an add expr. Check to see if we
3004 // already have one, otherwise create a new one.
3005 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
3006}
3007
3008const SCEV *ScalarEvolution::getOrCreateAddExpr(ArrayRef<SCEVUse> Ops,
3009 SCEV::NoWrapFlags Flags) {
3012 for (SCEVUse Op : Ops)
3013 ID.AddPointer(Op.getOpaqueValue());
3015 SCEVAddExpr *S = static_cast<SCEVAddExpr *>(UniqueSCEVs.lookup(ID, Token));
3016 if (!S) {
3017 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3019 S = new (SCEVAllocator)
3020 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
3021 UniqueSCEVs.insert(S, Token);
3022 S->computeAndSetCanonical(*this);
3023 registerUser(S, Ops);
3024 }
3025 S->setNoWrapFlags(Flags);
3026 return S;
3027}
3028
3029const SCEV *ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<SCEVUse> Ops,
3030 const Loop *L,
3031 SCEV::NoWrapFlags Flags) {
3032 FoldingSetNodeID ID;
3033 ID.AddInteger(scAddRecExpr);
3034 for (SCEVUse Op : Ops)
3035 ID.AddPointer(Op.getOpaqueValue());
3036 ID.AddPointer(L);
3037 FoldingSetInsertToken Token;
3038 SCEVAddRecExpr *S =
3039 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.lookup(ID, Token));
3040 if (!S) {
3041 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3043 S = new (SCEVAllocator)
3044 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
3045 UniqueSCEVs.insert(S, Token);
3046 S->computeAndSetCanonical(*this);
3047 LoopUsers[L].push_back(S);
3048 registerUser(S, Ops);
3049 }
3050 setNoWrapFlags(S, Flags);
3051 return S;
3052}
3053
3054const SCEV *ScalarEvolution::getOrCreateMulExpr(ArrayRef<SCEVUse> Ops,
3055 SCEV::NoWrapFlags Flags) {
3056 FoldingSetNodeID ID;
3057 ID.AddInteger(scMulExpr);
3058 for (SCEVUse Op : Ops)
3059 ID.AddPointer(Op.getOpaqueValue());
3060 FoldingSetInsertToken Token;
3061 SCEVMulExpr *S = static_cast<SCEVMulExpr *>(UniqueSCEVs.lookup(ID, Token));
3062 if (!S) {
3063 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3065 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
3066 O, Ops.size());
3067 UniqueSCEVs.insert(S, Token);
3068 S->computeAndSetCanonical(*this);
3069 registerUser(S, Ops);
3070 }
3071 S->setNoWrapFlags(Flags);
3072 return S;
3073}
3074
3075const SCEV *ScalarEvolution::getOrCreateUDivExpr(SCEVUse LHS, SCEVUse RHS) {
3076 FoldingSetNodeID ID;
3077 ID.AddInteger(scUDivExpr);
3078 ID.AddPointer(LHS.getOpaqueValue());
3079 ID.AddPointer(RHS.getOpaqueValue());
3080 FoldingSetInsertToken Token;
3081 SCEV *S = UniqueSCEVs.lookup(ID, Token);
3082 if (!S) {
3083 S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), LHS, RHS);
3084 UniqueSCEVs.insert(S, Token);
3085 S->computeAndSetCanonical(*this);
3086 registerUser(S, {LHS, RHS});
3087 }
3088 return S;
3089}
3090
3091static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
3092 uint64_t k = i*j;
3093 if (j > 1 && k / j != i) Overflow = true;
3094 return k;
3095}
3096
3097/// Compute the result of "n choose k", the binomial coefficient. If an
3098/// intermediate computation overflows, Overflow will be set and the return will
3099/// be garbage. Overflow is not cleared on absence of overflow.
3100static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3101 // We use the multiplicative formula:
3102 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3103 // At each iteration, we take the n-th term of the numeral and divide by the
3104 // (k-n)th term of the denominator. This division will always produce an
3105 // integral result, and helps reduce the chance of overflow in the
3106 // intermediate computations. However, we can still overflow even when the
3107 // final result would fit.
3108
3109 if (n == 0 || n == k) return 1;
3110 if (k > n) return 0;
3111
3112 if (k > n/2)
3113 k = n-k;
3114
3115 uint64_t r = 1;
3116 for (uint64_t i = 1; i <= k; ++i) {
3117 r = umul_ov(r, n-(i-1), Overflow);
3118 r /= i;
3119 }
3120 return r;
3121}
3122
3123/// Determine if any of the operands in this SCEV are a constant or if
3124/// any of the add or multiply expressions in this SCEV contain a constant.
3125static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3126 struct FindConstantInAddMulChain {
3127 bool FoundConstant = false;
3128
3129 bool follow(const SCEV *S) {
3130 FoundConstant |= isa<SCEVConstant>(S);
3131 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3132 }
3133
3134 bool isDone() const {
3135 return FoundConstant;
3136 }
3137 };
3138
3139 FindConstantInAddMulChain F;
3141 ST.visitAll(StartExpr);
3142 return F.FoundConstant;
3143}
3144
3145/// Get a canonical multiply expression, or something simpler if possible.
3147 SCEV::NoWrapFlags OrigFlags,
3148 unsigned Depth) {
3149 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3150 "only nuw or nsw allowed");
3151 assert(!Ops.empty() && "Cannot get empty mul!");
3152 if (Ops.size() == 1) return Ops[0];
3153#ifndef NDEBUG
3154 Type *ETy = Ops[0]->getType();
3155 assert(!ETy->isPointerTy());
3156 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3157 assert(Ops[i]->getType() == ETy &&
3158 "SCEVMulExpr operand types don't match!");
3159#endif
3160
3161 const SCEV *Folded = constantFoldAndGroupOps(
3162 *this, LI, DT, Ops,
3163 [](const APInt &C1, const APInt &C2) { return C1 * C2; },
3164 [](const APInt &C) { return C.isOne(); }, // identity
3165 [](const APInt &C) { return C.isZero(); }); // absorber
3166 if (Folded)
3167 return Folded;
3168
3169 // Delay expensive flag strengthening until necessary.
3170 auto ComputeFlags = [this, OrigFlags](const ArrayRef<SCEVUse> Ops) {
3171 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3172 };
3173
3174 // Limit recursion calls depth.
3176 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3177
3178 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3179 // Don't strengthen flags if we have no new information.
3180 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3181 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3182 Mul->setNoWrapFlags(ComputeFlags(Ops));
3183 return S;
3184 }
3185
3186 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3187 if (Ops.size() == 2) {
3188 // C1*(C2+V) -> C1*C2 + C1*V
3189 // If any of Add's ops are Adds or Muls with a constant, apply this
3190 // transformation as well.
3191 //
3192 // TODO: There are some cases where this transformation is not
3193 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
3194 // this transformation should be narrowed down.
3195 const SCEV *Op0, *Op1;
3196 if (match(Ops[1], m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))) &&
3198 const SCEV *LHS = getMulExpr(LHSC, Op0, SCEV::FlagAnyWrap, Depth + 1);
3199 const SCEV *RHS = getMulExpr(LHSC, Op1, SCEV::FlagAnyWrap, Depth + 1);
3200 return getAddExpr(LHS, RHS, SCEV::FlagAnyWrap, Depth + 1);
3201 }
3202
3203 if (Ops[0]->isAllOnesValue()) {
3204 // If we have a mul by -1 of an add, try distributing the -1 among the
3205 // add operands.
3206 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3208 bool AnyFolded = false;
3209 for (const SCEV *AddOp : Add->operands()) {
3210 const SCEV *Mul = getMulExpr(Ops[0], SCEVUse(AddOp),
3212 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3213 NewOps.push_back(Mul);
3214 }
3215 if (AnyFolded)
3216 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3217 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3218 // Negation preserves a recurrence's no self-wrap property.
3220 for (const SCEV *AddRecOp : AddRec->operands())
3221 Operands.push_back(getMulExpr(Ops[0], SCEVUse(AddRecOp),
3222 SCEV::FlagAnyWrap, Depth + 1));
3223 // Let M be the minimum representable signed value. AddRec with nsw
3224 // multiplied by -1 can have signed overflow if and only if it takes a
3225 // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3226 // maximum signed value. In all other cases signed overflow is
3227 // impossible.
3228 auto FlagsMask = SCEV::FlagNW;
3229 if (AddRec->hasNoSignedWrap()) {
3230 auto MinInt =
3231 APInt::getSignedMinValue(getTypeSizeInBits(AddRec->getType()));
3232 if (getSignedRangeMin(AddRec) != MinInt)
3233 FlagsMask = setFlags(FlagsMask, SCEV::FlagNSW);
3234 }
3235 return getAddRecExpr(Operands, AddRec->getLoop(),
3236 AddRec->getNoWrapFlags(FlagsMask));
3237 }
3238 }
3239
3240 // Try to push the constant operand into a ZExt: C * zext (A + B) ->
3241 // zext (C*A + C*B) if trunc (C) * (A + B) does not unsigned-wrap.
3242 const SCEVAddExpr *InnerAdd;
3243 if (match(Ops[1], m_scev_ZExt(m_scev_Add(InnerAdd)))) {
3244 const SCEV *NarrowC = getTruncateExpr(LHSC, InnerAdd->getType());
3245 if (isa<SCEVConstant>(InnerAdd->getOperand(0)) &&
3246 getZeroExtendExpr(NarrowC, Ops[1]->getType()) == LHSC &&
3247 hasFlags(StrengthenNoWrapFlags(this, scMulExpr, {NarrowC, InnerAdd},
3249 SCEV::FlagNUW)) {
3250 auto *Res = getMulExpr(NarrowC, InnerAdd, SCEV::FlagNUW, Depth + 1);
3251 return getZeroExtendExpr(Res, Ops[1]->getType(), Depth + 1);
3252 };
3253 }
3254
3255 // Try to fold (C1 * D /u C2) -> C1/C2 * D, if C1 and C2 are powers-of-2,
3256 // D is a multiple of C2, and C1 is a multiple of C2. If C2 is a multiple
3257 // of C1, fold to (D /u (C2 /u C1)).
3258 const SCEV *D;
3259 APInt C1V = LHSC->getAPInt();
3260 // (C1 * D /u C2) == -1 * -C1 * D /u C2 when C1 != INT_MIN. Don't treat -1
3261 // as -1 * 1, as it won't enable additional folds.
3262 if (C1V.isNegative() && !C1V.isMinSignedValue() && !C1V.isAllOnes())
3263 C1V = C1V.abs();
3264 const SCEVConstant *C2;
3265 if (C1V.isPowerOf2() &&
3267 C2->getAPInt().isPowerOf2() &&
3268 C1V.logBase2() <= getMinTrailingZeros(D)) {
3269 const SCEV *NewMul = nullptr;
3270 if (C1V.uge(C2->getAPInt())) {
3271 NewMul = getMulExpr(getUDivExpr(getConstant(C1V), C2), D);
3272 } else if (C2->getAPInt().logBase2() <= getMinTrailingZeros(D)) {
3273 assert(C1V.ugt(1) && "C1 <= 1 should have been folded earlier");
3274 NewMul = getUDivExpr(D, getUDivExpr(C2, getConstant(C1V)));
3275 }
3276 if (NewMul)
3277 return C1V == LHSC->getAPInt() ? NewMul : getNegativeSCEV(NewMul);
3278 }
3279 }
3280 }
3281
3282 // Skip over the add expression until we get to a multiply.
3283 unsigned Idx = 0;
3284 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3285 ++Idx;
3286
3287 // If there are mul operands inline them all into this expression.
3288 if (Idx < Ops.size()) {
3289 bool DeletedMul = false;
3290 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3291 if (Ops.size() > MulOpsInlineThreshold)
3292 break;
3293 // If we have an mul, expand the mul operands onto the end of the
3294 // operands list.
3295 Ops.erase(Ops.begin()+Idx);
3296 append_range(Ops, Mul->operands());
3297 DeletedMul = true;
3298 }
3299
3300 // If we deleted at least one mul, we added operands to the end of the
3301 // list, and they are not necessarily sorted. Recurse to resort and
3302 // resimplify any operands we just acquired.
3303 if (DeletedMul)
3304 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3305 }
3306
3307 // If there are any add recurrences in the operands list, see if any other
3308 // added values are loop invariant. If so, we can fold them into the
3309 // recurrence.
3310 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3311 ++Idx;
3312
3313 // Scan over all recurrences, trying to fold loop invariants into them.
3314 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3315 // Scan all of the other operands to this mul and add them to the vector
3316 // if they are loop invariant w.r.t. the recurrence.
3318 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3319 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3320 if (isAvailableAtLoopEntry(Ops[i], AddRec->getLoop())) {
3321 LIOps.push_back(Ops[i]);
3322 Ops.erase(Ops.begin()+i);
3323 --i; --e;
3324 }
3325
3326 // If we found some loop invariants, fold them into the recurrence.
3327 if (!LIOps.empty()) {
3328 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3330 NewOps.reserve(AddRec->getNumOperands());
3331 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3332
3333 // If both the mul and addrec are nuw, we can preserve nuw.
3334 // If both the mul and addrec are nsw, we can only preserve nsw if either
3335 // a) they are also nuw, or
3336 // b) all multiplications of addrec operands with scale are nsw.
3337 SCEV::NoWrapFlags Flags =
3338 AddRec->getNoWrapFlags(ComputeFlags({Scale, AddRec}));
3339
3340 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3341 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3342 SCEV::FlagAnyWrap, Depth + 1));
3343
3344 if (hasFlags(Flags, SCEV::FlagNSW) && !hasFlags(Flags, SCEV::FlagNUW)) {
3346 Instruction::Mul, getSignedRange(Scale),
3348 if (!NSWRegion.contains(getSignedRange(AddRec->getOperand(i))))
3349 Flags = clearFlags(Flags, SCEV::FlagNSW);
3350 }
3351 }
3352
3353 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(), Flags);
3354
3355 // If all of the other operands were loop invariant, we are done.
3356 if (Ops.size() == 1) return NewRec;
3357
3358 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3359 for (unsigned i = 0;; ++i)
3360 if (Ops[i] == AddRec) {
3361 Ops[i] = NewRec;
3362 break;
3363 }
3364 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3365 }
3366
3367 // Okay, if there weren't any loop invariants to be folded, check to see
3368 // if there are multiple AddRec's with the same loop induction variable
3369 // being multiplied together. If so, we can fold them.
3370
3371 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3372 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3373 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3374 // ]]],+,...up to x=2n}.
3375 // Note that the arguments to choose() are always integers with values
3376 // known at compile time, never SCEV objects.
3377 //
3378 // The implementation avoids pointless extra computations when the two
3379 // addrec's are of different length (mathematically, it's equivalent to
3380 // an infinite stream of zeros on the right).
3381 bool OpsModified = false;
3382 for (unsigned OtherIdx = Idx+1;
3383 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3384 ++OtherIdx) {
3385 const SCEVAddRecExpr *OtherAddRec =
3386 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3387 if (!OtherAddRec || OtherAddRec->getLoop() != AddRec->getLoop())
3388 continue;
3389
3390 // Limit max number of arguments to avoid creation of unreasonably big
3391 // SCEVAddRecs with very complex operands.
3392 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3393 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3394 continue;
3395
3396 bool Overflow = false;
3397 Type *Ty = AddRec->getType();
3398 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3399 SmallVector<SCEVUse, 7> AddRecOps;
3400 for (int x = 0, xe = AddRec->getNumOperands() +
3401 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3403 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3404 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3405 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3406 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3407 z < ze && !Overflow; ++z) {
3408 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3409 uint64_t Coeff;
3410 if (LargerThan64Bits)
3411 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3412 else
3413 Coeff = Coeff1*Coeff2;
3414 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3415 const SCEV *Term1 = AddRec->getOperand(y-z);
3416 const SCEV *Term2 = OtherAddRec->getOperand(z);
3417 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3418 SCEV::FlagAnyWrap, Depth + 1));
3419 }
3420 }
3421 if (SumOps.empty())
3422 SumOps.push_back(getZero(Ty));
3423 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3424 }
3425 if (!Overflow) {
3426 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
3428 if (Ops.size() == 2) return NewAddRec;
3429 Ops[Idx] = NewAddRec;
3430 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3431 OpsModified = true;
3432 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3433 if (!AddRec)
3434 break;
3435 }
3436 }
3437 if (OpsModified)
3438 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3439
3440 // Otherwise couldn't fold anything into this recurrence. Move onto the
3441 // next one.
3442 }
3443
3444 // Okay, it looks like we really DO need an mul expr. Check to see if we
3445 // already have one, otherwise create a new one.
3446 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3447}
3448
3449/// Represents an unsigned remainder expression based on unsigned division.
3451 assert(getEffectiveSCEVType(LHS->getType()) ==
3452 getEffectiveSCEVType(RHS->getType()) &&
3453 "SCEVURemExpr operand types don't match!");
3454
3455 // Short-circuit easy cases
3456 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3457 // If constant is one, the result is trivial
3458 if (RHSC->getValue()->isOne())
3459 return getZero(LHS->getType()); // X urem 1 --> 0
3460
3461 // If constant is a power of two, fold into a zext(trunc(LHS)).
3462 if (RHSC->getAPInt().isPowerOf2()) {
3463 Type *FullTy = LHS->getType();
3464 Type *TruncTy =
3465 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3466 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3467 }
3468 }
3469
3470 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3471 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3472 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3473 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3474}
3475
3476/// Get a canonical unsigned division expression, or something simpler if
3477/// possible.
3479 assert(!LHS->getType()->isPointerTy() &&
3480 "SCEVUDivExpr operand can't be pointer!");
3481 assert(LHS->getType() == RHS->getType() &&
3482 "SCEVUDivExpr operand types don't match!");
3483
3484 if (SCEV *S = findExistingSCEVInCache(scUDivExpr, {LHS, RHS}))
3485 return S;
3486
3487 // 0 udiv Y == 0
3488 if (match(LHS, m_scev_Zero()))
3489 return LHS;
3490
3491 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3492 if (RHSC->getValue()->isOne())
3493 return LHS; // X udiv 1 --> x
3494 // If the denominator is zero, the result of the udiv is undefined. Don't
3495 // try to analyze it, because the resolution chosen here may differ from
3496 // the resolution chosen in other parts of the compiler.
3497 if (!RHSC->getValue()->isZero()) {
3498 // Determine if the division can be folded into the operands of
3499 // its operands.
3500 // TODO: Generalize this to non-constants by using known-bits information.
3501 Type *Ty = LHS->getType();
3502 unsigned LZ = RHSC->getAPInt().countl_zero();
3503 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3504 // For non-power-of-two values, effectively round the value up to the
3505 // nearest power of two.
3506 if (!RHSC->getAPInt().isPowerOf2())
3507 ++MaxShiftAmt;
3508 IntegerType *ExtTy =
3509 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3510 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3511 if (const SCEVConstant *Step =
3512 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3513 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3514 const APInt &StepInt = Step->getAPInt();
3515 const APInt &DivInt = RHSC->getAPInt();
3516 if (!StepInt.urem(DivInt) &&
3517 getZeroExtendExpr(AR, ExtTy) ==
3518 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3519 getZeroExtendExpr(Step, ExtTy),
3520 AR->getLoop(), SCEV::FlagAnyWrap)) {
3522 for (const SCEV *Op : AR->operands())
3523 Operands.push_back(getUDivExpr(Op, RHS));
3524 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3525 }
3526 /// Get a canonical UDivExpr for a recurrence.
3527 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3528 const APInt *StartRem;
3529 if (!DivInt.urem(StepInt) && match(getURemExpr(AR->getStart(), Step),
3530 m_scev_APInt(StartRem))) {
3531 bool NoWrap =
3532 getZeroExtendExpr(AR, ExtTy) ==
3533 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3534 getZeroExtendExpr(Step, ExtTy), AR->getLoop(),
3536
3537 // With N <= C and both N, C as powers-of-2, the transformation
3538 // {X,+,N}/C => {(X - X%N),+,N}/C preserves division results even
3539 // if wrapping occurs, as the division results remain equivalent for
3540 // all offsets in [[(X - X%N), X).
3541 bool CanFoldWithWrap = StepInt.ule(DivInt) && // N <= C
3542 StepInt.isPowerOf2() && DivInt.isPowerOf2();
3543 // Only fold if the subtraction can be folded in the start
3544 // expression.
3545 const SCEV *NewStart =
3546 getMinusSCEV(AR->getStart(), getConstant(*StartRem));
3547 if (*StartRem != 0 && (NoWrap || CanFoldWithWrap) &&
3548 !isa<SCEVAddExpr>(NewStart)) {
3549 const SCEV *NewLHS =
3550 getAddRecExpr(NewStart, Step, AR->getLoop(),
3551 NoWrap ? SCEV::FlagNW : SCEV::FlagAnyWrap);
3552 if (LHS != NewLHS)
3553 return getUDivExpr(NewLHS, RHS);
3554 }
3555 }
3556 }
3557 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3558 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3559 if (M->hasNoUnsignedWrap()) {
3560 // Find an operand that's safely divisible.
3561 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3562 const SCEV *Op = M->getOperand(i);
3563 const SCEV *Div = getUDivExpr(Op, RHSC);
3564 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3565 SmallVector<SCEVUse, 4> Operands(M->operands());
3566 Operands[i] = Div;
3567 return getMulExpr(Operands);
3568 }
3569 }
3570
3571 // Even if it's not divisible, try to remove a common factor.
3572 if (const auto *LHSC = dyn_cast<SCEVConstant>(M->getOperand(0))) {
3573 APInt Factor = APIntOps::GreatestCommonDivisor(LHSC->getAPInt(),
3574 RHSC->getAPInt());
3575 if (!Factor.isIntN(1)) {
3576 SmallVector<SCEVUse, 2> NewOperands;
3577 NewOperands.push_back(getConstant(LHSC->getAPInt().udiv(Factor)));
3578 append_range(NewOperands, M->operands().drop_front());
3579 const SCEV *NewMul = getMulExpr(NewOperands);
3580 return getUDivExpr(NewMul,
3581 getConstant(RHSC->getAPInt().udiv(Factor)));
3582 }
3583 }
3584 }
3585 }
3586
3587 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3588 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3589 if (auto *DivisorConstant =
3590 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3591 bool Overflow = false;
3592 APInt NewRHS =
3593 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3594 if (Overflow) {
3595 return getConstant(RHSC->getType(), 0, false);
3596 }
3597 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3598 }
3599 }
3600
3601 // (A+B)/C --> (A/C + B/C) if the add does not unsigned wrap and A/C and
3602 // B/C can be folded.
3603 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3604 if (A->hasNoUnsignedWrap()) {
3606 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3607 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3608 if (isa<SCEVUDivExpr>(Op) ||
3609 getMulExpr(Op, RHS) != A->getOperand(i))
3610 break;
3611 Operands.push_back(Op);
3612 }
3613 if (Operands.size() == A->getNumOperands())
3614 return getAddExpr(Operands);
3615 }
3616 }
3617
3618 // ((N - M) + (M * A)) / N --> ((N - 1) + (M * A)) / N
3619 // This is an idiom for rounding A up to the next multiple of N, where A
3620 // is aready known to be a multiple of M. In this case, instcombine can
3621 // see that some low bits of the added constant are unused, so can clear
3622 // them, but we want to canonicalise to set the low bits. This makes the
3623 // pattern easier to match, without needing to check for known bits in
3624 // A*M.
3625 const APInt &N = RHSC->getAPInt();
3626 const APInt *NMinusM, *M;
3627 const SCEV *A;
3628 if (match(LHS, m_scev_Add(m_scev_APInt(NMinusM),
3629 m_scev_Mul(m_scev_APInt(M), m_SCEV(A))))) {
3630 if (N.isPowerOf2() && M->isPowerOf2() && M->ult(N) &&
3631 *NMinusM == N - *M) {
3632 return getUDivExpr(
3634 RHS);
3635 }
3636 }
3637
3638 // Fold if both operands are constant.
3639 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3640 return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3641 }
3642 }
3643
3644 // ((-C + (C smax %x)) /u %x) evaluates to zero, for any positive constant C.
3645 const APInt *NegC, *C;
3646 if (match(LHS,
3649 NegC->isNegative() && !NegC->isMinSignedValue() && *C == -*NegC)
3650 return getZero(LHS->getType());
3651
3652 // (%a * %b)<nuw> / %b -> %a
3653 const auto *Mul = dyn_cast<SCEVMulExpr>(LHS);
3654 if (Mul && Mul->hasNoUnsignedWrap()) {
3655 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3656 if (Mul->getOperand(i) == RHS) {
3658 append_range(Operands, Mul->operands().take_front(i));
3659 append_range(Operands, Mul->operands().drop_front(i + 1));
3660 return getMulExpr(Operands);
3661 }
3662 }
3663 }
3664
3665 // TODO: Generalize to handle any common factors.
3666 // udiv (mul nuw a, vscale), (mul nuw b, vscale) --> udiv a, b
3667 const SCEV *NewLHS, *NewRHS;
3668 if (match(LHS, m_scev_c_NUWMul(m_SCEV(NewLHS), m_SCEVVScale())) &&
3669 match(RHS, m_scev_c_NUWMul(m_SCEV(NewRHS), m_SCEVVScale())))
3670 return getUDivExpr(NewLHS, NewRHS);
3671
3672 return getOrCreateUDivExpr(LHS, RHS);
3673}
3674
3675/// Get a canonical unsigned division expression, or something simpler if
3676/// possible. There is no representation for an exact udiv in SCEV IR, but we
3677/// can attempt to optimize it prior to construction.
3679 // Currently there is no exact specific logic.
3680
3681 return getUDivExpr(LHS, RHS);
3682}
3683
3684/// Get an add recurrence expression for the specified loop. Simplify the
3685/// expression as much as possible.
3687 const Loop *L,
3688 SCEV::NoWrapFlags Flags) {
3690 Operands.push_back(Start);
3691 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3692 if (StepChrec->getLoop() == L) {
3693 append_range(Operands, StepChrec->operands());
3694 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3695 }
3696
3697 Operands.push_back(Step);
3698 return getAddRecExpr(Operands, L, Flags);
3699}
3700
3701/// Get an add recurrence expression for the specified loop. Simplify the
3702/// expression as much as possible.
3704 const Loop *L,
3705 SCEV::NoWrapFlags Flags) {
3706 if (Operands.size() == 1) return Operands[0];
3707#ifndef NDEBUG
3709 for (const SCEV *Op : llvm::drop_begin(Operands)) {
3710 assert(getEffectiveSCEVType(Op->getType()) == ETy &&
3711 "SCEVAddRecExpr operand types don't match!");
3712 assert(!Op->getType()->isPointerTy() && "Step must be integer");
3713 }
3714 for (const SCEV *Op : Operands)
3716 "SCEVAddRecExpr operand is not available at loop entry!");
3717#endif
3718
3719 if (Operands.back()->isZero()) {
3720 Operands.pop_back();
3721 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3722 }
3723
3724 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3725 // use that information to infer NUW and NSW flags. However, computing a
3726 // BE count requires calling getAddRecExpr, so we may not yet have a
3727 // meaningful BE count at this point (and if we don't, we'd be stuck
3728 // with a SCEVCouldNotCompute as the cached BE count).
3729
3730 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3731
3732 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3733 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3734 const Loop *NestedLoop = NestedAR->getLoop();
3735 if (L->contains(NestedLoop)
3736 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3737 : (!NestedLoop->contains(L) &&
3738 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3739 SmallVector<SCEVUse, 4> NestedOperands(NestedAR->operands());
3740 Operands[0] = NestedAR->getStart();
3741 // AddRecs require their operands be loop-invariant with respect to their
3742 // loops. Don't perform this transformation if it would break this
3743 // requirement.
3744 bool AllInvariant = all_of(
3745 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3746
3747 if (AllInvariant) {
3748 // Create a recurrence for the outer loop with the same step size.
3749 //
3750 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3751 // inner recurrence has the same property.
3752 SCEV::NoWrapFlags OuterFlags =
3753 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3754
3755 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3756 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3757 return isLoopInvariant(Op, NestedLoop);
3758 });
3759
3760 if (AllInvariant) {
3761 // Ok, both add recurrences are valid after the transformation.
3762 //
3763 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3764 // the outer recurrence has the same property.
3765 SCEV::NoWrapFlags InnerFlags =
3766 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3767 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3768 }
3769 }
3770 // Reset Operands to its original state.
3771 Operands[0] = NestedAR;
3772 }
3773 }
3774
3775 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3776 // already have one, otherwise create a new one.
3777 return getOrCreateAddRecExpr(Operands, L, Flags);
3778}
3779
3781 ArrayRef<SCEVUse> IndexExprs) {
3782 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3783 // getSCEV(Base)->getType() has the same address space as Base->getType()
3784 // because SCEV::getType() preserves the address space.
3785 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
3786 if (NW != GEPNoWrapFlags::none()) {
3787 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3788 // but to do that, we have to ensure that said flag is valid in the entire
3789 // defined scope of the SCEV.
3790 // TODO: non-instructions have global scope. We might be able to prove
3791 // some global scope cases
3792 auto *GEPI = dyn_cast<Instruction>(GEP);
3793 if (!GEPI || !isSCEVExprNeverPoison(GEPI))
3794 NW = GEPNoWrapFlags::none();
3795 }
3796
3797 return getGEPExpr(BaseExpr, IndexExprs, GEP->getSourceElementType(), NW);
3798}
3799
3801 ArrayRef<SCEVUse> IndexExprs,
3802 Type *SrcElementTy, GEPNoWrapFlags NW) {
3804 if (NW.hasNoUnsignedSignedWrap())
3805 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNSW);
3806 if (NW.hasNoUnsignedWrap())
3807 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNUW);
3808
3809 Type *CurTy = BaseExpr->getType();
3810 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3811 bool FirstIter = true;
3813 for (SCEVUse IndexExpr : IndexExprs) {
3814 // Compute the (potentially symbolic) offset in bytes for this index.
3815 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3816 // For a struct, add the member offset.
3817 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3818 unsigned FieldNo = Index->getZExtValue();
3819 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3820 Offsets.push_back(FieldOffset);
3821
3822 // Update CurTy to the type of the field at Index.
3823 CurTy = STy->getTypeAtIndex(Index);
3824 } else {
3825 // Update CurTy to its element type.
3826 if (FirstIter) {
3827 assert(isa<PointerType>(CurTy) &&
3828 "The first index of a GEP indexes a pointer");
3829 CurTy = SrcElementTy;
3830 FirstIter = false;
3831 } else {
3832 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3833 }
3834 // For an array, add the element offset, explicitly scaled.
3835 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3836 // Getelementptr indices are signed.
3837 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3838
3839 // Multiply the index by the element size to compute the element offset.
3840 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3841 Offsets.push_back(LocalOffset);
3842 }
3843 }
3844
3845 // Handle degenerate case of GEP without offsets.
3846 if (Offsets.empty())
3847 return BaseExpr;
3848
3849 // Add the offsets together, assuming nsw if inbounds.
3850 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3851 // Add the base address and the offset. We cannot use the nsw flag, as the
3852 // base address is unsigned. However, if we know that the offset is
3853 // non-negative, we can use nuw.
3854 bool NUW = NW.hasNoUnsignedWrap() ||
3857 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3858 assert(BaseExpr->getType() == GEPExpr->getType() &&
3859 "GEP should not change type mid-flight.");
3860 return GEPExpr;
3861}
3862
3863SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3866 ID.AddInteger(SCEVType);
3867 for (SCEVUse Op : Ops)
3868 ID.AddPointer(Op.getOpaqueValue());
3870 return UniqueSCEVs.lookup(ID, Token);
3871}
3872
3873const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3875 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3876}
3877
3880 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3881 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3882 if (Ops.size() == 1) return Ops[0];
3883#ifndef NDEBUG
3884 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3885 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3886 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3887 "Operand types don't match!");
3888 assert(Ops[0]->getType()->isPointerTy() ==
3889 Ops[i]->getType()->isPointerTy() &&
3890 "min/max should be consistently pointerish");
3891 }
3892#endif
3893
3894 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3895 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3896
3897 const SCEV *Folded = constantFoldAndGroupOps(
3898 *this, LI, DT, Ops,
3899 [&](const APInt &C1, const APInt &C2) {
3900 switch (Kind) {
3901 case scSMaxExpr:
3902 return APIntOps::smax(C1, C2);
3903 case scSMinExpr:
3904 return APIntOps::smin(C1, C2);
3905 case scUMaxExpr:
3906 return APIntOps::umax(C1, C2);
3907 case scUMinExpr:
3908 return APIntOps::umin(C1, C2);
3909 default:
3910 llvm_unreachable("Unknown SCEV min/max opcode");
3911 }
3912 },
3913 [&](const APInt &C) {
3914 // identity
3915 if (IsMax)
3916 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3917 else
3918 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3919 },
3920 [&](const APInt &C) {
3921 // absorber
3922 if (IsMax)
3923 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3924 else
3925 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3926 });
3927 if (Folded)
3928 return Folded;
3929
3930 // Check if we have created the same expression before.
3931 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3932 return S;
3933 }
3934
3935 // Find the first operation of the same kind
3936 unsigned Idx = 0;
3937 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3938 ++Idx;
3939
3940 // Check to see if one of the operands is of the same kind. If so, expand its
3941 // operands onto our operand list, and recurse to simplify.
3942 if (Idx < Ops.size()) {
3943 bool DeletedAny = false;
3944 while (Ops[Idx]->getSCEVType() == Kind) {
3945 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3946 Ops.erase(Ops.begin()+Idx);
3947 append_range(Ops, SMME->operands());
3948 DeletedAny = true;
3949 }
3950
3951 if (DeletedAny)
3952 return getMinMaxExpr(Kind, Ops);
3953 }
3954
3955 // Okay, check to see if the same value occurs in the operand list twice. If
3956 // so, delete one. Since we sorted the list, these values are required to
3957 // be adjacent.
3962 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3963 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3964 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3965 if (Ops[i] == Ops[i + 1] ||
3966 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3967 // X op Y op Y --> X op Y
3968 // X op Y --> X, if we know X, Y are ordered appropriately
3969 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3970 --i;
3971 --e;
3972 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3973 Ops[i + 1])) {
3974 // X op Y --> Y, if we know X, Y are ordered appropriately
3975 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3976 --i;
3977 --e;
3978 }
3979 }
3980
3981 if (Ops.size() == 1) return Ops[0];
3982
3983 assert(!Ops.empty() && "Reduced smax down to nothing!");
3984
3985 // Okay, it looks like we really DO need an expr. Check to see if we
3986 // already have one, otherwise create a new one.
3988 ID.AddInteger(Kind);
3989 for (SCEVUse Op : Ops)
3990 ID.AddPointer(Op.getOpaqueValue());
3992 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
3993 if (ExistingSCEV)
3994 return ExistingSCEV;
3995 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3997 SCEV *S = new (SCEVAllocator)
3998 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3999
4000 UniqueSCEVs.insert(S, Token);
4001 S->computeAndSetCanonical(*this);
4002 registerUser(S, Ops);
4003 return S;
4004}
4005
4006namespace {
4007
4008class SCEVSequentialMinMaxDeduplicatingVisitor final
4009 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
4010 std::optional<const SCEV *>> {
4011 using RetVal = std::optional<const SCEV *>;
4012
4013 ScalarEvolution &SE;
4014 const SCEVTypes RootKind; // Must be a sequential min/max expression.
4015 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
4017
4018 bool canRecurseInto(SCEVTypes Kind) const {
4019 // We can only recurse into the SCEV expression of the same effective type
4020 // as the type of our root SCEV expression.
4021 return RootKind == Kind || NonSequentialRootKind == Kind;
4022 };
4023
4024 RetVal visit(const SCEV *S) {
4025 // Has the whole operand been seen already?
4026 if (!SeenOps.insert(S).second)
4027 return std::nullopt;
4029 SCEVTypes Kind = S->getSCEVType();
4030
4031 if (!canRecurseInto(Kind))
4032 return S;
4033
4034 auto *NAry = cast<SCEVNAryExpr>(S);
4035 SmallVector<SCEVUse> NewOps;
4036 bool Changed = visit(Kind, NAry->operands(), NewOps);
4037
4038 if (!Changed)
4039 return S;
4040 if (NewOps.empty())
4041 return std::nullopt;
4042
4044 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
4045 : SE.getMinMaxExpr(Kind, NewOps);
4046 }
4047 return S;
4048 }
4049
4050public:
4051 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
4052 SCEVTypes RootKind)
4053 : SE(SE), RootKind(RootKind),
4054 NonSequentialRootKind(
4055 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4056 RootKind)) {}
4057
4058 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<SCEVUse> OrigOps,
4059 SmallVectorImpl<SCEVUse> &NewOps) {
4060 bool Changed = false;
4062 Ops.reserve(OrigOps.size());
4063
4064 for (const SCEV *Op : OrigOps) {
4065 RetVal NewOp = visit(Op);
4066 if (NewOp != Op)
4067 Changed = true;
4068 if (NewOp)
4069 Ops.emplace_back(*NewOp);
4070 }
4071
4072 if (Changed)
4073 NewOps = std::move(Ops);
4074 return Changed;
4075 }
4076};
4077
4078} // namespace
4079
4081 switch (Kind) {
4082 case scConstant:
4083 case scVScale:
4084 case scTruncate:
4085 case scZeroExtend:
4086 case scSignExtend:
4087 case scPtrToAddr:
4088 case scAddExpr:
4089 case scMulExpr:
4090 case scUDivExpr:
4091 case scAddRecExpr:
4092 case scUMaxExpr:
4093 case scSMaxExpr:
4094 case scUMinExpr:
4095 case scSMinExpr:
4096 case scUnknown:
4097 // If any operand is poison, the whole expression is poison.
4098 return true;
4100 // FIXME: if the *first* operand is poison, the whole expression is poison.
4101 return false; // Pessimistically, say that it does not propagate poison.
4102 case scCouldNotCompute:
4103 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4104 }
4105 llvm_unreachable("Unknown SCEV kind!");
4106}
4107
4108namespace {
4109// The only way poison may be introduced in a SCEV expression is from a
4110// poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4111// not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not*
4112// introduce poison -- they encode guaranteed, non-speculated knowledge.
4113//
4114// Additionally, all SCEV nodes propagate poison from inputs to outputs,
4115// with the notable exception of umin_seq, where only poison from the first
4116// operand is (unconditionally) propagated.
4117struct SCEVPoisonCollector {
4118 bool LookThroughMaybePoisonBlocking;
4119 SmallPtrSet<const SCEVUnknown *, 4> MaybePoison;
4120 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4121 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4122
4123 bool follow(const SCEV *S) {
4124 if (!LookThroughMaybePoisonBlocking &&
4126 return false;
4127
4128 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4129 if (!isGuaranteedNotToBePoison(SU->getValue()))
4130 MaybePoison.insert(SU);
4131 }
4132 return true;
4133 }
4134 bool isDone() const { return false; }
4135};
4136} // namespace
4137
4138/// Return true if V is poison given that AssumedPoison is already poison.
4139static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4140 // First collect all SCEVs that might result in AssumedPoison to be poison.
4141 // We need to look through potentially poison-blocking operations here,
4142 // because we want to find all SCEVs that *might* result in poison, not only
4143 // those that are *required* to.
4144 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4145 visitAll(AssumedPoison, PC1);
4146
4147 // AssumedPoison is never poison. As the assumption is false, the implication
4148 // is true. Don't bother walking the other SCEV in this case.
4149 if (PC1.MaybePoison.empty())
4150 return true;
4151
4152 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4153 // as well. We cannot look through potentially poison-blocking operations
4154 // here, as their arguments only *may* make the result poison.
4155 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4156 visitAll(S, PC2);
4157
4158 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4159 // it will also make S poison by being part of PC2.MaybePoison.
4160 return llvm::set_is_subset(PC1.MaybePoison, PC2.MaybePoison);
4161}
4162
4164 SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4165 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4166 visitAll(S, PC);
4167 for (const SCEVUnknown *SU : PC.MaybePoison)
4168 Result.insert(SU->getValue());
4169}
4170
4172 const SCEV *S, Instruction *I,
4173 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
4174 // If the instruction cannot be poison, it's always safe to reuse.
4176 return true;
4177
4178 // Otherwise, it is possible that I is more poisonous that S. Collect the
4179 // poison-contributors of S, and then check whether I has any additional
4180 // poison-contributors. Poison that is contributed through poison-generating
4181 // flags is handled by dropping those flags instead.
4183 getPoisonGeneratingValues(PoisonVals, S);
4184
4185 SmallVector<Value *> Worklist;
4187 Worklist.push_back(I);
4188 while (!Worklist.empty()) {
4189 Value *V = Worklist.pop_back_val();
4190 if (!Visited.insert(V).second)
4191 continue;
4192
4193 // Avoid walking large instruction graphs.
4194 if (Visited.size() > 16)
4195 return false;
4196
4197 // Either the value can't be poison, or the S would also be poison if it
4198 // is.
4199 if (PoisonVals.contains(V) || ::isGuaranteedNotToBePoison(V))
4200 continue;
4201
4202 auto *I = dyn_cast<Instruction>(V);
4203 if (!I)
4204 return false;
4205
4206 // Disjoint or instructions are interpreted as adds by SCEV. However, we
4207 // can't replace an arbitrary add with disjoint or, even if we drop the
4208 // flag. We would need to convert the or into an add.
4209 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
4210 if (PDI->isDisjoint())
4211 return false;
4212
4213 // FIXME: Ignore vscale, even though it technically could be poison. Do this
4214 // because SCEV currently assumes it can't be poison. Remove this special
4215 // case once we proper model when vscale can be poison.
4216 if (auto *II = dyn_cast<IntrinsicInst>(I);
4217 II && II->getIntrinsicID() == Intrinsic::vscale)
4218 continue;
4219
4220 if (canCreatePoison(cast<Operator>(I), /*ConsiderFlagsAndMetadata*/ false))
4221 return false;
4222
4223 // If the instruction can't create poison, we can recurse to its operands.
4224 if (I->hasPoisonGeneratingAnnotations())
4225 DropPoisonGeneratingInsts.push_back(I);
4226
4227 llvm::append_range(Worklist, I->operands());
4228 }
4229 return true;
4230}
4231
4232const SCEV *
4235 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4236 "Not a SCEVSequentialMinMaxExpr!");
4237 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4238 if (Ops.size() == 1)
4239 return Ops[0];
4240#ifndef NDEBUG
4241 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4242 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4243 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4244 "Operand types don't match!");
4245 assert(Ops[0]->getType()->isPointerTy() ==
4246 Ops[i]->getType()->isPointerTy() &&
4247 "min/max should be consistently pointerish");
4248 }
4249#endif
4250
4251 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4252 // so we can *NOT* do any kind of sorting of the expressions!
4253
4254 // Check if we have created the same expression before.
4255 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4256 return S;
4257
4258 // FIXME: there are *some* simplifications that we can do here.
4259
4260 // Keep only the first instance of an operand.
4261 {
4262 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4263 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4264 if (Changed)
4265 return getSequentialMinMaxExpr(Kind, Ops);
4266 }
4267
4268 // Check to see if one of the operands is of the same kind. If so, expand its
4269 // operands onto our operand list, and recurse to simplify.
4270 {
4271 unsigned Idx = 0;
4272 bool DeletedAny = false;
4273 while (Idx < Ops.size()) {
4274 if (Ops[Idx]->getSCEVType() != Kind) {
4275 ++Idx;
4276 continue;
4277 }
4278 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4279 Ops.erase(Ops.begin() + Idx);
4280 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4281 SMME->operands().end());
4282 DeletedAny = true;
4283 }
4284
4285 if (DeletedAny)
4286 return getSequentialMinMaxExpr(Kind, Ops);
4287 }
4288
4289 const SCEV *SaturationPoint;
4291 switch (Kind) {
4293 SaturationPoint = getZero(Ops[0]->getType());
4294 Pred = ICmpInst::ICMP_ULE;
4295 break;
4296 default:
4297 llvm_unreachable("Not a sequential min/max type.");
4298 }
4299
4300 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4301 if (!isGuaranteedNotToCauseUB(Ops[i]))
4302 continue;
4303 // We can replace %x umin_seq %y with %x umin %y if either:
4304 // * %y being poison implies %x is also poison.
4305 // * %x cannot be the saturating value (e.g. zero for umin).
4306 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4307 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4308 SaturationPoint)) {
4309 SmallVector<SCEVUse, 2> SeqOps = {Ops[i - 1], Ops[i]};
4310 Ops[i - 1] = getMinMaxExpr(
4312 SeqOps);
4313 Ops.erase(Ops.begin() + i);
4314 return getSequentialMinMaxExpr(Kind, Ops);
4315 }
4316 // Fold %x umin_seq %y to %x if %x ule %y.
4317 // TODO: We might be able to prove the predicate for a later operand.
4318 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4319 Ops.erase(Ops.begin() + i);
4320 return getSequentialMinMaxExpr(Kind, Ops);
4321 }
4322 }
4323
4324 // Okay, it looks like we really DO need an expr. Check to see if we
4325 // already have one, otherwise create a new one.
4327 ID.AddInteger(Kind);
4328 for (SCEVUse Op : Ops)
4329 ID.AddPointer(Op.getOpaqueValue());
4331 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
4332 if (ExistingSCEV)
4333 return ExistingSCEV;
4334
4335 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4337 SCEV *S = new (SCEVAllocator)
4338 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4339
4340 UniqueSCEVs.insert(S, Token);
4341 S->computeAndSetCanonical(*this);
4342 registerUser(S, Ops);
4343 return S;
4344}
4345
4350
4354
4359
4363
4368
4372
4374 bool Sequential) {
4375 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4376 return getUMinExpr(Ops, Sequential);
4377}
4378
4384
4385const SCEV *
4387 const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4388 if (Size.isScalable())
4389 Res = getMulExpr(Res, getVScale(IntTy));
4390 return Res;
4391}
4392
4394 return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4395}
4396
4398 return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4399}
4400
4402 StructType *STy,
4403 unsigned FieldNo) {
4404 // We can bypass creating a target-independent constant expression and then
4405 // folding it back into a ConstantInt. This is just a compile-time
4406 // optimization.
4407 const StructLayout *SL = getDataLayout().getStructLayout(STy);
4408 assert(!SL->getSizeInBits().isScalable() &&
4409 "Cannot get offset for structure containing scalable vector types");
4410 return getConstant(IntTy, SL->getElementOffset(FieldNo));
4411}
4412
4414 // Don't attempt to do anything other than create a SCEVUnknown object
4415 // here. createSCEV only calls getUnknown after checking for all other
4416 // interesting possibilities, and any other code that calls getUnknown
4417 // is doing so in order to hide a value from SCEV canonicalization.
4418
4421 ID.AddPointer(V);
4423 if (SCEV *S = UniqueSCEVs.lookup(ID, Token)) {
4424 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4425 "Stale SCEVUnknown in uniquing map!");
4426 return S;
4427 }
4428 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4429 FirstUnknown);
4430 FirstUnknown = cast<SCEVUnknown>(S);
4431 UniqueSCEVs.insert(S, Token);
4432 S->computeAndSetCanonical(*this);
4433 return S;
4434}
4435
4436//===----------------------------------------------------------------------===//
4437// Basic SCEV Analysis and PHI Idiom Recognition Code
4438//
4439
4440/// Test if values of the given type are analyzable within the SCEV
4441/// framework. This primarily includes integer types, and it can optionally
4442/// include pointer types if the ScalarEvolution class has access to
4443/// target-specific information.
4445 // Integers and pointers are always SCEVable.
4446 return Ty->isIntOrPtrTy();
4447}
4448
4449/// Return the size in bits of the specified type, for which isSCEVable must
4450/// return true.
4452 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4453 if (Ty->isPointerTy())
4455 return getDataLayout().getTypeSizeInBits(Ty);
4456}
4457
4458/// Return a type with the same bitwidth as the given type and which represents
4459/// how SCEV will treat the given type, for which isSCEVable must return
4460/// true. For pointer types, this is the pointer index sized integer type.
4462 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4463
4464 if (Ty->isIntegerTy())
4465 return Ty;
4466
4467 // The only other support type is pointer.
4468 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4469 return getDataLayout().getIndexType(Ty);
4470}
4471
4473 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4474}
4475
4477 const SCEV *B) {
4478 /// For a valid use point to exist, the defining scope of one operand
4479 /// must dominate the other.
4480 bool PreciseA, PreciseB;
4481 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4482 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4483 if (!PreciseA || !PreciseB)
4484 // Can't tell.
4485 return false;
4486 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4487 DT.dominates(ScopeB, ScopeA);
4488}
4489
4491 return CouldNotCompute.get();
4492}
4493
4494bool ScalarEvolution::checkValidity(const SCEV *S) const {
4495 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4496 auto *SU = dyn_cast<SCEVUnknown>(S);
4497 return SU && SU->getValue() == nullptr;
4498 });
4499
4500 return !ContainsNulls;
4501}
4502
4504 HasRecMapType::iterator I = HasRecMap.find(S);
4505 if (I != HasRecMap.end())
4506 return I->second;
4507
4508 bool FoundAddRec =
4509 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4510 HasRecMap.insert({S, FoundAddRec});
4511 return FoundAddRec;
4512}
4513
4514/// Return the ValueOffsetPair set for \p S. \p S can be represented
4515/// by the value and offset from any ValueOffsetPair in the set.
4516ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4517 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4518 if (SI == ExprValueMap.end())
4519 return {};
4520 return SI->second.getArrayRef();
4521}
4522
4523/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4524/// cannot be used separately. eraseValueFromMap should be used to remove
4525/// V from ValueExprMap and ExprValueMap at the same time.
4526void ScalarEvolution::eraseValueFromMap(Value *V) {
4527 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4528 if (I != ValueExprMap.end()) {
4529 auto EVIt = ExprValueMap.find(I->second);
4530 bool Removed = EVIt->second.remove(V);
4531 (void) Removed;
4532 assert(Removed && "Value not in ExprValueMap?");
4533 ValueExprMap.erase(I);
4534 }
4535}
4536
4537void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4538 // A recursive query may have already computed the SCEV. It should be
4539 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4540 // inferred nowrap flags.
4541 auto It = ValueExprMap.find_as(V);
4542 if (It == ValueExprMap.end()) {
4543 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4544 ExprValueMap[S].insert(V);
4545 }
4546}
4547
4548/// Return an existing SCEV if it exists, otherwise analyze the expression and
4549/// create a new one.
4551 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4552
4553 if (const SCEV *S = getExistingSCEV(V))
4554 return S;
4555 return createSCEVIter(V);
4556}
4557
4559 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4560
4561 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4562 if (I != ValueExprMap.end()) {
4563 const SCEV *S = I->second;
4564 assert(checkValidity(S) &&
4565 "existing SCEV has not been properly invalidated");
4566 return S;
4567 }
4568 return nullptr;
4569}
4570
4571/// Return a SCEV corresponding to -V = -1*V
4573 SCEV::NoWrapFlags Flags) {
4574 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4575 return getConstant(
4576 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4577
4578 Type *Ty = V->getType();
4579 Ty = getEffectiveSCEVType(Ty);
4580 return getMulExpr(V, getMinusOne(Ty), Flags);
4581}
4582
4583/// If Expr computes ~A, return A else return nullptr
4584static const SCEV *MatchNotExpr(const SCEV *Expr) {
4585 const SCEV *MulOp;
4586 if (match(Expr, m_scev_Add(m_scev_AllOnes(),
4587 m_scev_Mul(m_scev_AllOnes(), m_SCEV(MulOp)))))
4588 return MulOp;
4589 return nullptr;
4590}
4591
4592/// Return a SCEV corresponding to ~V = -1-V
4594 assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4595
4596 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4597 return getConstant(
4598 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4599
4600 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4601 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4602 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4603 SmallVector<SCEVUse, 2> MatchedOperands;
4604 for (const SCEV *Operand : MME->operands()) {
4605 const SCEV *Matched = MatchNotExpr(Operand);
4606 if (!Matched)
4607 return (const SCEV *)nullptr;
4608 MatchedOperands.push_back(Matched);
4609 }
4610 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4611 MatchedOperands);
4612 };
4613 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4614 return Replaced;
4615 }
4616
4617 Type *Ty = V->getType();
4618 Ty = getEffectiveSCEVType(Ty);
4619 return getMinusSCEV(getMinusOne(Ty), V);
4620}
4621
4623 assert(P->getType()->isPointerTy());
4624
4625 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4626 // The base of an AddRec is the first operand.
4627 SmallVector<SCEVUse> Ops{AddRec->operands()};
4628 Ops[0] = removePointerBase(Ops[0]);
4629 // Don't try to transfer nowrap flags for now. We could in some cases
4630 // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4631 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
4632 }
4633 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4634 // The base of an Add is the pointer operand.
4635 SmallVector<SCEVUse> Ops{Add->operands()};
4636 SCEVUse *PtrOp = nullptr;
4637 for (SCEVUse &AddOp : Ops) {
4638 if (AddOp->getType()->isPointerTy()) {
4639 assert(!PtrOp && "Cannot have multiple pointer ops");
4640 PtrOp = &AddOp;
4641 }
4642 }
4643 *PtrOp = removePointerBase(*PtrOp);
4644 // Don't try to transfer nowrap flags for now. We could in some cases
4645 // (for example, if the pointer operand of the Add is a SCEVUnknown).
4646 return getAddExpr(Ops);
4647 }
4648 // Any other expression must be a pointer base.
4649 return getZero(P->getType());
4650}
4651
4653 SCEV::NoWrapFlags Flags,
4654 unsigned Depth) {
4655 // Fast path: X - X --> 0.
4656 if (LHS == RHS)
4657 return getZero(LHS->getType());
4658
4659 // If we subtract two pointers with different pointer bases, bail.
4660 // Eventually, we're going to add an assertion to getMulExpr that we
4661 // can't multiply by a pointer.
4662 if (RHS->getType()->isPointerTy()) {
4663 if (!LHS->getType()->isPointerTy() ||
4664 getPointerBase(LHS) != getPointerBase(RHS))
4665 return getCouldNotCompute();
4666 LHS = removePointerBase(LHS);
4667 RHS = removePointerBase(RHS);
4668 }
4669
4670 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4671 // makes it so that we cannot make much use of NUW.
4672 auto AddFlags = SCEV::FlagAnyWrap;
4673 const bool RHSIsNotMinSigned =
4675 if (hasFlags(Flags, SCEV::FlagNSW)) {
4676 // Let M be the minimum representable signed value. Then (-1)*RHS
4677 // signed-wraps if and only if RHS is M. That can happen even for
4678 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4679 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4680 // (-1)*RHS, we need to prove that RHS != M.
4681 //
4682 // If LHS is non-negative and we know that LHS - RHS does not
4683 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4684 // either by proving that RHS > M or that LHS >= 0.
4685 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4686 AddFlags = SCEV::FlagNSW;
4687 }
4688 }
4689
4690 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4691 // RHS is NSW and LHS >= 0.
4692 //
4693 // The difficulty here is that the NSW flag may have been proven
4694 // relative to a loop that is to be found in a recurrence in LHS and
4695 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4696 // larger scope than intended.
4697 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4698
4699 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4700}
4701
4703 unsigned Depth) {
4704 Type *SrcTy = V->getType();
4705 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4706 "Cannot truncate or zero extend with non-integer arguments!");
4707 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4708 return V; // No conversion
4709 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4710 return getTruncateExpr(V, Ty, Depth);
4711 return getZeroExtendExpr(V, Ty, Depth);
4712}
4713
4715 unsigned Depth) {
4716 Type *SrcTy = V->getType();
4717 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4718 "Cannot truncate or zero extend with non-integer arguments!");
4719 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4720 return V; // No conversion
4721 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4722 return getTruncateExpr(V, Ty, Depth);
4723 return getSignExtendExpr(V, Ty, Depth);
4724}
4725
4727 Type *SrcTy = V->getType();
4728 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4729 "Cannot noop or zero extend with non-integer arguments!");
4731 "getNoopOrZeroExtend cannot truncate!");
4732 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4733 return V; // No conversion
4734 return getZeroExtendExpr(V, Ty);
4735}
4736
4738 Type *SrcTy = V->getType();
4739 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4740 "Cannot noop or sign extend with non-integer arguments!");
4742 "getNoopOrSignExtend cannot truncate!");
4743 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4744 return V; // No conversion
4745 return getSignExtendExpr(V, Ty);
4746}
4747
4749 Type *SrcTy = V->getType();
4750 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4751 "Cannot noop or any extend with non-integer arguments!");
4753 "getNoopOrAnyExtend cannot truncate!");
4754 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4755 return V; // No conversion
4756 return getAnyExtendExpr(V, Ty);
4757}
4758
4760 Type *SrcTy = V->getType();
4761 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4762 "Cannot truncate or noop with non-integer arguments!");
4764 "getTruncateOrNoop cannot extend!");
4765 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4766 return V; // No conversion
4767 return getTruncateExpr(V, Ty);
4768}
4769
4771 const SCEV *RHS) {
4772 const SCEV *PromotedLHS = LHS;
4773 const SCEV *PromotedRHS = RHS;
4774
4775 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4776 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4777 else
4778 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4779
4780 return getUMaxExpr(PromotedLHS, PromotedRHS);
4781}
4782
4784 const SCEV *RHS,
4785 bool Sequential) {
4786 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4787 return getUMinFromMismatchedTypes(Ops, Sequential);
4788}
4789
4790const SCEV *
4792 bool Sequential) {
4793 assert(!Ops.empty() && "At least one operand must be!");
4794 // Trivial case.
4795 if (Ops.size() == 1)
4796 return Ops[0];
4797
4798 // Find the max type first.
4799 Type *MaxType = nullptr;
4800 for (SCEVUse S : Ops)
4801 if (MaxType)
4802 MaxType = getWiderType(MaxType, S->getType());
4803 else
4804 MaxType = S->getType();
4805 assert(MaxType && "Failed to find maximum type!");
4806
4807 // Extend all ops to max type.
4808 SmallVector<SCEVUse, 2> PromotedOps;
4809 for (SCEVUse S : Ops)
4810 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4811
4812 // Generate umin.
4813 return getUMinExpr(PromotedOps, Sequential);
4814}
4815
4817 // A pointer operand may evaluate to a nonpointer expression, such as null.
4818 if (!V->getType()->isPointerTy())
4819 return V;
4820
4821 while (true) {
4822 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4823 V = AddRec->getStart();
4824 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4825 const SCEV *PtrOp = nullptr;
4826 for (const SCEV *AddOp : Add->operands()) {
4827 if (AddOp->getType()->isPointerTy()) {
4828 assert(!PtrOp && "Cannot have multiple pointer ops");
4829 PtrOp = AddOp;
4830 }
4831 }
4832 assert(PtrOp && "Must have pointer op");
4833 V = PtrOp;
4834 } else // Not something we can look further into.
4835 return V;
4836 }
4837}
4838
4839/// Push users of the given Instruction onto the given Worklist.
4843 // Push the def-use children onto the Worklist stack.
4844 for (User *U : I->users()) {
4845 auto *UserInsn = cast<Instruction>(U);
4846 if (Visited.insert(UserInsn).second)
4847 Worklist.push_back(UserInsn);
4848 }
4849}
4850
4851namespace {
4852
4853/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4854/// expression in case its Loop is L. If it is not L then
4855/// if IgnoreOtherLoops is true then use AddRec itself
4856/// otherwise rewrite cannot be done.
4857/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4858class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4859public:
4860 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4861 bool IgnoreOtherLoops = true) {
4862 SCEVInitRewriter Rewriter(L, SE);
4863 const SCEV *Result = Rewriter.visit(S);
4864 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4865 return SE.getCouldNotCompute();
4866 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4867 ? SE.getCouldNotCompute()
4868 : Result;
4869 }
4870
4871 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4872 if (!SE.isLoopInvariant(Expr, L))
4873 SeenLoopVariantSCEVUnknown = true;
4874 return Expr;
4875 }
4876
4877 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4878 // Only re-write AddRecExprs for this loop.
4879 if (Expr->getLoop() == L)
4880 return Expr->getStart();
4881 SeenOtherLoops = true;
4882 return Expr;
4883 }
4884
4885 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4886
4887 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4888
4889private:
4890 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4891 : SCEVRewriteVisitor(SE), L(L) {}
4892
4893 const Loop *L;
4894 bool SeenLoopVariantSCEVUnknown = false;
4895 bool SeenOtherLoops = false;
4896};
4897
4898/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4899/// increment expression in case its Loop is L. If it is not L then
4900/// use AddRec itself.
4901/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4902class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4903public:
4904 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4905 SCEVPostIncRewriter Rewriter(L, SE);
4906 const SCEV *Result = Rewriter.visit(S);
4907 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4908 ? SE.getCouldNotCompute()
4909 : Result;
4910 }
4911
4912 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4913 if (!SE.isLoopInvariant(Expr, L))
4914 SeenLoopVariantSCEVUnknown = true;
4915 return Expr;
4916 }
4917
4918 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4919 // Only re-write AddRecExprs for this loop.
4920 if (Expr->getLoop() == L)
4921 return Expr->getPostIncExpr(SE);
4922 SeenOtherLoops = true;
4923 return Expr;
4924 }
4925
4926 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4927
4928 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4929
4930private:
4931 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4932 : SCEVRewriteVisitor(SE), L(L) {}
4933
4934 const Loop *L;
4935 bool SeenLoopVariantSCEVUnknown = false;
4936 bool SeenOtherLoops = false;
4937};
4938
4939/// This class evaluates the compare condition by matching it against the
4940/// condition of loop latch. If there is a match we assume a true value
4941/// for the condition while building SCEV nodes.
4942class SCEVBackedgeConditionFolder
4943 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4944public:
4945 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4946 ScalarEvolution &SE) {
4947 bool IsPosBECond = false;
4948 Value *BECond = nullptr;
4949 if (BasicBlock *Latch = L->getLoopLatch()) {
4950 if (CondBrInst *BI = dyn_cast<CondBrInst>(Latch->getTerminator())) {
4951 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4952 "Both outgoing branches should not target same header!");
4953 BECond = BI->getCondition();
4954 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4955 } else {
4956 return S;
4957 }
4958 }
4959 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4960 return Rewriter.visit(S);
4961 }
4962
4963 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4964 const SCEV *Result = Expr;
4965 bool InvariantF = SE.isLoopInvariant(Expr, L);
4966
4967 if (!InvariantF) {
4969 switch (I->getOpcode()) {
4970 case Instruction::Select: {
4971 SelectInst *SI = cast<SelectInst>(I);
4972 std::optional<const SCEV *> Res =
4973 compareWithBackedgeCondition(SI->getCondition());
4974 if (Res) {
4975 bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
4976 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4977 }
4978 break;
4979 }
4980 default: {
4981 std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4982 if (Res)
4983 Result = *Res;
4984 break;
4985 }
4986 }
4987 }
4988 return Result;
4989 }
4990
4991private:
4992 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4993 bool IsPosBECond, ScalarEvolution &SE)
4994 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4995 IsPositiveBECond(IsPosBECond) {}
4996
4997 std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4998
4999 const Loop *L;
5000 /// Loop back condition.
5001 Value *BackedgeCond = nullptr;
5002 /// Set to true if loop back is on positive branch condition.
5003 bool IsPositiveBECond;
5004};
5005
5006std::optional<const SCEV *>
5007SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
5008
5009 // If value matches the backedge condition for loop latch,
5010 // then return a constant evolution node based on loopback
5011 // branch taken.
5012 if (BackedgeCond == IC)
5013 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
5015 return std::nullopt;
5016}
5017
5018class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
5019public:
5020 static const SCEV *rewrite(const SCEV *S, const Loop *L,
5021 ScalarEvolution &SE) {
5022 SCEVShiftRewriter Rewriter(L, SE);
5023 const SCEV *Result = Rewriter.visit(S);
5024 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
5025 }
5026
5027 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5028 // Only allow AddRecExprs for this loop.
5029 if (!SE.isLoopInvariant(Expr, L))
5030 Valid = false;
5031 return Expr;
5032 }
5033
5034 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5035 if (Expr->getLoop() == L && Expr->isAffine())
5036 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
5037 Valid = false;
5038 return Expr;
5039 }
5040
5041 bool isValid() { return Valid; }
5042
5043private:
5044 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
5045 : SCEVRewriteVisitor(SE), L(L) {}
5046
5047 const Loop *L;
5048 bool Valid = true;
5049};
5050
5051} // end anonymous namespace
5052
5053void ScalarEvolution::inferNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
5054 if (!AR->isAffine())
5055 return;
5056
5057 // Force computation of ranges, which will also perform range-based flag
5058 // inference.
5059 if (!AR->hasNoSignedWrap())
5060 (void)getSignedRange(AR);
5061
5062 if (!AR->hasNoUnsignedWrap())
5063 (void)getUnsignedRange(AR);
5064
5065 if (!AR->hasNoSelfWrap()) {
5066 const SCEV *BECount = getConstantMaxBackedgeTakenCount(AR->getLoop());
5067 if (const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(BECount)) {
5068 ConstantRange StepCR = getSignedRange(AR->getStepRecurrence(*this));
5069 const APInt &BECountAP = BECountMax->getAPInt();
5070 unsigned NoOverflowBitWidth =
5071 BECountAP.getActiveBits() + StepCR.getMinSignedBits();
5072 if (NoOverflowBitWidth <= getTypeSizeInBits(AR->getType()))
5073 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
5074 }
5075 }
5076}
5077
5079ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5081
5082 if (AR->hasNoSignedWrap())
5083 return Result;
5084
5085 if (!AR->isAffine())
5086 return Result;
5087
5088 // This function can be expensive, only try to prove NSW once per AddRec.
5089 if (!SignedWrapViaInductionTried.insert(AR).second)
5090 return Result;
5091
5092 const SCEV *Step = AR->getStepRecurrence(*this);
5093 const Loop *L = AR->getLoop();
5094
5095 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5096 // Note that this serves two purposes: It filters out loops that are
5097 // simply not analyzable, and it covers the case where this code is
5098 // being called from within backedge-taken count analysis, such that
5099 // attempting to ask for the backedge-taken count would likely result
5100 // in infinite recursion. In the later case, the analysis code will
5101 // cope with a conservative value, and it will take care to purge
5102 // that value once it has finished.
5103 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5104
5105 // Normally, in the cases we can prove no-overflow via a
5106 // backedge guarding condition, we can also compute a backedge
5107 // taken count for the loop. The exceptions are assumptions and
5108 // guards present in the loop -- SCEV is not great at exploiting
5109 // these to compute max backedge taken counts, but can still use
5110 // these to prove lack of overflow. Use this fact to avoid
5111 // doing extra work that may not pay off.
5112
5113 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5114 AC.assumptions().empty())
5115 return Result;
5116
5117 // If the backedge is guarded by a comparison with the pre-inc value the
5118 // addrec is safe. Also, if the entry is guarded by a comparison with the
5119 // start value and the backedge is guarded by a comparison with the post-inc
5120 // value, the addrec is safe.
5122 const SCEV *OverflowLimit =
5123 getSignedOverflowLimitForStep(Step, &Pred, this);
5124 if (OverflowLimit &&
5125 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5126 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
5127 Result = setFlags(Result, SCEV::FlagNSW);
5128 }
5129 return Result;
5130}
5132ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5134
5135 if (AR->hasNoUnsignedWrap())
5136 return Result;
5137
5138 if (!AR->isAffine())
5139 return Result;
5140
5141 // This function can be expensive, only try to prove NUW once per AddRec.
5142 if (!UnsignedWrapViaInductionTried.insert(AR).second)
5143 return Result;
5144
5145 const SCEV *Step = AR->getStepRecurrence(*this);
5146 const Loop *L = AR->getLoop();
5147
5148 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5149 // Note that this serves two purposes: It filters out loops that are
5150 // simply not analyzable, and it covers the case where this code is
5151 // being called from within backedge-taken count analysis, such that
5152 // attempting to ask for the backedge-taken count would likely result
5153 // in infinite recursion. In the later case, the analysis code will
5154 // cope with a conservative value, and it will take care to purge
5155 // that value once it has finished.
5156 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5157
5158 // Normally, in the cases we can prove no-overflow via a
5159 // backedge guarding condition, we can also compute a backedge
5160 // taken count for the loop. The exceptions are assumptions and
5161 // guards present in the loop -- SCEV is not great at exploiting
5162 // these to compute max backedge taken counts, but can still use
5163 // these to prove lack of overflow. Use this fact to avoid
5164 // doing extra work that may not pay off.
5165
5166 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5167 AC.assumptions().empty())
5168 return Result;
5169
5170 // If the backedge is guarded by a comparison with the pre-inc value the
5171 // addrec is safe. Also, if the entry is guarded by a comparison with the
5172 // start value and the backedge is guarded by a comparison with the post-inc
5173 // value, the addrec is safe.
5174 if (isKnownPositive(Step)) {
5176 const SCEV *OverflowLimit =
5177 getUnsignedOverflowLimitForStep(Step, &Pred, this);
5178 if (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5179 isKnownOnEveryIteration(Pred, AR, OverflowLimit))
5180 Result = setFlags(Result, SCEV::FlagNUW);
5181 }
5182 return Result;
5183}
5184
5185namespace {
5186
5187/// Represents an abstract binary operation. This may exist as a
5188/// normal instruction or constant expression, or may have been
5189/// derived from an expression tree.
5190struct BinaryOp {
5191 unsigned Opcode;
5192 Value *LHS;
5193 Value *RHS;
5194 bool IsNSW = false;
5195 bool IsNUW = false;
5196
5197 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5198 /// constant expression.
5199 Operator *Op = nullptr;
5200
5201 explicit BinaryOp(Operator *Op)
5202 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5203 Op(Op) {
5204 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5205 IsNSW = OBO->hasNoSignedWrap();
5206 IsNUW = OBO->hasNoUnsignedWrap();
5207 }
5208 }
5209
5210 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5211 bool IsNUW = false)
5212 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5213};
5214
5215} // end anonymous namespace
5216
5217/// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
5218static std::optional<BinaryOp> MatchBinaryOp(Value *V, const DataLayout &DL,
5219 AssumptionCache &AC,
5220 const DominatorTree &DT,
5221 const Instruction *CxtI) {
5222 auto *Op = dyn_cast<Operator>(V);
5223 if (!Op)
5224 return std::nullopt;
5225
5226 // Implementation detail: all the cleverness here should happen without
5227 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5228 // SCEV expressions when possible, and we should not break that.
5229
5230 switch (Op->getOpcode()) {
5231 case Instruction::Add:
5232 case Instruction::Sub:
5233 case Instruction::Mul:
5234 case Instruction::UDiv:
5235 case Instruction::URem:
5236 case Instruction::And:
5237 case Instruction::AShr:
5238 case Instruction::Shl:
5239 return BinaryOp(Op);
5240
5241 case Instruction::Or: {
5242 // Convert or disjoint into add nuw nsw.
5243 if (cast<PossiblyDisjointInst>(Op)->isDisjoint()) {
5244 BinaryOp BinOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
5245 /*IsNSW=*/true, /*IsNUW=*/true);
5246 // Keep the reference to the original instruction so that we can later
5247 // check whether it can produce poison value or not.
5248 BinOp.Op = Op;
5249 return BinOp;
5250 }
5251 return BinaryOp(Op);
5252 }
5253
5254 case Instruction::Xor:
5255 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5256 // If the RHS of the xor is a signmask, then this is just an add.
5257 // Instcombine turns add of signmask into xor as a strength reduction step.
5258 if (RHSC->getValue().isSignMask())
5259 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5260 // Binary `xor` is a bit-wise `add`.
5261 if (V->getType()->isIntegerTy(1))
5262 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5263 return BinaryOp(Op);
5264
5265 case Instruction::LShr:
5266 // Turn logical shift right of a constant into a unsigned divide.
5267 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5268 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5269
5270 // If the shift count is not less than the bitwidth, the result of
5271 // the shift is undefined. Don't try to analyze it, because the
5272 // resolution chosen here may differ from the resolution chosen in
5273 // other parts of the compiler.
5274 if (SA->getValue().ult(BitWidth)) {
5275 Constant *X =
5276 ConstantInt::get(SA->getContext(),
5277 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5278 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5279 }
5280 }
5281 return BinaryOp(Op);
5282
5283 case Instruction::ExtractValue: {
5284 auto *EVI = cast<ExtractValueInst>(Op);
5285 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5286 break;
5287
5288 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5289 if (!WO)
5290 break;
5291
5292 Instruction::BinaryOps BinOp = WO->getBinaryOp();
5293 bool Signed = WO->isSigned();
5294 // TODO: Should add nuw/nsw flags for mul as well.
5295 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5296 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5297
5298 // Now that we know that all uses of the arithmetic-result component of
5299 // CI are guarded by the overflow check, we can go ahead and pretend
5300 // that the arithmetic is non-overflowing.
5301 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5302 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5303 }
5304
5305 default:
5306 break;
5307 }
5308
5309 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5310 // semantics as a Sub, return a binary sub expression.
5311 if (auto *II = dyn_cast<IntrinsicInst>(V))
5312 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5313 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5314
5315 return std::nullopt;
5316}
5317
5318/// Helper function to createAddRecFromPHIWithCasts. We have a phi
5319/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5320/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5321/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5322/// follows one of the following patterns:
5323/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5324/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5325/// If the SCEV expression of \p Op conforms with one of the expected patterns
5326/// we return the type of the truncation operation, and indicate whether the
5327/// truncated type should be treated as signed/unsigned by setting
5328/// \p Signed to true/false, respectively.
5329static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5330 bool &Signed, ScalarEvolution &SE) {
5331 // The case where Op == SymbolicPHI (that is, with no type conversions on
5332 // the way) is handled by the regular add recurrence creating logic and
5333 // would have already been triggered in createAddRecForPHI. Reaching it here
5334 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5335 // because one of the other operands of the SCEVAddExpr updating this PHI is
5336 // not invariant).
5337 //
5338 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5339 // this case predicates that allow us to prove that Op == SymbolicPHI will
5340 // be added.
5341 if (Op == SymbolicPHI)
5342 return nullptr;
5343
5344 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5345 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5346 if (SourceBits != NewBits)
5347 return nullptr;
5348
5349 if (match(Op, m_scev_SExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5350 Signed = true;
5351 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5352 }
5353 if (match(Op, m_scev_ZExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5354 Signed = false;
5355 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5356 }
5357 return nullptr;
5358}
5359
5360static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5361 if (!PN->getType()->isIntegerTy())
5362 return nullptr;
5363 const Loop *L = LI.getLoopFor(PN->getParent());
5364 if (!L || L->getHeader() != PN->getParent())
5365 return nullptr;
5366 return L;
5367}
5368
5369// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5370// computation that updates the phi follows the following pattern:
5371// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5372// which correspond to a phi->trunc->sext/zext->add->phi update chain.
5373// If so, try to see if it can be rewritten as an AddRecExpr under some
5374// Predicates. If successful, return them as a pair. Also cache the results
5375// of the analysis.
5376//
5377// Example usage scenario:
5378// Say the Rewriter is called for the following SCEV:
5379// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5380// where:
5381// %X = phi i64 (%Start, %BEValue)
5382// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5383// and call this function with %SymbolicPHI = %X.
5384//
5385// The analysis will find that the value coming around the backedge has
5386// the following SCEV:
5387// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5388// Upon concluding that this matches the desired pattern, the function
5389// will return the pair {NewAddRec, SmallPredsVec} where:
5390// NewAddRec = {%Start,+,%Step}
5391// SmallPredsVec = {P1, P2, P3} as follows:
5392// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5393// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5394// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5395// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5396// under the predicates {P1,P2,P3}.
5397// This predicated rewrite will be cached in PredicatedSCEVRewrites:
5398// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5399//
5400// TODO's:
5401//
5402// 1) Extend the Induction descriptor to also support inductions that involve
5403// casts: When needed (namely, when we are called in the context of the
5404// vectorizer induction analysis), a Set of cast instructions will be
5405// populated by this method, and provided back to isInductionPHI. This is
5406// needed to allow the vectorizer to properly record them to be ignored by
5407// the cost model and to avoid vectorizing them (otherwise these casts,
5408// which are redundant under the runtime overflow checks, will be
5409// vectorized, which can be costly).
5410//
5411// 2) Support additional induction/PHISCEV patterns: We also want to support
5412// inductions where the sext-trunc / zext-trunc operations (partly) occur
5413// after the induction update operation (the induction increment):
5414//
5415// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5416// which correspond to a phi->add->trunc->sext/zext->phi update chain.
5417//
5418// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5419// which correspond to a phi->trunc->add->sext/zext->phi update chain.
5420//
5421// 3) Outline common code with createAddRecFromPHI to avoid duplication.
5422std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5423ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5425
5426 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5427 // return an AddRec expression under some predicate.
5428
5429 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5430 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5431 assert(L && "Expecting an integer loop header phi");
5432
5433 // The loop may have multiple entrances or multiple exits; we can analyze
5434 // this phi as an addrec if it has a unique entry value and a unique
5435 // backedge value.
5436 Value *BEValueV = nullptr, *StartValueV = nullptr;
5437 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5438 Value *V = PN->getIncomingValue(i);
5439 if (L->contains(PN->getIncomingBlock(i))) {
5440 if (!BEValueV) {
5441 BEValueV = V;
5442 } else if (BEValueV != V) {
5443 BEValueV = nullptr;
5444 break;
5445 }
5446 } else if (!StartValueV) {
5447 StartValueV = V;
5448 } else if (StartValueV != V) {
5449 StartValueV = nullptr;
5450 break;
5451 }
5452 }
5453 if (!BEValueV || !StartValueV)
5454 return std::nullopt;
5455
5456 const SCEV *BEValue = getSCEV(BEValueV);
5457
5458 // If the value coming around the backedge is an add with the symbolic
5459 // value we just inserted, possibly with casts that we can ignore under
5460 // an appropriate runtime guard, then we found a simple induction variable!
5461 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5462 if (!Add)
5463 return std::nullopt;
5464
5465 // If there is a single occurrence of the symbolic value, possibly
5466 // casted, replace it with a recurrence.
5467 unsigned FoundIndex = Add->getNumOperands();
5468 Type *TruncTy = nullptr;
5469 bool Signed;
5470 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5471 if ((TruncTy =
5472 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5473 if (FoundIndex == e) {
5474 FoundIndex = i;
5475 break;
5476 }
5477
5478 if (FoundIndex == Add->getNumOperands())
5479 return std::nullopt;
5480
5481 // Create an add with everything but the specified operand.
5483 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5484 if (i != FoundIndex)
5485 Ops.push_back(Add->getOperand(i));
5486 const SCEV *Accum = getAddExpr(Ops);
5487
5488 // The runtime checks will not be valid if the step amount is
5489 // varying inside the loop.
5490 if (!isLoopInvariant(Accum, L))
5491 return std::nullopt;
5492
5493 // *** Part2: Create the predicates
5494
5495 // Analysis was successful: we have a phi-with-cast pattern for which we
5496 // can return an AddRec expression under the following predicates:
5497 //
5498 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5499 // fits within the truncated type (does not overflow) for i = 0 to n-1.
5500 // P2: An Equal predicate that guarantees that
5501 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5502 // P3: An Equal predicate that guarantees that
5503 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5504 //
5505 // As we next prove, the above predicates guarantee that:
5506 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5507 //
5508 //
5509 // More formally, we want to prove that:
5510 // Expr(i+1) = Start + (i+1) * Accum
5511 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5512 //
5513 // Given that:
5514 // 1) Expr(0) = Start
5515 // 2) Expr(1) = Start + Accum
5516 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5517 // 3) Induction hypothesis (step i):
5518 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5519 //
5520 // Proof:
5521 // Expr(i+1) =
5522 // = Start + (i+1)*Accum
5523 // = (Start + i*Accum) + Accum
5524 // = Expr(i) + Accum
5525 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5526 // :: from step i
5527 //
5528 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5529 //
5530 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5531 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
5532 // + Accum :: from P3
5533 //
5534 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5535 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5536 //
5537 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5538 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5539 //
5540 // By induction, the same applies to all iterations 1<=i<n:
5541 //
5542
5543 // Create a truncated addrec for which we will add a no overflow check (P1).
5544 const SCEV *StartVal = getSCEV(StartValueV);
5545 const SCEV *PHISCEV =
5546 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5547 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5548
5549 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5550 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5551 // will be constant.
5552 //
5553 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5554 // add P1.
5555 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5559 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5560 Predicates.push_back(AddRecPred);
5561 }
5562
5563 // Create the Equal Predicates P2,P3:
5564
5565 // It is possible that the predicates P2 and/or P3 are computable at
5566 // compile time due to StartVal and/or Accum being constants.
5567 // If either one is, then we can check that now and escape if either P2
5568 // or P3 is false.
5569
5570 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5571 // for each of StartVal and Accum
5572 auto getExtendedExpr = [&](const SCEV *Expr,
5573 bool CreateSignExtend) -> const SCEV * {
5574 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5575 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5576 const SCEV *ExtendedExpr =
5577 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5578 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5579 return ExtendedExpr;
5580 };
5581
5582 // Given:
5583 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5584 // = getExtendedExpr(Expr)
5585 // Determine whether the predicate P: Expr == ExtendedExpr
5586 // is known to be false at compile time
5587 auto PredIsKnownFalse = [&](const SCEV *Expr,
5588 const SCEV *ExtendedExpr) -> bool {
5589 return Expr != ExtendedExpr &&
5590 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5591 };
5592
5593 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5594 if (PredIsKnownFalse(StartVal, StartExtended)) {
5595 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5596 return std::nullopt;
5597 }
5598
5599 // The Step is always Signed (because the overflow checks are either
5600 // NSSW or NUSW)
5601 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5602 if (PredIsKnownFalse(Accum, AccumExtended)) {
5603 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5604 return std::nullopt;
5605 }
5606
5607 auto AppendPredicate = [&](const SCEV *Expr,
5608 const SCEV *ExtendedExpr) -> void {
5609 if (Expr != ExtendedExpr &&
5610 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5611 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5612 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5613 Predicates.push_back(Pred);
5614 }
5615 };
5616
5617 AppendPredicate(StartVal, StartExtended);
5618 AppendPredicate(Accum, AccumExtended);
5619
5620 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5621 // which the casts had been folded away. The caller can rewrite SymbolicPHI
5622 // into NewAR if it will also add the runtime overflow checks specified in
5623 // Predicates.
5624 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5625
5626 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5627 std::make_pair(NewAR, Predicates);
5628 // Remember the result of the analysis for this SCEV at this locayyytion.
5629 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5630 return PredRewrite;
5631}
5632
5633std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5635 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5636 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5637 if (!L)
5638 return std::nullopt;
5639
5640 // Check to see if we already analyzed this PHI.
5641 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5642 if (I != PredicatedSCEVRewrites.end()) {
5643 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5644 I->second;
5645 // Analysis was done before and failed to create an AddRec:
5646 if (Rewrite.first == SymbolicPHI)
5647 return std::nullopt;
5648 // Analysis was done before and succeeded to create an AddRec under
5649 // a predicate:
5650 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5651 assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5652 return Rewrite;
5653 }
5654
5655 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5656 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5657
5658 // Record in the cache that the analysis failed
5659 if (!Rewrite) {
5661 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5662 return std::nullopt;
5663 }
5664
5665 return Rewrite;
5666}
5667
5668// FIXME: This utility is currently required because the Rewriter currently
5669// does not rewrite this expression:
5670// {0, +, (sext ix (trunc iy to ix) to iy)}
5671// into {0, +, %step},
5672// even when the following Equal predicate exists:
5673// "%step == (sext ix (trunc iy to ix) to iy)".
5675 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2,
5676 ArrayRef<const SCEVPredicate *> NoWrapPreds) const {
5677 if (AR1 == AR2)
5678 return true;
5679
5680 SCEVUnionPredicate NoWrapUnionPred(NoWrapPreds, SE);
5681 SCEVUnionPredicate AllPreds = Preds->getUnionWith(&NoWrapUnionPred, SE);
5682 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5683 if (Expr1 != Expr2 &&
5684 !AllPreds.implies(SE.getEqualPredicate(Expr1, Expr2), SE) &&
5685 !AllPreds.implies(SE.getEqualPredicate(Expr2, Expr1), SE))
5686 return false;
5687 return true;
5688 };
5689
5690 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5691 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5692 return false;
5693 return true;
5694}
5695
5696static SCEV::NoWrapFlags
5699 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
5700 // If the increment has any nowrap flags, then we know the address
5701 // space cannot be wrapped around.
5702 if (NW != GEPNoWrapFlags::none())
5704 // If the GEP is nuw or nusw with non-negative offset, we know that
5705 // no unsigned wrap occurs. We cannot set the nsw flag as only the
5706 // offset is treated as signed, while the base is unsigned.
5707 if (NW.hasNoUnsignedWrap() ||
5708 (NW.hasNoUnsignedSignedWrap() && SE.isKnownNonNegative(Accum)))
5710
5711 return Flags;
5712}
5713
5714/// A helper function for createAddRecFromPHI to handle simple cases.
5715///
5716/// This function tries to find an AddRec expression for the simplest (yet most
5717/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5718/// If it fails, createAddRecFromPHI will use a more general, but slow,
5719/// technique for finding the AddRec expression.
5720const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5721 Value *BEValueV,
5722 Value *StartValueV) {
5723 const Loop *L = LI.getLoopFor(PN->getParent());
5724 assert(L && L->getHeader() == PN->getParent());
5725 assert(BEValueV && StartValueV);
5726
5727 const SCEV *Accum = nullptr;
5729 if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
5730 if (BO->Opcode != Instruction::Add)
5731 return nullptr;
5732
5733 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5734 Accum = getSCEV(BO->RHS);
5735 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5736 Accum = getSCEV(BO->LHS);
5737
5738 if (!Accum)
5739 return nullptr;
5740
5741 if (BO->IsNUW)
5742 Flags = setFlags(Flags, SCEV::FlagNUW);
5743 if (BO->IsNSW)
5744 Flags = setFlags(Flags, SCEV::FlagNSW);
5745 } else {
5746 // Handle pointer induction variable: PN = PHI(Start, gep PN,
5747 // LoopInvariant).
5748 auto *GEP = dyn_cast<GEPOperator>(BEValueV);
5749 if (!GEP || GEP->getPointerOperand() != PN || GEP->getNumIndices() != 1)
5750 return nullptr;
5751 Value *Idx = *GEP->idx_begin();
5752 if (!L->isLoopInvariant(Idx))
5753 return nullptr;
5754
5755 Type *IntIdxTy = getEffectiveSCEVType(GEP->getType());
5756 Accum = getMulExpr(getTruncateOrSignExtend(getSCEV(Idx), IntIdxTy),
5757 getSizeOfExpr(IntIdxTy, GEP->getSourceElementType()));
5758 Flags = getNoWrapFlagsForGEP(GEP, Accum, *this);
5759 }
5760
5761 const SCEV *StartVal = getSCEV(StartValueV);
5762 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5763 insertValueToMap(PN, PHISCEV);
5764
5765 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5766 inferNoWrapViaConstantRanges(AR);
5767
5768 // We can add Flags to the post-inc expression only if we
5769 // know that it is *undefined behavior* for BEValueV to
5770 // overflow.
5771 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5772 assert(isLoopInvariant(Accum, L) &&
5773 "Accum is defined outside L, but is not invariant?");
5774 if (isAddRecNeverPoison(BEInst, L))
5775 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5776 }
5777
5778 return PHISCEV;
5779}
5780
5781const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5782 const Loop *L = LI.getLoopFor(PN->getParent());
5783 if (!L || L->getHeader() != PN->getParent())
5784 return nullptr;
5785
5786 // The loop may have multiple entrances or multiple exits; we can analyze
5787 // this phi as an addrec if it has a unique entry value and a unique
5788 // backedge value.
5789 Value *BEValueV = nullptr, *StartValueV = nullptr;
5790 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5791 Value *V = PN->getIncomingValue(i);
5792 if (L->contains(PN->getIncomingBlock(i))) {
5793 if (!BEValueV) {
5794 BEValueV = V;
5795 } else if (BEValueV != V) {
5796 BEValueV = nullptr;
5797 break;
5798 }
5799 } else if (!StartValueV) {
5800 StartValueV = V;
5801 } else if (StartValueV != V) {
5802 StartValueV = nullptr;
5803 break;
5804 }
5805 }
5806 if (!BEValueV || !StartValueV)
5807 return nullptr;
5808
5809 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5810 "PHI node already processed?");
5811
5812 // First, try to find AddRec expression without creating a fictituos symbolic
5813 // value for PN.
5814 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5815 return S;
5816
5817 // Handle PHI node value symbolically.
5818 const SCEV *SymbolicName = getUnknown(PN);
5819 insertValueToMap(PN, SymbolicName);
5820
5821 // Using this symbolic name for the PHI, analyze the value coming around
5822 // the back-edge.
5823 const SCEV *BEValue = getSCEV(BEValueV);
5824
5825 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5826 // has a special value for the first iteration of the loop.
5827
5828 // If the value coming around the backedge is an add with the symbolic
5829 // value we just inserted, then we found a simple induction variable!
5830 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5831 // If there is a single occurrence of the symbolic value, replace it
5832 // with a recurrence.
5833 unsigned FoundIndex = Add->getNumOperands();
5834 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5835 if (Add->getOperand(i) == SymbolicName)
5836 if (FoundIndex == e) {
5837 FoundIndex = i;
5838 break;
5839 }
5840
5841 if (FoundIndex != Add->getNumOperands()) {
5842 // Create an add with everything but the specified operand.
5844 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5845 if (i != FoundIndex)
5846 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5847 L, *this));
5848 const SCEV *Accum = getAddExpr(Ops);
5849
5850 // This is not a valid addrec if the step amount is varying each
5851 // loop iteration, but is not itself an addrec in this loop.
5852 if (isLoopInvariant(Accum, L) ||
5853 (isa<SCEVAddRecExpr>(Accum) &&
5854 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5856
5857 if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
5858 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5859 if (BO->IsNUW)
5860 Flags = setFlags(Flags, SCEV::FlagNUW);
5861 if (BO->IsNSW)
5862 Flags = setFlags(Flags, SCEV::FlagNSW);
5863 }
5864 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5865 if (GEP->getOperand(0) == PN)
5866 Flags = getNoWrapFlagsForGEP(GEP, Accum, *this);
5867
5868 // We cannot transfer nuw and nsw flags from subtraction
5869 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5870 // for instance.
5871 }
5872
5873 const SCEV *StartVal = getSCEV(StartValueV);
5874 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5875
5876 // Okay, for the entire analysis of this edge we assumed the PHI
5877 // to be symbolic. We now need to go back and purge all of the
5878 // entries for the scalars that use the symbolic expression.
5879 forgetMemoizedResults({SymbolicName});
5880 insertValueToMap(PN, PHISCEV);
5881
5882 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5883 inferNoWrapViaConstantRanges(AR);
5884
5885 // We can add Flags to the post-inc expression only if we
5886 // know that it is *undefined behavior* for BEValueV to
5887 // overflow.
5888 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5889 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5890 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5891
5892 return PHISCEV;
5893 }
5894 }
5895 } else {
5896 // Otherwise, this could be a loop like this:
5897 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5898 // In this case, j = {1,+,1} and BEValue is j.
5899 // Because the other in-value of i (0) fits the evolution of BEValue
5900 // i really is an addrec evolution.
5901 //
5902 // We can generalize this saying that i is the shifted value of BEValue
5903 // by one iteration:
5904 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5905
5906 // Do not allow refinement in rewriting of BEValue.
5907 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5908 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5909 if (Shifted != getCouldNotCompute() && Start != getCouldNotCompute() &&
5910 isGuaranteedNotToCauseUB(Shifted) && ::impliesPoison(Shifted, Start)) {
5911 const SCEV *StartVal = getSCEV(StartValueV);
5912 if (Start == StartVal) {
5913 // Okay, for the entire analysis of this edge we assumed the PHI
5914 // to be symbolic. We now need to go back and purge all of the
5915 // entries for the scalars that use the symbolic expression.
5916 forgetMemoizedResults({SymbolicName});
5917 insertValueToMap(PN, Shifted);
5918 return Shifted;
5919 }
5920 }
5921 }
5922
5923 // Remove the temporary PHI node SCEV that has been inserted while intending
5924 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5925 // as it will prevent later (possibly simpler) SCEV expressions to be added
5926 // to the ValueExprMap.
5927 eraseValueFromMap(PN);
5928
5929 return nullptr;
5930}
5931
5932// Try to match a control flow sequence that branches out at BI and merges back
5933// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5934// match.
5936 Value *&C, Value *&LHS, Value *&RHS) {
5937 C = BI->getCondition();
5938
5939 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5940 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5941
5942 Use &LeftUse = Merge->getOperandUse(0);
5943 Use &RightUse = Merge->getOperandUse(1);
5944
5945 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5946 LHS = LeftUse;
5947 RHS = RightUse;
5948 return true;
5949 }
5950
5951 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5952 LHS = RightUse;
5953 RHS = LeftUse;
5954 return true;
5955 }
5956
5957 return false;
5958}
5959
5961 Value *&Cond, Value *&LHS,
5962 Value *&RHS) {
5963 auto IsReachable =
5964 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5965 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5966 // Try to match
5967 //
5968 // br %cond, label %left, label %right
5969 // left:
5970 // br label %merge
5971 // right:
5972 // br label %merge
5973 // merge:
5974 // V = phi [ %x, %left ], [ %y, %right ]
5975 //
5976 // as "select %cond, %x, %y"
5977
5978 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5979 assert(IDom && "At least the entry block should dominate PN");
5980
5981 auto *BI = dyn_cast<CondBrInst>(IDom->getTerminator());
5982 return BI && BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS);
5983 }
5984 return false;
5985}
5986
5987const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5988 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5989 if (getOperandsForSelectLikePHI(DT, PN, Cond, LHS, RHS) &&
5992 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5993
5994 return nullptr;
5995}
5996
5998 BinaryOperator *CommonInst = nullptr;
5999 // Check if instructions are identical.
6000 for (Value *Incoming : PN->incoming_values()) {
6001 auto *IncomingInst = dyn_cast<BinaryOperator>(Incoming);
6002 if (!IncomingInst)
6003 return nullptr;
6004 if (CommonInst) {
6005 if (!CommonInst->isIdenticalToWhenDefined(IncomingInst))
6006 return nullptr; // Not identical, give up
6007 } else {
6008 // Remember binary operator
6009 CommonInst = IncomingInst;
6010 }
6011 }
6012 return CommonInst;
6013}
6014
6015/// Returns SCEV for the first operand of a phi if all phi operands have
6016/// identical opcodes and operands
6017/// eg.
6018/// a: %add = %a + %b
6019/// br %c
6020/// b: %add1 = %a + %b
6021/// br %c
6022/// c: %phi = phi [%add, a], [%add1, b]
6023/// scev(%phi) => scev(%add)
6024const SCEV *
6025ScalarEvolution::createNodeForPHIWithIdenticalOperands(PHINode *PN) {
6026 BinaryOperator *CommonInst = getCommonInstForPHI(PN);
6027 if (!CommonInst)
6028 return nullptr;
6029
6030 // Check if SCEV exprs for instructions are identical.
6031 const SCEV *CommonSCEV = getSCEV(CommonInst);
6032 bool SCEVExprsIdentical =
6034 [this, CommonSCEV](Value *V) { return CommonSCEV == getSCEV(V); });
6035 return SCEVExprsIdentical ? CommonSCEV : nullptr;
6036}
6037
6038const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
6039 if (const SCEV *S = createAddRecFromPHI(PN))
6040 return S;
6041
6042 // We do not allow simplifying phi (undef, X) to X here, to avoid reusing the
6043 // phi node for X.
6044 if (Value *V = simplifyInstruction(
6045 PN, {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
6046 /*UseInstrInfo=*/true, /*CanUseUndef=*/false}))
6047 return getSCEV(V);
6048
6049 if (const SCEV *S = createNodeForPHIWithIdenticalOperands(PN))
6050 return S;
6051
6052 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
6053 return S;
6054
6055 // If it's not a loop phi, we can't handle it yet.
6056 return getUnknown(PN);
6057}
6058
6059bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
6060 SCEVTypes RootKind) {
6061 struct FindClosure {
6062 const SCEV *OperandToFind;
6063 const SCEVTypes RootKind; // Must be a sequential min/max expression.
6064 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
6065
6066 bool Found = false;
6067
6068 bool canRecurseInto(SCEVTypes Kind) const {
6069 // We can only recurse into the SCEV expression of the same effective type
6070 // as the type of our root SCEV expression, and into zero-extensions.
6071 return RootKind == Kind || NonSequentialRootKind == Kind ||
6072 scZeroExtend == Kind;
6073 };
6074
6075 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
6076 : OperandToFind(OperandToFind), RootKind(RootKind),
6077 NonSequentialRootKind(
6079 RootKind)) {}
6080
6081 bool follow(const SCEV *S) {
6082 Found = S == OperandToFind;
6083
6084 return !isDone() && canRecurseInto(S->getSCEVType());
6085 }
6086
6087 bool isDone() const { return Found; }
6088 };
6089
6090 FindClosure FC(OperandToFind, RootKind);
6091 visitAll(Root, FC);
6092 return FC.Found;
6093}
6094
6095std::optional<const SCEV *>
6096ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
6097 ICmpInst *Cond,
6098 Value *TrueVal,
6099 Value *FalseVal) {
6100 // Try to match some simple smax or umax patterns.
6101 auto *ICI = Cond;
6102
6103 Value *LHS = ICI->getOperand(0);
6104 Value *RHS = ICI->getOperand(1);
6105
6106 switch (ICI->getPredicate()) {
6107 case ICmpInst::ICMP_SLT:
6108 case ICmpInst::ICMP_SLE:
6109 case ICmpInst::ICMP_ULT:
6110 case ICmpInst::ICMP_ULE:
6111 std::swap(LHS, RHS);
6112 [[fallthrough]];
6113 case ICmpInst::ICMP_SGT:
6114 case ICmpInst::ICMP_SGE:
6115 case ICmpInst::ICMP_UGT:
6116 case ICmpInst::ICMP_UGE:
6117 // a > b ? a+x : b+x -> max(a, b)+x
6118 // a > b ? b+x : a+x -> min(a, b)+x
6120 bool Signed = ICI->isSigned();
6121 const SCEV *LA = getSCEV(TrueVal);
6122 const SCEV *RA = getSCEV(FalseVal);
6123 const SCEV *LS = getSCEV(LHS);
6124 const SCEV *RS = getSCEV(RHS);
6125 if (LA->getType()->isPointerTy()) {
6126 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6127 // Need to make sure we can't produce weird expressions involving
6128 // negated pointers.
6129 if (LA == LS && RA == RS)
6130 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6131 if (LA == RS && RA == LS)
6132 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6133 }
6134 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6135 if (Op->getType()->isPointerTy()) {
6138 return Op;
6139 }
6140 if (Signed)
6141 Op = getNoopOrSignExtend(Op, Ty);
6142 else
6143 Op = getNoopOrZeroExtend(Op, Ty);
6144 return Op;
6145 };
6146 LS = CoerceOperand(LS);
6147 RS = CoerceOperand(RS);
6149 break;
6150 const SCEV *LDiff = getMinusSCEV(LA, LS);
6151 const SCEV *RDiff = getMinusSCEV(RA, RS);
6152 if (LDiff == RDiff)
6153 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6154 LDiff);
6155 LDiff = getMinusSCEV(LA, RS);
6156 RDiff = getMinusSCEV(RA, LS);
6157 if (LDiff == RDiff)
6158 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6159 LDiff);
6160 }
6161 break;
6162 case ICmpInst::ICMP_NE:
6163 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
6164 std::swap(TrueVal, FalseVal);
6165 [[fallthrough]];
6166 case ICmpInst::ICMP_EQ:
6167 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
6170 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6171 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y
6172 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y
6173 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6174 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y
6175 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6176 return getAddExpr(getUMaxExpr(X, C), Y);
6177 }
6178 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
6179 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
6180 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
6181 // -> umin_seq(x, umin (..., umin_seq(...), ...))
6183 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6184 const SCEV *X = getSCEV(LHS);
6185 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6186 X = ZExt->getOperand();
6187 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6188 const SCEV *FalseValExpr = getSCEV(FalseVal);
6189 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6190 return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6191 /*Sequential=*/true);
6192 }
6193 }
6194 break;
6195 default:
6196 break;
6197 }
6198
6199 return std::nullopt;
6200}
6201
6202static std::optional<const SCEV *>
6204 const SCEV *TrueExpr, const SCEV *FalseExpr) {
6205 assert(CondExpr->getType()->isIntegerTy(1) &&
6206 TrueExpr->getType() == FalseExpr->getType() &&
6207 TrueExpr->getType()->isIntegerTy(1) &&
6208 "Unexpected operands of a select.");
6209
6210 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
6211 // --> C + (umin_seq cond, x - C)
6212 //
6213 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
6214 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6215 // --> C + (umin_seq ~cond, x - C)
6216
6217 // FIXME: while we can't legally model the case where both of the hands
6218 // are fully variable, we only require that the *difference* is constant.
6219 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6220 return std::nullopt;
6221
6222 const SCEV *X, *C;
6223 if (isa<SCEVConstant>(TrueExpr)) {
6224 CondExpr = SE->getNotSCEV(CondExpr);
6225 X = FalseExpr;
6226 C = TrueExpr;
6227 } else {
6228 X = TrueExpr;
6229 C = FalseExpr;
6230 }
6231 return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6232 /*Sequential=*/true));
6233}
6234
6235static std::optional<const SCEV *>
6237 Value *FalseVal) {
6238 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6239 return std::nullopt;
6240
6241 const auto *SECond = SE->getSCEV(Cond);
6242 const auto *SETrue = SE->getSCEV(TrueVal);
6243 const auto *SEFalse = SE->getSCEV(FalseVal);
6244 return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6245}
6246
6247const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6248 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6249 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6250 assert(TrueVal->getType() == FalseVal->getType() &&
6251 V->getType() == TrueVal->getType() &&
6252 "Types of select hands and of the result must match.");
6253
6254 // For now, only deal with i1-typed `select`s.
6255 if (!V->getType()->isIntegerTy(1))
6256 return getUnknown(V);
6257
6258 if (std::optional<const SCEV *> S =
6259 createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6260 return *S;
6261
6262 return getUnknown(V);
6263}
6264
6265const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6266 Value *TrueVal,
6267 Value *FalseVal) {
6268 // Handle "constant" branch or select. This can occur for instance when a
6269 // loop pass transforms an inner loop and moves on to process the outer loop.
6270 if (auto *CI = dyn_cast<ConstantInt>(Cond))
6271 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6272
6273 if (auto *I = dyn_cast<Instruction>(V)) {
6274 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6275 if (std::optional<const SCEV *> S =
6276 createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6277 TrueVal, FalseVal))
6278 return *S;
6279 }
6280 }
6281
6282 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6283}
6284
6285/// Expand GEP instructions into add and multiply operations. This allows them
6286/// to be analyzed by regular SCEV code.
6287const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6288 assert(GEP->getSourceElementType()->isSized() &&
6289 "GEP source element type must be sized");
6290
6291 SmallVector<SCEVUse, 4> IndexExprs;
6292 for (Value *Index : GEP->indices())
6293 IndexExprs.push_back(getSCEV(Index));
6294 return getGEPExpr(GEP, IndexExprs);
6295}
6296
6297APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S,
6298 const Instruction *CtxI) {
6300 auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6301 return TrailingZeros >= BitWidth
6303 : APInt::getOneBitSet(BitWidth, TrailingZeros);
6304 };
6305 auto GetGCDMultiple = [this, CtxI](const SCEVNAryExpr *N) {
6306 // The result is GCD of all operands results.
6307 APInt Res = getConstantMultiple(N->getOperand(0), CtxI);
6308 for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6310 Res, getConstantMultiple(N->getOperand(I), CtxI));
6311 return Res;
6312 };
6313
6314 switch (S->getSCEVType()) {
6315 case scConstant:
6316 return cast<SCEVConstant>(S)->getAPInt();
6317 case scPtrToAddr:
6318 return getConstantMultiple(cast<SCEVCastExpr>(S)->getOperand());
6319 case scUDivExpr:
6320 case scVScale:
6321 return APInt(BitWidth, 1);
6322 case scTruncate: {
6323 // Only multiples that are a power of 2 will hold after truncation.
6324 const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6325 uint32_t TZ = getMinTrailingZeros(T->getOperand(), CtxI);
6326 return GetShiftedByZeros(TZ);
6327 }
6328 case scZeroExtend: {
6329 const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(S);
6330 return getConstantMultiple(Z->getOperand(), CtxI).zext(BitWidth);
6331 }
6332 case scSignExtend: {
6333 // Only multiples that are a power of 2 will hold after sext.
6334 const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6335 uint32_t TZ = getMinTrailingZeros(E->getOperand(), CtxI);
6336 return GetShiftedByZeros(TZ);
6337 }
6338 case scMulExpr: {
6339 const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6340 if (M->hasNoUnsignedWrap()) {
6341 // The result is the product of all operand results.
6342 APInt Res = getConstantMultiple(M->getOperand(0), CtxI);
6343 for (const SCEV *Operand : M->operands().drop_front())
6344 Res = Res * getConstantMultiple(Operand, CtxI);
6345 return Res;
6346 }
6347
6348 // If there are no wrap guarentees, find the trailing zeros, which is the
6349 // sum of trailing zeros for all its operands.
6350 uint32_t TZ = 0;
6351 for (const SCEV *Operand : M->operands())
6352 TZ += getMinTrailingZeros(Operand, CtxI);
6353 return GetShiftedByZeros(TZ);
6354 }
6355 case scAddExpr:
6356 case scAddRecExpr: {
6357 const SCEVNAryExpr *N = cast<SCEVNAryExpr>(S);
6358 if (N->hasNoUnsignedWrap())
6359 return GetGCDMultiple(N);
6360 // Find the trailing bits, which is the minimum of its operands.
6361 uint32_t TZ = getMinTrailingZeros(N->getOperand(0), CtxI);
6362 for (const SCEV *Operand : N->operands().drop_front())
6363 TZ = std::min(TZ, getMinTrailingZeros(Operand, CtxI));
6364 return GetShiftedByZeros(TZ);
6365 }
6366 case scUMaxExpr:
6367 case scSMaxExpr:
6368 case scUMinExpr:
6369 case scSMinExpr:
6371 return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6372 case scUnknown: {
6373 // Ask ValueTracking for known bits. SCEVUnknown only become available at
6374 // the point their underlying IR instruction has been defined. If CtxI was
6375 // not provided, use:
6376 // * the first instruction in the entry block if it is an argument
6377 // * the instruction itself otherwise.
6378 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6379 if (!CtxI) {
6380 if (isa<Argument>(U->getValue()))
6381 CtxI = &*F.getEntryBlock().begin();
6382 else if (auto *I = dyn_cast<Instruction>(U->getValue()))
6383 CtxI = I;
6384 }
6385 unsigned Known =
6386 computeKnownBits(U->getValue(),
6387 SimplifyQuery(getDataLayout(), &DT, &AC, CtxI)
6388 .allowEphemerals(true))
6389 .countMinTrailingZeros();
6390 return GetShiftedByZeros(Known);
6391 }
6392 case scCouldNotCompute:
6393 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6394 }
6395 llvm_unreachable("Unknown SCEV kind!");
6396}
6397
6399 const Instruction *CtxI) {
6400 // Skip looking up and updating the cache if there is a context instruction,
6401 // as the result will only be valid in the specified context.
6402 if (CtxI)
6403 return getConstantMultipleImpl(S, CtxI);
6404
6405 auto I = ConstantMultipleCache.find(S);
6406 if (I != ConstantMultipleCache.end())
6407 return I->second;
6408
6409 APInt Result = getConstantMultipleImpl(S, CtxI);
6410 auto InsertPair = ConstantMultipleCache.insert({S, Result});
6411 assert(InsertPair.second && "Should insert a new key");
6412 return InsertPair.first->second;
6413}
6414
6416 APInt Multiple = getConstantMultiple(S);
6417 return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6418}
6419
6421 const Instruction *CtxI) {
6422 return std::min(getConstantMultiple(S, CtxI).countTrailingZeros(),
6423 (unsigned)getTypeSizeInBits(S->getType()));
6424}
6425
6426/// Helper method to assign a range to V from metadata present in the IR.
6427static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6429 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6430 return getConstantRangeFromMetadata(*MD);
6431 if (const auto *CB = dyn_cast<CallBase>(V))
6432 if (std::optional<ConstantRange> Range = CB->getRange())
6433 return Range;
6434 }
6435 if (auto *A = dyn_cast<Argument>(V))
6436 if (std::optional<ConstantRange> Range = A->getRange())
6437 return Range;
6438
6439 return std::nullopt;
6440}
6441
6443 SCEV::NoWrapFlags Flags) {
6444 if (AddRec->getNoWrapFlags(Flags) != Flags) {
6445 AddRec->setNoWrapFlags(Flags);
6446 UnsignedRanges.erase(AddRec);
6447 SignedRanges.erase(AddRec);
6448 ConstantMultipleCache.erase(AddRec);
6449 }
6450}
6451
6452ConstantRange ScalarEvolution::
6453getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6454 const DataLayout &DL = getDataLayout();
6455
6456 unsigned BitWidth = getTypeSizeInBits(U->getType());
6457 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6458
6459 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6460 // use information about the trip count to improve our available range. Note
6461 // that the trip count independent cases are already handled by known bits.
6462 // WARNING: The definition of recurrence used here is subtly different than
6463 // the one used by AddRec (and thus most of this file). Step is allowed to
6464 // be arbitrarily loop varying here, where AddRec allows only loop invariant
6465 // and other addrecs in the same loop (for non-affine addrecs). The code
6466 // below intentionally handles the case where step is not loop invariant.
6467 auto *P = dyn_cast<PHINode>(U->getValue());
6468 if (!P)
6469 return FullSet;
6470
6471 // Make sure that no Phi input comes from an unreachable block. Otherwise,
6472 // even the values that are not available in these blocks may come from them,
6473 // and this leads to false-positive recurrence test.
6474 for (auto *Pred : predecessors(P->getParent()))
6475 if (!DT.isReachableFromEntry(Pred))
6476 return FullSet;
6477
6478 BinaryOperator *BO;
6479 Value *Start, *Step;
6480 if (!matchSimpleRecurrence(P, BO, Start, Step))
6481 return FullSet;
6482
6483 // If we found a recurrence in reachable code, we must be in a loop. Note
6484 // that BO might be in some subloop of L, and that's completely okay.
6485 auto *L = LI.getLoopFor(P->getParent());
6486 assert(L && L->getHeader() == P->getParent());
6487 if (!L->contains(BO->getParent()))
6488 // NOTE: This bailout should be an assert instead. However, asserting
6489 // the condition here exposes a case where LoopFusion is querying SCEV
6490 // with malformed loop information during the midst of the transform.
6491 // There doesn't appear to be an obvious fix, so for the moment bailout
6492 // until the caller issue can be fixed. PR49566 tracks the bug.
6493 return FullSet;
6494
6495 // TODO: Extend to other opcodes such as mul, and div
6496 switch (BO->getOpcode()) {
6497 default:
6498 return FullSet;
6499 case Instruction::AShr:
6500 case Instruction::LShr:
6501 case Instruction::Shl:
6502 break;
6503 };
6504
6505 if (BO->getOperand(0) != P)
6506 // TODO: Handle the power function forms some day.
6507 return FullSet;
6508
6509 unsigned TC = getSmallConstantMaxTripCount(L);
6510 if (!TC || TC >= BitWidth)
6511 return FullSet;
6512
6513 auto KnownStart = computeKnownBits(Start, DL, &AC, nullptr, &DT);
6514 auto KnownStep = computeKnownBits(Step, DL, &AC, nullptr, &DT);
6515 assert(KnownStart.getBitWidth() == BitWidth &&
6516 KnownStep.getBitWidth() == BitWidth);
6517
6518 // Compute total shift amount, being careful of overflow and bitwidths.
6519 auto MaxShiftAmt = KnownStep.getMaxValue();
6520 APInt TCAP(BitWidth, TC-1);
6521 bool Overflow = false;
6522 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6523 if (Overflow)
6524 return FullSet;
6525
6526 switch (BO->getOpcode()) {
6527 default:
6528 llvm_unreachable("filtered out above");
6529 case Instruction::AShr: {
6530 // For each ashr, three cases:
6531 // shift = 0 => unchanged value
6532 // saturation => 0 or -1
6533 // other => a value closer to zero (of the same sign)
6534 // Thus, the end value is closer to zero than the start.
6535 auto KnownEnd = KnownBits::ashr(KnownStart,
6536 KnownBits::makeConstant(TotalShift));
6537 if (KnownStart.isNonNegative())
6538 // Analogous to lshr (simply not yet canonicalized)
6539 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6540 KnownStart.getMaxValue() + 1);
6541 if (KnownStart.isNegative())
6542 // End >=u Start && End <=s Start
6543 return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6544 KnownEnd.getMaxValue() + 1);
6545 break;
6546 }
6547 case Instruction::LShr: {
6548 // For each lshr, three cases:
6549 // shift = 0 => unchanged value
6550 // saturation => 0
6551 // other => a smaller positive number
6552 // Thus, the low end of the unsigned range is the last value produced.
6553 auto KnownEnd = KnownBits::lshr(KnownStart,
6554 KnownBits::makeConstant(TotalShift));
6555 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6556 KnownStart.getMaxValue() + 1);
6557 }
6558 case Instruction::Shl: {
6559 // Iff no bits are shifted out, value increases on every shift.
6560 auto KnownEnd = KnownBits::shl(KnownStart,
6561 KnownBits::makeConstant(TotalShift));
6562 if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6563 return ConstantRange(KnownStart.getMinValue(),
6564 KnownEnd.getMaxValue() + 1);
6565 break;
6566 }
6567 };
6568 return FullSet;
6569}
6570
6571// The goal of this function is to check if recursively visiting the operands
6572// of this PHI might lead to an infinite loop. If we do see such a loop,
6573// there's no good way to break it, so we avoid analyzing such cases.
6574//
6575// getRangeRef previously used a visited set to avoid infinite loops, but this
6576// caused other issues: the result was dependent on the order of getRangeRef
6577// calls, and the interaction with createSCEVIter could cause a stack overflow
6578// in some cases (see issue #148253).
6579//
6580// FIXME: The way this is implemented is overly conservative; this checks
6581// for a few obviously safe patterns, but anything that doesn't lead to
6582// recursion is fine.
6584 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6586 return true;
6587
6588 if (all_of(PHI->operands(),
6589 [&](Value *Operand) { return DT.dominates(Operand, PHI); }))
6590 return true;
6591
6592 return false;
6593}
6594
6595const ConstantRange &
6596ScalarEvolution::getRangeRefIter(const SCEV *S,
6597 ScalarEvolution::RangeSignHint SignHint) {
6598 DenseMap<const SCEV *, ConstantRange> &Cache =
6599 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6600 : SignedRanges;
6601 SmallVector<SCEVUse> WorkList;
6602 SmallPtrSet<const SCEV *, 8> Seen;
6603
6604 // Add Expr to the worklist, if Expr is either an N-ary expression or a
6605 // SCEVUnknown PHI node.
6606 auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6607 if (!Seen.insert(Expr).second)
6608 return;
6609 if (Cache.contains(Expr))
6610 return;
6611 switch (Expr->getSCEVType()) {
6612 case scUnknown:
6614 break;
6615 [[fallthrough]];
6616 case scConstant:
6617 case scVScale:
6618 case scTruncate:
6619 case scZeroExtend:
6620 case scSignExtend:
6621 case scPtrToAddr:
6622 case scAddExpr:
6623 case scMulExpr:
6624 case scUDivExpr:
6625 case scAddRecExpr:
6626 case scUMaxExpr:
6627 case scSMaxExpr:
6628 case scUMinExpr:
6629 case scSMinExpr:
6631 WorkList.push_back(Expr);
6632 break;
6633 case scCouldNotCompute:
6634 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6635 }
6636 };
6637 AddToWorklist(S);
6638
6639 // Build worklist by queuing operands of N-ary expressions and phi nodes.
6640 for (unsigned I = 0; I != WorkList.size(); ++I) {
6641 const SCEV *P = WorkList[I];
6642 auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6643 // If it is not a `SCEVUnknown`, just recurse into operands.
6644 if (!UnknownS) {
6645 for (const SCEV *Op : P->operands())
6646 AddToWorklist(Op);
6647 continue;
6648 }
6649 // `SCEVUnknown`'s require special treatment.
6650 if (PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6651 if (!RangeRefPHIAllowedOperands(DT, P))
6652 continue;
6653 for (auto &Op : reverse(P->operands()))
6654 AddToWorklist(getSCEV(Op));
6655 }
6656 }
6657
6658 if (!WorkList.empty()) {
6659 // Use getRangeRef to compute ranges for items in the worklist in reverse
6660 // order. This will force ranges for earlier operands to be computed before
6661 // their users in most cases.
6662 for (const SCEV *P : reverse(drop_begin(WorkList))) {
6663 getRangeRef(P, SignHint);
6664 }
6665 }
6666
6667 return getRangeRef(S, SignHint, 0);
6668}
6669
6670const APInt *ScalarEvolution::getConstantAPIntOrNull(const SCEV *S) {
6671 if (const auto *C = dyn_cast<SCEVConstant>(S))
6672 return &C->getAPInt();
6673 return nullptr;
6674}
6675
6676/// Determine the range for a particular SCEV. If SignHint is
6677/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6678/// with a "cleaner" unsigned (resp. signed) representation.
6679const ConstantRange &ScalarEvolution::getRangeRef(
6680 const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6681 DenseMap<const SCEV *, ConstantRange> &Cache =
6682 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6683 : SignedRanges;
6685 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6687
6688 // See if we've computed this range already.
6689 auto I = Cache.find(S);
6690 if (I != Cache.end())
6691 return I->second;
6692
6693 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6694 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6695
6696 // Switch to iteratively computing the range for S, if it is part of a deeply
6697 // nested expression.
6699 return getRangeRefIter(S, SignHint);
6700
6701 unsigned BitWidth = getTypeSizeInBits(S->getType());
6702 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6703 using OBO = OverflowingBinaryOperator;
6704
6705 // If the value has known zeros, the maximum value will have those known zeros
6706 // as well.
6707 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6708 APInt Multiple = getNonZeroConstantMultiple(S);
6709 APInt Remainder = APInt::getMaxValue(BitWidth).urem(Multiple);
6710 if (!Remainder.isZero())
6711 ConservativeResult =
6712 ConstantRange(APInt::getMinValue(BitWidth),
6713 APInt::getMaxValue(BitWidth) - Remainder + 1);
6714 }
6715 else {
6716 uint32_t TZ = getMinTrailingZeros(S);
6717 if (TZ != 0) {
6718 ConservativeResult = ConstantRange(
6720 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6721 }
6722 }
6723
6724 switch (S->getSCEVType()) {
6725 case scConstant:
6726 llvm_unreachable("Already handled above.");
6727 case scVScale:
6728 return setRange(S, SignHint, getVScaleRange(&F, BitWidth));
6729 case scTruncate: {
6730 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6731 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6732 return setRange(
6733 Trunc, SignHint,
6734 ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6735 }
6736 case scZeroExtend: {
6737 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6738 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6739 return setRange(
6740 ZExt, SignHint,
6741 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6742 }
6743 case scSignExtend: {
6744 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6745 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6746 return setRange(
6747 SExt, SignHint,
6748 ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6749 }
6750 case scPtrToAddr: {
6751 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6752 ConstantRange X = getRangeRef(Cast->getOperand(), SignHint, Depth + 1);
6753 return setRange(Cast, SignHint, X);
6754 }
6755 case scAddExpr: {
6756 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6757 // Check if this is a URem pattern: A - (A / B) * B, which is always < B.
6758 const SCEV *URemLHS = nullptr, *URemRHS = nullptr;
6759 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED &&
6760 match(S, m_scev_URem(m_SCEV(URemLHS), m_SCEV(URemRHS), *this))) {
6761 ConstantRange LHSRange = getRangeRef(URemLHS, SignHint, Depth + 1);
6762 ConstantRange RHSRange = getRangeRef(URemRHS, SignHint, Depth + 1);
6763 ConservativeResult =
6764 ConservativeResult.intersectWith(LHSRange.urem(RHSRange), RangeType);
6765 }
6766 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6767 unsigned WrapType = OBO::AnyWrap;
6768 if (Add->hasNoSignedWrap())
6769 WrapType |= OBO::NoSignedWrap;
6770 if (Add->hasNoUnsignedWrap())
6771 WrapType |= OBO::NoUnsignedWrap;
6772 for (const SCEV *Op : drop_begin(Add->operands()))
6773 X = X.addWithNoWrap(getRangeRef(Op, SignHint, Depth + 1), WrapType,
6774 RangeType);
6775 return setRange(Add, SignHint,
6776 ConservativeResult.intersectWith(X, RangeType));
6777 }
6778 case scMulExpr: {
6779 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6780 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6781 for (const SCEV *Op : drop_begin(Mul->operands()))
6782 X = X.multiply(getRangeRef(Op, SignHint, Depth + 1));
6783 return setRange(Mul, SignHint,
6784 ConservativeResult.intersectWith(X, RangeType));
6785 }
6786 case scUDivExpr: {
6787 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6788 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6789 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6790 return setRange(UDiv, SignHint,
6791 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6792 }
6793 case scAddRecExpr: {
6794 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6795 // If there's no unsigned wrap, the value will never be less than its
6796 // initial value.
6797 if (AddRec->hasNoUnsignedWrap()) {
6798 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6799 if (!UnsignedMinValue.isZero())
6800 ConservativeResult = ConservativeResult.intersectWith(
6801 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6802 }
6803
6804 // If there's no signed wrap, and all the operands except initial value have
6805 // the same sign or zero, the value won't ever be:
6806 // 1: smaller than initial value if operands are non negative,
6807 // 2: bigger than initial value if operands are non positive.
6808 // For both cases, value can not cross signed min/max boundary.
6809 if (AddRec->hasNoSignedWrap()) {
6810 bool AllNonNeg = true;
6811 bool AllNonPos = true;
6812 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6813 if (!isKnownNonNegative(AddRec->getOperand(i)))
6814 AllNonNeg = false;
6815 if (!isKnownNonPositive(AddRec->getOperand(i)))
6816 AllNonPos = false;
6817 }
6818 if (AllNonNeg)
6819 ConservativeResult = ConservativeResult.intersectWith(
6822 RangeType);
6823 else if (AllNonPos)
6824 ConservativeResult = ConservativeResult.intersectWith(
6826 getSignedRangeMax(AddRec->getStart()) +
6827 1),
6828 RangeType);
6829 }
6830
6831 // TODO: non-affine addrec
6832 if (AddRec->isAffine()) {
6833 const SCEV *MaxBEScev =
6835 if (!isa<SCEVCouldNotCompute>(MaxBEScev)) {
6836 APInt MaxBECount = cast<SCEVConstant>(MaxBEScev)->getAPInt();
6837
6838 // Adjust MaxBECount to the same bitwidth as AddRec. We can truncate if
6839 // MaxBECount's active bits are all <= AddRec's bit width.
6840 if (MaxBECount.getBitWidth() > BitWidth &&
6841 MaxBECount.getActiveBits() <= BitWidth)
6842 MaxBECount = MaxBECount.trunc(BitWidth);
6843 else if (MaxBECount.getBitWidth() < BitWidth)
6844 MaxBECount = MaxBECount.zext(BitWidth);
6845
6846 if (MaxBECount.getBitWidth() == BitWidth) {
6847 auto [RangeFromAffine, Flags] = getRangeForAffineAR(
6848 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6849 ConservativeResult =
6850 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6851 const_cast<SCEVAddRecExpr *>(AddRec)->setNoWrapFlags(Flags);
6852
6853 auto RangeFromFactoring = getRangeViaFactoring(
6854 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6855 ConservativeResult =
6856 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6857 }
6858 }
6859
6860 // Now try symbolic BE count and more powerful methods.
6862 const SCEV *SymbolicMaxBECount =
6864 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6865 getTypeSizeInBits(MaxBEScev->getType()) <= BitWidth &&
6866 AddRec->hasNoSelfWrap()) {
6867 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6868 AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6869 ConservativeResult =
6870 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6871 }
6872 }
6873 }
6874
6875 return setRange(AddRec, SignHint, std::move(ConservativeResult));
6876 }
6877 case scUMaxExpr:
6878 case scSMaxExpr:
6879 case scUMinExpr:
6880 case scSMinExpr:
6881 case scSequentialUMinExpr: {
6883 switch (S->getSCEVType()) {
6884 case scUMaxExpr:
6885 ID = Intrinsic::umax;
6886 break;
6887 case scSMaxExpr:
6888 ID = Intrinsic::smax;
6889 break;
6890 case scUMinExpr:
6892 ID = Intrinsic::umin;
6893 break;
6894 case scSMinExpr:
6895 ID = Intrinsic::smin;
6896 break;
6897 default:
6898 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6899 }
6900
6901 const auto *NAry = cast<SCEVNAryExpr>(S);
6902 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
6903 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6904 X = X.intrinsic(
6905 ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
6906 return setRange(S, SignHint,
6907 ConservativeResult.intersectWith(X, RangeType));
6908 }
6909 case scUnknown: {
6910 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6911 Value *V = U->getValue();
6912
6913 // Check if the IR explicitly contains !range metadata.
6914 std::optional<ConstantRange> MDRange = GetRangeFromMetadata(V);
6915 if (MDRange)
6916 ConservativeResult =
6917 ConservativeResult.intersectWith(*MDRange, RangeType);
6918
6919 // Use facts about recurrences in the underlying IR. Note that add
6920 // recurrences are AddRecExprs and thus don't hit this path. This
6921 // primarily handles shift recurrences.
6922 auto CR = getRangeForUnknownRecurrence(U);
6923 ConservativeResult = ConservativeResult.intersectWith(CR);
6924
6925 // See if ValueTracking can give us a useful range.
6926 const DataLayout &DL = getDataLayout();
6927 KnownBits Known = computeKnownBits(V, DL, &AC, nullptr, &DT);
6928 if (Known.getBitWidth() != BitWidth)
6929 Known = Known.zextOrTrunc(BitWidth);
6930
6931 // ValueTracking may be able to compute a tighter result for the number of
6932 // sign bits than for the value of those sign bits.
6933 unsigned NS = ComputeNumSignBits(V, DL, &AC, nullptr, &DT);
6934 if (U->getType()->isPointerTy()) {
6935 // If the pointer size is larger than the index size type, this can cause
6936 // NS to be larger than BitWidth. So compensate for this.
6937 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
6938 int ptrIdxDiff = ptrSize - BitWidth;
6939 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
6940 NS -= ptrIdxDiff;
6941 }
6942
6943 if (NS > 1) {
6944 // If we know any of the sign bits, we know all of the sign bits.
6945 if (!Known.Zero.getHiBits(NS).isZero())
6946 Known.Zero.setHighBits(NS);
6947 if (!Known.One.getHiBits(NS).isZero())
6948 Known.One.setHighBits(NS);
6949 }
6950
6951 if (Known.getMinValue() != Known.getMaxValue() + 1)
6952 ConservativeResult = ConservativeResult.intersectWith(
6953 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6954 RangeType);
6955 if (NS > 1)
6956 ConservativeResult = ConservativeResult.intersectWith(
6957 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6958 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6959 RangeType);
6960
6961 if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
6962 // Strengthen the range if the underlying IR value is a
6963 // global/alloca/heap allocation using the size of the object.
6964 bool CanBeNull;
6965 uint64_t DerefBytes = V->getPointerDereferenceableBytes(
6966 DL, CanBeNull, /*CanBeFreed=*/nullptr);
6967 if (DerefBytes > 1 && isUIntN(BitWidth, DerefBytes)) {
6968 // The highest address the object can start is DerefBytes bytes before
6969 // the end (unsigned max value). If this value is not a multiple of the
6970 // alignment, the last possible start value is the next lowest multiple
6971 // of the alignment. Note: The computations below cannot overflow,
6972 // because if they would there's no possible start address for the
6973 // object.
6974 APInt MaxVal =
6975 APInt::getMaxValue(BitWidth) - APInt(BitWidth, DerefBytes);
6976 uint64_t Align = U->getValue()->getPointerAlignment(DL).value();
6977 uint64_t Rem = MaxVal.urem(Align);
6978 MaxVal -= APInt(BitWidth, Rem);
6979 APInt MinVal = APInt::getZero(BitWidth);
6980 if (llvm::isKnownNonZero(V, DL))
6981 MinVal = Align;
6982 ConservativeResult = ConservativeResult.intersectWith(
6983 ConstantRange::getNonEmpty(MinVal, MaxVal + 1), RangeType);
6984 }
6985 }
6986
6987 // A range of Phi is a subset of union of all ranges of its input.
6988 if (PHINode *Phi = dyn_cast<PHINode>(V)) {
6989 // SCEVExpander sometimes creates SCEVUnknowns that are secretly
6990 // AddRecs; return the range for the corresponding AddRec.
6991 if (auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V)))
6992 return getRangeRef(AR, SignHint, Depth + 1);
6993
6994 // Make sure that we do not run over cycled Phis.
6995 if (RangeRefPHIAllowedOperands(DT, Phi)) {
6996 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6997
6998 for (const auto &Op : Phi->operands()) {
6999 auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
7000 RangeFromOps = RangeFromOps.unionWith(OpRange);
7001 // No point to continue if we already have a full set.
7002 if (RangeFromOps.isFullSet())
7003 break;
7004 }
7005 ConservativeResult =
7006 ConservativeResult.intersectWith(RangeFromOps, RangeType);
7007 }
7008 }
7009
7010 // vscale can't be equal to zero
7011 if (const auto *II = dyn_cast<IntrinsicInst>(V))
7012 if (II->getIntrinsicID() == Intrinsic::vscale) {
7013 ConstantRange Disallowed = APInt::getZero(BitWidth);
7014 ConservativeResult = ConservativeResult.difference(Disallowed);
7015 }
7016
7017 return setRange(U, SignHint, std::move(ConservativeResult));
7018 }
7019 case scCouldNotCompute:
7020 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
7021 }
7022
7023 return setRange(S, SignHint, std::move(ConservativeResult));
7024}
7025
7026// Given a StartRange, Step and MaxBECount for an expression compute a range of
7027// values that the expression can take. Initially, the expression has a value
7028// from StartRange and then is changed by Step up to MaxBECount times. Signed
7029// argument defines if we treat Step as signed or unsigned. The second return
7030// value indicates that no wrapping occurred.
7031static std::pair<ConstantRange, bool>
7033 const APInt &MaxBECount, bool Signed) {
7034 unsigned BitWidth = Step.getBitWidth();
7035 assert(BitWidth == StartRange.getBitWidth() &&
7036 BitWidth == MaxBECount.getBitWidth() && "mismatched bit widths");
7037 // If either Step or MaxBECount is 0, then the expression won't change, and we
7038 // just need to return the initial range.
7039 if (Step == 0 || MaxBECount == 0)
7040 return {StartRange, true};
7041
7042 // If we don't know anything about the initial value (i.e. StartRange is
7043 // FullRange), then we don't know anything about the final range either.
7044 // Return FullRange.
7045 if (StartRange.isFullSet())
7046 return {ConstantRange::getFull(BitWidth), false};
7047
7048 // If Step is signed and negative, then we use its absolute value, but we also
7049 // note that we're moving in the opposite direction.
7050 bool Descending = Signed && Step.isNegative();
7051
7052 if (Signed)
7053 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
7054 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
7055 // This equations hold true due to the well-defined wrap-around behavior of
7056 // APInt.
7057 Step = Step.abs();
7058
7059 // Check if Offset is more than full span of BitWidth. If it is, the
7060 // expression is guaranteed to overflow.
7061 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
7062 return {ConstantRange::getFull(BitWidth), false};
7063
7064 // Offset is by how much the expression can change. Checks above guarantee no
7065 // overflow here.
7066 APInt Offset = Step * MaxBECount;
7067
7068 // Minimum value of the final range will match the minimal value of StartRange
7069 // if the expression is increasing and will be decreased by Offset otherwise.
7070 // Maximum value of the final range will match the maximal value of StartRange
7071 // if the expression is decreasing and will be increased by Offset otherwise.
7072 APInt StartLower = StartRange.getLower();
7073 APInt StartUpper = StartRange.getUpper() - 1;
7074 bool Overflow;
7075 APInt MovedBoundary;
7076 if (Signed) {
7077 // This does not use sadd_ov, as we want to check overflow for a signed
7078 // start with an unsigned offset.
7079 if (Descending) {
7080 MovedBoundary = StartLower - std::move(Offset);
7081 Overflow = MovedBoundary.sgt(StartLower) || StartRange.isSignWrappedSet();
7082 } else {
7083 MovedBoundary = StartUpper + std::move(Offset);
7084 Overflow = MovedBoundary.slt(StartUpper) || StartRange.isSignWrappedSet();
7085 }
7086 } else {
7087 MovedBoundary = StartUpper.uadd_ov(std::move(Offset), Overflow);
7088 Overflow |= StartRange.isWrappedSet();
7089 }
7090
7091 // It's possible that the new minimum/maximum value will fall into the initial
7092 // range (due to wrap around). This means that the expression can take any
7093 // value in this bitwidth, and we have to return full range.
7094 if (StartRange.contains(MovedBoundary))
7095 return {ConstantRange::getFull(BitWidth), false};
7096
7097 APInt NewLower =
7098 Descending ? std::move(MovedBoundary) : std::move(StartLower);
7099 APInt NewUpper =
7100 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
7101 NewUpper += 1;
7102
7103 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
7104 return {ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)),
7105 !Overflow};
7106}
7107
7108std::pair<ConstantRange, SCEV::NoWrapFlags>
7109ScalarEvolution::getRangeForAffineAR(const SCEV *Start, const SCEV *Step,
7110 const APInt &MaxBECount) {
7111 assert(getTypeSizeInBits(Start->getType()) ==
7112 getTypeSizeInBits(Step->getType()) &&
7113 getTypeSizeInBits(Start->getType()) == MaxBECount.getBitWidth() &&
7114 "mismatched bit widths");
7115
7116 // First, consider step signed.
7117 ConstantRange StartSRange = getSignedRange(Start);
7118 ConstantRange StepSRange = getSignedRange(Step);
7119
7120 // If Step can be both positive and negative, we need to find ranges for the
7121 // maximum absolute step values in both directions and union them.
7122 auto [SR1, NSW1] = getRangeForAffineARHelper(
7123 StepSRange.getSignedMin(), StartSRange, MaxBECount, /*Signed=*/true);
7124 auto [SR2, NSW2] = getRangeForAffineARHelper(StepSRange.getSignedMax(),
7125 StartSRange, MaxBECount,
7126 /*Signed=*/true);
7127 ConstantRange SR = SR1.unionWith(SR2);
7128
7129 // Next, consider step unsigned.
7130 auto [UR, NUW] = getRangeForAffineARHelper(
7131 getUnsignedRangeMax(Step), getUnsignedRange(Start), MaxBECount,
7132 /*Signed=*/false);
7133
7135 if (NUW)
7137 if (NSW1 && NSW2)
7139
7140 // Finally, intersect signed and unsigned ranges.
7142}
7143
7144ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
7145 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
7146 ScalarEvolution::RangeSignHint SignHint) {
7147 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
7148 assert(AddRec->hasNoSelfWrap() &&
7149 "This only works for non-self-wrapping AddRecs!");
7150 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
7151 const SCEV *Step = AddRec->getStepRecurrence(*this);
7152 // Only deal with constant step to save compile time.
7153 if (!isa<SCEVConstant>(Step))
7154 return ConstantRange::getFull(BitWidth);
7155 // Let's make sure that we can prove that we do not self-wrap during
7156 // MaxBECount iterations. We need this because MaxBECount is a maximum
7157 // iteration count estimate, and we might infer nw from some exit for which we
7158 // do not know max exit count (or any other side reasoning).
7159 // TODO: Turn into assert at some point.
7160 if (getTypeSizeInBits(MaxBECount->getType()) >
7161 getTypeSizeInBits(AddRec->getType()))
7162 return ConstantRange::getFull(BitWidth);
7163 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
7164 const SCEV *RangeWidth = getMinusOne(AddRec->getType());
7165 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
7166 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
7167 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
7168 MaxItersWithoutWrap))
7169 return ConstantRange::getFull(BitWidth);
7170
7171 ICmpInst::Predicate LEPred =
7173 ICmpInst::Predicate GEPred =
7175 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7176
7177 // We know that there is no self-wrap. Let's take Start and End values and
7178 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7179 // the iteration. They either lie inside the range [Min(Start, End),
7180 // Max(Start, End)] or outside it:
7181 //
7182 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
7183 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
7184 //
7185 // No self wrap flag guarantees that the intermediate values cannot be BOTH
7186 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7187 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7188 // Start <= End and step is positive, or Start >= End and step is negative.
7189 const SCEV *Start = applyLoopGuards(AddRec->getStart(), AddRec->getLoop());
7190 ConstantRange StartRange = getRangeRef(Start, SignHint);
7191 ConstantRange EndRange = getRangeRef(End, SignHint);
7192 ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7193 // If they already cover full iteration space, we will know nothing useful
7194 // even if we prove what we want to prove.
7195 if (RangeBetween.isFullSet())
7196 return RangeBetween;
7197 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7198 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7199 : RangeBetween.isWrappedSet();
7200 if (IsWrappedSet)
7201 return ConstantRange::getFull(BitWidth);
7202
7203 if (isKnownPositive(Step) &&
7204 isKnownPredicateViaConstantRanges(LEPred, Start, End))
7205 return RangeBetween;
7206 if (isKnownNegative(Step) &&
7207 isKnownPredicateViaConstantRanges(GEPred, Start, End))
7208 return RangeBetween;
7209 return ConstantRange::getFull(BitWidth);
7210}
7211
7212ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7213 const SCEV *Step,
7214 const APInt &MaxBECount) {
7215 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7216 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7217
7218 unsigned BitWidth = MaxBECount.getBitWidth();
7219 assert(getTypeSizeInBits(Start->getType()) == BitWidth &&
7220 getTypeSizeInBits(Step->getType()) == BitWidth &&
7221 "mismatched bit widths");
7222
7223 struct SelectPattern {
7224 Value *Condition = nullptr;
7225 APInt TrueValue;
7226 APInt FalseValue;
7227
7228 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7229 const SCEV *S) {
7230 std::optional<unsigned> CastOp;
7231 APInt Offset(BitWidth, 0);
7232
7234 "Should be!");
7235
7236 // Peel off a constant offset. In the future we could consider being
7237 // smarter here and handle {Start+Step,+,Step} too.
7238 const APInt *Off;
7239 if (match(S, m_scev_Add(m_scev_APInt(Off), m_SCEV(S))))
7240 Offset = *Off;
7241
7242 // Peel off a cast operation
7243 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7244 CastOp = SCast->getSCEVType();
7245 S = SCast->getOperand();
7246 }
7247
7248 using namespace llvm::PatternMatch;
7249
7250 auto *SU = dyn_cast<SCEVUnknown>(S);
7251 const APInt *TrueVal, *FalseVal;
7252 if (!SU ||
7253 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7254 m_APInt(FalseVal)))) {
7255 Condition = nullptr;
7256 return;
7257 }
7258
7259 TrueValue = *TrueVal;
7260 FalseValue = *FalseVal;
7261
7262 // Re-apply the cast we peeled off earlier
7263 if (CastOp)
7264 switch (*CastOp) {
7265 default:
7266 llvm_unreachable("Unknown SCEV cast type!");
7267
7268 case scTruncate:
7269 TrueValue = TrueValue.trunc(BitWidth);
7270 FalseValue = FalseValue.trunc(BitWidth);
7271 break;
7272 case scZeroExtend:
7273 TrueValue = TrueValue.zext(BitWidth);
7274 FalseValue = FalseValue.zext(BitWidth);
7275 break;
7276 case scSignExtend:
7277 TrueValue = TrueValue.sext(BitWidth);
7278 FalseValue = FalseValue.sext(BitWidth);
7279 break;
7280 }
7281
7282 // Re-apply the constant offset we peeled off earlier
7283 TrueValue += Offset;
7284 FalseValue += Offset;
7285 }
7286
7287 bool isRecognized() { return Condition != nullptr; }
7288 };
7289
7290 SelectPattern StartPattern(*this, BitWidth, Start);
7291 if (!StartPattern.isRecognized())
7292 return ConstantRange::getFull(BitWidth);
7293
7294 SelectPattern StepPattern(*this, BitWidth, Step);
7295 if (!StepPattern.isRecognized())
7296 return ConstantRange::getFull(BitWidth);
7297
7298 if (StartPattern.Condition != StepPattern.Condition) {
7299 // We don't handle this case today; but we could, by considering four
7300 // possibilities below instead of two. I'm not sure if there are cases where
7301 // that will help over what getRange already does, though.
7302 return ConstantRange::getFull(BitWidth);
7303 }
7304
7305 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7306 // construct arbitrary general SCEV expressions here. This function is called
7307 // from deep in the call stack, and calling getSCEV (on a sext instruction,
7308 // say) can end up caching a suboptimal value.
7309
7310 // FIXME: without the explicit `this` receiver below, MSVC errors out with
7311 // C2352 and C2512 (otherwise it isn't needed).
7312
7313 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7314 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7315 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7316 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7317
7318 ConstantRange TrueRange =
7319 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount).first;
7320 ConstantRange FalseRange =
7321 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount).first;
7322
7323 return TrueRange.unionWith(FalseRange);
7324}
7325
7326SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7327 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
7328 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7329
7330 // Return early if there are no flags to propagate to the SCEV.
7332 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(BinOp);
7333 PDI && PDI->isDisjoint()) {
7335 } else {
7336 if (BinOp->hasNoUnsignedWrap())
7338 if (BinOp->hasNoSignedWrap())
7340 }
7341 if (Flags == SCEV::FlagAnyWrap)
7342 return SCEV::FlagAnyWrap;
7343
7344 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
7345}
7346
7347const Instruction *
7348ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7349 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7350 return &*AddRec->getLoop()->getHeader()->begin();
7351 if (auto *U = dyn_cast<SCEVUnknown>(S))
7352 if (auto *I = dyn_cast<Instruction>(U->getValue()))
7353 return I;
7354 return nullptr;
7355}
7356
7357const Instruction *ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops,
7358 bool &Precise) {
7359 Precise = true;
7360 // Do a bounded search of the def relation of the requested SCEVs.
7361 SmallPtrSet<const SCEV *, 16> Visited;
7362 SmallVector<SCEVUse> Worklist;
7363 auto pushOp = [&](const SCEV *S) {
7364 if (!Visited.insert(S).second)
7365 return;
7366 // Threshold of 30 here is arbitrary.
7367 if (Visited.size() > 30) {
7368 Precise = false;
7369 return;
7370 }
7371 Worklist.push_back(S);
7372 };
7373
7374 for (SCEVUse S : Ops)
7375 pushOp(S);
7376
7377 const Instruction *Bound = nullptr;
7378 while (!Worklist.empty()) {
7379 SCEVUse S = Worklist.pop_back_val();
7380 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7381 if (!Bound || DT.dominates(Bound, DefI))
7382 Bound = DefI;
7383 } else {
7384 for (SCEVUse Op : S->operands())
7385 pushOp(Op);
7386 }
7387 }
7388 return Bound ? Bound : &*F.getEntryBlock().begin();
7389}
7390
7391const Instruction *
7392ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops) {
7393 bool Discard;
7394 return getDefiningScopeBound(Ops, Discard);
7395}
7396
7397bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7398 const Instruction *B) {
7399 if (A->getParent() == B->getParent() &&
7401 B->getIterator()))
7402 return true;
7403
7404 auto *BLoop = LI.getLoopFor(B->getParent());
7405 if (BLoop && BLoop->getHeader() == B->getParent() &&
7406 BLoop->getLoopPreheader() == A->getParent() &&
7408 A->getParent()->end()) &&
7409 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7410 B->getIterator()))
7411 return true;
7412 return false;
7413}
7414
7416 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ true);
7417 visitAll(Op, PC);
7418 return PC.MaybePoison.empty();
7419}
7420
7421bool ScalarEvolution::isGuaranteedNotToCauseUB(const SCEV *Op) {
7422 return !SCEVExprContains(Op, [this](const SCEV *S) {
7423 const SCEV *Op1;
7424 bool M = match(S, m_scev_UDiv(m_SCEV(), m_SCEV(Op1)));
7425 // The UDiv may be UB if the divisor is poison or zero. Unless the divisor
7426 // is a non-zero constant, we have to assume the UDiv may be UB.
7427 return M && (!isKnownNonZero(Op1) || !isGuaranteedNotToBePoison(Op1));
7428 });
7429}
7430
7431bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7432 // Only proceed if we can prove that I does not yield poison.
7434 return false;
7435
7436 // At this point we know that if I is executed, then it does not wrap
7437 // according to at least one of NSW or NUW. If I is not executed, then we do
7438 // not know if the calculation that I represents would wrap. Multiple
7439 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7440 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7441 // derived from other instructions that map to the same SCEV. We cannot make
7442 // that guarantee for cases where I is not executed. So we need to find a
7443 // upper bound on the defining scope for the SCEV, and prove that I is
7444 // executed every time we enter that scope. When the bounding scope is a
7445 // loop (the common case), this is equivalent to proving I executes on every
7446 // iteration of that loop.
7447 SmallVector<SCEVUse> SCEVOps;
7448 for (const Use &Op : I->operands()) {
7449 // I could be an extractvalue from a call to an overflow intrinsic.
7450 // TODO: We can do better here in some cases.
7451 if (isSCEVable(Op->getType()))
7452 SCEVOps.push_back(getSCEV(Op));
7453 }
7454 auto *DefI = getDefiningScopeBound(SCEVOps);
7455 return isGuaranteedToTransferExecutionTo(DefI, I);
7456}
7457
7458bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7459 // If we know that \c I can never be poison period, then that's enough.
7460 if (isSCEVExprNeverPoison(I))
7461 return true;
7462
7463 // If the loop only has one exit, then we know that, if the loop is entered,
7464 // any instruction dominating that exit will be executed. If any such
7465 // instruction would result in UB, the addrec cannot be poison.
7466 //
7467 // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7468 // also handles uses outside the loop header (they just need to dominate the
7469 // single exit).
7470
7471 auto *ExitingBB = L->getExitingBlock();
7472 if (!ExitingBB || !loopHasNoAbnormalExits(L))
7473 return false;
7474
7475 SmallPtrSet<const Value *, 16> KnownPoison;
7477
7478 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
7479 // things that are known to be poison under that assumption go on the
7480 // Worklist.
7481 KnownPoison.insert(I);
7482 Worklist.push_back(I);
7483
7484 while (!Worklist.empty()) {
7485 const Instruction *Poison = Worklist.pop_back_val();
7486
7487 for (const Use &U : Poison->uses()) {
7488 const Instruction *PoisonUser = cast<Instruction>(U.getUser());
7489 if (mustTriggerUB(PoisonUser, KnownPoison) &&
7490 DT.dominates(PoisonUser->getParent(), ExitingBB))
7491 return true;
7492
7493 if (propagatesPoison(U) && L->contains(PoisonUser))
7494 if (KnownPoison.insert(PoisonUser).second)
7495 Worklist.push_back(PoisonUser);
7496 }
7497 }
7498
7499 return false;
7500}
7501
7502ScalarEvolution::LoopProperties
7503ScalarEvolution::getLoopProperties(const Loop *L) {
7504 using LoopProperties = ScalarEvolution::LoopProperties;
7505
7506 auto Itr = LoopPropertiesCache.find(L);
7507 if (Itr == LoopPropertiesCache.end()) {
7508 auto HasSideEffects = [](Instruction *I) {
7509 if (auto *SI = dyn_cast<StoreInst>(I))
7510 return !SI->isSimple();
7511
7512 if (I->mayThrow())
7513 return true;
7514
7515 // Non-volatile memset / memcpy do not count as side-effect for forward
7516 // progress.
7517 if (isa<MemIntrinsic>(I) && !I->isVolatile())
7518 return false;
7519
7520 return I->mayWriteToMemory();
7521 };
7522
7523 LoopProperties LP = {/* HasNoAbnormalExits */ true,
7524 /*HasNoSideEffects*/ true};
7525
7526 for (auto *BB : L->getBlocks())
7527 for (auto &I : *BB) {
7529 LP.HasNoAbnormalExits = false;
7530 if (HasSideEffects(&I))
7531 LP.HasNoSideEffects = false;
7532 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7533 break; // We're already as pessimistic as we can get.
7534 }
7535
7536 auto InsertPair = LoopPropertiesCache.insert({L, LP});
7537 assert(InsertPair.second && "We just checked!");
7538 Itr = InsertPair.first;
7539 }
7540
7541 return Itr->second;
7542}
7543
7545 // A mustprogress loop without side effects must be finite.
7546 // TODO: The check used here is very conservative. It's only *specific*
7547 // side effects which are well defined in infinite loops.
7548 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7549}
7550
7551const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7552 // Worklist item with a Value and a bool indicating whether all operands have
7553 // been visited already.
7556
7557 Stack.emplace_back(V, false);
7558 while (!Stack.empty()) {
7559 auto E = Stack.back();
7560 Value *CurV = E.getPointer();
7561
7562 if (getExistingSCEV(CurV)) {
7563 Stack.pop_back();
7564 continue;
7565 }
7566
7568 const SCEV *CreatedSCEV = nullptr;
7569 // If all operands have been visited already, create the SCEV.
7570 if (E.getInt()) {
7571 CreatedSCEV = createSCEV(CurV);
7572 } else {
7573 // Otherwise get the operands we need to create SCEV's for before creating
7574 // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7575 // just use it.
7576 CreatedSCEV = getOperandsToCreate(CurV, Ops);
7577 }
7578
7579 if (CreatedSCEV) {
7580 insertValueToMap(CurV, CreatedSCEV);
7581 Stack.pop_back();
7582 } else {
7583 Stack.back().setInt(true);
7584 // Queue its operands which need to be constructed.
7585 for (Value *Op : Ops)
7586 Stack.emplace_back(Op, false);
7587 }
7588 }
7589
7590 return getExistingSCEV(V);
7591}
7592
7593const SCEV *
7594ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7595 if (!isSCEVable(V->getType()))
7596 return getUnknown(V);
7597
7598 if (Instruction *I = dyn_cast<Instruction>(V)) {
7599 // Don't attempt to analyze instructions in blocks that aren't
7600 // reachable. Such instructions don't matter, and they aren't required
7601 // to obey basic rules for definitions dominating uses which this
7602 // analysis depends on.
7603 if (!DT.isReachableFromEntry(I->getParent()))
7604 return getUnknown(PoisonValue::get(V->getType()));
7605 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7606 return getConstant(CI);
7607 else if (isa<GlobalAlias>(V))
7608 return getUnknown(V);
7609 else if (!isa<ConstantExpr>(V))
7610 return getUnknown(V);
7611
7613 if (auto BO =
7615 bool IsConstArg = isa<ConstantInt>(BO->RHS);
7616 switch (BO->Opcode) {
7617 case Instruction::Add:
7618 case Instruction::Mul: {
7619 // For additions and multiplications, traverse add/mul chains for which we
7620 // can potentially create a single SCEV, to reduce the number of
7621 // get{Add,Mul}Expr calls.
7622 do {
7623 if (BO->Op) {
7624 if (BO->Op != V && getExistingSCEV(BO->Op)) {
7625 Ops.push_back(BO->Op);
7626 break;
7627 }
7628 }
7629 Ops.push_back(BO->RHS);
7630 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7632 if (!NewBO ||
7633 (BO->Opcode == Instruction::Add &&
7634 (NewBO->Opcode != Instruction::Add &&
7635 NewBO->Opcode != Instruction::Sub)) ||
7636 (BO->Opcode == Instruction::Mul &&
7637 NewBO->Opcode != Instruction::Mul)) {
7638 Ops.push_back(BO->LHS);
7639 break;
7640 }
7641 // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7642 // requires a SCEV for the LHS.
7643 if (BO->Op && (BO->IsNSW || BO->IsNUW)) {
7644 auto *I = dyn_cast<Instruction>(BO->Op);
7645 if (I && programUndefinedIfPoison(I)) {
7646 Ops.push_back(BO->LHS);
7647 break;
7648 }
7649 }
7650 BO = NewBO;
7651 } while (true);
7652 return nullptr;
7653 }
7654 case Instruction::Sub:
7655 case Instruction::UDiv:
7656 case Instruction::URem:
7657 break;
7658 case Instruction::AShr:
7659 case Instruction::Shl:
7660 case Instruction::Xor:
7661 if (!IsConstArg)
7662 return nullptr;
7663 break;
7664 case Instruction::And:
7665 case Instruction::Or:
7666 if (!IsConstArg && !BO->LHS->getType()->isIntegerTy(1))
7667 return nullptr;
7668 break;
7669 case Instruction::LShr:
7670 return getUnknown(V);
7671 default:
7672 llvm_unreachable("Unhandled binop");
7673 break;
7674 }
7675
7676 Ops.push_back(BO->LHS);
7677 Ops.push_back(BO->RHS);
7678 return nullptr;
7679 }
7680
7681 switch (U->getOpcode()) {
7682 case Instruction::Trunc:
7683 case Instruction::ZExt:
7684 case Instruction::SExt:
7685 case Instruction::PtrToAddr:
7686 case Instruction::PtrToInt:
7687 Ops.push_back(U->getOperand(0));
7688 return nullptr;
7689
7690 case Instruction::BitCast:
7691 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
7692 Ops.push_back(U->getOperand(0));
7693 return nullptr;
7694 }
7695 return getUnknown(V);
7696
7697 case Instruction::SDiv:
7698 case Instruction::SRem:
7699 Ops.push_back(U->getOperand(0));
7700 Ops.push_back(U->getOperand(1));
7701 return nullptr;
7702
7703 case Instruction::GetElementPtr:
7704 assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7705 "GEP source element type must be sized");
7706 llvm::append_range(Ops, U->operands());
7707 return nullptr;
7708
7709 case Instruction::IntToPtr:
7710 return getUnknown(V);
7711
7712 case Instruction::PHI:
7713 // getNodeForPHI has four ways to turn a PHI into a SCEV; retrieve the
7714 // relevant nodes for each of them.
7715 //
7716 // The first is just to call simplifyInstruction, and get something back
7717 // that isn't a PHI.
7718 if (Value *V = simplifyInstruction(
7719 cast<PHINode>(U),
7720 {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
7721 /*UseInstrInfo=*/true, /*CanUseUndef=*/false})) {
7722 assert(V);
7723 Ops.push_back(V);
7724 return nullptr;
7725 }
7726 // The second is createNodeForPHIWithIdenticalOperands: this looks for
7727 // operands which all perform the same operation, but haven't been
7728 // CSE'ed for whatever reason.
7729 if (BinaryOperator *BO = getCommonInstForPHI(cast<PHINode>(U))) {
7730 assert(BO);
7731 Ops.push_back(BO);
7732 return nullptr;
7733 }
7734 // The third is createNodeFromSelectLikePHI; this takes a PHI which
7735 // is equivalent to a select, and analyzes it like a select.
7736 {
7737 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
7739 assert(Cond);
7740 assert(LHS);
7741 assert(RHS);
7742 if (auto *CondICmp = dyn_cast<ICmpInst>(Cond)) {
7743 Ops.push_back(CondICmp->getOperand(0));
7744 Ops.push_back(CondICmp->getOperand(1));
7745 }
7746 Ops.push_back(Cond);
7747 Ops.push_back(LHS);
7748 Ops.push_back(RHS);
7749 return nullptr;
7750 }
7751 }
7752 // The fourth way is createAddRecFromPHI. It's complicated to handle here,
7753 // so just construct it recursively.
7754 //
7755 // In addition to getNodeForPHI, also construct nodes which might be needed
7756 // by getRangeRef.
7758 for (Value *V : cast<PHINode>(U)->operands())
7759 Ops.push_back(V);
7760 return nullptr;
7761 }
7762 return nullptr;
7763
7764 case Instruction::Select: {
7765 // Check if U is a select that can be simplified to a SCEVUnknown.
7766 auto CanSimplifyToUnknown = [this, U]() {
7767 if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
7768 return false;
7769
7770 auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
7771 if (!ICI)
7772 return false;
7773 Value *LHS = ICI->getOperand(0);
7774 Value *RHS = ICI->getOperand(1);
7775 if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7776 ICI->getPredicate() == CmpInst::ICMP_NE) {
7778 return true;
7779 } else if (getTypeSizeInBits(LHS->getType()) >
7780 getTypeSizeInBits(U->getType()))
7781 return true;
7782 return false;
7783 };
7784 if (CanSimplifyToUnknown())
7785 return getUnknown(U);
7786
7787 llvm::append_range(Ops, U->operands());
7788 return nullptr;
7789 break;
7790 }
7791 case Instruction::Call:
7792 case Instruction::Invoke:
7793 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7794 Ops.push_back(RV);
7795 return nullptr;
7796 }
7797
7798 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7799 switch (II->getIntrinsicID()) {
7800 case Intrinsic::abs:
7801 Ops.push_back(II->getArgOperand(0));
7802 return nullptr;
7803 case Intrinsic::umax:
7804 case Intrinsic::umin:
7805 case Intrinsic::smax:
7806 case Intrinsic::smin:
7807 case Intrinsic::usub_sat:
7808 case Intrinsic::uadd_sat:
7809 Ops.push_back(II->getArgOperand(0));
7810 Ops.push_back(II->getArgOperand(1));
7811 return nullptr;
7812 case Intrinsic::start_loop_iterations:
7813 case Intrinsic::annotation:
7814 case Intrinsic::ptr_annotation:
7815 Ops.push_back(II->getArgOperand(0));
7816 return nullptr;
7817 default:
7818 break;
7819 }
7820 }
7821 break;
7822 }
7823
7824 return nullptr;
7825}
7826
7827const SCEV *ScalarEvolution::createSCEV(Value *V) {
7828 if (!isSCEVable(V->getType()))
7829 return getUnknown(V);
7830
7831 if (Instruction *I = dyn_cast<Instruction>(V)) {
7832 // Don't attempt to analyze instructions in blocks that aren't
7833 // reachable. Such instructions don't matter, and they aren't required
7834 // to obey basic rules for definitions dominating uses which this
7835 // analysis depends on.
7836 if (!DT.isReachableFromEntry(I->getParent()))
7837 return getUnknown(PoisonValue::get(V->getType()));
7838 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7839 return getConstant(CI);
7840 else if (isa<GlobalAlias>(V))
7841 return getUnknown(V);
7842 else if (!isa<ConstantExpr>(V))
7843 return getUnknown(V);
7844
7845 const SCEV *LHS;
7846 const SCEV *RHS;
7847
7849 if (auto BO =
7851 switch (BO->Opcode) {
7852 case Instruction::Add: {
7853 // The simple thing to do would be to just call getSCEV on both operands
7854 // and call getAddExpr with the result. However if we're looking at a
7855 // bunch of things all added together, this can be quite inefficient,
7856 // because it leads to N-1 getAddExpr calls for N ultimate operands.
7857 // Instead, gather up all the operands and make a single getAddExpr call.
7858 // LLVM IR canonical form means we need only traverse the left operands.
7860 do {
7861 if (BO->Op) {
7862 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7863 AddOps.push_back(OpSCEV);
7864 break;
7865 }
7866
7867 // If a NUW or NSW flag can be applied to the SCEV for this
7868 // addition, then compute the SCEV for this addition by itself
7869 // with a separate call to getAddExpr. We need to do that
7870 // instead of pushing the operands of the addition onto AddOps,
7871 // since the flags are only known to apply to this particular
7872 // addition - they may not apply to other additions that can be
7873 // formed with operands from AddOps.
7874 const SCEV *RHS = getSCEV(BO->RHS);
7875 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7876 if (Flags != SCEV::FlagAnyWrap) {
7877 const SCEV *LHS = getSCEV(BO->LHS);
7878 if (BO->Opcode == Instruction::Sub)
7879 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7880 else
7881 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7882 break;
7883 }
7884 }
7885
7886 if (BO->Opcode == Instruction::Sub)
7887 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7888 else
7889 AddOps.push_back(getSCEV(BO->RHS));
7890
7891 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7893 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7894 NewBO->Opcode != Instruction::Sub)) {
7895 AddOps.push_back(getSCEV(BO->LHS));
7896 break;
7897 }
7898 BO = NewBO;
7899 } while (true);
7900
7901 return getAddExpr(AddOps);
7902 }
7903
7904 case Instruction::Mul: {
7906 do {
7907 if (BO->Op) {
7908 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7909 MulOps.push_back(OpSCEV);
7910 break;
7911 }
7912
7913 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7914 if (Flags != SCEV::FlagAnyWrap) {
7915 LHS = getSCEV(BO->LHS);
7916 RHS = getSCEV(BO->RHS);
7917 MulOps.push_back(getMulExpr(LHS, RHS, Flags));
7918 break;
7919 }
7920 }
7921
7922 MulOps.push_back(getSCEV(BO->RHS));
7923 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7925 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7926 MulOps.push_back(getSCEV(BO->LHS));
7927 break;
7928 }
7929 BO = NewBO;
7930 } while (true);
7931
7932 return getMulExpr(MulOps);
7933 }
7934 case Instruction::UDiv:
7935 LHS = getSCEV(BO->LHS);
7936 RHS = getSCEV(BO->RHS);
7937 return getUDivExpr(LHS, RHS);
7938 case Instruction::URem:
7939 LHS = getSCEV(BO->LHS);
7940 RHS = getSCEV(BO->RHS);
7941 return getURemExpr(LHS, RHS);
7942 case Instruction::Sub: {
7944 if (BO->Op)
7945 Flags = getNoWrapFlagsFromUB(BO->Op);
7946
7947 // Try to use ptrtoaddr for subtracts with at least one ptrtoint
7948 // operand. While we don't model ptrtoint directly in SCEV, the
7949 // difference between two pointer addresses is well-defined.
7950 Value *PtrLHS = nullptr, *PtrRHS = nullptr;
7951 bool HasPtrLHS = match(BO->LHS, m_PtrToInt(m_Value(PtrLHS)));
7952 bool HasPtrRHS = match(BO->RHS, m_PtrToInt(m_Value(PtrRHS)));
7953 if (HasPtrLHS || HasPtrRHS) {
7954 // Convert a ptrtoint operand (OrigOp) to ptrtoaddr of its pointer
7955 // PtrOp. When only one side is ptrtoint (BothPtr is false), skip
7956 // SCEVUnknown pointers since wrapping them in ptrtoaddr adds no
7957 // useful structure.
7958 auto GetOp = [&](bool HasPtr, Value *PtrOp, Value *OrigOp,
7959 bool BothPtr) -> const SCEV * {
7960 if (!HasPtr)
7961 return getSCEV(OrigOp);
7962 const SCEV *PtrSCEV = getSCEV(PtrOp);
7963 if (BothPtr || !isa<SCEVUnknown>(PtrSCEV)) {
7964 const SCEV *Addr = getPtrToAddrExpr(PtrSCEV);
7965 if (!isa<SCEVCouldNotCompute>(Addr) &&
7966 getTypeSizeInBits(OrigOp->getType()) <=
7967 getTypeSizeInBits(Addr->getType()))
7968 return getTruncateOrNoop(Addr, OrigOp->getType());
7969 }
7970 return getSCEV(OrigOp);
7971 };
7972 const SCEV *L = GetOp(HasPtrLHS, PtrLHS, BO->LHS, HasPtrRHS);
7973 const SCEV *R = GetOp(HasPtrRHS, PtrRHS, BO->RHS, HasPtrLHS);
7974 return getMinusSCEV(L, R, Flags);
7975 }
7976
7977 LHS = getSCEV(BO->LHS);
7978 RHS = getSCEV(BO->RHS);
7979 return getMinusSCEV(LHS, RHS, Flags);
7980 }
7981 case Instruction::And:
7982 // For an expression like x&255 that merely masks off the high bits,
7983 // use zext(trunc(x)) as the SCEV expression.
7984 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7985 if (CI->isZero())
7986 return getSCEV(BO->RHS);
7987 if (CI->isMinusOne())
7988 return getSCEV(BO->LHS);
7989 const APInt &A = CI->getValue();
7990
7991 // Instcombine's ShrinkDemandedConstant may strip bits out of
7992 // constants, obscuring what would otherwise be a low-bits mask.
7993 // Use computeKnownBits to compute what ShrinkDemandedConstant
7994 // knew about to reconstruct a low-bits mask value.
7995 unsigned LZ = A.countl_zero();
7996 unsigned TZ = A.countr_zero();
7997 unsigned BitWidth = A.getBitWidth();
7998 KnownBits Known(BitWidth);
7999 computeKnownBits(BO->LHS, Known, getDataLayout(), &AC, nullptr, &DT);
8000
8001 APInt EffectiveMask =
8002 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
8003 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
8004 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
8005 const SCEV *LHS = getSCEV(BO->LHS);
8006 const SCEV *ShiftedLHS = nullptr;
8007 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
8008 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
8009 // For an expression like (x * 8) & 8, simplify the multiply.
8010 unsigned MulZeros = OpC->getAPInt().countr_zero();
8011 unsigned GCD = std::min(MulZeros, TZ);
8012 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
8014 MulOps.push_back(getConstant(OpC->getAPInt().ashr(GCD)));
8015 append_range(MulOps, LHSMul->operands().drop_front());
8016 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
8017 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
8018 }
8019 }
8020 if (!ShiftedLHS)
8021 ShiftedLHS = getUDivExpr(LHS, MulCount);
8022 return getMulExpr(
8024 getTruncateExpr(ShiftedLHS,
8025 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
8026 BO->LHS->getType()),
8027 MulCount);
8028 }
8029 }
8030 // Binary `and` is a bit-wise `umin`.
8031 if (BO->LHS->getType()->isIntegerTy(1)) {
8032 LHS = getSCEV(BO->LHS);
8033 RHS = getSCEV(BO->RHS);
8034 return getUMinExpr(LHS, RHS);
8035 }
8036 break;
8037
8038 case Instruction::Or:
8039 // Binary `or` is a bit-wise `umax`.
8040 if (BO->LHS->getType()->isIntegerTy(1)) {
8041 LHS = getSCEV(BO->LHS);
8042 RHS = getSCEV(BO->RHS);
8043 return getUMaxExpr(LHS, RHS);
8044 }
8045 break;
8046
8047 case Instruction::Xor:
8048 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
8049 // If the RHS of xor is -1, then this is a not operation.
8050 if (CI->isMinusOne())
8051 return getNotSCEV(getSCEV(BO->LHS));
8052
8053 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
8054 // This is a variant of the check for xor with -1, and it handles
8055 // the case where instcombine has trimmed non-demanded bits out
8056 // of an xor with -1.
8057 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
8058 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
8059 if (LBO->getOpcode() == Instruction::And &&
8060 LCI->getValue() == CI->getValue())
8061 if (const SCEVZeroExtendExpr *Z =
8063 Type *UTy = BO->LHS->getType();
8064 const SCEV *Z0 = Z->getOperand();
8065 Type *Z0Ty = Z0->getType();
8066 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
8067
8068 // If C is a low-bits mask, the zero extend is serving to
8069 // mask off the high bits. Complement the operand and
8070 // re-apply the zext.
8071 if (CI->getValue().isMask(Z0TySize))
8072 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
8073
8074 // If C is a single bit, it may be in the sign-bit position
8075 // before the zero-extend. In this case, represent the xor
8076 // using an add, which is equivalent, and re-apply the zext.
8077 APInt Trunc = CI->getValue().trunc(Z0TySize);
8078 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
8079 Trunc.isSignMask())
8080 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
8081 UTy);
8082 }
8083 }
8084 break;
8085
8086 case Instruction::Shl:
8087 // Turn shift left of a constant amount into a multiply.
8088 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
8089 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
8090
8091 // If the shift count is not less than the bitwidth, the result of
8092 // the shift is undefined. Don't try to analyze it, because the
8093 // resolution chosen here may differ from the resolution chosen in
8094 // other parts of the compiler.
8095 if (SA->getValue().uge(BitWidth))
8096 break;
8097
8098 // We can safely preserve the nuw flag in all cases. It's also safe to
8099 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
8100 // requires special handling. It can be preserved as long as we're not
8101 // left shifting by bitwidth - 1.
8102 auto Flags = SCEV::FlagAnyWrap;
8103 if (BO->Op) {
8104 auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
8105 if (any(MulFlags & SCEV::FlagNSW) &&
8106 (any(MulFlags & SCEV::FlagNUW) ||
8107 SA->getValue().ult(BitWidth - 1)))
8109 if (any(MulFlags & SCEV::FlagNUW))
8111 }
8112
8113 ConstantInt *X = ConstantInt::get(
8114 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
8115 return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
8116 }
8117 break;
8118
8119 case Instruction::AShr:
8120 // AShr X, C, where C is a constant.
8121 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
8122 if (!CI)
8123 break;
8124
8125 Type *OuterTy = BO->LHS->getType();
8127 // If the shift count is not less than the bitwidth, the result of
8128 // the shift is undefined. Don't try to analyze it, because the
8129 // resolution chosen here may differ from the resolution chosen in
8130 // other parts of the compiler.
8131 if (CI->getValue().uge(BitWidth))
8132 break;
8133
8134 if (CI->isZero())
8135 return getSCEV(BO->LHS); // shift by zero --> noop
8136
8137 uint64_t AShrAmt = CI->getZExtValue();
8138 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
8139
8140 Operator *L = dyn_cast<Operator>(BO->LHS);
8141 const SCEV *AddTruncateExpr = nullptr;
8142 ConstantInt *ShlAmtCI = nullptr;
8143 const SCEV *AddConstant = nullptr;
8144
8145 if (L && L->getOpcode() == Instruction::Add) {
8146 // X = Shl A, n
8147 // Y = Add X, c
8148 // Z = AShr Y, m
8149 // n, c and m are constants.
8150
8151 Operator *LShift = dyn_cast<Operator>(L->getOperand(0));
8152 ConstantInt *AddOperandCI = dyn_cast<ConstantInt>(L->getOperand(1));
8153 if (LShift && LShift->getOpcode() == Instruction::Shl) {
8154 if (AddOperandCI) {
8155 const SCEV *ShlOp0SCEV = getSCEV(LShift->getOperand(0));
8156 ShlAmtCI = dyn_cast<ConstantInt>(LShift->getOperand(1));
8157 // since we truncate to TruncTy, the AddConstant should be of the
8158 // same type, so create a new Constant with type same as TruncTy.
8159 // Also, the Add constant should be shifted right by AShr amount.
8160 APInt AddOperand = AddOperandCI->getValue().ashr(AShrAmt);
8161 AddConstant = getConstant(AddOperand.trunc(BitWidth - AShrAmt));
8162 // we model the expression as sext(add(trunc(A), c << n)), since the
8163 // sext(trunc) part is already handled below, we create a
8164 // AddExpr(TruncExp) which will be used later.
8165 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8166 }
8167 }
8168 } else if (L && L->getOpcode() == Instruction::Shl) {
8169 // X = Shl A, n
8170 // Y = AShr X, m
8171 // Both n and m are constant.
8172
8173 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
8174 ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
8175 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8176 }
8177
8178 if (AddTruncateExpr && ShlAmtCI) {
8179 // We can merge the two given cases into a single SCEV statement,
8180 // incase n = m, the mul expression will be 2^0, so it gets resolved to
8181 // a simpler case. The following code handles the two cases:
8182 //
8183 // 1) For a two-shift sext-inreg, i.e. n = m,
8184 // use sext(trunc(x)) as the SCEV expression.
8185 //
8186 // 2) When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
8187 // expression. We already checked that ShlAmt < BitWidth, so
8188 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
8189 // ShlAmt - AShrAmt < Amt.
8190 const APInt &ShlAmt = ShlAmtCI->getValue();
8191 if (ShlAmt.ult(BitWidth) && ShlAmt.uge(AShrAmt)) {
8192 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
8193 ShlAmtCI->getZExtValue() - AShrAmt);
8194 const SCEV *CompositeExpr =
8195 getMulExpr(AddTruncateExpr, getConstant(Mul));
8196 if (L->getOpcode() != Instruction::Shl)
8197 CompositeExpr = getAddExpr(CompositeExpr, AddConstant);
8198
8199 return getSignExtendExpr(CompositeExpr, OuterTy);
8200 }
8201 }
8202 break;
8203 }
8204 }
8205
8206 switch (U->getOpcode()) {
8207 case Instruction::Trunc:
8208 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
8209
8210 case Instruction::ZExt:
8211 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8212
8213 case Instruction::SExt:
8214 if (auto BO = MatchBinaryOp(U->getOperand(0), getDataLayout(), AC, DT,
8216 // The NSW flag of a subtract does not always survive the conversion to
8217 // A + (-1)*B. By pushing sign extension onto its operands we are much
8218 // more likely to preserve NSW and allow later AddRec optimisations.
8219 //
8220 // NOTE: This is effectively duplicating this logic from getSignExtend:
8221 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
8222 // but by that point the NSW information has potentially been lost.
8223 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
8224 Type *Ty = U->getType();
8225 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
8226 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
8227 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
8228 }
8229 }
8230 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8231
8232 case Instruction::BitCast:
8233 // BitCasts are no-op casts so we just eliminate the cast.
8234 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
8235 return getSCEV(U->getOperand(0));
8236 break;
8237
8238 case Instruction::PtrToAddr: {
8239 const SCEV *IntOp = getPtrToAddrExpr(getSCEV(U->getOperand(0)));
8240 if (isa<SCEVCouldNotCompute>(IntOp))
8241 return getUnknown(V);
8242 return IntOp;
8243 }
8244
8245 case Instruction::PtrToInt:
8246 // SCEV only models ptrtoaddr.
8247 return getUnknown(V);
8248
8249 case Instruction::IntToPtr:
8250 // Just don't deal with inttoptr casts.
8251 return getUnknown(V);
8252
8253 case Instruction::SDiv:
8254 // If both operands are non-negative, this is just an udiv.
8255 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8256 isKnownNonNegative(getSCEV(U->getOperand(1))))
8257 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8258 break;
8259
8260 case Instruction::SRem:
8261 // If both operands are non-negative, this is just an urem.
8262 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8263 isKnownNonNegative(getSCEV(U->getOperand(1))))
8264 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8265 break;
8266
8267 case Instruction::GetElementPtr:
8268 return createNodeForGEP(cast<GEPOperator>(U));
8269
8270 case Instruction::PHI:
8271 return createNodeForPHI(cast<PHINode>(U));
8272
8273 case Instruction::Select:
8274 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
8275 U->getOperand(2));
8276
8277 case Instruction::Call:
8278 case Instruction::Invoke:
8279 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
8280 return getSCEV(RV);
8281
8282 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
8283 switch (II->getIntrinsicID()) {
8284 case Intrinsic::abs:
8285 return getAbsExpr(
8286 getSCEV(II->getArgOperand(0)),
8287 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
8288 case Intrinsic::umax:
8289 LHS = getSCEV(II->getArgOperand(0));
8290 RHS = getSCEV(II->getArgOperand(1));
8291 return getUMaxExpr(LHS, RHS);
8292 case Intrinsic::umin:
8293 LHS = getSCEV(II->getArgOperand(0));
8294 RHS = getSCEV(II->getArgOperand(1));
8295 return getUMinExpr(LHS, RHS);
8296 case Intrinsic::smax:
8297 LHS = getSCEV(II->getArgOperand(0));
8298 RHS = getSCEV(II->getArgOperand(1));
8299 return getSMaxExpr(LHS, RHS);
8300 case Intrinsic::smin:
8301 LHS = getSCEV(II->getArgOperand(0));
8302 RHS = getSCEV(II->getArgOperand(1));
8303 return getSMinExpr(LHS, RHS);
8304 case Intrinsic::usub_sat: {
8305 const SCEV *X = getSCEV(II->getArgOperand(0));
8306 const SCEV *Y = getSCEV(II->getArgOperand(1));
8307 const SCEV *ClampedY = getUMinExpr(X, Y);
8308 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
8309 }
8310 case Intrinsic::uadd_sat: {
8311 const SCEV *X = getSCEV(II->getArgOperand(0));
8312 const SCEV *Y = getSCEV(II->getArgOperand(1));
8313 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
8314 return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
8315 }
8316 case Intrinsic::start_loop_iterations:
8317 case Intrinsic::annotation:
8318 case Intrinsic::ptr_annotation:
8319 // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8320 // just eqivalent to the first operand for SCEV purposes.
8321 return getSCEV(II->getArgOperand(0));
8322 case Intrinsic::vscale:
8323 return getVScale(II->getType());
8324 default:
8325 break;
8326 }
8327 }
8328 break;
8329 }
8330
8331 return getUnknown(V);
8332}
8333
8334//===----------------------------------------------------------------------===//
8335// Iteration Count Computation Code
8336//
8337
8339 if (isa<SCEVCouldNotCompute>(ExitCount))
8340 return getCouldNotCompute();
8341
8342 auto *ExitCountType = ExitCount->getType();
8343 assert(ExitCountType->isIntegerTy());
8344 auto *EvalTy = Type::getIntNTy(ExitCountType->getContext(),
8345 1 + ExitCountType->getScalarSizeInBits());
8346 return getTripCountFromExitCount(ExitCount, EvalTy, nullptr);
8347}
8348
8350 Type *EvalTy,
8351 const Loop *L) {
8352 if (isa<SCEVCouldNotCompute>(ExitCount))
8353 return getCouldNotCompute();
8354
8355 unsigned ExitCountSize = getTypeSizeInBits(ExitCount->getType());
8356 unsigned EvalSize = EvalTy->getPrimitiveSizeInBits();
8357
8358 auto CanAddOneWithoutOverflow = [&]() {
8359 ConstantRange ExitCountRange =
8360 getRangeRef(ExitCount, RangeSignHint::HINT_RANGE_UNSIGNED);
8361 if (!ExitCountRange.contains(APInt::getMaxValue(ExitCountSize)))
8362 return true;
8363
8364 return L && isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
8365 getMinusOne(ExitCount->getType()));
8366 };
8367
8368 // If we need to zero extend the backedge count, check if we can add one to
8369 // it prior to zero extending without overflow. Provided this is safe, it
8370 // allows better simplification of the +1.
8371 if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8372 return getZeroExtendExpr(
8373 getAddExpr(ExitCount, getOne(ExitCount->getType())), EvalTy);
8374
8375 // Get the total trip count from the count by adding 1. This may wrap.
8376 return getAddExpr(getTruncateOrZeroExtend(ExitCount, EvalTy), getOne(EvalTy));
8377}
8378
8379static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8380 if (!ExitCount)
8381 return 0;
8382
8383 ConstantInt *ExitConst = ExitCount->getValue();
8384
8385 // Guard against huge trip counts.
8386 if (ExitConst->getValue().getActiveBits() > 32)
8387 return 0;
8388
8389 // In case of integer overflow, this returns 0, which is correct.
8390 return ((unsigned)ExitConst->getZExtValue()) + 1;
8391}
8392
8394 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
8395 return getConstantTripCount(ExitCount);
8396}
8397
8398unsigned
8400 const BasicBlock *ExitingBlock) {
8401 assert(ExitingBlock && "Must pass a non-null exiting block!");
8402 assert(L->isLoopExiting(ExitingBlock) &&
8403 "Exiting block must actually branch out of the loop!");
8404 const SCEVConstant *ExitCount =
8405 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
8406 return getConstantTripCount(ExitCount);
8407}
8408
8410 const Loop *L, SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8411
8412 const auto *MaxExitCount =
8413 Predicates ? getPredicatedConstantMaxBackedgeTakenCount(L, *Predicates)
8415 return getConstantTripCount(dyn_cast<SCEVConstant>(MaxExitCount));
8416}
8417
8419 SmallVector<BasicBlock *, 8> ExitingBlocks;
8420 L->getExitingBlocks(ExitingBlocks);
8421
8422 // An exit with an uncomputable exit count makes the result 1.
8423 if (ExitingBlocks.empty() ||
8424 any_of(ExitingBlocks, [this, L](BasicBlock *ExitingBB) {
8425 return isa<SCEVCouldNotCompute>(getExitCount(L, ExitingBB));
8426 }))
8427 return 1;
8428
8429 LoopGuards Guards = LoopGuards::collect(L, *this);
8430 unsigned Res = 0;
8431 for (BasicBlock *ExitingBB : ExitingBlocks)
8432 Res = std::gcd(
8433 Res, getSmallConstantTripMultiple(getExitCount(L, ExitingBB), Guards));
8434 return Res;
8435}
8436
8437unsigned
8439 const LoopGuards &Guards) {
8440 assert(!isa<SCEVCouldNotCompute>(ExitCount) && "Must be computable!");
8441
8442 // Get the trip count
8443 const SCEV *TCExpr =
8444 getTripCountFromExitCount(applyLoopGuards(ExitCount, Guards));
8445
8446 APInt Multiple = getNonZeroConstantMultiple(TCExpr);
8447 // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8448 // the greatest power of 2 divisor less than 2^32.
8449 return Multiple.getActiveBits() > 32
8450 ? 1U << std::min(31U, Multiple.countTrailingZeros())
8451 : (unsigned)Multiple.getZExtValue();
8452}
8453
8455 const SCEV *ExitCount) {
8456 if (isa<SCEVCouldNotCompute>(ExitCount))
8457 return 1;
8458
8459 return getSmallConstantTripMultiple(ExitCount, LoopGuards::collect(L, *this));
8460}
8461
8462/// Returns the largest constant divisor of the trip count of this loop as a
8463/// normal unsigned value, if possible. This means that the actual trip count is
8464/// always a multiple of the returned value (don't forget the trip count could
8465/// very well be zero as well!).
8466///
8467/// Returns 1 if the trip count is unknown or not guaranteed to be the
8468/// multiple of a constant (which is also the case if the trip count is simply
8469/// constant, use getSmallConstantTripCount for that case), Will also return 1
8470/// if the trip count is very large (>= 2^32).
8471///
8472/// As explained in the comments for getSmallConstantTripCount, this assumes
8473/// that control exits the loop via ExitingBlock.
8474unsigned
8476 const BasicBlock *ExitingBlock) {
8477 assert(ExitingBlock && "Must pass a non-null exiting block!");
8478 assert(L->isLoopExiting(ExitingBlock) &&
8479 "Exiting block must actually branch out of the loop!");
8480 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8481 return getSmallConstantTripMultiple(L, ExitCount);
8482}
8483
8485 const BasicBlock *ExitingBlock,
8486 ExitCountKind Kind) {
8487 switch (Kind) {
8488 case Exact:
8489 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8490 case SymbolicMaximum:
8491 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8492 case ConstantMaximum:
8493 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8494 };
8495 llvm_unreachable("Invalid ExitCountKind!");
8496}
8497
8499 const Loop *L, const BasicBlock *ExitingBlock,
8501 switch (Kind) {
8502 case Exact:
8503 return getPredicatedBackedgeTakenInfo(L).getExact(ExitingBlock, this,
8504 Predicates);
8505 case SymbolicMaximum:
8506 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this,
8507 Predicates);
8508 case ConstantMaximum:
8509 return getPredicatedBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this,
8510 Predicates);
8511 };
8512 llvm_unreachable("Invalid ExitCountKind!");
8513}
8514
8517 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8518}
8519
8521 ExitCountKind Kind) {
8522 switch (Kind) {
8523 case Exact:
8524 return getBackedgeTakenInfo(L).getExact(L, this);
8525 case ConstantMaximum:
8526 return getBackedgeTakenInfo(L).getConstantMax(this);
8527 case SymbolicMaximum:
8528 return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8529 };
8530 llvm_unreachable("Invalid ExitCountKind!");
8531}
8532
8535 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(L, this, &Preds);
8536}
8537
8540 return getPredicatedBackedgeTakenInfo(L).getConstantMax(this, &Preds);
8541}
8542
8544 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8545}
8546
8547/// Push PHI nodes in the header of the given loop onto the given Worklist.
8548static void PushLoopPHIs(const Loop *L,
8551 BasicBlock *Header = L->getHeader();
8552
8553 // Push all Loop-header PHIs onto the Worklist stack.
8554 for (PHINode &PN : Header->phis())
8555 if (Visited.insert(&PN).second)
8556 Worklist.push_back(&PN);
8557}
8558
8559ScalarEvolution::BackedgeTakenInfo &
8560ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8561 auto &BTI = getBackedgeTakenInfo(L);
8562 if (BTI.hasFullInfo())
8563 return BTI;
8564
8565 auto Pair = PredicatedBackedgeTakenCounts.try_emplace(L);
8566
8567 if (!Pair.second)
8568 return Pair.first->second;
8569
8570 BackedgeTakenInfo Result =
8571 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8572
8573 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8574}
8575
8576ScalarEvolution::BackedgeTakenInfo &
8577ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8578 // Initially insert an invalid entry for this loop. If the insertion
8579 // succeeds, proceed to actually compute a backedge-taken count and
8580 // update the value. The temporary CouldNotCompute value tells SCEV
8581 // code elsewhere that it shouldn't attempt to request a new
8582 // backedge-taken count, which could result in infinite recursion.
8583 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8584 BackedgeTakenCounts.try_emplace(L);
8585 if (!Pair.second)
8586 return Pair.first->second;
8587
8588 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8589 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8590 // must be cleared in this scope.
8591 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8592
8593 // Now that we know more about the trip count for this loop, forget any
8594 // existing SCEV values for PHI nodes in this loop since they are only
8595 // conservative estimates made without the benefit of trip count
8596 // information. This invalidation is not necessary for correctness, and is
8597 // only done to produce more precise results.
8598 if (Result.hasAnyInfo()) {
8599 // Invalidate any expression using an addrec in this loop.
8600 SmallVector<SCEVUse, 8> ToForget;
8601 auto LoopUsersIt = LoopUsers.find(L);
8602 if (LoopUsersIt != LoopUsers.end())
8603 append_range(ToForget, LoopUsersIt->second);
8604 forgetMemoizedResults(ToForget);
8605
8606 // Invalidate constant-evolved loop header phis.
8607 for (PHINode &PN : L->getHeader()->phis())
8608 ConstantEvolutionLoopExitValue.erase(&PN);
8609 }
8610
8611 // Re-lookup the insert position, since the call to
8612 // computeBackedgeTakenCount above could result in a
8613 // recusive call to getBackedgeTakenInfo (on a different
8614 // loop), which would invalidate the iterator computed
8615 // earlier.
8616 return BackedgeTakenCounts.find(L)->second = std::move(Result);
8617}
8618
8620 // This method is intended to forget all info about loops. It should
8621 // invalidate caches as if the following happened:
8622 // - The trip counts of all loops have changed arbitrarily
8623 // - Every llvm::Value has been updated in place to produce a different
8624 // result.
8625 BackedgeTakenCounts.clear();
8626 PredicatedBackedgeTakenCounts.clear();
8627 BECountUsers.clear();
8628 LoopPropertiesCache.clear();
8629 ConstantEvolutionLoopExitValue.clear();
8630 ValueExprMap.clear();
8631 ValuesAtScopes.clear();
8632 ValuesAtScopesUsers.clear();
8633 LoopDispositions.clear();
8634 BlockDispositions.clear();
8635 UnsignedRanges.clear();
8636 SignedRanges.clear();
8637 ExprValueMap.clear();
8638 HasRecMap.clear();
8639 ConstantMultipleCache.clear();
8640 PredicatedSCEVRewrites.clear();
8641 FoldCache.clear();
8642 FoldCacheUser.clear();
8643}
8644void ScalarEvolution::visitAndClearUsers(
8647 SmallVectorImpl<SCEVUse> &ToForget) {
8648 while (!Worklist.empty()) {
8649 Instruction *I = Worklist.pop_back_val();
8650 if (!isSCEVable(I->getType()) && !isa<WithOverflowInst>(I))
8651 continue;
8652
8654 ValueExprMap.find_as(static_cast<Value *>(I));
8655 if (It != ValueExprMap.end()) {
8656 ToForget.push_back(It->second);
8657 eraseValueFromMap(It->first);
8658 if (PHINode *PN = dyn_cast<PHINode>(I))
8659 ConstantEvolutionLoopExitValue.erase(PN);
8660 }
8661
8662 PushDefUseChildren(I, Worklist, Visited);
8663 }
8664}
8665
8667 SmallVector<const Loop *, 16> LoopWorklist(1, L);
8670 SmallVector<SCEVUse, 16> ToForget;
8671
8672 // Iterate over all the loops and sub-loops to drop SCEV information.
8673 while (!LoopWorklist.empty()) {
8674 auto *CurrL = LoopWorklist.pop_back_val();
8675
8676 // Drop any stored trip count value.
8677 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8678 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8679
8680 // Drop information about predicated SCEV rewrites for this loop.
8681 PredicatedSCEVRewrites.remove_if(
8682 [&](const auto &Entry) { return Entry.first.second == CurrL; });
8683
8684 auto LoopUsersItr = LoopUsers.find(CurrL);
8685 if (LoopUsersItr != LoopUsers.end())
8686 llvm::append_range(ToForget, LoopUsersItr->second);
8687
8688 // Drop information about expressions based on loop-header PHIs.
8689 PushLoopPHIs(CurrL, Worklist, Visited);
8690 visitAndClearUsers(Worklist, Visited, ToForget);
8691
8692 LoopPropertiesCache.erase(CurrL);
8693 // Forget all contained loops too, to avoid dangling entries in the
8694 // ValuesAtScopes map.
8695 LoopWorklist.append(CurrL->begin(), CurrL->end());
8696 }
8697 forgetMemoizedResults(ToForget);
8698}
8699
8701 forgetLoop(L->getOutermostLoop());
8702}
8703
8706 if (!I) return;
8707
8708 // Drop information about expressions based on loop-header PHIs.
8711 SmallVector<SCEVUse, 8> ToForget;
8712 Worklist.push_back(I);
8713 Visited.insert(I);
8714 visitAndClearUsers(Worklist, Visited, ToForget);
8715
8716 forgetMemoizedResults(ToForget);
8717}
8718
8722 SmallVector<SCEVUse, 8> ToForget;
8723 for (Value *V : Values)
8724 if (auto *I = dyn_cast<Instruction>(V))
8725 if (Visited.insert(I).second)
8726 Worklist.push_back(I);
8727 visitAndClearUsers(Worklist, Visited, ToForget);
8728
8729 forgetMemoizedResults(ToForget);
8730}
8731
8733 // If SCEV looked through a trivial LCSSA phi node, we might have SCEV's
8734 // directly using a SCEVUnknown/SCEVAddRec defined in the loop. After an
8735 // extra predecessor is added, this is no longer valid. Find all Unknowns and
8736 // AddRecs defined in the loop and invalidate any SCEV's making use of them.
8737 auto InvalidateValue = [&](Value *Val) {
8738 if (!isSCEVable(Val->getType()))
8739 return;
8740 if (const SCEV *S = getExistingSCEV(Val)) {
8741 struct InvalidationRootCollector {
8742 Loop *L;
8744
8745 InvalidationRootCollector(Loop *L) : L(L) {}
8746
8747 bool follow(const SCEV *S) {
8748 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
8749 if (auto *I = dyn_cast<Instruction>(SU->getValue()))
8750 if (L->contains(I))
8751 Roots.push_back(S);
8752 } else if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
8753 if (L->contains(AddRec->getLoop()))
8754 Roots.push_back(S);
8755 }
8756 return true;
8757 }
8758 bool isDone() const { return false; }
8759 };
8760
8761 InvalidationRootCollector C(L);
8762 visitAll(S, C);
8763 forgetMemoizedResults(C.Roots);
8764 }
8765 };
8766
8767 InvalidateValue(V);
8768
8769 // If V has a non-SCEV-able type (e.g. {i64, i1} from a with.overflow
8770 // intrinsic), its users (e.g. extractvalue) may have stale SCEV
8771 // expressions referencing loop-internal values.
8772 if (!isSCEVable(V->getType()) &&
8773 any_of(V->incoming_values(), IsaPred<WithOverflowInst>))
8774 for (User *U : V->users())
8775 InvalidateValue(U);
8776 // Also perform the normal invalidation.
8777 forgetValue(V);
8778}
8779
8780void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8781
8783 // Unless a specific value is passed to invalidation, completely clear both
8784 // caches.
8785 if (!V) {
8786 BlockDispositions.clear();
8787 LoopDispositions.clear();
8788 return;
8789 }
8790
8791 if (!isSCEVable(V->getType()))
8792 return;
8793
8794 const SCEV *S = getExistingSCEV(V);
8795 if (!S)
8796 return;
8797
8798 // Invalidate the block and loop dispositions cached for S. Dispositions of
8799 // S's users may change if S's disposition changes (i.e. a user may change to
8800 // loop-invariant, if S changes to loop invariant), so also invalidate
8801 // dispositions of S's users recursively.
8802 SmallVector<SCEVUse, 8> Worklist = {S};
8804 while (!Worklist.empty()) {
8805 const SCEV *Curr = Worklist.pop_back_val();
8806 bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8807 bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8808 if (!LoopDispoRemoved && !BlockDispoRemoved)
8809 continue;
8810 auto Users = SCEVUsers.find(Curr);
8811 if (Users != SCEVUsers.end())
8812 for (const auto *User : Users->second)
8813 if (Seen.insert(User).second)
8814 Worklist.push_back(User);
8815 }
8816}
8817
8818/// Get the exact loop backedge taken count considering all loop exits. A
8819/// computable result can only be returned for loops with all exiting blocks
8820/// dominating the latch. howFarToZero assumes that the limit of each loop test
8821/// is never skipped. This is a valid assumption as long as the loop exits via
8822/// that test. For precise results, it is the caller's responsibility to specify
8823/// the relevant loop exiting block using getExact(ExitingBlock, SE).
8824const SCEV *ScalarEvolution::BackedgeTakenInfo::getExact(
8825 const Loop *L, ScalarEvolution *SE,
8827 // If any exits were not computable, the loop is not computable.
8828 if (!isComplete() || ExitNotTaken.empty())
8829 return SE->getCouldNotCompute();
8830
8831 const BasicBlock *Latch = L->getLoopLatch();
8832 // All exiting blocks we have collected must dominate the only backedge.
8833 if (!Latch)
8834 return SE->getCouldNotCompute();
8835
8836 // All exiting blocks we have gathered dominate loop's latch, so exact trip
8837 // count is simply a minimum out of all these calculated exit counts.
8839 for (const auto &ENT : ExitNotTaken) {
8840 const SCEV *BECount = ENT.ExactNotTaken;
8841 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8842 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8843 "We should only have known counts for exiting blocks that dominate "
8844 "latch!");
8845
8846 Ops.push_back(BECount);
8847
8848 if (Preds)
8849 append_range(*Preds, ENT.Predicates);
8850
8851 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8852 "Predicate should be always true!");
8853 }
8854
8855 // If an earlier exit exits on the first iteration (exit count zero), then
8856 // a later poison exit count should not propagate into the result. This are
8857 // exactly the semantics provided by umin_seq.
8858 return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8859}
8860
8861const ScalarEvolution::ExitNotTakenInfo *
8862ScalarEvolution::BackedgeTakenInfo::getExitNotTaken(
8863 const BasicBlock *ExitingBlock,
8864 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8865 for (const auto &ENT : ExitNotTaken)
8866 if (ENT.ExitingBlock == ExitingBlock) {
8867 if (ENT.hasAlwaysTruePredicate())
8868 return &ENT;
8869 else if (Predicates) {
8870 append_range(*Predicates, ENT.Predicates);
8871 return &ENT;
8872 }
8873 }
8874
8875 return nullptr;
8876}
8877
8878/// getConstantMax - Get the constant max backedge taken count for the loop.
8879const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8880 ScalarEvolution *SE,
8881 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8882 if (!getConstantMax())
8883 return SE->getCouldNotCompute();
8884
8885 for (const auto &ENT : ExitNotTaken)
8886 if (!ENT.hasAlwaysTruePredicate()) {
8887 if (!Predicates)
8888 return SE->getCouldNotCompute();
8889 append_range(*Predicates, ENT.Predicates);
8890 }
8891
8892 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8893 isa<SCEVConstant>(getConstantMax())) &&
8894 "No point in having a non-constant max backedge taken count!");
8895 return getConstantMax();
8896}
8897
8898const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8899 const Loop *L, ScalarEvolution *SE,
8900 SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8901 if (!SymbolicMax) {
8902 // Form an expression for the maximum exit count possible for this loop. We
8903 // merge the max and exact information to approximate a version of
8904 // getConstantMaxBackedgeTakenCount which isn't restricted to just
8905 // constants.
8906 SmallVector<SCEVUse, 4> ExitCounts;
8907
8908 for (const auto &ENT : ExitNotTaken) {
8909 const SCEV *ExitCount = ENT.SymbolicMaxNotTaken;
8910 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
8911 assert(SE->DT.dominates(ENT.ExitingBlock, L->getLoopLatch()) &&
8912 "We should only have known counts for exiting blocks that "
8913 "dominate latch!");
8914 ExitCounts.push_back(ExitCount);
8915 if (Predicates)
8916 append_range(*Predicates, ENT.Predicates);
8917
8918 assert((Predicates || ENT.hasAlwaysTruePredicate()) &&
8919 "Predicate should be always true!");
8920 }
8921 }
8922 if (ExitCounts.empty())
8923 SymbolicMax = SE->getCouldNotCompute();
8924 else
8925 SymbolicMax =
8926 SE->getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
8927 }
8928 return SymbolicMax;
8929}
8930
8931bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8932 ScalarEvolution *SE) const {
8933 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8934 return !ENT.hasAlwaysTruePredicate();
8935 };
8936 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8937}
8938
8941
8943 const SCEV *E, const SCEV *ConstantMaxNotTaken,
8944 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8948 // If we prove the max count is zero, so is the symbolic bound. This happens
8949 // in practice due to differences in a) how context sensitive we've chosen
8950 // to be and b) how we reason about bounds implied by UB.
8951 if (ConstantMaxNotTaken->isZero()) {
8952 this->ExactNotTaken = E = ConstantMaxNotTaken;
8953 this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
8954 }
8955
8958 "Exact is not allowed to be less precise than Constant Max");
8961 "Exact is not allowed to be less precise than Symbolic Max");
8964 "Symbolic Max is not allowed to be less precise than Constant Max");
8967 "No point in having a non-constant max backedge taken count!");
8969 for (const auto PredList : PredLists)
8970 for (const auto *P : PredList) {
8971 if (SeenPreds.contains(P))
8972 continue;
8973 assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!");
8974 SeenPreds.insert(P);
8975 Predicates.push_back(P);
8976 }
8977 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8978 "Backedge count should be int");
8980 !ConstantMaxNotTaken->getType()->isPointerTy()) &&
8981 "Max backedge count should be int");
8982}
8983
8991
8992/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8993/// computable exit into a persistent ExitNotTakenInfo array.
8994ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8996 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
8997 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8998 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8999
9000 ExitNotTaken.reserve(ExitCounts.size());
9001 std::transform(ExitCounts.begin(), ExitCounts.end(),
9002 std::back_inserter(ExitNotTaken),
9003 [&](const EdgeExitInfo &EEI) {
9004 BasicBlock *ExitBB = EEI.first;
9005 const ExitLimit &EL = EEI.second;
9006 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
9007 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
9008 EL.Predicates);
9009 });
9010 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
9011 isa<SCEVConstant>(ConstantMax)) &&
9012 "No point in having a non-constant max backedge taken count!");
9013}
9014
9015/// Compute the number of times the backedge of the specified loop will execute.
9016ScalarEvolution::BackedgeTakenInfo
9017ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
9018 bool AllowPredicates) {
9019 SmallVector<BasicBlock *, 8> ExitingBlocks;
9020 L->getExitingBlocks(ExitingBlocks);
9021
9022 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
9023
9025 bool CouldComputeBECount = true;
9026 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
9027 const SCEV *MustExitMaxBECount = nullptr;
9028 const SCEV *MayExitMaxBECount = nullptr;
9029 bool MustExitMaxOrZero = false;
9030 bool IsOnlyExit = ExitingBlocks.size() == 1;
9031
9032 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
9033 // and compute maxBECount.
9034 // Do a union of all the predicates here.
9035 for (BasicBlock *ExitBB : ExitingBlocks) {
9036 // We canonicalize untaken exits to br (constant), ignore them so that
9037 // proving an exit untaken doesn't negatively impact our ability to reason
9038 // about the loop as whole.
9039 if (auto *BI = dyn_cast<CondBrInst>(ExitBB->getTerminator()))
9040 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
9041 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9042 if (ExitIfTrue == CI->isZero())
9043 continue;
9044 }
9045
9046 ExitLimit EL = computeExitLimit(L, ExitBB, IsOnlyExit, AllowPredicates);
9047
9048 assert((AllowPredicates || EL.Predicates.empty()) &&
9049 "Predicated exit limit when predicates are not allowed!");
9050
9051 // 1. For each exit that can be computed, add an entry to ExitCounts.
9052 // CouldComputeBECount is true only if all exits can be computed.
9053 if (EL.ExactNotTaken != getCouldNotCompute())
9054 ++NumExitCountsComputed;
9055 else
9056 // We couldn't compute an exact value for this exit, so
9057 // we won't be able to compute an exact value for the loop.
9058 CouldComputeBECount = false;
9059 // Remember exit count if either exact or symbolic is known. Because
9060 // Exact always implies symbolic, only check symbolic.
9061 if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
9062 ExitCounts.emplace_back(ExitBB, EL);
9063 else {
9064 assert(EL.ExactNotTaken == getCouldNotCompute() &&
9065 "Exact is known but symbolic isn't?");
9066 ++NumExitCountsNotComputed;
9067 }
9068
9069 // 2. Derive the loop's MaxBECount from each exit's max number of
9070 // non-exiting iterations. Partition the loop exits into two kinds:
9071 // LoopMustExits and LoopMayExits.
9072 //
9073 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
9074 // is a LoopMayExit. If any computable LoopMustExit is found, then
9075 // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
9076 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
9077 // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
9078 // any
9079 // computable EL.ConstantMaxNotTaken.
9080 if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
9081 DT.dominates(ExitBB, Latch)) {
9082 if (!MustExitMaxBECount) {
9083 MustExitMaxBECount = EL.ConstantMaxNotTaken;
9084 MustExitMaxOrZero = EL.MaxOrZero;
9085 } else {
9086 MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
9087 EL.ConstantMaxNotTaken);
9088 }
9089 } else if (MayExitMaxBECount != getCouldNotCompute()) {
9090 if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
9091 MayExitMaxBECount = EL.ConstantMaxNotTaken;
9092 else {
9093 MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
9094 EL.ConstantMaxNotTaken);
9095 }
9096 }
9097 }
9098 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
9099 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
9100 // The loop backedge will be taken the maximum or zero times if there's
9101 // a single exit that must be taken the maximum or zero times.
9102 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
9103
9104 // Remember which SCEVs are used in exit limits for invalidation purposes.
9105 // We only care about non-constant SCEVs here, so we can ignore
9106 // EL.ConstantMaxNotTaken
9107 // and MaxBECount, which must be SCEVConstant.
9108 for (const auto &Pair : ExitCounts) {
9109 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
9110 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
9111 if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
9112 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
9113 {L, AllowPredicates});
9114 }
9115 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
9116 MaxBECount, MaxOrZero);
9117}
9118
9119ScalarEvolution::ExitLimit
9120ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
9121 bool IsOnlyExit, bool AllowPredicates) {
9122 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
9123 // If our exiting block does not dominate the latch, then its connection with
9124 // loop's exit limit may be far from trivial.
9125 const BasicBlock *Latch = L->getLoopLatch();
9126 if (!Latch || !DT.dominates(ExitingBlock, Latch))
9127 return getCouldNotCompute();
9128
9129 Instruction *Term = ExitingBlock->getTerminator();
9130 if (CondBrInst *BI = dyn_cast<CondBrInst>(Term)) {
9131 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9132 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
9133 "It should have one successor in loop and one exit block!");
9134 // Proceed to the next level to examine the exit condition expression.
9135 return computeExitLimitFromCond(L, BI->getCondition(), ExitIfTrue,
9136 /*ControlsOnlyExit=*/IsOnlyExit,
9137 AllowPredicates);
9138 }
9139
9140 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
9141 // For switch, make sure that there is a single exit from the loop.
9142 BasicBlock *Exit = nullptr;
9143 for (auto *SBB : successors(ExitingBlock))
9144 if (!L->contains(SBB)) {
9145 if (Exit) // Multiple exit successors.
9146 return getCouldNotCompute();
9147 Exit = SBB;
9148 }
9149 assert(Exit && "Exiting block must have at least one exit");
9150 return computeExitLimitFromSingleExitSwitch(
9151 L, SI, Exit, /*ControlsOnlyExit=*/IsOnlyExit);
9152 }
9153
9154 return getCouldNotCompute();
9155}
9156
9158 const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9159 bool AllowPredicates) {
9160 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
9161 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
9162 ControlsOnlyExit, AllowPredicates);
9163}
9164
9165std::optional<ScalarEvolution::ExitLimit>
9166ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
9167 bool ExitIfTrue, bool ControlsOnlyExit,
9168 bool AllowPredicates) {
9169 (void)this->L;
9170 (void)this->ExitIfTrue;
9171 (void)this->AllowPredicates;
9172
9173 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9174 this->AllowPredicates == AllowPredicates &&
9175 "Variance in assumed invariant key components!");
9176 auto Itr = TripCountMap.find({ExitCond, ControlsOnlyExit});
9177 if (Itr == TripCountMap.end())
9178 return std::nullopt;
9179 return Itr->second;
9180}
9181
9182void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
9183 bool ExitIfTrue,
9184 bool ControlsOnlyExit,
9185 bool AllowPredicates,
9186 const ExitLimit &EL) {
9187 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9188 this->AllowPredicates == AllowPredicates &&
9189 "Variance in assumed invariant key components!");
9190
9191 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsOnlyExit}, EL});
9192 assert(InsertResult.second && "Expected successful insertion!");
9193 (void)InsertResult;
9194 (void)ExitIfTrue;
9195}
9196
9197ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
9198 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9199 bool ControlsOnlyExit, bool AllowPredicates) {
9200
9201 if (auto MaybeEL = Cache.find(L, ExitCond, ExitIfTrue, ControlsOnlyExit,
9202 AllowPredicates))
9203 return *MaybeEL;
9204
9205 ExitLimit EL = computeExitLimitFromCondImpl(
9206 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates);
9207 Cache.insert(L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates, EL);
9208 return EL;
9209}
9210
9211ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
9212 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9213 bool ControlsOnlyExit, bool AllowPredicates) {
9214 // Handle BinOp conditions (And, Or).
9215 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
9216 Cache, L, ExitCond, ExitIfTrue, AllowPredicates))
9217 return *LimitFromBinOp;
9218
9219 // With an icmp, it may be feasible to compute an exact backedge-taken count.
9220 // Proceed to the next level to examine the icmp.
9221 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
9222 ExitLimit EL =
9223 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsOnlyExit);
9224 if (EL.hasFullInfo() || !AllowPredicates)
9225 return EL;
9226
9227 // Try again, but use SCEV predicates this time.
9228 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue,
9229 ControlsOnlyExit,
9230 /*AllowPredicates=*/true);
9231 }
9232
9233 // Check for a constant condition. These are normally stripped out by
9234 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
9235 // preserve the CFG and is temporarily leaving constant conditions
9236 // in place.
9237 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
9238 if (ExitIfTrue == !CI->getZExtValue())
9239 // The backedge is always taken.
9240 return getCouldNotCompute();
9241 // The backedge is never taken.
9242 return getZero(CI->getType());
9243 }
9244
9245 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
9246 // with a constant step, we can form an equivalent icmp predicate and figure
9247 // out how many iterations will be taken before we exit.
9248 const WithOverflowInst *WO;
9249 const APInt *C;
9250 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
9251 match(WO->getRHS(), m_APInt(C))) {
9252 ConstantRange NWR =
9254 WO->getNoWrapKind());
9255 CmpInst::Predicate Pred;
9256 APInt NewRHSC, Offset;
9257 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
9258 if (!ExitIfTrue)
9259 Pred = ICmpInst::getInversePredicate(Pred);
9260 auto *LHS = getSCEV(WO->getLHS());
9261 if (Offset != 0)
9263 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
9264 ControlsOnlyExit, AllowPredicates);
9265 if (EL.hasAnyInfo())
9266 return EL;
9267 }
9268
9269 // If it's not an integer or pointer comparison then compute it the hard way.
9270 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9271}
9272
9273std::optional<ScalarEvolution::ExitLimit>
9274ScalarEvolution::computeExitLimitFromCondFromBinOp(ExitLimitCacheTy &Cache,
9275 const Loop *L,
9276 Value *ExitCond,
9277 bool ExitIfTrue,
9278 bool AllowPredicates) {
9279 // Check if the controlling expression for this loop is an And or Or.
9280 Value *Op0, *Op1;
9281 bool IsAnd;
9282 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
9283 IsAnd = true;
9284 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
9285 IsAnd = false;
9286 else
9287 return std::nullopt;
9288
9289 // A sub-condition of a non-trivial binop never solely controls the exit,
9290 // whether we exit always depends on both conditions.
9291 ExitLimit EL0 = computeExitLimitFromCondCached(
9292 Cache, L, Op0, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9293 ExitLimit EL1 = computeExitLimitFromCondCached(
9294 Cache, L, Op1, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9295
9296 // EitherMayExit is true in these two cases:
9297 // br (and Op0 Op1), loop, exit
9298 // br (or Op0 Op1), exit, loop
9299 bool EitherMayExit = IsAnd ^ ExitIfTrue;
9300
9301 const SCEV *BECount = getCouldNotCompute();
9302 const SCEV *ConstantMaxBECount = getCouldNotCompute();
9303 const SCEV *SymbolicMaxBECount = getCouldNotCompute();
9304 if (EitherMayExit) {
9305 bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
9306 // Both conditions must be same for the loop to continue executing.
9307 // Choose the less conservative count.
9308 if (EL0.ExactNotTaken != getCouldNotCompute() &&
9309 EL1.ExactNotTaken != getCouldNotCompute()) {
9310 BECount = getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken,
9311 UseSequentialUMin);
9312 }
9313 if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
9314 ConstantMaxBECount = EL1.ConstantMaxNotTaken;
9315 else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
9316 ConstantMaxBECount = EL0.ConstantMaxNotTaken;
9317 else
9318 ConstantMaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
9319 EL1.ConstantMaxNotTaken);
9320 if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
9321 SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
9322 else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
9323 SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
9324 else
9325 SymbolicMaxBECount = getUMinFromMismatchedTypes(
9326 EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
9327 } else {
9328 // Both conditions must be same at the same time for the loop to exit.
9329 // For now, be conservative.
9330 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
9331 BECount = EL0.ExactNotTaken;
9332 }
9333
9334 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
9335 // to be more aggressive when computing BECount than when computing
9336 // ConstantMaxBECount. In these cases it is possible for EL0.ExactNotTaken
9337 // and
9338 // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
9339 // EL1.ConstantMaxNotTaken to not.
9340 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
9341 !isa<SCEVCouldNotCompute>(BECount))
9342 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
9343 if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
9344 SymbolicMaxBECount =
9345 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
9346 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
9347 {ArrayRef(EL0.Predicates), ArrayRef(EL1.Predicates)});
9348}
9349
9350ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9351 const Loop *L, ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9352 bool AllowPredicates) {
9353 // If the condition was exit on true, convert the condition to exit on false
9354 CmpPredicate Pred;
9355 if (!ExitIfTrue)
9356 Pred = ExitCond->getCmpPredicate();
9357 else
9358 Pred = ExitCond->getInverseCmpPredicate();
9359 const ICmpInst::Predicate OriginalPred = Pred;
9360
9361 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
9362 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
9363
9364 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsOnlyExit,
9365 AllowPredicates);
9366 if (EL.hasAnyInfo())
9367 return EL;
9368
9369 auto *ExhaustiveCount =
9370 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9371
9372 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
9373 return ExhaustiveCount;
9374
9375 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
9376 ExitCond->getOperand(1), L, OriginalPred);
9377}
9378ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9379 const Loop *L, CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS,
9380 bool ControlsOnlyExit, bool AllowPredicates) {
9381
9382 // Try to evaluate any dependencies out of the loop.
9383 LHS = getSCEVAtScope(LHS, L);
9384 RHS = getSCEVAtScope(RHS, L);
9385
9386 // At this point, we would like to compute how many iterations of the
9387 // loop the predicate will return true for these inputs.
9388 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
9389 // If there is a loop-invariant, force it into the RHS.
9390 std::swap(LHS, RHS);
9392 }
9393
9394 bool ControllingFiniteLoop = ControlsOnlyExit && loopHasNoAbnormalExits(L) &&
9396 // Simplify the operands before analyzing them.
9397 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0);
9398
9399 // If we have a comparison of a chrec against a constant, try to use value
9400 // ranges to answer this query.
9401 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
9402 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
9403 if (AddRec->getLoop() == L) {
9404 // Form the constant range.
9405 ConstantRange CompRange =
9406 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
9407
9408 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
9409 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
9410 }
9411
9412 // If this loop must exit based on this condition (or execute undefined
9413 // behaviour), see if we can improve wrap flags. This is essentially
9414 // a must execute style proof.
9415 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
9416 // If we can prove the test sequence produced must repeat the same values
9417 // on self-wrap of the IV, then we can infer that IV doesn't self wrap
9418 // because if it did, we'd have an infinite (undefined) loop.
9419 // TODO: We can peel off any functions which are invertible *in L*. Loop
9420 // invariant terms are effectively constants for our purposes here.
9421 SCEVUse InnerLHS = LHS;
9422 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
9423 InnerLHS = ZExt->getOperand();
9424 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS);
9425 AR && !AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
9426 isKnownToBeAPowerOfTwo(AR->getStepRecurrence(*this), /*OrZero=*/true,
9427 /*OrNegative=*/true)) {
9428 auto Flags = AR->getNoWrapFlags();
9429 Flags = setFlags(Flags, SCEV::FlagNW);
9432 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9433 }
9434
9435 // For a slt/ult condition with a positive step, can we prove nsw/nuw?
9436 // From no-self-wrap, this follows trivially from the fact that every
9437 // (un)signed-wrapped, but not self-wrapped value must be LT than the
9438 // last value before (un)signed wrap. Since we know that last value
9439 // didn't exit, nor will any smaller one.
9440 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT) {
9441 auto WrapType = Pred == ICmpInst::ICMP_SLT ? SCEV::FlagNSW : SCEV::FlagNUW;
9442 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9443 AR && AR->getLoop() == L && AR->isAffine() &&
9444 !AR->getNoWrapFlags(WrapType) && AR->hasNoSelfWrap() &&
9445 isKnownPositive(AR->getStepRecurrence(*this))) {
9446 auto Flags = AR->getNoWrapFlags();
9447 Flags = setFlags(Flags, WrapType);
9450 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9451 }
9452 }
9453 }
9454
9455 switch (Pred) {
9456 case ICmpInst::ICMP_NE: { // while (X != Y)
9457 // Convert to: while (X-Y != 0)
9458 if (LHS->getType()->isPointerTy()) {
9461 return LHS;
9462 }
9463 if (RHS->getType()->isPointerTy()) {
9466 return RHS;
9467 }
9468 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit,
9469 AllowPredicates);
9470 if (EL.hasAnyInfo())
9471 return EL;
9472 break;
9473 }
9474 case ICmpInst::ICMP_EQ: { // while (X == Y)
9475 // Convert to: while (X-Y == 0)
9476 if (LHS->getType()->isPointerTy()) {
9479 return LHS;
9480 }
9481 if (RHS->getType()->isPointerTy()) {
9484 return RHS;
9485 }
9486 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
9487 if (EL.hasAnyInfo()) return EL;
9488 break;
9489 }
9490 case ICmpInst::ICMP_SLE:
9491 case ICmpInst::ICMP_ULE:
9492 // Since the loop is finite, an invariant RHS cannot include the boundary
9493 // value, otherwise it would loop forever.
9494 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9495 !isLoopInvariant(RHS, L)) {
9496 // Otherwise, perform the addition in a wider type, to avoid overflow.
9497 // If the LHS is an addrec with the appropriate nowrap flag, the
9498 // extension will be sunk into it and the exit count can be analyzed.
9499 auto *OldType = dyn_cast<IntegerType>(LHS->getType());
9500 if (!OldType)
9501 break;
9502 // Prefer doubling the bitwidth over adding a single bit to make it more
9503 // likely that we use a legal type.
9504 auto *NewType =
9505 Type::getIntNTy(OldType->getContext(), OldType->getBitWidth() * 2);
9506 if (ICmpInst::isSigned(Pred)) {
9507 LHS = getSignExtendExpr(LHS, NewType);
9508 RHS = getSignExtendExpr(RHS, NewType);
9509 } else {
9510 LHS = getZeroExtendExpr(LHS, NewType);
9511 RHS = getZeroExtendExpr(RHS, NewType);
9512 }
9513 }
9515 [[fallthrough]];
9516 case ICmpInst::ICMP_SLT:
9517 case ICmpInst::ICMP_ULT: { // while (X < Y)
9518 bool IsSigned = ICmpInst::isSigned(Pred);
9519 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9520 AllowPredicates);
9521 if (EL.hasAnyInfo())
9522 return EL;
9523 break;
9524 }
9525 case ICmpInst::ICMP_SGE:
9526 case ICmpInst::ICMP_UGE:
9527 // Since the loop is finite, an invariant RHS cannot include the boundary
9528 // value, otherwise it would loop forever.
9529 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9530 !isLoopInvariant(RHS, L))
9531 break;
9533 [[fallthrough]];
9534 case ICmpInst::ICMP_SGT:
9535 case ICmpInst::ICMP_UGT: { // while (X > Y)
9536 bool IsSigned = ICmpInst::isSigned(Pred);
9537 ExitLimit EL = howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9538 AllowPredicates);
9539 if (EL.hasAnyInfo())
9540 return EL;
9541 break;
9542 }
9543 default:
9544 break;
9545 }
9546
9547 return getCouldNotCompute();
9548}
9549
9550ScalarEvolution::ExitLimit
9551ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
9552 SwitchInst *Switch,
9553 BasicBlock *ExitingBlock,
9554 bool ControlsOnlyExit) {
9555 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
9556
9557 // Give up if the exit is the default dest of a switch.
9558 if (Switch->getDefaultDest() == ExitingBlock)
9559 return getCouldNotCompute();
9560
9561 assert(L->contains(Switch->getDefaultDest()) &&
9562 "Default case must not exit the loop!");
9563 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
9564 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
9565
9566 // while (X != Y) --> while (X-Y != 0)
9567 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit);
9568 if (EL.hasAnyInfo())
9569 return EL;
9570
9571 return getCouldNotCompute();
9572}
9573
9574static ConstantInt *
9576 ScalarEvolution &SE) {
9577 const SCEV *InVal = SE.getConstant(C);
9578 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
9580 "Evaluation of SCEV at constant didn't fold correctly?");
9581 return cast<SCEVConstant>(Val)->getValue();
9582}
9583
9584ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
9585 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
9586 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
9587 if (!RHS)
9588 return getCouldNotCompute();
9589
9590 const BasicBlock *Latch = L->getLoopLatch();
9591 if (!Latch)
9592 return getCouldNotCompute();
9593
9594 const BasicBlock *Predecessor = L->getLoopPredecessor();
9595 if (!Predecessor)
9596 return getCouldNotCompute();
9597
9598 // Return true if V is of the form "LHS `shift_op` <positive constant>".
9599 // Return LHS in OutLHS, shift_op in OutOpCode, and the shift amount in
9600 // OutShiftAmt.
9601 auto MatchPositiveShift = [](Value *V, Value *&OutLHS,
9602 Instruction::BinaryOps &OutOpCode,
9603 unsigned &OutShiftAmt) {
9604 using namespace PatternMatch;
9605
9606 ConstantInt *ShiftAmt;
9607 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9608 OutOpCode = Instruction::LShr;
9609 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9610 OutOpCode = Instruction::AShr;
9611 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9612 OutOpCode = Instruction::Shl;
9613 else
9614 return false;
9615
9616 uint64_t Amt = ShiftAmt->getValue().getLimitedValue();
9617 if (Amt == 0 || Amt >= OutLHS->getType()->getScalarSizeInBits())
9618 return false;
9619 OutShiftAmt = Amt;
9620 return true;
9621 };
9622
9623 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
9624 //
9625 // loop:
9626 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
9627 // %iv.shifted = lshr i32 %iv, <positive constant>
9628 //
9629 // Return true on a successful match. Return the corresponding PHI node (%iv
9630 // above) in PNOut, the opcode of the shift operation in OpCodeOut, and the
9631 // shift amount in ShiftAmtOut.
9632 auto MatchShiftRecurrence = [&](Value *V, PHINode *&PNOut,
9633 Instruction::BinaryOps &OpCodeOut,
9634 unsigned &ShiftAmtOut) {
9635 std::optional<Instruction::BinaryOps> PostShiftOpCode;
9636
9637 {
9639 Value *V;
9640 unsigned Amt;
9641
9642 // If we encounter a shift instruction, "peel off" the shift operation,
9643 // and remember that we did so. Later when we inspect %iv's backedge
9644 // value, we will make sure that the backedge value uses the same
9645 // operation.
9646 //
9647 // Note: the peeled shift operation does not have to be the same
9648 // instruction as the one feeding into the PHI's backedge value. We only
9649 // really care about it being the same *kind* of shift instruction --
9650 // that's all that is required for our later inferences to hold.
9651 if (MatchPositiveShift(LHS, V, OpC, Amt)) {
9652 PostShiftOpCode = OpC;
9653 LHS = V;
9654 }
9655 }
9656
9657 PNOut = dyn_cast<PHINode>(LHS);
9658 if (!PNOut || PNOut->getParent() != L->getHeader())
9659 return false;
9660
9661 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
9662 Value *OpLHS;
9663
9664 return
9665 // The backedge value for the PHI node must be a shift by a positive
9666 // amount
9667 MatchPositiveShift(BEValue, OpLHS, OpCodeOut, ShiftAmtOut) &&
9668
9669 // of the PHI node itself
9670 OpLHS == PNOut &&
9671
9672 // and the kind of shift should be match the kind of shift we peeled
9673 // off, if any.
9674 (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9675 };
9676
9677 PHINode *PN;
9679 unsigned ShiftAmt;
9680 if (!MatchShiftRecurrence(LHS, PN, OpCode, ShiftAmt))
9681 return getCouldNotCompute();
9682
9683 const DataLayout &DL = getDataLayout();
9684
9685 // The key rationale for this optimization is that for some kinds of shift
9686 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
9687 // within a finite number of iterations. If the condition guarding the
9688 // backedge (in the sense that the backedge is taken if the condition is true)
9689 // is false for the value the shift recurrence stabilizes to, then we know
9690 // that the backedge is taken only a finite number of times.
9691
9692 ConstantInt *StableValue = nullptr;
9693 switch (OpCode) {
9694 default:
9695 llvm_unreachable("Impossible case!");
9696
9697 case Instruction::AShr: {
9698 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
9699 // bitwidth(K) iterations.
9700 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
9701 KnownBits Known = computeKnownBits(FirstValue, DL, &AC,
9702 Predecessor->getTerminator(), &DT);
9703 auto *Ty = cast<IntegerType>(RHS->getType());
9704 if (Known.isNonNegative())
9705 StableValue = ConstantInt::get(Ty, 0);
9706 else if (Known.isNegative())
9707 StableValue = ConstantInt::get(Ty, -1, true);
9708 else
9709 return getCouldNotCompute();
9710
9711 break;
9712 }
9713 case Instruction::LShr:
9714 case Instruction::Shl:
9715 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
9716 // stabilize to 0 in at most bitwidth(K) iterations.
9717 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
9718 break;
9719 }
9720
9721 auto *Result =
9722 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
9723 assert(Result->getType()->isIntegerTy(1) &&
9724 "Otherwise cannot be an operand to a branch instruction");
9725
9726 if (Result->isNullValue()) {
9727 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9728 unsigned MaxBTC = BitWidth;
9729
9730 // For right-shift recurrences (lshr/ashr with non-negative start), we can
9731 // compute a tighter max backedge-taken count from the range of the start
9732 // value. After k shifts of ShiftAmt, value = start >> (k * ShiftAmt).
9733 // The value reaches 0 (the stable value) when k * ShiftAmt >=
9734 // activeBits(start), so max BTC = ceil(activeBits(maxStart) / ShiftAmt).
9735 if (OpCode == Instruction::LShr || OpCode == Instruction::AShr) {
9736 Value *StartValue = PN->getIncomingValueForBlock(Predecessor);
9737 const SCEV *StartSCEV = getSCEV(StartValue);
9738 APInt MaxStart = getUnsignedRangeMax(StartSCEV);
9739 if (MaxStart.isStrictlyPositive()) {
9740 unsigned ActiveBits = MaxStart.getActiveBits();
9741 unsigned RangeBTC = divideCeil(ActiveBits, ShiftAmt);
9742 MaxBTC = std::min(MaxBTC, RangeBTC);
9743 }
9744 }
9745
9746 const SCEV *UpperBound =
9748 return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
9749 }
9750
9751 return getCouldNotCompute();
9752}
9753
9754/// Return true if we can constant fold an instruction of the specified type,
9755/// assuming that all operands were constants.
9756static bool canConstantFold(const Instruction *I,
9757 const TargetLibraryInfo *TLI) {
9761 return true;
9762
9763 if (const CallInst *CI = dyn_cast<CallInst>(I))
9764 if (const Function *F = CI->getCalledFunction())
9765 return canConstantFoldCallTo(CI, F, TLI);
9766 return false;
9767}
9768
9769/// Determine whether this instruction can constant evolve within this loop
9770/// assuming its operands can all constant evolve.
9771static bool canConstantEvolve(Instruction *I, const Loop *L,
9772 const TargetLibraryInfo *TLI) {
9773 // An instruction outside of the loop can't be derived from a loop PHI.
9774 if (!L->contains(I)) return false;
9775
9776 if (isa<PHINode>(I)) {
9777 // We don't currently keep track of the control flow needed to evaluate
9778 // PHIs, so we cannot handle PHIs inside of loops.
9779 return L->getHeader() == I->getParent();
9780 }
9781
9782 // If we won't be able to constant fold this expression even if the operands
9783 // are constants, bail early.
9784 return canConstantFold(I, TLI);
9785}
9786
9787/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
9788/// recursing through each instruction operand until reaching a loop header phi.
9789static PHINode *
9792 const TargetLibraryInfo *TLI, unsigned Depth) {
9794 return nullptr;
9795
9796 // Otherwise, we can evaluate this instruction if all of its operands are
9797 // constant or derived from a PHI node themselves.
9798 PHINode *PHI = nullptr;
9799 for (Value *Op : UseInst->operands()) {
9800 if (isa<Constant>(Op)) continue;
9801
9803 if (!OpInst || !canConstantEvolve(OpInst, L, TLI))
9804 return nullptr;
9805
9806 PHINode *P = dyn_cast<PHINode>(OpInst);
9807 if (!P)
9808 // If this operand is already visited, reuse the prior result.
9809 // We may have P != PHI if this is the deepest point at which the
9810 // inconsistent paths meet.
9811 P = PHIMap.lookup(OpInst);
9812 if (!P) {
9813 // Recurse and memoize the results, whether a phi is found or not.
9814 // This recursive call invalidates pointers into PHIMap.
9815 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, TLI, Depth + 1);
9816 PHIMap[OpInst] = P;
9817 }
9818 if (!P)
9819 return nullptr; // Not evolving from PHI
9820 if (PHI && PHI != P)
9821 return nullptr; // Evolving from multiple different PHIs.
9822 PHI = P;
9823 }
9824 // This is a expression evolving from a constant PHI!
9825 return PHI;
9826}
9827
9828/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9829/// in the loop that V is derived from. We allow arbitrary operations along the
9830/// way, but the operands of an operation must either be constants or a value
9831/// derived from a constant PHI. If this expression does not fit with these
9832/// constraints, return null.
9834 const TargetLibraryInfo *TLI) {
9836 if (!I || !canConstantEvolve(I, L, TLI))
9837 return nullptr;
9838
9839 if (PHINode *PN = dyn_cast<PHINode>(I))
9840 return PN;
9841
9842 // Record non-constant instructions contained by the loop.
9844 return getConstantEvolvingPHIOperands(I, L, PHIMap, TLI, 0);
9845}
9846
9847/// EvaluateExpression - Given an expression that passes the
9848/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9849/// in the loop has the value PHIVal. If we can't fold this expression for some
9850/// reason, return null.
9853 const DataLayout &DL,
9854 const TargetLibraryInfo *TLI) {
9855 // Convenient constant check, but redundant for recursive calls.
9856 if (Constant *C = dyn_cast<Constant>(V)) return C;
9858 if (!I) return nullptr;
9859
9860 if (Constant *C = Vals.lookup(I)) return C;
9861
9862 // An instruction inside the loop depends on a value outside the loop that we
9863 // weren't given a mapping for, or a value such as a call inside the loop.
9864 if (!canConstantEvolve(I, L, TLI))
9865 return nullptr;
9866
9867 // An unmapped PHI can be due to a branch or another loop inside this loop,
9868 // or due to this not being the initial iteration through a loop where we
9869 // couldn't compute the evolution of this particular PHI last time.
9870 if (isa<PHINode>(I)) return nullptr;
9871
9872 std::vector<Constant*> Operands(I->getNumOperands());
9873
9874 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9875 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9876 if (!Operand) {
9877 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9878 if (!Operands[i]) return nullptr;
9879 continue;
9880 }
9881 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9882 Vals[Operand] = C;
9883 if (!C) return nullptr;
9884 Operands[i] = C;
9885 }
9886
9887 return ConstantFoldInstOperands(I, Operands, DL, TLI,
9888 /*AllowNonDeterministic=*/false);
9889}
9890
9891
9892// If every incoming value to PN except the one for BB is a specific Constant,
9893// return that, else return nullptr.
9895 Constant *IncomingVal = nullptr;
9896
9897 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9898 if (PN->getIncomingBlock(i) == BB)
9899 continue;
9900
9901 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
9902 if (!CurrentVal)
9903 return nullptr;
9904
9905 if (IncomingVal != CurrentVal) {
9906 if (IncomingVal)
9907 return nullptr;
9908 IncomingVal = CurrentVal;
9909 }
9910 }
9911
9912 return IncomingVal;
9913}
9914
9915/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9916/// in the header of its containing loop, we know the loop executes a
9917/// constant number of times, and the PHI node is just a recurrence
9918/// involving constants, fold it.
9919Constant *
9920ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9921 const APInt &BEs,
9922 const Loop *L) {
9923 auto [I, Inserted] = ConstantEvolutionLoopExitValue.try_emplace(PN);
9924 if (!Inserted)
9925 return I->second;
9926
9928 return nullptr; // Not going to evaluate it.
9929
9930 Constant *&RetVal = I->second;
9931
9932 DenseMap<Instruction *, Constant *> CurrentIterVals;
9933 BasicBlock *Header = L->getHeader();
9934 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9935
9936 BasicBlock *Latch = L->getLoopLatch();
9937 if (!Latch)
9938 return nullptr;
9939
9940 for (PHINode &PHI : Header->phis()) {
9941 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9942 CurrentIterVals[&PHI] = StartCST;
9943 }
9944 if (!CurrentIterVals.count(PN))
9945 return RetVal = nullptr;
9946
9947 Value *BEValue = PN->getIncomingValueForBlock(Latch);
9948
9949 // Execute the loop symbolically to determine the exit value.
9950 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
9951 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
9952
9953 unsigned NumIterations = BEs.getZExtValue(); // must be in range
9954 unsigned IterationNum = 0;
9955 const DataLayout &DL = getDataLayout();
9956 for (; ; ++IterationNum) {
9957 if (IterationNum == NumIterations)
9958 return RetVal = CurrentIterVals[PN]; // Got exit value!
9959
9960 // Compute the value of the PHIs for the next iteration.
9961 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9962 DenseMap<Instruction *, Constant *> NextIterVals;
9963 Constant *NextPHI =
9964 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9965 if (!NextPHI)
9966 return nullptr; // Couldn't evaluate!
9967 NextIterVals[PN] = NextPHI;
9968
9969 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9970
9971 // Also evaluate the other PHI nodes. However, we don't get to stop if we
9972 // cease to be able to evaluate one of them or if they stop evolving,
9973 // because that doesn't necessarily prevent us from computing PN.
9975 for (const auto &I : CurrentIterVals) {
9976 PHINode *PHI = dyn_cast<PHINode>(I.first);
9977 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
9978 PHIsToCompute.emplace_back(PHI, I.second);
9979 }
9980 // We use two distinct loops because EvaluateExpression may invalidate any
9981 // iterators into CurrentIterVals.
9982 for (const auto &I : PHIsToCompute) {
9983 PHINode *PHI = I.first;
9984 Constant *&NextPHI = NextIterVals[PHI];
9985 if (!NextPHI) { // Not already computed.
9986 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9987 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9988 }
9989 if (NextPHI != I.second)
9990 StoppedEvolving = false;
9991 }
9992
9993 // If all entries in CurrentIterVals == NextIterVals then we can stop
9994 // iterating, the loop can't continue to change.
9995 if (StoppedEvolving)
9996 return RetVal = CurrentIterVals[PN];
9997
9998 CurrentIterVals.swap(NextIterVals);
9999 }
10000}
10001
10002const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
10003 Value *Cond,
10004 bool ExitWhen) {
10005 PHINode *PN = getConstantEvolvingPHI(Cond, L, &TLI);
10006 if (!PN) return getCouldNotCompute();
10007
10008 // If the loop is canonicalized, the PHI will have exactly two entries.
10009 // That's the only form we support here.
10010 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
10011
10012 DenseMap<Instruction *, Constant *> CurrentIterVals;
10013 BasicBlock *Header = L->getHeader();
10014 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
10015
10016 BasicBlock *Latch = L->getLoopLatch();
10017 assert(Latch && "Should follow from NumIncomingValues == 2!");
10018
10019 for (PHINode &PHI : Header->phis()) {
10020 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
10021 CurrentIterVals[&PHI] = StartCST;
10022 }
10023 if (!CurrentIterVals.count(PN))
10024 return getCouldNotCompute();
10025
10026 // Okay, we find a PHI node that defines the trip count of this loop. Execute
10027 // the loop symbolically to determine when the condition gets a value of
10028 // "ExitWhen".
10029 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
10030 const DataLayout &DL = getDataLayout();
10031 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
10032 auto *CondVal = dyn_cast_or_null<ConstantInt>(
10033 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
10034
10035 // Couldn't symbolically evaluate.
10036 if (!CondVal) return getCouldNotCompute();
10037
10038 if (CondVal->getValue() == uint64_t(ExitWhen)) {
10039 ++NumBruteForceTripCountsComputed;
10040 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
10041 }
10042
10043 // Update all the PHI nodes for the next iteration.
10044 DenseMap<Instruction *, Constant *> NextIterVals;
10045
10046 // Create a list of which PHIs we need to compute. We want to do this before
10047 // calling EvaluateExpression on them because that may invalidate iterators
10048 // into CurrentIterVals.
10049 SmallVector<PHINode *, 8> PHIsToCompute;
10050 for (const auto &I : CurrentIterVals) {
10051 PHINode *PHI = dyn_cast<PHINode>(I.first);
10052 if (!PHI || PHI->getParent() != Header) continue;
10053 PHIsToCompute.push_back(PHI);
10054 }
10055 for (PHINode *PHI : PHIsToCompute) {
10056 Constant *&NextPHI = NextIterVals[PHI];
10057 if (NextPHI) continue; // Already computed!
10058
10059 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
10060 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
10061 }
10062 CurrentIterVals.swap(NextIterVals);
10063 }
10064
10065 // Too many iterations were needed to evaluate.
10066 return getCouldNotCompute();
10067}
10068
10070 auto &Values = ValuesAtScopes[V];
10071 // Check to see if we've folded this expression at this loop before.
10072 for (auto &LS : Values)
10073 if (LS.first == L)
10074 return LS.second ? LS.second : SCEVUse(V);
10075
10076 Values.emplace_back(L, nullptr);
10077
10078 // Otherwise compute it.
10079 SCEVUse C = computeSCEVAtScope(V, L);
10080 for (auto &LS : reverse(ValuesAtScopes[V]))
10081 if (LS.first == L) {
10082 LS.second = C;
10083 // Record the dependency under the bare expression: invalidation walks
10084 // expressions, and any use flags on C do not change which expression
10085 // this is the value at scope of.
10086 if (!isa<SCEVConstant>(C))
10087 ValuesAtScopesUsers[C.getPointer()].push_back({L, V});
10088 break;
10089 }
10090 return C;
10091}
10092
10093/// This builds up a Constant using the ConstantExpr interface. That way, we
10094/// will return Constants for objects which aren't represented by a
10095/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
10096/// Returns NULL if the SCEV isn't representable as a Constant.
10098 switch (V->getSCEVType()) {
10099 case scCouldNotCompute:
10100 case scAddRecExpr:
10101 case scVScale:
10102 return nullptr;
10103 case scConstant:
10104 return cast<SCEVConstant>(V)->getValue();
10105 case scUnknown:
10107 case scPtrToAddr: {
10109 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
10110 return ConstantExpr::getPtrToAddr(CastOp, P2I->getType());
10111
10112 return nullptr;
10113 }
10114 case scTruncate: {
10116 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
10117 return ConstantExpr::getTrunc(CastOp, ST->getType());
10118 return nullptr;
10119 }
10120 case scAddExpr: {
10121 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
10122 Constant *C = nullptr;
10123 for (const SCEV *Op : SA->operands()) {
10125 if (!OpC)
10126 return nullptr;
10127 if (!C) {
10128 C = OpC;
10129 continue;
10130 }
10131 assert(!C->getType()->isPointerTy() &&
10132 "Can only have one pointer, and it must be last");
10133 if (OpC->getType()->isPointerTy()) {
10134 // The offsets have been converted to bytes. We can add bytes using
10135 // an i8 GEP.
10136 C = ConstantExpr::getPtrAdd(OpC, C);
10137 } else {
10138 C = ConstantExpr::getAdd(C, OpC);
10139 }
10140 }
10141 return C;
10142 }
10143 case scMulExpr:
10144 case scSignExtend:
10145 case scZeroExtend:
10146 case scUDivExpr:
10147 case scSMaxExpr:
10148 case scUMaxExpr:
10149 case scSMinExpr:
10150 case scUMinExpr:
10152 return nullptr;
10153 }
10154 llvm_unreachable("Unknown SCEV kind!");
10155}
10156
10157const SCEV *ScalarEvolution::getWithOperands(const SCEV *S,
10158 SmallVectorImpl<SCEVUse> &NewOps) {
10159 switch (S->getSCEVType()) {
10160 case scTruncate:
10161 case scZeroExtend:
10162 case scSignExtend:
10163 case scPtrToAddr:
10164 return getCastExpr(S->getSCEVType(), NewOps[0], S->getType());
10165 case scAddRecExpr: {
10166 auto *AddRec = cast<SCEVAddRecExpr>(S);
10167 return getAddRecExpr(NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags());
10168 }
10169 case scAddExpr:
10170 return getAddExpr(NewOps, cast<SCEVAddExpr>(S)->getNoWrapFlags());
10171 case scMulExpr:
10172 return getMulExpr(NewOps, cast<SCEVMulExpr>(S)->getNoWrapFlags());
10173 case scUDivExpr:
10174 return getUDivExpr(NewOps[0], NewOps[1]);
10175 case scUMaxExpr:
10176 case scSMaxExpr:
10177 case scUMinExpr:
10178 case scSMinExpr:
10179 return getMinMaxExpr(S->getSCEVType(), NewOps);
10181 return getSequentialMinMaxExpr(S->getSCEVType(), NewOps);
10182 case scConstant:
10183 case scVScale:
10184 case scUnknown:
10185 return S;
10186 case scCouldNotCompute:
10187 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10188 }
10189 llvm_unreachable("Unknown SCEV kind!");
10190}
10191
10192SCEVUse ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
10193 switch (V->getSCEVType()) {
10194 case scConstant:
10195 case scVScale:
10196 return V;
10197 case scAddRecExpr: {
10198 // If this is a loop recurrence for a loop that does not contain L, then we
10199 // are dealing with the final value computed by the loop.
10200 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(V);
10201 // First, attempt to evaluate each operand.
10202 // Avoid performing the look-up in the common case where the specified
10203 // expression has no loop-variant portions.
10204 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
10205 SCEVUse OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
10206 if (OpAtScope == AddRec->getOperand(i))
10207 continue;
10208
10209 // Okay, at least one of these operands is loop variant but might be
10210 // foldable. Build a new instance of the folded commutative expression.
10212 NewOps.reserve(AddRec->getNumOperands());
10213 append_range(NewOps, AddRec->operands().take_front(i));
10214 NewOps.push_back(OpAtScope);
10215 for (++i; i != e; ++i)
10216 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
10217
10218 const SCEV *FoldedRec = getAddRecExpr(
10219 NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags(SCEV::FlagNW));
10220 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
10221 // The addrec may be folded to a nonrecurrence, for example, if the
10222 // induction variable is multiplied by zero after constant folding. Go
10223 // ahead and return the folded value.
10224 if (!AddRec)
10225 return FoldedRec;
10226 break;
10227 }
10228
10229 // If the scope is outside the addrec's loop, evaluate it by using the
10230 // loop exit value of the addrec.
10231 if (!AddRec->getLoop()->contains(L)) {
10232 SCEVUse ExitValue = AddRec->getExitValue(*this);
10233 if (isa<SCEVCouldNotCompute>(ExitValue))
10234 return AddRec;
10235 return ExitValue;
10236 }
10237
10238 return AddRec;
10239 }
10240 case scTruncate:
10241 case scZeroExtend:
10242 case scSignExtend:
10243 case scPtrToAddr:
10244 case scAddExpr:
10245 case scMulExpr:
10246 case scUDivExpr:
10247 case scUMaxExpr:
10248 case scSMaxExpr:
10249 case scUMinExpr:
10250 case scSMinExpr:
10251 case scSequentialUMinExpr: {
10252 ArrayRef<SCEVUse> Ops = V->operands();
10253 // Avoid performing the look-up in the common case where the specified
10254 // expression has no loop-variant portions.
10255 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
10256 SCEVUse OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10257 if (OpAtScope != Ops[i].getPointer()) {
10258 // Okay, at least one of these operands is loop variant but might be
10259 // foldable. Build a new instance of the folded commutative expression.
10261 NewOps.reserve(Ops.size());
10262 append_range(NewOps, Ops.take_front(i));
10263 NewOps.push_back(OpAtScope);
10264
10265 for (++i; i != e; ++i) {
10266 OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10267 NewOps.push_back(OpAtScope);
10268 }
10269
10270 return getWithOperands(V, NewOps);
10271 }
10272 }
10273 // If we got here, all operands are loop invariant.
10274 return V;
10275 }
10276 case scUnknown: {
10277 // If this instruction is evolved from a constant-evolving PHI, compute the
10278 // exit value from the loop without using SCEVs.
10279 const SCEVUnknown *SU = cast<SCEVUnknown>(V);
10281 if (!I)
10282 return V; // This is some other type of SCEVUnknown, just return it.
10283
10284 if (PHINode *PN = dyn_cast<PHINode>(I)) {
10285 const Loop *CurrLoop = this->LI[I->getParent()];
10286 // Looking for loop exit value.
10287 if (CurrLoop && CurrLoop->getParentLoop() == L &&
10288 PN->getParent() == CurrLoop->getHeader()) {
10289 // Okay, there is no closed form solution for the PHI node. Check
10290 // to see if the loop that contains it has a known backedge-taken
10291 // count. If so, we may be able to force computation of the exit
10292 // value.
10293 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
10294 // This trivial case can show up in some degenerate cases where
10295 // the incoming IR has not yet been fully simplified.
10296 if (BackedgeTakenCount->isZero()) {
10297 Value *InitValue = nullptr;
10298 bool MultipleInitValues = false;
10299 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
10300 if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
10301 if (!InitValue)
10302 InitValue = PN->getIncomingValue(i);
10303 else if (InitValue != PN->getIncomingValue(i)) {
10304 MultipleInitValues = true;
10305 break;
10306 }
10307 }
10308 }
10309 if (!MultipleInitValues && InitValue)
10310 return getSCEV(InitValue);
10311 }
10312 // Do we have a loop invariant value flowing around the backedge
10313 // for a loop which must execute the backedge?
10314 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
10315 isKnownNonZero(BackedgeTakenCount) &&
10316 PN->getNumIncomingValues() == 2) {
10317
10318 unsigned InLoopPred =
10319 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
10320 Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
10321 if (CurrLoop->isLoopInvariant(BackedgeVal))
10322 return getSCEV(BackedgeVal);
10323 }
10324 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
10325 // Okay, we know how many times the containing loop executes. If
10326 // this is a constant evolving PHI node, get the final value at
10327 // the specified iteration number.
10328 Constant *RV =
10329 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
10330 if (RV)
10331 return getSCEV(RV);
10332 }
10333 }
10334 }
10335
10336 // Okay, this is an expression that we cannot symbolically evaluate
10337 // into a SCEV. Check to see if it's possible to symbolically evaluate
10338 // the arguments into constants, and if so, try to constant propagate the
10339 // result. This is particularly useful for computing loop exit values.
10340 if (!canConstantFold(I, &TLI))
10341 return V; // This is some other type of SCEVUnknown, just return it.
10342
10343 SmallVector<Constant *, 4> Operands;
10344 Operands.reserve(I->getNumOperands());
10345 bool MadeImprovement = false;
10346 for (Value *Op : I->operands()) {
10347 if (Constant *C = dyn_cast<Constant>(Op)) {
10348 Operands.push_back(C);
10349 continue;
10350 }
10351
10352 // If any of the operands is non-constant and if they are
10353 // non-integer and non-pointer, don't even try to analyze them
10354 // with scev techniques.
10355 if (!isSCEVable(Op->getType()))
10356 return V;
10357
10358 const SCEV *OrigV = getSCEV(Op);
10359 const SCEV *OpV = getSCEVAtScope(OrigV, L);
10360 MadeImprovement |= OrigV != OpV;
10361
10363 if (!C)
10364 return V;
10365 assert(C->getType() == Op->getType() && "Type mismatch");
10366 Operands.push_back(C);
10367 }
10368
10369 // Check to see if getSCEVAtScope actually made an improvement.
10370 if (!MadeImprovement)
10371 return V; // This is some other type of SCEVUnknown, just return it.
10372
10373 Constant *C = nullptr;
10374 const DataLayout &DL = getDataLayout();
10375 C = ConstantFoldInstOperands(I, Operands, DL, &TLI,
10376 /*AllowNonDeterministic=*/false);
10377 if (!C)
10378 return V;
10379 return getSCEV(C);
10380 }
10381 case scCouldNotCompute:
10382 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10383 }
10384 llvm_unreachable("Unknown SCEV type!");
10385}
10386
10388 return getSCEVAtScope(getSCEV(V), L);
10389}
10390
10391const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
10393 return stripInjectiveFunctions(ZExt->getOperand());
10395 return stripInjectiveFunctions(SExt->getOperand());
10396 return S;
10397}
10398
10399/// Finds the minimum unsigned root of the following equation:
10400///
10401/// A * X = B (mod N)
10402///
10403/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
10404/// A and B isn't important.
10405///
10406/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
10407static const SCEV *
10410 ScalarEvolution &SE, const Loop *L) {
10411 uint32_t BW = A.getBitWidth();
10412 assert(BW == SE.getTypeSizeInBits(B->getType()));
10413 assert(A != 0 && "A must be non-zero.");
10414
10415 // 1. D = gcd(A, N)
10416 //
10417 // The gcd of A and N may have only one prime factor: 2. The number of
10418 // trailing zeros in A is its multiplicity
10419 uint32_t Mult2 = A.countr_zero();
10420 // D = 2^Mult2
10421
10422 // 2. Check if B is divisible by D.
10423 //
10424 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
10425 // is not less than multiplicity of this prime factor for D.
10426 unsigned MinTZ = SE.getMinTrailingZeros(B);
10427 // Try again with the terminator of the loop predecessor for context-specific
10428 // result, if MinTZ s too small.
10429 if (MinTZ < Mult2 && L->getLoopPredecessor())
10430 MinTZ = SE.getMinTrailingZeros(B, L->getLoopPredecessor()->getTerminator());
10431 if (MinTZ < Mult2) {
10432 // Check if we can prove there's no remainder using URem.
10433 const SCEV *URem =
10434 SE.getURemExpr(B, SE.getConstant(APInt::getOneBitSet(BW, Mult2)));
10435 const SCEV *Zero = SE.getZero(B->getType());
10436 if (!SE.isKnownPredicate(CmpInst::ICMP_EQ, URem, Zero)) {
10437 // Try to add a predicate ensuring B is a multiple of 1 << Mult2.
10438 if (!Predicates)
10439 return SE.getCouldNotCompute();
10440
10441 // Avoid adding a predicate that is known to be false.
10442 if (SE.isKnownPredicate(CmpInst::ICMP_NE, URem, Zero))
10443 return SE.getCouldNotCompute();
10444 Predicates->push_back(SE.getEqualPredicate(URem, Zero));
10445 }
10446 }
10447
10448 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
10449 // modulo (N / D).
10450 //
10451 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
10452 // (N / D) in general. The inverse itself always fits into BW bits, though,
10453 // so we immediately truncate it.
10454 APInt AD = A.lshr(Mult2).trunc(BW - Mult2); // AD = A / D
10455 APInt I = AD.multiplicativeInverse().zext(BW);
10456
10457 // 4. Compute the minimum unsigned root of the equation:
10458 // I * (B / D) mod (N / D)
10459 // To simplify the computation, we factor out the divide by D:
10460 // (I * B mod N) / D
10461 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
10462 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
10463}
10464
10465/// For a given quadratic addrec, generate coefficients of the corresponding
10466/// quadratic equation, multiplied by a common value to ensure that they are
10467/// integers.
10468/// The returned value is a tuple { A, B, C, M, BitWidth }, where
10469/// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
10470/// were multiplied by, and BitWidth is the bit width of the original addrec
10471/// coefficients.
10472/// This function returns std::nullopt if the addrec coefficients are not
10473/// compile- time constants.
10474static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
10476 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
10477 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
10478 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
10479 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
10480 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
10481 << *AddRec << '\n');
10482
10483 // We currently can only solve this if the coefficients are constants.
10484 if (!LC || !MC || !NC) {
10485 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
10486 return std::nullopt;
10487 }
10488
10489 APInt L = LC->getAPInt();
10490 APInt M = MC->getAPInt();
10491 APInt N = NC->getAPInt();
10492 assert(!N.isZero() && "This is not a quadratic addrec");
10493
10494 unsigned BitWidth = LC->getAPInt().getBitWidth();
10495 unsigned NewWidth = BitWidth + 1;
10496 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
10497 << BitWidth << '\n');
10498 // The sign-extension (as opposed to a zero-extension) here matches the
10499 // extension used in SolveQuadraticEquationWrap (with the same motivation).
10500 N = N.sext(NewWidth);
10501 M = M.sext(NewWidth);
10502 L = L.sext(NewWidth);
10503
10504 // The increments are M, M+N, M+2N, ..., so the accumulated values are
10505 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
10506 // L+M, L+2M+N, L+3M+3N, ...
10507 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
10508 //
10509 // The equation Acc = 0 is then
10510 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
10511 // In a quadratic form it becomes:
10512 // N n^2 + (2M-N) n + 2L = 0.
10513
10514 APInt A = N;
10515 APInt B = 2 * M - A;
10516 APInt C = 2 * L;
10517 APInt T = APInt(NewWidth, 2);
10518 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
10519 << "x + " << C << ", coeff bw: " << NewWidth
10520 << ", multiplied by " << T << '\n');
10521 return std::make_tuple(A, B, C, T, BitWidth);
10522}
10523
10524/// Helper function to compare optional APInts:
10525/// (a) if X and Y both exist, return min(X, Y),
10526/// (b) if neither X nor Y exist, return std::nullopt,
10527/// (c) if exactly one of X and Y exists, return that value.
10528static std::optional<APInt> MinOptional(std::optional<APInt> X,
10529 std::optional<APInt> Y) {
10530 if (X && Y) {
10531 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
10532 APInt XW = X->sext(W);
10533 APInt YW = Y->sext(W);
10534 return XW.slt(YW) ? *X : *Y;
10535 }
10536 if (!X && !Y)
10537 return std::nullopt;
10538 return X ? *X : *Y;
10539}
10540
10541/// Helper function to truncate an optional APInt to a given BitWidth.
10542/// When solving addrec-related equations, it is preferable to return a value
10543/// that has the same bit width as the original addrec's coefficients. If the
10544/// solution fits in the original bit width, truncate it (except for i1).
10545/// Returning a value of a different bit width may inhibit some optimizations.
10546///
10547/// In general, a solution to a quadratic equation generated from an addrec
10548/// may require BW+1 bits, where BW is the bit width of the addrec's
10549/// coefficients. The reason is that the coefficients of the quadratic
10550/// equation are BW+1 bits wide (to avoid truncation when converting from
10551/// the addrec to the equation).
10552static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
10553 unsigned BitWidth) {
10554 if (!X)
10555 return std::nullopt;
10556 unsigned W = X->getBitWidth();
10558 return X->trunc(BitWidth);
10559 return X;
10560}
10561
10562/// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
10563/// iterations. The values L, M, N are assumed to be signed, and they
10564/// should all have the same bit widths.
10565/// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
10566/// where BW is the bit width of the addrec's coefficients.
10567/// If the calculated value is a BW-bit integer (for BW > 1), it will be
10568/// returned as such, otherwise the bit width of the returned value may
10569/// be greater than BW.
10570///
10571/// This function returns std::nullopt if
10572/// (a) the addrec coefficients are not constant, or
10573/// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
10574/// like x^2 = 5, no integer solutions exist, in other cases an integer
10575/// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
10576static std::optional<APInt>
10578 APInt A, B, C, M;
10579 unsigned BitWidth;
10580 auto T = GetQuadraticEquation(AddRec);
10581 if (!T)
10582 return std::nullopt;
10583
10584 std::tie(A, B, C, M, BitWidth) = *T;
10585 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
10586 std::optional<APInt> X =
10588 if (!X)
10589 return std::nullopt;
10590
10591 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
10592 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
10593 if (!V->isZero())
10594 return std::nullopt;
10595
10596 return TruncIfPossible(X, BitWidth);
10597}
10598
10599/// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
10600/// iterations. The values M, N are assumed to be signed, and they
10601/// should all have the same bit widths.
10602/// Find the least n such that c(n) does not belong to the given range,
10603/// while c(n-1) does.
10604///
10605/// This function returns std::nullopt if
10606/// (a) the addrec coefficients are not constant, or
10607/// (b) SolveQuadraticEquationWrap was unable to find a solution for the
10608/// bounds of the range.
10609static std::optional<APInt>
10611 const ConstantRange &Range, ScalarEvolution &SE) {
10612 assert(AddRec->getOperand(0)->isZero() &&
10613 "Starting value of addrec should be 0");
10614 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
10615 << Range << ", addrec " << *AddRec << '\n');
10616 // This case is handled in getNumIterationsInRange. Here we can assume that
10617 // we start in the range.
10618 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
10619 "Addrec's initial value should be in range");
10620
10621 APInt A, B, C, M;
10622 unsigned BitWidth;
10623 auto T = GetQuadraticEquation(AddRec);
10624 if (!T)
10625 return std::nullopt;
10626
10627 // Be careful about the return value: there can be two reasons for not
10628 // returning an actual number. First, if no solutions to the equations
10629 // were found, and second, if the solutions don't leave the given range.
10630 // The first case means that the actual solution is "unknown", the second
10631 // means that it's known, but not valid. If the solution is unknown, we
10632 // cannot make any conclusions.
10633 // Return a pair: the optional solution and a flag indicating if the
10634 // solution was found.
10635 auto SolveForBoundary =
10636 [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
10637 // Solve for signed overflow and unsigned overflow, pick the lower
10638 // solution.
10639 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
10640 << Bound << " (before multiplying by " << M << ")\n");
10641 Bound *= M; // The quadratic equation multiplier.
10642
10643 std::optional<APInt> SO;
10644 if (BitWidth > 1) {
10645 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10646 "signed overflow\n");
10648 }
10649 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10650 "unsigned overflow\n");
10651 std::optional<APInt> UO =
10653
10654 auto LeavesRange = [&] (const APInt &X) {
10655 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
10656 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
10657 if (Range.contains(V0->getValue()))
10658 return false;
10659 // X should be at least 1, so X-1 is non-negative.
10660 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
10662 if (Range.contains(V1->getValue()))
10663 return true;
10664 return false;
10665 };
10666
10667 // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
10668 // can be a solution, but the function failed to find it. We cannot treat it
10669 // as "no solution".
10670 if (!SO || !UO)
10671 return {std::nullopt, false};
10672
10673 // Check the smaller value first to see if it leaves the range.
10674 // At this point, both SO and UO must have values.
10675 std::optional<APInt> Min = MinOptional(SO, UO);
10676 if (LeavesRange(*Min))
10677 return { Min, true };
10678 std::optional<APInt> Max = Min == SO ? UO : SO;
10679 if (LeavesRange(*Max))
10680 return { Max, true };
10681
10682 // Solutions were found, but were eliminated, hence the "true".
10683 return {std::nullopt, true};
10684 };
10685
10686 std::tie(A, B, C, M, BitWidth) = *T;
10687 // Lower bound is inclusive, subtract 1 to represent the exiting value.
10688 APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
10689 APInt Upper = Range.getUpper().sext(A.getBitWidth());
10690 auto SL = SolveForBoundary(Lower);
10691 auto SU = SolveForBoundary(Upper);
10692 // If any of the solutions was unknown, no meaninigful conclusions can
10693 // be made.
10694 if (!SL.second || !SU.second)
10695 return std::nullopt;
10696
10697 // Claim: The correct solution is not some value between Min and Max.
10698 //
10699 // Justification: Assuming that Min and Max are different values, one of
10700 // them is when the first signed overflow happens, the other is when the
10701 // first unsigned overflow happens. Crossing the range boundary is only
10702 // possible via an overflow (treating 0 as a special case of it, modeling
10703 // an overflow as crossing k*2^W for some k).
10704 //
10705 // The interesting case here is when Min was eliminated as an invalid
10706 // solution, but Max was not. The argument is that if there was another
10707 // overflow between Min and Max, it would also have been eliminated if
10708 // it was considered.
10709 //
10710 // For a given boundary, it is possible to have two overflows of the same
10711 // type (signed/unsigned) without having the other type in between: this
10712 // can happen when the vertex of the parabola is between the iterations
10713 // corresponding to the overflows. This is only possible when the two
10714 // overflows cross k*2^W for the same k. In such case, if the second one
10715 // left the range (and was the first one to do so), the first overflow
10716 // would have to enter the range, which would mean that either we had left
10717 // the range before or that we started outside of it. Both of these cases
10718 // are contradictions.
10719 //
10720 // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
10721 // solution is not some value between the Max for this boundary and the
10722 // Min of the other boundary.
10723 //
10724 // Justification: Assume that we had such Max_A and Min_B corresponding
10725 // to range boundaries A and B and such that Max_A < Min_B. If there was
10726 // a solution between Max_A and Min_B, it would have to be caused by an
10727 // overflow corresponding to either A or B. It cannot correspond to B,
10728 // since Min_B is the first occurrence of such an overflow. If it
10729 // corresponded to A, it would have to be either a signed or an unsigned
10730 // overflow that is larger than both eliminated overflows for A. But
10731 // between the eliminated overflows and this overflow, the values would
10732 // cover the entire value space, thus crossing the other boundary, which
10733 // is a contradiction.
10734
10735 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
10736}
10737
10738ScalarEvolution::ExitLimit ScalarEvolution::howFarToZero(const SCEV *V,
10739 const Loop *L,
10740 bool ControlsOnlyExit,
10741 bool AllowPredicates) {
10742
10743 // This is only used for loops with a "x != y" exit test. The exit condition
10744 // is now expressed as a single expression, V = x-y. So the exit test is
10745 // effectively V != 0. We know and take advantage of the fact that this
10746 // expression only being used in a comparison by zero context.
10747
10749 // If the value is a constant
10750 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10751 // If the value is already zero, the branch will execute zero times.
10752 if (C->getValue()->isZero()) return C;
10753 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10754 }
10755
10756 const SCEVAddRecExpr *AddRec =
10757 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
10758
10759 if (!AddRec && AllowPredicates)
10760 // Try to make this an AddRec using runtime tests, in the first X
10761 // iterations of this loop, where X is the SCEV expression found by the
10762 // algorithm below.
10763 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
10764
10765 if (!AddRec || AddRec->getLoop() != L)
10766 return getCouldNotCompute();
10767
10768 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
10769 // the quadratic equation to solve it.
10770 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
10771 // We can only use this value if the chrec ends up with an exact zero
10772 // value at this index. When solving for "X*X != 5", for example, we
10773 // should not accept a root of 2.
10774 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
10775 const auto *R = cast<SCEVConstant>(getConstant(*S));
10776 return ExitLimit(R, R, R, false, Predicates);
10777 }
10778 return getCouldNotCompute();
10779 }
10780
10781 // Otherwise we can only handle this if it is affine.
10782 if (!AddRec->isAffine())
10783 return getCouldNotCompute();
10784
10785 // If this is an affine expression, the execution count of this branch is
10786 // the minimum unsigned root of the following equation:
10787 //
10788 // Start + Step*N = 0 (mod 2^BW)
10789 //
10790 // equivalent to:
10791 //
10792 // Step*N = -Start (mod 2^BW)
10793 //
10794 // where BW is the common bit width of Start and Step.
10795
10796 // Get the initial value for the loop.
10797 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
10798 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
10799
10800 if (!isLoopInvariant(Step, L))
10801 return getCouldNotCompute();
10802
10803 LoopGuards Guards = LoopGuards::collect(L, *this);
10804 // Specialize step for this loop so we get context sensitive facts below.
10805 const SCEV *StepWLG = applyLoopGuards(Step, Guards);
10806
10807 // For positive steps (counting up until unsigned overflow):
10808 // N = -Start/Step (as unsigned)
10809 // For negative steps (counting down to zero):
10810 // N = Start/-Step
10811 // First compute the unsigned distance from zero in the direction of Step.
10812 bool CountDown = isKnownNegative(StepWLG);
10813 if (!CountDown && !isKnownNonNegative(StepWLG))
10814 return getCouldNotCompute();
10815
10816 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
10817 // Handle unitary steps, which cannot wraparound.
10818 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10819 // N = Distance (as unsigned)
10820
10821 if (match(Step, m_CombineOr(m_scev_One(), m_scev_AllOnes()))) {
10822 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, Guards));
10823 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
10824
10825 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10826 // we end up with a loop whose backedge-taken count is n - 1. Detect this
10827 // case, and see if we can improve the bound.
10828 //
10829 // Explicitly handling this here is necessary because getUnsignedRange
10830 // isn't context-sensitive; it doesn't know that we only care about the
10831 // range inside the loop.
10832 const SCEV *Zero = getZero(Distance->getType());
10833 const SCEV *One = getOne(Distance->getType());
10834 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
10835 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
10836 // If Distance + 1 doesn't overflow, we can compute the maximum distance
10837 // as "unsigned_max(Distance + 1) - 1". Also apply the loop guards to
10838 // Distance + 1; the range of Distance itself may be a wrapped set even
10839 // when the guards bound Distance + 1 tightly.
10840 APInt Max = APIntOps::umin(
10841 getUnsignedRangeMax(applyLoopGuards(DistancePlusOne, Guards)),
10842 getUnsignedRangeMax(DistancePlusOne));
10843 MaxBECount = APIntOps::umin(MaxBECount, Max - 1);
10844 }
10845 return ExitLimit(Distance, getConstant(MaxBECount), Distance, false,
10846 Predicates);
10847 }
10848
10849 // If the condition controls loop exit (the loop exits only if the expression
10850 // is true) and the addition is no-wrap we can use unsigned divide to
10851 // compute the backedge count. In this case, the step may not divide the
10852 // distance, but we don't care because if the condition is "missed" the loop
10853 // will have undefined behavior due to wrapping.
10854 if (ControlsOnlyExit && AddRec->hasNoSelfWrap() &&
10855 loopHasNoAbnormalExits(AddRec->getLoop())) {
10856
10857 // If the stride is zero and the start is non-zero, the loop must be
10858 // infinite. In C++, most loops are finite by assumption, in which case the
10859 // step being zero implies UB must execute if the loop is entered.
10860 if (!(loopIsFiniteByAssumption(L) && isKnownNonZero(Start)) &&
10861 !isKnownNonZero(StepWLG))
10862 return getCouldNotCompute();
10863
10864 const SCEV *Exact =
10865 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10866 const SCEV *ConstantMax = getCouldNotCompute();
10867 if (Exact != getCouldNotCompute()) {
10868 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, Guards));
10869 ConstantMax =
10871 }
10872 const SCEV *SymbolicMax =
10873 isa<SCEVCouldNotCompute>(Exact) ? ConstantMax : Exact;
10874 return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
10875 }
10876
10877 // Solve the general equation.
10878 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
10879 if (!StepC || StepC->getValue()->isZero())
10880 return getCouldNotCompute();
10881 const SCEV *E = SolveLinEquationWithOverflow(
10882 StepC->getAPInt(), getNegativeSCEV(Start),
10883 AllowPredicates ? &Predicates : nullptr, *this, L);
10884
10885 const SCEV *M = E;
10886 if (E != getCouldNotCompute()) {
10887 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, Guards));
10888 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
10889 }
10890 auto *S = isa<SCEVCouldNotCompute>(E) ? M : E;
10891 return ExitLimit(E, M, S, false, Predicates);
10892}
10893
10894ScalarEvolution::ExitLimit
10895ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10896 // Loops that look like: while (X == 0) are very strange indeed. We don't
10897 // handle them yet except for the trivial case. This could be expanded in the
10898 // future as needed.
10899
10900 // If the value is a constant, check to see if it is known to be non-zero
10901 // already. If so, the backedge will execute zero times.
10902 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10903 if (!C->getValue()->isZero())
10904 return getZero(C->getType());
10905 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10906 }
10907
10908 // We could implement others, but I really doubt anyone writes loops like
10909 // this, and if they did, they would already be constant folded.
10910 return getCouldNotCompute();
10911}
10912
10913std::pair<const BasicBlock *, const BasicBlock *>
10914ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10915 const {
10916 // If the block has a unique predecessor, then there is no path from the
10917 // predecessor to the block that does not go through the direct edge
10918 // from the predecessor to the block.
10919 if (const BasicBlock *Pred = BB->getSinglePredecessor())
10920 return {Pred, BB};
10921
10922 // A loop's header is defined to be a block that dominates the loop.
10923 // If the header has a unique predecessor outside the loop, it must be
10924 // a block that has exactly one successor that can reach the loop.
10925 if (const Loop *L = LI.getLoopFor(BB))
10926 return {L->getLoopPredecessor(), L->getHeader()};
10927
10928 return {nullptr, BB};
10929}
10930
10931/// SCEV structural equivalence is usually sufficient for testing whether two
10932/// expressions are equal, however for the purposes of looking for a condition
10933/// guarding a loop, it can be useful to be a little more general, since a
10934/// front-end may have replicated the controlling expression.
10935static bool HasSameValue(const SCEV *A, const SCEV *B) {
10936 // Quick check to see if they are the same SCEV.
10937 if (A == B) return true;
10938
10939 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10940 // Not all instructions that are "identical" compute the same value. For
10941 // instance, two distinct alloca instructions allocating the same type are
10942 // identical and do not read memory; but compute distinct values.
10943 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
10944 };
10945
10946 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10947 // two different instructions with the same value. Check for this case.
10948 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
10949 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
10950 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
10951 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
10952 if (ComputesEqualValues(AI, BI))
10953 return true;
10954
10955 // Otherwise assume they may have a different value.
10956 return false;
10957}
10958
10959static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS) {
10960 const SCEV *Op0, *Op1;
10961 if (!match(S, m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))))
10962 return false;
10963 if (match(Op0, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10964 LHS = Op1;
10965 return true;
10966 }
10967 if (match(Op1, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10968 LHS = Op0;
10969 return true;
10970 }
10971 return false;
10972}
10973
10975 SCEVUse &RHS, unsigned Depth) {
10976 bool Changed = false;
10977 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
10978 // '0 != 0'.
10979 auto TrivialCase = [&](bool TriviallyTrue) {
10981 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
10982 return true;
10983 };
10984 // If we hit the max recursion limit bail out.
10985 if (Depth >= 3)
10986 return false;
10987
10988 const SCEV *NewLHS, *NewRHS;
10989 if (match(LHS, m_scev_c_Mul(m_SCEV(NewLHS), m_SCEVVScale())) &&
10990 match(RHS, m_scev_c_Mul(m_SCEV(NewRHS), m_SCEVVScale()))) {
10991 const SCEVMulExpr *LMul = cast<SCEVMulExpr>(LHS);
10992 const SCEVMulExpr *RMul = cast<SCEVMulExpr>(RHS);
10993
10994 // (X * vscale) pred (Y * vscale) ==> X pred Y
10995 // when both multiples are NSW.
10996 // (X * vscale) uicmp/eq/ne (Y * vscale) ==> X uicmp/eq/ne Y
10997 // when both multiples are NUW.
10998 if ((LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap()) ||
10999 (LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap() &&
11000 !ICmpInst::isSigned(Pred))) {
11001 LHS = NewLHS;
11002 RHS = NewRHS;
11003 Changed = true;
11004 }
11005 }
11006
11007 // Canonicalize a constant to the right side.
11008 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
11009 // Check for both operands constant.
11010 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
11011 if (!ICmpInst::compare(LHSC->getAPInt(), RHSC->getAPInt(), Pred))
11012 return TrivialCase(false);
11013 return TrivialCase(true);
11014 }
11015 // Otherwise swap the operands to put the constant on the right.
11016 std::swap(LHS, RHS);
11018 Changed = true;
11019 }
11020
11021 // (K + A) pred (K + B) --> A pred B
11022 // For equality, no flags are needed.
11023 // For signed, both adds must be NSW. For unsigned, both must be NUW.
11024 {
11025 const SCEVConstant *C = nullptr;
11026 if (match(LHS, m_scev_Add(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11027 match(RHS, m_scev_Add(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11028 const auto *LAdd = cast<SCEVAddExpr>(LHS);
11029 const auto *RAdd = cast<SCEVAddExpr>(RHS);
11030 if (ICmpInst::isEquality(Pred) ||
11031 (ICmpInst::isSigned(Pred) && LAdd->hasNoSignedWrap() &&
11032 RAdd->hasNoSignedWrap()) ||
11033 (ICmpInst::isUnsigned(Pred) && LAdd->hasNoUnsignedWrap() &&
11034 RAdd->hasNoUnsignedWrap())) {
11035 LHS = NewLHS;
11036 RHS = NewRHS;
11037 Changed = true;
11038 }
11039 }
11040 }
11041
11042 // (C * A) pred (C * B) --> A pred B
11043 // For equality predicates, both muls must be NUW or both must be NSW
11044 // (either suffices to make multiplication by C injective; C == 0 is
11045 // impossible because SCEV folds 0 * X to 0).
11046 // For signed ordering, C must be positive and both muls must be NSW.
11047 // For unsigned ordering, both muls must be NUW.
11048 {
11049 const SCEVConstant *C = nullptr;
11050 if (match(LHS, m_scev_Mul(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11051 match(RHS, m_scev_Mul(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11052 const auto *LMul = cast<SCEVMulExpr>(LHS);
11053 const auto *RMul = cast<SCEVMulExpr>(RHS);
11054 bool BothNUW = LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap();
11055 bool BothNSW = LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap();
11056 if ((ICmpInst::isEquality(Pred) && (BothNUW || BothNSW)) ||
11057 (ICmpInst::isSigned(Pred) && BothNSW &&
11058 C->getAPInt().isStrictlyPositive()) ||
11059 (ICmpInst::isUnsigned(Pred) && BothNUW)) {
11060 LHS = NewLHS;
11061 RHS = NewRHS;
11062 Changed = true;
11063 }
11064 }
11065 }
11066
11067 // If we're comparing an addrec with a value which is loop-invariant in the
11068 // addrec's loop, put the addrec on the left. Also make a dominance check,
11069 // as both operands could be addrecs loop-invariant in each other's loop.
11070 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
11071 const Loop *L = AR->getLoop();
11072 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
11073 std::swap(LHS, RHS);
11075 Changed = true;
11076 }
11077 }
11078
11079 // If there's a constant operand, canonicalize comparisons with boundary
11080 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
11081 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
11082 const APInt &RA = RC->getAPInt();
11083
11084 bool SimplifiedByConstantRange = false;
11085
11086 if (!ICmpInst::isEquality(Pred)) {
11088 if (ExactCR.isFullSet())
11089 return TrivialCase(true);
11090 if (ExactCR.isEmptySet())
11091 return TrivialCase(false);
11092
11093 APInt NewRHS;
11094 CmpInst::Predicate NewPred;
11095 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
11096 ICmpInst::isEquality(NewPred)) {
11097 // We were able to convert an inequality to an equality.
11098 Pred = NewPred;
11099 RHS = getConstant(NewRHS);
11100 Changed = SimplifiedByConstantRange = true;
11101 }
11102 }
11103
11104 if (!SimplifiedByConstantRange) {
11105 switch (Pred) {
11106 default:
11107 break;
11108 case ICmpInst::ICMP_EQ:
11109 case ICmpInst::ICMP_NE:
11110 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
11111 if (RA.isZero() && MatchBinarySub(LHS, LHS, RHS))
11112 Changed = true;
11113 break;
11114
11115 // The "Should have been caught earlier!" messages refer to the fact
11116 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
11117 // should have fired on the corresponding cases, and canonicalized the
11118 // check to trivial case.
11119
11120 case ICmpInst::ICMP_UGE:
11121 assert(!RA.isMinValue() && "Should have been caught earlier!");
11122 Pred = ICmpInst::ICMP_UGT;
11123 RHS = getConstant(RA - 1);
11124 Changed = true;
11125 break;
11126 case ICmpInst::ICMP_ULE:
11127 assert(!RA.isMaxValue() && "Should have been caught earlier!");
11128 Pred = ICmpInst::ICMP_ULT;
11129 RHS = getConstant(RA + 1);
11130 Changed = true;
11131 break;
11132 case ICmpInst::ICMP_SGE:
11133 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
11134 Pred = ICmpInst::ICMP_SGT;
11135 RHS = getConstant(RA - 1);
11136 Changed = true;
11137 break;
11138 case ICmpInst::ICMP_SLE:
11139 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
11140 Pred = ICmpInst::ICMP_SLT;
11141 RHS = getConstant(RA + 1);
11142 Changed = true;
11143 break;
11144 }
11145 }
11146 }
11147
11148 // a /u b == 0 => a < b
11149 // a /u b != 0 => a >= b
11150 if (ICmpInst::isEquality(Pred) && RHS->isZero() &&
11151 match(LHS, m_scev_UDiv(m_SCEV(LHS), m_SCEV(RHS)))) {
11153 Changed = true;
11154 }
11155
11156 // Check for obvious equality.
11157 if (HasSameValue(LHS, RHS)) {
11158 if (ICmpInst::isTrueWhenEqual(Pred))
11159 return TrivialCase(true);
11161 return TrivialCase(false);
11162 }
11163
11164 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
11165 // adding or subtracting 1 from one of the operands.
11166 switch (Pred) {
11167 case ICmpInst::ICMP_SLE:
11168 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
11169 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11171 Pred = ICmpInst::ICMP_SLT;
11172 Changed = true;
11173 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
11174 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
11176 Pred = ICmpInst::ICMP_SLT;
11177 Changed = true;
11178 }
11179 break;
11180 case ICmpInst::ICMP_SGE:
11181 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
11182 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
11184 Pred = ICmpInst::ICMP_SGT;
11185 Changed = true;
11186 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
11187 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11189 Pred = ICmpInst::ICMP_SGT;
11190 Changed = true;
11191 }
11192 break;
11193 case ICmpInst::ICMP_ULE:
11194 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
11195 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11197 Pred = ICmpInst::ICMP_ULT;
11198 Changed = true;
11199 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
11200 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
11201 Pred = ICmpInst::ICMP_ULT;
11202 Changed = true;
11203 }
11204 break;
11205 case ICmpInst::ICMP_UGE:
11206 // If RHS is an op we can fold the -1, try that first.
11207 // Otherwise prefer LHS to preserve the nuw flag.
11208 if ((isa<SCEVConstant>(RHS) ||
11210 isa<SCEVConstant>(cast<SCEVNAryExpr>(RHS)->getOperand(0)))) &&
11211 !getUnsignedRangeMin(RHS).isMinValue()) {
11212 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11213 Pred = ICmpInst::ICMP_UGT;
11214 Changed = true;
11215 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
11216 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11218 Pred = ICmpInst::ICMP_UGT;
11219 Changed = true;
11220 } else if (!getUnsignedRangeMin(RHS).isMinValue()) {
11221 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11222 Pred = ICmpInst::ICMP_UGT;
11223 Changed = true;
11224 }
11225 break;
11226 default:
11227 break;
11228 }
11229
11230 // TODO: More simplifications are possible here.
11231
11232 // Recursively simplify until we either hit a recursion limit or nothing
11233 // changes.
11234 if (Changed)
11235 (void)SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1);
11236
11237 return Changed;
11238}
11239
11241 return getSignedRangeMax(S).isNegative();
11242}
11243
11247
11249 return !getSignedRangeMin(S).isNegative();
11250}
11251
11255
11257 // Query push down for cases where the unsigned range is
11258 // less than sufficient.
11259 if (const auto *SExt = dyn_cast<SCEVSignExtendExpr>(S))
11260 return isKnownNonZero(SExt->getOperand(0));
11261 return getUnsignedRangeMin(S) != 0;
11262}
11263
11265 bool OrNegative) {
11266 auto NonRecursive = [OrNegative](const SCEV *S) {
11267 if (auto *C = dyn_cast<SCEVConstant>(S))
11268 return C->getAPInt().isPowerOf2() ||
11269 (OrNegative && C->getAPInt().isNegatedPowerOf2());
11270
11271 // vscale is a power-of-two.
11272 return isa<SCEVVScale>(S);
11273 };
11274
11275 if (NonRecursive(S))
11276 return true;
11277
11278 auto *Mul = dyn_cast<SCEVMulExpr>(S);
11279 if (!Mul)
11280 return false;
11281 return all_of(Mul->operands(), NonRecursive) && (OrZero || isKnownNonZero(S));
11282}
11283
11285 const SCEV *S, uint64_t M,
11287 if (M == 0)
11288 return false;
11289 if (M == 1)
11290 return true;
11291
11292 // Recursively check AddRec operands. An AddRecExpr S is a multiple of M if S
11293 // starts with a multiple of M and at every iteration step S only adds
11294 // multiples of M.
11295 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
11296 return isKnownMultipleOf(AddRec->getStart(), M, Predicates) &&
11297 isKnownMultipleOf(AddRec->getStepRecurrence(*this), M, Predicates);
11298
11299 // For a constant, check that "S % M == 0".
11300 if (auto *Cst = dyn_cast<SCEVConstant>(S)) {
11301 APInt C = Cst->getAPInt();
11302 return C.urem(M) == 0;
11303 }
11304
11305 // TODO: Also check other SCEV expressions, i.e., SCEVAddRecExpr, etc.
11306
11307 // Basic tests have failed.
11308 // Check "S % M == 0" at compile time and record runtime Assumptions.
11309 auto *STy = dyn_cast<IntegerType>(S->getType());
11310 const SCEV *SmodM =
11311 getURemExpr(S, getConstant(ConstantInt::get(STy, M, false)));
11312 const SCEV *Zero = getZero(STy);
11313
11314 // Check whether "S % M == 0" is known at compile time.
11315 if (isKnownPredicate(ICmpInst::ICMP_EQ, SmodM, Zero))
11316 return true;
11317
11318 // Check whether "S % M != 0" is known at compile time.
11319 if (isKnownPredicate(ICmpInst::ICMP_NE, SmodM, Zero))
11320 return false;
11321
11322 if (!Predicates)
11323 return false;
11324
11326
11327 // Detect redundant predicates.
11328 for (auto *A : *Predicates)
11329 if (A->implies(P, *this))
11330 return true;
11331
11332 // Only record non-redundant predicates.
11333 Predicates->push_back(P);
11334 return true;
11335}
11336
11338 return ((isKnownNonNegative(S1) && isKnownNonNegative(S2)) ||
11340}
11341
11342std::pair<const SCEV *, const SCEV *>
11344 // Compute SCEV on entry of loop L.
11345 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
11346 if (Start == getCouldNotCompute())
11347 return { Start, Start };
11348 // Compute post increment SCEV for loop L.
11349 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
11350 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
11351 return { Start, PostInc };
11352}
11353
11355 SCEVUse RHS) {
11356 // First collect all loops.
11358 getUsedLoops(LHS, LoopsUsed);
11359 getUsedLoops(RHS, LoopsUsed);
11360
11361 if (LoopsUsed.empty())
11362 return false;
11363
11364 // Domination relationship must be a linear order on collected loops.
11365#ifndef NDEBUG
11366 for (const auto *L1 : LoopsUsed)
11367 for (const auto *L2 : LoopsUsed)
11368 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
11369 DT.dominates(L2->getHeader(), L1->getHeader())) &&
11370 "Domination relationship is not a linear order");
11371#endif
11372
11373 const Loop *MDL =
11374 *llvm::max_element(LoopsUsed, [&](const Loop *L1, const Loop *L2) {
11375 return DT.properlyDominates(L1->getHeader(), L2->getHeader());
11376 });
11377
11378 // Get init and post increment value for LHS.
11379 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
11380 // if LHS contains unknown non-invariant SCEV then bail out.
11381 if (SplitLHS.first == getCouldNotCompute())
11382 return false;
11383 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
11384 // Get init and post increment value for RHS.
11385 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
11386 // if RHS contains unknown non-invariant SCEV then bail out.
11387 if (SplitRHS.first == getCouldNotCompute())
11388 return false;
11389 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
11390 // It is possible that init SCEV contains an invariant load but it does
11391 // not dominate MDL and is not available at MDL loop entry, so we should
11392 // check it here.
11393 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
11394 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
11395 return false;
11396
11397 // It seems backedge guard check is faster than entry one so in some cases
11398 // it can speed up whole estimation by short circuit
11399 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
11400 SplitRHS.second) &&
11401 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
11402}
11403
11405 SCEVUse RHS) {
11406 // Canonicalize the inputs first.
11407 (void)SimplifyICmpOperands(Pred, LHS, RHS);
11408
11409 return isKnownViaInduction(Pred, LHS, RHS) ||
11410 isKnownPredicateViaSplitting(Pred, LHS, RHS) ||
11411 isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
11412}
11413
11415 const SCEV *LHS,
11416 const SCEV *RHS) {
11417 if (isKnownPredicate(Pred, LHS, RHS))
11418 return true;
11420 return false;
11421 return std::nullopt;
11422}
11423
11425 const SCEV *RHS,
11426 const Instruction *CtxI) {
11427 // TODO: Analyze guards and assumes from Context's block.
11428 return isKnownPredicate(Pred, LHS, RHS) ||
11429 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
11430}
11431
11432std::optional<bool>
11434 const SCEV *RHS, const Instruction *CtxI) {
11435 std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
11436 if (KnownWithoutContext)
11437 return KnownWithoutContext;
11438
11439 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
11440 return true;
11442 CtxI->getParent(), ICmpInst::getInverseCmpPredicate(Pred), LHS, RHS))
11443 return false;
11444 return std::nullopt;
11445}
11446
11448 const SCEVAddRecExpr *LHS,
11449 const SCEV *RHS) {
11450 const Loop *L = LHS->getLoop();
11451 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
11452 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
11453}
11454
11455std::optional<ScalarEvolution::MonotonicPredicateType>
11457 ICmpInst::Predicate Pred) {
11458 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
11459
11460#ifndef NDEBUG
11461 // Verify an invariant: inverting the predicate should turn a monotonically
11462 // increasing change to a monotonically decreasing one, and vice versa.
11463 if (Result) {
11464 auto ResultSwapped =
11465 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
11466
11467 assert(*ResultSwapped != *Result &&
11468 "monotonicity should flip as we flip the predicate");
11469 }
11470#endif
11471
11472 return Result;
11473}
11474
11475std::optional<ScalarEvolution::MonotonicPredicateType>
11476ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
11477 ICmpInst::Predicate Pred) {
11478 // A zero step value for LHS means the induction variable is essentially a
11479 // loop invariant value. We don't really depend on the predicate actually
11480 // flipping from false to true (for increasing predicates, and the other way
11481 // around for decreasing predicates), all we care about is that *if* the
11482 // predicate changes then it only changes from false to true.
11483 //
11484 // A zero step value in itself is not very useful, but there may be places
11485 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
11486 // as general as possible.
11487
11488 // Only handle LE/LT/GE/GT predicates.
11489 if (!ICmpInst::isRelational(Pred))
11490 return std::nullopt;
11491
11492 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
11493 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
11494 "Should be greater or less!");
11495
11496 // Check that AR does not wrap.
11497 if (ICmpInst::isUnsigned(Pred)) {
11498 if (!LHS->hasNoUnsignedWrap())
11499 return std::nullopt;
11501 }
11502 assert(ICmpInst::isSigned(Pred) &&
11503 "Relational predicate is either signed or unsigned!");
11504 if (!LHS->hasNoSignedWrap())
11505 return std::nullopt;
11506
11507 const SCEV *Step = LHS->getStepRecurrence(*this);
11508
11509 if (isKnownNonNegative(Step))
11511
11512 if (isKnownNonPositive(Step))
11514
11515 return std::nullopt;
11516}
11517
11518std::optional<ScalarEvolution::LoopInvariantPredicate>
11520 const SCEV *RHS, const Loop *L,
11521 const Instruction *CtxI) {
11522 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11523 if (!isLoopInvariant(RHS, L)) {
11524 if (!isLoopInvariant(LHS, L))
11525 return std::nullopt;
11526
11527 std::swap(LHS, RHS);
11529 }
11530
11531 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11532 if (!ArLHS || ArLHS->getLoop() != L)
11533 return std::nullopt;
11534
11535 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
11536 if (!MonotonicType)
11537 return std::nullopt;
11538 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
11539 // true as the loop iterates, and the backedge is control dependent on
11540 // "ArLHS `Pred` RHS" == true then we can reason as follows:
11541 //
11542 // * if the predicate was false in the first iteration then the predicate
11543 // is never evaluated again, since the loop exits without taking the
11544 // backedge.
11545 // * if the predicate was true in the first iteration then it will
11546 // continue to be true for all future iterations since it is
11547 // monotonically increasing.
11548 //
11549 // For both the above possibilities, we can replace the loop varying
11550 // predicate with its value on the first iteration of the loop (which is
11551 // loop invariant).
11552 //
11553 // A similar reasoning applies for a monotonically decreasing predicate, by
11554 // replacing true with false and false with true in the above two bullets.
11556 auto P = Increasing ? Pred : ICmpInst::getInverseCmpPredicate(Pred);
11557
11558 if (isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
11560 RHS);
11561
11562 if (!CtxI)
11563 return std::nullopt;
11564 // Try to prove via context.
11565 // TODO: Support other cases.
11566 switch (Pred) {
11567 default:
11568 break;
11569 case ICmpInst::ICMP_ULE:
11570 case ICmpInst::ICMP_ULT: {
11571 assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!");
11572 // Given preconditions
11573 // (1) ArLHS does not cross the border of positive and negative parts of
11574 // range because of:
11575 // - Positive step; (TODO: lift this limitation)
11576 // - nuw - does not cross zero boundary;
11577 // - nsw - does not cross SINT_MAX boundary;
11578 // (2) ArLHS <s RHS
11579 // (3) RHS >=s 0
11580 // we can replace the loop variant ArLHS <u RHS condition with loop
11581 // invariant Start(ArLHS) <u RHS.
11582 //
11583 // Because of (1) there are two options:
11584 // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
11585 // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
11586 // It means that ArLHS <s RHS <=> ArLHS <u RHS.
11587 // Because of (2) ArLHS <u RHS is trivially true.
11588 // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
11589 // We can strengthen this to Start(ArLHS) <u RHS.
11590 auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
11591 if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
11592 isKnownPositive(ArLHS->getStepRecurrence(*this)) &&
11593 isKnownNonNegative(RHS) &&
11594 isKnownPredicateAt(SignFlippedPred, ArLHS, RHS, CtxI))
11596 RHS);
11597 }
11598 }
11599
11600 return std::nullopt;
11601}
11602
11603std::optional<ScalarEvolution::LoopInvariantPredicate>
11605 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11606 const Instruction *CtxI, const SCEV *MaxIter) {
11608 Pred, LHS, RHS, L, CtxI, MaxIter))
11609 return LIP;
11610 if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
11611 // Number of iterations expressed as UMIN isn't always great for expressing
11612 // the value on the last iteration. If the straightforward approach didn't
11613 // work, try the following trick: if the a predicate is invariant for X, it
11614 // is also invariant for umin(X, ...). So try to find something that works
11615 // among subexpressions of MaxIter expressed as umin.
11616 for (SCEVUse Op : UMin->operands())
11618 Pred, LHS, RHS, L, CtxI, Op))
11619 return LIP;
11620 return std::nullopt;
11621}
11622
11623std::optional<ScalarEvolution::LoopInvariantPredicate>
11625 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11626 const Instruction *CtxI, const SCEV *MaxIter) {
11627 // Try to prove the following set of facts:
11628 // - The predicate is monotonic in the iteration space.
11629 // - If the check does not fail on the 1st iteration:
11630 // - No overflow will happen during first MaxIter iterations;
11631 // - It will not fail on the MaxIter'th iteration.
11632 // If the check does fail on the 1st iteration, we leave the loop and no
11633 // other checks matter.
11634
11635 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11636 if (!isLoopInvariant(RHS, L)) {
11637 if (!isLoopInvariant(LHS, L))
11638 return std::nullopt;
11639
11640 std::swap(LHS, RHS);
11642 }
11643
11644 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
11645 if (!AR || AR->getLoop() != L)
11646 return std::nullopt;
11647
11648 // Even if both are valid, we need to consistently chose the unsigned or the
11649 // signed predicate below, not mixtures of both. For now, prefer the unsigned
11650 // predicate.
11651 Pred = Pred.dropSameSign();
11652
11653 // The predicate must be relational (i.e. <, <=, >=, >).
11654 if (!ICmpInst::isRelational(Pred))
11655 return std::nullopt;
11656
11657 // TODO: Support steps other than +/- 1.
11658 const SCEV *Step = AR->getStepRecurrence(*this);
11659 auto *One = getOne(Step->getType());
11660 auto *MinusOne = getNegativeSCEV(One);
11661 if (Step != One && Step != MinusOne)
11662 return std::nullopt;
11663
11664 // Type mismatch here means that MaxIter is potentially larger than max
11665 // unsigned value in start type, which mean we cannot prove no wrap for the
11666 // indvar.
11667 if (AR->getType() != MaxIter->getType())
11668 return std::nullopt;
11669
11670 // Value of IV on suggested last iteration.
11671 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
11672 // Does it still meet the requirement?
11673 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
11674 return std::nullopt;
11675 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
11676 // not exceed max unsigned value of this type), this effectively proves
11677 // that there is no wrap during the iteration. To prove that there is no
11678 // signed/unsigned wrap, we need to check that
11679 // Start <= Last for step = 1 or Start >= Last for step = -1.
11680 ICmpInst::Predicate NoOverflowPred =
11682 if (Step == MinusOne)
11683 NoOverflowPred = ICmpInst::getSwappedPredicate(NoOverflowPred);
11684 const SCEV *Start = AR->getStart();
11685 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
11686 return std::nullopt;
11687
11688 // Everything is fine.
11689 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
11690}
11691
11692bool ScalarEvolution::isKnownPredicateViaConstantRanges(CmpPredicate Pred,
11693 SCEVUse LHS,
11694 SCEVUse RHS) {
11695 if (HasSameValue(LHS, RHS))
11696 return ICmpInst::isTrueWhenEqual(Pred);
11697
11698 auto CheckRange = [&](bool IsSigned) {
11699 auto RangeLHS = IsSigned ? getSignedRange(LHS) : getUnsignedRange(LHS);
11700 auto RangeRHS = IsSigned ? getSignedRange(RHS) : getUnsignedRange(RHS);
11701 return RangeLHS.icmp(Pred, RangeRHS);
11702 };
11703
11704 // The check at the top of the function catches the case where the values are
11705 // known to be equal.
11706 if (Pred == CmpInst::ICMP_EQ)
11707 return false;
11708
11709 if (Pred == CmpInst::ICMP_NE) {
11710 if (CheckRange(true) || CheckRange(false))
11711 return true;
11712 auto *Diff = getMinusSCEV(LHS, RHS);
11713 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
11714 }
11715
11716 return CheckRange(CmpInst::isSigned(Pred));
11717}
11718
11719bool ScalarEvolution::isKnownPredicateViaNoOverflow(CmpPredicate Pred,
11721 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
11722 // C1 and C2 are constant integers. If either X or Y are not add expressions,
11723 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
11724 // OutC1 and OutC2.
11725 auto MatchBinaryAddToConst = [this](SCEVUse X, SCEVUse Y, APInt &OutC1,
11726 APInt &OutC2,
11727 SCEV::NoWrapFlags ExpectedFlags) {
11728 SCEVUse XNonConstOp, XConstOp;
11729 SCEVUse YNonConstOp, YConstOp;
11730 SCEV::NoWrapFlags XFlagsPresent;
11731 SCEV::NoWrapFlags YFlagsPresent;
11732
11733 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
11734 XConstOp = getZero(X->getType());
11735 XNonConstOp = X;
11736 XFlagsPresent = ExpectedFlags;
11737 }
11738 if (!isa<SCEVConstant>(XConstOp))
11739 return false;
11740
11741 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
11742 YConstOp = getZero(Y->getType());
11743 YNonConstOp = Y;
11744 YFlagsPresent = ExpectedFlags;
11745 }
11746
11747 if (YNonConstOp != XNonConstOp)
11748 return false;
11749
11750 if (!isa<SCEVConstant>(YConstOp))
11751 return false;
11752
11753 // When matching ADDs with NUW flags (and unsigned predicates), only the
11754 // second ADD (with the larger constant) requires NUW.
11755 if ((YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11756 return false;
11757 if (ExpectedFlags != SCEV::FlagNUW &&
11758 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) {
11759 return false;
11760 }
11761
11762 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
11763 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
11764
11765 return true;
11766 };
11767
11768 APInt C1;
11769 APInt C2;
11770
11771 switch (Pred) {
11772 default:
11773 break;
11774
11775 case ICmpInst::ICMP_SGE:
11776 std::swap(LHS, RHS);
11777 [[fallthrough]];
11778 case ICmpInst::ICMP_SLE:
11779 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
11780 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
11781 return true;
11782
11783 break;
11784
11785 case ICmpInst::ICMP_SGT:
11786 std::swap(LHS, RHS);
11787 [[fallthrough]];
11788 case ICmpInst::ICMP_SLT:
11789 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
11790 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
11791 return true;
11792
11793 break;
11794
11795 case ICmpInst::ICMP_UGE:
11796 std::swap(LHS, RHS);
11797 [[fallthrough]];
11798 case ICmpInst::ICMP_ULE:
11799 // (X + C1) u<= (X + C2)<nuw> for C1 u<= C2.
11800 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ule(C2))
11801 return true;
11802
11803 break;
11804
11805 case ICmpInst::ICMP_UGT:
11806 std::swap(LHS, RHS);
11807 [[fallthrough]];
11808 case ICmpInst::ICMP_ULT:
11809 // (X + C1) u< (X + C2)<nuw> if C1 u< C2.
11810 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ult(C2))
11811 return true;
11812 break;
11813 }
11814
11815 return false;
11816}
11817
11818bool ScalarEvolution::isKnownPredicateViaSplitting(CmpPredicate Pred,
11820 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
11821 return false;
11822
11823 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
11824 // the stack can result in exponential time complexity.
11825 SaveAndRestore Restore(ProvingSplitPredicate, true);
11826
11827 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
11828 //
11829 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
11830 // isKnownPredicate. isKnownPredicate is more powerful, but also more
11831 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
11832 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
11833 // use isKnownPredicate later if needed.
11834 return isKnownNonNegative(RHS) &&
11837}
11838
11839bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, CmpPredicate Pred,
11840 const SCEV *LHS, const SCEV *RHS) {
11841 // No need to even try if we know the module has no guards.
11842 if (!HasGuards)
11843 return false;
11844
11845 return any_of(*BB, [&](const Instruction &I) {
11846 using namespace llvm::PatternMatch;
11847
11848 Value *Condition;
11850 m_Value(Condition))) &&
11851 isImpliedCond(Pred, LHS, RHS, Condition, false);
11852 });
11853}
11854
11855/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
11856/// protected by a conditional between LHS and RHS. This is used to
11857/// to eliminate casts.
11859 CmpPredicate Pred,
11860 const SCEV *LHS,
11861 const SCEV *RHS) {
11862 // Interpret a null as meaning no loop, where there is obviously no guard
11863 // (interprocedural conditions notwithstanding). Do not bother about
11864 // unreachable loops.
11865 if (!L || !DT.isReachableFromEntry(L->getHeader()))
11866 return true;
11867
11868 if (VerifyIR)
11869 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
11870 "This cannot be done on broken IR!");
11871
11872
11873 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11874 return true;
11875
11876 BasicBlock *Latch = L->getLoopLatch();
11877 if (!Latch)
11878 return false;
11879
11880 CondBrInst *LoopContinuePredicate =
11882 if (LoopContinuePredicate &&
11883 isImpliedCond(Pred, LHS, RHS, LoopContinuePredicate->getCondition(),
11884 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
11885 return true;
11886
11887 // We don't want more than one activation of the following loops on the stack
11888 // -- that can lead to O(n!) time complexity.
11889 if (WalkingBEDominatingConds)
11890 return false;
11891
11892 SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
11893
11894 // See if we can exploit a trip count to prove the predicate.
11895 const auto &BETakenInfo = getBackedgeTakenInfo(L);
11896 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
11897 if (LatchBECount != getCouldNotCompute()) {
11898 // We know that Latch branches back to the loop header exactly
11899 // LatchBECount times. This means the backdege condition at Latch is
11900 // equivalent to "{0,+,1} u< LatchBECount".
11901 Type *Ty = LatchBECount->getType();
11902 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
11903 const SCEV *LoopCounter =
11904 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
11905 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
11906 LatchBECount))
11907 return true;
11908 }
11909
11910 // Check conditions due to any @llvm.assume intrinsics.
11911 for (auto &AssumeVH : AC.assumptions()) {
11912 if (!AssumeVH)
11913 continue;
11914 auto *CI = cast<CallInst>(AssumeVH);
11915 if (!DT.dominates(CI, Latch->getTerminator()))
11916 continue;
11917
11918 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
11919 return true;
11920 }
11921
11922 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
11923 return true;
11924
11925 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
11926 DTN != HeaderDTN; DTN = DTN->getIDom()) {
11927 assert(DTN && "should reach the loop header before reaching the root!");
11928
11929 BasicBlock *BB = DTN->getBlock();
11930 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
11931 return true;
11932
11933 BasicBlock *PBB = BB->getSinglePredecessor();
11934 if (!PBB)
11935 continue;
11936
11938 if (!ContBr || ContBr->getSuccessor(0) == ContBr->getSuccessor(1))
11939 continue;
11940
11941 // If we have an edge `E` within the loop body that dominates the only
11942 // latch, the condition guarding `E` also guards the backedge. This
11943 // reasoning works only for loops with a single latch.
11944 // We're constructively (and conservatively) enumerating edges within the
11945 // loop body that dominate the latch. The dominator tree better agree
11946 // with us on this:
11947 assert(DT.dominates(BasicBlockEdge(PBB, BB), Latch) && "should be!");
11948 if (isImpliedCond(Pred, LHS, RHS, ContBr->getCondition(),
11949 BB != ContBr->getSuccessor(0)))
11950 return true;
11951 }
11952
11953 return false;
11954}
11955
11957 CmpPredicate Pred,
11958 const SCEV *LHS,
11959 const SCEV *RHS) {
11960 // Do not bother proving facts for unreachable code.
11961 if (!DT.isReachableFromEntry(BB))
11962 return true;
11963 if (VerifyIR)
11964 assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
11965 "This cannot be done on broken IR!");
11966
11967 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
11968 // the facts (a >= b && a != b) separately. A typical situation is when the
11969 // non-strict comparison is known from ranges and non-equality is known from
11970 // dominating predicates. If we are proving strict comparison, we always try
11971 // to prove non-equality and non-strict comparison separately.
11972 CmpPredicate NonStrictPredicate = ICmpInst::getNonStrictCmpPredicate(Pred);
11973 const bool ProvingStrictComparison =
11974 Pred != NonStrictPredicate.dropSameSign();
11975 bool ProvedNonStrictComparison = false;
11976 bool ProvedNonEquality = false;
11977
11978 auto SplitAndProve = [&](std::function<bool(CmpPredicate)> Fn) -> bool {
11979 if (!ProvedNonStrictComparison)
11980 ProvedNonStrictComparison = Fn(NonStrictPredicate);
11981 if (!ProvedNonEquality)
11982 ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
11983 if (ProvedNonStrictComparison && ProvedNonEquality)
11984 return true;
11985 return false;
11986 };
11987
11988 if (ProvingStrictComparison) {
11989 auto ProofFn = [&](CmpPredicate P) {
11990 return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
11991 };
11992 if (SplitAndProve(ProofFn))
11993 return true;
11994 }
11995
11996 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
11997 auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
11998 const Instruction *CtxI = &BB->front();
11999 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
12000 return true;
12001 if (ProvingStrictComparison) {
12002 auto ProofFn = [&](CmpPredicate P) {
12003 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
12004 };
12005 if (SplitAndProve(ProofFn))
12006 return true;
12007 }
12008 return false;
12009 };
12010
12011 // Starting at the block's predecessor, climb up the predecessor chain, as long
12012 // as there are predecessors that can be found that have unique successors
12013 // leading to the original block.
12014 const Loop *ContainingLoop = LI.getLoopFor(BB);
12015 const BasicBlock *PredBB;
12016 if (ContainingLoop && ContainingLoop->getHeader() == BB)
12017 PredBB = ContainingLoop->getLoopPredecessor();
12018 else
12019 PredBB = BB->getSinglePredecessor();
12020 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
12021 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
12022 const CondBrInst *BlockEntryPredicate =
12023 dyn_cast<CondBrInst>(Pair.first->getTerminator());
12024 if (!BlockEntryPredicate)
12025 continue;
12026
12027 if (ProveViaCond(BlockEntryPredicate->getCondition(),
12028 BlockEntryPredicate->getSuccessor(0) != Pair.second))
12029 return true;
12030 }
12031
12032 // Check conditions due to any @llvm.assume intrinsics.
12033 for (auto &AssumeVH : AC.assumptions()) {
12034 if (!AssumeVH)
12035 continue;
12036 auto *CI = cast<CallInst>(AssumeVH);
12037 if (!DT.dominates(CI, BB))
12038 continue;
12039
12040 if (ProveViaCond(CI->getArgOperand(0), false))
12041 return true;
12042 }
12043
12044 // Check conditions due to any @llvm.experimental.guard intrinsics.
12045 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
12046 F.getParent(), Intrinsic::experimental_guard);
12047 if (GuardDecl)
12048 for (const auto *GU : GuardDecl->users())
12049 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
12050 if (Guard->getFunction() == BB->getParent() && DT.dominates(Guard, BB))
12051 if (ProveViaCond(Guard->getArgOperand(0), false))
12052 return true;
12053 return false;
12054}
12055
12057 const SCEV *LHS,
12058 const SCEV *RHS) {
12059 // Interpret a null as meaning no loop, where there is obviously no guard
12060 // (interprocedural conditions notwithstanding).
12061 if (!L)
12062 return false;
12063
12064 // Both LHS and RHS must be available at loop entry.
12066 "LHS is not available at Loop Entry");
12068 "RHS is not available at Loop Entry");
12069
12070 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
12071 return true;
12072
12073 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
12074}
12075
12076bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12077 const SCEV *RHS,
12078 const Value *FoundCondValue, bool Inverse,
12079 const Instruction *CtxI) {
12080 // False conditions implies anything. Do not bother analyzing it further.
12081 if (FoundCondValue ==
12082 ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
12083 return true;
12084
12085 if (!PendingLoopPredicates.insert(FoundCondValue).second)
12086 return false;
12087
12088 llvm::scope_exit ClearOnExit(
12089 [&]() { PendingLoopPredicates.erase(FoundCondValue); });
12090
12091 // Recursively handle And and Or conditions.
12092 const Value *Op0, *Op1;
12093 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
12094 if (!Inverse)
12095 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12096 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12097 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
12098 if (Inverse)
12099 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12100 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12101 }
12102
12103 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
12104 if (!ICI) return false;
12105
12106 // Now that we found a conditional branch that dominates the loop or controls
12107 // the loop latch. Check to see if it is the comparison we are looking for.
12108 CmpPredicate FoundPred;
12109 if (Inverse)
12110 FoundPred = ICI->getInverseCmpPredicate();
12111 else
12112 FoundPred = ICI->getCmpPredicate();
12113
12114 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
12115 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
12116
12117 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
12118}
12119
12120bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12121 const SCEV *RHS, CmpPredicate FoundPred,
12122 const SCEV *FoundLHS, const SCEV *FoundRHS,
12123 const Instruction *CtxI) {
12124 // Balance the types.
12125 if (getTypeSizeInBits(LHS->getType()) <
12126 getTypeSizeInBits(FoundLHS->getType())) {
12127 // For unsigned and equality predicates, try to prove that both found
12128 // operands fit into narrow unsigned range. If so, try to prove facts in
12129 // narrow types.
12130 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
12131 !FoundRHS->getType()->isPointerTy()) {
12132 auto *NarrowType = LHS->getType();
12133 auto *WideType = FoundLHS->getType();
12134 auto BitWidth = getTypeSizeInBits(NarrowType);
12135 const SCEV *MaxValue = getZeroExtendExpr(
12137 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
12138 MaxValue) &&
12139 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
12140 MaxValue)) {
12141 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
12142 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
12143 // We cannot preserve samesign after truncation.
12144 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred.dropSameSign(),
12145 TruncFoundLHS, TruncFoundRHS, CtxI))
12146 return true;
12147 }
12148 }
12149
12150 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
12151 return false;
12152 if (CmpInst::isSigned(Pred)) {
12153 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
12154 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
12155 } else {
12156 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
12157 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
12158 }
12159 } else if (getTypeSizeInBits(LHS->getType()) >
12160 getTypeSizeInBits(FoundLHS->getType())) {
12161 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
12162 return false;
12163 if (CmpInst::isSigned(FoundPred)) {
12164 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
12165 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
12166 } else {
12167 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
12168 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
12169 }
12170 }
12171 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
12172 FoundRHS, CtxI);
12173}
12174
12175bool ScalarEvolution::isImpliedCondBalancedTypes(
12176 CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, CmpPredicate FoundPred,
12177 SCEVUse FoundLHS, SCEVUse FoundRHS, const Instruction *CtxI) {
12179 getTypeSizeInBits(FoundLHS->getType()) &&
12180 "Types should be balanced!");
12181 // Canonicalize the query to match the way instcombine will have
12182 // canonicalized the comparison.
12183 if (SimplifyICmpOperands(Pred, LHS, RHS))
12184 if (LHS == RHS)
12185 return CmpInst::isTrueWhenEqual(Pred);
12186 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
12187 if (FoundLHS == FoundRHS)
12188 return CmpInst::isFalseWhenEqual(FoundPred);
12189
12190 // Check to see if we can make the LHS or RHS match.
12191 if (LHS == FoundRHS || RHS == FoundLHS) {
12192 if (isa<SCEVConstant>(RHS)) {
12193 std::swap(FoundLHS, FoundRHS);
12194 FoundPred = ICmpInst::getSwappedCmpPredicate(FoundPred);
12195 } else {
12196 std::swap(LHS, RHS);
12198 }
12199 }
12200
12201 // Check whether the found predicate is the same as the desired predicate.
12202 if (auto P = CmpPredicate::getMatching(FoundPred, Pred))
12203 return isImpliedCondOperands(*P, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12204
12205 // Check whether swapping the found predicate makes it the same as the
12206 // desired predicate.
12207 if (auto P = CmpPredicate::getMatching(
12208 ICmpInst::getSwappedCmpPredicate(FoundPred), Pred)) {
12209 // We can write the implication
12210 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS
12211 // using one of the following ways:
12212 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS
12213 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS
12214 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS
12215 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS
12216 // Forms 1. and 2. require swapping the operands of one condition. Don't
12217 // do this if it would break canonical constant/addrec ordering.
12219 return isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P), RHS,
12220 LHS, FoundLHS, FoundRHS, CtxI);
12221 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
12222 return isImpliedCondOperands(*P, LHS, RHS, FoundRHS, FoundLHS, CtxI);
12223
12224 // There's no clear preference between forms 3. and 4., try both. Avoid
12225 // forming getNotSCEV of pointer values as the resulting subtract is
12226 // not legal.
12227 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() &&
12228 isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P),
12229 getNotSCEV(LHS), getNotSCEV(RHS), FoundLHS,
12230 FoundRHS, CtxI))
12231 return true;
12232
12233 if (!FoundLHS->getType()->isPointerTy() &&
12234 !FoundRHS->getType()->isPointerTy() &&
12235 isImpliedCondOperands(*P, LHS, RHS, getNotSCEV(FoundLHS),
12236 getNotSCEV(FoundRHS), CtxI))
12237 return true;
12238
12239 return false;
12240 }
12241
12242 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
12244 assert(P1 != P2 && "Handled earlier!");
12245 return CmpInst::isRelational(P2) &&
12247 };
12248 if (IsSignFlippedPredicate(Pred, FoundPred)) {
12249 // Unsigned comparison is the same as signed comparison when both the
12250 // operands are non-negative or negative.
12251 if (haveSameSign(FoundLHS, FoundRHS))
12252 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12253 // Create local copies that we can freely swap and canonicalize our
12254 // conditions to "le/lt".
12255 CmpPredicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
12256 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
12257 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
12258 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
12259 CanonicalPred = ICmpInst::getSwappedCmpPredicate(CanonicalPred);
12260 CanonicalFoundPred = ICmpInst::getSwappedCmpPredicate(CanonicalFoundPred);
12261 std::swap(CanonicalLHS, CanonicalRHS);
12262 std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
12263 }
12264 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
12265 "Must be!");
12266 assert((ICmpInst::isLT(CanonicalFoundPred) ||
12267 ICmpInst::isLE(CanonicalFoundPred)) &&
12268 "Must be!");
12269 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
12270 // Use implication:
12271 // x <u y && y >=s 0 --> x <s y.
12272 // If we can prove the left part, the right part is also proven.
12273 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
12274 CanonicalRHS, CanonicalFoundLHS,
12275 CanonicalFoundRHS);
12276 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
12277 // Use implication:
12278 // x <s y && y <s 0 --> x <u y.
12279 // If we can prove the left part, the right part is also proven.
12280 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
12281 CanonicalRHS, CanonicalFoundLHS,
12282 CanonicalFoundRHS);
12283 }
12284
12285 // Check if we can make progress by sharpening ranges.
12286 if (FoundPred == ICmpInst::ICMP_NE &&
12287 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
12288
12289 const SCEVConstant *C = nullptr;
12290 const SCEV *V = nullptr;
12291
12292 if (isa<SCEVConstant>(FoundLHS)) {
12293 C = cast<SCEVConstant>(FoundLHS);
12294 V = FoundRHS;
12295 } else {
12296 C = cast<SCEVConstant>(FoundRHS);
12297 V = FoundLHS;
12298 }
12299
12300 // The guarding predicate tells us that C != V. If the known range
12301 // of V is [C, t), we can sharpen the range to [C + 1, t). The
12302 // range we consider has to correspond to same signedness as the
12303 // predicate we're interested in folding.
12304
12305 APInt Min = ICmpInst::isSigned(Pred) ?
12307
12308 if (Min == C->getAPInt()) {
12309 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
12310 // This is true even if (Min + 1) wraps around -- in case of
12311 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
12312
12313 APInt SharperMin = Min + 1;
12314
12315 switch (Pred) {
12316 case ICmpInst::ICMP_SGE:
12317 case ICmpInst::ICMP_UGE:
12318 // We know V `Pred` SharperMin. If this implies LHS `Pred`
12319 // RHS, we're done.
12320 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
12321 CtxI))
12322 return true;
12323 [[fallthrough]];
12324
12325 case ICmpInst::ICMP_SGT:
12326 case ICmpInst::ICMP_UGT:
12327 // We know from the range information that (V `Pred` Min ||
12328 // V == Min). We know from the guarding condition that !(V
12329 // == Min). This gives us
12330 //
12331 // V `Pred` Min || V == Min && !(V == Min)
12332 // => V `Pred` Min
12333 //
12334 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
12335
12336 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
12337 return true;
12338 break;
12339
12340 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
12341 case ICmpInst::ICMP_SLE:
12342 case ICmpInst::ICMP_ULE:
12343 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12344 LHS, V, getConstant(SharperMin), CtxI))
12345 return true;
12346 [[fallthrough]];
12347
12348 case ICmpInst::ICMP_SLT:
12349 case ICmpInst::ICMP_ULT:
12350 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12351 LHS, V, getConstant(Min), CtxI))
12352 return true;
12353 break;
12354
12355 default:
12356 // No change
12357 break;
12358 }
12359 }
12360 }
12361
12362 // Check whether the actual condition is beyond sufficient.
12363 if (FoundPred == ICmpInst::ICMP_EQ)
12364 if (ICmpInst::isTrueWhenEqual(Pred))
12365 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12366 return true;
12367 if (Pred == ICmpInst::ICMP_NE)
12368 if (!ICmpInst::isTrueWhenEqual(FoundPred))
12369 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12370 return true;
12371
12372 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS))
12373 return true;
12374
12375 // Otherwise assume the worst.
12376 return false;
12377}
12378
12379bool ScalarEvolution::splitBinaryAdd(SCEVUse Expr, SCEVUse &L, SCEVUse &R,
12380 SCEV::NoWrapFlags &Flags) {
12381 if (!match(Expr, m_scev_Add(m_SCEV(L), m_SCEV(R))))
12382 return false;
12383
12384 Flags = cast<SCEVAddExpr>(Expr)->getNoWrapFlags();
12385 return true;
12386}
12387
12388std::optional<APInt>
12390 // We avoid subtracting expressions here because this function is usually
12391 // fairly deep in the call stack (i.e. is called many times).
12392
12393 unsigned BW = getTypeSizeInBits(More->getType());
12394 APInt Diff(BW, 0);
12395 APInt DiffMul(BW, 1);
12396 // Try various simplifications to reduce the difference to a constant. Limit
12397 // the number of allowed simplifications to keep compile-time low.
12398 for (unsigned I = 0; I < 8; ++I) {
12399 if (More == Less)
12400 return Diff;
12401
12402 // Reduce addrecs with identical steps to their start value.
12404 const auto *LAR = cast<SCEVAddRecExpr>(Less);
12405 const auto *MAR = cast<SCEVAddRecExpr>(More);
12406
12407 if (LAR->getLoop() != MAR->getLoop())
12408 return std::nullopt;
12409
12410 // We look at affine expressions only; not for correctness but to keep
12411 // getStepRecurrence cheap.
12412 if (!LAR->isAffine() || !MAR->isAffine())
12413 return std::nullopt;
12414
12415 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
12416 return std::nullopt;
12417
12418 Less = LAR->getStart();
12419 More = MAR->getStart();
12420 continue;
12421 }
12422
12423 // Try to match a common constant multiply.
12424 auto MatchConstMul =
12425 [](const SCEV *S) -> std::optional<std::pair<const SCEV *, APInt>> {
12426 const APInt *C;
12427 const SCEV *Op;
12428 if (match(S, m_scev_Mul(m_scev_APInt(C), m_SCEV(Op))))
12429 return {{Op, *C}};
12430 return std::nullopt;
12431 };
12432 if (auto MatchedMore = MatchConstMul(More)) {
12433 if (auto MatchedLess = MatchConstMul(Less)) {
12434 if (MatchedMore->second == MatchedLess->second) {
12435 More = MatchedMore->first;
12436 Less = MatchedLess->first;
12437 DiffMul *= MatchedMore->second;
12438 continue;
12439 }
12440 }
12441 }
12442
12443 // Try to cancel out common factors in two add expressions.
12445 auto Add = [&](const SCEV *S, int Mul) {
12446 if (auto *C = dyn_cast<SCEVConstant>(S)) {
12447 if (Mul == 1) {
12448 Diff += C->getAPInt() * DiffMul;
12449 } else {
12450 assert(Mul == -1);
12451 Diff -= C->getAPInt() * DiffMul;
12452 }
12453 } else
12454 Multiplicity[S] += Mul;
12455 };
12456 auto Decompose = [&](const SCEV *S, int Mul) {
12457 if (isa<SCEVAddExpr>(S)) {
12458 for (const SCEV *Op : S->operands())
12459 Add(Op, Mul);
12460 } else
12461 Add(S, Mul);
12462 };
12463 Decompose(More, 1);
12464 Decompose(Less, -1);
12465
12466 // Check whether all the non-constants cancel out, or reduce to new
12467 // More/Less values.
12468 const SCEV *NewMore = nullptr, *NewLess = nullptr;
12469 for (const auto &[S, Mul] : Multiplicity) {
12470 if (Mul == 0)
12471 continue;
12472 if (Mul == 1) {
12473 if (NewMore)
12474 return std::nullopt;
12475 NewMore = S;
12476 } else if (Mul == -1) {
12477 if (NewLess)
12478 return std::nullopt;
12479 NewLess = S;
12480 } else
12481 return std::nullopt;
12482 }
12483
12484 // Values stayed the same, no point in trying further.
12485 if (NewMore == More || NewLess == Less)
12486 return std::nullopt;
12487
12488 More = NewMore;
12489 Less = NewLess;
12490
12491 // Reduced to constant.
12492 if (!More && !Less)
12493 return Diff;
12494
12495 // Left with variable on only one side, bail out.
12496 if (!More || !Less)
12497 return std::nullopt;
12498 }
12499
12500 // Did not reduce to constant.
12501 return std::nullopt;
12502}
12503
12504bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
12505 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12506 const SCEV *FoundRHS, const Instruction *CtxI) {
12507 // Try to recognize the following pattern:
12508 //
12509 // FoundRHS = ...
12510 // ...
12511 // loop:
12512 // FoundLHS = {Start,+,W}
12513 // context_bb: // Basic block from the same loop
12514 // known(Pred, FoundLHS, FoundRHS)
12515 //
12516 // If some predicate is known in the context of a loop, it is also known on
12517 // each iteration of this loop, including the first iteration. Therefore, in
12518 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
12519 // prove the original pred using this fact.
12520 if (!CtxI)
12521 return false;
12522 const BasicBlock *ContextBB = CtxI->getParent();
12523 // Make sure AR varies in the context block.
12524 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
12525 const Loop *L = AR->getLoop();
12526 const auto *Latch = L->getLoopLatch();
12527 // Make sure that context belongs to the loop and executes on 1st iteration
12528 // (if it ever executes at all).
12529 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12530 return false;
12531 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
12532 return false;
12533 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
12534 }
12535
12536 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
12537 const Loop *L = AR->getLoop();
12538 const auto *Latch = L->getLoopLatch();
12539 // Make sure that context belongs to the loop and executes on 1st iteration
12540 // (if it ever executes at all).
12541 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12542 return false;
12543 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
12544 return false;
12545 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
12546 }
12547
12548 return false;
12549}
12550
12551bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(CmpPredicate Pred,
12552 const SCEV *LHS,
12553 const SCEV *RHS,
12554 const SCEV *FoundLHS,
12555 const SCEV *FoundRHS) {
12556 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
12557 return false;
12558
12559 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
12560 if (!AddRecLHS)
12561 return false;
12562
12563 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12564 if (!AddRecFoundLHS)
12565 return false;
12566
12567 // We'd like to let SCEV reason about control dependencies, so we constrain
12568 // both the inequalities to be about add recurrences on the same loop. This
12569 // way we can use isLoopEntryGuardedByCond later.
12570
12571 const Loop *L = AddRecFoundLHS->getLoop();
12572 if (L != AddRecLHS->getLoop())
12573 return false;
12574
12575 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
12576 //
12577 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
12578 // ... (2)
12579 //
12580 // Informal proof for (2), assuming (1) [*]:
12581 //
12582 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
12583 //
12584 // Then
12585 //
12586 // FoundLHS s< FoundRHS s< INT_MIN - C
12587 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
12588 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
12589 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
12590 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
12591 // <=> FoundLHS + C s< FoundRHS + C
12592 //
12593 // [*]: (1) can be proved by ruling out overflow.
12594 //
12595 // [**]: This can be proved by analyzing all the four possibilities:
12596 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
12597 // (A s>= 0, B s>= 0).
12598 //
12599 // Note:
12600 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
12601 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
12602 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
12603 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
12604 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
12605 // C)".
12606
12607 std::optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
12608 if (!LDiff)
12609 return false;
12610 std::optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
12611 if (!RDiff || *LDiff != *RDiff)
12612 return false;
12613
12614 if (LDiff->isMinValue())
12615 return true;
12616
12617 APInt FoundRHSLimit;
12618
12619 if (Pred == CmpInst::ICMP_ULT) {
12620 FoundRHSLimit = -(*RDiff);
12621 } else {
12622 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
12623 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
12624 }
12625
12626 // Try to prove (1) or (2), as needed.
12627 return isAvailableAtLoopEntry(FoundRHS, L) &&
12628 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
12629 getConstant(FoundRHSLimit));
12630}
12631
12632bool ScalarEvolution::isImpliedViaMerge(CmpPredicate Pred, const SCEV *LHS,
12633 const SCEV *RHS, const SCEV *FoundLHS,
12634 const SCEV *FoundRHS, unsigned Depth) {
12635 const PHINode *LPhi = nullptr, *RPhi = nullptr;
12636
12637 llvm::scope_exit ClearOnExit([&]() {
12638 if (LPhi) {
12639 bool Erased = PendingMerges.erase(LPhi);
12640 assert(Erased && "Failed to erase LPhi!");
12641 (void)Erased;
12642 }
12643 if (RPhi) {
12644 bool Erased = PendingMerges.erase(RPhi);
12645 assert(Erased && "Failed to erase RPhi!");
12646 (void)Erased;
12647 }
12648 });
12649
12650 // Find respective Phis and check that they are not being pending.
12651 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
12652 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
12653 if (!PendingMerges.insert(Phi).second)
12654 return false;
12655 LPhi = Phi;
12656 }
12657 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
12658 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
12659 // If we detect a loop of Phi nodes being processed by this method, for
12660 // example:
12661 //
12662 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
12663 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
12664 //
12665 // we don't want to deal with a case that complex, so return conservative
12666 // answer false.
12667 if (!PendingMerges.insert(Phi).second)
12668 return false;
12669 RPhi = Phi;
12670 }
12671
12672 // If none of LHS, RHS is a Phi, nothing to do here.
12673 if (!LPhi && !RPhi)
12674 return false;
12675
12676 // If there is a SCEVUnknown Phi we are interested in, make it left.
12677 if (!LPhi) {
12678 std::swap(LHS, RHS);
12679 std::swap(FoundLHS, FoundRHS);
12680 std::swap(LPhi, RPhi);
12682 }
12683
12684 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
12685 const BasicBlock *LBB = LPhi->getParent();
12686 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12687
12688 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
12689 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
12690 isImpliedCondOperandsViaRanges(Pred, S1, S2, Pred, FoundLHS, FoundRHS) ||
12691 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
12692 };
12693
12694 if (RPhi && RPhi->getParent() == LBB) {
12695 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
12696 // If we compare two Phis from the same block, and for each entry block
12697 // the predicate is true for incoming values from this block, then the
12698 // predicate is also true for the Phis.
12699 for (const BasicBlock *IncBB : predecessors(LBB)) {
12700 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12701 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
12702 if (!ProvedEasily(L, R))
12703 return false;
12704 }
12705 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
12706 // Case two: RHS is also a Phi from the same basic block, and it is an
12707 // AddRec. It means that there is a loop which has both AddRec and Unknown
12708 // PHIs, for it we can compare incoming values of AddRec from above the loop
12709 // and latch with their respective incoming values of LPhi.
12710 // TODO: Generalize to handle loops with many inputs in a header.
12711 if (LPhi->getNumIncomingValues() != 2) return false;
12712
12713 auto *RLoop = RAR->getLoop();
12714 auto *Predecessor = RLoop->getLoopPredecessor();
12715 assert(Predecessor && "Loop with AddRec with no predecessor?");
12716 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
12717 if (!ProvedEasily(L1, RAR->getStart()))
12718 return false;
12719 auto *Latch = RLoop->getLoopLatch();
12720 assert(Latch && "Loop with AddRec with no latch?");
12721 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
12722 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
12723 return false;
12724 } else {
12725 // In all other cases go over inputs of LHS and compare each of them to RHS,
12726 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
12727 // At this point RHS is either a non-Phi, or it is a Phi from some block
12728 // different from LBB.
12729 for (const BasicBlock *IncBB : predecessors(LBB)) {
12730 // Check that RHS is available in this block.
12731 if (!dominates(RHS, IncBB))
12732 return false;
12733 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12734 // Make sure L does not refer to a value from a potentially previous
12735 // iteration of a loop.
12736 if (!properlyDominates(L, LBB))
12737 return false;
12738 // Addrecs are considered to properly dominate their loop, so are missed
12739 // by the previous check. Discard any values that have computable
12740 // evolution in this loop.
12741 if (auto *Loop = LI.getLoopFor(LBB))
12743 return false;
12744 if (!ProvedEasily(L, RHS))
12745 return false;
12746 }
12747 }
12748 return true;
12749}
12750
12751bool ScalarEvolution::isImpliedCondOperandsViaShift(CmpPredicate Pred,
12752 const SCEV *LHS,
12753 const SCEV *RHS,
12754 const SCEV *FoundLHS,
12755 const SCEV *FoundRHS) {
12756 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make
12757 // sure that we are dealing with same LHS.
12758 if (RHS == FoundRHS) {
12759 std::swap(LHS, RHS);
12760 std::swap(FoundLHS, FoundRHS);
12762 }
12763 if (LHS != FoundLHS)
12764 return false;
12765
12766 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
12767 if (!SUFoundRHS)
12768 return false;
12769
12770 Value *Shiftee, *ShiftValue;
12771
12772 using namespace PatternMatch;
12773 if (match(SUFoundRHS->getValue(),
12774 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
12775 auto *ShifteeS = getSCEV(Shiftee);
12776 // Prove one of the following:
12777 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
12778 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
12779 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12780 // ---> LHS <s RHS
12781 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12782 // ---> LHS <=s RHS
12783 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
12784 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
12785 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
12786 if (isKnownNonNegative(ShifteeS))
12787 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
12788 }
12789
12790 return false;
12791}
12792
12793bool ScalarEvolution::isImpliedCondOperandsViaMatchingDiff(
12794 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12795 const SCEV *FoundRHS) {
12796 // Only valid for equality predicates: (A == B) implies (C == D) when
12797 // the SCEV difference A - B equals C - D (they check the same
12798 // underlying relationship at every iteration).
12799 if (!ICmpInst::isEquality(Pred))
12800 return false;
12801
12802 // Restrict to cases involving loop recurrences - that's where this
12803 // pattern arises (correlated IV comparisons). This avoids calling
12804 // getMinusSCEV on arbitrary non-loop expressions.
12806 (!isa<SCEVAddRecExpr>(FoundLHS) && !isa<SCEVAddRecExpr>(FoundRHS)))
12807 return false;
12808
12809 // AddRecs from different loops can never produce matching differences.
12810 const SCEVAddRecExpr *QueryAddRec = dyn_cast<SCEVAddRecExpr>(LHS);
12811 if (!QueryAddRec)
12812 QueryAddRec = cast<SCEVAddRecExpr>(RHS);
12813 const SCEVAddRecExpr *FoundAddRec = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12814 if (!FoundAddRec)
12815 FoundAddRec = cast<SCEVAddRecExpr>(FoundRHS);
12816 if (QueryAddRec->getLoop() != FoundAddRec->getLoop())
12817 return false;
12818
12819 // If the strides differ, the differences can never match.
12820 if (QueryAddRec->getStepRecurrence(*this) !=
12821 FoundAddRec->getStepRecurrence(*this))
12822 return false;
12823
12824 // Compute differences. For pointer-typed operands sharing the same base,
12825 // getMinusSCEV strips the common base and returns an integer SCEV.
12826 // For example, {base,+,8} - (base+8*n) = {-8n,+,8}
12827 const SCEV *FoundDiff = getMinusSCEV(FoundLHS, FoundRHS);
12828 if (isa<SCEVCouldNotCompute>(FoundDiff))
12829 return false;
12830
12831 const SCEV *Diff = getMinusSCEV(LHS, RHS);
12832 if (isa<SCEVCouldNotCompute>(Diff))
12833 return false;
12834
12835 return Diff == FoundDiff;
12836}
12837
12838bool ScalarEvolution::isImpliedCondOperands(CmpPredicate Pred, const SCEV *LHS,
12839 const SCEV *RHS,
12840 const SCEV *FoundLHS,
12841 const SCEV *FoundRHS,
12842 const Instruction *CtxI) {
12843 return isImpliedCondOperandsViaRanges(Pred, LHS, RHS, Pred, FoundLHS,
12844 FoundRHS) ||
12845 isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS,
12846 FoundRHS) ||
12847 isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS) ||
12848 isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12849 CtxI) ||
12850 isImpliedCondOperandsViaMatchingDiff(Pred, LHS, RHS, FoundLHS,
12851 FoundRHS) ||
12852 isImpliedCondOperandsHelper(Pred, LHS, RHS, FoundLHS, FoundRHS);
12853}
12854
12855/// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
12856template <typename MinMaxExprType>
12857static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
12858 const SCEV *Candidate) {
12859 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12860 if (!MinMaxExpr)
12861 return false;
12862
12863 return is_contained(MinMaxExpr->operands(), Candidate);
12864}
12865
12867 CmpPredicate Pred, const SCEV *LHS,
12868 const SCEV *RHS) {
12869 // If both sides are affine addrecs for the same loop, with equal
12870 // steps, and we know the recurrences don't wrap, then we only
12871 // need to check the predicate on the starting values.
12872
12873 if (!ICmpInst::isRelational(Pred))
12874 return false;
12875
12876 const SCEV *LStart, *RStart, *Step;
12877 const Loop *L;
12878 if (!match(LHS,
12879 m_scev_AffineAddRec(m_SCEV(LStart), m_SCEV(Step), m_Loop(L))) ||
12881 m_SpecificLoop(L))))
12882 return false;
12887 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
12888 return false;
12889
12890 return SE.isKnownPredicate(Pred, LStart, RStart);
12891}
12892
12893/// Is LHS `Pred` RHS true because one of them is an AddRec that is known not to
12894/// go below its own start value?
12896 CmpPredicate Pred,
12897 const SCEV *LHS,
12898 const SCEV *RHS) {
12899 // Normalize to (AddRec Pred Start).
12902 std::swap(LHS, RHS);
12903 }
12904
12905 // The recurrence is equal to Start in the first iteration, so only the
12906 // non-strict predicate holds.
12907 if (Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE)
12908 return false;
12909
12910 const auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
12911 if (!AR || AR->getStart() != RHS)
12912 return false;
12913
12914 return SE.getMonotonicPredicateType(AR, Pred) ==
12916}
12917
12918/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
12919/// expression?
12921 const SCEV *LHS, const SCEV *RHS) {
12922 switch (Pred) {
12923 default:
12924 return false;
12925
12926 case ICmpInst::ICMP_SGE:
12927 std::swap(LHS, RHS);
12928 [[fallthrough]];
12929 case ICmpInst::ICMP_SLE:
12930 return
12931 // min(A, ...) <= A
12933 // A <= max(A, ...)
12935
12936 case ICmpInst::ICMP_UGE:
12937 std::swap(LHS, RHS);
12938 [[fallthrough]];
12939 case ICmpInst::ICMP_ULE:
12940 return
12941 // min(A, ...) <= A
12942 // FIXME: what about umin_seq?
12944 // A <= max(A, ...)
12946
12947 case ICmpInst::ICMP_UGT:
12948 std::swap(LHS, RHS);
12949 [[fallthrough]];
12950 case ICmpInst::ICMP_ULT:
12951 // umin(Ops) u<= each Op, so proving Op u< RHS for any Op proves
12952 // umin(Ops) u< RHS.
12953 //
12954 // Use computeConstantDifference instead of the more powerful
12955 // isKnownPredicate to keep this check cheap: isKnownPredicateViaMinOrMax
12956 // is called from isKnownViaNonRecursiveReasoning, so recursing into
12957 // the full predicate prover would be expensive.
12958 if (const auto *Min = dyn_cast<SCEVUMinExpr>(LHS)) {
12959 for (SCEVUse Op : Min->operands()) {
12960 std::optional<APInt> Diff = SE.computeConstantDifference(RHS, Op);
12961 // When Op and RHS share a common base differing by a
12962 // constant offset D (RHS - Op = D), Op u< RHS holds iff D != 0 and
12963 // RHS >= D (unsigned), i.e. the subtraction doesn't underflow.
12964 if (Diff && !Diff->isZero() && SE.getUnsignedRangeMin(RHS).uge(*Diff))
12965 return true;
12966 }
12967 }
12968 return false;
12969 }
12970
12971 llvm_unreachable("covered switch fell through?!");
12972}
12973
12974bool ScalarEvolution::isImpliedViaOperations(CmpPredicate Pred, const SCEV *LHS,
12975 const SCEV *RHS,
12976 const SCEV *FoundLHS,
12977 const SCEV *FoundRHS,
12978 unsigned Depth) {
12981 "LHS and RHS have different sizes?");
12982 assert(getTypeSizeInBits(FoundLHS->getType()) ==
12983 getTypeSizeInBits(FoundRHS->getType()) &&
12984 "FoundLHS and FoundRHS have different sizes?");
12985 // We want to avoid hurting the compile time with analysis of too big trees.
12987 return false;
12988
12989 // We only want to work with GT comparison so far.
12990 if (ICmpInst::isLT(Pred)) {
12992 std::swap(LHS, RHS);
12993 std::swap(FoundLHS, FoundRHS);
12994 }
12995
12997
12998 // For unsigned, try to reduce it to corresponding signed comparison.
12999 if (P == ICmpInst::ICMP_UGT)
13000 // We can replace unsigned predicate with its signed counterpart if all
13001 // involved values are non-negative.
13002 // TODO: We could have better support for unsigned.
13003 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
13004 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
13005 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
13006 // use this fact to prove that LHS and RHS are non-negative.
13007 const SCEV *MinusOne = getMinusOne(LHS->getType());
13008 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
13009 FoundRHS) &&
13010 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
13011 FoundRHS))
13013 }
13014
13015 if (P != ICmpInst::ICMP_SGT)
13016 return false;
13017
13018 auto GetOpFromSExt = [&](const SCEV *S) -> const SCEV * {
13019 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
13020 return Ext->getOperand();
13021 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
13022 // the constant in some cases.
13023 return S;
13024 };
13025
13026 // Acquire values from extensions.
13027 auto *OrigLHS = LHS;
13028 auto *OrigFoundLHS = FoundLHS;
13029 LHS = GetOpFromSExt(LHS);
13030 FoundLHS = GetOpFromSExt(FoundLHS);
13031
13032 // Is the SGT predicate can be proved trivially or using the found context.
13033 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
13034 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
13035 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
13036 FoundRHS, Depth + 1);
13037 };
13038
13039 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
13040 // We want to avoid creation of any new non-constant SCEV. Since we are
13041 // going to compare the operands to RHS, we should be certain that we don't
13042 // need any size extensions for this. So let's decline all cases when the
13043 // sizes of types of LHS and RHS do not match.
13044 // TODO: Maybe try to get RHS from sext to catch more cases?
13046 return false;
13047
13048 // Should not overflow.
13049 if (!LHSAddExpr->hasNoSignedWrap())
13050 return false;
13051
13052 SCEVUse LL = LHSAddExpr->getOperand(0);
13053 SCEVUse LR = LHSAddExpr->getOperand(1);
13054 auto *MinusOne = getMinusOne(RHS->getType());
13055
13056 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
13057 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
13058 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
13059 };
13060 // Try to prove the following rule:
13061 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
13062 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
13063 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
13064 return true;
13065 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
13066 Value *LL, *LR;
13067 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
13068
13069 using namespace llvm::PatternMatch;
13070
13071 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
13072 // Rules for division.
13073 // We are going to perform some comparisons with Denominator and its
13074 // derivative expressions. In general case, creating a SCEV for it may
13075 // lead to a complex analysis of the entire graph, and in particular it
13076 // can request trip count recalculation for the same loop. This would
13077 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
13078 // this, we only want to create SCEVs that are constants in this section.
13079 // So we bail if Denominator is not a constant.
13080 if (!isa<ConstantInt>(LR))
13081 return false;
13082
13083 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
13084
13085 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
13086 // then a SCEV for the numerator already exists and matches with FoundLHS.
13087 auto *Numerator = getExistingSCEV(LL);
13088 if (!Numerator || Numerator->getType() != FoundLHS->getType())
13089 return false;
13090
13091 // Make sure that the numerator matches with FoundLHS and the denominator
13092 // is positive.
13093 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
13094 return false;
13095
13096 auto *DTy = Denominator->getType();
13097 auto *FRHSTy = FoundRHS->getType();
13098 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
13099 // One of types is a pointer and another one is not. We cannot extend
13100 // them properly to a wider type, so let us just reject this case.
13101 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
13102 // to avoid this check.
13103 return false;
13104
13105 // Given that:
13106 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
13107 auto *WTy = getWiderType(DTy, FRHSTy);
13108 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
13109 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
13110
13111 // Try to prove the following rule:
13112 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
13113 // For example, given that FoundLHS > 2. It means that FoundLHS is at
13114 // least 3. If we divide it by Denominator < 4, we will have at least 1.
13115 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
13116 if (isKnownNonPositive(RHS) &&
13117 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
13118 return true;
13119
13120 // Try to prove the following rule:
13121 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
13122 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
13123 // If we divide it by Denominator > 2, then:
13124 // 1. If FoundLHS is negative, then the result is 0.
13125 // 2. If FoundLHS is non-negative, then the result is non-negative.
13126 // Anyways, the result is non-negative.
13127 auto *MinusOne = getMinusOne(WTy);
13128 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
13129 if (isKnownNegative(RHS) &&
13130 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
13131 return true;
13132 }
13133 }
13134
13135 // If our expression contained SCEVUnknown Phis, and we split it down and now
13136 // need to prove something for them, try to prove the predicate for every
13137 // possible incoming values of those Phis.
13138 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
13139 return true;
13140
13141 return false;
13142}
13143
13145 const SCEV *RHS) {
13146 // zext x u<= sext x, sext x s<= zext x
13147 const SCEV *Op;
13148 switch (Pred) {
13149 case ICmpInst::ICMP_SGE:
13150 std::swap(LHS, RHS);
13151 [[fallthrough]];
13152 case ICmpInst::ICMP_SLE: {
13153 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt.
13154 return match(LHS, m_scev_SExt(m_SCEV(Op))) &&
13156 }
13157 case ICmpInst::ICMP_UGE:
13158 std::swap(LHS, RHS);
13159 [[fallthrough]];
13160 case ICmpInst::ICMP_ULE: {
13161 // If operand >=u 0 then ZExt == SExt. If operand <u 0 then ZExt <u SExt.
13162 return match(LHS, m_scev_ZExt(m_SCEV(Op))) &&
13164 }
13165 default:
13166 return false;
13167 };
13168 llvm_unreachable("unhandled case");
13169}
13170
13171bool ScalarEvolution::isKnownViaNonRecursiveReasoning(CmpPredicate Pred,
13172 SCEVUse LHS,
13173 SCEVUse RHS) {
13174 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
13175 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
13176 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
13177 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
13179 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
13180}
13181
13182bool ScalarEvolution::isImpliedCondOperandsHelper(CmpPredicate Pred,
13183 const SCEV *LHS,
13184 const SCEV *RHS,
13185 const SCEV *FoundLHS,
13186 const SCEV *FoundRHS) {
13187 switch (Pred) {
13188 default:
13189 llvm_unreachable("Unexpected CmpPredicate value!");
13190 case ICmpInst::ICMP_EQ:
13191 case ICmpInst::ICMP_NE:
13192 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
13193 return true;
13194 break;
13195 case ICmpInst::ICMP_SLT:
13196 case ICmpInst::ICMP_SLE:
13197 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
13198 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
13199 return true;
13200 break;
13201 case ICmpInst::ICMP_SGT:
13202 case ICmpInst::ICMP_SGE:
13203 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
13204 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
13205 return true;
13206 break;
13207 case ICmpInst::ICMP_ULT:
13208 case ICmpInst::ICMP_ULE:
13209 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
13210 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
13211 return true;
13212 break;
13213 case ICmpInst::ICMP_UGT:
13214 case ICmpInst::ICMP_UGE:
13215 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
13216 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
13217 return true;
13218 break;
13219 }
13220
13221 // Maybe it can be proved via operations?
13222 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
13223 return true;
13224
13225 return false;
13226}
13227
13228bool ScalarEvolution::isImpliedCondOperandsViaRanges(
13229 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, CmpPredicate FoundPred,
13230 const SCEV *FoundLHS, const SCEV *FoundRHS) {
13231 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
13232 // The restriction on `FoundRHS` be lifted easily -- it exists only to
13233 // reduce the compile time impact of this optimization.
13234 return false;
13235
13236 std::optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
13237 if (!Addend)
13238 return false;
13239
13240 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
13241
13242 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
13243 // antecedent "`FoundLHS` `FoundPred` `FoundRHS`".
13244 ConstantRange FoundLHSRange =
13245 ConstantRange::makeExactICmpRegion(FoundPred, ConstFoundRHS);
13246
13247 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
13248 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
13249
13250 // We can also compute the range of values for `LHS` that satisfy the
13251 // consequent, "`LHS` `Pred` `RHS`":
13252 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
13253 // The antecedent implies the consequent if every value of `LHS` that
13254 // satisfies the antecedent also satisfies the consequent.
13255 return LHSRange.icmp(Pred, ConstRHS);
13256}
13257
13258bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
13259 bool IsSigned) {
13260 assert(isKnownPositive(Stride) && "Positive stride expected!");
13261
13262 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13263 const SCEV *One = getOne(Stride->getType());
13264
13265 if (IsSigned) {
13266 APInt MaxRHS = getSignedRangeMax(RHS);
13267 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
13268 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13269
13270 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
13271 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
13272 }
13273
13274 APInt MaxRHS = getUnsignedRangeMax(RHS);
13275 APInt MaxValue = APInt::getMaxValue(BitWidth);
13276 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13277
13278 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
13279 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
13280}
13281
13282bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
13283 bool IsSigned) {
13284
13285 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13286 const SCEV *One = getOne(Stride->getType());
13287
13288 if (IsSigned) {
13289 APInt MinRHS = getSignedRangeMin(RHS);
13290 APInt MinValue = APInt::getSignedMinValue(BitWidth);
13291 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13292
13293 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
13294 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
13295 }
13296
13297 APInt MinRHS = getUnsignedRangeMin(RHS);
13298 APInt MinValue = APInt::getMinValue(BitWidth);
13299 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13300
13301 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
13302 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
13303}
13304
13306 // umin(N, 1) + floor((N - umin(N, 1)) / D)
13307 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
13308 // expression fixes the case of N=0.
13309 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
13310 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
13311 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
13312}
13313
13314const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
13315 const SCEV *Stride,
13316 const SCEV *End,
13317 unsigned BitWidth,
13318 bool IsSigned) {
13319 // The logic in this function assumes we can represent a positive stride.
13320 // If we can't, the backedge-taken count must be zero.
13321 if (IsSigned && BitWidth == 1)
13322 return getZero(Stride->getType());
13323
13324 // This code below only been closely audited for negative strides in the
13325 // unsigned comparison case, it may be correct for signed comparison, but
13326 // that needs to be established.
13327 if (IsSigned && isKnownNegative(Stride))
13328 return getCouldNotCompute();
13329
13330 // Calculate the maximum backedge count based on the range of values
13331 // permitted by Start, End, and Stride.
13332 APInt MinStart =
13333 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
13334
13335 APInt MinStride =
13336 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
13337
13338 // We assume either the stride is positive, or the backedge-taken count
13339 // is zero. So force StrideForMaxBECount to be at least one.
13340 APInt One(BitWidth, 1);
13341 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
13342 : APIntOps::umax(One, MinStride);
13343
13344 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
13345 : APInt::getMaxValue(BitWidth);
13346 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
13347
13348 // Although End can be a MAX expression we estimate MaxEnd considering only
13349 // the case End = RHS of the loop termination condition. This is safe because
13350 // in the other case (End - Start) is zero, leading to a zero maximum backedge
13351 // taken count.
13352 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
13353 : APIntOps::umin(getUnsignedRangeMax(End), Limit);
13354
13355 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
13356 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
13357 : APIntOps::umax(MaxEnd, MinStart);
13358
13359 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */,
13360 getConstant(StrideForMaxBECount) /* Step */);
13361}
13362
13364ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
13365 const Loop *L, bool IsSigned,
13366 bool ControlsOnlyExit, bool AllowPredicates) {
13368
13370 bool PredicatedIV = false;
13371 if (!IV) {
13372 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
13373 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
13374 if (AR && AR->getLoop() == L && AR->isAffine()) {
13375 auto canProveNUW = [&]() {
13376 // We can use the comparison to infer no-wrap flags only if it fully
13377 // controls the loop exit.
13378 if (!ControlsOnlyExit)
13379 return false;
13380
13381 if (!isLoopInvariant(RHS, L))
13382 return false;
13383
13384 if (!isKnownNonZero(AR->getStepRecurrence(*this)))
13385 // We need the sequence defined by AR to strictly increase in the
13386 // unsigned integer domain for the logic below to hold.
13387 return false;
13388
13389 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
13390 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
13391 // If RHS <=u Limit, then there must exist a value V in the sequence
13392 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
13393 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned
13394 // overflow occurs. This limit also implies that a signed comparison
13395 // (in the wide bitwidth) is equivalent to an unsigned comparison as
13396 // the high bits on both sides must be zero.
13397 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
13398 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
13399 Limit = Limit.zext(OuterBitWidth);
13400 return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit);
13401 };
13402 auto Flags = AR->getNoWrapFlags();
13403 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
13404 Flags = setFlags(Flags, SCEV::FlagNUW);
13405
13406 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
13407 if (AR->hasNoUnsignedWrap()) {
13408 // Emulate what getZeroExtendExpr would have done during construction
13409 // if we'd been able to infer the fact just above at that time.
13410 const SCEV *Step = AR->getStepRecurrence(*this);
13411 Type *Ty = ZExt->getType();
13412 auto *S = getAddRecExpr(
13414 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
13416 }
13417 }
13418 }
13419 }
13420
13421
13422 if (!IV && AllowPredicates) {
13423 // Try to make this an AddRec using runtime tests, in the first X
13424 // iterations of this loop, where X is the SCEV expression found by the
13425 // algorithm below.
13426 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13427 PredicatedIV = true;
13428 }
13429
13430 // Avoid weird loops
13431 if (!IV || IV->getLoop() != L || !IV->isAffine())
13432 return getCouldNotCompute();
13433
13434 // A precondition of this method is that the condition being analyzed
13435 // reaches an exiting branch which dominates the latch. Given that, we can
13436 // assume that an increment which violates the nowrap specification and
13437 // produces poison must cause undefined behavior when the resulting poison
13438 // value is branched upon and thus we can conclude that the backedge is
13439 // taken no more often than would be required to produce that poison value.
13440 // Note that a well defined loop can exit on the iteration which violates
13441 // the nowrap specification if there is another exit (either explicit or
13442 // implicit/exceptional) which causes the loop to execute before the
13443 // exiting instruction we're analyzing would trigger UB.
13444 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13445 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13447
13448 const SCEV *Stride = IV->getStepRecurrence(*this);
13449
13450 bool PositiveStride = isKnownPositive(Stride);
13451
13452 // Whether the IV may reach the maximum value before the exit is taken.
13453 bool IVMayOverflow = true;
13454
13455 // Avoid negative or zero stride values.
13456 if (!PositiveStride) {
13457 // We can compute the correct backedge taken count for loops with unknown
13458 // strides if we can prove that the loop is not an infinite loop with side
13459 // effects. Here's the loop structure we are trying to handle -
13460 //
13461 // i = start
13462 // do {
13463 // A[i] = i;
13464 // i += s;
13465 // } while (i < end);
13466 //
13467 // The backedge taken count for such loops is evaluated as -
13468 // (max(end, start + stride) - start - 1) /u stride
13469 //
13470 // The additional preconditions that we need to check to prove correctness
13471 // of the above formula is as follows -
13472 //
13473 // a) IV is either nuw or nsw depending upon signedness (indicated by the
13474 // NoWrap flag).
13475 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13476 // no side effects within the loop)
13477 // c) loop has a single static exit (with no abnormal exits)
13478 //
13479 // Precondition a) implies that if the stride is negative, this is a single
13480 // trip loop. The backedge taken count formula reduces to zero in this case.
13481 //
13482 // Precondition b) and c) combine to imply that if rhs is invariant in L,
13483 // then a zero stride means the backedge can't be taken without executing
13484 // undefined behavior.
13485 //
13486 // The positive stride case is the same as isKnownPositive(Stride) returning
13487 // true (original behavior of the function).
13488 //
13489 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
13491 return getCouldNotCompute();
13492
13493 if (!isKnownNonZero(Stride)) {
13494 // If we have a step of zero, and RHS isn't invariant in L, we don't know
13495 // if it might eventually be greater than start and if so, on which
13496 // iteration. We can't even produce a useful upper bound.
13497 if (!isLoopInvariant(RHS, L))
13498 return getCouldNotCompute();
13499
13500 // We allow a potentially zero stride, but we need to divide by stride
13501 // below. Since the loop can't be infinite and this check must control
13502 // the sole exit, we can infer the exit must be taken on the first
13503 // iteration (e.g. backedge count = 0) if the stride is zero. Given that,
13504 // we know the numerator in the divides below must be zero, so we can
13505 // pick an arbitrary non-zero value for the denominator (e.g. stride)
13506 // and produce the right result.
13507 // FIXME: Handle the case where Stride is poison?
13508 auto wouldZeroStrideBeUB = [&]() {
13509 // Proof by contradiction. Suppose the stride were zero. If we can
13510 // prove that the backedge *is* taken on the first iteration, then since
13511 // we know this condition controls the sole exit, we must have an
13512 // infinite loop. We can't have a (well defined) infinite loop per
13513 // check just above.
13514 // Note: The (Start - Stride) term is used to get the start' term from
13515 // (start' + stride,+,stride). Remember that we only care about the
13516 // result of this expression when stride == 0 at runtime.
13517 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
13518 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
13519 };
13520 if (!wouldZeroStrideBeUB()) {
13521 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13522 }
13523 }
13524 } else {
13525 // Avoid proven overflow cases: this will ensure that the backedge taken
13526 // count will not generate any unsigned overflow.
13527 IVMayOverflow = canIVOverflowOnLT(RHS, Stride, IsSigned);
13528 if (IVMayOverflow && !NoWrap)
13529 return getCouldNotCompute();
13530 }
13531
13532 // On all paths just preceeding, we established the following invariant:
13533 // IV can be assumed not to overflow up to and including the exiting
13534 // iteration. We proved this in one of two ways:
13535 // 1) We can show overflow doesn't occur before the exiting iteration
13536 // 1a) canIVOverflowOnLT, and b) step of one
13537 // 2) We can show that if overflow occurs, the loop must execute UB
13538 // before any possible exit.
13539 // Note that we have not yet proved RHS invariant (in general).
13540
13541 const SCEV *Start = IV->getStart();
13542
13543 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
13544 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
13545 // Use integer-typed versions for actual computation; we can't subtract
13546 // pointers in general.
13547 const SCEV *OrigStart = Start;
13548 const SCEV *OrigRHS = RHS;
13549 if (Start->getType()->isPointerTy()) {
13550 Start = getPtrToAddrExpr(Start);
13551 if (isa<SCEVCouldNotCompute>(Start))
13552 return Start;
13553 }
13554 if (RHS->getType()->isPointerTy()) {
13557 return RHS;
13558 }
13559
13560 const SCEV *End = nullptr, *BECount = getCouldNotCompute(),
13561 *BECountIfBackedgeTaken = getCouldNotCompute();
13562 if (!isLoopInvariant(RHS, L)) {
13563 const auto *RHSAddRec = dyn_cast<SCEVAddRecExpr>(RHS);
13564 if (PositiveStride && RHSAddRec != nullptr && RHSAddRec->getLoop() == L &&
13565 any(RHSAddRec->getNoWrapFlags())) {
13566 // The structure of loop we are trying to calculate backedge count of:
13567 //
13568 // left = left_start
13569 // right = right_start
13570 //
13571 // while(left < right){
13572 // ... do something here ...
13573 // left += s1; // stride of left is s1 (s1 > 0)
13574 // right += s2; // stride of right is s2 (s2 < 0)
13575 // }
13576 //
13577
13578 const SCEV *RHSStart = RHSAddRec->getStart();
13579 const SCEV *RHSStride = RHSAddRec->getStepRecurrence(*this);
13580
13581 // If Stride - RHSStride is positive and does not overflow, we can write
13582 // backedge count as ->
13583 // ceil((End - Start) /u (Stride - RHSStride))
13584 // Where, End = max(RHSStart, Start)
13585
13586 // Check if RHSStride < 0 and Stride - RHSStride will not overflow.
13587 if (isKnownNegative(RHSStride) &&
13588 willNotOverflow(Instruction::Sub, /*Signed=*/true, Stride,
13589 RHSStride)) {
13590
13591 const SCEV *Denominator = getMinusSCEV(Stride, RHSStride);
13592 if (isKnownPositive(Denominator)) {
13593 End = IsSigned ? getSMaxExpr(RHSStart, Start)
13594 : getUMaxExpr(RHSStart, Start);
13595
13596 // We can do this because End >= Start, as End = max(RHSStart, Start)
13597 const SCEV *Delta = getMinusSCEV(End, Start);
13598
13599 BECount = getUDivCeilSCEV(Delta, Denominator);
13600 BECountIfBackedgeTaken =
13601 getUDivCeilSCEV(getMinusSCEV(RHSStart, Start), Denominator);
13602 }
13603 }
13604 }
13605 } else {
13606 // Let End = max(RHS,Start). We use the expression (End-Start)/Stride to
13607 // describe the backedge count: if the backedge is taken at least once then
13608 // End is RHS, and if not End is Start so we get a backedge count of zero.
13609 //
13610 // AddingStrideMinusOneMayOverflow has the following preconditions:
13611 //
13612 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
13613 // 2. The index variable doesn't overflow.
13614 //
13615 // Therefore, we know N exists such that
13616 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
13617 // doesn't overflow.
13618 //
13619 // Using this information, try to prove whether the addition in
13620 // "(End - Start) + (Stride - 1)" has unsigned overflow.
13621 //
13622 // If the IV cannot overflow, RHS is at least Stride - 1 below the maximum
13623 // value, so the distance End - Start is at most UMAX - (Stride - 1) and
13624 // the (Stride - 1) addition below cannot overflow.
13625 const SCEV *One = getOne(Stride->getType());
13626 bool AddingStrideMinusOneMayOverflow = IVMayOverflow && [&] {
13627 if (isKnownToBeAPowerOfTwo(Stride)) {
13628 // Suppose Stride is a power of two, and Start/End are unsigned
13629 // integers. Let UMAX be the largest representable unsigned
13630 // integer.
13631 //
13632 // By the preconditions of this function, we know
13633 // "(Start + Stride * N) >= End", and this doesn't overflow.
13634 // As a formula:
13635 //
13636 // End <= (Start + Stride * N) <= UMAX
13637 //
13638 // Subtracting Start from all the terms:
13639 //
13640 // End - Start <= Stride * N <= UMAX - Start
13641 //
13642 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore:
13643 //
13644 // End - Start <= Stride * N <= UMAX
13645 //
13646 // Stride * N is a multiple of Stride. Therefore,
13647 //
13648 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
13649 //
13650 // Since Stride is a power of two, UMAX + 1 is divisible by
13651 // Stride. Therefore, UMAX mod Stride == Stride - 1. So we can
13652 // write:
13653 //
13654 // End - Start <= Stride * N <= UMAX - Stride - 1
13655 //
13656 // Dropping the middle term:
13657 //
13658 // End - Start <= UMAX - Stride - 1
13659 //
13660 // Adding Stride - 1 to both sides:
13661 //
13662 // (End - Start) + (Stride - 1) <= UMAX
13663 //
13664 // In other words, the addition doesn't have unsigned overflow.
13665 //
13666 // A similar proof works if we treat Start/End as signed values.
13667 // Just rewrite steps before "End - Start <= Stride * N <= UMAX"
13668 // to use signed max instead of unsigned max. Note that we're
13669 // trying to prove a lack of unsigned overflow in either case.
13670 return false;
13671 }
13672 if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
13673 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End
13674 // - 1. If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1
13675 // <u End. If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End -
13676 // 1 <s End.
13677 //
13678 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 ==
13679 // End.
13680 return false;
13681 }
13682 return true;
13683 }();
13684
13685 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
13686 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!");
13687 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
13688 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
13689 // Can we prove Start - Stride < RHS, and either Start - Stride < Start or
13690 // (via !AddingStrideMinusOneMayOverflow) that (RHS - Start) + (Stride - 1)
13691 // does not overflow?
13692 if ((!AddingStrideMinusOneMayOverflow ||
13693 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart)) &&
13694 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
13695 // In this case, we can use a refined formula for computing backedge
13696 // taken count. The general formula remains:
13697 // "End-Start /uceiling Stride"
13698 // We want to use the alternate formula:
13699 // "((RHS - 1) - (Start - Stride)) /u Stride"
13700 // Let's do a quick case analysis to show these are equivalent under
13701 // our preconditions.
13702 // * For RHS <= Start (End is Start), the backedge-taken count must be
13703 // zero. Together with the precondition "Start - Stride < RHS", we have
13704 // "Start - Stride < RHS <= Start". Subtracting Start - Stride from
13705 // all sides we get "0 < RHS - (Start - Stride) <= Stride".
13706 // Subtracting 1 we get "0 <= (RHS - 1) - (Start - Stride) < Stride".
13707 // So dividing that by Stride gives zero.
13708 //
13709 // * For RHS > Start (End is RHS), the backedge count must be
13710 // "RHS-Start /uceil Stride", so it is sufficient to show that the
13711 // numerator "((RHS - 1) - (Start - Stride))" does not overflow.
13712 //
13713 // If "Start - Stride < Start" holds, we have
13714 // "RHS > Start > Start - Stride". As such
13715 // "RHS - (Start - Stride) - 1" does not overflow, which is the
13716 // reassociated numerator.
13717 //
13718 // Otherwise !AddingStrideMinusOneMayOverflow guarantees that
13719 // "(End - Start) + (Stride - 1)" does not overflow unsigned. Here
13720 // "End" is "RHS", as "RHS > Start", so this is the reassociated
13721 // numerator. Neither sub-term wraps unsigned: "RHS - Start"
13722 // due to "RHS > Start", and "Stride - 1", as Stride is non-zero.
13723 const SCEV *MinusOne = getMinusOne(Stride->getType());
13724 const SCEV *Numerator =
13725 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
13726 BECount = getUDivExpr(Numerator, Stride);
13727 }
13728
13729 if (isa<SCEVCouldNotCompute>(BECount)) {
13730 auto canProveRHSGreaterThanEqualStart = [&]() {
13731 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
13732 const SCEV *GuardedRHS = applyLoopGuards(OrigRHS, L);
13733 const SCEV *GuardedStart = applyLoopGuards(OrigStart, L);
13734
13735 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart) ||
13736 isKnownPredicate(CondGE, GuardedRHS, GuardedStart))
13737 return true;
13738
13739 // (RHS > Start - 1) implies RHS >= Start.
13740 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
13741 // "Start - 1" doesn't overflow.
13742 // * For signed comparison, if Start - 1 does overflow, it's equal
13743 // to INT_MAX, and "RHS >s INT_MAX" is trivially false.
13744 // * For unsigned comparison, if Start - 1 does overflow, it's equal
13745 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
13746 //
13747 // FIXME: Should isLoopEntryGuardedByCond do this for us?
13748 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13749 auto *StartMinusOne =
13750 getAddExpr(OrigStart, getMinusOne(OrigStart->getType()));
13751 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
13752 };
13753
13754 // If we know that RHS >= Start in the context of loop, then we know
13755 // that max(RHS, Start) = RHS at this point.
13756 if (canProveRHSGreaterThanEqualStart()) {
13757 End = RHS;
13758 } else {
13759 // If RHS < Start, the backedge will be taken zero times. So in
13760 // general, we can write the backedge-taken count as:
13761 //
13762 // RHS >= Start ? ceil(RHS - Start) / Stride : 0
13763 //
13764 // We convert it to the following to make it more convenient for SCEV:
13765 //
13766 // ceil(max(RHS, Start) - Start) / Stride
13767 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
13768
13769 // See what would happen if we assume the backedge is taken. This is
13770 // used to compute MaxBECount.
13771 BECountIfBackedgeTaken =
13772 getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
13773 }
13774
13775 const SCEV *Delta = getMinusSCEV(End, Start);
13776 if (!AddingStrideMinusOneMayOverflow) {
13777 // floor((D + (S - 1)) / S)
13778 // We prefer this formulation if it's legal because it's fewer
13779 // operations.
13780 BECount =
13781 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13782 } else {
13783 BECount = getUDivCeilSCEV(Delta, Stride);
13784 }
13785 }
13786 }
13787
13788 const SCEV *ConstantMaxBECount;
13789 bool MaxOrZero = false;
13790 if (isa<SCEVConstant>(BECount)) {
13791 ConstantMaxBECount = BECount;
13792 } else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
13793 // If we know exactly how many times the backedge will be taken if it's
13794 // taken at least once, then the backedge count will either be that or
13795 // zero.
13796 ConstantMaxBECount = BECountIfBackedgeTaken;
13797 MaxOrZero = true;
13798 } else {
13799 ConstantMaxBECount = computeMaxBECountForLT(
13800 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
13801 }
13802
13803 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
13804 !isa<SCEVCouldNotCompute>(BECount))
13805 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
13806
13807 const SCEV *SymbolicMaxBECount =
13808 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13809 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
13810 Predicates);
13811}
13812
13813ScalarEvolution::ExitLimit ScalarEvolution::howManyGreaterThans(
13814 const SCEV *LHS, const SCEV *RHS, const Loop *L, bool IsSigned,
13815 bool ControlsOnlyExit, bool AllowPredicates) {
13817 // We handle only IV > Invariant
13818 if (!isLoopInvariant(RHS, L))
13819 return getCouldNotCompute();
13820
13821 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
13822 if (!IV && AllowPredicates)
13823 // Try to make this an AddRec using runtime tests, in the first X
13824 // iterations of this loop, where X is the SCEV expression found by the
13825 // algorithm below.
13826 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13827
13828 // Avoid weird loops
13829 if (!IV || IV->getLoop() != L || !IV->isAffine())
13830 return getCouldNotCompute();
13831
13832 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13833 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13835
13836 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
13837
13838 // Avoid negative or zero stride values
13839 if (!isKnownPositive(Stride))
13840 return getCouldNotCompute();
13841
13842 // Avoid proven overflow cases: this will ensure that the backedge taken count
13843 // will not generate any unsigned overflow. Relaxed no-overflow conditions
13844 // exploit NoWrapFlags, allowing to optimize in presence of undefined
13845 // behaviors like the case of C language.
13846 bool MayAddOverflow = false;
13847 const SCEV *Start = IV->getStart();
13848 const SCEV *End = RHS;
13849 if (!Stride->isOne() && canIVOverflowOnGT(RHS, Stride, IsSigned)) {
13850 if (!NoWrap)
13851 return getCouldNotCompute();
13852 MayAddOverflow = true;
13853 }
13854
13855 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
13856 // If we know that Start >= RHS in the context of loop, then we know that
13857 // min(RHS, Start) = RHS at this point.
13859 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
13860 End = RHS;
13861 else
13862 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
13863 }
13864
13865 if (Start->getType()->isPointerTy()) {
13866 Start = getPtrToAddrExpr(Start);
13867 if (isa<SCEVCouldNotCompute>(Start))
13868 return Start;
13869 }
13870 if (End->getType()->isPointerTy()) {
13871 End = getPtrToAddrExpr(End);
13872 if (isa<SCEVCouldNotCompute>(End))
13873 return End;
13874 }
13875
13876 const SCEV *Delta = getMinusSCEV(Start, End);
13877 const SCEV *BECount;
13878 if (MayAddOverflow) {
13879 // The ceiling division instead needs Start >= End, so that (Start - End) is
13880 // the exact unsigned distance between them.
13882 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, End))
13883 return getCouldNotCompute();
13884 BECount = getUDivCeilSCEV(Delta, Stride);
13885 } else {
13886 // Compute ((Start - End) + (Stride - 1)) / Stride, if the IV cannot
13887 // overflow as it requires fewer operations.
13888 const SCEV *One = getOne(Stride->getType());
13889 BECount = getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13890 }
13891
13892 APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
13894
13895 APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
13896 : getUnsignedRangeMin(Stride);
13897
13898 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
13899 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
13900 : APInt::getMinValue(BitWidth) + (MinStride - 1);
13901
13902 // Although End can be a MIN expression we estimate MinEnd considering only
13903 // the case End = RHS. This is safe because in the other case (Start - End)
13904 // is zero, leading to a zero maximum backedge taken count.
13905 APInt MinEnd =
13906 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
13907 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
13908
13909 const SCEV *ConstantMaxBECount =
13910 isa<SCEVConstant>(BECount)
13911 ? BECount
13912 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd),
13913 getConstant(MinStride));
13914
13915 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount))
13916 ConstantMaxBECount = BECount;
13917 const SCEV *SymbolicMaxBECount =
13918 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13919
13920 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
13921 Predicates);
13922}
13923
13925 ScalarEvolution &SE) const {
13926 if (Range.isFullSet()) // Infinite loop.
13927 return SE.getCouldNotCompute();
13928
13929 // If the start is a non-zero constant, shift the range to simplify things.
13930 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
13931 if (!SC->getValue()->isZero()) {
13933 Operands[0] = SE.getZero(SC->getType());
13934 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
13936 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
13937 return ShiftedAddRec->getNumIterationsInRange(
13938 Range.subtract(SC->getAPInt()), SE);
13939 // This is strange and shouldn't happen.
13940 return SE.getCouldNotCompute();
13941 }
13942
13943 // The only time we can solve this is when we have all constant indices.
13944 // Otherwise, we cannot determine the overflow conditions.
13946 return SE.getCouldNotCompute();
13947
13948 // Okay at this point we know that all elements of the chrec are constants and
13949 // that the start element is zero.
13950
13951 // First check to see if the range contains zero. If not, the first
13952 // iteration exits.
13953 unsigned BitWidth = SE.getTypeSizeInBits(getType());
13954 if (!Range.contains(APInt(BitWidth, 0)))
13955 return SE.getZero(getType());
13956
13957 if (isAffine()) {
13958 // If this is an affine expression then we have this situation:
13959 // Solve {0,+,A} in Range === Ax in Range
13960
13961 // We know that zero is in the range. If A is positive then we know that
13962 // the upper value of the range must be the first possible exit value.
13963 // If A is negative then the lower of the range is the last possible loop
13964 // value. Also note that we already checked for a full range.
13965 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
13966 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
13967
13968 // The exit value should be (End+A)/A.
13969 APInt ExitVal = (End + A).udiv(A);
13970 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
13971
13972 // Evaluate at the exit value. If we really did fall out of the valid
13973 // range, then we computed our trip count, otherwise wrap around or other
13974 // things must have happened.
13975 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
13976 if (Range.contains(Val->getValue()))
13977 return SE.getCouldNotCompute(); // Something strange happened
13978
13979 // Ensure that the previous value is in the range.
13980 assert(Range.contains(
13982 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
13983 "Linear scev computation is off in a bad way!");
13984 return SE.getConstant(ExitValue);
13985 }
13986
13987 if (isQuadratic()) {
13988 if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
13989 return SE.getConstant(*S);
13990 }
13991
13992 return SE.getCouldNotCompute();
13993}
13994
13995const SCEVAddRecExpr *
13997 assert(getNumOperands() > 1 && "AddRec with zero step?");
13998 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
13999 // but in this case we cannot guarantee that the value returned will be an
14000 // AddRec because SCEV does not have a fixed point where it stops
14001 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
14002 // may happen if we reach arithmetic depth limit while simplifying. So we
14003 // construct the returned value explicitly.
14005 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
14006 // (this + Step) is {A+B,+,B+C,+...,+,N}.
14007 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
14008 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
14009 // We know that the last operand is not a constant zero (otherwise it would
14010 // have been popped out earlier). This guarantees us that if the result has
14011 // the same last operand, then it will also not be popped out, meaning that
14012 // the returned value will be an AddRec.
14013 const SCEV *Last = getOperand(getNumOperands() - 1);
14014 assert(!Last->isZero() && "Recurrency with zero step?");
14015 Ops.push_back(Last);
14018}
14019
14020// Return true when S contains at least an undef value.
14022 return SCEVExprContains(
14023 S, [](const SCEV *S) { return match(S, m_scev_UndefOrPoison()); });
14024}
14025
14026// Return true when S contains a value that is a nullptr.
14028 return SCEVExprContains(S, [](const SCEV *S) {
14029 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
14030 return SU->getValue() == nullptr;
14031 return false;
14032 });
14033}
14034
14035/// Return the size of an element read or written by Inst.
14037 Type *Ty;
14038 Type *PtrTy;
14039 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
14040 Ty = Store->getValueOperand()->getType();
14041 PtrTy = Store->getPointerOperandType();
14042 } else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
14043 Ty = Load->getType();
14044 PtrTy = Load->getPointerOperandType();
14045 } else {
14046 return nullptr;
14047 }
14048
14049 Type *ETy = getEffectiveSCEVType(PtrTy);
14050 return getSizeOfExpr(ETy, Ty);
14051}
14052
14053//===----------------------------------------------------------------------===//
14054// SCEVCallbackVH Class Implementation
14055//===----------------------------------------------------------------------===//
14056
14058 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14059 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
14060 SE->ConstantEvolutionLoopExitValue.erase(PN);
14061 SE->eraseValueFromMap(getValPtr());
14062 // this now dangles!
14063}
14064
14065void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
14066 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14067
14068 // Forget all the expressions associated with users of the old value,
14069 // so that future queries will recompute the expressions using the new
14070 // value.
14071 SE->forgetValue(getValPtr());
14072 // this now dangles!
14073}
14074
14075ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
14076 : CallbackVH(V), SE(se) {}
14077
14078//===----------------------------------------------------------------------===//
14079// ScalarEvolution Class Implementation
14080//===----------------------------------------------------------------------===//
14081
14084 LoopInfo &LI)
14085 : F(F), DL(F.getDataLayout()), TLI(TLI), AC(AC), DT(DT), LI(LI),
14086 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
14087 LoopDispositions(64), BlockDispositions(64) {
14088 // To use guards for proving predicates, we need to scan every instruction in
14089 // relevant basic blocks, and not just terminators. Doing this is a waste of
14090 // time if the IR does not actually contain any calls to
14091 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
14092 //
14093 // This pessimizes the case where a pass that preserves ScalarEvolution wants
14094 // to _add_ guards to the module when there weren't any before, and wants
14095 // ScalarEvolution to optimize based on those guards. For now we prefer to be
14096 // efficient in lieu of being smart in that rather obscure case.
14097
14098 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
14099 F.getParent(), Intrinsic::experimental_guard);
14100 HasGuards = GuardDecl && !GuardDecl->use_empty();
14101}
14102
14104 : F(Arg.F), DL(Arg.DL), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC),
14105 DT(Arg.DT), LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
14106 ValueExprMap(std::move(Arg.ValueExprMap)),
14107 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
14108 PendingMerges(std::move(Arg.PendingMerges)),
14109 ConstantMultipleCache(std::move(Arg.ConstantMultipleCache)),
14110 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
14111 PredicatedBackedgeTakenCounts(
14112 std::move(Arg.PredicatedBackedgeTakenCounts)),
14113 BECountUsers(std::move(Arg.BECountUsers)),
14114 ConstantEvolutionLoopExitValue(
14115 std::move(Arg.ConstantEvolutionLoopExitValue)),
14116 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
14117 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
14118 LoopDispositions(std::move(Arg.LoopDispositions)),
14119 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
14120 BlockDispositions(std::move(Arg.BlockDispositions)),
14121 SCEVUsers(std::move(Arg.SCEVUsers)),
14122 UnsignedRanges(std::move(Arg.UnsignedRanges)),
14123 SignedRanges(std::move(Arg.SignedRanges)),
14124 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
14125 UniquePreds(std::move(Arg.UniquePreds)),
14126 SCEVAllocator(std::move(Arg.SCEVAllocator)),
14127 ConstantSCEVs(std::move(Arg.ConstantSCEVs)),
14128 LoopUsers(std::move(Arg.LoopUsers)),
14129 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
14130 FirstUnknown(Arg.FirstUnknown) {
14131 Arg.FirstUnknown = nullptr;
14132}
14133
14135 // Iterate through all the SCEVUnknown instances and call their
14136 // destructors, so that they release their references to their values.
14137 for (SCEVUnknown *U = FirstUnknown; U;) {
14138 SCEVUnknown *Tmp = U;
14139 U = U->Next;
14140 Tmp->~SCEVUnknown();
14141 }
14142 FirstUnknown = nullptr;
14143
14144 ExprValueMap.clear();
14145 ValueExprMap.clear();
14146 HasRecMap.clear();
14147 BackedgeTakenCounts.clear();
14148 PredicatedBackedgeTakenCounts.clear();
14149
14150 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
14151 assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
14152 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
14153 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
14154}
14155
14159
14160/// When printing a top-level SCEV for trip counts, it's helpful to include
14161/// a type for constants which are otherwise hard to disambiguate.
14162static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV* S) {
14163 if (isa<SCEVConstant>(S))
14164 OS << *S->getType() << " ";
14165 OS << *S;
14166}
14167
14169 const Loop *L) {
14170 // Print all inner loops first
14171 for (Loop *I : *L)
14172 PrintLoopInfo(OS, SE, I);
14173
14174 OS << "Loop ";
14175 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14176 OS << ": ";
14177
14178 SmallVector<BasicBlock *, 8> ExitingBlocks;
14179 L->getExitingBlocks(ExitingBlocks);
14180 if (ExitingBlocks.size() != 1)
14181 OS << "<multiple exits> ";
14182
14183 auto *BTC = SE->getBackedgeTakenCount(L);
14184 if (!isa<SCEVCouldNotCompute>(BTC)) {
14185 OS << "backedge-taken count is ";
14186 PrintSCEVWithTypeHint(OS, BTC);
14187 } else
14188 OS << "Unpredictable backedge-taken count.";
14189 OS << "\n";
14190
14191 if (ExitingBlocks.size() > 1)
14192 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14193 OS << " exit count for " << ExitingBlock->getName() << ": ";
14194 const SCEV *EC = SE->getExitCount(L, ExitingBlock);
14195 PrintSCEVWithTypeHint(OS, EC);
14196 if (isa<SCEVCouldNotCompute>(EC)) {
14197 // Retry with predicates.
14199 EC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates);
14200 if (!isa<SCEVCouldNotCompute>(EC)) {
14201 OS << "\n predicated exit count for " << ExitingBlock->getName()
14202 << ": ";
14203 PrintSCEVWithTypeHint(OS, EC);
14204 OS << "\n Predicates:\n";
14205 for (const auto *P : Predicates)
14206 P->print(OS, 4);
14207 }
14208 }
14209 OS << "\n";
14210 }
14211
14212 OS << "Loop ";
14213 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14214 OS << ": ";
14215
14216 auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
14217 if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
14218 OS << "constant max backedge-taken count is ";
14219 PrintSCEVWithTypeHint(OS, ConstantBTC);
14221 OS << ", actual taken count either this or zero.";
14222 } else {
14223 OS << "Unpredictable constant max backedge-taken count. ";
14224 }
14225
14226 OS << "\n"
14227 "Loop ";
14228 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14229 OS << ": ";
14230
14231 auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
14232 if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
14233 OS << "symbolic max backedge-taken count is ";
14234 PrintSCEVWithTypeHint(OS, SymbolicBTC);
14236 OS << ", actual taken count either this or zero.";
14237 } else {
14238 OS << "Unpredictable symbolic max backedge-taken count. ";
14239 }
14240 OS << "\n";
14241
14242 if (ExitingBlocks.size() > 1)
14243 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14244 OS << " symbolic max exit count for " << ExitingBlock->getName() << ": ";
14245 auto *ExitBTC = SE->getExitCount(L, ExitingBlock,
14247 PrintSCEVWithTypeHint(OS, ExitBTC);
14248 if (isa<SCEVCouldNotCompute>(ExitBTC)) {
14249 // Retry with predicates.
14251 ExitBTC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates,
14253 if (!isa<SCEVCouldNotCompute>(ExitBTC)) {
14254 OS << "\n predicated symbolic max exit count for "
14255 << ExitingBlock->getName() << ": ";
14256 PrintSCEVWithTypeHint(OS, ExitBTC);
14257 OS << "\n Predicates:\n";
14258 for (const auto *P : Predicates)
14259 P->print(OS, 4);
14260 }
14261 }
14262 OS << "\n";
14263 }
14264
14266 auto *PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
14267 if (PBT != BTC) {
14268 OS << "Loop ";
14269 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14270 OS << ": ";
14271 if (!isa<SCEVCouldNotCompute>(PBT)) {
14272 OS << "Predicated backedge-taken count is ";
14273 PrintSCEVWithTypeHint(OS, PBT);
14274 } else
14275 OS << "Unpredictable predicated backedge-taken count.";
14276 OS << "\n";
14277 OS << " Predicates:\n";
14278 for (const auto *P : Preds)
14279 P->print(OS, 4);
14280 }
14281 Preds.clear();
14282
14283 auto *PredConstantMax =
14285 if (PredConstantMax != ConstantBTC) {
14286 OS << "Loop ";
14287 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14288 OS << ": ";
14289 if (!isa<SCEVCouldNotCompute>(PredConstantMax)) {
14290 OS << "Predicated constant max backedge-taken count is ";
14291 PrintSCEVWithTypeHint(OS, PredConstantMax);
14292 } else
14293 OS << "Unpredictable predicated constant max backedge-taken count.";
14294 OS << "\n";
14295 OS << " Predicates:\n";
14296 for (const auto *P : Preds)
14297 P->print(OS, 4);
14298 }
14299 Preds.clear();
14300
14301 auto *PredSymbolicMax =
14303 if (SymbolicBTC != PredSymbolicMax) {
14304 OS << "Loop ";
14305 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14306 OS << ": ";
14307 if (!isa<SCEVCouldNotCompute>(PredSymbolicMax)) {
14308 OS << "Predicated symbolic max backedge-taken count is ";
14309 PrintSCEVWithTypeHint(OS, PredSymbolicMax);
14310 } else
14311 OS << "Unpredictable predicated symbolic max backedge-taken count.";
14312 OS << "\n";
14313 OS << " Predicates:\n";
14314 for (const auto *P : Preds)
14315 P->print(OS, 4);
14316 }
14317
14319 OS << "Loop ";
14320 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14321 OS << ": ";
14322 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
14323 }
14324}
14325
14326namespace llvm {
14327// Note: these overloaded operators need to be in the llvm namespace for them
14328// to be resolved correctly. If we put them outside the llvm namespace, the
14329//
14330// OS << ": " << SE.getLoopDisposition(SV, InnerL);
14331//
14332// code below "breaks" and start printing raw enum values as opposed to the
14333// string values.
14336 switch (LD) {
14338 OS << "Variant";
14339 break;
14341 OS << "Invariant";
14342 break;
14344 OS << "Uniform";
14345 break;
14347 OS << "Computable";
14348 break;
14349 }
14350 return OS;
14351}
14352
14355 switch (BD) {
14357 OS << "DoesNotDominate";
14358 break;
14360 OS << "Dominates";
14361 break;
14363 OS << "ProperlyDominates";
14364 break;
14365 }
14366 return OS;
14367}
14368} // namespace llvm
14369
14371 // ScalarEvolution's implementation of the print method is to print
14372 // out SCEV values of all instructions that are interesting. Doing
14373 // this potentially causes it to create new SCEV objects though,
14374 // which technically conflicts with the const qualifier. This isn't
14375 // observable from outside the class though, so casting away the
14376 // const isn't dangerous.
14377 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14378
14379 if (ClassifyExpressions) {
14380 OS << "Classifying expressions for: ";
14381 F.printAsOperand(OS, /*PrintType=*/false);
14382 OS << "\n";
14383 for (Instruction &I : instructions(F))
14384 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
14385 OS << I << '\n';
14386 OS << " --> ";
14387 const SCEV *SV = SE.getSCEV(&I);
14388 SV->print(OS);
14389 if (!isa<SCEVCouldNotCompute>(SV)) {
14390 OS << " U: ";
14391 SE.getUnsignedRange(SV).print(OS);
14392 OS << " S: ";
14393 SE.getSignedRange(SV).print(OS);
14394 }
14395
14396 const Loop *L = LI.getLoopFor(I.getParent());
14397
14398 SCEVUse AtUse = SE.getSCEVAtScope(SV, L);
14399 if (AtUse != SV) {
14400 OS << " --> ";
14401 OS << AtUse;
14402 if (!isa<SCEVCouldNotCompute>(AtUse)) {
14403 OS << " U: ";
14404 SE.getUnsignedRange(AtUse).print(OS);
14405 OS << " S: ";
14406 SE.getSignedRange(AtUse).print(OS);
14407 }
14408 }
14409
14410 if (L) {
14411 OS << "\t\t" "Exits: ";
14412 SCEVUse ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
14413 if (!SE.isLoopInvariant(ExitValue, L)) {
14414 OS << "<<Unknown>>";
14415 } else {
14416 OS << ExitValue;
14417 }
14418
14419 ListSeparator LS(", ", "\t\tLoopDispositions: { ");
14420 for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
14421 OS << LS;
14422 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14423 OS << ": " << SE.getLoopDisposition(SV, Iter);
14424 }
14425
14426 for (const auto *InnerL : depth_first(L)) {
14427 if (InnerL == L)
14428 continue;
14429 OS << LS;
14430 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14431 OS << ": " << SE.getLoopDisposition(SV, InnerL);
14432 }
14433
14434 OS << " }";
14435 }
14436
14437 OS << "\n";
14438 }
14439 }
14440
14441 OS << "Determining loop execution counts for: ";
14442 F.printAsOperand(OS, /*PrintType=*/false);
14443 OS << "\n";
14444 for (Loop *I : LI)
14445 PrintLoopInfo(OS, &SE, I);
14446}
14447
14450 auto &Values = LoopDispositions[S];
14451 for (auto &V : Values) {
14452 if (V.getPointer() == L)
14453 return V.getInt();
14454 }
14455 Values.emplace_back(L, LoopVariant);
14456 LoopDisposition D = computeLoopDisposition(S, L);
14457 auto &Values2 = LoopDispositions[S];
14458 for (auto &V : llvm::reverse(Values2)) {
14459 if (V.getPointer() == L) {
14460 V.setInt(D);
14461 break;
14462 }
14463 }
14464 return D;
14465}
14466
14468ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
14469 switch (S->getSCEVType()) {
14470 case scConstant:
14471 case scVScale:
14472 return LoopInvariant;
14473 case scAddRecExpr: {
14474 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14475
14476 // If L is the addrec's loop, it's computable.
14477 if (AR->getLoop() == L)
14478 return LoopComputable;
14479
14480 // Add recurrences are never invariant in the function-body (null loop).
14481 if (!L)
14482 return LoopVariant;
14483
14484 // Everything that is not defined at loop entry is variant.
14485 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) {
14486 if (L->contains(AR->getLoop()) &&
14487 llvm::all_of(AR->operands(),
14488 [&](const SCEV *Op) { return isLoopUniform(Op, L); }))
14489 return LoopUniform;
14490
14491 return LoopVariant;
14492 }
14493 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
14494 " dominate the contained loop's header?");
14495
14496 // This recurrence is invariant w.r.t. L if AR's loop contains L.
14497 if (AR->getLoop()->contains(L))
14498 return LoopInvariant;
14499
14500 // This recurrence is variant w.r.t. L if any of its operands
14501 // are variant.
14502 for (SCEVUse Op : AR->operands())
14503 if (!isLoopInvariant(Op, L))
14504 return LoopVariant;
14505
14506 // Otherwise it's loop-invariant.
14507 return LoopInvariant;
14508 }
14509 case scTruncate:
14510 case scZeroExtend:
14511 case scSignExtend:
14512 case scPtrToAddr:
14513 case scAddExpr:
14514 case scMulExpr:
14515 case scUDivExpr:
14516 case scUMaxExpr:
14517 case scSMaxExpr:
14518 case scUMinExpr:
14519 case scSMinExpr:
14520 case scSequentialUMinExpr: {
14521 bool HasVarying = false;
14522 bool HasUniform = false;
14523 for (SCEVUse Op : S->operands()) {
14525 if (D == LoopVariant)
14526 return LoopVariant;
14527 if (D == LoopComputable)
14528 HasVarying = true;
14529 if (D == LoopUniform)
14530 HasUniform = true;
14531 }
14532 return HasVarying ? (HasUniform ? LoopVariant : LoopComputable)
14533 : (HasUniform ? LoopUniform : LoopInvariant);
14534 }
14535 case scUnknown:
14536 // All non-instruction values are loop invariant. All instructions are loop
14537 // invariant if they are not contained in the specified loop.
14538 // Instructions are never considered invariant in the function body
14539 // (null loop) because they are defined within the "loop".
14541 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
14542 return LoopInvariant;
14543 case scCouldNotCompute:
14544 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14545 }
14546 llvm_unreachable("Unknown SCEV kind!");
14547}
14548
14549bool ScalarEvolution::isLoopUniform(const SCEV *S, const Loop *L) {
14551 return D == LoopUniform || D == LoopInvariant;
14552}
14553
14555 return getLoopDisposition(S, L) == LoopInvariant;
14556}
14557
14559 return getLoopDisposition(S, L) == LoopComputable;
14560}
14561
14564 auto &Values = BlockDispositions[S];
14565 for (auto &V : Values) {
14566 if (V.getPointer() == BB)
14567 return V.getInt();
14568 }
14569 Values.emplace_back(BB, DoesNotDominateBlock);
14570 BlockDisposition D = computeBlockDisposition(S, BB);
14571 auto &Values2 = BlockDispositions[S];
14572 for (auto &V : llvm::reverse(Values2)) {
14573 if (V.getPointer() == BB) {
14574 V.setInt(D);
14575 break;
14576 }
14577 }
14578 return D;
14579}
14580
14582ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
14583 switch (S->getSCEVType()) {
14584 case scConstant:
14585 case scVScale:
14587 case scAddRecExpr: {
14588 // This uses a "dominates" query instead of "properly dominates" query
14589 // to test for proper dominance too, because the instruction which
14590 // produces the addrec's value is a PHI, and a PHI effectively properly
14591 // dominates its entire containing block.
14592 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14593 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
14594 return DoesNotDominateBlock;
14595
14596 // Fall through into SCEVNAryExpr handling.
14597 [[fallthrough]];
14598 }
14599 case scTruncate:
14600 case scZeroExtend:
14601 case scSignExtend:
14602 case scPtrToAddr:
14603 case scAddExpr:
14604 case scMulExpr:
14605 case scUDivExpr:
14606 case scUMaxExpr:
14607 case scSMaxExpr:
14608 case scUMinExpr:
14609 case scSMinExpr:
14610 case scSequentialUMinExpr: {
14611 bool Proper = true;
14612 for (const SCEV *NAryOp : S->operands()) {
14614 if (D == DoesNotDominateBlock)
14615 return DoesNotDominateBlock;
14616 if (D == DominatesBlock)
14617 Proper = false;
14618 }
14619 return Proper ? ProperlyDominatesBlock : DominatesBlock;
14620 }
14621 case scUnknown:
14622 if (Instruction *I =
14624 if (I->getParent() == BB)
14625 return DominatesBlock;
14626 if (DT.properlyDominates(I->getParent(), BB))
14628 return DoesNotDominateBlock;
14629 }
14631 case scCouldNotCompute:
14632 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14633 }
14634 llvm_unreachable("Unknown SCEV kind!");
14635}
14636
14637bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
14638 return getBlockDisposition(S, BB) >= DominatesBlock;
14639}
14640
14643}
14644
14645bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
14646 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
14647}
14648
14649void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
14650 bool Predicated) {
14651 auto &BECounts =
14652 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14653 auto It = BECounts.find(L);
14654 if (It != BECounts.end()) {
14655 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
14656 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14657 if (!isa<SCEVConstant>(S)) {
14658 auto UserIt = BECountUsers.find(S);
14659 assert(UserIt != BECountUsers.end());
14660 UserIt->second.erase({L, Predicated});
14661 }
14662 }
14663 }
14664 BECounts.erase(It);
14665 }
14666}
14667
14668void ScalarEvolution::forgetMemoizedResults(ArrayRef<SCEVUse> SCEVs) {
14669 SmallPtrSet<const SCEV *, 8> ToForget(llvm::from_range, SCEVs);
14670 SmallVector<SCEVUse, 8> Worklist(ToForget.begin(), ToForget.end());
14671
14672 while (!Worklist.empty()) {
14673 const SCEV *Curr = Worklist.pop_back_val();
14674 auto Users = SCEVUsers.find(Curr);
14675 if (Users != SCEVUsers.end())
14676 for (const auto *User : Users->second)
14677 if (ToForget.insert(User).second)
14678 Worklist.push_back(User);
14679 }
14680
14681 for (const auto *S : ToForget)
14682 forgetMemoizedResultsImpl(S);
14683
14684 PredicatedSCEVRewrites.remove_if(
14685 [&](const auto &Entry) { return ToForget.count(Entry.first.first); });
14686}
14687
14688void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
14689 LoopDispositions.erase(S);
14690 BlockDispositions.erase(S);
14691 UnsignedRanges.erase(S);
14692 SignedRanges.erase(S);
14693 HasRecMap.erase(S);
14694 ConstantMultipleCache.erase(S);
14695
14696 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
14697 UnsignedWrapViaInductionTried.erase(AR);
14698 SignedWrapViaInductionTried.erase(AR);
14699 }
14700
14701 auto ExprIt = ExprValueMap.find(S);
14702 if (ExprIt != ExprValueMap.end()) {
14703 for (Value *V : ExprIt->second) {
14704 auto ValueIt = ValueExprMap.find_as(V);
14705 if (ValueIt != ValueExprMap.end())
14706 ValueExprMap.erase(ValueIt);
14707 }
14708 ExprValueMap.erase(ExprIt);
14709 }
14710
14711 auto ScopeIt = ValuesAtScopes.find(S);
14712 if (ScopeIt != ValuesAtScopes.end()) {
14713 for (const auto &Pair : ScopeIt->second)
14714 if (!isa_and_nonnull<SCEVConstant>(Pair.second))
14715 llvm::erase(ValuesAtScopesUsers[Pair.second.getPointer()],
14716 std::make_pair(Pair.first, S));
14717 ValuesAtScopes.erase(ScopeIt);
14718 }
14719
14720 auto ScopeUserIt = ValuesAtScopesUsers.find(S);
14721 if (ScopeUserIt != ValuesAtScopesUsers.end()) {
14722 for (const auto &Pair : ScopeUserIt->second)
14723 // The recorded value at scope is a use of S, which may carry no-wrap
14724 // flags that are not part of this key.
14725 llvm::erase_if(ValuesAtScopes[Pair.second], [&](const auto &LS) {
14726 return LS.first == Pair.first && LS.second.getPointer() == S;
14727 });
14728 ValuesAtScopesUsers.erase(ScopeUserIt);
14729 }
14730
14731 auto BEUsersIt = BECountUsers.find(S);
14732 if (BEUsersIt != BECountUsers.end()) {
14733 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
14734 auto Copy = BEUsersIt->second;
14735 for (const auto &Pair : Copy)
14736 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
14737 BECountUsers.erase(BEUsersIt);
14738 }
14739
14740 auto FoldUser = FoldCacheUser.find(S);
14741 if (FoldUser != FoldCacheUser.end())
14742 for (auto &KV : FoldUser->second)
14743 FoldCache.erase(KV);
14744 FoldCacheUser.erase(S);
14745}
14746
14747void
14748ScalarEvolution::getUsedLoops(const SCEV *S,
14749 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
14750 struct FindUsedLoops {
14751 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
14752 : LoopsUsed(LoopsUsed) {}
14753 SmallPtrSetImpl<const Loop *> &LoopsUsed;
14754 bool follow(const SCEV *S) {
14755 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
14756 LoopsUsed.insert(AR->getLoop());
14757 return true;
14758 }
14759
14760 bool isDone() const { return false; }
14761 };
14762
14763 FindUsedLoops F(LoopsUsed);
14764 SCEVTraversal<FindUsedLoops>(F).visitAll(S);
14765}
14766
14767void ScalarEvolution::getReachableBlocks(
14770 Worklist.push_back(&F.getEntryBlock());
14771 while (!Worklist.empty()) {
14772 BasicBlock *BB = Worklist.pop_back_val();
14773 if (!Reachable.insert(BB).second)
14774 continue;
14775
14776 Value *Cond;
14777 BasicBlock *TrueBB, *FalseBB;
14778 if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
14779 m_BasicBlock(FalseBB)))) {
14780 if (auto *C = dyn_cast<ConstantInt>(Cond)) {
14781 Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
14782 continue;
14783 }
14784
14785 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14786 const SCEV *L = getSCEV(Cmp->getOperand(0));
14787 const SCEV *R = getSCEV(Cmp->getOperand(1));
14788 if (isKnownPredicateViaConstantRanges(Cmp->getCmpPredicate(), L, R)) {
14789 Worklist.push_back(TrueBB);
14790 continue;
14791 }
14792 if (isKnownPredicateViaConstantRanges(Cmp->getInverseCmpPredicate(), L,
14793 R)) {
14794 Worklist.push_back(FalseBB);
14795 continue;
14796 }
14797 }
14798 }
14799
14800 append_range(Worklist, successors(BB));
14801 }
14802}
14803
14805 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14806 ScalarEvolution SE2(F, TLI, AC, DT, LI);
14807
14808 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
14809
14810 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
14811 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
14812 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
14813
14814 const SCEV *visitConstant(const SCEVConstant *Constant) {
14815 return SE.getConstant(Constant->getAPInt());
14816 }
14817
14818 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14819 return SE.getUnknown(Expr->getValue());
14820 }
14821
14822 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
14823 return SE.getCouldNotCompute();
14824 }
14825 };
14826
14827 SCEVMapper SCM(SE2);
14828 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
14829 SE2.getReachableBlocks(ReachableBlocks, F);
14830
14831 auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
14832 if (containsUndefs(Old) || containsUndefs(New)) {
14833 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
14834 // not propagate undef aggressively). This means we can (and do) fail
14835 // verification in cases where a transform makes a value go from "undef"
14836 // to "undef+1" (say). The transform is fine, since in both cases the
14837 // result is "undef", but SCEV thinks the value increased by 1.
14838 return nullptr;
14839 }
14840
14841 // Unless VerifySCEVStrict is set, we only compare constant deltas.
14842 const SCEV *Delta = SE2.getMinusSCEV(Old, New);
14843 if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
14844 return nullptr;
14845
14846 return Delta;
14847 };
14848
14849 while (!LoopStack.empty()) {
14850 auto *L = LoopStack.pop_back_val();
14851 llvm::append_range(LoopStack, *L);
14852
14853 // Only verify BECounts in reachable loops. For an unreachable loop,
14854 // any BECount is legal.
14855 if (!ReachableBlocks.contains(L->getHeader()))
14856 continue;
14857
14858 // Only verify cached BECounts. Computing new BECounts may change the
14859 // results of subsequent SCEV uses.
14860 auto It = BackedgeTakenCounts.find(L);
14861 if (It == BackedgeTakenCounts.end())
14862 continue;
14863
14864 auto *CurBECount =
14865 SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
14866 auto *NewBECount = SE2.getBackedgeTakenCount(L);
14867
14868 if (CurBECount == SE2.getCouldNotCompute() ||
14869 NewBECount == SE2.getCouldNotCompute()) {
14870 // NB! This situation is legal, but is very suspicious -- whatever pass
14871 // change the loop to make a trip count go from could not compute to
14872 // computable or vice-versa *should have* invalidated SCEV. However, we
14873 // choose not to assert here (for now) since we don't want false
14874 // positives.
14875 continue;
14876 }
14877
14878 if (SE.getTypeSizeInBits(CurBECount->getType()) >
14879 SE.getTypeSizeInBits(NewBECount->getType()))
14880 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
14881 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
14882 SE.getTypeSizeInBits(NewBECount->getType()))
14883 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
14884
14885 const SCEV *Delta = GetDelta(CurBECount, NewBECount);
14886 if (Delta && !Delta->isZero()) {
14887 dbgs() << "Trip Count for " << *L << " Changed!\n";
14888 dbgs() << "Old: " << *CurBECount << "\n";
14889 dbgs() << "New: " << *NewBECount << "\n";
14890 dbgs() << "Delta: " << *Delta << "\n";
14891 std::abort();
14892 }
14893 }
14894
14895 // Collect all valid loops currently in LoopInfo.
14896 SmallPtrSet<Loop *, 32> ValidLoops;
14897 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
14898 while (!Worklist.empty()) {
14899 Loop *L = Worklist.pop_back_val();
14900 if (ValidLoops.insert(L).second)
14901 Worklist.append(L->begin(), L->end());
14902 }
14903 for (const auto &KV : ValueExprMap) {
14904#ifndef NDEBUG
14905 // Check for SCEV expressions referencing invalid/deleted loops.
14906 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14907 assert(ValidLoops.contains(AR->getLoop()) &&
14908 "AddRec references invalid loop");
14909 }
14910#endif
14911
14912 // Check that the value is also part of the reverse map.
14913 auto It = ExprValueMap.find(KV.second);
14914 if (It == ExprValueMap.end() || !It->second.contains(KV.first)) {
14915 dbgs() << "Value " << *KV.first
14916 << " is in ValueExprMap but not in ExprValueMap\n";
14917 std::abort();
14918 }
14919
14920 if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
14921 if (!ReachableBlocks.contains(I->getParent()))
14922 continue;
14923 const SCEV *OldSCEV = SCM.visit(KV.second);
14924 const SCEV *NewSCEV = SE2.getSCEV(I);
14925 const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14926 if (Delta && !Delta->isZero()) {
14927 dbgs() << "SCEV for value " << *I << " changed!\n"
14928 << "Old: " << *OldSCEV << "\n"
14929 << "New: " << *NewSCEV << "\n"
14930 << "Delta: " << *Delta << "\n";
14931 std::abort();
14932 }
14933 }
14934 }
14935
14936 for (const auto &KV : ExprValueMap) {
14937 for (Value *V : KV.second) {
14938 const SCEV *S = ValueExprMap.lookup(V);
14939 if (!S) {
14940 dbgs() << "Value " << *V
14941 << " is in ExprValueMap but not in ValueExprMap\n";
14942 std::abort();
14943 }
14944 if (S != KV.first) {
14945 dbgs() << "Value " << *V << " mapped to " << *S << " rather than "
14946 << *KV.first << "\n";
14947 std::abort();
14948 }
14949 }
14950 }
14951
14952 // Verify integrity of SCEV users.
14953 for (const auto &S : UniqueSCEVs) {
14954 for (SCEVUse Op : S.operands()) {
14955 // We do not store dependencies of constants.
14956 if (isa<SCEVConstant>(Op))
14957 continue;
14958 auto It = SCEVUsers.find(Op);
14959 if (It != SCEVUsers.end() && It->second.count(&S))
14960 continue;
14961 dbgs() << "Use of operand " << *Op << " by user " << S
14962 << " is not being tracked!\n";
14963 std::abort();
14964 }
14965 }
14966
14967 // Verify integrity of ValuesAtScopes users.
14968 for (const auto &ValueAndVec : ValuesAtScopes) {
14969 const SCEV *Value = ValueAndVec.first;
14970 for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
14971 const Loop *L = LoopAndValueAtScope.first;
14972 SCEVUse ValueAtScope = LoopAndValueAtScope.second;
14973 if (!isa<SCEVConstant>(ValueAtScope)) {
14974 auto It = ValuesAtScopesUsers.find(ValueAtScope.getPointer());
14975 if (It != ValuesAtScopesUsers.end() &&
14976 is_contained(It->second, std::make_pair(L, Value)))
14977 continue;
14978 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14979 << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
14980 std::abort();
14981 }
14982 }
14983 }
14984
14985 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
14986 const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
14987 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
14988 const Loop *L = LoopAndValue.first;
14989 const SCEV *Value = LoopAndValue.second;
14991 auto It = ValuesAtScopes.find(Value);
14992 // The recorded value at scope may carry no-wrap flags that are not part
14993 // of the key it is recorded under.
14994 if (It != ValuesAtScopes.end() && any_of(It->second, [&](const auto &LS) {
14995 return LS.first == L && LS.second.getPointer() == ValueAtScope;
14996 }))
14997 continue;
14998 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14999 << *ValueAtScope << " missing in ValuesAtScopes\n";
15000 std::abort();
15001 }
15002 }
15003
15004 // Verify integrity of BECountUsers.
15005 auto VerifyBECountUsers = [&](bool Predicated) {
15006 auto &BECounts =
15007 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
15008 for (const auto &LoopAndBEInfo : BECounts) {
15009 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
15010 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
15011 if (!isa<SCEVConstant>(S)) {
15012 auto UserIt = BECountUsers.find(S);
15013 if (UserIt != BECountUsers.end() &&
15014 UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
15015 continue;
15016 dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
15017 << " missing from BECountUsers\n";
15018 std::abort();
15019 }
15020 }
15021 }
15022 }
15023 };
15024 VerifyBECountUsers(/* Predicated */ false);
15025 VerifyBECountUsers(/* Predicated */ true);
15026
15027 // Verify intergity of loop disposition cache.
15028 for (auto &[S, Values] : LoopDispositions) {
15029 for (auto [Loop, CachedDisposition] : Values) {
15030 const auto RecomputedDisposition = SE2.getLoopDisposition(S, Loop);
15031 if (CachedDisposition != RecomputedDisposition) {
15032 dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
15033 << " is incorrect: cached " << CachedDisposition << ", actual "
15034 << RecomputedDisposition << "\n";
15035 std::abort();
15036 }
15037 }
15038 }
15039
15040 // Verify integrity of the block disposition cache.
15041 for (auto &[S, Values] : BlockDispositions) {
15042 for (auto [BB, CachedDisposition] : Values) {
15043 const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
15044 if (CachedDisposition != RecomputedDisposition) {
15045 dbgs() << "Cached disposition of " << *S << " for block %"
15046 << BB->getName() << " is incorrect: cached " << CachedDisposition
15047 << ", actual " << RecomputedDisposition << "\n";
15048 std::abort();
15049 }
15050 }
15051 }
15052
15053 // Verify FoldCache/FoldCacheUser caches.
15054 for (auto [FoldID, Expr] : FoldCache) {
15055 auto I = FoldCacheUser.find(Expr);
15056 if (I == FoldCacheUser.end()) {
15057 dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
15058 << "!\n";
15059 std::abort();
15060 }
15061 if (!is_contained(I->second, FoldID)) {
15062 dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
15063 std::abort();
15064 }
15065 }
15066 for (auto [Expr, IDs] : FoldCacheUser) {
15067 for (auto &FoldID : IDs) {
15068 const SCEV *S = FoldCache.lookup(FoldID);
15069 if (!S) {
15070 dbgs() << "Missing entry in FoldCache for expression " << *Expr
15071 << "!\n";
15072 std::abort();
15073 }
15074 if (S != Expr) {
15075 dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: " << *S
15076 << " != " << *Expr << "!\n";
15077 std::abort();
15078 }
15079 }
15080 }
15081
15082 // Verify that ConstantMultipleCache computations are correct. We check that
15083 // cached multiples and recomputed multiples are multiples of each other to
15084 // verify correctness. It is possible that a recomputed multiple is different
15085 // from the cached multiple due to strengthened no wrap flags or changes in
15086 // KnownBits computations.
15087 for (auto [S, Multiple] : ConstantMultipleCache) {
15088 APInt RecomputedMultiple = SE2.getConstantMultiple(S);
15089 if ((Multiple != 0 && RecomputedMultiple != 0 &&
15090 Multiple.urem(RecomputedMultiple) != 0 &&
15091 RecomputedMultiple.urem(Multiple) != 0)) {
15092 dbgs() << "Incorrect cached computation in ConstantMultipleCache for "
15093 << *S << " : Computed " << RecomputedMultiple
15094 << " but cache contains " << Multiple << "!\n";
15095 std::abort();
15096 }
15097 }
15098}
15099
15101 Function &F, const PreservedAnalyses &PA,
15102 FunctionAnalysisManager::Invalidator &Inv) {
15103 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
15104 // of its dependencies is invalidated.
15105 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
15106 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
15107 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
15108 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
15109 Inv.invalidate<LoopAnalysis>(F, PA);
15110}
15111
15112AnalysisKey ScalarEvolutionAnalysis::Key;
15113
15116 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
15117 auto &AC = AM.getResult<AssumptionAnalysis>(F);
15118 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
15119 auto &LI = AM.getResult<LoopAnalysis>(F);
15120 return ScalarEvolution(F, TLI, AC, DT, LI);
15121}
15122
15128
15131 // For compatibility with opt's -analyze feature under legacy pass manager
15132 // which was not ported to NPM. This keeps tests using
15133 // update_analyze_test_checks.py working.
15134 OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
15135 << F.getName() << "':\n";
15137 return PreservedAnalyses::all();
15138}
15139
15141 "Scalar Evolution Analysis", false, true)
15147 "Scalar Evolution Analysis", false, true)
15148
15149char ScalarEvolutionWrapperPass::ID = 0;
15150
15152
15154 SE.reset(new ScalarEvolution(
15156 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
15158 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
15159 return false;
15160}
15161
15163
15165 SE->print(OS);
15166}
15167
15169 if (!VerifySCEV)
15170 return;
15171
15172 SE->verify();
15173}
15174
15182
15184 const SCEV *RHS) {
15185 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
15186}
15187
15188const SCEVPredicate *
15190 const SCEV *LHS, const SCEV *RHS) {
15192 assert(LHS->getType() == RHS->getType() &&
15193 "Type mismatch between LHS and RHS");
15194 // Unique this node based on the arguments
15195 ID.AddInteger(SCEVPredicate::P_Compare);
15196 ID.AddInteger(Pred);
15197 ID.AddPointer(LHS);
15198 ID.AddPointer(RHS);
15200 if (const auto *S = UniquePreds.lookup(ID, Token))
15201 return S;
15202 SCEVComparePredicate *Eq = new (SCEVAllocator)
15203 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
15204 UniquePreds.insert(Eq, Token);
15205 return Eq;
15206}
15207
15209 const SCEVAddRecExpr *AR,
15212 // Unique this node based on the arguments
15214 ID.AddPointer(AR);
15215 ID.AddInteger(AddedFlags);
15217 if (const auto *S = UniquePreds.lookup(ID, Token))
15218 return S;
15219 auto *OF = new (SCEVAllocator)
15220 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
15221 UniquePreds.insert(OF, Token);
15222 return OF;
15223}
15224
15225namespace {
15226
15227class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
15228public:
15229
15230 /// Rewrites \p S in the context of a loop L and the SCEV predication
15231 /// infrastructure.
15232 ///
15233 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
15234 /// equivalences present in \p Pred.
15235 ///
15236 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
15237 /// \p NewPreds such that the result will be an AddRecExpr.
15238 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
15240 const SCEVPredicate *Pred) {
15241 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
15242 return Rewriter.visit(S);
15243 }
15244
15245 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
15246 if (Pred) {
15247 if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
15248 for (const auto *Pred : U->getPredicates())
15249 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
15250 if (IPred->getLHS() == Expr &&
15251 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15252 return IPred->getRHS();
15253 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
15254 if (IPred->getLHS() == Expr &&
15255 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15256 return IPred->getRHS();
15257 }
15258 }
15259 return convertToAddRecWithPreds(Expr);
15260 }
15261
15262 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
15263 const SCEV *Operand = visit(Expr->getOperand());
15264 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15265 if (AR && AR->getLoop() == L && AR->isAffine()) {
15266 // This couldn't be folded because the operand didn't have the nuw
15267 // flag. Add the nusw flag as an assumption that we could make.
15268 const SCEV *Step = AR->getStepRecurrence(SE);
15269 Type *Ty = Expr->getType();
15270 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
15271 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
15272 SE.getSignExtendExpr(Step, Ty), L,
15273 AR->getNoWrapFlags());
15274 }
15275 return SE.getZeroExtendExpr(Operand, Expr->getType());
15276 }
15277
15278 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
15279 const SCEV *Operand = visit(Expr->getOperand());
15280 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15281 if (AR && AR->getLoop() == L && AR->isAffine()) {
15282 // This couldn't be folded because the operand didn't have the nsw
15283 // flag. Add the nssw flag as an assumption that we could make.
15284 const SCEV *Step = AR->getStepRecurrence(SE);
15285 Type *Ty = Expr->getType();
15286 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
15287 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
15288 SE.getSignExtendExpr(Step, Ty), L,
15289 AR->getNoWrapFlags());
15290 }
15291 return SE.getSignExtendExpr(Operand, Expr->getType());
15292 }
15293
15294private:
15295 explicit SCEVPredicateRewriter(
15296 const Loop *L, ScalarEvolution &SE,
15297 SmallVectorImpl<const SCEVPredicate *> *NewPreds,
15298 const SCEVPredicate *Pred)
15299 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
15300
15301 bool addOverflowAssumption(const SCEVPredicate *P) {
15302 if (!NewPreds) {
15303 // Check if we've already made this assumption.
15304 return Pred && Pred->implies(P, SE);
15305 }
15306 NewPreds->push_back(P);
15307 return true;
15308 }
15309
15310 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
15312 auto *A = SE.getWrapPredicate(AR, AddedFlags);
15313 return addOverflowAssumption(A);
15314 }
15315
15316 // If \p Expr represents a PHINode, we try to see if it can be represented
15317 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
15318 // to add this predicate as a runtime overflow check, we return the AddRec.
15319 // If \p Expr does not meet these conditions (is not a PHI node, or we
15320 // couldn't create an AddRec for it, or couldn't add the predicate), we just
15321 // return \p Expr.
15322 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
15323 if (!isa<PHINode>(Expr->getValue()))
15324 return Expr;
15325 std::optional<
15326 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
15327 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
15328 if (!PredicatedRewrite)
15329 return Expr;
15330 for (const auto *P : PredicatedRewrite->second){
15331 // Wrap predicates from outer loops are not supported.
15332 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
15333 if (L != WP->getExpr()->getLoop())
15334 return Expr;
15335 }
15336 if (!addOverflowAssumption(P))
15337 return Expr;
15338 }
15339 return PredicatedRewrite->first;
15340 }
15341
15342 SmallVectorImpl<const SCEVPredicate *> *NewPreds;
15343 const SCEVPredicate *Pred;
15344 const Loop *L;
15345};
15346
15347} // end anonymous namespace
15348
15349const SCEV *
15351 const SCEVPredicate &Preds) {
15352 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
15353}
15354
15356 const SCEV *S, const Loop *L,
15359 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
15360 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
15361
15362 if (!AddRec)
15363 return nullptr;
15364
15365 // Check if any of the transformed predicates is known to be false. In that
15366 // case, it doesn't make sense to convert to a predicated AddRec, as the
15367 // versioned loop will never execute.
15368 for (const SCEVPredicate *Pred : TransformPreds) {
15369 auto *WrapPred = dyn_cast<SCEVWrapPredicate>(Pred);
15370 if (!WrapPred || WrapPred->getFlags() != SCEVWrapPredicate::IncrementNSSW)
15371 continue;
15372
15373 const SCEVAddRecExpr *AddRecToCheck = WrapPred->getExpr();
15374 const SCEV *ExitCount = getBackedgeTakenCount(AddRecToCheck->getLoop());
15375 if (isa<SCEVCouldNotCompute>(ExitCount))
15376 continue;
15377
15378 const SCEV *Step = AddRecToCheck->getStepRecurrence(*this);
15379 if (!Step->isOne())
15380 continue;
15381
15382 ExitCount = getTruncateOrSignExtend(ExitCount, Step->getType());
15383 const SCEV *Add = getAddExpr(AddRecToCheck->getStart(), ExitCount);
15384 if (isKnownPredicate(CmpInst::ICMP_SLT, Add, AddRecToCheck->getStart()))
15385 return nullptr;
15386 }
15387
15388 // Since the transformation was successful, we can now transfer the SCEV
15389 // predicates.
15390 Preds.append(TransformPreds.begin(), TransformPreds.end());
15391
15392 return AddRec;
15393}
15394
15395/// SCEV predicates
15399
15401 const ICmpInst::Predicate Pred,
15402 const SCEV *LHS, const SCEV *RHS)
15403 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
15404 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
15405 assert(LHS != RHS && "LHS and RHS are the same SCEV");
15406}
15407
15409 ScalarEvolution &SE) const {
15410 const auto *Op = dyn_cast<SCEVComparePredicate>(N);
15411
15412 if (!Op)
15413 return false;
15414
15415 if (Pred != ICmpInst::ICMP_EQ)
15416 return false;
15417
15418 return Op->LHS == LHS && Op->RHS == RHS;
15419}
15420
15421bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
15422
15424 if (Pred == ICmpInst::ICMP_EQ)
15425 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
15426 else
15427 OS.indent(Depth) << "Compare predicate: " << *LHS << " " << Pred << ") "
15428 << *RHS << "\n";
15429
15430}
15431
15433 const SCEVAddRecExpr *AR,
15434 IncrementWrapFlags Flags)
15435 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
15436
15437const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
15438
15440 ScalarEvolution &SE) const {
15441 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
15442 if (!Op || setFlags(Flags, Op->Flags) != Flags)
15443 return false;
15444
15445 if (Op->AR == AR)
15446 return true;
15447
15448 if (Flags != SCEVWrapPredicate::IncrementNSSW &&
15450 return false;
15451
15452 const SCEV *Start = AR->getStart();
15453 const SCEV *OpStart = Op->AR->getStart();
15454 if (Start->getType()->isPointerTy() != OpStart->getType()->isPointerTy())
15455 return false;
15456
15457 // Reject pointers to different address spaces.
15458 if (Start->getType()->isPointerTy() && Start->getType() != OpStart->getType())
15459 return false;
15460
15461 // NUSW/NSSW on a wider-type AddRec does not imply the same on a
15462 // narrower-type AddRec.
15463 if (SE.getTypeSizeInBits(AR->getType()) >
15464 SE.getTypeSizeInBits(Op->AR->getType()))
15465 return false;
15466
15467 const SCEV *Step = AR->getStepRecurrence(SE);
15468 const SCEV *OpStep = Op->AR->getStepRecurrence(SE);
15469 if (!SE.isKnownPositive(Step) || !SE.isKnownPositive(OpStep))
15470 return false;
15471
15472 // If both steps are positive, this implies N, if N's start and step are
15473 // ULE/SLE (for NSUW/NSSW) than this'.
15474 Type *WiderTy = SE.getWiderType(Step->getType(), OpStep->getType());
15475 Step = SE.getNoopOrZeroExtend(Step, WiderTy);
15476 OpStep = SE.getNoopOrZeroExtend(OpStep, WiderTy);
15477
15478 bool IsNUW = Flags == SCEVWrapPredicate::IncrementNUSW;
15479 OpStart = IsNUW ? SE.getNoopOrZeroExtend(OpStart, WiderTy)
15480 : SE.getNoopOrSignExtend(OpStart, WiderTy);
15481 Start = IsNUW ? SE.getNoopOrZeroExtend(Start, WiderTy)
15482 : SE.getNoopOrSignExtend(Start, WiderTy);
15484 return SE.isKnownPredicate(Pred, OpStep, Step) &&
15485 SE.isKnownPredicate(Pred, OpStart, Start);
15486}
15487
15489 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
15490 IncrementWrapFlags IFlags = Flags;
15491
15492 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
15493 IFlags = clearFlags(IFlags, IncrementNSSW);
15494
15495 return IFlags == IncrementAnyWrap;
15496}
15497
15498void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
15499 OS.indent(Depth) << *getExpr() << " Added Flags: ";
15501 OS << "<nusw>";
15503 OS << "<nssw>";
15504 OS << "\n";
15505}
15506
15509 ScalarEvolution &SE) {
15510 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
15511 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
15512
15513 // We can safely transfer the NSW flag as NSSW.
15514 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
15515 ImpliedFlags = IncrementNSSW;
15516
15517 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
15518 // If the increment is positive, the SCEV NUW flag will also imply the
15519 // WrapPredicate NUSW flag.
15520 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
15521 if (Step->getValue()->getValue().isNonNegative())
15522 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
15523 }
15524
15525 return ImpliedFlags;
15526}
15527
15528/// Union predicates don't get cached so create a dummy set ID for it.
15530 ScalarEvolution &SE)
15532 for (const auto *P : Preds)
15533 add(P, SE);
15534}
15535
15537 return all_of(Preds,
15538 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
15539}
15540
15542 ScalarEvolution &SE) const {
15543 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
15544 return all_of(Set->Preds, [this, &SE](const SCEVPredicate *I) {
15545 return this->implies(I, SE);
15546 });
15547
15548 if (any_of(Preds,
15549 [N, &SE](const SCEVPredicate *I) { return I->implies(N, SE); }))
15550 return true;
15551
15552 // A wrap predicate may be implied by a wrap predicate in Preds after applying
15553 // equal predicates.
15554 const auto *NWrap = dyn_cast<SCEVWrapPredicate>(N);
15555 if (!NWrap)
15556 return false;
15557 const Loop *L = NWrap->getExpr()->getLoop();
15558 return any_of(Preds, [&](const SCEVPredicate *I) {
15559 const auto *IWrap = dyn_cast<SCEVWrapPredicate>(I);
15560 if (!IWrap)
15561 return false;
15562 const auto *RewrittenAR = dyn_cast<SCEVAddRecExpr>(
15563 SE.rewriteUsingPredicate(IWrap->getExpr(), L, *this));
15564 return RewrittenAR &&
15565 SE.getWrapPredicate(RewrittenAR, IWrap->getFlags())->implies(N, SE);
15566 });
15567}
15568
15570 for (const auto *Pred : Preds)
15571 Pred->print(OS, Depth);
15572}
15573
15574void SCEVUnionPredicate::add(const SCEVPredicate *N, ScalarEvolution &SE) {
15575 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
15576 for (const auto *Pred : Set->Preds)
15577 add(Pred, SE);
15578 return;
15579 }
15580
15581 // Implication checks are quadratic in the number of predicates. Stop doing
15582 // them if there are many predicates, as they should be too expensive to use
15583 // anyway at that point.
15584 bool CheckImplies = Preds.size() < 16;
15585
15586 // Only add predicate if it is not already implied by this union predicate.
15587 if (CheckImplies && implies(N, SE))
15588 return;
15589
15590 // Build a new vector containing the current predicates, except the ones that
15591 // are implied by the new predicate N.
15593 for (auto *P : Preds) {
15594 if (CheckImplies && N->implies(P, SE))
15595 continue;
15596 PrunedPreds.push_back(P);
15597 }
15598 Preds = std::move(PrunedPreds);
15599 Preds.push_back(N);
15600}
15601
15603 Loop &L)
15604 : SE(SE), L(L) {
15606 Preds = std::make_unique<SCEVUnionPredicate>(Empty, SE);
15607}
15608
15610 for (const SCEV *Op : Ops)
15611 // We do not expect that forgetting cached data for SCEVConstants will ever
15612 // open any prospects for sharpening or introduce any correctness issues,
15613 // so we don't bother storing their dependencies.
15614 if (!isa<SCEVConstant>(Op))
15615 SCEVUsers[Op].insert(User);
15616}
15617
15619 const SCEV *Expr = SE.getSCEV(V);
15620 return getPredicatedSCEV(Expr);
15621}
15622
15624 RewriteEntry &Entry = RewriteMap[Expr];
15625
15626 // If we already have an entry and the version matches, return it.
15627 if (Entry.second && Generation == Entry.first)
15628 return Entry.second;
15629
15630 // We found an entry but it's stale. Rewrite the stale entry
15631 // according to the current predicate.
15632 if (Entry.second)
15633 Expr = Entry.second;
15634
15635 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
15636 Entry = {Generation, NewSCEV};
15637
15638 return NewSCEV;
15639}
15640
15642 if (!BackedgeCount) {
15644 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
15645 for (const auto *P : Preds)
15646 addPredicate(*P);
15647 }
15648 return BackedgeCount;
15649}
15650
15652 if (!SymbolicMaxBackedgeCount) {
15654 SymbolicMaxBackedgeCount =
15655 SE.getPredicatedSymbolicMaxBackedgeTakenCount(&L, Preds);
15656 for (const auto *P : Preds)
15657 addPredicate(*P);
15658 }
15659 return SymbolicMaxBackedgeCount;
15660}
15661
15663 if (!SmallConstantMaxTripCount) {
15665 SmallConstantMaxTripCount = SE.getSmallConstantMaxTripCount(&L, &Preds);
15666 for (const auto *P : Preds)
15667 addPredicate(*P);
15668 }
15669 return *SmallConstantMaxTripCount;
15670}
15671
15673 if (Preds->implies(&Pred, SE))
15674 return;
15675
15676 SmallVector<const SCEVPredicate *, 4> NewPreds(Preds->getPredicates());
15677 NewPreds.push_back(&Pred);
15678 Preds = std::make_unique<SCEVUnionPredicate>(NewPreds, SE);
15679 updateGeneration();
15680}
15681
15684 for (const SCEVPredicate *P : Preds)
15685 addPredicate(*P);
15686}
15687
15689 return *Preds;
15690}
15691
15692void PredicatedScalarEvolution::updateGeneration() {
15693 // If the generation number wrapped recompute everything.
15694 if (++Generation == 0) {
15695 for (auto &II : RewriteMap) {
15696 const SCEV *Rewritten = II.second.second;
15697 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
15698 }
15699 }
15700}
15701
15704 const auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V));
15705 if (!AR)
15706 return false;
15707
15709 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
15710
15712}
15713
15716 const SCEV *Expr = this->getSCEV(V);
15718 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
15719
15720 if (!New)
15721 return nullptr;
15722
15723 if (ExtraPreds) {
15724 ExtraPreds->append(NewPreds);
15725 return New;
15726 }
15727
15728 addPredicates(NewPreds);
15729
15730 RewriteMap[SE.getSCEV(V)] = {Generation, New};
15731 return New;
15732}
15733
15736 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
15737 Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates(),
15738 SE)),
15739 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {}
15740
15742 // For each block.
15743 for (auto *BB : L.getBlocks())
15744 for (auto &I : *BB) {
15745 if (!SE.isSCEVable(I.getType()))
15746 continue;
15747
15748 auto *Expr = SE.getSCEV(&I);
15749 auto II = RewriteMap.find(Expr);
15750
15751 if (II == RewriteMap.end())
15752 continue;
15753
15754 // Don't print things that are not interesting.
15755 if (II->second.second == Expr)
15756 continue;
15757
15758 OS.indent(Depth) << "[PSE]" << I << ":\n";
15759 OS.indent(Depth + 2) << *Expr << "\n";
15760 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
15761 }
15762}
15763
15766 BasicBlock *Header = L->getHeader();
15767 BasicBlock *Pred = L->getLoopPredecessor();
15768 LoopGuards Guards(SE);
15769 if (!Pred)
15770 return Guards;
15772 collectFromBlock(SE, Guards, Header, Pred, VisitedBlocks);
15773 return Guards;
15774}
15775
15776void ScalarEvolution::LoopGuards::collectFromPHI(
15780 unsigned Depth) {
15781 if (!SE.isSCEVable(Phi.getType()))
15782 return;
15783
15784 using MinMaxPattern = std::pair<const SCEVConstant *, SCEVTypes>;
15785 auto GetMinMaxConst = [&](unsigned IncomingIdx) -> MinMaxPattern {
15786 const BasicBlock *InBlock = Phi.getIncomingBlock(IncomingIdx);
15787 if (!VisitedBlocks.insert(InBlock).second)
15788 return {nullptr, scCouldNotCompute};
15789
15790 // Avoid analyzing unreachable blocks so that we don't get trapped
15791 // traversing cycles with ill-formed dominance or infinite cycles
15792 if (!SE.DT.isReachableFromEntry(InBlock))
15793 return {nullptr, scCouldNotCompute};
15794
15795 auto [G, Inserted] = IncomingGuards.try_emplace(InBlock, LoopGuards(SE));
15796 if (Inserted)
15797 collectFromBlock(SE, G->second, Phi.getParent(), InBlock, VisitedBlocks,
15798 Depth + 1);
15799 auto &RewriteMap = G->second.RewriteMap;
15800 if (RewriteMap.empty())
15801 return {nullptr, scCouldNotCompute};
15802 auto S = RewriteMap.find(SE.getSCEV(Phi.getIncomingValue(IncomingIdx)));
15803 if (S == RewriteMap.end())
15804 return {nullptr, scCouldNotCompute};
15805 auto *SM = dyn_cast_if_present<SCEVMinMaxExpr>(S->second);
15806 if (!SM)
15807 return {nullptr, scCouldNotCompute};
15808 if (const SCEVConstant *C0 = dyn_cast<SCEVConstant>(SM->getOperand(0)))
15809 return {C0, SM->getSCEVType()};
15810 return {nullptr, scCouldNotCompute};
15811 };
15812 auto MergeMinMaxConst = [](MinMaxPattern P1,
15813 MinMaxPattern P2) -> MinMaxPattern {
15814 auto [C1, T1] = P1;
15815 auto [C2, T2] = P2;
15816 if (!C1 || !C2 || T1 != T2)
15817 return {nullptr, scCouldNotCompute};
15818 switch (T1) {
15819 case scUMaxExpr:
15820 return {C1->getAPInt().ult(C2->getAPInt()) ? C1 : C2, T1};
15821 case scSMaxExpr:
15822 return {C1->getAPInt().slt(C2->getAPInt()) ? C1 : C2, T1};
15823 case scUMinExpr:
15824 return {C1->getAPInt().ugt(C2->getAPInt()) ? C1 : C2, T1};
15825 case scSMinExpr:
15826 return {C1->getAPInt().sgt(C2->getAPInt()) ? C1 : C2, T1};
15827 default:
15828 llvm_unreachable("Trying to merge non-MinMaxExpr SCEVs.");
15829 }
15830 };
15831 auto P = GetMinMaxConst(0);
15832 for (unsigned int In = 1; In < Phi.getNumIncomingValues(); In++) {
15833 if (!P.first)
15834 break;
15835 P = MergeMinMaxConst(P, GetMinMaxConst(In));
15836 }
15837 if (P.first) {
15838 const SCEV *LHS = SE.getSCEV(const_cast<PHINode *>(&Phi));
15839 SmallVector<SCEVUse, 2> Ops({P.first, LHS});
15840 const SCEV *RHS = SE.getMinMaxExpr(P.second, Ops);
15841 Guards.RewriteMap.insert({LHS, RHS});
15842 }
15843}
15844
15845// Return a new SCEV that modifies \p Expr to the closest number divides by
15846// \p Divisor and less or equal than Expr. For now, only handle constant
15847// Expr.
15849 const APInt &DivisorVal,
15850 ScalarEvolution &SE) {
15851 const APInt *ExprVal;
15852 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15853 DivisorVal.isNonPositive())
15854 return Expr;
15855 APInt Rem = ExprVal->urem(DivisorVal);
15856 // return the SCEV: Expr - Expr % Divisor
15857 return SE.getConstant(*ExprVal - Rem);
15858}
15859
15860// Return a new SCEV that modifies \p Expr to the closest number divides by
15861// \p Divisor and greater or equal than Expr. For now, only handle constant
15862// Expr.
15863static const SCEV *getNextSCEVDivisibleByDivisor(const SCEV *Expr,
15864 const APInt &DivisorVal,
15865 ScalarEvolution &SE) {
15866 const APInt *ExprVal;
15867 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15868 DivisorVal.isNonPositive())
15869 return Expr;
15870 APInt Rem = ExprVal->urem(DivisorVal);
15871 if (Rem.isZero())
15872 return Expr;
15873 // return the SCEV: Expr + Divisor - Expr % Divisor
15874 return SE.getConstant(*ExprVal + DivisorVal - Rem);
15875}
15876
15878 ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS,
15881 // If we have LHS == 0, check if LHS is computing a property of some unknown
15882 // SCEV %v which we can rewrite %v to express explicitly.
15884 return false;
15885 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
15886 // explicitly express that.
15887 const SCEVUnknown *URemLHS = nullptr;
15888 const SCEV *URemRHS = nullptr;
15889 if (!match(LHS, m_scev_URem(m_SCEVUnknown(URemLHS), m_SCEV(URemRHS), SE)))
15890 return false;
15891
15892 const SCEV *Multiple =
15893 SE.getMulExpr(SE.getUDivExpr(URemLHS, URemRHS), URemRHS);
15894 DivInfo[URemLHS] = Multiple;
15895 if (auto *C = dyn_cast<SCEVConstant>(URemRHS))
15896 Multiples[URemLHS] = C->getAPInt();
15897 return true;
15898}
15899
15900// Check if the condition is a divisibility guard (A % B == 0).
15901static bool isDivisibilityGuard(const SCEV *LHS, const SCEV *RHS,
15902 ScalarEvolution &SE) {
15903 const SCEV *X, *Y;
15904 return match(LHS, m_scev_URem(m_SCEV(X), m_SCEV(Y), SE)) && RHS->isZero();
15905}
15906
15907// Apply divisibility by \p Divisor on MinMaxExpr with constant values,
15908// recursively. This is done by aligning up/down the constant value to the
15909// Divisor.
15910static const SCEV *applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr,
15911 APInt Divisor,
15912 ScalarEvolution &SE) {
15913 // Return true if \p Expr is a MinMax SCEV expression with a non-negative
15914 // constant operand. If so, return in \p SCTy the SCEV type and in \p RHS
15915 // the non-constant operand and in \p LHS the constant operand.
15916 auto IsMinMaxSCEVWithNonNegativeConstant =
15917 [&](const SCEV *Expr, SCEVTypes &SCTy, const SCEV *&LHS,
15918 const SCEV *&RHS) {
15919 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr)) {
15920 if (MinMax->getNumOperands() != 2)
15921 return false;
15922 if (auto *C = dyn_cast<SCEVConstant>(MinMax->getOperand(0))) {
15923 if (C->getAPInt().isNegative())
15924 return false;
15925 SCTy = MinMax->getSCEVType();
15926 LHS = MinMax->getOperand(0);
15927 RHS = MinMax->getOperand(1);
15928 return true;
15929 }
15930 }
15931 return false;
15932 };
15933
15934 const SCEV *MinMaxLHS = nullptr, *MinMaxRHS = nullptr;
15935 SCEVTypes SCTy;
15936 if (!IsMinMaxSCEVWithNonNegativeConstant(MinMaxExpr, SCTy, MinMaxLHS,
15937 MinMaxRHS))
15938 return MinMaxExpr;
15939 auto IsMin = isa<SCEVSMinExpr>(MinMaxExpr) || isa<SCEVUMinExpr>(MinMaxExpr);
15940 assert(SE.isKnownNonNegative(MinMaxLHS) && "Expected non-negative operand!");
15941 auto *DivisibleExpr =
15942 IsMin ? getPreviousSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE)
15943 : getNextSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE);
15945 applyDivisibilityOnMinMaxExpr(MinMaxRHS, Divisor, SE), DivisibleExpr};
15946 return SE.getMinMaxExpr(SCTy, Ops);
15947}
15948
15949void ScalarEvolution::LoopGuards::collectFromBlock(
15950 ScalarEvolution &SE, ScalarEvolution::LoopGuards &Guards,
15951 const BasicBlock *Block, const BasicBlock *Pred,
15952 SmallPtrSetImpl<const BasicBlock *> &VisitedBlocks, unsigned Depth) {
15953
15955
15956 SmallVector<SCEVUse> ExprsToRewrite;
15957 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
15958 const SCEV *RHS,
15959 DenseMap<const SCEV *, const SCEV *> &RewriteMap,
15960 const LoopGuards &DivGuards) {
15961 // WARNING: It is generally unsound to apply any wrap flags to the proposed
15962 // replacement SCEV which isn't directly implied by the structure of that
15963 // SCEV. In particular, using contextual facts to imply flags is *NOT*
15964 // legal. See the scoping rules for flags in the header to understand why.
15965
15966 // Puts rewrite rule \p From -> \p To into the rewrite map. Also if \p From
15967 // and \p FromRewritten are the same (i.e. there has been no rewrite
15968 // registered for \p From), then puts this value in the list of rewritten
15969 // expressions.
15970 auto AddRewrite = [&](const SCEV *From, const SCEV *FromRewritten,
15971 const SCEV *To) {
15972 if (From == FromRewritten)
15973 ExprsToRewrite.push_back(From);
15974 RewriteMap[From] = To;
15975 };
15976
15977 // Checks whether \p S has already been rewritten. In that case returns the
15978 // existing rewrite because we want to chain further rewrites onto the
15979 // already rewritten value. Otherwise returns \p S.
15980 auto GetMaybeRewritten = [&](const SCEV *S) {
15981 return RewriteMap.lookup_or(S, S);
15982 };
15983
15984 // Check for a condition of the form (-C1 + X < C2). InstCombine will
15985 // create this form when combining two checks of the form (X u< C2 + C1) and
15986 // (X >=u C1).
15987 auto MatchRangeCheckIdiom = [&](ICmpInst::Predicate Pred,
15988 const SCEV *MatchLHS,
15989 const SCEV *MatchRHS) {
15990 const SCEVConstant *C1;
15991 const SCEVUnknown *LHSUnknown;
15992 auto *C2 = dyn_cast<SCEVConstant>(MatchRHS);
15993 if (!match(MatchLHS,
15994 m_scev_Add(m_SCEVConstant(C1), m_SCEVUnknown(LHSUnknown))) ||
15995 !C2)
15996 return false;
15997
15998 auto ExactRegion =
15999 ConstantRange::makeExactICmpRegion(Pred, C2->getAPInt())
16000 .sub(C1->getAPInt());
16001
16002 // Tighten the raw range with what we already know about LHSUnknown
16003 // from prior guards recorded in RewriteMap, or from SCEV's own range
16004 // analysis.
16005 const SCEV *RewrittenLHS = GetMaybeRewritten(LHSUnknown);
16006 ExactRegion = ExactRegion.intersectWith(SE.getUnsignedRange(RewrittenLHS),
16008
16009 // Bail if the guard is inconsistent with prior facts, or if the range
16010 // is still not a monotonic non-wrapping interval after tightening.
16011 if (ExactRegion.isEmptySet() || ExactRegion.isWrappedSet() ||
16012 ExactRegion.isFullSet())
16013 return false;
16014
16015 const SCEV *RegionMin = SE.getConstant(ExactRegion.getUnsignedMin());
16016 const SCEV *RegionMax = SE.getConstant(ExactRegion.getUnsignedMax());
16017 const SCEV *ClampedLHS =
16018 SE.getUMaxExpr(RegionMin, SE.getUMinExpr(RewrittenLHS, RegionMax));
16019 AddRewrite(LHSUnknown, RewrittenLHS, ClampedLHS);
16020 return true;
16021 };
16022 if (MatchRangeCheckIdiom(Predicate, LHS, RHS))
16023 return;
16024
16025 // Do not apply information for constants or if RHS contains an AddRec.
16027 return;
16028
16029 // If RHS is SCEVUnknown, make sure the information is applied to it.
16031 std::swap(LHS, RHS);
16033 }
16034
16035 const SCEV *RewrittenLHS = GetMaybeRewritten(LHS);
16036 // Apply divisibility information when computing the constant multiple.
16037 const APInt &DividesBy =
16038 SE.getConstantMultiple(DivGuards.rewrite(RewrittenLHS));
16039
16040 // Collect rewrites for LHS and its transitive operands based on the
16041 // condition.
16042 // For min/max expressions, also apply the guard to its operands:
16043 // 'min(a, b) >= c' -> '(a >= c) and (b >= c)',
16044 // 'min(a, b) > c' -> '(a > c) and (b > c)',
16045 // 'max(a, b) <= c' -> '(a <= c) and (b <= c)',
16046 // 'max(a, b) < c' -> '(a < c) and (b < c)'.
16047
16048 // We cannot express strict predicates in SCEV, so instead we replace them
16049 // with non-strict ones against plus or minus one of RHS depending on the
16050 // predicate.
16051 const SCEV *One = SE.getOne(RHS->getType());
16052 switch (Predicate) {
16053 case CmpInst::ICMP_ULT:
16054 if (RHS->getType()->isPointerTy())
16055 return;
16056 RHS = SE.getUMaxExpr(RHS, One);
16057 [[fallthrough]];
16058 case CmpInst::ICMP_SLT: {
16059 RHS = SE.getMinusSCEV(RHS, One);
16060 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16061 break;
16062 }
16063 case CmpInst::ICMP_UGT:
16064 case CmpInst::ICMP_SGT:
16065 RHS = SE.getAddExpr(RHS, One);
16066 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16067 break;
16068 case CmpInst::ICMP_ULE:
16069 case CmpInst::ICMP_SLE:
16070 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16071 break;
16072 case CmpInst::ICMP_UGE:
16073 case CmpInst::ICMP_SGE:
16074 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16075 break;
16076 default:
16077 break;
16078 }
16079
16080 SmallVector<SCEVUse, 16> Worklist(1, LHS);
16081 SmallPtrSet<const SCEV *, 16> Visited;
16082
16083 auto EnqueueOperands = [&Worklist](const SCEVNAryExpr *S) {
16084 append_range(Worklist, S->operands());
16085 };
16086
16087 while (!Worklist.empty()) {
16088 const SCEV *From = Worklist.pop_back_val();
16089 if (isa<SCEVConstant>(From))
16090 continue;
16091 if (!Visited.insert(From).second)
16092 continue;
16093 const SCEV *FromRewritten = GetMaybeRewritten(From);
16094 const SCEV *To = nullptr;
16095
16096 switch (Predicate) {
16097 case CmpInst::ICMP_ULT:
16098 case CmpInst::ICMP_ULE:
16099 To = SE.getUMinExpr(FromRewritten, RHS);
16100 if (auto *UMax = dyn_cast<SCEVUMaxExpr>(FromRewritten))
16101 EnqueueOperands(UMax);
16102 break;
16103 case CmpInst::ICMP_SLT:
16104 case CmpInst::ICMP_SLE:
16105 To = SE.getSMinExpr(FromRewritten, RHS);
16106 if (auto *SMax = dyn_cast<SCEVSMaxExpr>(FromRewritten))
16107 EnqueueOperands(SMax);
16108 break;
16109 case CmpInst::ICMP_UGT:
16110 case CmpInst::ICMP_UGE:
16111 To = SE.getUMaxExpr(FromRewritten, RHS);
16112 if (auto *UMin = dyn_cast<SCEVUMinExpr>(FromRewritten))
16113 EnqueueOperands(UMin);
16114 break;
16115 case CmpInst::ICMP_SGT:
16116 case CmpInst::ICMP_SGE:
16117 To = SE.getSMaxExpr(FromRewritten, RHS);
16118 if (auto *SMin = dyn_cast<SCEVSMinExpr>(FromRewritten))
16119 EnqueueOperands(SMin);
16120 break;
16121 case CmpInst::ICMP_EQ:
16123 To = RHS;
16124 break;
16125 case CmpInst::ICMP_NE:
16126 if (match(RHS, m_scev_Zero())) {
16127 const SCEV *OneAlignedUp =
16128 getNextSCEVDivisibleByDivisor(One, DividesBy, SE);
16129 To = SE.getUMaxExpr(FromRewritten, OneAlignedUp);
16130 } else {
16131 // LHS != RHS can be rewritten as (LHS - RHS) = UMax(1, LHS - RHS),
16132 // but creating the subtraction eagerly is expensive. Track the
16133 // inequalities in a separate map, and materialize the rewrite lazily
16134 // when encountering a suitable subtraction while re-writing.
16135 if (LHS->getType()->isPointerTy()) {
16136 LHS = SE.getPtrToAddrExpr(LHS);
16137 RHS = SE.getPtrToAddrExpr(RHS);
16139 break;
16140 }
16141 const SCEVConstant *C;
16142 const SCEV *A, *B;
16145 RHS = A;
16146 LHS = B;
16147 }
16148 if (LHS > RHS)
16149 std::swap(LHS, RHS);
16150 Guards.NotEqual.insert({LHS, RHS});
16151 continue;
16152 }
16153 break;
16154 default:
16155 break;
16156 }
16157
16158 if (To)
16159 AddRewrite(From, FromRewritten, To);
16160 }
16161 };
16162
16164 // First, collect information from assumptions dominating the loop.
16165 for (auto &AssumeVH : SE.AC.assumptions()) {
16166 if (!AssumeVH)
16167 continue;
16168 auto *AssumeI = cast<CallInst>(AssumeVH);
16169 if (!SE.DT.dominates(AssumeI, Block))
16170 continue;
16171 Terms.emplace_back(AssumeI->getOperand(0), true);
16172 }
16173
16174 // Second, collect information from llvm.experimental.guards dominating the loop.
16175 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
16176 SE.F.getParent(), Intrinsic::experimental_guard);
16177 if (GuardDecl)
16178 for (const auto *GU : GuardDecl->users())
16179 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
16180 if (Guard->getFunction() == Block->getParent() &&
16181 SE.DT.dominates(Guard, Block))
16182 Terms.emplace_back(Guard->getArgOperand(0), true);
16183
16184 // Third, collect conditions from dominating branches. Starting at the loop
16185 // predecessor, climb up the predecessor chain, as long as there are
16186 // predecessors that can be found that have unique successors leading to the
16187 // original header.
16188 // TODO: share this logic with isLoopEntryGuardedByCond.
16189 unsigned NumCollectedConditions = 0;
16191 std::pair<const BasicBlock *, const BasicBlock *> Pair(Pred, Block);
16192 for (; Pair.first;
16193 Pair = SE.getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
16194 VisitedBlocks.insert(Pair.second);
16195 const CondBrInst *LoopEntryPredicate =
16196 dyn_cast<CondBrInst>(Pair.first->getTerminator());
16197 if (!LoopEntryPredicate)
16198 continue;
16199
16200 Terms.emplace_back(LoopEntryPredicate->getCondition(),
16201 LoopEntryPredicate->getSuccessor(0) == Pair.second);
16202 NumCollectedConditions++;
16203
16204 // If we are recursively collecting guards stop after 2
16205 // conditions to limit compile-time impact for now.
16206 if (Depth > 0 && NumCollectedConditions == 2)
16207 break;
16208 }
16209 // Finally, if we stopped climbing the predecessor chain because
16210 // there wasn't a unique one to continue, try to collect conditions
16211 // for PHINodes by recursively following all of their incoming
16212 // blocks and try to merge the found conditions to build a new one
16213 // for the Phi.
16214 if (Pair.second->hasNPredecessorsOrMore(2) &&
16216 SmallDenseMap<const BasicBlock *, LoopGuards> IncomingGuards;
16217 for (auto &Phi : Pair.second->phis())
16218 collectFromPHI(SE, Guards, Phi, VisitedBlocks, IncomingGuards, Depth);
16219 }
16220
16221 // Now apply the information from the collected conditions to
16222 // Guards.RewriteMap. Conditions are processed in reverse order, so the
16223 // earliest conditions is processed first, except guards with divisibility
16224 // information, which are moved to the back. This ensures the SCEVs with the
16225 // shortest dependency chains are constructed first.
16227 GuardsToProcess;
16228 for (auto [Term, EnterIfTrue] : reverse(Terms)) {
16229 SmallVector<Value *, 8> Worklist;
16230 SmallPtrSet<Value *, 8> Visited;
16231 Worklist.push_back(Term);
16232 while (!Worklist.empty()) {
16233 Value *Cond = Worklist.pop_back_val();
16234 if (!Visited.insert(Cond).second)
16235 continue;
16236
16237 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
16238 auto Predicate =
16239 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
16240 const auto *LHS = SE.getSCEV(Cmp->getOperand(0));
16241 const auto *RHS = SE.getSCEV(Cmp->getOperand(1));
16242 // If LHS is a constant, apply information to the other expression.
16243 // TODO: If LHS is not a constant, check if using CompareSCEVComplexity
16244 // can improve results.
16245 if (isa<SCEVConstant>(LHS)) {
16246 std::swap(LHS, RHS);
16248 }
16249 GuardsToProcess.emplace_back(Predicate, LHS, RHS);
16250 continue;
16251 }
16252
16253 Value *L, *R;
16254 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
16255 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
16256 Worklist.push_back(L);
16257 Worklist.push_back(R);
16258 }
16259 }
16260 }
16261
16262 // Process divisibility guards in reverse order to populate DivGuards early.
16263 DenseMap<const SCEV *, APInt> Multiples;
16264 LoopGuards DivGuards(SE);
16265 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess) {
16266 if (!isDivisibilityGuard(LHS, RHS, SE))
16267 continue;
16268 collectDivisibilityInformation(Predicate, LHS, RHS, DivGuards.RewriteMap,
16269 Multiples, SE);
16270 }
16271
16272 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess)
16273 CollectCondition(Predicate, LHS, RHS, Guards.RewriteMap, DivGuards);
16274
16275 // Apply divisibility information last. This ensures it is applied to the
16276 // outermost expression after other rewrites for the given value.
16277 for (const auto &[K, Divisor] : Multiples) {
16278 const SCEV *DivisorSCEV = SE.getConstant(Divisor);
16279 Guards.RewriteMap[K] =
16281 Guards.rewrite(K), Divisor, SE),
16282 DivisorSCEV),
16283 DivisorSCEV);
16284 ExprsToRewrite.push_back(K);
16285 }
16286
16287 // Let the rewriter preserve NUW/NSW flags if the unsigned/signed ranges of
16288 // the replacement expressions are contained in the ranges of the replaced
16289 // expressions.
16290 Guards.PreserveNUW = true;
16291 Guards.PreserveNSW = true;
16292 for (const SCEV *Expr : ExprsToRewrite) {
16293 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16294 Guards.PreserveNUW &=
16295 SE.getUnsignedRange(Expr).contains(SE.getUnsignedRange(RewriteTo));
16296 Guards.PreserveNSW &=
16297 SE.getSignedRange(Expr).contains(SE.getSignedRange(RewriteTo));
16298 }
16299
16300 // Now that all rewrite information is collect, rewrite the collected
16301 // expressions with the information in the map. This applies information to
16302 // sub-expressions.
16303 if (ExprsToRewrite.size() > 1) {
16304 for (const SCEV *Expr : ExprsToRewrite) {
16305 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16306 Guards.RewriteMap.erase(Expr);
16307 Guards.RewriteMap.insert({Expr, Guards.rewrite(RewriteTo)});
16308 }
16309 }
16310}
16311
16313 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
16314 /// in the map. It skips AddRecExpr because we cannot guarantee that the
16315 /// replacement is loop invariant in the loop of the AddRec.
16316 class SCEVLoopGuardRewriter
16317 : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
16320
16322
16323 public:
16324 SCEVLoopGuardRewriter(ScalarEvolution &SE,
16325 const ScalarEvolution::LoopGuards &Guards)
16326 : SCEVRewriteVisitor(SE), Map(Guards.RewriteMap),
16327 NotEqual(Guards.NotEqual) {
16328 if (Guards.PreserveNUW)
16329 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNUW);
16330 if (Guards.PreserveNSW)
16331 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNSW);
16332 }
16333
16334 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
16335
16336 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
16337 return Map.lookup_or(Expr, Expr);
16338 }
16339
16340 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
16341 if (const SCEV *S = Map.lookup(Expr))
16342 return S;
16343
16344 // If we didn't find the extact ZExt expr in the map, check if there's
16345 // an entry for a smaller ZExt we can use instead.
16346 Type *Ty = Expr->getType();
16347 const SCEV *Op = Expr->getOperand(0);
16348 unsigned Bitwidth = Ty->getScalarSizeInBits() / 2;
16349 while (Bitwidth % 8 == 0 && Bitwidth >= 8 &&
16350 Bitwidth > Op->getType()->getScalarSizeInBits()) {
16351 Type *NarrowTy = IntegerType::get(SE.getContext(), Bitwidth);
16352 auto *NarrowExt = SE.getZeroExtendExpr(Op, NarrowTy);
16353 if (const SCEV *S = Map.lookup(NarrowExt))
16354 return SE.getZeroExtendExpr(S, Ty);
16355 Bitwidth = Bitwidth / 2;
16356 }
16357
16359 Expr);
16360 }
16361
16362 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
16363 if (const SCEV *S = Map.lookup(Expr))
16364 return S;
16366 Expr);
16367 }
16368
16369 const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
16370 if (const SCEV *S = Map.lookup(Expr))
16371 return S;
16373 }
16374
16375 const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
16376 if (const SCEV *S = Map.lookup(Expr))
16377 return S;
16379 }
16380
16381 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
16382 if (const SCEV *S = Map.lookup(Expr))
16383 return S;
16384
16385 // Helper to check if S is a subtraction (A - B) where A != B, and if so,
16386 // return UMax(S, 1).
16387 auto RewriteSubtraction = [&](const SCEV *S) -> const SCEV * {
16388 SCEVUse LHS, RHS;
16389 if (MatchBinarySub(S, LHS, RHS)) {
16390 if (LHS > RHS)
16391 std::swap(LHS, RHS);
16392 if (NotEqual.contains({LHS, RHS})) {
16393 const SCEV *OneAlignedUp = getNextSCEVDivisibleByDivisor(
16394 SE.getOne(S->getType()), SE.getConstantMultiple(S), SE);
16395 return SE.getUMaxExpr(OneAlignedUp, S);
16396 }
16397 }
16398 return nullptr;
16399 };
16400
16401 // Check if Expr itself is a subtraction pattern with guard info.
16402 if (const SCEV *Rewritten = RewriteSubtraction(Expr))
16403 return Rewritten;
16404
16405 // Trip count expressions sometimes consist of adding 3 operands, i.e.
16406 // (Const + A + B). There may be guard info for A + B, and if so, apply
16407 // it.
16408 // TODO: Could more generally apply guards to Add sub-expressions.
16409 if (isa<SCEVConstant>(Expr->getOperand(0))) {
16410 if (Expr->getNumOperands() == 3) {
16411 const SCEV *Add =
16412 SE.getAddExpr(Expr->getOperand(1), Expr->getOperand(2));
16413 if (const SCEV *Rewritten = RewriteSubtraction(Add))
16414 return SE.getAddExpr(
16415 Expr->getOperand(0), Rewritten,
16416 ScalarEvolution::maskFlags(Expr->getNoWrapFlags(), FlagMask));
16417 if (const SCEV *S = Map.lookup(Add))
16418 return SE.getAddExpr(Expr->getOperand(0), S);
16419 }
16420
16421 // For expressions of the form (Const + A), check if we have guard info
16422 // for (Const + 1 + A), and rewrite to ((Const + 1 + A) - 1). This makes
16423 // sure we don't lose information when rewriting expressions based on
16424 // back-edge taken counts in some cases.
16425 if (Expr->getNumOperands() == 2) {
16426 const SCEV *S = nullptr;
16427 // Handle (-1 + 1 + A) without constructing SCEVs.
16428 if (match(Expr->getOperand(0), m_scev_AllOnes())) {
16429 S = Map.lookup(Expr->getOperand(1));
16430 } else {
16431 const SCEV *NewC =
16432 SE.getAddExpr(Expr->getOperand(0), SE.getOne(Expr->getType()));
16433 S = Map.lookup(SE.getAddExpr(NewC, Expr->getOperand(1)));
16434 }
16435 if (S)
16436 return SE.getAddExpr(S, SE.getMinusOne(Expr->getType()));
16437 }
16438 }
16440 bool Changed = false;
16441 for (SCEVUse Op : Expr->operands()) {
16442 Operands.push_back(
16444 Changed |= Op != Operands.back();
16445 }
16446 // We are only replacing operands with equivalent values, so transfer the
16447 // flags from the original expression.
16448 return !Changed ? Expr
16449 : SE.getAddExpr(Operands,
16451 Expr->getNoWrapFlags(), FlagMask));
16452 }
16453
16454 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
16456 bool Changed = false;
16457 for (SCEVUse Op : Expr->operands()) {
16458 Operands.push_back(
16460 Changed |= Op != Operands.back();
16461 }
16462 // We are only replacing operands with equivalent values, so transfer the
16463 // flags from the original expression.
16464 return !Changed ? Expr
16465 : SE.getMulExpr(Operands,
16467 Expr->getNoWrapFlags(), FlagMask));
16468 }
16469 };
16470
16471 if (RewriteMap.empty() && NotEqual.empty())
16472 return Expr;
16473
16474 SCEVLoopGuardRewriter Rewriter(SE, *this);
16475 return Rewriter.visit(Expr);
16476}
16477
16478const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
16479 return applyLoopGuards(Expr, LoopGuards::collect(L, *this));
16480}
16481
16483 const LoopGuards &Guards) {
16484 return Guards.rewrite(Expr);
16485}
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 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 SCEVUse withUseFlagsIfNotFolded(const SCEV *Res, SCEVUse LHS, SCEVUse RHS, SCEV::NoWrapFlags UseFlags)
Attach UseFlags to Res as use-specific flags, but only if Res really is the two-operand ExprT over LH...
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:420
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1561
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1533
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:203
APInt abs() const
Get the absolute value.
Definition APInt.h:1816
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1206
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:368
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1187
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:377
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition APInt.h:463
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:1509
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1116
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:206
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:213
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:326
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1171
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:216
bool isNonPositive() const
Determine if this APInt Value is non-positive (<= 0).
Definition APInt.h:358
unsigned countTrailingZeros() const
Definition APInt.h:1668
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:353
unsigned logBase2() const
Definition APInt.h:1782
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:472
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:830
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1303
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1155
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:876
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:437
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:303
bool isSignBitSet() const
Determine if sign bit of this APInt is set.
Definition APInt.h:338
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1135
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:197
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition APInt.h:429
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1242
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:236
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1226
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:1497
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:278
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:251
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:341
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition DenseMap.h:161
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive,...
Definition DenseMap.h:264
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:247
iterator end()
Definition DenseMap.h:169
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:242
void swap(DerivedT &RHS)
Definition DenseMap.h:479
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:312
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:1079
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 bool hasNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags)
Returns true if we've statically proved that V doesn't wrap.
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=NoWrapMask) 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 * 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.
static SCEVWrapPredicate::IncrementWrapFlags getImpliedFlags(const SCEVAddRecExpr *AR, ScalarEvolution &SE)
Returns the set of SCEVWrapPredicate no wrap flags implied by a SCEVAddRecExpr.
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.
static constexpr auto FlagAnyWrap
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.
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 const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
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.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
ConstantRange getSignedRange(const SCEV *S)
Determine the signed range for a particular SCEV.
LLVM_ABI const SCEV * getAddRecExpr(SCEVUse Start, SCEVUse Step, const Loop *L, SCEV::NoWrapFlags Flags)
Get an add recurrence expression for the specified loop.
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 const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
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 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 const SCEV * getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
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 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.
LLVM_ABI const SCEV * getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
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 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 * 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 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.
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.
An instruction for storing to memory.
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:2275
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition APInt.h:2280
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition APInt.h:2285
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:2290
constexpr bool any(E Val)
@ Entry
Definition COFF.h:862
int getMinValue(MCInstrInfo const &MCII, MCInst const &MCI)
Return the minimum value of an extendable operand.
@ 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)
match_bind< const SCEVAddExpr > m_scev_Add(const SCEVAddExpr *&V)
SCEVBinaryExpr_match< SCEVSMaxExpr, Op0_t, Op1_t, SCEV::FlagAnyWrap, true > m_scev_SMax(const Op0_t &Op0, const Op1_t &Op1)
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t, SCEV::FlagAnyWrap, true > m_scev_c_Mul(const Op0_t &Op0, const Op1_t &Op1)
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:315
@ Offset
Definition DWP.cpp:577
void stable_sort(R &&Range)
Definition STLExtras.h:2116
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:1739
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 >
@ BinaryOp
One of the operands is a binary op.
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
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:2208
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Instruction *I=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
void * PointerTy
LLVM_ABI bool VerifySCEV
auto uninitialized_copy(R &&Src, IterTy Dst)
Definition STLExtras.h:2111
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:2200
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:1746
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
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:2012
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:2088
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:1917
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:2019
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:2192
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:1947
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:2146
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
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:
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.