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
5696/// A helper function for createAddRecFromPHI to handle simple cases.
5697///
5698/// This function tries to find an AddRec expression for the simplest (yet most
5699/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5700/// If it fails, createAddRecFromPHI will use a more general, but slow,
5701/// technique for finding the AddRec expression.
5702const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5703 Value *BEValueV,
5704 Value *StartValueV) {
5705 const Loop *L = LI.getLoopFor(PN->getParent());
5706 assert(L && L->getHeader() == PN->getParent());
5707 assert(BEValueV && StartValueV);
5708
5709 auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN);
5710 if (!BO)
5711 return nullptr;
5712
5713 if (BO->Opcode != Instruction::Add)
5714 return nullptr;
5715
5716 const SCEV *Accum = nullptr;
5717 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5718 Accum = getSCEV(BO->RHS);
5719 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5720 Accum = getSCEV(BO->LHS);
5721
5722 if (!Accum)
5723 return nullptr;
5724
5726 if (BO->IsNUW)
5727 Flags = setFlags(Flags, SCEV::FlagNUW);
5728 if (BO->IsNSW)
5729 Flags = setFlags(Flags, SCEV::FlagNSW);
5730
5731 const SCEV *StartVal = getSCEV(StartValueV);
5732 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5733 insertValueToMap(PN, PHISCEV);
5734
5735 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5736 inferNoWrapViaConstantRanges(AR);
5737
5738 // We can add Flags to the post-inc expression only if we
5739 // know that it is *undefined behavior* for BEValueV to
5740 // overflow.
5741 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5742 assert(isLoopInvariant(Accum, L) &&
5743 "Accum is defined outside L, but is not invariant?");
5744 if (isAddRecNeverPoison(BEInst, L))
5745 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5746 }
5747
5748 return PHISCEV;
5749}
5750
5751const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5752 const Loop *L = LI.getLoopFor(PN->getParent());
5753 if (!L || L->getHeader() != PN->getParent())
5754 return nullptr;
5755
5756 // The loop may have multiple entrances or multiple exits; we can analyze
5757 // this phi as an addrec if it has a unique entry value and a unique
5758 // backedge value.
5759 Value *BEValueV = nullptr, *StartValueV = nullptr;
5760 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5761 Value *V = PN->getIncomingValue(i);
5762 if (L->contains(PN->getIncomingBlock(i))) {
5763 if (!BEValueV) {
5764 BEValueV = V;
5765 } else if (BEValueV != V) {
5766 BEValueV = nullptr;
5767 break;
5768 }
5769 } else if (!StartValueV) {
5770 StartValueV = V;
5771 } else if (StartValueV != V) {
5772 StartValueV = nullptr;
5773 break;
5774 }
5775 }
5776 if (!BEValueV || !StartValueV)
5777 return nullptr;
5778
5779 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5780 "PHI node already processed?");
5781
5782 // First, try to find AddRec expression without creating a fictituos symbolic
5783 // value for PN.
5784 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5785 return S;
5786
5787 // Handle PHI node value symbolically.
5788 const SCEV *SymbolicName = getUnknown(PN);
5789 insertValueToMap(PN, SymbolicName);
5790
5791 // Using this symbolic name for the PHI, analyze the value coming around
5792 // the back-edge.
5793 const SCEV *BEValue = getSCEV(BEValueV);
5794
5795 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5796 // has a special value for the first iteration of the loop.
5797
5798 // If the value coming around the backedge is an add with the symbolic
5799 // value we just inserted, then we found a simple induction variable!
5800 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5801 // If there is a single occurrence of the symbolic value, replace it
5802 // with a recurrence.
5803 unsigned FoundIndex = Add->getNumOperands();
5804 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5805 if (Add->getOperand(i) == SymbolicName)
5806 if (FoundIndex == e) {
5807 FoundIndex = i;
5808 break;
5809 }
5810
5811 if (FoundIndex != Add->getNumOperands()) {
5812 // Create an add with everything but the specified operand.
5814 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5815 if (i != FoundIndex)
5816 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5817 L, *this));
5818 const SCEV *Accum = getAddExpr(Ops);
5819
5820 // This is not a valid addrec if the step amount is varying each
5821 // loop iteration, but is not itself an addrec in this loop.
5822 if (isLoopInvariant(Accum, L) ||
5823 (isa<SCEVAddRecExpr>(Accum) &&
5824 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5826
5827 if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
5828 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5829 if (BO->IsNUW)
5830 Flags = setFlags(Flags, SCEV::FlagNUW);
5831 if (BO->IsNSW)
5832 Flags = setFlags(Flags, SCEV::FlagNSW);
5833 }
5834 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5835 if (GEP->getOperand(0) == PN) {
5836 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
5837 // If the increment has any nowrap flags, then we know the address
5838 // space cannot be wrapped around.
5839 if (NW != GEPNoWrapFlags::none())
5840 Flags = setFlags(Flags, SCEV::FlagNW);
5841 // If the GEP is nuw or nusw with non-negative offset, we know that
5842 // no unsigned wrap occurs. We cannot set the nsw flag as only the
5843 // offset is treated as signed, while the base is unsigned.
5844 if (NW.hasNoUnsignedWrap() ||
5846 Flags = setFlags(Flags, SCEV::FlagNUW);
5847 }
5848
5849 // We cannot transfer nuw and nsw flags from subtraction
5850 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5851 // for instance.
5852 }
5853
5854 const SCEV *StartVal = getSCEV(StartValueV);
5855 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5856
5857 // Okay, for the entire analysis of this edge we assumed the PHI
5858 // to be symbolic. We now need to go back and purge all of the
5859 // entries for the scalars that use the symbolic expression.
5860 forgetMemoizedResults({SymbolicName});
5861 insertValueToMap(PN, PHISCEV);
5862
5863 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5864 inferNoWrapViaConstantRanges(AR);
5865
5866 // We can add Flags to the post-inc expression only if we
5867 // know that it is *undefined behavior* for BEValueV to
5868 // overflow.
5869 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5870 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5871 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5872
5873 return PHISCEV;
5874 }
5875 }
5876 } else {
5877 // Otherwise, this could be a loop like this:
5878 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5879 // In this case, j = {1,+,1} and BEValue is j.
5880 // Because the other in-value of i (0) fits the evolution of BEValue
5881 // i really is an addrec evolution.
5882 //
5883 // We can generalize this saying that i is the shifted value of BEValue
5884 // by one iteration:
5885 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5886
5887 // Do not allow refinement in rewriting of BEValue.
5888 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5889 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5890 if (Shifted != getCouldNotCompute() && Start != getCouldNotCompute() &&
5891 isGuaranteedNotToCauseUB(Shifted) && ::impliesPoison(Shifted, Start)) {
5892 const SCEV *StartVal = getSCEV(StartValueV);
5893 if (Start == StartVal) {
5894 // Okay, for the entire analysis of this edge we assumed the PHI
5895 // to be symbolic. We now need to go back and purge all of the
5896 // entries for the scalars that use the symbolic expression.
5897 forgetMemoizedResults({SymbolicName});
5898 insertValueToMap(PN, Shifted);
5899 return Shifted;
5900 }
5901 }
5902 }
5903
5904 // Remove the temporary PHI node SCEV that has been inserted while intending
5905 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5906 // as it will prevent later (possibly simpler) SCEV expressions to be added
5907 // to the ValueExprMap.
5908 eraseValueFromMap(PN);
5909
5910 return nullptr;
5911}
5912
5913// Try to match a control flow sequence that branches out at BI and merges back
5914// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5915// match.
5917 Value *&C, Value *&LHS, Value *&RHS) {
5918 C = BI->getCondition();
5919
5920 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5921 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5922
5923 Use &LeftUse = Merge->getOperandUse(0);
5924 Use &RightUse = Merge->getOperandUse(1);
5925
5926 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5927 LHS = LeftUse;
5928 RHS = RightUse;
5929 return true;
5930 }
5931
5932 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5933 LHS = RightUse;
5934 RHS = LeftUse;
5935 return true;
5936 }
5937
5938 return false;
5939}
5940
5942 Value *&Cond, Value *&LHS,
5943 Value *&RHS) {
5944 auto IsReachable =
5945 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5946 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5947 // Try to match
5948 //
5949 // br %cond, label %left, label %right
5950 // left:
5951 // br label %merge
5952 // right:
5953 // br label %merge
5954 // merge:
5955 // V = phi [ %x, %left ], [ %y, %right ]
5956 //
5957 // as "select %cond, %x, %y"
5958
5959 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5960 assert(IDom && "At least the entry block should dominate PN");
5961
5962 auto *BI = dyn_cast<CondBrInst>(IDom->getTerminator());
5963 return BI && BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS);
5964 }
5965 return false;
5966}
5967
5968const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5969 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5970 if (getOperandsForSelectLikePHI(DT, PN, Cond, LHS, RHS) &&
5973 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5974
5975 return nullptr;
5976}
5977
5979 BinaryOperator *CommonInst = nullptr;
5980 // Check if instructions are identical.
5981 for (Value *Incoming : PN->incoming_values()) {
5982 auto *IncomingInst = dyn_cast<BinaryOperator>(Incoming);
5983 if (!IncomingInst)
5984 return nullptr;
5985 if (CommonInst) {
5986 if (!CommonInst->isIdenticalToWhenDefined(IncomingInst))
5987 return nullptr; // Not identical, give up
5988 } else {
5989 // Remember binary operator
5990 CommonInst = IncomingInst;
5991 }
5992 }
5993 return CommonInst;
5994}
5995
5996/// Returns SCEV for the first operand of a phi if all phi operands have
5997/// identical opcodes and operands
5998/// eg.
5999/// a: %add = %a + %b
6000/// br %c
6001/// b: %add1 = %a + %b
6002/// br %c
6003/// c: %phi = phi [%add, a], [%add1, b]
6004/// scev(%phi) => scev(%add)
6005const SCEV *
6006ScalarEvolution::createNodeForPHIWithIdenticalOperands(PHINode *PN) {
6007 BinaryOperator *CommonInst = getCommonInstForPHI(PN);
6008 if (!CommonInst)
6009 return nullptr;
6010
6011 // Check if SCEV exprs for instructions are identical.
6012 const SCEV *CommonSCEV = getSCEV(CommonInst);
6013 bool SCEVExprsIdentical =
6015 [this, CommonSCEV](Value *V) { return CommonSCEV == getSCEV(V); });
6016 return SCEVExprsIdentical ? CommonSCEV : nullptr;
6017}
6018
6019const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
6020 if (const SCEV *S = createAddRecFromPHI(PN))
6021 return S;
6022
6023 // We do not allow simplifying phi (undef, X) to X here, to avoid reusing the
6024 // phi node for X.
6025 if (Value *V = simplifyInstruction(
6026 PN, {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
6027 /*UseInstrInfo=*/true, /*CanUseUndef=*/false}))
6028 return getSCEV(V);
6029
6030 if (const SCEV *S = createNodeForPHIWithIdenticalOperands(PN))
6031 return S;
6032
6033 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
6034 return S;
6035
6036 // If it's not a loop phi, we can't handle it yet.
6037 return getUnknown(PN);
6038}
6039
6040bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
6041 SCEVTypes RootKind) {
6042 struct FindClosure {
6043 const SCEV *OperandToFind;
6044 const SCEVTypes RootKind; // Must be a sequential min/max expression.
6045 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
6046
6047 bool Found = false;
6048
6049 bool canRecurseInto(SCEVTypes Kind) const {
6050 // We can only recurse into the SCEV expression of the same effective type
6051 // as the type of our root SCEV expression, and into zero-extensions.
6052 return RootKind == Kind || NonSequentialRootKind == Kind ||
6053 scZeroExtend == Kind;
6054 };
6055
6056 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
6057 : OperandToFind(OperandToFind), RootKind(RootKind),
6058 NonSequentialRootKind(
6060 RootKind)) {}
6061
6062 bool follow(const SCEV *S) {
6063 Found = S == OperandToFind;
6064
6065 return !isDone() && canRecurseInto(S->getSCEVType());
6066 }
6067
6068 bool isDone() const { return Found; }
6069 };
6070
6071 FindClosure FC(OperandToFind, RootKind);
6072 visitAll(Root, FC);
6073 return FC.Found;
6074}
6075
6076std::optional<const SCEV *>
6077ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
6078 ICmpInst *Cond,
6079 Value *TrueVal,
6080 Value *FalseVal) {
6081 // Try to match some simple smax or umax patterns.
6082 auto *ICI = Cond;
6083
6084 Value *LHS = ICI->getOperand(0);
6085 Value *RHS = ICI->getOperand(1);
6086
6087 switch (ICI->getPredicate()) {
6088 case ICmpInst::ICMP_SLT:
6089 case ICmpInst::ICMP_SLE:
6090 case ICmpInst::ICMP_ULT:
6091 case ICmpInst::ICMP_ULE:
6092 std::swap(LHS, RHS);
6093 [[fallthrough]];
6094 case ICmpInst::ICMP_SGT:
6095 case ICmpInst::ICMP_SGE:
6096 case ICmpInst::ICMP_UGT:
6097 case ICmpInst::ICMP_UGE:
6098 // a > b ? a+x : b+x -> max(a, b)+x
6099 // a > b ? b+x : a+x -> min(a, b)+x
6101 bool Signed = ICI->isSigned();
6102 const SCEV *LA = getSCEV(TrueVal);
6103 const SCEV *RA = getSCEV(FalseVal);
6104 const SCEV *LS = getSCEV(LHS);
6105 const SCEV *RS = getSCEV(RHS);
6106 if (LA->getType()->isPointerTy()) {
6107 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6108 // Need to make sure we can't produce weird expressions involving
6109 // negated pointers.
6110 if (LA == LS && RA == RS)
6111 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6112 if (LA == RS && RA == LS)
6113 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6114 }
6115 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6116 if (Op->getType()->isPointerTy()) {
6119 return Op;
6120 }
6121 if (Signed)
6122 Op = getNoopOrSignExtend(Op, Ty);
6123 else
6124 Op = getNoopOrZeroExtend(Op, Ty);
6125 return Op;
6126 };
6127 LS = CoerceOperand(LS);
6128 RS = CoerceOperand(RS);
6130 break;
6131 const SCEV *LDiff = getMinusSCEV(LA, LS);
6132 const SCEV *RDiff = getMinusSCEV(RA, RS);
6133 if (LDiff == RDiff)
6134 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6135 LDiff);
6136 LDiff = getMinusSCEV(LA, RS);
6137 RDiff = getMinusSCEV(RA, LS);
6138 if (LDiff == RDiff)
6139 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6140 LDiff);
6141 }
6142 break;
6143 case ICmpInst::ICMP_NE:
6144 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
6145 std::swap(TrueVal, FalseVal);
6146 [[fallthrough]];
6147 case ICmpInst::ICMP_EQ:
6148 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
6151 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6152 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y
6153 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y
6154 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6155 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y
6156 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6157 return getAddExpr(getUMaxExpr(X, C), Y);
6158 }
6159 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
6160 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
6161 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
6162 // -> umin_seq(x, umin (..., umin_seq(...), ...))
6164 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6165 const SCEV *X = getSCEV(LHS);
6166 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6167 X = ZExt->getOperand();
6168 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6169 const SCEV *FalseValExpr = getSCEV(FalseVal);
6170 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6171 return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6172 /*Sequential=*/true);
6173 }
6174 }
6175 break;
6176 default:
6177 break;
6178 }
6179
6180 return std::nullopt;
6181}
6182
6183static std::optional<const SCEV *>
6185 const SCEV *TrueExpr, const SCEV *FalseExpr) {
6186 assert(CondExpr->getType()->isIntegerTy(1) &&
6187 TrueExpr->getType() == FalseExpr->getType() &&
6188 TrueExpr->getType()->isIntegerTy(1) &&
6189 "Unexpected operands of a select.");
6190
6191 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
6192 // --> C + (umin_seq cond, x - C)
6193 //
6194 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
6195 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6196 // --> C + (umin_seq ~cond, x - C)
6197
6198 // FIXME: while we can't legally model the case where both of the hands
6199 // are fully variable, we only require that the *difference* is constant.
6200 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6201 return std::nullopt;
6202
6203 const SCEV *X, *C;
6204 if (isa<SCEVConstant>(TrueExpr)) {
6205 CondExpr = SE->getNotSCEV(CondExpr);
6206 X = FalseExpr;
6207 C = TrueExpr;
6208 } else {
6209 X = TrueExpr;
6210 C = FalseExpr;
6211 }
6212 return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6213 /*Sequential=*/true));
6214}
6215
6216static std::optional<const SCEV *>
6218 Value *FalseVal) {
6219 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6220 return std::nullopt;
6221
6222 const auto *SECond = SE->getSCEV(Cond);
6223 const auto *SETrue = SE->getSCEV(TrueVal);
6224 const auto *SEFalse = SE->getSCEV(FalseVal);
6225 return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6226}
6227
6228const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6229 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6230 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6231 assert(TrueVal->getType() == FalseVal->getType() &&
6232 V->getType() == TrueVal->getType() &&
6233 "Types of select hands and of the result must match.");
6234
6235 // For now, only deal with i1-typed `select`s.
6236 if (!V->getType()->isIntegerTy(1))
6237 return getUnknown(V);
6238
6239 if (std::optional<const SCEV *> S =
6240 createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6241 return *S;
6242
6243 return getUnknown(V);
6244}
6245
6246const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6247 Value *TrueVal,
6248 Value *FalseVal) {
6249 // Handle "constant" branch or select. This can occur for instance when a
6250 // loop pass transforms an inner loop and moves on to process the outer loop.
6251 if (auto *CI = dyn_cast<ConstantInt>(Cond))
6252 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6253
6254 if (auto *I = dyn_cast<Instruction>(V)) {
6255 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6256 if (std::optional<const SCEV *> S =
6257 createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6258 TrueVal, FalseVal))
6259 return *S;
6260 }
6261 }
6262
6263 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6264}
6265
6266/// Expand GEP instructions into add and multiply operations. This allows them
6267/// to be analyzed by regular SCEV code.
6268const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6269 assert(GEP->getSourceElementType()->isSized() &&
6270 "GEP source element type must be sized");
6271
6272 SmallVector<SCEVUse, 4> IndexExprs;
6273 for (Value *Index : GEP->indices())
6274 IndexExprs.push_back(getSCEV(Index));
6275 return getGEPExpr(GEP, IndexExprs);
6276}
6277
6278APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S,
6279 const Instruction *CtxI) {
6281 auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6282 return TrailingZeros >= BitWidth
6284 : APInt::getOneBitSet(BitWidth, TrailingZeros);
6285 };
6286 auto GetGCDMultiple = [this, CtxI](const SCEVNAryExpr *N) {
6287 // The result is GCD of all operands results.
6288 APInt Res = getConstantMultiple(N->getOperand(0), CtxI);
6289 for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6291 Res, getConstantMultiple(N->getOperand(I), CtxI));
6292 return Res;
6293 };
6294
6295 switch (S->getSCEVType()) {
6296 case scConstant:
6297 return cast<SCEVConstant>(S)->getAPInt();
6298 case scPtrToAddr:
6299 return getConstantMultiple(cast<SCEVCastExpr>(S)->getOperand());
6300 case scUDivExpr:
6301 case scVScale:
6302 return APInt(BitWidth, 1);
6303 case scTruncate: {
6304 // Only multiples that are a power of 2 will hold after truncation.
6305 const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6306 uint32_t TZ = getMinTrailingZeros(T->getOperand(), CtxI);
6307 return GetShiftedByZeros(TZ);
6308 }
6309 case scZeroExtend: {
6310 const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(S);
6311 return getConstantMultiple(Z->getOperand(), CtxI).zext(BitWidth);
6312 }
6313 case scSignExtend: {
6314 // Only multiples that are a power of 2 will hold after sext.
6315 const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6316 uint32_t TZ = getMinTrailingZeros(E->getOperand(), CtxI);
6317 return GetShiftedByZeros(TZ);
6318 }
6319 case scMulExpr: {
6320 const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6321 if (M->hasNoUnsignedWrap()) {
6322 // The result is the product of all operand results.
6323 APInt Res = getConstantMultiple(M->getOperand(0), CtxI);
6324 for (const SCEV *Operand : M->operands().drop_front())
6325 Res = Res * getConstantMultiple(Operand, CtxI);
6326 return Res;
6327 }
6328
6329 // If there are no wrap guarentees, find the trailing zeros, which is the
6330 // sum of trailing zeros for all its operands.
6331 uint32_t TZ = 0;
6332 for (const SCEV *Operand : M->operands())
6333 TZ += getMinTrailingZeros(Operand, CtxI);
6334 return GetShiftedByZeros(TZ);
6335 }
6336 case scAddExpr:
6337 case scAddRecExpr: {
6338 const SCEVNAryExpr *N = cast<SCEVNAryExpr>(S);
6339 if (N->hasNoUnsignedWrap())
6340 return GetGCDMultiple(N);
6341 // Find the trailing bits, which is the minimum of its operands.
6342 uint32_t TZ = getMinTrailingZeros(N->getOperand(0), CtxI);
6343 for (const SCEV *Operand : N->operands().drop_front())
6344 TZ = std::min(TZ, getMinTrailingZeros(Operand, CtxI));
6345 return GetShiftedByZeros(TZ);
6346 }
6347 case scUMaxExpr:
6348 case scSMaxExpr:
6349 case scUMinExpr:
6350 case scSMinExpr:
6352 return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6353 case scUnknown: {
6354 // Ask ValueTracking for known bits. SCEVUnknown only become available at
6355 // the point their underlying IR instruction has been defined. If CtxI was
6356 // not provided, use:
6357 // * the first instruction in the entry block if it is an argument
6358 // * the instruction itself otherwise.
6359 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6360 if (!CtxI) {
6361 if (isa<Argument>(U->getValue()))
6362 CtxI = &*F.getEntryBlock().begin();
6363 else if (auto *I = dyn_cast<Instruction>(U->getValue()))
6364 CtxI = I;
6365 }
6366 unsigned Known =
6367 computeKnownBits(U->getValue(),
6368 SimplifyQuery(getDataLayout(), &DT, &AC, CtxI)
6369 .allowEphemerals(true))
6370 .countMinTrailingZeros();
6371 return GetShiftedByZeros(Known);
6372 }
6373 case scCouldNotCompute:
6374 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6375 }
6376 llvm_unreachable("Unknown SCEV kind!");
6377}
6378
6380 const Instruction *CtxI) {
6381 // Skip looking up and updating the cache if there is a context instruction,
6382 // as the result will only be valid in the specified context.
6383 if (CtxI)
6384 return getConstantMultipleImpl(S, CtxI);
6385
6386 auto I = ConstantMultipleCache.find(S);
6387 if (I != ConstantMultipleCache.end())
6388 return I->second;
6389
6390 APInt Result = getConstantMultipleImpl(S, CtxI);
6391 auto InsertPair = ConstantMultipleCache.insert({S, Result});
6392 assert(InsertPair.second && "Should insert a new key");
6393 return InsertPair.first->second;
6394}
6395
6397 APInt Multiple = getConstantMultiple(S);
6398 return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6399}
6400
6402 const Instruction *CtxI) {
6403 return std::min(getConstantMultiple(S, CtxI).countTrailingZeros(),
6404 (unsigned)getTypeSizeInBits(S->getType()));
6405}
6406
6407/// Helper method to assign a range to V from metadata present in the IR.
6408static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6410 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6411 return getConstantRangeFromMetadata(*MD);
6412 if (const auto *CB = dyn_cast<CallBase>(V))
6413 if (std::optional<ConstantRange> Range = CB->getRange())
6414 return Range;
6415 }
6416 if (auto *A = dyn_cast<Argument>(V))
6417 if (std::optional<ConstantRange> Range = A->getRange())
6418 return Range;
6419
6420 return std::nullopt;
6421}
6422
6424 SCEV::NoWrapFlags Flags) {
6425 if (AddRec->getNoWrapFlags(Flags) != Flags) {
6426 AddRec->setNoWrapFlags(Flags);
6427 UnsignedRanges.erase(AddRec);
6428 SignedRanges.erase(AddRec);
6429 ConstantMultipleCache.erase(AddRec);
6430 }
6431}
6432
6433ConstantRange ScalarEvolution::
6434getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6435 const DataLayout &DL = getDataLayout();
6436
6437 unsigned BitWidth = getTypeSizeInBits(U->getType());
6438 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6439
6440 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6441 // use information about the trip count to improve our available range. Note
6442 // that the trip count independent cases are already handled by known bits.
6443 // WARNING: The definition of recurrence used here is subtly different than
6444 // the one used by AddRec (and thus most of this file). Step is allowed to
6445 // be arbitrarily loop varying here, where AddRec allows only loop invariant
6446 // and other addrecs in the same loop (for non-affine addrecs). The code
6447 // below intentionally handles the case where step is not loop invariant.
6448 auto *P = dyn_cast<PHINode>(U->getValue());
6449 if (!P)
6450 return FullSet;
6451
6452 // Make sure that no Phi input comes from an unreachable block. Otherwise,
6453 // even the values that are not available in these blocks may come from them,
6454 // and this leads to false-positive recurrence test.
6455 for (auto *Pred : predecessors(P->getParent()))
6456 if (!DT.isReachableFromEntry(Pred))
6457 return FullSet;
6458
6459 BinaryOperator *BO;
6460 Value *Start, *Step;
6461 if (!matchSimpleRecurrence(P, BO, Start, Step))
6462 return FullSet;
6463
6464 // If we found a recurrence in reachable code, we must be in a loop. Note
6465 // that BO might be in some subloop of L, and that's completely okay.
6466 auto *L = LI.getLoopFor(P->getParent());
6467 assert(L && L->getHeader() == P->getParent());
6468 if (!L->contains(BO->getParent()))
6469 // NOTE: This bailout should be an assert instead. However, asserting
6470 // the condition here exposes a case where LoopFusion is querying SCEV
6471 // with malformed loop information during the midst of the transform.
6472 // There doesn't appear to be an obvious fix, so for the moment bailout
6473 // until the caller issue can be fixed. PR49566 tracks the bug.
6474 return FullSet;
6475
6476 // TODO: Extend to other opcodes such as mul, and div
6477 switch (BO->getOpcode()) {
6478 default:
6479 return FullSet;
6480 case Instruction::AShr:
6481 case Instruction::LShr:
6482 case Instruction::Shl:
6483 break;
6484 };
6485
6486 if (BO->getOperand(0) != P)
6487 // TODO: Handle the power function forms some day.
6488 return FullSet;
6489
6490 unsigned TC = getSmallConstantMaxTripCount(L);
6491 if (!TC || TC >= BitWidth)
6492 return FullSet;
6493
6494 auto KnownStart = computeKnownBits(Start, DL, &AC, nullptr, &DT);
6495 auto KnownStep = computeKnownBits(Step, DL, &AC, nullptr, &DT);
6496 assert(KnownStart.getBitWidth() == BitWidth &&
6497 KnownStep.getBitWidth() == BitWidth);
6498
6499 // Compute total shift amount, being careful of overflow and bitwidths.
6500 auto MaxShiftAmt = KnownStep.getMaxValue();
6501 APInt TCAP(BitWidth, TC-1);
6502 bool Overflow = false;
6503 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6504 if (Overflow)
6505 return FullSet;
6506
6507 switch (BO->getOpcode()) {
6508 default:
6509 llvm_unreachable("filtered out above");
6510 case Instruction::AShr: {
6511 // For each ashr, three cases:
6512 // shift = 0 => unchanged value
6513 // saturation => 0 or -1
6514 // other => a value closer to zero (of the same sign)
6515 // Thus, the end value is closer to zero than the start.
6516 auto KnownEnd = KnownBits::ashr(KnownStart,
6517 KnownBits::makeConstant(TotalShift));
6518 if (KnownStart.isNonNegative())
6519 // Analogous to lshr (simply not yet canonicalized)
6520 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6521 KnownStart.getMaxValue() + 1);
6522 if (KnownStart.isNegative())
6523 // End >=u Start && End <=s Start
6524 return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6525 KnownEnd.getMaxValue() + 1);
6526 break;
6527 }
6528 case Instruction::LShr: {
6529 // For each lshr, three cases:
6530 // shift = 0 => unchanged value
6531 // saturation => 0
6532 // other => a smaller positive number
6533 // Thus, the low end of the unsigned range is the last value produced.
6534 auto KnownEnd = KnownBits::lshr(KnownStart,
6535 KnownBits::makeConstant(TotalShift));
6536 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6537 KnownStart.getMaxValue() + 1);
6538 }
6539 case Instruction::Shl: {
6540 // Iff no bits are shifted out, value increases on every shift.
6541 auto KnownEnd = KnownBits::shl(KnownStart,
6542 KnownBits::makeConstant(TotalShift));
6543 if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6544 return ConstantRange(KnownStart.getMinValue(),
6545 KnownEnd.getMaxValue() + 1);
6546 break;
6547 }
6548 };
6549 return FullSet;
6550}
6551
6552// The goal of this function is to check if recursively visiting the operands
6553// of this PHI might lead to an infinite loop. If we do see such a loop,
6554// there's no good way to break it, so we avoid analyzing such cases.
6555//
6556// getRangeRef previously used a visited set to avoid infinite loops, but this
6557// caused other issues: the result was dependent on the order of getRangeRef
6558// calls, and the interaction with createSCEVIter could cause a stack overflow
6559// in some cases (see issue #148253).
6560//
6561// FIXME: The way this is implemented is overly conservative; this checks
6562// for a few obviously safe patterns, but anything that doesn't lead to
6563// recursion is fine.
6565 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6567 return true;
6568
6569 if (all_of(PHI->operands(),
6570 [&](Value *Operand) { return DT.dominates(Operand, PHI); }))
6571 return true;
6572
6573 return false;
6574}
6575
6576const ConstantRange &
6577ScalarEvolution::getRangeRefIter(const SCEV *S,
6578 ScalarEvolution::RangeSignHint SignHint) {
6579 DenseMap<const SCEV *, ConstantRange> &Cache =
6580 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6581 : SignedRanges;
6582 SmallVector<SCEVUse> WorkList;
6583 SmallPtrSet<const SCEV *, 8> Seen;
6584
6585 // Add Expr to the worklist, if Expr is either an N-ary expression or a
6586 // SCEVUnknown PHI node.
6587 auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6588 if (!Seen.insert(Expr).second)
6589 return;
6590 if (Cache.contains(Expr))
6591 return;
6592 switch (Expr->getSCEVType()) {
6593 case scUnknown:
6595 break;
6596 [[fallthrough]];
6597 case scConstant:
6598 case scVScale:
6599 case scTruncate:
6600 case scZeroExtend:
6601 case scSignExtend:
6602 case scPtrToAddr:
6603 case scAddExpr:
6604 case scMulExpr:
6605 case scUDivExpr:
6606 case scAddRecExpr:
6607 case scUMaxExpr:
6608 case scSMaxExpr:
6609 case scUMinExpr:
6610 case scSMinExpr:
6612 WorkList.push_back(Expr);
6613 break;
6614 case scCouldNotCompute:
6615 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6616 }
6617 };
6618 AddToWorklist(S);
6619
6620 // Build worklist by queuing operands of N-ary expressions and phi nodes.
6621 for (unsigned I = 0; I != WorkList.size(); ++I) {
6622 const SCEV *P = WorkList[I];
6623 auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6624 // If it is not a `SCEVUnknown`, just recurse into operands.
6625 if (!UnknownS) {
6626 for (const SCEV *Op : P->operands())
6627 AddToWorklist(Op);
6628 continue;
6629 }
6630 // `SCEVUnknown`'s require special treatment.
6631 if (PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6632 if (!RangeRefPHIAllowedOperands(DT, P))
6633 continue;
6634 for (auto &Op : reverse(P->operands()))
6635 AddToWorklist(getSCEV(Op));
6636 }
6637 }
6638
6639 if (!WorkList.empty()) {
6640 // Use getRangeRef to compute ranges for items in the worklist in reverse
6641 // order. This will force ranges for earlier operands to be computed before
6642 // their users in most cases.
6643 for (const SCEV *P : reverse(drop_begin(WorkList))) {
6644 getRangeRef(P, SignHint);
6645 }
6646 }
6647
6648 return getRangeRef(S, SignHint, 0);
6649}
6650
6651const APInt *ScalarEvolution::getConstantAPIntOrNull(const SCEV *S) {
6652 if (const auto *C = dyn_cast<SCEVConstant>(S))
6653 return &C->getAPInt();
6654 return nullptr;
6655}
6656
6657/// Determine the range for a particular SCEV. If SignHint is
6658/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6659/// with a "cleaner" unsigned (resp. signed) representation.
6660const ConstantRange &ScalarEvolution::getRangeRef(
6661 const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6662 DenseMap<const SCEV *, ConstantRange> &Cache =
6663 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6664 : SignedRanges;
6666 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6668
6669 // See if we've computed this range already.
6670 auto I = Cache.find(S);
6671 if (I != Cache.end())
6672 return I->second;
6673
6674 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6675 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6676
6677 // Switch to iteratively computing the range for S, if it is part of a deeply
6678 // nested expression.
6680 return getRangeRefIter(S, SignHint);
6681
6682 unsigned BitWidth = getTypeSizeInBits(S->getType());
6683 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6684 using OBO = OverflowingBinaryOperator;
6685
6686 // If the value has known zeros, the maximum value will have those known zeros
6687 // as well.
6688 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6689 APInt Multiple = getNonZeroConstantMultiple(S);
6690 APInt Remainder = APInt::getMaxValue(BitWidth).urem(Multiple);
6691 if (!Remainder.isZero())
6692 ConservativeResult =
6693 ConstantRange(APInt::getMinValue(BitWidth),
6694 APInt::getMaxValue(BitWidth) - Remainder + 1);
6695 }
6696 else {
6697 uint32_t TZ = getMinTrailingZeros(S);
6698 if (TZ != 0) {
6699 ConservativeResult = ConstantRange(
6701 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6702 }
6703 }
6704
6705 switch (S->getSCEVType()) {
6706 case scConstant:
6707 llvm_unreachable("Already handled above.");
6708 case scVScale:
6709 return setRange(S, SignHint, getVScaleRange(&F, BitWidth));
6710 case scTruncate: {
6711 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6712 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6713 return setRange(
6714 Trunc, SignHint,
6715 ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6716 }
6717 case scZeroExtend: {
6718 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6719 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6720 return setRange(
6721 ZExt, SignHint,
6722 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6723 }
6724 case scSignExtend: {
6725 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6726 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6727 return setRange(
6728 SExt, SignHint,
6729 ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6730 }
6731 case scPtrToAddr: {
6732 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6733 ConstantRange X = getRangeRef(Cast->getOperand(), SignHint, Depth + 1);
6734 return setRange(Cast, SignHint, X);
6735 }
6736 case scAddExpr: {
6737 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6738 // Check if this is a URem pattern: A - (A / B) * B, which is always < B.
6739 const SCEV *URemLHS = nullptr, *URemRHS = nullptr;
6740 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED &&
6741 match(S, m_scev_URem(m_SCEV(URemLHS), m_SCEV(URemRHS), *this))) {
6742 ConstantRange LHSRange = getRangeRef(URemLHS, SignHint, Depth + 1);
6743 ConstantRange RHSRange = getRangeRef(URemRHS, SignHint, Depth + 1);
6744 ConservativeResult =
6745 ConservativeResult.intersectWith(LHSRange.urem(RHSRange), RangeType);
6746 }
6747 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6748 unsigned WrapType = OBO::AnyWrap;
6749 if (Add->hasNoSignedWrap())
6750 WrapType |= OBO::NoSignedWrap;
6751 if (Add->hasNoUnsignedWrap())
6752 WrapType |= OBO::NoUnsignedWrap;
6753 for (const SCEV *Op : drop_begin(Add->operands()))
6754 X = X.addWithNoWrap(getRangeRef(Op, SignHint, Depth + 1), WrapType,
6755 RangeType);
6756 return setRange(Add, SignHint,
6757 ConservativeResult.intersectWith(X, RangeType));
6758 }
6759 case scMulExpr: {
6760 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6761 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6762 for (const SCEV *Op : drop_begin(Mul->operands()))
6763 X = X.multiply(getRangeRef(Op, SignHint, Depth + 1));
6764 return setRange(Mul, SignHint,
6765 ConservativeResult.intersectWith(X, RangeType));
6766 }
6767 case scUDivExpr: {
6768 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6769 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6770 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6771 return setRange(UDiv, SignHint,
6772 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6773 }
6774 case scAddRecExpr: {
6775 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6776 // If there's no unsigned wrap, the value will never be less than its
6777 // initial value.
6778 if (AddRec->hasNoUnsignedWrap()) {
6779 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6780 if (!UnsignedMinValue.isZero())
6781 ConservativeResult = ConservativeResult.intersectWith(
6782 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6783 }
6784
6785 // If there's no signed wrap, and all the operands except initial value have
6786 // the same sign or zero, the value won't ever be:
6787 // 1: smaller than initial value if operands are non negative,
6788 // 2: bigger than initial value if operands are non positive.
6789 // For both cases, value can not cross signed min/max boundary.
6790 if (AddRec->hasNoSignedWrap()) {
6791 bool AllNonNeg = true;
6792 bool AllNonPos = true;
6793 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6794 if (!isKnownNonNegative(AddRec->getOperand(i)))
6795 AllNonNeg = false;
6796 if (!isKnownNonPositive(AddRec->getOperand(i)))
6797 AllNonPos = false;
6798 }
6799 if (AllNonNeg)
6800 ConservativeResult = ConservativeResult.intersectWith(
6803 RangeType);
6804 else if (AllNonPos)
6805 ConservativeResult = ConservativeResult.intersectWith(
6807 getSignedRangeMax(AddRec->getStart()) +
6808 1),
6809 RangeType);
6810 }
6811
6812 // TODO: non-affine addrec
6813 if (AddRec->isAffine()) {
6814 const SCEV *MaxBEScev =
6816 if (!isa<SCEVCouldNotCompute>(MaxBEScev)) {
6817 APInt MaxBECount = cast<SCEVConstant>(MaxBEScev)->getAPInt();
6818
6819 // Adjust MaxBECount to the same bitwidth as AddRec. We can truncate if
6820 // MaxBECount's active bits are all <= AddRec's bit width.
6821 if (MaxBECount.getBitWidth() > BitWidth &&
6822 MaxBECount.getActiveBits() <= BitWidth)
6823 MaxBECount = MaxBECount.trunc(BitWidth);
6824 else if (MaxBECount.getBitWidth() < BitWidth)
6825 MaxBECount = MaxBECount.zext(BitWidth);
6826
6827 if (MaxBECount.getBitWidth() == BitWidth) {
6828 auto [RangeFromAffine, Flags] = getRangeForAffineAR(
6829 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6830 ConservativeResult =
6831 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6832 const_cast<SCEVAddRecExpr *>(AddRec)->setNoWrapFlags(Flags);
6833
6834 auto RangeFromFactoring = getRangeViaFactoring(
6835 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6836 ConservativeResult =
6837 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6838 }
6839 }
6840
6841 // Now try symbolic BE count and more powerful methods.
6843 const SCEV *SymbolicMaxBECount =
6845 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6846 getTypeSizeInBits(MaxBEScev->getType()) <= BitWidth &&
6847 AddRec->hasNoSelfWrap()) {
6848 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6849 AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6850 ConservativeResult =
6851 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6852 }
6853 }
6854 }
6855
6856 return setRange(AddRec, SignHint, std::move(ConservativeResult));
6857 }
6858 case scUMaxExpr:
6859 case scSMaxExpr:
6860 case scUMinExpr:
6861 case scSMinExpr:
6862 case scSequentialUMinExpr: {
6864 switch (S->getSCEVType()) {
6865 case scUMaxExpr:
6866 ID = Intrinsic::umax;
6867 break;
6868 case scSMaxExpr:
6869 ID = Intrinsic::smax;
6870 break;
6871 case scUMinExpr:
6873 ID = Intrinsic::umin;
6874 break;
6875 case scSMinExpr:
6876 ID = Intrinsic::smin;
6877 break;
6878 default:
6879 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6880 }
6881
6882 const auto *NAry = cast<SCEVNAryExpr>(S);
6883 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
6884 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6885 X = X.intrinsic(
6886 ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
6887 return setRange(S, SignHint,
6888 ConservativeResult.intersectWith(X, RangeType));
6889 }
6890 case scUnknown: {
6891 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6892 Value *V = U->getValue();
6893
6894 // Check if the IR explicitly contains !range metadata.
6895 std::optional<ConstantRange> MDRange = GetRangeFromMetadata(V);
6896 if (MDRange)
6897 ConservativeResult =
6898 ConservativeResult.intersectWith(*MDRange, RangeType);
6899
6900 // Use facts about recurrences in the underlying IR. Note that add
6901 // recurrences are AddRecExprs and thus don't hit this path. This
6902 // primarily handles shift recurrences.
6903 auto CR = getRangeForUnknownRecurrence(U);
6904 ConservativeResult = ConservativeResult.intersectWith(CR);
6905
6906 // See if ValueTracking can give us a useful range.
6907 const DataLayout &DL = getDataLayout();
6908 KnownBits Known = computeKnownBits(V, DL, &AC, nullptr, &DT);
6909 if (Known.getBitWidth() != BitWidth)
6910 Known = Known.zextOrTrunc(BitWidth);
6911
6912 // ValueTracking may be able to compute a tighter result for the number of
6913 // sign bits than for the value of those sign bits.
6914 unsigned NS = ComputeNumSignBits(V, DL, &AC, nullptr, &DT);
6915 if (U->getType()->isPointerTy()) {
6916 // If the pointer size is larger than the index size type, this can cause
6917 // NS to be larger than BitWidth. So compensate for this.
6918 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
6919 int ptrIdxDiff = ptrSize - BitWidth;
6920 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
6921 NS -= ptrIdxDiff;
6922 }
6923
6924 if (NS > 1) {
6925 // If we know any of the sign bits, we know all of the sign bits.
6926 if (!Known.Zero.getHiBits(NS).isZero())
6927 Known.Zero.setHighBits(NS);
6928 if (!Known.One.getHiBits(NS).isZero())
6929 Known.One.setHighBits(NS);
6930 }
6931
6932 if (Known.getMinValue() != Known.getMaxValue() + 1)
6933 ConservativeResult = ConservativeResult.intersectWith(
6934 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6935 RangeType);
6936 if (NS > 1)
6937 ConservativeResult = ConservativeResult.intersectWith(
6938 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6939 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6940 RangeType);
6941
6942 if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
6943 // Strengthen the range if the underlying IR value is a
6944 // global/alloca/heap allocation using the size of the object.
6945 bool CanBeNull;
6946 uint64_t DerefBytes = V->getPointerDereferenceableBytes(
6947 DL, CanBeNull, /*CanBeFreed=*/nullptr);
6948 if (DerefBytes > 1 && isUIntN(BitWidth, DerefBytes)) {
6949 // The highest address the object can start is DerefBytes bytes before
6950 // the end (unsigned max value). If this value is not a multiple of the
6951 // alignment, the last possible start value is the next lowest multiple
6952 // of the alignment. Note: The computations below cannot overflow,
6953 // because if they would there's no possible start address for the
6954 // object.
6955 APInt MaxVal =
6956 APInt::getMaxValue(BitWidth) - APInt(BitWidth, DerefBytes);
6957 uint64_t Align = U->getValue()->getPointerAlignment(DL).value();
6958 uint64_t Rem = MaxVal.urem(Align);
6959 MaxVal -= APInt(BitWidth, Rem);
6960 APInt MinVal = APInt::getZero(BitWidth);
6961 if (llvm::isKnownNonZero(V, DL))
6962 MinVal = Align;
6963 ConservativeResult = ConservativeResult.intersectWith(
6964 ConstantRange::getNonEmpty(MinVal, MaxVal + 1), RangeType);
6965 }
6966 }
6967
6968 // A range of Phi is a subset of union of all ranges of its input.
6969 if (PHINode *Phi = dyn_cast<PHINode>(V)) {
6970 // SCEVExpander sometimes creates SCEVUnknowns that are secretly
6971 // AddRecs; return the range for the corresponding AddRec.
6972 if (auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V)))
6973 return getRangeRef(AR, SignHint, Depth + 1);
6974
6975 // Make sure that we do not run over cycled Phis.
6976 if (RangeRefPHIAllowedOperands(DT, Phi)) {
6977 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6978
6979 for (const auto &Op : Phi->operands()) {
6980 auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
6981 RangeFromOps = RangeFromOps.unionWith(OpRange);
6982 // No point to continue if we already have a full set.
6983 if (RangeFromOps.isFullSet())
6984 break;
6985 }
6986 ConservativeResult =
6987 ConservativeResult.intersectWith(RangeFromOps, RangeType);
6988 }
6989 }
6990
6991 // vscale can't be equal to zero
6992 if (const auto *II = dyn_cast<IntrinsicInst>(V))
6993 if (II->getIntrinsicID() == Intrinsic::vscale) {
6994 ConstantRange Disallowed = APInt::getZero(BitWidth);
6995 ConservativeResult = ConservativeResult.difference(Disallowed);
6996 }
6997
6998 return setRange(U, SignHint, std::move(ConservativeResult));
6999 }
7000 case scCouldNotCompute:
7001 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
7002 }
7003
7004 return setRange(S, SignHint, std::move(ConservativeResult));
7005}
7006
7007// Given a StartRange, Step and MaxBECount for an expression compute a range of
7008// values that the expression can take. Initially, the expression has a value
7009// from StartRange and then is changed by Step up to MaxBECount times. Signed
7010// argument defines if we treat Step as signed or unsigned. The second return
7011// value indicates that no wrapping occurred.
7012static std::pair<ConstantRange, bool>
7014 const APInt &MaxBECount, bool Signed) {
7015 unsigned BitWidth = Step.getBitWidth();
7016 assert(BitWidth == StartRange.getBitWidth() &&
7017 BitWidth == MaxBECount.getBitWidth() && "mismatched bit widths");
7018 // If either Step or MaxBECount is 0, then the expression won't change, and we
7019 // just need to return the initial range.
7020 if (Step == 0 || MaxBECount == 0)
7021 return {StartRange, true};
7022
7023 // If we don't know anything about the initial value (i.e. StartRange is
7024 // FullRange), then we don't know anything about the final range either.
7025 // Return FullRange.
7026 if (StartRange.isFullSet())
7027 return {ConstantRange::getFull(BitWidth), false};
7028
7029 // If Step is signed and negative, then we use its absolute value, but we also
7030 // note that we're moving in the opposite direction.
7031 bool Descending = Signed && Step.isNegative();
7032
7033 if (Signed)
7034 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
7035 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
7036 // This equations hold true due to the well-defined wrap-around behavior of
7037 // APInt.
7038 Step = Step.abs();
7039
7040 // Check if Offset is more than full span of BitWidth. If it is, the
7041 // expression is guaranteed to overflow.
7042 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
7043 return {ConstantRange::getFull(BitWidth), false};
7044
7045 // Offset is by how much the expression can change. Checks above guarantee no
7046 // overflow here.
7047 APInt Offset = Step * MaxBECount;
7048
7049 // Minimum value of the final range will match the minimal value of StartRange
7050 // if the expression is increasing and will be decreased by Offset otherwise.
7051 // Maximum value of the final range will match the maximal value of StartRange
7052 // if the expression is decreasing and will be increased by Offset otherwise.
7053 APInt StartLower = StartRange.getLower();
7054 APInt StartUpper = StartRange.getUpper() - 1;
7055 bool Overflow;
7056 APInt MovedBoundary;
7057 if (Signed) {
7058 // This does not use sadd_ov, as we want to check overflow for a signed
7059 // start with an unsigned offset.
7060 if (Descending) {
7061 MovedBoundary = StartLower - std::move(Offset);
7062 Overflow = MovedBoundary.sgt(StartLower) || StartRange.isSignWrappedSet();
7063 } else {
7064 MovedBoundary = StartUpper + std::move(Offset);
7065 Overflow = MovedBoundary.slt(StartUpper) || StartRange.isSignWrappedSet();
7066 }
7067 } else {
7068 MovedBoundary = StartUpper.uadd_ov(std::move(Offset), Overflow);
7069 Overflow |= StartRange.isWrappedSet();
7070 }
7071
7072 // It's possible that the new minimum/maximum value will fall into the initial
7073 // range (due to wrap around). This means that the expression can take any
7074 // value in this bitwidth, and we have to return full range.
7075 if (StartRange.contains(MovedBoundary))
7076 return {ConstantRange::getFull(BitWidth), false};
7077
7078 APInt NewLower =
7079 Descending ? std::move(MovedBoundary) : std::move(StartLower);
7080 APInt NewUpper =
7081 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
7082 NewUpper += 1;
7083
7084 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
7085 return {ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)),
7086 !Overflow};
7087}
7088
7089std::pair<ConstantRange, SCEV::NoWrapFlags>
7090ScalarEvolution::getRangeForAffineAR(const SCEV *Start, const SCEV *Step,
7091 const APInt &MaxBECount) {
7092 assert(getTypeSizeInBits(Start->getType()) ==
7093 getTypeSizeInBits(Step->getType()) &&
7094 getTypeSizeInBits(Start->getType()) == MaxBECount.getBitWidth() &&
7095 "mismatched bit widths");
7096
7097 // First, consider step signed.
7098 ConstantRange StartSRange = getSignedRange(Start);
7099 ConstantRange StepSRange = getSignedRange(Step);
7100
7101 // If Step can be both positive and negative, we need to find ranges for the
7102 // maximum absolute step values in both directions and union them.
7103 auto [SR1, NSW1] = getRangeForAffineARHelper(
7104 StepSRange.getSignedMin(), StartSRange, MaxBECount, /*Signed=*/true);
7105 auto [SR2, NSW2] = getRangeForAffineARHelper(StepSRange.getSignedMax(),
7106 StartSRange, MaxBECount,
7107 /*Signed=*/true);
7108 ConstantRange SR = SR1.unionWith(SR2);
7109
7110 // Next, consider step unsigned.
7111 auto [UR, NUW] = getRangeForAffineARHelper(
7112 getUnsignedRangeMax(Step), getUnsignedRange(Start), MaxBECount,
7113 /*Signed=*/false);
7114
7116 if (NUW)
7118 if (NSW1 && NSW2)
7120
7121 // Finally, intersect signed and unsigned ranges.
7123}
7124
7125ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
7126 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
7127 ScalarEvolution::RangeSignHint SignHint) {
7128 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
7129 assert(AddRec->hasNoSelfWrap() &&
7130 "This only works for non-self-wrapping AddRecs!");
7131 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
7132 const SCEV *Step = AddRec->getStepRecurrence(*this);
7133 // Only deal with constant step to save compile time.
7134 if (!isa<SCEVConstant>(Step))
7135 return ConstantRange::getFull(BitWidth);
7136 // Let's make sure that we can prove that we do not self-wrap during
7137 // MaxBECount iterations. We need this because MaxBECount is a maximum
7138 // iteration count estimate, and we might infer nw from some exit for which we
7139 // do not know max exit count (or any other side reasoning).
7140 // TODO: Turn into assert at some point.
7141 if (getTypeSizeInBits(MaxBECount->getType()) >
7142 getTypeSizeInBits(AddRec->getType()))
7143 return ConstantRange::getFull(BitWidth);
7144 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
7145 const SCEV *RangeWidth = getMinusOne(AddRec->getType());
7146 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
7147 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
7148 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
7149 MaxItersWithoutWrap))
7150 return ConstantRange::getFull(BitWidth);
7151
7152 ICmpInst::Predicate LEPred =
7154 ICmpInst::Predicate GEPred =
7156 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7157
7158 // We know that there is no self-wrap. Let's take Start and End values and
7159 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7160 // the iteration. They either lie inside the range [Min(Start, End),
7161 // Max(Start, End)] or outside it:
7162 //
7163 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
7164 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
7165 //
7166 // No self wrap flag guarantees that the intermediate values cannot be BOTH
7167 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7168 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7169 // Start <= End and step is positive, or Start >= End and step is negative.
7170 const SCEV *Start = applyLoopGuards(AddRec->getStart(), AddRec->getLoop());
7171 ConstantRange StartRange = getRangeRef(Start, SignHint);
7172 ConstantRange EndRange = getRangeRef(End, SignHint);
7173 ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7174 // If they already cover full iteration space, we will know nothing useful
7175 // even if we prove what we want to prove.
7176 if (RangeBetween.isFullSet())
7177 return RangeBetween;
7178 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7179 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7180 : RangeBetween.isWrappedSet();
7181 if (IsWrappedSet)
7182 return ConstantRange::getFull(BitWidth);
7183
7184 if (isKnownPositive(Step) &&
7185 isKnownPredicateViaConstantRanges(LEPred, Start, End))
7186 return RangeBetween;
7187 if (isKnownNegative(Step) &&
7188 isKnownPredicateViaConstantRanges(GEPred, Start, End))
7189 return RangeBetween;
7190 return ConstantRange::getFull(BitWidth);
7191}
7192
7193ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7194 const SCEV *Step,
7195 const APInt &MaxBECount) {
7196 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7197 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7198
7199 unsigned BitWidth = MaxBECount.getBitWidth();
7200 assert(getTypeSizeInBits(Start->getType()) == BitWidth &&
7201 getTypeSizeInBits(Step->getType()) == BitWidth &&
7202 "mismatched bit widths");
7203
7204 struct SelectPattern {
7205 Value *Condition = nullptr;
7206 APInt TrueValue;
7207 APInt FalseValue;
7208
7209 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7210 const SCEV *S) {
7211 std::optional<unsigned> CastOp;
7212 APInt Offset(BitWidth, 0);
7213
7215 "Should be!");
7216
7217 // Peel off a constant offset. In the future we could consider being
7218 // smarter here and handle {Start+Step,+,Step} too.
7219 const APInt *Off;
7220 if (match(S, m_scev_Add(m_scev_APInt(Off), m_SCEV(S))))
7221 Offset = *Off;
7222
7223 // Peel off a cast operation
7224 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7225 CastOp = SCast->getSCEVType();
7226 S = SCast->getOperand();
7227 }
7228
7229 using namespace llvm::PatternMatch;
7230
7231 auto *SU = dyn_cast<SCEVUnknown>(S);
7232 const APInt *TrueVal, *FalseVal;
7233 if (!SU ||
7234 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7235 m_APInt(FalseVal)))) {
7236 Condition = nullptr;
7237 return;
7238 }
7239
7240 TrueValue = *TrueVal;
7241 FalseValue = *FalseVal;
7242
7243 // Re-apply the cast we peeled off earlier
7244 if (CastOp)
7245 switch (*CastOp) {
7246 default:
7247 llvm_unreachable("Unknown SCEV cast type!");
7248
7249 case scTruncate:
7250 TrueValue = TrueValue.trunc(BitWidth);
7251 FalseValue = FalseValue.trunc(BitWidth);
7252 break;
7253 case scZeroExtend:
7254 TrueValue = TrueValue.zext(BitWidth);
7255 FalseValue = FalseValue.zext(BitWidth);
7256 break;
7257 case scSignExtend:
7258 TrueValue = TrueValue.sext(BitWidth);
7259 FalseValue = FalseValue.sext(BitWidth);
7260 break;
7261 }
7262
7263 // Re-apply the constant offset we peeled off earlier
7264 TrueValue += Offset;
7265 FalseValue += Offset;
7266 }
7267
7268 bool isRecognized() { return Condition != nullptr; }
7269 };
7270
7271 SelectPattern StartPattern(*this, BitWidth, Start);
7272 if (!StartPattern.isRecognized())
7273 return ConstantRange::getFull(BitWidth);
7274
7275 SelectPattern StepPattern(*this, BitWidth, Step);
7276 if (!StepPattern.isRecognized())
7277 return ConstantRange::getFull(BitWidth);
7278
7279 if (StartPattern.Condition != StepPattern.Condition) {
7280 // We don't handle this case today; but we could, by considering four
7281 // possibilities below instead of two. I'm not sure if there are cases where
7282 // that will help over what getRange already does, though.
7283 return ConstantRange::getFull(BitWidth);
7284 }
7285
7286 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7287 // construct arbitrary general SCEV expressions here. This function is called
7288 // from deep in the call stack, and calling getSCEV (on a sext instruction,
7289 // say) can end up caching a suboptimal value.
7290
7291 // FIXME: without the explicit `this` receiver below, MSVC errors out with
7292 // C2352 and C2512 (otherwise it isn't needed).
7293
7294 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7295 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7296 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7297 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7298
7299 ConstantRange TrueRange =
7300 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount).first;
7301 ConstantRange FalseRange =
7302 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount).first;
7303
7304 return TrueRange.unionWith(FalseRange);
7305}
7306
7307SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7308 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
7309 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7310
7311 // Return early if there are no flags to propagate to the SCEV.
7313 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(BinOp);
7314 PDI && PDI->isDisjoint()) {
7316 } else {
7317 if (BinOp->hasNoUnsignedWrap())
7319 if (BinOp->hasNoSignedWrap())
7321 }
7322 if (Flags == SCEV::FlagAnyWrap)
7323 return SCEV::FlagAnyWrap;
7324
7325 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
7326}
7327
7328const Instruction *
7329ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7330 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7331 return &*AddRec->getLoop()->getHeader()->begin();
7332 if (auto *U = dyn_cast<SCEVUnknown>(S))
7333 if (auto *I = dyn_cast<Instruction>(U->getValue()))
7334 return I;
7335 return nullptr;
7336}
7337
7338const Instruction *ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops,
7339 bool &Precise) {
7340 Precise = true;
7341 // Do a bounded search of the def relation of the requested SCEVs.
7342 SmallPtrSet<const SCEV *, 16> Visited;
7343 SmallVector<SCEVUse> Worklist;
7344 auto pushOp = [&](const SCEV *S) {
7345 if (!Visited.insert(S).second)
7346 return;
7347 // Threshold of 30 here is arbitrary.
7348 if (Visited.size() > 30) {
7349 Precise = false;
7350 return;
7351 }
7352 Worklist.push_back(S);
7353 };
7354
7355 for (SCEVUse S : Ops)
7356 pushOp(S);
7357
7358 const Instruction *Bound = nullptr;
7359 while (!Worklist.empty()) {
7360 SCEVUse S = Worklist.pop_back_val();
7361 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7362 if (!Bound || DT.dominates(Bound, DefI))
7363 Bound = DefI;
7364 } else {
7365 for (SCEVUse Op : S->operands())
7366 pushOp(Op);
7367 }
7368 }
7369 return Bound ? Bound : &*F.getEntryBlock().begin();
7370}
7371
7372const Instruction *
7373ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops) {
7374 bool Discard;
7375 return getDefiningScopeBound(Ops, Discard);
7376}
7377
7378bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7379 const Instruction *B) {
7380 if (A->getParent() == B->getParent() &&
7382 B->getIterator()))
7383 return true;
7384
7385 auto *BLoop = LI.getLoopFor(B->getParent());
7386 if (BLoop && BLoop->getHeader() == B->getParent() &&
7387 BLoop->getLoopPreheader() == A->getParent() &&
7389 A->getParent()->end()) &&
7390 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7391 B->getIterator()))
7392 return true;
7393 return false;
7394}
7395
7397 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ true);
7398 visitAll(Op, PC);
7399 return PC.MaybePoison.empty();
7400}
7401
7402bool ScalarEvolution::isGuaranteedNotToCauseUB(const SCEV *Op) {
7403 return !SCEVExprContains(Op, [this](const SCEV *S) {
7404 const SCEV *Op1;
7405 bool M = match(S, m_scev_UDiv(m_SCEV(), m_SCEV(Op1)));
7406 // The UDiv may be UB if the divisor is poison or zero. Unless the divisor
7407 // is a non-zero constant, we have to assume the UDiv may be UB.
7408 return M && (!isKnownNonZero(Op1) || !isGuaranteedNotToBePoison(Op1));
7409 });
7410}
7411
7412bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7413 // Only proceed if we can prove that I does not yield poison.
7415 return false;
7416
7417 // At this point we know that if I is executed, then it does not wrap
7418 // according to at least one of NSW or NUW. If I is not executed, then we do
7419 // not know if the calculation that I represents would wrap. Multiple
7420 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7421 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7422 // derived from other instructions that map to the same SCEV. We cannot make
7423 // that guarantee for cases where I is not executed. So we need to find a
7424 // upper bound on the defining scope for the SCEV, and prove that I is
7425 // executed every time we enter that scope. When the bounding scope is a
7426 // loop (the common case), this is equivalent to proving I executes on every
7427 // iteration of that loop.
7428 SmallVector<SCEVUse> SCEVOps;
7429 for (const Use &Op : I->operands()) {
7430 // I could be an extractvalue from a call to an overflow intrinsic.
7431 // TODO: We can do better here in some cases.
7432 if (isSCEVable(Op->getType()))
7433 SCEVOps.push_back(getSCEV(Op));
7434 }
7435 auto *DefI = getDefiningScopeBound(SCEVOps);
7436 return isGuaranteedToTransferExecutionTo(DefI, I);
7437}
7438
7439bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7440 // If we know that \c I can never be poison period, then that's enough.
7441 if (isSCEVExprNeverPoison(I))
7442 return true;
7443
7444 // If the loop only has one exit, then we know that, if the loop is entered,
7445 // any instruction dominating that exit will be executed. If any such
7446 // instruction would result in UB, the addrec cannot be poison.
7447 //
7448 // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7449 // also handles uses outside the loop header (they just need to dominate the
7450 // single exit).
7451
7452 auto *ExitingBB = L->getExitingBlock();
7453 if (!ExitingBB || !loopHasNoAbnormalExits(L))
7454 return false;
7455
7456 SmallPtrSet<const Value *, 16> KnownPoison;
7458
7459 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
7460 // things that are known to be poison under that assumption go on the
7461 // Worklist.
7462 KnownPoison.insert(I);
7463 Worklist.push_back(I);
7464
7465 while (!Worklist.empty()) {
7466 const Instruction *Poison = Worklist.pop_back_val();
7467
7468 for (const Use &U : Poison->uses()) {
7469 const Instruction *PoisonUser = cast<Instruction>(U.getUser());
7470 if (mustTriggerUB(PoisonUser, KnownPoison) &&
7471 DT.dominates(PoisonUser->getParent(), ExitingBB))
7472 return true;
7473
7474 if (propagatesPoison(U) && L->contains(PoisonUser))
7475 if (KnownPoison.insert(PoisonUser).second)
7476 Worklist.push_back(PoisonUser);
7477 }
7478 }
7479
7480 return false;
7481}
7482
7483ScalarEvolution::LoopProperties
7484ScalarEvolution::getLoopProperties(const Loop *L) {
7485 using LoopProperties = ScalarEvolution::LoopProperties;
7486
7487 auto Itr = LoopPropertiesCache.find(L);
7488 if (Itr == LoopPropertiesCache.end()) {
7489 auto HasSideEffects = [](Instruction *I) {
7490 if (auto *SI = dyn_cast<StoreInst>(I))
7491 return !SI->isSimple();
7492
7493 if (I->mayThrow())
7494 return true;
7495
7496 // Non-volatile memset / memcpy do not count as side-effect for forward
7497 // progress.
7498 if (isa<MemIntrinsic>(I) && !I->isVolatile())
7499 return false;
7500
7501 return I->mayWriteToMemory();
7502 };
7503
7504 LoopProperties LP = {/* HasNoAbnormalExits */ true,
7505 /*HasNoSideEffects*/ true};
7506
7507 for (auto *BB : L->getBlocks())
7508 for (auto &I : *BB) {
7510 LP.HasNoAbnormalExits = false;
7511 if (HasSideEffects(&I))
7512 LP.HasNoSideEffects = false;
7513 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7514 break; // We're already as pessimistic as we can get.
7515 }
7516
7517 auto InsertPair = LoopPropertiesCache.insert({L, LP});
7518 assert(InsertPair.second && "We just checked!");
7519 Itr = InsertPair.first;
7520 }
7521
7522 return Itr->second;
7523}
7524
7526 // A mustprogress loop without side effects must be finite.
7527 // TODO: The check used here is very conservative. It's only *specific*
7528 // side effects which are well defined in infinite loops.
7529 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7530}
7531
7532const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7533 // Worklist item with a Value and a bool indicating whether all operands have
7534 // been visited already.
7537
7538 Stack.emplace_back(V, false);
7539 while (!Stack.empty()) {
7540 auto E = Stack.back();
7541 Value *CurV = E.getPointer();
7542
7543 if (getExistingSCEV(CurV)) {
7544 Stack.pop_back();
7545 continue;
7546 }
7547
7549 const SCEV *CreatedSCEV = nullptr;
7550 // If all operands have been visited already, create the SCEV.
7551 if (E.getInt()) {
7552 CreatedSCEV = createSCEV(CurV);
7553 } else {
7554 // Otherwise get the operands we need to create SCEV's for before creating
7555 // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7556 // just use it.
7557 CreatedSCEV = getOperandsToCreate(CurV, Ops);
7558 }
7559
7560 if (CreatedSCEV) {
7561 insertValueToMap(CurV, CreatedSCEV);
7562 Stack.pop_back();
7563 } else {
7564 Stack.back().setInt(true);
7565 // Queue its operands which need to be constructed.
7566 for (Value *Op : Ops)
7567 Stack.emplace_back(Op, false);
7568 }
7569 }
7570
7571 return getExistingSCEV(V);
7572}
7573
7574const SCEV *
7575ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7576 if (!isSCEVable(V->getType()))
7577 return getUnknown(V);
7578
7579 if (Instruction *I = dyn_cast<Instruction>(V)) {
7580 // Don't attempt to analyze instructions in blocks that aren't
7581 // reachable. Such instructions don't matter, and they aren't required
7582 // to obey basic rules for definitions dominating uses which this
7583 // analysis depends on.
7584 if (!DT.isReachableFromEntry(I->getParent()))
7585 return getUnknown(PoisonValue::get(V->getType()));
7586 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7587 return getConstant(CI);
7588 else if (isa<GlobalAlias>(V))
7589 return getUnknown(V);
7590 else if (!isa<ConstantExpr>(V))
7591 return getUnknown(V);
7592
7594 if (auto BO =
7596 bool IsConstArg = isa<ConstantInt>(BO->RHS);
7597 switch (BO->Opcode) {
7598 case Instruction::Add:
7599 case Instruction::Mul: {
7600 // For additions and multiplications, traverse add/mul chains for which we
7601 // can potentially create a single SCEV, to reduce the number of
7602 // get{Add,Mul}Expr calls.
7603 do {
7604 if (BO->Op) {
7605 if (BO->Op != V && getExistingSCEV(BO->Op)) {
7606 Ops.push_back(BO->Op);
7607 break;
7608 }
7609 }
7610 Ops.push_back(BO->RHS);
7611 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7613 if (!NewBO ||
7614 (BO->Opcode == Instruction::Add &&
7615 (NewBO->Opcode != Instruction::Add &&
7616 NewBO->Opcode != Instruction::Sub)) ||
7617 (BO->Opcode == Instruction::Mul &&
7618 NewBO->Opcode != Instruction::Mul)) {
7619 Ops.push_back(BO->LHS);
7620 break;
7621 }
7622 // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7623 // requires a SCEV for the LHS.
7624 if (BO->Op && (BO->IsNSW || BO->IsNUW)) {
7625 auto *I = dyn_cast<Instruction>(BO->Op);
7626 if (I && programUndefinedIfPoison(I)) {
7627 Ops.push_back(BO->LHS);
7628 break;
7629 }
7630 }
7631 BO = NewBO;
7632 } while (true);
7633 return nullptr;
7634 }
7635 case Instruction::Sub:
7636 case Instruction::UDiv:
7637 case Instruction::URem:
7638 break;
7639 case Instruction::AShr:
7640 case Instruction::Shl:
7641 case Instruction::Xor:
7642 if (!IsConstArg)
7643 return nullptr;
7644 break;
7645 case Instruction::And:
7646 case Instruction::Or:
7647 if (!IsConstArg && !BO->LHS->getType()->isIntegerTy(1))
7648 return nullptr;
7649 break;
7650 case Instruction::LShr:
7651 return getUnknown(V);
7652 default:
7653 llvm_unreachable("Unhandled binop");
7654 break;
7655 }
7656
7657 Ops.push_back(BO->LHS);
7658 Ops.push_back(BO->RHS);
7659 return nullptr;
7660 }
7661
7662 switch (U->getOpcode()) {
7663 case Instruction::Trunc:
7664 case Instruction::ZExt:
7665 case Instruction::SExt:
7666 case Instruction::PtrToAddr:
7667 case Instruction::PtrToInt:
7668 Ops.push_back(U->getOperand(0));
7669 return nullptr;
7670
7671 case Instruction::BitCast:
7672 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
7673 Ops.push_back(U->getOperand(0));
7674 return nullptr;
7675 }
7676 return getUnknown(V);
7677
7678 case Instruction::SDiv:
7679 case Instruction::SRem:
7680 Ops.push_back(U->getOperand(0));
7681 Ops.push_back(U->getOperand(1));
7682 return nullptr;
7683
7684 case Instruction::GetElementPtr:
7685 assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7686 "GEP source element type must be sized");
7687 llvm::append_range(Ops, U->operands());
7688 return nullptr;
7689
7690 case Instruction::IntToPtr:
7691 return getUnknown(V);
7692
7693 case Instruction::PHI:
7694 // getNodeForPHI has four ways to turn a PHI into a SCEV; retrieve the
7695 // relevant nodes for each of them.
7696 //
7697 // The first is just to call simplifyInstruction, and get something back
7698 // that isn't a PHI.
7699 if (Value *V = simplifyInstruction(
7700 cast<PHINode>(U),
7701 {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
7702 /*UseInstrInfo=*/true, /*CanUseUndef=*/false})) {
7703 assert(V);
7704 Ops.push_back(V);
7705 return nullptr;
7706 }
7707 // The second is createNodeForPHIWithIdenticalOperands: this looks for
7708 // operands which all perform the same operation, but haven't been
7709 // CSE'ed for whatever reason.
7710 if (BinaryOperator *BO = getCommonInstForPHI(cast<PHINode>(U))) {
7711 assert(BO);
7712 Ops.push_back(BO);
7713 return nullptr;
7714 }
7715 // The third is createNodeFromSelectLikePHI; this takes a PHI which
7716 // is equivalent to a select, and analyzes it like a select.
7717 {
7718 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
7720 assert(Cond);
7721 assert(LHS);
7722 assert(RHS);
7723 if (auto *CondICmp = dyn_cast<ICmpInst>(Cond)) {
7724 Ops.push_back(CondICmp->getOperand(0));
7725 Ops.push_back(CondICmp->getOperand(1));
7726 }
7727 Ops.push_back(Cond);
7728 Ops.push_back(LHS);
7729 Ops.push_back(RHS);
7730 return nullptr;
7731 }
7732 }
7733 // The fourth way is createAddRecFromPHI. It's complicated to handle here,
7734 // so just construct it recursively.
7735 //
7736 // In addition to getNodeForPHI, also construct nodes which might be needed
7737 // by getRangeRef.
7739 for (Value *V : cast<PHINode>(U)->operands())
7740 Ops.push_back(V);
7741 return nullptr;
7742 }
7743 return nullptr;
7744
7745 case Instruction::Select: {
7746 // Check if U is a select that can be simplified to a SCEVUnknown.
7747 auto CanSimplifyToUnknown = [this, U]() {
7748 if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
7749 return false;
7750
7751 auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
7752 if (!ICI)
7753 return false;
7754 Value *LHS = ICI->getOperand(0);
7755 Value *RHS = ICI->getOperand(1);
7756 if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7757 ICI->getPredicate() == CmpInst::ICMP_NE) {
7759 return true;
7760 } else if (getTypeSizeInBits(LHS->getType()) >
7761 getTypeSizeInBits(U->getType()))
7762 return true;
7763 return false;
7764 };
7765 if (CanSimplifyToUnknown())
7766 return getUnknown(U);
7767
7768 llvm::append_range(Ops, U->operands());
7769 return nullptr;
7770 break;
7771 }
7772 case Instruction::Call:
7773 case Instruction::Invoke:
7774 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7775 Ops.push_back(RV);
7776 return nullptr;
7777 }
7778
7779 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7780 switch (II->getIntrinsicID()) {
7781 case Intrinsic::abs:
7782 Ops.push_back(II->getArgOperand(0));
7783 return nullptr;
7784 case Intrinsic::umax:
7785 case Intrinsic::umin:
7786 case Intrinsic::smax:
7787 case Intrinsic::smin:
7788 case Intrinsic::usub_sat:
7789 case Intrinsic::uadd_sat:
7790 Ops.push_back(II->getArgOperand(0));
7791 Ops.push_back(II->getArgOperand(1));
7792 return nullptr;
7793 case Intrinsic::start_loop_iterations:
7794 case Intrinsic::annotation:
7795 case Intrinsic::ptr_annotation:
7796 Ops.push_back(II->getArgOperand(0));
7797 return nullptr;
7798 default:
7799 break;
7800 }
7801 }
7802 break;
7803 }
7804
7805 return nullptr;
7806}
7807
7808const SCEV *ScalarEvolution::createSCEV(Value *V) {
7809 if (!isSCEVable(V->getType()))
7810 return getUnknown(V);
7811
7812 if (Instruction *I = dyn_cast<Instruction>(V)) {
7813 // Don't attempt to analyze instructions in blocks that aren't
7814 // reachable. Such instructions don't matter, and they aren't required
7815 // to obey basic rules for definitions dominating uses which this
7816 // analysis depends on.
7817 if (!DT.isReachableFromEntry(I->getParent()))
7818 return getUnknown(PoisonValue::get(V->getType()));
7819 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7820 return getConstant(CI);
7821 else if (isa<GlobalAlias>(V))
7822 return getUnknown(V);
7823 else if (!isa<ConstantExpr>(V))
7824 return getUnknown(V);
7825
7826 const SCEV *LHS;
7827 const SCEV *RHS;
7828
7830 if (auto BO =
7832 switch (BO->Opcode) {
7833 case Instruction::Add: {
7834 // The simple thing to do would be to just call getSCEV on both operands
7835 // and call getAddExpr with the result. However if we're looking at a
7836 // bunch of things all added together, this can be quite inefficient,
7837 // because it leads to N-1 getAddExpr calls for N ultimate operands.
7838 // Instead, gather up all the operands and make a single getAddExpr call.
7839 // LLVM IR canonical form means we need only traverse the left operands.
7841 do {
7842 if (BO->Op) {
7843 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7844 AddOps.push_back(OpSCEV);
7845 break;
7846 }
7847
7848 // If a NUW or NSW flag can be applied to the SCEV for this
7849 // addition, then compute the SCEV for this addition by itself
7850 // with a separate call to getAddExpr. We need to do that
7851 // instead of pushing the operands of the addition onto AddOps,
7852 // since the flags are only known to apply to this particular
7853 // addition - they may not apply to other additions that can be
7854 // formed with operands from AddOps.
7855 const SCEV *RHS = getSCEV(BO->RHS);
7856 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7857 if (Flags != SCEV::FlagAnyWrap) {
7858 const SCEV *LHS = getSCEV(BO->LHS);
7859 if (BO->Opcode == Instruction::Sub)
7860 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7861 else
7862 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7863 break;
7864 }
7865 }
7866
7867 if (BO->Opcode == Instruction::Sub)
7868 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7869 else
7870 AddOps.push_back(getSCEV(BO->RHS));
7871
7872 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7874 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7875 NewBO->Opcode != Instruction::Sub)) {
7876 AddOps.push_back(getSCEV(BO->LHS));
7877 break;
7878 }
7879 BO = NewBO;
7880 } while (true);
7881
7882 return getAddExpr(AddOps);
7883 }
7884
7885 case Instruction::Mul: {
7887 do {
7888 if (BO->Op) {
7889 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7890 MulOps.push_back(OpSCEV);
7891 break;
7892 }
7893
7894 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7895 if (Flags != SCEV::FlagAnyWrap) {
7896 LHS = getSCEV(BO->LHS);
7897 RHS = getSCEV(BO->RHS);
7898 MulOps.push_back(getMulExpr(LHS, RHS, Flags));
7899 break;
7900 }
7901 }
7902
7903 MulOps.push_back(getSCEV(BO->RHS));
7904 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7906 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7907 MulOps.push_back(getSCEV(BO->LHS));
7908 break;
7909 }
7910 BO = NewBO;
7911 } while (true);
7912
7913 return getMulExpr(MulOps);
7914 }
7915 case Instruction::UDiv:
7916 LHS = getSCEV(BO->LHS);
7917 RHS = getSCEV(BO->RHS);
7918 return getUDivExpr(LHS, RHS);
7919 case Instruction::URem:
7920 LHS = getSCEV(BO->LHS);
7921 RHS = getSCEV(BO->RHS);
7922 return getURemExpr(LHS, RHS);
7923 case Instruction::Sub: {
7925 if (BO->Op)
7926 Flags = getNoWrapFlagsFromUB(BO->Op);
7927
7928 // Try to use ptrtoaddr for subtracts with at least one ptrtoint
7929 // operand. While we don't model ptrtoint directly in SCEV, the
7930 // difference between two pointer addresses is well-defined.
7931 Value *PtrLHS = nullptr, *PtrRHS = nullptr;
7932 bool HasPtrLHS = match(BO->LHS, m_PtrToInt(m_Value(PtrLHS)));
7933 bool HasPtrRHS = match(BO->RHS, m_PtrToInt(m_Value(PtrRHS)));
7934 if (HasPtrLHS || HasPtrRHS) {
7935 // Convert a ptrtoint operand (OrigOp) to ptrtoaddr of its pointer
7936 // PtrOp. When only one side is ptrtoint (BothPtr is false), skip
7937 // SCEVUnknown pointers since wrapping them in ptrtoaddr adds no
7938 // useful structure.
7939 auto GetOp = [&](bool HasPtr, Value *PtrOp, Value *OrigOp,
7940 bool BothPtr) -> const SCEV * {
7941 if (!HasPtr)
7942 return getSCEV(OrigOp);
7943 const SCEV *PtrSCEV = getSCEV(PtrOp);
7944 if (BothPtr || !isa<SCEVUnknown>(PtrSCEV)) {
7945 const SCEV *Addr = getPtrToAddrExpr(PtrSCEV);
7946 if (!isa<SCEVCouldNotCompute>(Addr) &&
7947 getTypeSizeInBits(OrigOp->getType()) <=
7948 getTypeSizeInBits(Addr->getType()))
7949 return getTruncateOrNoop(Addr, OrigOp->getType());
7950 }
7951 return getSCEV(OrigOp);
7952 };
7953 const SCEV *L = GetOp(HasPtrLHS, PtrLHS, BO->LHS, HasPtrRHS);
7954 const SCEV *R = GetOp(HasPtrRHS, PtrRHS, BO->RHS, HasPtrLHS);
7955 return getMinusSCEV(L, R, Flags);
7956 }
7957
7958 LHS = getSCEV(BO->LHS);
7959 RHS = getSCEV(BO->RHS);
7960 return getMinusSCEV(LHS, RHS, Flags);
7961 }
7962 case Instruction::And:
7963 // For an expression like x&255 that merely masks off the high bits,
7964 // use zext(trunc(x)) as the SCEV expression.
7965 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7966 if (CI->isZero())
7967 return getSCEV(BO->RHS);
7968 if (CI->isMinusOne())
7969 return getSCEV(BO->LHS);
7970 const APInt &A = CI->getValue();
7971
7972 // Instcombine's ShrinkDemandedConstant may strip bits out of
7973 // constants, obscuring what would otherwise be a low-bits mask.
7974 // Use computeKnownBits to compute what ShrinkDemandedConstant
7975 // knew about to reconstruct a low-bits mask value.
7976 unsigned LZ = A.countl_zero();
7977 unsigned TZ = A.countr_zero();
7978 unsigned BitWidth = A.getBitWidth();
7979 KnownBits Known(BitWidth);
7980 computeKnownBits(BO->LHS, Known, getDataLayout(), &AC, nullptr, &DT);
7981
7982 APInt EffectiveMask =
7983 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
7984 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
7985 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
7986 const SCEV *LHS = getSCEV(BO->LHS);
7987 const SCEV *ShiftedLHS = nullptr;
7988 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
7989 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
7990 // For an expression like (x * 8) & 8, simplify the multiply.
7991 unsigned MulZeros = OpC->getAPInt().countr_zero();
7992 unsigned GCD = std::min(MulZeros, TZ);
7993 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
7995 MulOps.push_back(getConstant(OpC->getAPInt().ashr(GCD)));
7996 append_range(MulOps, LHSMul->operands().drop_front());
7997 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
7998 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
7999 }
8000 }
8001 if (!ShiftedLHS)
8002 ShiftedLHS = getUDivExpr(LHS, MulCount);
8003 return getMulExpr(
8005 getTruncateExpr(ShiftedLHS,
8006 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
8007 BO->LHS->getType()),
8008 MulCount);
8009 }
8010 }
8011 // Binary `and` is a bit-wise `umin`.
8012 if (BO->LHS->getType()->isIntegerTy(1)) {
8013 LHS = getSCEV(BO->LHS);
8014 RHS = getSCEV(BO->RHS);
8015 return getUMinExpr(LHS, RHS);
8016 }
8017 break;
8018
8019 case Instruction::Or:
8020 // Binary `or` is a bit-wise `umax`.
8021 if (BO->LHS->getType()->isIntegerTy(1)) {
8022 LHS = getSCEV(BO->LHS);
8023 RHS = getSCEV(BO->RHS);
8024 return getUMaxExpr(LHS, RHS);
8025 }
8026 break;
8027
8028 case Instruction::Xor:
8029 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
8030 // If the RHS of xor is -1, then this is a not operation.
8031 if (CI->isMinusOne())
8032 return getNotSCEV(getSCEV(BO->LHS));
8033
8034 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
8035 // This is a variant of the check for xor with -1, and it handles
8036 // the case where instcombine has trimmed non-demanded bits out
8037 // of an xor with -1.
8038 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
8039 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
8040 if (LBO->getOpcode() == Instruction::And &&
8041 LCI->getValue() == CI->getValue())
8042 if (const SCEVZeroExtendExpr *Z =
8044 Type *UTy = BO->LHS->getType();
8045 const SCEV *Z0 = Z->getOperand();
8046 Type *Z0Ty = Z0->getType();
8047 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
8048
8049 // If C is a low-bits mask, the zero extend is serving to
8050 // mask off the high bits. Complement the operand and
8051 // re-apply the zext.
8052 if (CI->getValue().isMask(Z0TySize))
8053 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
8054
8055 // If C is a single bit, it may be in the sign-bit position
8056 // before the zero-extend. In this case, represent the xor
8057 // using an add, which is equivalent, and re-apply the zext.
8058 APInt Trunc = CI->getValue().trunc(Z0TySize);
8059 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
8060 Trunc.isSignMask())
8061 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
8062 UTy);
8063 }
8064 }
8065 break;
8066
8067 case Instruction::Shl:
8068 // Turn shift left of a constant amount into a multiply.
8069 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
8070 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
8071
8072 // If the shift count is not less than the bitwidth, the result of
8073 // the shift is undefined. Don't try to analyze it, because the
8074 // resolution chosen here may differ from the resolution chosen in
8075 // other parts of the compiler.
8076 if (SA->getValue().uge(BitWidth))
8077 break;
8078
8079 // We can safely preserve the nuw flag in all cases. It's also safe to
8080 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
8081 // requires special handling. It can be preserved as long as we're not
8082 // left shifting by bitwidth - 1.
8083 auto Flags = SCEV::FlagAnyWrap;
8084 if (BO->Op) {
8085 auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
8086 if (any(MulFlags & SCEV::FlagNSW) &&
8087 (any(MulFlags & SCEV::FlagNUW) ||
8088 SA->getValue().ult(BitWidth - 1)))
8090 if (any(MulFlags & SCEV::FlagNUW))
8092 }
8093
8094 ConstantInt *X = ConstantInt::get(
8095 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
8096 return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
8097 }
8098 break;
8099
8100 case Instruction::AShr:
8101 // AShr X, C, where C is a constant.
8102 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
8103 if (!CI)
8104 break;
8105
8106 Type *OuterTy = BO->LHS->getType();
8108 // If the shift count is not less than the bitwidth, the result of
8109 // the shift is undefined. Don't try to analyze it, because the
8110 // resolution chosen here may differ from the resolution chosen in
8111 // other parts of the compiler.
8112 if (CI->getValue().uge(BitWidth))
8113 break;
8114
8115 if (CI->isZero())
8116 return getSCEV(BO->LHS); // shift by zero --> noop
8117
8118 uint64_t AShrAmt = CI->getZExtValue();
8119 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
8120
8121 Operator *L = dyn_cast<Operator>(BO->LHS);
8122 const SCEV *AddTruncateExpr = nullptr;
8123 ConstantInt *ShlAmtCI = nullptr;
8124 const SCEV *AddConstant = nullptr;
8125
8126 if (L && L->getOpcode() == Instruction::Add) {
8127 // X = Shl A, n
8128 // Y = Add X, c
8129 // Z = AShr Y, m
8130 // n, c and m are constants.
8131
8132 Operator *LShift = dyn_cast<Operator>(L->getOperand(0));
8133 ConstantInt *AddOperandCI = dyn_cast<ConstantInt>(L->getOperand(1));
8134 if (LShift && LShift->getOpcode() == Instruction::Shl) {
8135 if (AddOperandCI) {
8136 const SCEV *ShlOp0SCEV = getSCEV(LShift->getOperand(0));
8137 ShlAmtCI = dyn_cast<ConstantInt>(LShift->getOperand(1));
8138 // since we truncate to TruncTy, the AddConstant should be of the
8139 // same type, so create a new Constant with type same as TruncTy.
8140 // Also, the Add constant should be shifted right by AShr amount.
8141 APInt AddOperand = AddOperandCI->getValue().ashr(AShrAmt);
8142 AddConstant = getConstant(AddOperand.trunc(BitWidth - AShrAmt));
8143 // we model the expression as sext(add(trunc(A), c << n)), since the
8144 // sext(trunc) part is already handled below, we create a
8145 // AddExpr(TruncExp) which will be used later.
8146 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8147 }
8148 }
8149 } else if (L && L->getOpcode() == Instruction::Shl) {
8150 // X = Shl A, n
8151 // Y = AShr X, m
8152 // Both n and m are constant.
8153
8154 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
8155 ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
8156 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8157 }
8158
8159 if (AddTruncateExpr && ShlAmtCI) {
8160 // We can merge the two given cases into a single SCEV statement,
8161 // incase n = m, the mul expression will be 2^0, so it gets resolved to
8162 // a simpler case. The following code handles the two cases:
8163 //
8164 // 1) For a two-shift sext-inreg, i.e. n = m,
8165 // use sext(trunc(x)) as the SCEV expression.
8166 //
8167 // 2) When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
8168 // expression. We already checked that ShlAmt < BitWidth, so
8169 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
8170 // ShlAmt - AShrAmt < Amt.
8171 const APInt &ShlAmt = ShlAmtCI->getValue();
8172 if (ShlAmt.ult(BitWidth) && ShlAmt.uge(AShrAmt)) {
8173 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
8174 ShlAmtCI->getZExtValue() - AShrAmt);
8175 const SCEV *CompositeExpr =
8176 getMulExpr(AddTruncateExpr, getConstant(Mul));
8177 if (L->getOpcode() != Instruction::Shl)
8178 CompositeExpr = getAddExpr(CompositeExpr, AddConstant);
8179
8180 return getSignExtendExpr(CompositeExpr, OuterTy);
8181 }
8182 }
8183 break;
8184 }
8185 }
8186
8187 switch (U->getOpcode()) {
8188 case Instruction::Trunc:
8189 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
8190
8191 case Instruction::ZExt:
8192 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8193
8194 case Instruction::SExt:
8195 if (auto BO = MatchBinaryOp(U->getOperand(0), getDataLayout(), AC, DT,
8197 // The NSW flag of a subtract does not always survive the conversion to
8198 // A + (-1)*B. By pushing sign extension onto its operands we are much
8199 // more likely to preserve NSW and allow later AddRec optimisations.
8200 //
8201 // NOTE: This is effectively duplicating this logic from getSignExtend:
8202 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
8203 // but by that point the NSW information has potentially been lost.
8204 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
8205 Type *Ty = U->getType();
8206 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
8207 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
8208 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
8209 }
8210 }
8211 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8212
8213 case Instruction::BitCast:
8214 // BitCasts are no-op casts so we just eliminate the cast.
8215 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
8216 return getSCEV(U->getOperand(0));
8217 break;
8218
8219 case Instruction::PtrToAddr: {
8220 const SCEV *IntOp = getPtrToAddrExpr(getSCEV(U->getOperand(0)));
8221 if (isa<SCEVCouldNotCompute>(IntOp))
8222 return getUnknown(V);
8223 return IntOp;
8224 }
8225
8226 case Instruction::PtrToInt:
8227 // SCEV only models ptrtoaddr.
8228 return getUnknown(V);
8229
8230 case Instruction::IntToPtr:
8231 // Just don't deal with inttoptr casts.
8232 return getUnknown(V);
8233
8234 case Instruction::SDiv:
8235 // If both operands are non-negative, this is just an udiv.
8236 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8237 isKnownNonNegative(getSCEV(U->getOperand(1))))
8238 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8239 break;
8240
8241 case Instruction::SRem:
8242 // If both operands are non-negative, this is just an urem.
8243 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8244 isKnownNonNegative(getSCEV(U->getOperand(1))))
8245 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8246 break;
8247
8248 case Instruction::GetElementPtr:
8249 return createNodeForGEP(cast<GEPOperator>(U));
8250
8251 case Instruction::PHI:
8252 return createNodeForPHI(cast<PHINode>(U));
8253
8254 case Instruction::Select:
8255 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
8256 U->getOperand(2));
8257
8258 case Instruction::Call:
8259 case Instruction::Invoke:
8260 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
8261 return getSCEV(RV);
8262
8263 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
8264 switch (II->getIntrinsicID()) {
8265 case Intrinsic::abs:
8266 return getAbsExpr(
8267 getSCEV(II->getArgOperand(0)),
8268 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
8269 case Intrinsic::umax:
8270 LHS = getSCEV(II->getArgOperand(0));
8271 RHS = getSCEV(II->getArgOperand(1));
8272 return getUMaxExpr(LHS, RHS);
8273 case Intrinsic::umin:
8274 LHS = getSCEV(II->getArgOperand(0));
8275 RHS = getSCEV(II->getArgOperand(1));
8276 return getUMinExpr(LHS, RHS);
8277 case Intrinsic::smax:
8278 LHS = getSCEV(II->getArgOperand(0));
8279 RHS = getSCEV(II->getArgOperand(1));
8280 return getSMaxExpr(LHS, RHS);
8281 case Intrinsic::smin:
8282 LHS = getSCEV(II->getArgOperand(0));
8283 RHS = getSCEV(II->getArgOperand(1));
8284 return getSMinExpr(LHS, RHS);
8285 case Intrinsic::usub_sat: {
8286 const SCEV *X = getSCEV(II->getArgOperand(0));
8287 const SCEV *Y = getSCEV(II->getArgOperand(1));
8288 const SCEV *ClampedY = getUMinExpr(X, Y);
8289 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
8290 }
8291 case Intrinsic::uadd_sat: {
8292 const SCEV *X = getSCEV(II->getArgOperand(0));
8293 const SCEV *Y = getSCEV(II->getArgOperand(1));
8294 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
8295 return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
8296 }
8297 case Intrinsic::start_loop_iterations:
8298 case Intrinsic::annotation:
8299 case Intrinsic::ptr_annotation:
8300 // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8301 // just eqivalent to the first operand for SCEV purposes.
8302 return getSCEV(II->getArgOperand(0));
8303 case Intrinsic::vscale:
8304 return getVScale(II->getType());
8305 default:
8306 break;
8307 }
8308 }
8309 break;
8310 }
8311
8312 return getUnknown(V);
8313}
8314
8315//===----------------------------------------------------------------------===//
8316// Iteration Count Computation Code
8317//
8318
8320 if (isa<SCEVCouldNotCompute>(ExitCount))
8321 return getCouldNotCompute();
8322
8323 auto *ExitCountType = ExitCount->getType();
8324 assert(ExitCountType->isIntegerTy());
8325 auto *EvalTy = Type::getIntNTy(ExitCountType->getContext(),
8326 1 + ExitCountType->getScalarSizeInBits());
8327 return getTripCountFromExitCount(ExitCount, EvalTy, nullptr);
8328}
8329
8331 Type *EvalTy,
8332 const Loop *L) {
8333 if (isa<SCEVCouldNotCompute>(ExitCount))
8334 return getCouldNotCompute();
8335
8336 unsigned ExitCountSize = getTypeSizeInBits(ExitCount->getType());
8337 unsigned EvalSize = EvalTy->getPrimitiveSizeInBits();
8338
8339 auto CanAddOneWithoutOverflow = [&]() {
8340 ConstantRange ExitCountRange =
8341 getRangeRef(ExitCount, RangeSignHint::HINT_RANGE_UNSIGNED);
8342 if (!ExitCountRange.contains(APInt::getMaxValue(ExitCountSize)))
8343 return true;
8344
8345 return L && isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
8346 getMinusOne(ExitCount->getType()));
8347 };
8348
8349 // If we need to zero extend the backedge count, check if we can add one to
8350 // it prior to zero extending without overflow. Provided this is safe, it
8351 // allows better simplification of the +1.
8352 if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8353 return getZeroExtendExpr(
8354 getAddExpr(ExitCount, getOne(ExitCount->getType())), EvalTy);
8355
8356 // Get the total trip count from the count by adding 1. This may wrap.
8357 return getAddExpr(getTruncateOrZeroExtend(ExitCount, EvalTy), getOne(EvalTy));
8358}
8359
8360static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8361 if (!ExitCount)
8362 return 0;
8363
8364 ConstantInt *ExitConst = ExitCount->getValue();
8365
8366 // Guard against huge trip counts.
8367 if (ExitConst->getValue().getActiveBits() > 32)
8368 return 0;
8369
8370 // In case of integer overflow, this returns 0, which is correct.
8371 return ((unsigned)ExitConst->getZExtValue()) + 1;
8372}
8373
8375 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
8376 return getConstantTripCount(ExitCount);
8377}
8378
8379unsigned
8381 const BasicBlock *ExitingBlock) {
8382 assert(ExitingBlock && "Must pass a non-null exiting block!");
8383 assert(L->isLoopExiting(ExitingBlock) &&
8384 "Exiting block must actually branch out of the loop!");
8385 const SCEVConstant *ExitCount =
8386 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
8387 return getConstantTripCount(ExitCount);
8388}
8389
8391 const Loop *L, SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8392
8393 const auto *MaxExitCount =
8394 Predicates ? getPredicatedConstantMaxBackedgeTakenCount(L, *Predicates)
8396 return getConstantTripCount(dyn_cast<SCEVConstant>(MaxExitCount));
8397}
8398
8400 SmallVector<BasicBlock *, 8> ExitingBlocks;
8401 L->getExitingBlocks(ExitingBlocks);
8402
8403 // An exit with an uncomputable exit count makes the result 1.
8404 if (ExitingBlocks.empty() ||
8405 any_of(ExitingBlocks, [this, L](BasicBlock *ExitingBB) {
8406 return isa<SCEVCouldNotCompute>(getExitCount(L, ExitingBB));
8407 }))
8408 return 1;
8409
8410 LoopGuards Guards = LoopGuards::collect(L, *this);
8411 unsigned Res = 0;
8412 for (BasicBlock *ExitingBB : ExitingBlocks)
8413 Res = std::gcd(
8414 Res, getSmallConstantTripMultiple(getExitCount(L, ExitingBB), Guards));
8415 return Res;
8416}
8417
8418unsigned
8420 const LoopGuards &Guards) {
8421 assert(!isa<SCEVCouldNotCompute>(ExitCount) && "Must be computable!");
8422
8423 // Get the trip count
8424 const SCEV *TCExpr =
8425 getTripCountFromExitCount(applyLoopGuards(ExitCount, Guards));
8426
8427 APInt Multiple = getNonZeroConstantMultiple(TCExpr);
8428 // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8429 // the greatest power of 2 divisor less than 2^32.
8430 return Multiple.getActiveBits() > 32
8431 ? 1U << std::min(31U, Multiple.countTrailingZeros())
8432 : (unsigned)Multiple.getZExtValue();
8433}
8434
8436 const SCEV *ExitCount) {
8437 if (isa<SCEVCouldNotCompute>(ExitCount))
8438 return 1;
8439
8440 return getSmallConstantTripMultiple(ExitCount, LoopGuards::collect(L, *this));
8441}
8442
8443/// Returns the largest constant divisor of the trip count of this loop as a
8444/// normal unsigned value, if possible. This means that the actual trip count is
8445/// always a multiple of the returned value (don't forget the trip count could
8446/// very well be zero as well!).
8447///
8448/// Returns 1 if the trip count is unknown or not guaranteed to be the
8449/// multiple of a constant (which is also the case if the trip count is simply
8450/// constant, use getSmallConstantTripCount for that case), Will also return 1
8451/// if the trip count is very large (>= 2^32).
8452///
8453/// As explained in the comments for getSmallConstantTripCount, this assumes
8454/// that control exits the loop via ExitingBlock.
8455unsigned
8457 const BasicBlock *ExitingBlock) {
8458 assert(ExitingBlock && "Must pass a non-null exiting block!");
8459 assert(L->isLoopExiting(ExitingBlock) &&
8460 "Exiting block must actually branch out of the loop!");
8461 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8462 return getSmallConstantTripMultiple(L, ExitCount);
8463}
8464
8466 const BasicBlock *ExitingBlock,
8467 ExitCountKind Kind) {
8468 switch (Kind) {
8469 case Exact:
8470 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8471 case SymbolicMaximum:
8472 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8473 case ConstantMaximum:
8474 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8475 };
8476 llvm_unreachable("Invalid ExitCountKind!");
8477}
8478
8480 const Loop *L, const BasicBlock *ExitingBlock,
8482 switch (Kind) {
8483 case Exact:
8484 return getPredicatedBackedgeTakenInfo(L).getExact(ExitingBlock, this,
8485 Predicates);
8486 case SymbolicMaximum:
8487 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this,
8488 Predicates);
8489 case ConstantMaximum:
8490 return getPredicatedBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this,
8491 Predicates);
8492 };
8493 llvm_unreachable("Invalid ExitCountKind!");
8494}
8495
8498 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8499}
8500
8502 ExitCountKind Kind) {
8503 switch (Kind) {
8504 case Exact:
8505 return getBackedgeTakenInfo(L).getExact(L, this);
8506 case ConstantMaximum:
8507 return getBackedgeTakenInfo(L).getConstantMax(this);
8508 case SymbolicMaximum:
8509 return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8510 };
8511 llvm_unreachable("Invalid ExitCountKind!");
8512}
8513
8516 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(L, this, &Preds);
8517}
8518
8521 return getPredicatedBackedgeTakenInfo(L).getConstantMax(this, &Preds);
8522}
8523
8525 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8526}
8527
8528/// Push PHI nodes in the header of the given loop onto the given Worklist.
8529static void PushLoopPHIs(const Loop *L,
8532 BasicBlock *Header = L->getHeader();
8533
8534 // Push all Loop-header PHIs onto the Worklist stack.
8535 for (PHINode &PN : Header->phis())
8536 if (Visited.insert(&PN).second)
8537 Worklist.push_back(&PN);
8538}
8539
8540ScalarEvolution::BackedgeTakenInfo &
8541ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8542 auto &BTI = getBackedgeTakenInfo(L);
8543 if (BTI.hasFullInfo())
8544 return BTI;
8545
8546 auto Pair = PredicatedBackedgeTakenCounts.try_emplace(L);
8547
8548 if (!Pair.second)
8549 return Pair.first->second;
8550
8551 BackedgeTakenInfo Result =
8552 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8553
8554 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8555}
8556
8557ScalarEvolution::BackedgeTakenInfo &
8558ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8559 // Initially insert an invalid entry for this loop. If the insertion
8560 // succeeds, proceed to actually compute a backedge-taken count and
8561 // update the value. The temporary CouldNotCompute value tells SCEV
8562 // code elsewhere that it shouldn't attempt to request a new
8563 // backedge-taken count, which could result in infinite recursion.
8564 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8565 BackedgeTakenCounts.try_emplace(L);
8566 if (!Pair.second)
8567 return Pair.first->second;
8568
8569 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8570 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8571 // must be cleared in this scope.
8572 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8573
8574 // Now that we know more about the trip count for this loop, forget any
8575 // existing SCEV values for PHI nodes in this loop since they are only
8576 // conservative estimates made without the benefit of trip count
8577 // information. This invalidation is not necessary for correctness, and is
8578 // only done to produce more precise results.
8579 if (Result.hasAnyInfo()) {
8580 // Invalidate any expression using an addrec in this loop.
8581 SmallVector<SCEVUse, 8> ToForget;
8582 auto LoopUsersIt = LoopUsers.find(L);
8583 if (LoopUsersIt != LoopUsers.end())
8584 append_range(ToForget, LoopUsersIt->second);
8585 forgetMemoizedResults(ToForget);
8586
8587 // Invalidate constant-evolved loop header phis.
8588 for (PHINode &PN : L->getHeader()->phis())
8589 ConstantEvolutionLoopExitValue.erase(&PN);
8590 }
8591
8592 // Re-lookup the insert position, since the call to
8593 // computeBackedgeTakenCount above could result in a
8594 // recusive call to getBackedgeTakenInfo (on a different
8595 // loop), which would invalidate the iterator computed
8596 // earlier.
8597 return BackedgeTakenCounts.find(L)->second = std::move(Result);
8598}
8599
8601 // This method is intended to forget all info about loops. It should
8602 // invalidate caches as if the following happened:
8603 // - The trip counts of all loops have changed arbitrarily
8604 // - Every llvm::Value has been updated in place to produce a different
8605 // result.
8606 BackedgeTakenCounts.clear();
8607 PredicatedBackedgeTakenCounts.clear();
8608 BECountUsers.clear();
8609 LoopPropertiesCache.clear();
8610 ConstantEvolutionLoopExitValue.clear();
8611 ValueExprMap.clear();
8612 ValuesAtScopes.clear();
8613 ValuesAtScopesUsers.clear();
8614 LoopDispositions.clear();
8615 BlockDispositions.clear();
8616 UnsignedRanges.clear();
8617 SignedRanges.clear();
8618 ExprValueMap.clear();
8619 HasRecMap.clear();
8620 ConstantMultipleCache.clear();
8621 PredicatedSCEVRewrites.clear();
8622 FoldCache.clear();
8623 FoldCacheUser.clear();
8624}
8625void ScalarEvolution::visitAndClearUsers(
8628 SmallVectorImpl<SCEVUse> &ToForget) {
8629 while (!Worklist.empty()) {
8630 Instruction *I = Worklist.pop_back_val();
8631 if (!isSCEVable(I->getType()) && !isa<WithOverflowInst>(I))
8632 continue;
8633
8635 ValueExprMap.find_as(static_cast<Value *>(I));
8636 if (It != ValueExprMap.end()) {
8637 ToForget.push_back(It->second);
8638 eraseValueFromMap(It->first);
8639 if (PHINode *PN = dyn_cast<PHINode>(I))
8640 ConstantEvolutionLoopExitValue.erase(PN);
8641 }
8642
8643 PushDefUseChildren(I, Worklist, Visited);
8644 }
8645}
8646
8648 SmallVector<const Loop *, 16> LoopWorklist(1, L);
8651 SmallVector<SCEVUse, 16> ToForget;
8652
8653 // Iterate over all the loops and sub-loops to drop SCEV information.
8654 while (!LoopWorklist.empty()) {
8655 auto *CurrL = LoopWorklist.pop_back_val();
8656
8657 // Drop any stored trip count value.
8658 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8659 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8660
8661 // Drop information about predicated SCEV rewrites for this loop.
8662 PredicatedSCEVRewrites.remove_if(
8663 [&](const auto &Entry) { return Entry.first.second == CurrL; });
8664
8665 auto LoopUsersItr = LoopUsers.find(CurrL);
8666 if (LoopUsersItr != LoopUsers.end())
8667 llvm::append_range(ToForget, LoopUsersItr->second);
8668
8669 // Drop information about expressions based on loop-header PHIs.
8670 PushLoopPHIs(CurrL, Worklist, Visited);
8671 visitAndClearUsers(Worklist, Visited, ToForget);
8672
8673 LoopPropertiesCache.erase(CurrL);
8674 // Forget all contained loops too, to avoid dangling entries in the
8675 // ValuesAtScopes map.
8676 LoopWorklist.append(CurrL->begin(), CurrL->end());
8677 }
8678 forgetMemoizedResults(ToForget);
8679}
8680
8682 forgetLoop(L->getOutermostLoop());
8683}
8684
8687 if (!I) return;
8688
8689 // Drop information about expressions based on loop-header PHIs.
8692 SmallVector<SCEVUse, 8> ToForget;
8693 Worklist.push_back(I);
8694 Visited.insert(I);
8695 visitAndClearUsers(Worklist, Visited, ToForget);
8696
8697 forgetMemoizedResults(ToForget);
8698}
8699
8703 SmallVector<SCEVUse, 8> ToForget;
8704 for (Value *V : Values)
8705 if (auto *I = dyn_cast<Instruction>(V))
8706 if (Visited.insert(I).second)
8707 Worklist.push_back(I);
8708 visitAndClearUsers(Worklist, Visited, ToForget);
8709
8710 forgetMemoizedResults(ToForget);
8711}
8712
8714 // If SCEV looked through a trivial LCSSA phi node, we might have SCEV's
8715 // directly using a SCEVUnknown/SCEVAddRec defined in the loop. After an
8716 // extra predecessor is added, this is no longer valid. Find all Unknowns and
8717 // AddRecs defined in the loop and invalidate any SCEV's making use of them.
8718 auto InvalidateValue = [&](Value *Val) {
8719 if (!isSCEVable(Val->getType()))
8720 return;
8721 if (const SCEV *S = getExistingSCEV(Val)) {
8722 struct InvalidationRootCollector {
8723 Loop *L;
8725
8726 InvalidationRootCollector(Loop *L) : L(L) {}
8727
8728 bool follow(const SCEV *S) {
8729 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
8730 if (auto *I = dyn_cast<Instruction>(SU->getValue()))
8731 if (L->contains(I))
8732 Roots.push_back(S);
8733 } else if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
8734 if (L->contains(AddRec->getLoop()))
8735 Roots.push_back(S);
8736 }
8737 return true;
8738 }
8739 bool isDone() const { return false; }
8740 };
8741
8742 InvalidationRootCollector C(L);
8743 visitAll(S, C);
8744 forgetMemoizedResults(C.Roots);
8745 }
8746 };
8747
8748 InvalidateValue(V);
8749
8750 // If V has a non-SCEV-able type (e.g. {i64, i1} from a with.overflow
8751 // intrinsic), its users (e.g. extractvalue) may have stale SCEV
8752 // expressions referencing loop-internal values.
8753 if (!isSCEVable(V->getType()) &&
8754 any_of(V->incoming_values(), IsaPred<WithOverflowInst>))
8755 for (User *U : V->users())
8756 InvalidateValue(U);
8757 // Also perform the normal invalidation.
8758 forgetValue(V);
8759}
8760
8761void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8762
8764 // Unless a specific value is passed to invalidation, completely clear both
8765 // caches.
8766 if (!V) {
8767 BlockDispositions.clear();
8768 LoopDispositions.clear();
8769 return;
8770 }
8771
8772 if (!isSCEVable(V->getType()))
8773 return;
8774
8775 const SCEV *S = getExistingSCEV(V);
8776 if (!S)
8777 return;
8778
8779 // Invalidate the block and loop dispositions cached for S. Dispositions of
8780 // S's users may change if S's disposition changes (i.e. a user may change to
8781 // loop-invariant, if S changes to loop invariant), so also invalidate
8782 // dispositions of S's users recursively.
8783 SmallVector<SCEVUse, 8> Worklist = {S};
8785 while (!Worklist.empty()) {
8786 const SCEV *Curr = Worklist.pop_back_val();
8787 bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8788 bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8789 if (!LoopDispoRemoved && !BlockDispoRemoved)
8790 continue;
8791 auto Users = SCEVUsers.find(Curr);
8792 if (Users != SCEVUsers.end())
8793 for (const auto *User : Users->second)
8794 if (Seen.insert(User).second)
8795 Worklist.push_back(User);
8796 }
8797}
8798
8799/// Get the exact loop backedge taken count considering all loop exits. A
8800/// computable result can only be returned for loops with all exiting blocks
8801/// dominating the latch. howFarToZero assumes that the limit of each loop test
8802/// is never skipped. This is a valid assumption as long as the loop exits via
8803/// that test. For precise results, it is the caller's responsibility to specify
8804/// the relevant loop exiting block using getExact(ExitingBlock, SE).
8805const SCEV *ScalarEvolution::BackedgeTakenInfo::getExact(
8806 const Loop *L, ScalarEvolution *SE,
8808 // If any exits were not computable, the loop is not computable.
8809 if (!isComplete() || ExitNotTaken.empty())
8810 return SE->getCouldNotCompute();
8811
8812 const BasicBlock *Latch = L->getLoopLatch();
8813 // All exiting blocks we have collected must dominate the only backedge.
8814 if (!Latch)
8815 return SE->getCouldNotCompute();
8816
8817 // All exiting blocks we have gathered dominate loop's latch, so exact trip
8818 // count is simply a minimum out of all these calculated exit counts.
8820 for (const auto &ENT : ExitNotTaken) {
8821 const SCEV *BECount = ENT.ExactNotTaken;
8822 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8823 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8824 "We should only have known counts for exiting blocks that dominate "
8825 "latch!");
8826
8827 Ops.push_back(BECount);
8828
8829 if (Preds)
8830 append_range(*Preds, ENT.Predicates);
8831
8832 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8833 "Predicate should be always true!");
8834 }
8835
8836 // If an earlier exit exits on the first iteration (exit count zero), then
8837 // a later poison exit count should not propagate into the result. This are
8838 // exactly the semantics provided by umin_seq.
8839 return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8840}
8841
8842const ScalarEvolution::ExitNotTakenInfo *
8843ScalarEvolution::BackedgeTakenInfo::getExitNotTaken(
8844 const BasicBlock *ExitingBlock,
8845 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8846 for (const auto &ENT : ExitNotTaken)
8847 if (ENT.ExitingBlock == ExitingBlock) {
8848 if (ENT.hasAlwaysTruePredicate())
8849 return &ENT;
8850 else if (Predicates) {
8851 append_range(*Predicates, ENT.Predicates);
8852 return &ENT;
8853 }
8854 }
8855
8856 return nullptr;
8857}
8858
8859/// getConstantMax - Get the constant max backedge taken count for the loop.
8860const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8861 ScalarEvolution *SE,
8862 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8863 if (!getConstantMax())
8864 return SE->getCouldNotCompute();
8865
8866 for (const auto &ENT : ExitNotTaken)
8867 if (!ENT.hasAlwaysTruePredicate()) {
8868 if (!Predicates)
8869 return SE->getCouldNotCompute();
8870 append_range(*Predicates, ENT.Predicates);
8871 }
8872
8873 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8874 isa<SCEVConstant>(getConstantMax())) &&
8875 "No point in having a non-constant max backedge taken count!");
8876 return getConstantMax();
8877}
8878
8879const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8880 const Loop *L, ScalarEvolution *SE,
8881 SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8882 if (!SymbolicMax) {
8883 // Form an expression for the maximum exit count possible for this loop. We
8884 // merge the max and exact information to approximate a version of
8885 // getConstantMaxBackedgeTakenCount which isn't restricted to just
8886 // constants.
8887 SmallVector<SCEVUse, 4> ExitCounts;
8888
8889 for (const auto &ENT : ExitNotTaken) {
8890 const SCEV *ExitCount = ENT.SymbolicMaxNotTaken;
8891 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
8892 assert(SE->DT.dominates(ENT.ExitingBlock, L->getLoopLatch()) &&
8893 "We should only have known counts for exiting blocks that "
8894 "dominate latch!");
8895 ExitCounts.push_back(ExitCount);
8896 if (Predicates)
8897 append_range(*Predicates, ENT.Predicates);
8898
8899 assert((Predicates || ENT.hasAlwaysTruePredicate()) &&
8900 "Predicate should be always true!");
8901 }
8902 }
8903 if (ExitCounts.empty())
8904 SymbolicMax = SE->getCouldNotCompute();
8905 else
8906 SymbolicMax =
8907 SE->getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
8908 }
8909 return SymbolicMax;
8910}
8911
8912bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8913 ScalarEvolution *SE) const {
8914 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8915 return !ENT.hasAlwaysTruePredicate();
8916 };
8917 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8918}
8919
8922
8924 const SCEV *E, const SCEV *ConstantMaxNotTaken,
8925 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8929 // If we prove the max count is zero, so is the symbolic bound. This happens
8930 // in practice due to differences in a) how context sensitive we've chosen
8931 // to be and b) how we reason about bounds implied by UB.
8932 if (ConstantMaxNotTaken->isZero()) {
8933 this->ExactNotTaken = E = ConstantMaxNotTaken;
8934 this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
8935 }
8936
8939 "Exact is not allowed to be less precise than Constant Max");
8942 "Exact is not allowed to be less precise than Symbolic Max");
8945 "Symbolic Max is not allowed to be less precise than Constant Max");
8948 "No point in having a non-constant max backedge taken count!");
8950 for (const auto PredList : PredLists)
8951 for (const auto *P : PredList) {
8952 if (SeenPreds.contains(P))
8953 continue;
8954 assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!");
8955 SeenPreds.insert(P);
8956 Predicates.push_back(P);
8957 }
8958 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8959 "Backedge count should be int");
8961 !ConstantMaxNotTaken->getType()->isPointerTy()) &&
8962 "Max backedge count should be int");
8963}
8964
8972
8973/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8974/// computable exit into a persistent ExitNotTakenInfo array.
8975ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8977 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
8978 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8979 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8980
8981 ExitNotTaken.reserve(ExitCounts.size());
8982 std::transform(ExitCounts.begin(), ExitCounts.end(),
8983 std::back_inserter(ExitNotTaken),
8984 [&](const EdgeExitInfo &EEI) {
8985 BasicBlock *ExitBB = EEI.first;
8986 const ExitLimit &EL = EEI.second;
8987 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
8988 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
8989 EL.Predicates);
8990 });
8991 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
8992 isa<SCEVConstant>(ConstantMax)) &&
8993 "No point in having a non-constant max backedge taken count!");
8994}
8995
8996/// Compute the number of times the backedge of the specified loop will execute.
8997ScalarEvolution::BackedgeTakenInfo
8998ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
8999 bool AllowPredicates) {
9000 SmallVector<BasicBlock *, 8> ExitingBlocks;
9001 L->getExitingBlocks(ExitingBlocks);
9002
9003 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
9004
9006 bool CouldComputeBECount = true;
9007 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
9008 const SCEV *MustExitMaxBECount = nullptr;
9009 const SCEV *MayExitMaxBECount = nullptr;
9010 bool MustExitMaxOrZero = false;
9011 bool IsOnlyExit = ExitingBlocks.size() == 1;
9012
9013 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
9014 // and compute maxBECount.
9015 // Do a union of all the predicates here.
9016 for (BasicBlock *ExitBB : ExitingBlocks) {
9017 // We canonicalize untaken exits to br (constant), ignore them so that
9018 // proving an exit untaken doesn't negatively impact our ability to reason
9019 // about the loop as whole.
9020 if (auto *BI = dyn_cast<CondBrInst>(ExitBB->getTerminator()))
9021 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
9022 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9023 if (ExitIfTrue == CI->isZero())
9024 continue;
9025 }
9026
9027 ExitLimit EL = computeExitLimit(L, ExitBB, IsOnlyExit, AllowPredicates);
9028
9029 assert((AllowPredicates || EL.Predicates.empty()) &&
9030 "Predicated exit limit when predicates are not allowed!");
9031
9032 // 1. For each exit that can be computed, add an entry to ExitCounts.
9033 // CouldComputeBECount is true only if all exits can be computed.
9034 if (EL.ExactNotTaken != getCouldNotCompute())
9035 ++NumExitCountsComputed;
9036 else
9037 // We couldn't compute an exact value for this exit, so
9038 // we won't be able to compute an exact value for the loop.
9039 CouldComputeBECount = false;
9040 // Remember exit count if either exact or symbolic is known. Because
9041 // Exact always implies symbolic, only check symbolic.
9042 if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
9043 ExitCounts.emplace_back(ExitBB, EL);
9044 else {
9045 assert(EL.ExactNotTaken == getCouldNotCompute() &&
9046 "Exact is known but symbolic isn't?");
9047 ++NumExitCountsNotComputed;
9048 }
9049
9050 // 2. Derive the loop's MaxBECount from each exit's max number of
9051 // non-exiting iterations. Partition the loop exits into two kinds:
9052 // LoopMustExits and LoopMayExits.
9053 //
9054 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
9055 // is a LoopMayExit. If any computable LoopMustExit is found, then
9056 // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
9057 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
9058 // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
9059 // any
9060 // computable EL.ConstantMaxNotTaken.
9061 if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
9062 DT.dominates(ExitBB, Latch)) {
9063 if (!MustExitMaxBECount) {
9064 MustExitMaxBECount = EL.ConstantMaxNotTaken;
9065 MustExitMaxOrZero = EL.MaxOrZero;
9066 } else {
9067 MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
9068 EL.ConstantMaxNotTaken);
9069 }
9070 } else if (MayExitMaxBECount != getCouldNotCompute()) {
9071 if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
9072 MayExitMaxBECount = EL.ConstantMaxNotTaken;
9073 else {
9074 MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
9075 EL.ConstantMaxNotTaken);
9076 }
9077 }
9078 }
9079 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
9080 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
9081 // The loop backedge will be taken the maximum or zero times if there's
9082 // a single exit that must be taken the maximum or zero times.
9083 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
9084
9085 // Remember which SCEVs are used in exit limits for invalidation purposes.
9086 // We only care about non-constant SCEVs here, so we can ignore
9087 // EL.ConstantMaxNotTaken
9088 // and MaxBECount, which must be SCEVConstant.
9089 for (const auto &Pair : ExitCounts) {
9090 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
9091 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
9092 if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
9093 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
9094 {L, AllowPredicates});
9095 }
9096 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
9097 MaxBECount, MaxOrZero);
9098}
9099
9100ScalarEvolution::ExitLimit
9101ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
9102 bool IsOnlyExit, bool AllowPredicates) {
9103 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
9104 // If our exiting block does not dominate the latch, then its connection with
9105 // loop's exit limit may be far from trivial.
9106 const BasicBlock *Latch = L->getLoopLatch();
9107 if (!Latch || !DT.dominates(ExitingBlock, Latch))
9108 return getCouldNotCompute();
9109
9110 Instruction *Term = ExitingBlock->getTerminator();
9111 if (CondBrInst *BI = dyn_cast<CondBrInst>(Term)) {
9112 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9113 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
9114 "It should have one successor in loop and one exit block!");
9115 // Proceed to the next level to examine the exit condition expression.
9116 return computeExitLimitFromCond(L, BI->getCondition(), ExitIfTrue,
9117 /*ControlsOnlyExit=*/IsOnlyExit,
9118 AllowPredicates);
9119 }
9120
9121 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
9122 // For switch, make sure that there is a single exit from the loop.
9123 BasicBlock *Exit = nullptr;
9124 for (auto *SBB : successors(ExitingBlock))
9125 if (!L->contains(SBB)) {
9126 if (Exit) // Multiple exit successors.
9127 return getCouldNotCompute();
9128 Exit = SBB;
9129 }
9130 assert(Exit && "Exiting block must have at least one exit");
9131 return computeExitLimitFromSingleExitSwitch(
9132 L, SI, Exit, /*ControlsOnlyExit=*/IsOnlyExit);
9133 }
9134
9135 return getCouldNotCompute();
9136}
9137
9139 const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9140 bool AllowPredicates) {
9141 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
9142 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
9143 ControlsOnlyExit, AllowPredicates);
9144}
9145
9146std::optional<ScalarEvolution::ExitLimit>
9147ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
9148 bool ExitIfTrue, bool ControlsOnlyExit,
9149 bool AllowPredicates) {
9150 (void)this->L;
9151 (void)this->ExitIfTrue;
9152 (void)this->AllowPredicates;
9153
9154 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9155 this->AllowPredicates == AllowPredicates &&
9156 "Variance in assumed invariant key components!");
9157 auto Itr = TripCountMap.find({ExitCond, ControlsOnlyExit});
9158 if (Itr == TripCountMap.end())
9159 return std::nullopt;
9160 return Itr->second;
9161}
9162
9163void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
9164 bool ExitIfTrue,
9165 bool ControlsOnlyExit,
9166 bool AllowPredicates,
9167 const ExitLimit &EL) {
9168 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9169 this->AllowPredicates == AllowPredicates &&
9170 "Variance in assumed invariant key components!");
9171
9172 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsOnlyExit}, EL});
9173 assert(InsertResult.second && "Expected successful insertion!");
9174 (void)InsertResult;
9175 (void)ExitIfTrue;
9176}
9177
9178ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
9179 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9180 bool ControlsOnlyExit, bool AllowPredicates) {
9181
9182 if (auto MaybeEL = Cache.find(L, ExitCond, ExitIfTrue, ControlsOnlyExit,
9183 AllowPredicates))
9184 return *MaybeEL;
9185
9186 ExitLimit EL = computeExitLimitFromCondImpl(
9187 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates);
9188 Cache.insert(L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates, EL);
9189 return EL;
9190}
9191
9192ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
9193 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9194 bool ControlsOnlyExit, bool AllowPredicates) {
9195 // Handle BinOp conditions (And, Or).
9196 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
9197 Cache, L, ExitCond, ExitIfTrue, AllowPredicates))
9198 return *LimitFromBinOp;
9199
9200 // With an icmp, it may be feasible to compute an exact backedge-taken count.
9201 // Proceed to the next level to examine the icmp.
9202 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
9203 ExitLimit EL =
9204 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsOnlyExit);
9205 if (EL.hasFullInfo() || !AllowPredicates)
9206 return EL;
9207
9208 // Try again, but use SCEV predicates this time.
9209 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue,
9210 ControlsOnlyExit,
9211 /*AllowPredicates=*/true);
9212 }
9213
9214 // Check for a constant condition. These are normally stripped out by
9215 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
9216 // preserve the CFG and is temporarily leaving constant conditions
9217 // in place.
9218 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
9219 if (ExitIfTrue == !CI->getZExtValue())
9220 // The backedge is always taken.
9221 return getCouldNotCompute();
9222 // The backedge is never taken.
9223 return getZero(CI->getType());
9224 }
9225
9226 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
9227 // with a constant step, we can form an equivalent icmp predicate and figure
9228 // out how many iterations will be taken before we exit.
9229 const WithOverflowInst *WO;
9230 const APInt *C;
9231 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
9232 match(WO->getRHS(), m_APInt(C))) {
9233 ConstantRange NWR =
9235 WO->getNoWrapKind());
9236 CmpInst::Predicate Pred;
9237 APInt NewRHSC, Offset;
9238 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
9239 if (!ExitIfTrue)
9240 Pred = ICmpInst::getInversePredicate(Pred);
9241 auto *LHS = getSCEV(WO->getLHS());
9242 if (Offset != 0)
9244 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
9245 ControlsOnlyExit, AllowPredicates);
9246 if (EL.hasAnyInfo())
9247 return EL;
9248 }
9249
9250 // If it's not an integer or pointer comparison then compute it the hard way.
9251 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9252}
9253
9254std::optional<ScalarEvolution::ExitLimit>
9255ScalarEvolution::computeExitLimitFromCondFromBinOp(ExitLimitCacheTy &Cache,
9256 const Loop *L,
9257 Value *ExitCond,
9258 bool ExitIfTrue,
9259 bool AllowPredicates) {
9260 // Check if the controlling expression for this loop is an And or Or.
9261 Value *Op0, *Op1;
9262 bool IsAnd;
9263 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
9264 IsAnd = true;
9265 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
9266 IsAnd = false;
9267 else
9268 return std::nullopt;
9269
9270 // A sub-condition of a non-trivial binop never solely controls the exit,
9271 // whether we exit always depends on both conditions.
9272 ExitLimit EL0 = computeExitLimitFromCondCached(
9273 Cache, L, Op0, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9274 ExitLimit EL1 = computeExitLimitFromCondCached(
9275 Cache, L, Op1, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9276
9277 // EitherMayExit is true in these two cases:
9278 // br (and Op0 Op1), loop, exit
9279 // br (or Op0 Op1), exit, loop
9280 bool EitherMayExit = IsAnd ^ ExitIfTrue;
9281
9282 const SCEV *BECount = getCouldNotCompute();
9283 const SCEV *ConstantMaxBECount = getCouldNotCompute();
9284 const SCEV *SymbolicMaxBECount = getCouldNotCompute();
9285 if (EitherMayExit) {
9286 bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
9287 // Both conditions must be same for the loop to continue executing.
9288 // Choose the less conservative count.
9289 if (EL0.ExactNotTaken != getCouldNotCompute() &&
9290 EL1.ExactNotTaken != getCouldNotCompute()) {
9291 BECount = getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken,
9292 UseSequentialUMin);
9293 }
9294 if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
9295 ConstantMaxBECount = EL1.ConstantMaxNotTaken;
9296 else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
9297 ConstantMaxBECount = EL0.ConstantMaxNotTaken;
9298 else
9299 ConstantMaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
9300 EL1.ConstantMaxNotTaken);
9301 if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
9302 SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
9303 else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
9304 SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
9305 else
9306 SymbolicMaxBECount = getUMinFromMismatchedTypes(
9307 EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
9308 } else {
9309 // Both conditions must be same at the same time for the loop to exit.
9310 // For now, be conservative.
9311 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
9312 BECount = EL0.ExactNotTaken;
9313 }
9314
9315 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
9316 // to be more aggressive when computing BECount than when computing
9317 // ConstantMaxBECount. In these cases it is possible for EL0.ExactNotTaken
9318 // and
9319 // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
9320 // EL1.ConstantMaxNotTaken to not.
9321 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
9322 !isa<SCEVCouldNotCompute>(BECount))
9323 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
9324 if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
9325 SymbolicMaxBECount =
9326 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
9327 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
9328 {ArrayRef(EL0.Predicates), ArrayRef(EL1.Predicates)});
9329}
9330
9331ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9332 const Loop *L, ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9333 bool AllowPredicates) {
9334 // If the condition was exit on true, convert the condition to exit on false
9335 CmpPredicate Pred;
9336 if (!ExitIfTrue)
9337 Pred = ExitCond->getCmpPredicate();
9338 else
9339 Pred = ExitCond->getInverseCmpPredicate();
9340 const ICmpInst::Predicate OriginalPred = Pred;
9341
9342 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
9343 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
9344
9345 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsOnlyExit,
9346 AllowPredicates);
9347 if (EL.hasAnyInfo())
9348 return EL;
9349
9350 auto *ExhaustiveCount =
9351 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9352
9353 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
9354 return ExhaustiveCount;
9355
9356 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
9357 ExitCond->getOperand(1), L, OriginalPred);
9358}
9359ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9360 const Loop *L, CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS,
9361 bool ControlsOnlyExit, bool AllowPredicates) {
9362
9363 // Try to evaluate any dependencies out of the loop.
9364 LHS = getSCEVAtScope(LHS, L);
9365 RHS = getSCEVAtScope(RHS, L);
9366
9367 // At this point, we would like to compute how many iterations of the
9368 // loop the predicate will return true for these inputs.
9369 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
9370 // If there is a loop-invariant, force it into the RHS.
9371 std::swap(LHS, RHS);
9373 }
9374
9375 bool ControllingFiniteLoop = ControlsOnlyExit && loopHasNoAbnormalExits(L) &&
9377 // Simplify the operands before analyzing them.
9378 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0);
9379
9380 // If we have a comparison of a chrec against a constant, try to use value
9381 // ranges to answer this query.
9382 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
9383 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
9384 if (AddRec->getLoop() == L) {
9385 // Form the constant range.
9386 ConstantRange CompRange =
9387 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
9388
9389 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
9390 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
9391 }
9392
9393 // If this loop must exit based on this condition (or execute undefined
9394 // behaviour), see if we can improve wrap flags. This is essentially
9395 // a must execute style proof.
9396 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
9397 // If we can prove the test sequence produced must repeat the same values
9398 // on self-wrap of the IV, then we can infer that IV doesn't self wrap
9399 // because if it did, we'd have an infinite (undefined) loop.
9400 // TODO: We can peel off any functions which are invertible *in L*. Loop
9401 // invariant terms are effectively constants for our purposes here.
9402 SCEVUse InnerLHS = LHS;
9403 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
9404 InnerLHS = ZExt->getOperand();
9405 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS);
9406 AR && !AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
9407 isKnownToBeAPowerOfTwo(AR->getStepRecurrence(*this), /*OrZero=*/true,
9408 /*OrNegative=*/true)) {
9409 auto Flags = AR->getNoWrapFlags();
9410 Flags = setFlags(Flags, SCEV::FlagNW);
9413 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9414 }
9415
9416 // For a slt/ult condition with a positive step, can we prove nsw/nuw?
9417 // From no-self-wrap, this follows trivially from the fact that every
9418 // (un)signed-wrapped, but not self-wrapped value must be LT than the
9419 // last value before (un)signed wrap. Since we know that last value
9420 // didn't exit, nor will any smaller one.
9421 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT) {
9422 auto WrapType = Pred == ICmpInst::ICMP_SLT ? SCEV::FlagNSW : SCEV::FlagNUW;
9423 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9424 AR && AR->getLoop() == L && AR->isAffine() &&
9425 !AR->getNoWrapFlags(WrapType) && AR->hasNoSelfWrap() &&
9426 isKnownPositive(AR->getStepRecurrence(*this))) {
9427 auto Flags = AR->getNoWrapFlags();
9428 Flags = setFlags(Flags, WrapType);
9431 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9432 }
9433 }
9434 }
9435
9436 switch (Pred) {
9437 case ICmpInst::ICMP_NE: { // while (X != Y)
9438 // Convert to: while (X-Y != 0)
9439 if (LHS->getType()->isPointerTy()) {
9442 return LHS;
9443 }
9444 if (RHS->getType()->isPointerTy()) {
9447 return RHS;
9448 }
9449 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit,
9450 AllowPredicates);
9451 if (EL.hasAnyInfo())
9452 return EL;
9453 break;
9454 }
9455 case ICmpInst::ICMP_EQ: { // while (X == Y)
9456 // Convert to: while (X-Y == 0)
9457 if (LHS->getType()->isPointerTy()) {
9460 return LHS;
9461 }
9462 if (RHS->getType()->isPointerTy()) {
9465 return RHS;
9466 }
9467 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
9468 if (EL.hasAnyInfo()) return EL;
9469 break;
9470 }
9471 case ICmpInst::ICMP_SLE:
9472 case ICmpInst::ICMP_ULE:
9473 // Since the loop is finite, an invariant RHS cannot include the boundary
9474 // value, otherwise it would loop forever.
9475 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9476 !isLoopInvariant(RHS, L)) {
9477 // Otherwise, perform the addition in a wider type, to avoid overflow.
9478 // If the LHS is an addrec with the appropriate nowrap flag, the
9479 // extension will be sunk into it and the exit count can be analyzed.
9480 auto *OldType = dyn_cast<IntegerType>(LHS->getType());
9481 if (!OldType)
9482 break;
9483 // Prefer doubling the bitwidth over adding a single bit to make it more
9484 // likely that we use a legal type.
9485 auto *NewType =
9486 Type::getIntNTy(OldType->getContext(), OldType->getBitWidth() * 2);
9487 if (ICmpInst::isSigned(Pred)) {
9488 LHS = getSignExtendExpr(LHS, NewType);
9489 RHS = getSignExtendExpr(RHS, NewType);
9490 } else {
9491 LHS = getZeroExtendExpr(LHS, NewType);
9492 RHS = getZeroExtendExpr(RHS, NewType);
9493 }
9494 }
9496 [[fallthrough]];
9497 case ICmpInst::ICMP_SLT:
9498 case ICmpInst::ICMP_ULT: { // while (X < Y)
9499 bool IsSigned = ICmpInst::isSigned(Pred);
9500 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9501 AllowPredicates);
9502 if (EL.hasAnyInfo())
9503 return EL;
9504 break;
9505 }
9506 case ICmpInst::ICMP_SGE:
9507 case ICmpInst::ICMP_UGE:
9508 // Since the loop is finite, an invariant RHS cannot include the boundary
9509 // value, otherwise it would loop forever.
9510 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9511 !isLoopInvariant(RHS, L))
9512 break;
9514 [[fallthrough]];
9515 case ICmpInst::ICMP_SGT:
9516 case ICmpInst::ICMP_UGT: { // while (X > Y)
9517 bool IsSigned = ICmpInst::isSigned(Pred);
9518 ExitLimit EL = howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9519 AllowPredicates);
9520 if (EL.hasAnyInfo())
9521 return EL;
9522 break;
9523 }
9524 default:
9525 break;
9526 }
9527
9528 return getCouldNotCompute();
9529}
9530
9531ScalarEvolution::ExitLimit
9532ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
9533 SwitchInst *Switch,
9534 BasicBlock *ExitingBlock,
9535 bool ControlsOnlyExit) {
9536 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
9537
9538 // Give up if the exit is the default dest of a switch.
9539 if (Switch->getDefaultDest() == ExitingBlock)
9540 return getCouldNotCompute();
9541
9542 assert(L->contains(Switch->getDefaultDest()) &&
9543 "Default case must not exit the loop!");
9544 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
9545 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
9546
9547 // while (X != Y) --> while (X-Y != 0)
9548 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit);
9549 if (EL.hasAnyInfo())
9550 return EL;
9551
9552 return getCouldNotCompute();
9553}
9554
9555static ConstantInt *
9557 ScalarEvolution &SE) {
9558 const SCEV *InVal = SE.getConstant(C);
9559 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
9561 "Evaluation of SCEV at constant didn't fold correctly?");
9562 return cast<SCEVConstant>(Val)->getValue();
9563}
9564
9565ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
9566 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
9567 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
9568 if (!RHS)
9569 return getCouldNotCompute();
9570
9571 const BasicBlock *Latch = L->getLoopLatch();
9572 if (!Latch)
9573 return getCouldNotCompute();
9574
9575 const BasicBlock *Predecessor = L->getLoopPredecessor();
9576 if (!Predecessor)
9577 return getCouldNotCompute();
9578
9579 // Return true if V is of the form "LHS `shift_op` <positive constant>".
9580 // Return LHS in OutLHS, shift_op in OutOpCode, and the shift amount in
9581 // OutShiftAmt.
9582 auto MatchPositiveShift = [](Value *V, Value *&OutLHS,
9583 Instruction::BinaryOps &OutOpCode,
9584 unsigned &OutShiftAmt) {
9585 using namespace PatternMatch;
9586
9587 ConstantInt *ShiftAmt;
9588 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9589 OutOpCode = Instruction::LShr;
9590 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9591 OutOpCode = Instruction::AShr;
9592 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9593 OutOpCode = Instruction::Shl;
9594 else
9595 return false;
9596
9597 uint64_t Amt = ShiftAmt->getValue().getLimitedValue();
9598 if (Amt == 0 || Amt >= OutLHS->getType()->getScalarSizeInBits())
9599 return false;
9600 OutShiftAmt = Amt;
9601 return true;
9602 };
9603
9604 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
9605 //
9606 // loop:
9607 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
9608 // %iv.shifted = lshr i32 %iv, <positive constant>
9609 //
9610 // Return true on a successful match. Return the corresponding PHI node (%iv
9611 // above) in PNOut, the opcode of the shift operation in OpCodeOut, and the
9612 // shift amount in ShiftAmtOut.
9613 auto MatchShiftRecurrence = [&](Value *V, PHINode *&PNOut,
9614 Instruction::BinaryOps &OpCodeOut,
9615 unsigned &ShiftAmtOut) {
9616 std::optional<Instruction::BinaryOps> PostShiftOpCode;
9617
9618 {
9620 Value *V;
9621 unsigned Amt;
9622
9623 // If we encounter a shift instruction, "peel off" the shift operation,
9624 // and remember that we did so. Later when we inspect %iv's backedge
9625 // value, we will make sure that the backedge value uses the same
9626 // operation.
9627 //
9628 // Note: the peeled shift operation does not have to be the same
9629 // instruction as the one feeding into the PHI's backedge value. We only
9630 // really care about it being the same *kind* of shift instruction --
9631 // that's all that is required for our later inferences to hold.
9632 if (MatchPositiveShift(LHS, V, OpC, Amt)) {
9633 PostShiftOpCode = OpC;
9634 LHS = V;
9635 }
9636 }
9637
9638 PNOut = dyn_cast<PHINode>(LHS);
9639 if (!PNOut || PNOut->getParent() != L->getHeader())
9640 return false;
9641
9642 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
9643 Value *OpLHS;
9644
9645 return
9646 // The backedge value for the PHI node must be a shift by a positive
9647 // amount
9648 MatchPositiveShift(BEValue, OpLHS, OpCodeOut, ShiftAmtOut) &&
9649
9650 // of the PHI node itself
9651 OpLHS == PNOut &&
9652
9653 // and the kind of shift should be match the kind of shift we peeled
9654 // off, if any.
9655 (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9656 };
9657
9658 PHINode *PN;
9660 unsigned ShiftAmt;
9661 if (!MatchShiftRecurrence(LHS, PN, OpCode, ShiftAmt))
9662 return getCouldNotCompute();
9663
9664 const DataLayout &DL = getDataLayout();
9665
9666 // The key rationale for this optimization is that for some kinds of shift
9667 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
9668 // within a finite number of iterations. If the condition guarding the
9669 // backedge (in the sense that the backedge is taken if the condition is true)
9670 // is false for the value the shift recurrence stabilizes to, then we know
9671 // that the backedge is taken only a finite number of times.
9672
9673 ConstantInt *StableValue = nullptr;
9674 switch (OpCode) {
9675 default:
9676 llvm_unreachable("Impossible case!");
9677
9678 case Instruction::AShr: {
9679 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
9680 // bitwidth(K) iterations.
9681 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
9682 KnownBits Known = computeKnownBits(FirstValue, DL, &AC,
9683 Predecessor->getTerminator(), &DT);
9684 auto *Ty = cast<IntegerType>(RHS->getType());
9685 if (Known.isNonNegative())
9686 StableValue = ConstantInt::get(Ty, 0);
9687 else if (Known.isNegative())
9688 StableValue = ConstantInt::get(Ty, -1, true);
9689 else
9690 return getCouldNotCompute();
9691
9692 break;
9693 }
9694 case Instruction::LShr:
9695 case Instruction::Shl:
9696 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
9697 // stabilize to 0 in at most bitwidth(K) iterations.
9698 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
9699 break;
9700 }
9701
9702 auto *Result =
9703 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
9704 assert(Result->getType()->isIntegerTy(1) &&
9705 "Otherwise cannot be an operand to a branch instruction");
9706
9707 if (Result->isNullValue()) {
9708 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9709 unsigned MaxBTC = BitWidth;
9710
9711 // For right-shift recurrences (lshr/ashr with non-negative start), we can
9712 // compute a tighter max backedge-taken count from the range of the start
9713 // value. After k shifts of ShiftAmt, value = start >> (k * ShiftAmt).
9714 // The value reaches 0 (the stable value) when k * ShiftAmt >=
9715 // activeBits(start), so max BTC = ceil(activeBits(maxStart) / ShiftAmt).
9716 if (OpCode == Instruction::LShr || OpCode == Instruction::AShr) {
9717 Value *StartValue = PN->getIncomingValueForBlock(Predecessor);
9718 const SCEV *StartSCEV = getSCEV(StartValue);
9719 APInt MaxStart = getUnsignedRangeMax(StartSCEV);
9720 if (MaxStart.isStrictlyPositive()) {
9721 unsigned ActiveBits = MaxStart.getActiveBits();
9722 unsigned RangeBTC = divideCeil(ActiveBits, ShiftAmt);
9723 MaxBTC = std::min(MaxBTC, RangeBTC);
9724 }
9725 }
9726
9727 const SCEV *UpperBound =
9729 return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
9730 }
9731
9732 return getCouldNotCompute();
9733}
9734
9735/// Return true if we can constant fold an instruction of the specified type,
9736/// assuming that all operands were constants.
9737static bool canConstantFold(const Instruction *I,
9738 const TargetLibraryInfo *TLI) {
9742 return true;
9743
9744 if (const CallInst *CI = dyn_cast<CallInst>(I))
9745 if (const Function *F = CI->getCalledFunction())
9746 return canConstantFoldCallTo(CI, F, TLI);
9747 return false;
9748}
9749
9750/// Determine whether this instruction can constant evolve within this loop
9751/// assuming its operands can all constant evolve.
9752static bool canConstantEvolve(Instruction *I, const Loop *L,
9753 const TargetLibraryInfo *TLI) {
9754 // An instruction outside of the loop can't be derived from a loop PHI.
9755 if (!L->contains(I)) return false;
9756
9757 if (isa<PHINode>(I)) {
9758 // We don't currently keep track of the control flow needed to evaluate
9759 // PHIs, so we cannot handle PHIs inside of loops.
9760 return L->getHeader() == I->getParent();
9761 }
9762
9763 // If we won't be able to constant fold this expression even if the operands
9764 // are constants, bail early.
9765 return canConstantFold(I, TLI);
9766}
9767
9768/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
9769/// recursing through each instruction operand until reaching a loop header phi.
9770static PHINode *
9773 const TargetLibraryInfo *TLI, unsigned Depth) {
9775 return nullptr;
9776
9777 // Otherwise, we can evaluate this instruction if all of its operands are
9778 // constant or derived from a PHI node themselves.
9779 PHINode *PHI = nullptr;
9780 for (Value *Op : UseInst->operands()) {
9781 if (isa<Constant>(Op)) continue;
9782
9784 if (!OpInst || !canConstantEvolve(OpInst, L, TLI))
9785 return nullptr;
9786
9787 PHINode *P = dyn_cast<PHINode>(OpInst);
9788 if (!P)
9789 // If this operand is already visited, reuse the prior result.
9790 // We may have P != PHI if this is the deepest point at which the
9791 // inconsistent paths meet.
9792 P = PHIMap.lookup(OpInst);
9793 if (!P) {
9794 // Recurse and memoize the results, whether a phi is found or not.
9795 // This recursive call invalidates pointers into PHIMap.
9796 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, TLI, Depth + 1);
9797 PHIMap[OpInst] = P;
9798 }
9799 if (!P)
9800 return nullptr; // Not evolving from PHI
9801 if (PHI && PHI != P)
9802 return nullptr; // Evolving from multiple different PHIs.
9803 PHI = P;
9804 }
9805 // This is a expression evolving from a constant PHI!
9806 return PHI;
9807}
9808
9809/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9810/// in the loop that V is derived from. We allow arbitrary operations along the
9811/// way, but the operands of an operation must either be constants or a value
9812/// derived from a constant PHI. If this expression does not fit with these
9813/// constraints, return null.
9815 const TargetLibraryInfo *TLI) {
9817 if (!I || !canConstantEvolve(I, L, TLI))
9818 return nullptr;
9819
9820 if (PHINode *PN = dyn_cast<PHINode>(I))
9821 return PN;
9822
9823 // Record non-constant instructions contained by the loop.
9825 return getConstantEvolvingPHIOperands(I, L, PHIMap, TLI, 0);
9826}
9827
9828/// EvaluateExpression - Given an expression that passes the
9829/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9830/// in the loop has the value PHIVal. If we can't fold this expression for some
9831/// reason, return null.
9834 const DataLayout &DL,
9835 const TargetLibraryInfo *TLI) {
9836 // Convenient constant check, but redundant for recursive calls.
9837 if (Constant *C = dyn_cast<Constant>(V)) return C;
9839 if (!I) return nullptr;
9840
9841 if (Constant *C = Vals.lookup(I)) return C;
9842
9843 // An instruction inside the loop depends on a value outside the loop that we
9844 // weren't given a mapping for, or a value such as a call inside the loop.
9845 if (!canConstantEvolve(I, L, TLI))
9846 return nullptr;
9847
9848 // An unmapped PHI can be due to a branch or another loop inside this loop,
9849 // or due to this not being the initial iteration through a loop where we
9850 // couldn't compute the evolution of this particular PHI last time.
9851 if (isa<PHINode>(I)) return nullptr;
9852
9853 std::vector<Constant*> Operands(I->getNumOperands());
9854
9855 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9856 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9857 if (!Operand) {
9858 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9859 if (!Operands[i]) return nullptr;
9860 continue;
9861 }
9862 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9863 Vals[Operand] = C;
9864 if (!C) return nullptr;
9865 Operands[i] = C;
9866 }
9867
9868 return ConstantFoldInstOperands(I, Operands, DL, TLI,
9869 /*AllowNonDeterministic=*/false);
9870}
9871
9872
9873// If every incoming value to PN except the one for BB is a specific Constant,
9874// return that, else return nullptr.
9876 Constant *IncomingVal = nullptr;
9877
9878 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9879 if (PN->getIncomingBlock(i) == BB)
9880 continue;
9881
9882 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
9883 if (!CurrentVal)
9884 return nullptr;
9885
9886 if (IncomingVal != CurrentVal) {
9887 if (IncomingVal)
9888 return nullptr;
9889 IncomingVal = CurrentVal;
9890 }
9891 }
9892
9893 return IncomingVal;
9894}
9895
9896/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9897/// in the header of its containing loop, we know the loop executes a
9898/// constant number of times, and the PHI node is just a recurrence
9899/// involving constants, fold it.
9900Constant *
9901ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9902 const APInt &BEs,
9903 const Loop *L) {
9904 auto [I, Inserted] = ConstantEvolutionLoopExitValue.try_emplace(PN);
9905 if (!Inserted)
9906 return I->second;
9907
9909 return nullptr; // Not going to evaluate it.
9910
9911 Constant *&RetVal = I->second;
9912
9913 DenseMap<Instruction *, Constant *> CurrentIterVals;
9914 BasicBlock *Header = L->getHeader();
9915 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9916
9917 BasicBlock *Latch = L->getLoopLatch();
9918 if (!Latch)
9919 return nullptr;
9920
9921 for (PHINode &PHI : Header->phis()) {
9922 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9923 CurrentIterVals[&PHI] = StartCST;
9924 }
9925 if (!CurrentIterVals.count(PN))
9926 return RetVal = nullptr;
9927
9928 Value *BEValue = PN->getIncomingValueForBlock(Latch);
9929
9930 // Execute the loop symbolically to determine the exit value.
9931 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
9932 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
9933
9934 unsigned NumIterations = BEs.getZExtValue(); // must be in range
9935 unsigned IterationNum = 0;
9936 const DataLayout &DL = getDataLayout();
9937 for (; ; ++IterationNum) {
9938 if (IterationNum == NumIterations)
9939 return RetVal = CurrentIterVals[PN]; // Got exit value!
9940
9941 // Compute the value of the PHIs for the next iteration.
9942 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9943 DenseMap<Instruction *, Constant *> NextIterVals;
9944 Constant *NextPHI =
9945 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9946 if (!NextPHI)
9947 return nullptr; // Couldn't evaluate!
9948 NextIterVals[PN] = NextPHI;
9949
9950 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9951
9952 // Also evaluate the other PHI nodes. However, we don't get to stop if we
9953 // cease to be able to evaluate one of them or if they stop evolving,
9954 // because that doesn't necessarily prevent us from computing PN.
9956 for (const auto &I : CurrentIterVals) {
9957 PHINode *PHI = dyn_cast<PHINode>(I.first);
9958 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
9959 PHIsToCompute.emplace_back(PHI, I.second);
9960 }
9961 // We use two distinct loops because EvaluateExpression may invalidate any
9962 // iterators into CurrentIterVals.
9963 for (const auto &I : PHIsToCompute) {
9964 PHINode *PHI = I.first;
9965 Constant *&NextPHI = NextIterVals[PHI];
9966 if (!NextPHI) { // Not already computed.
9967 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9968 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9969 }
9970 if (NextPHI != I.second)
9971 StoppedEvolving = false;
9972 }
9973
9974 // If all entries in CurrentIterVals == NextIterVals then we can stop
9975 // iterating, the loop can't continue to change.
9976 if (StoppedEvolving)
9977 return RetVal = CurrentIterVals[PN];
9978
9979 CurrentIterVals.swap(NextIterVals);
9980 }
9981}
9982
9983const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
9984 Value *Cond,
9985 bool ExitWhen) {
9986 PHINode *PN = getConstantEvolvingPHI(Cond, L, &TLI);
9987 if (!PN) return getCouldNotCompute();
9988
9989 // If the loop is canonicalized, the PHI will have exactly two entries.
9990 // That's the only form we support here.
9991 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
9992
9993 DenseMap<Instruction *, Constant *> CurrentIterVals;
9994 BasicBlock *Header = L->getHeader();
9995 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9996
9997 BasicBlock *Latch = L->getLoopLatch();
9998 assert(Latch && "Should follow from NumIncomingValues == 2!");
9999
10000 for (PHINode &PHI : Header->phis()) {
10001 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
10002 CurrentIterVals[&PHI] = StartCST;
10003 }
10004 if (!CurrentIterVals.count(PN))
10005 return getCouldNotCompute();
10006
10007 // Okay, we find a PHI node that defines the trip count of this loop. Execute
10008 // the loop symbolically to determine when the condition gets a value of
10009 // "ExitWhen".
10010 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
10011 const DataLayout &DL = getDataLayout();
10012 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
10013 auto *CondVal = dyn_cast_or_null<ConstantInt>(
10014 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
10015
10016 // Couldn't symbolically evaluate.
10017 if (!CondVal) return getCouldNotCompute();
10018
10019 if (CondVal->getValue() == uint64_t(ExitWhen)) {
10020 ++NumBruteForceTripCountsComputed;
10021 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
10022 }
10023
10024 // Update all the PHI nodes for the next iteration.
10025 DenseMap<Instruction *, Constant *> NextIterVals;
10026
10027 // Create a list of which PHIs we need to compute. We want to do this before
10028 // calling EvaluateExpression on them because that may invalidate iterators
10029 // into CurrentIterVals.
10030 SmallVector<PHINode *, 8> PHIsToCompute;
10031 for (const auto &I : CurrentIterVals) {
10032 PHINode *PHI = dyn_cast<PHINode>(I.first);
10033 if (!PHI || PHI->getParent() != Header) continue;
10034 PHIsToCompute.push_back(PHI);
10035 }
10036 for (PHINode *PHI : PHIsToCompute) {
10037 Constant *&NextPHI = NextIterVals[PHI];
10038 if (NextPHI) continue; // Already computed!
10039
10040 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
10041 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
10042 }
10043 CurrentIterVals.swap(NextIterVals);
10044 }
10045
10046 // Too many iterations were needed to evaluate.
10047 return getCouldNotCompute();
10048}
10049
10051 auto &Values = ValuesAtScopes[V];
10052 // Check to see if we've folded this expression at this loop before.
10053 for (auto &LS : Values)
10054 if (LS.first == L)
10055 return LS.second ? LS.second : SCEVUse(V);
10056
10057 Values.emplace_back(L, nullptr);
10058
10059 // Otherwise compute it.
10060 SCEVUse C = computeSCEVAtScope(V, L);
10061 for (auto &LS : reverse(ValuesAtScopes[V]))
10062 if (LS.first == L) {
10063 LS.second = C;
10064 // Record the dependency under the bare expression: invalidation walks
10065 // expressions, and any use flags on C do not change which expression
10066 // this is the value at scope of.
10067 if (!isa<SCEVConstant>(C))
10068 ValuesAtScopesUsers[C.getPointer()].push_back({L, V});
10069 break;
10070 }
10071 return C;
10072}
10073
10074/// This builds up a Constant using the ConstantExpr interface. That way, we
10075/// will return Constants for objects which aren't represented by a
10076/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
10077/// Returns NULL if the SCEV isn't representable as a Constant.
10079 switch (V->getSCEVType()) {
10080 case scCouldNotCompute:
10081 case scAddRecExpr:
10082 case scVScale:
10083 return nullptr;
10084 case scConstant:
10085 return cast<SCEVConstant>(V)->getValue();
10086 case scUnknown:
10088 case scPtrToAddr: {
10090 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
10091 return ConstantExpr::getPtrToAddr(CastOp, P2I->getType());
10092
10093 return nullptr;
10094 }
10095 case scTruncate: {
10097 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
10098 return ConstantExpr::getTrunc(CastOp, ST->getType());
10099 return nullptr;
10100 }
10101 case scAddExpr: {
10102 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
10103 Constant *C = nullptr;
10104 for (const SCEV *Op : SA->operands()) {
10106 if (!OpC)
10107 return nullptr;
10108 if (!C) {
10109 C = OpC;
10110 continue;
10111 }
10112 assert(!C->getType()->isPointerTy() &&
10113 "Can only have one pointer, and it must be last");
10114 if (OpC->getType()->isPointerTy()) {
10115 // The offsets have been converted to bytes. We can add bytes using
10116 // an i8 GEP.
10117 C = ConstantExpr::getPtrAdd(OpC, C);
10118 } else {
10119 C = ConstantExpr::getAdd(C, OpC);
10120 }
10121 }
10122 return C;
10123 }
10124 case scMulExpr:
10125 case scSignExtend:
10126 case scZeroExtend:
10127 case scUDivExpr:
10128 case scSMaxExpr:
10129 case scUMaxExpr:
10130 case scSMinExpr:
10131 case scUMinExpr:
10133 return nullptr;
10134 }
10135 llvm_unreachable("Unknown SCEV kind!");
10136}
10137
10138const SCEV *ScalarEvolution::getWithOperands(const SCEV *S,
10139 SmallVectorImpl<SCEVUse> &NewOps) {
10140 switch (S->getSCEVType()) {
10141 case scTruncate:
10142 case scZeroExtend:
10143 case scSignExtend:
10144 case scPtrToAddr:
10145 return getCastExpr(S->getSCEVType(), NewOps[0], S->getType());
10146 case scAddRecExpr: {
10147 auto *AddRec = cast<SCEVAddRecExpr>(S);
10148 return getAddRecExpr(NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags());
10149 }
10150 case scAddExpr:
10151 return getAddExpr(NewOps, cast<SCEVAddExpr>(S)->getNoWrapFlags());
10152 case scMulExpr:
10153 return getMulExpr(NewOps, cast<SCEVMulExpr>(S)->getNoWrapFlags());
10154 case scUDivExpr:
10155 return getUDivExpr(NewOps[0], NewOps[1]);
10156 case scUMaxExpr:
10157 case scSMaxExpr:
10158 case scUMinExpr:
10159 case scSMinExpr:
10160 return getMinMaxExpr(S->getSCEVType(), NewOps);
10162 return getSequentialMinMaxExpr(S->getSCEVType(), NewOps);
10163 case scConstant:
10164 case scVScale:
10165 case scUnknown:
10166 return S;
10167 case scCouldNotCompute:
10168 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10169 }
10170 llvm_unreachable("Unknown SCEV kind!");
10171}
10172
10173SCEVUse ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
10174 switch (V->getSCEVType()) {
10175 case scConstant:
10176 case scVScale:
10177 return V;
10178 case scAddRecExpr: {
10179 // If this is a loop recurrence for a loop that does not contain L, then we
10180 // are dealing with the final value computed by the loop.
10181 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(V);
10182 // First, attempt to evaluate each operand.
10183 // Avoid performing the look-up in the common case where the specified
10184 // expression has no loop-variant portions.
10185 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
10186 SCEVUse OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
10187 if (OpAtScope == AddRec->getOperand(i))
10188 continue;
10189
10190 // Okay, at least one of these operands is loop variant but might be
10191 // foldable. Build a new instance of the folded commutative expression.
10193 NewOps.reserve(AddRec->getNumOperands());
10194 append_range(NewOps, AddRec->operands().take_front(i));
10195 NewOps.push_back(OpAtScope);
10196 for (++i; i != e; ++i)
10197 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
10198
10199 const SCEV *FoldedRec = getAddRecExpr(
10200 NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags(SCEV::FlagNW));
10201 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
10202 // The addrec may be folded to a nonrecurrence, for example, if the
10203 // induction variable is multiplied by zero after constant folding. Go
10204 // ahead and return the folded value.
10205 if (!AddRec)
10206 return FoldedRec;
10207 break;
10208 }
10209
10210 // If the scope is outside the addrec's loop, evaluate it by using the
10211 // loop exit value of the addrec.
10212 if (!AddRec->getLoop()->contains(L)) {
10213 SCEVUse ExitValue = AddRec->getExitValue(*this);
10214 if (isa<SCEVCouldNotCompute>(ExitValue))
10215 return AddRec;
10216 return ExitValue;
10217 }
10218
10219 return AddRec;
10220 }
10221 case scTruncate:
10222 case scZeroExtend:
10223 case scSignExtend:
10224 case scPtrToAddr:
10225 case scAddExpr:
10226 case scMulExpr:
10227 case scUDivExpr:
10228 case scUMaxExpr:
10229 case scSMaxExpr:
10230 case scUMinExpr:
10231 case scSMinExpr:
10232 case scSequentialUMinExpr: {
10233 ArrayRef<SCEVUse> Ops = V->operands();
10234 // Avoid performing the look-up in the common case where the specified
10235 // expression has no loop-variant portions.
10236 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
10237 SCEVUse OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10238 if (OpAtScope != Ops[i].getPointer()) {
10239 // Okay, at least one of these operands is loop variant but might be
10240 // foldable. Build a new instance of the folded commutative expression.
10242 NewOps.reserve(Ops.size());
10243 append_range(NewOps, Ops.take_front(i));
10244 NewOps.push_back(OpAtScope);
10245
10246 for (++i; i != e; ++i) {
10247 OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10248 NewOps.push_back(OpAtScope);
10249 }
10250
10251 return getWithOperands(V, NewOps);
10252 }
10253 }
10254 // If we got here, all operands are loop invariant.
10255 return V;
10256 }
10257 case scUnknown: {
10258 // If this instruction is evolved from a constant-evolving PHI, compute the
10259 // exit value from the loop without using SCEVs.
10260 const SCEVUnknown *SU = cast<SCEVUnknown>(V);
10262 if (!I)
10263 return V; // This is some other type of SCEVUnknown, just return it.
10264
10265 if (PHINode *PN = dyn_cast<PHINode>(I)) {
10266 const Loop *CurrLoop = this->LI[I->getParent()];
10267 // Looking for loop exit value.
10268 if (CurrLoop && CurrLoop->getParentLoop() == L &&
10269 PN->getParent() == CurrLoop->getHeader()) {
10270 // Okay, there is no closed form solution for the PHI node. Check
10271 // to see if the loop that contains it has a known backedge-taken
10272 // count. If so, we may be able to force computation of the exit
10273 // value.
10274 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
10275 // This trivial case can show up in some degenerate cases where
10276 // the incoming IR has not yet been fully simplified.
10277 if (BackedgeTakenCount->isZero()) {
10278 Value *InitValue = nullptr;
10279 bool MultipleInitValues = false;
10280 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
10281 if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
10282 if (!InitValue)
10283 InitValue = PN->getIncomingValue(i);
10284 else if (InitValue != PN->getIncomingValue(i)) {
10285 MultipleInitValues = true;
10286 break;
10287 }
10288 }
10289 }
10290 if (!MultipleInitValues && InitValue)
10291 return getSCEV(InitValue);
10292 }
10293 // Do we have a loop invariant value flowing around the backedge
10294 // for a loop which must execute the backedge?
10295 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
10296 isKnownNonZero(BackedgeTakenCount) &&
10297 PN->getNumIncomingValues() == 2) {
10298
10299 unsigned InLoopPred =
10300 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
10301 Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
10302 if (CurrLoop->isLoopInvariant(BackedgeVal))
10303 return getSCEV(BackedgeVal);
10304 }
10305 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
10306 // Okay, we know how many times the containing loop executes. If
10307 // this is a constant evolving PHI node, get the final value at
10308 // the specified iteration number.
10309 Constant *RV =
10310 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
10311 if (RV)
10312 return getSCEV(RV);
10313 }
10314 }
10315 }
10316
10317 // Okay, this is an expression that we cannot symbolically evaluate
10318 // into a SCEV. Check to see if it's possible to symbolically evaluate
10319 // the arguments into constants, and if so, try to constant propagate the
10320 // result. This is particularly useful for computing loop exit values.
10321 if (!canConstantFold(I, &TLI))
10322 return V; // This is some other type of SCEVUnknown, just return it.
10323
10324 SmallVector<Constant *, 4> Operands;
10325 Operands.reserve(I->getNumOperands());
10326 bool MadeImprovement = false;
10327 for (Value *Op : I->operands()) {
10328 if (Constant *C = dyn_cast<Constant>(Op)) {
10329 Operands.push_back(C);
10330 continue;
10331 }
10332
10333 // If any of the operands is non-constant and if they are
10334 // non-integer and non-pointer, don't even try to analyze them
10335 // with scev techniques.
10336 if (!isSCEVable(Op->getType()))
10337 return V;
10338
10339 const SCEV *OrigV = getSCEV(Op);
10340 const SCEV *OpV = getSCEVAtScope(OrigV, L);
10341 MadeImprovement |= OrigV != OpV;
10342
10344 if (!C)
10345 return V;
10346 assert(C->getType() == Op->getType() && "Type mismatch");
10347 Operands.push_back(C);
10348 }
10349
10350 // Check to see if getSCEVAtScope actually made an improvement.
10351 if (!MadeImprovement)
10352 return V; // This is some other type of SCEVUnknown, just return it.
10353
10354 Constant *C = nullptr;
10355 const DataLayout &DL = getDataLayout();
10356 C = ConstantFoldInstOperands(I, Operands, DL, &TLI,
10357 /*AllowNonDeterministic=*/false);
10358 if (!C)
10359 return V;
10360 return getSCEV(C);
10361 }
10362 case scCouldNotCompute:
10363 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10364 }
10365 llvm_unreachable("Unknown SCEV type!");
10366}
10367
10369 return getSCEVAtScope(getSCEV(V), L);
10370}
10371
10372const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
10374 return stripInjectiveFunctions(ZExt->getOperand());
10376 return stripInjectiveFunctions(SExt->getOperand());
10377 return S;
10378}
10379
10380/// Finds the minimum unsigned root of the following equation:
10381///
10382/// A * X = B (mod N)
10383///
10384/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
10385/// A and B isn't important.
10386///
10387/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
10388static const SCEV *
10391 ScalarEvolution &SE, const Loop *L) {
10392 uint32_t BW = A.getBitWidth();
10393 assert(BW == SE.getTypeSizeInBits(B->getType()));
10394 assert(A != 0 && "A must be non-zero.");
10395
10396 // 1. D = gcd(A, N)
10397 //
10398 // The gcd of A and N may have only one prime factor: 2. The number of
10399 // trailing zeros in A is its multiplicity
10400 uint32_t Mult2 = A.countr_zero();
10401 // D = 2^Mult2
10402
10403 // 2. Check if B is divisible by D.
10404 //
10405 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
10406 // is not less than multiplicity of this prime factor for D.
10407 unsigned MinTZ = SE.getMinTrailingZeros(B);
10408 // Try again with the terminator of the loop predecessor for context-specific
10409 // result, if MinTZ s too small.
10410 if (MinTZ < Mult2 && L->getLoopPredecessor())
10411 MinTZ = SE.getMinTrailingZeros(B, L->getLoopPredecessor()->getTerminator());
10412 if (MinTZ < Mult2) {
10413 // Check if we can prove there's no remainder using URem.
10414 const SCEV *URem =
10415 SE.getURemExpr(B, SE.getConstant(APInt::getOneBitSet(BW, Mult2)));
10416 const SCEV *Zero = SE.getZero(B->getType());
10417 if (!SE.isKnownPredicate(CmpInst::ICMP_EQ, URem, Zero)) {
10418 // Try to add a predicate ensuring B is a multiple of 1 << Mult2.
10419 if (!Predicates)
10420 return SE.getCouldNotCompute();
10421
10422 // Avoid adding a predicate that is known to be false.
10423 if (SE.isKnownPredicate(CmpInst::ICMP_NE, URem, Zero))
10424 return SE.getCouldNotCompute();
10425 Predicates->push_back(SE.getEqualPredicate(URem, Zero));
10426 }
10427 }
10428
10429 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
10430 // modulo (N / D).
10431 //
10432 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
10433 // (N / D) in general. The inverse itself always fits into BW bits, though,
10434 // so we immediately truncate it.
10435 APInt AD = A.lshr(Mult2).trunc(BW - Mult2); // AD = A / D
10436 APInt I = AD.multiplicativeInverse().zext(BW);
10437
10438 // 4. Compute the minimum unsigned root of the equation:
10439 // I * (B / D) mod (N / D)
10440 // To simplify the computation, we factor out the divide by D:
10441 // (I * B mod N) / D
10442 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
10443 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
10444}
10445
10446/// For a given quadratic addrec, generate coefficients of the corresponding
10447/// quadratic equation, multiplied by a common value to ensure that they are
10448/// integers.
10449/// The returned value is a tuple { A, B, C, M, BitWidth }, where
10450/// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
10451/// were multiplied by, and BitWidth is the bit width of the original addrec
10452/// coefficients.
10453/// This function returns std::nullopt if the addrec coefficients are not
10454/// compile- time constants.
10455static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
10457 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
10458 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
10459 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
10460 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
10461 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
10462 << *AddRec << '\n');
10463
10464 // We currently can only solve this if the coefficients are constants.
10465 if (!LC || !MC || !NC) {
10466 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
10467 return std::nullopt;
10468 }
10469
10470 APInt L = LC->getAPInt();
10471 APInt M = MC->getAPInt();
10472 APInt N = NC->getAPInt();
10473 assert(!N.isZero() && "This is not a quadratic addrec");
10474
10475 unsigned BitWidth = LC->getAPInt().getBitWidth();
10476 unsigned NewWidth = BitWidth + 1;
10477 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
10478 << BitWidth << '\n');
10479 // The sign-extension (as opposed to a zero-extension) here matches the
10480 // extension used in SolveQuadraticEquationWrap (with the same motivation).
10481 N = N.sext(NewWidth);
10482 M = M.sext(NewWidth);
10483 L = L.sext(NewWidth);
10484
10485 // The increments are M, M+N, M+2N, ..., so the accumulated values are
10486 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
10487 // L+M, L+2M+N, L+3M+3N, ...
10488 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
10489 //
10490 // The equation Acc = 0 is then
10491 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
10492 // In a quadratic form it becomes:
10493 // N n^2 + (2M-N) n + 2L = 0.
10494
10495 APInt A = N;
10496 APInt B = 2 * M - A;
10497 APInt C = 2 * L;
10498 APInt T = APInt(NewWidth, 2);
10499 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
10500 << "x + " << C << ", coeff bw: " << NewWidth
10501 << ", multiplied by " << T << '\n');
10502 return std::make_tuple(A, B, C, T, BitWidth);
10503}
10504
10505/// Helper function to compare optional APInts:
10506/// (a) if X and Y both exist, return min(X, Y),
10507/// (b) if neither X nor Y exist, return std::nullopt,
10508/// (c) if exactly one of X and Y exists, return that value.
10509static std::optional<APInt> MinOptional(std::optional<APInt> X,
10510 std::optional<APInt> Y) {
10511 if (X && Y) {
10512 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
10513 APInt XW = X->sext(W);
10514 APInt YW = Y->sext(W);
10515 return XW.slt(YW) ? *X : *Y;
10516 }
10517 if (!X && !Y)
10518 return std::nullopt;
10519 return X ? *X : *Y;
10520}
10521
10522/// Helper function to truncate an optional APInt to a given BitWidth.
10523/// When solving addrec-related equations, it is preferable to return a value
10524/// that has the same bit width as the original addrec's coefficients. If the
10525/// solution fits in the original bit width, truncate it (except for i1).
10526/// Returning a value of a different bit width may inhibit some optimizations.
10527///
10528/// In general, a solution to a quadratic equation generated from an addrec
10529/// may require BW+1 bits, where BW is the bit width of the addrec's
10530/// coefficients. The reason is that the coefficients of the quadratic
10531/// equation are BW+1 bits wide (to avoid truncation when converting from
10532/// the addrec to the equation).
10533static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
10534 unsigned BitWidth) {
10535 if (!X)
10536 return std::nullopt;
10537 unsigned W = X->getBitWidth();
10539 return X->trunc(BitWidth);
10540 return X;
10541}
10542
10543/// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
10544/// iterations. The values L, M, N are assumed to be signed, and they
10545/// should all have the same bit widths.
10546/// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
10547/// where BW is the bit width of the addrec's coefficients.
10548/// If the calculated value is a BW-bit integer (for BW > 1), it will be
10549/// returned as such, otherwise the bit width of the returned value may
10550/// be greater than BW.
10551///
10552/// This function returns std::nullopt if
10553/// (a) the addrec coefficients are not constant, or
10554/// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
10555/// like x^2 = 5, no integer solutions exist, in other cases an integer
10556/// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
10557static std::optional<APInt>
10559 APInt A, B, C, M;
10560 unsigned BitWidth;
10561 auto T = GetQuadraticEquation(AddRec);
10562 if (!T)
10563 return std::nullopt;
10564
10565 std::tie(A, B, C, M, BitWidth) = *T;
10566 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
10567 std::optional<APInt> X =
10569 if (!X)
10570 return std::nullopt;
10571
10572 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
10573 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
10574 if (!V->isZero())
10575 return std::nullopt;
10576
10577 return TruncIfPossible(X, BitWidth);
10578}
10579
10580/// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
10581/// iterations. The values M, N are assumed to be signed, and they
10582/// should all have the same bit widths.
10583/// Find the least n such that c(n) does not belong to the given range,
10584/// while c(n-1) does.
10585///
10586/// This function returns std::nullopt if
10587/// (a) the addrec coefficients are not constant, or
10588/// (b) SolveQuadraticEquationWrap was unable to find a solution for the
10589/// bounds of the range.
10590static std::optional<APInt>
10592 const ConstantRange &Range, ScalarEvolution &SE) {
10593 assert(AddRec->getOperand(0)->isZero() &&
10594 "Starting value of addrec should be 0");
10595 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
10596 << Range << ", addrec " << *AddRec << '\n');
10597 // This case is handled in getNumIterationsInRange. Here we can assume that
10598 // we start in the range.
10599 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
10600 "Addrec's initial value should be in range");
10601
10602 APInt A, B, C, M;
10603 unsigned BitWidth;
10604 auto T = GetQuadraticEquation(AddRec);
10605 if (!T)
10606 return std::nullopt;
10607
10608 // Be careful about the return value: there can be two reasons for not
10609 // returning an actual number. First, if no solutions to the equations
10610 // were found, and second, if the solutions don't leave the given range.
10611 // The first case means that the actual solution is "unknown", the second
10612 // means that it's known, but not valid. If the solution is unknown, we
10613 // cannot make any conclusions.
10614 // Return a pair: the optional solution and a flag indicating if the
10615 // solution was found.
10616 auto SolveForBoundary =
10617 [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
10618 // Solve for signed overflow and unsigned overflow, pick the lower
10619 // solution.
10620 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
10621 << Bound << " (before multiplying by " << M << ")\n");
10622 Bound *= M; // The quadratic equation multiplier.
10623
10624 std::optional<APInt> SO;
10625 if (BitWidth > 1) {
10626 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10627 "signed overflow\n");
10629 }
10630 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10631 "unsigned overflow\n");
10632 std::optional<APInt> UO =
10634
10635 auto LeavesRange = [&] (const APInt &X) {
10636 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
10637 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
10638 if (Range.contains(V0->getValue()))
10639 return false;
10640 // X should be at least 1, so X-1 is non-negative.
10641 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
10643 if (Range.contains(V1->getValue()))
10644 return true;
10645 return false;
10646 };
10647
10648 // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
10649 // can be a solution, but the function failed to find it. We cannot treat it
10650 // as "no solution".
10651 if (!SO || !UO)
10652 return {std::nullopt, false};
10653
10654 // Check the smaller value first to see if it leaves the range.
10655 // At this point, both SO and UO must have values.
10656 std::optional<APInt> Min = MinOptional(SO, UO);
10657 if (LeavesRange(*Min))
10658 return { Min, true };
10659 std::optional<APInt> Max = Min == SO ? UO : SO;
10660 if (LeavesRange(*Max))
10661 return { Max, true };
10662
10663 // Solutions were found, but were eliminated, hence the "true".
10664 return {std::nullopt, true};
10665 };
10666
10667 std::tie(A, B, C, M, BitWidth) = *T;
10668 // Lower bound is inclusive, subtract 1 to represent the exiting value.
10669 APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
10670 APInt Upper = Range.getUpper().sext(A.getBitWidth());
10671 auto SL = SolveForBoundary(Lower);
10672 auto SU = SolveForBoundary(Upper);
10673 // If any of the solutions was unknown, no meaninigful conclusions can
10674 // be made.
10675 if (!SL.second || !SU.second)
10676 return std::nullopt;
10677
10678 // Claim: The correct solution is not some value between Min and Max.
10679 //
10680 // Justification: Assuming that Min and Max are different values, one of
10681 // them is when the first signed overflow happens, the other is when the
10682 // first unsigned overflow happens. Crossing the range boundary is only
10683 // possible via an overflow (treating 0 as a special case of it, modeling
10684 // an overflow as crossing k*2^W for some k).
10685 //
10686 // The interesting case here is when Min was eliminated as an invalid
10687 // solution, but Max was not. The argument is that if there was another
10688 // overflow between Min and Max, it would also have been eliminated if
10689 // it was considered.
10690 //
10691 // For a given boundary, it is possible to have two overflows of the same
10692 // type (signed/unsigned) without having the other type in between: this
10693 // can happen when the vertex of the parabola is between the iterations
10694 // corresponding to the overflows. This is only possible when the two
10695 // overflows cross k*2^W for the same k. In such case, if the second one
10696 // left the range (and was the first one to do so), the first overflow
10697 // would have to enter the range, which would mean that either we had left
10698 // the range before or that we started outside of it. Both of these cases
10699 // are contradictions.
10700 //
10701 // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
10702 // solution is not some value between the Max for this boundary and the
10703 // Min of the other boundary.
10704 //
10705 // Justification: Assume that we had such Max_A and Min_B corresponding
10706 // to range boundaries A and B and such that Max_A < Min_B. If there was
10707 // a solution between Max_A and Min_B, it would have to be caused by an
10708 // overflow corresponding to either A or B. It cannot correspond to B,
10709 // since Min_B is the first occurrence of such an overflow. If it
10710 // corresponded to A, it would have to be either a signed or an unsigned
10711 // overflow that is larger than both eliminated overflows for A. But
10712 // between the eliminated overflows and this overflow, the values would
10713 // cover the entire value space, thus crossing the other boundary, which
10714 // is a contradiction.
10715
10716 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
10717}
10718
10719ScalarEvolution::ExitLimit ScalarEvolution::howFarToZero(const SCEV *V,
10720 const Loop *L,
10721 bool ControlsOnlyExit,
10722 bool AllowPredicates) {
10723
10724 // This is only used for loops with a "x != y" exit test. The exit condition
10725 // is now expressed as a single expression, V = x-y. So the exit test is
10726 // effectively V != 0. We know and take advantage of the fact that this
10727 // expression only being used in a comparison by zero context.
10728
10730 // If the value is a constant
10731 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10732 // If the value is already zero, the branch will execute zero times.
10733 if (C->getValue()->isZero()) return C;
10734 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10735 }
10736
10737 const SCEVAddRecExpr *AddRec =
10738 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
10739
10740 if (!AddRec && AllowPredicates)
10741 // Try to make this an AddRec using runtime tests, in the first X
10742 // iterations of this loop, where X is the SCEV expression found by the
10743 // algorithm below.
10744 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
10745
10746 if (!AddRec || AddRec->getLoop() != L)
10747 return getCouldNotCompute();
10748
10749 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
10750 // the quadratic equation to solve it.
10751 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
10752 // We can only use this value if the chrec ends up with an exact zero
10753 // value at this index. When solving for "X*X != 5", for example, we
10754 // should not accept a root of 2.
10755 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
10756 const auto *R = cast<SCEVConstant>(getConstant(*S));
10757 return ExitLimit(R, R, R, false, Predicates);
10758 }
10759 return getCouldNotCompute();
10760 }
10761
10762 // Otherwise we can only handle this if it is affine.
10763 if (!AddRec->isAffine())
10764 return getCouldNotCompute();
10765
10766 // If this is an affine expression, the execution count of this branch is
10767 // the minimum unsigned root of the following equation:
10768 //
10769 // Start + Step*N = 0 (mod 2^BW)
10770 //
10771 // equivalent to:
10772 //
10773 // Step*N = -Start (mod 2^BW)
10774 //
10775 // where BW is the common bit width of Start and Step.
10776
10777 // Get the initial value for the loop.
10778 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
10779 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
10780
10781 if (!isLoopInvariant(Step, L))
10782 return getCouldNotCompute();
10783
10784 LoopGuards Guards = LoopGuards::collect(L, *this);
10785 // Specialize step for this loop so we get context sensitive facts below.
10786 const SCEV *StepWLG = applyLoopGuards(Step, Guards);
10787
10788 // For positive steps (counting up until unsigned overflow):
10789 // N = -Start/Step (as unsigned)
10790 // For negative steps (counting down to zero):
10791 // N = Start/-Step
10792 // First compute the unsigned distance from zero in the direction of Step.
10793 bool CountDown = isKnownNegative(StepWLG);
10794 if (!CountDown && !isKnownNonNegative(StepWLG))
10795 return getCouldNotCompute();
10796
10797 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
10798 // Handle unitary steps, which cannot wraparound.
10799 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10800 // N = Distance (as unsigned)
10801
10802 if (match(Step, m_CombineOr(m_scev_One(), m_scev_AllOnes()))) {
10803 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, Guards));
10804 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
10805
10806 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10807 // we end up with a loop whose backedge-taken count is n - 1. Detect this
10808 // case, and see if we can improve the bound.
10809 //
10810 // Explicitly handling this here is necessary because getUnsignedRange
10811 // isn't context-sensitive; it doesn't know that we only care about the
10812 // range inside the loop.
10813 const SCEV *Zero = getZero(Distance->getType());
10814 const SCEV *One = getOne(Distance->getType());
10815 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
10816 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
10817 // If Distance + 1 doesn't overflow, we can compute the maximum distance
10818 // as "unsigned_max(Distance + 1) - 1". Also apply the loop guards to
10819 // Distance + 1; the range of Distance itself may be a wrapped set even
10820 // when the guards bound Distance + 1 tightly.
10821 APInt Max = APIntOps::umin(
10822 getUnsignedRangeMax(applyLoopGuards(DistancePlusOne, Guards)),
10823 getUnsignedRangeMax(DistancePlusOne));
10824 MaxBECount = APIntOps::umin(MaxBECount, Max - 1);
10825 }
10826 return ExitLimit(Distance, getConstant(MaxBECount), Distance, false,
10827 Predicates);
10828 }
10829
10830 // If the condition controls loop exit (the loop exits only if the expression
10831 // is true) and the addition is no-wrap we can use unsigned divide to
10832 // compute the backedge count. In this case, the step may not divide the
10833 // distance, but we don't care because if the condition is "missed" the loop
10834 // will have undefined behavior due to wrapping.
10835 if (ControlsOnlyExit && AddRec->hasNoSelfWrap() &&
10836 loopHasNoAbnormalExits(AddRec->getLoop())) {
10837
10838 // If the stride is zero and the start is non-zero, the loop must be
10839 // infinite. In C++, most loops are finite by assumption, in which case the
10840 // step being zero implies UB must execute if the loop is entered.
10841 if (!(loopIsFiniteByAssumption(L) && isKnownNonZero(Start)) &&
10842 !isKnownNonZero(StepWLG))
10843 return getCouldNotCompute();
10844
10845 const SCEV *Exact =
10846 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10847 const SCEV *ConstantMax = getCouldNotCompute();
10848 if (Exact != getCouldNotCompute()) {
10849 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, Guards));
10850 ConstantMax =
10852 }
10853 const SCEV *SymbolicMax =
10854 isa<SCEVCouldNotCompute>(Exact) ? ConstantMax : Exact;
10855 return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
10856 }
10857
10858 // Solve the general equation.
10859 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
10860 if (!StepC || StepC->getValue()->isZero())
10861 return getCouldNotCompute();
10862 const SCEV *E = SolveLinEquationWithOverflow(
10863 StepC->getAPInt(), getNegativeSCEV(Start),
10864 AllowPredicates ? &Predicates : nullptr, *this, L);
10865
10866 const SCEV *M = E;
10867 if (E != getCouldNotCompute()) {
10868 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, Guards));
10869 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
10870 }
10871 auto *S = isa<SCEVCouldNotCompute>(E) ? M : E;
10872 return ExitLimit(E, M, S, false, Predicates);
10873}
10874
10875ScalarEvolution::ExitLimit
10876ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10877 // Loops that look like: while (X == 0) are very strange indeed. We don't
10878 // handle them yet except for the trivial case. This could be expanded in the
10879 // future as needed.
10880
10881 // If the value is a constant, check to see if it is known to be non-zero
10882 // already. If so, the backedge will execute zero times.
10883 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10884 if (!C->getValue()->isZero())
10885 return getZero(C->getType());
10886 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10887 }
10888
10889 // We could implement others, but I really doubt anyone writes loops like
10890 // this, and if they did, they would already be constant folded.
10891 return getCouldNotCompute();
10892}
10893
10894std::pair<const BasicBlock *, const BasicBlock *>
10895ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10896 const {
10897 // If the block has a unique predecessor, then there is no path from the
10898 // predecessor to the block that does not go through the direct edge
10899 // from the predecessor to the block.
10900 if (const BasicBlock *Pred = BB->getSinglePredecessor())
10901 return {Pred, BB};
10902
10903 // A loop's header is defined to be a block that dominates the loop.
10904 // If the header has a unique predecessor outside the loop, it must be
10905 // a block that has exactly one successor that can reach the loop.
10906 if (const Loop *L = LI.getLoopFor(BB))
10907 return {L->getLoopPredecessor(), L->getHeader()};
10908
10909 return {nullptr, BB};
10910}
10911
10912/// SCEV structural equivalence is usually sufficient for testing whether two
10913/// expressions are equal, however for the purposes of looking for a condition
10914/// guarding a loop, it can be useful to be a little more general, since a
10915/// front-end may have replicated the controlling expression.
10916static bool HasSameValue(const SCEV *A, const SCEV *B) {
10917 // Quick check to see if they are the same SCEV.
10918 if (A == B) return true;
10919
10920 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10921 // Not all instructions that are "identical" compute the same value. For
10922 // instance, two distinct alloca instructions allocating the same type are
10923 // identical and do not read memory; but compute distinct values.
10924 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
10925 };
10926
10927 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10928 // two different instructions with the same value. Check for this case.
10929 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
10930 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
10931 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
10932 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
10933 if (ComputesEqualValues(AI, BI))
10934 return true;
10935
10936 // Otherwise assume they may have a different value.
10937 return false;
10938}
10939
10940static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS) {
10941 const SCEV *Op0, *Op1;
10942 if (!match(S, m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))))
10943 return false;
10944 if (match(Op0, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10945 LHS = Op1;
10946 return true;
10947 }
10948 if (match(Op1, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10949 LHS = Op0;
10950 return true;
10951 }
10952 return false;
10953}
10954
10956 SCEVUse &RHS, unsigned Depth) {
10957 bool Changed = false;
10958 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
10959 // '0 != 0'.
10960 auto TrivialCase = [&](bool TriviallyTrue) {
10962 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
10963 return true;
10964 };
10965 // If we hit the max recursion limit bail out.
10966 if (Depth >= 3)
10967 return false;
10968
10969 const SCEV *NewLHS, *NewRHS;
10970 if (match(LHS, m_scev_c_Mul(m_SCEV(NewLHS), m_SCEVVScale())) &&
10971 match(RHS, m_scev_c_Mul(m_SCEV(NewRHS), m_SCEVVScale()))) {
10972 const SCEVMulExpr *LMul = cast<SCEVMulExpr>(LHS);
10973 const SCEVMulExpr *RMul = cast<SCEVMulExpr>(RHS);
10974
10975 // (X * vscale) pred (Y * vscale) ==> X pred Y
10976 // when both multiples are NSW.
10977 // (X * vscale) uicmp/eq/ne (Y * vscale) ==> X uicmp/eq/ne Y
10978 // when both multiples are NUW.
10979 if ((LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap()) ||
10980 (LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap() &&
10981 !ICmpInst::isSigned(Pred))) {
10982 LHS = NewLHS;
10983 RHS = NewRHS;
10984 Changed = true;
10985 }
10986 }
10987
10988 // Canonicalize a constant to the right side.
10989 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
10990 // Check for both operands constant.
10991 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
10992 if (!ICmpInst::compare(LHSC->getAPInt(), RHSC->getAPInt(), Pred))
10993 return TrivialCase(false);
10994 return TrivialCase(true);
10995 }
10996 // Otherwise swap the operands to put the constant on the right.
10997 std::swap(LHS, RHS);
10999 Changed = true;
11000 }
11001
11002 // (K + A) pred (K + B) --> A pred B
11003 // For equality, no flags are needed.
11004 // For signed, both adds must be NSW. For unsigned, both must be NUW.
11005 {
11006 const SCEVConstant *C = nullptr;
11007 if (match(LHS, m_scev_Add(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11008 match(RHS, m_scev_Add(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11009 const auto *LAdd = cast<SCEVAddExpr>(LHS);
11010 const auto *RAdd = cast<SCEVAddExpr>(RHS);
11011 if (ICmpInst::isEquality(Pred) ||
11012 (ICmpInst::isSigned(Pred) && LAdd->hasNoSignedWrap() &&
11013 RAdd->hasNoSignedWrap()) ||
11014 (ICmpInst::isUnsigned(Pred) && LAdd->hasNoUnsignedWrap() &&
11015 RAdd->hasNoUnsignedWrap())) {
11016 LHS = NewLHS;
11017 RHS = NewRHS;
11018 Changed = true;
11019 }
11020 }
11021 }
11022
11023 // (C * A) pred (C * B) --> A pred B
11024 // For equality predicates, both muls must be NUW or both must be NSW
11025 // (either suffices to make multiplication by C injective; C == 0 is
11026 // impossible because SCEV folds 0 * X to 0).
11027 // For signed ordering, C must be positive and both muls must be NSW.
11028 // For unsigned ordering, both muls must be NUW.
11029 {
11030 const SCEVConstant *C = nullptr;
11031 if (match(LHS, m_scev_Mul(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11032 match(RHS, m_scev_Mul(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11033 const auto *LMul = cast<SCEVMulExpr>(LHS);
11034 const auto *RMul = cast<SCEVMulExpr>(RHS);
11035 bool BothNUW = LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap();
11036 bool BothNSW = LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap();
11037 if ((ICmpInst::isEquality(Pred) && (BothNUW || BothNSW)) ||
11038 (ICmpInst::isSigned(Pred) && BothNSW &&
11039 C->getAPInt().isStrictlyPositive()) ||
11040 (ICmpInst::isUnsigned(Pred) && BothNUW)) {
11041 LHS = NewLHS;
11042 RHS = NewRHS;
11043 Changed = true;
11044 }
11045 }
11046 }
11047
11048 // If we're comparing an addrec with a value which is loop-invariant in the
11049 // addrec's loop, put the addrec on the left. Also make a dominance check,
11050 // as both operands could be addrecs loop-invariant in each other's loop.
11051 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
11052 const Loop *L = AR->getLoop();
11053 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
11054 std::swap(LHS, RHS);
11056 Changed = true;
11057 }
11058 }
11059
11060 // If there's a constant operand, canonicalize comparisons with boundary
11061 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
11062 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
11063 const APInt &RA = RC->getAPInt();
11064
11065 bool SimplifiedByConstantRange = false;
11066
11067 if (!ICmpInst::isEquality(Pred)) {
11069 if (ExactCR.isFullSet())
11070 return TrivialCase(true);
11071 if (ExactCR.isEmptySet())
11072 return TrivialCase(false);
11073
11074 APInt NewRHS;
11075 CmpInst::Predicate NewPred;
11076 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
11077 ICmpInst::isEquality(NewPred)) {
11078 // We were able to convert an inequality to an equality.
11079 Pred = NewPred;
11080 RHS = getConstant(NewRHS);
11081 Changed = SimplifiedByConstantRange = true;
11082 }
11083 }
11084
11085 if (!SimplifiedByConstantRange) {
11086 switch (Pred) {
11087 default:
11088 break;
11089 case ICmpInst::ICMP_EQ:
11090 case ICmpInst::ICMP_NE:
11091 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
11092 if (RA.isZero() && MatchBinarySub(LHS, LHS, RHS))
11093 Changed = true;
11094 break;
11095
11096 // The "Should have been caught earlier!" messages refer to the fact
11097 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
11098 // should have fired on the corresponding cases, and canonicalized the
11099 // check to trivial case.
11100
11101 case ICmpInst::ICMP_UGE:
11102 assert(!RA.isMinValue() && "Should have been caught earlier!");
11103 Pred = ICmpInst::ICMP_UGT;
11104 RHS = getConstant(RA - 1);
11105 Changed = true;
11106 break;
11107 case ICmpInst::ICMP_ULE:
11108 assert(!RA.isMaxValue() && "Should have been caught earlier!");
11109 Pred = ICmpInst::ICMP_ULT;
11110 RHS = getConstant(RA + 1);
11111 Changed = true;
11112 break;
11113 case ICmpInst::ICMP_SGE:
11114 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
11115 Pred = ICmpInst::ICMP_SGT;
11116 RHS = getConstant(RA - 1);
11117 Changed = true;
11118 break;
11119 case ICmpInst::ICMP_SLE:
11120 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
11121 Pred = ICmpInst::ICMP_SLT;
11122 RHS = getConstant(RA + 1);
11123 Changed = true;
11124 break;
11125 }
11126 }
11127 }
11128
11129 // a /u b == 0 => a < b
11130 // a /u b != 0 => a >= b
11131 if (ICmpInst::isEquality(Pred) && RHS->isZero() &&
11132 match(LHS, m_scev_UDiv(m_SCEV(LHS), m_SCEV(RHS)))) {
11134 Changed = true;
11135 }
11136
11137 // Check for obvious equality.
11138 if (HasSameValue(LHS, RHS)) {
11139 if (ICmpInst::isTrueWhenEqual(Pred))
11140 return TrivialCase(true);
11142 return TrivialCase(false);
11143 }
11144
11145 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
11146 // adding or subtracting 1 from one of the operands.
11147 switch (Pred) {
11148 case ICmpInst::ICMP_SLE:
11149 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
11150 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11152 Pred = ICmpInst::ICMP_SLT;
11153 Changed = true;
11154 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
11155 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
11157 Pred = ICmpInst::ICMP_SLT;
11158 Changed = true;
11159 }
11160 break;
11161 case ICmpInst::ICMP_SGE:
11162 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
11163 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
11165 Pred = ICmpInst::ICMP_SGT;
11166 Changed = true;
11167 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
11168 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11170 Pred = ICmpInst::ICMP_SGT;
11171 Changed = true;
11172 }
11173 break;
11174 case ICmpInst::ICMP_ULE:
11175 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
11176 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11178 Pred = ICmpInst::ICMP_ULT;
11179 Changed = true;
11180 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
11181 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
11182 Pred = ICmpInst::ICMP_ULT;
11183 Changed = true;
11184 }
11185 break;
11186 case ICmpInst::ICMP_UGE:
11187 // If RHS is an op we can fold the -1, try that first.
11188 // Otherwise prefer LHS to preserve the nuw flag.
11189 if ((isa<SCEVConstant>(RHS) ||
11191 isa<SCEVConstant>(cast<SCEVNAryExpr>(RHS)->getOperand(0)))) &&
11192 !getUnsignedRangeMin(RHS).isMinValue()) {
11193 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11194 Pred = ICmpInst::ICMP_UGT;
11195 Changed = true;
11196 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
11197 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11199 Pred = ICmpInst::ICMP_UGT;
11200 Changed = true;
11201 } else if (!getUnsignedRangeMin(RHS).isMinValue()) {
11202 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11203 Pred = ICmpInst::ICMP_UGT;
11204 Changed = true;
11205 }
11206 break;
11207 default:
11208 break;
11209 }
11210
11211 // TODO: More simplifications are possible here.
11212
11213 // Recursively simplify until we either hit a recursion limit or nothing
11214 // changes.
11215 if (Changed)
11216 (void)SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1);
11217
11218 return Changed;
11219}
11220
11222 return getSignedRangeMax(S).isNegative();
11223}
11224
11228
11230 return !getSignedRangeMin(S).isNegative();
11231}
11232
11236
11238 // Query push down for cases where the unsigned range is
11239 // less than sufficient.
11240 if (const auto *SExt = dyn_cast<SCEVSignExtendExpr>(S))
11241 return isKnownNonZero(SExt->getOperand(0));
11242 return getUnsignedRangeMin(S) != 0;
11243}
11244
11246 bool OrNegative) {
11247 auto NonRecursive = [OrNegative](const SCEV *S) {
11248 if (auto *C = dyn_cast<SCEVConstant>(S))
11249 return C->getAPInt().isPowerOf2() ||
11250 (OrNegative && C->getAPInt().isNegatedPowerOf2());
11251
11252 // vscale is a power-of-two.
11253 return isa<SCEVVScale>(S);
11254 };
11255
11256 if (NonRecursive(S))
11257 return true;
11258
11259 auto *Mul = dyn_cast<SCEVMulExpr>(S);
11260 if (!Mul)
11261 return false;
11262 return all_of(Mul->operands(), NonRecursive) && (OrZero || isKnownNonZero(S));
11263}
11264
11266 const SCEV *S, uint64_t M,
11268 if (M == 0)
11269 return false;
11270 if (M == 1)
11271 return true;
11272
11273 // Recursively check AddRec operands. An AddRecExpr S is a multiple of M if S
11274 // starts with a multiple of M and at every iteration step S only adds
11275 // multiples of M.
11276 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
11277 return isKnownMultipleOf(AddRec->getStart(), M, Predicates) &&
11278 isKnownMultipleOf(AddRec->getStepRecurrence(*this), M, Predicates);
11279
11280 // For a constant, check that "S % M == 0".
11281 if (auto *Cst = dyn_cast<SCEVConstant>(S)) {
11282 APInt C = Cst->getAPInt();
11283 return C.urem(M) == 0;
11284 }
11285
11286 // TODO: Also check other SCEV expressions, i.e., SCEVAddRecExpr, etc.
11287
11288 // Basic tests have failed.
11289 // Check "S % M == 0" at compile time and record runtime Assumptions.
11290 auto *STy = dyn_cast<IntegerType>(S->getType());
11291 const SCEV *SmodM =
11292 getURemExpr(S, getConstant(ConstantInt::get(STy, M, false)));
11293 const SCEV *Zero = getZero(STy);
11294
11295 // Check whether "S % M == 0" is known at compile time.
11296 if (isKnownPredicate(ICmpInst::ICMP_EQ, SmodM, Zero))
11297 return true;
11298
11299 // Check whether "S % M != 0" is known at compile time.
11300 if (isKnownPredicate(ICmpInst::ICMP_NE, SmodM, Zero))
11301 return false;
11302
11303 if (!Predicates)
11304 return false;
11305
11307
11308 // Detect redundant predicates.
11309 for (auto *A : *Predicates)
11310 if (A->implies(P, *this))
11311 return true;
11312
11313 // Only record non-redundant predicates.
11314 Predicates->push_back(P);
11315 return true;
11316}
11317
11319 return ((isKnownNonNegative(S1) && isKnownNonNegative(S2)) ||
11321}
11322
11323std::pair<const SCEV *, const SCEV *>
11325 // Compute SCEV on entry of loop L.
11326 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
11327 if (Start == getCouldNotCompute())
11328 return { Start, Start };
11329 // Compute post increment SCEV for loop L.
11330 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
11331 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
11332 return { Start, PostInc };
11333}
11334
11336 SCEVUse RHS) {
11337 // First collect all loops.
11339 getUsedLoops(LHS, LoopsUsed);
11340 getUsedLoops(RHS, LoopsUsed);
11341
11342 if (LoopsUsed.empty())
11343 return false;
11344
11345 // Domination relationship must be a linear order on collected loops.
11346#ifndef NDEBUG
11347 for (const auto *L1 : LoopsUsed)
11348 for (const auto *L2 : LoopsUsed)
11349 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
11350 DT.dominates(L2->getHeader(), L1->getHeader())) &&
11351 "Domination relationship is not a linear order");
11352#endif
11353
11354 const Loop *MDL =
11355 *llvm::max_element(LoopsUsed, [&](const Loop *L1, const Loop *L2) {
11356 return DT.properlyDominates(L1->getHeader(), L2->getHeader());
11357 });
11358
11359 // Get init and post increment value for LHS.
11360 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
11361 // if LHS contains unknown non-invariant SCEV then bail out.
11362 if (SplitLHS.first == getCouldNotCompute())
11363 return false;
11364 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
11365 // Get init and post increment value for RHS.
11366 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
11367 // if RHS contains unknown non-invariant SCEV then bail out.
11368 if (SplitRHS.first == getCouldNotCompute())
11369 return false;
11370 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
11371 // It is possible that init SCEV contains an invariant load but it does
11372 // not dominate MDL and is not available at MDL loop entry, so we should
11373 // check it here.
11374 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
11375 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
11376 return false;
11377
11378 // It seems backedge guard check is faster than entry one so in some cases
11379 // it can speed up whole estimation by short circuit
11380 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
11381 SplitRHS.second) &&
11382 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
11383}
11384
11386 SCEVUse RHS) {
11387 // Canonicalize the inputs first.
11388 (void)SimplifyICmpOperands(Pred, LHS, RHS);
11389
11390 return isKnownViaInduction(Pred, LHS, RHS) ||
11391 isKnownPredicateViaSplitting(Pred, LHS, RHS) ||
11392 isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
11393}
11394
11396 const SCEV *LHS,
11397 const SCEV *RHS) {
11398 if (isKnownPredicate(Pred, LHS, RHS))
11399 return true;
11401 return false;
11402 return std::nullopt;
11403}
11404
11406 const SCEV *RHS,
11407 const Instruction *CtxI) {
11408 // TODO: Analyze guards and assumes from Context's block.
11409 return isKnownPredicate(Pred, LHS, RHS) ||
11410 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
11411}
11412
11413std::optional<bool>
11415 const SCEV *RHS, const Instruction *CtxI) {
11416 std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
11417 if (KnownWithoutContext)
11418 return KnownWithoutContext;
11419
11420 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
11421 return true;
11423 CtxI->getParent(), ICmpInst::getInverseCmpPredicate(Pred), LHS, RHS))
11424 return false;
11425 return std::nullopt;
11426}
11427
11429 const SCEVAddRecExpr *LHS,
11430 const SCEV *RHS) {
11431 const Loop *L = LHS->getLoop();
11432 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
11433 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
11434}
11435
11436std::optional<ScalarEvolution::MonotonicPredicateType>
11438 ICmpInst::Predicate Pred) {
11439 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
11440
11441#ifndef NDEBUG
11442 // Verify an invariant: inverting the predicate should turn a monotonically
11443 // increasing change to a monotonically decreasing one, and vice versa.
11444 if (Result) {
11445 auto ResultSwapped =
11446 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
11447
11448 assert(*ResultSwapped != *Result &&
11449 "monotonicity should flip as we flip the predicate");
11450 }
11451#endif
11452
11453 return Result;
11454}
11455
11456std::optional<ScalarEvolution::MonotonicPredicateType>
11457ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
11458 ICmpInst::Predicate Pred) {
11459 // A zero step value for LHS means the induction variable is essentially a
11460 // loop invariant value. We don't really depend on the predicate actually
11461 // flipping from false to true (for increasing predicates, and the other way
11462 // around for decreasing predicates), all we care about is that *if* the
11463 // predicate changes then it only changes from false to true.
11464 //
11465 // A zero step value in itself is not very useful, but there may be places
11466 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
11467 // as general as possible.
11468
11469 // Only handle LE/LT/GE/GT predicates.
11470 if (!ICmpInst::isRelational(Pred))
11471 return std::nullopt;
11472
11473 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
11474 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
11475 "Should be greater or less!");
11476
11477 // Check that AR does not wrap.
11478 if (ICmpInst::isUnsigned(Pred)) {
11479 if (!LHS->hasNoUnsignedWrap())
11480 return std::nullopt;
11482 }
11483 assert(ICmpInst::isSigned(Pred) &&
11484 "Relational predicate is either signed or unsigned!");
11485 if (!LHS->hasNoSignedWrap())
11486 return std::nullopt;
11487
11488 const SCEV *Step = LHS->getStepRecurrence(*this);
11489
11490 if (isKnownNonNegative(Step))
11492
11493 if (isKnownNonPositive(Step))
11495
11496 return std::nullopt;
11497}
11498
11499std::optional<ScalarEvolution::LoopInvariantPredicate>
11501 const SCEV *RHS, const Loop *L,
11502 const Instruction *CtxI) {
11503 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11504 if (!isLoopInvariant(RHS, L)) {
11505 if (!isLoopInvariant(LHS, L))
11506 return std::nullopt;
11507
11508 std::swap(LHS, RHS);
11510 }
11511
11512 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11513 if (!ArLHS || ArLHS->getLoop() != L)
11514 return std::nullopt;
11515
11516 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
11517 if (!MonotonicType)
11518 return std::nullopt;
11519 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
11520 // true as the loop iterates, and the backedge is control dependent on
11521 // "ArLHS `Pred` RHS" == true then we can reason as follows:
11522 //
11523 // * if the predicate was false in the first iteration then the predicate
11524 // is never evaluated again, since the loop exits without taking the
11525 // backedge.
11526 // * if the predicate was true in the first iteration then it will
11527 // continue to be true for all future iterations since it is
11528 // monotonically increasing.
11529 //
11530 // For both the above possibilities, we can replace the loop varying
11531 // predicate with its value on the first iteration of the loop (which is
11532 // loop invariant).
11533 //
11534 // A similar reasoning applies for a monotonically decreasing predicate, by
11535 // replacing true with false and false with true in the above two bullets.
11537 auto P = Increasing ? Pred : ICmpInst::getInverseCmpPredicate(Pred);
11538
11539 if (isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
11541 RHS);
11542
11543 if (!CtxI)
11544 return std::nullopt;
11545 // Try to prove via context.
11546 // TODO: Support other cases.
11547 switch (Pred) {
11548 default:
11549 break;
11550 case ICmpInst::ICMP_ULE:
11551 case ICmpInst::ICMP_ULT: {
11552 assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!");
11553 // Given preconditions
11554 // (1) ArLHS does not cross the border of positive and negative parts of
11555 // range because of:
11556 // - Positive step; (TODO: lift this limitation)
11557 // - nuw - does not cross zero boundary;
11558 // - nsw - does not cross SINT_MAX boundary;
11559 // (2) ArLHS <s RHS
11560 // (3) RHS >=s 0
11561 // we can replace the loop variant ArLHS <u RHS condition with loop
11562 // invariant Start(ArLHS) <u RHS.
11563 //
11564 // Because of (1) there are two options:
11565 // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
11566 // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
11567 // It means that ArLHS <s RHS <=> ArLHS <u RHS.
11568 // Because of (2) ArLHS <u RHS is trivially true.
11569 // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
11570 // We can strengthen this to Start(ArLHS) <u RHS.
11571 auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
11572 if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
11573 isKnownPositive(ArLHS->getStepRecurrence(*this)) &&
11574 isKnownNonNegative(RHS) &&
11575 isKnownPredicateAt(SignFlippedPred, ArLHS, RHS, CtxI))
11577 RHS);
11578 }
11579 }
11580
11581 return std::nullopt;
11582}
11583
11584std::optional<ScalarEvolution::LoopInvariantPredicate>
11586 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11587 const Instruction *CtxI, const SCEV *MaxIter) {
11589 Pred, LHS, RHS, L, CtxI, MaxIter))
11590 return LIP;
11591 if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
11592 // Number of iterations expressed as UMIN isn't always great for expressing
11593 // the value on the last iteration. If the straightforward approach didn't
11594 // work, try the following trick: if the a predicate is invariant for X, it
11595 // is also invariant for umin(X, ...). So try to find something that works
11596 // among subexpressions of MaxIter expressed as umin.
11597 for (SCEVUse Op : UMin->operands())
11599 Pred, LHS, RHS, L, CtxI, Op))
11600 return LIP;
11601 return std::nullopt;
11602}
11603
11604std::optional<ScalarEvolution::LoopInvariantPredicate>
11606 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11607 const Instruction *CtxI, const SCEV *MaxIter) {
11608 // Try to prove the following set of facts:
11609 // - The predicate is monotonic in the iteration space.
11610 // - If the check does not fail on the 1st iteration:
11611 // - No overflow will happen during first MaxIter iterations;
11612 // - It will not fail on the MaxIter'th iteration.
11613 // If the check does fail on the 1st iteration, we leave the loop and no
11614 // other checks matter.
11615
11616 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11617 if (!isLoopInvariant(RHS, L)) {
11618 if (!isLoopInvariant(LHS, L))
11619 return std::nullopt;
11620
11621 std::swap(LHS, RHS);
11623 }
11624
11625 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
11626 if (!AR || AR->getLoop() != L)
11627 return std::nullopt;
11628
11629 // Even if both are valid, we need to consistently chose the unsigned or the
11630 // signed predicate below, not mixtures of both. For now, prefer the unsigned
11631 // predicate.
11632 Pred = Pred.dropSameSign();
11633
11634 // The predicate must be relational (i.e. <, <=, >=, >).
11635 if (!ICmpInst::isRelational(Pred))
11636 return std::nullopt;
11637
11638 // TODO: Support steps other than +/- 1.
11639 const SCEV *Step = AR->getStepRecurrence(*this);
11640 auto *One = getOne(Step->getType());
11641 auto *MinusOne = getNegativeSCEV(One);
11642 if (Step != One && Step != MinusOne)
11643 return std::nullopt;
11644
11645 // Type mismatch here means that MaxIter is potentially larger than max
11646 // unsigned value in start type, which mean we cannot prove no wrap for the
11647 // indvar.
11648 if (AR->getType() != MaxIter->getType())
11649 return std::nullopt;
11650
11651 // Value of IV on suggested last iteration.
11652 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
11653 // Does it still meet the requirement?
11654 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
11655 return std::nullopt;
11656 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
11657 // not exceed max unsigned value of this type), this effectively proves
11658 // that there is no wrap during the iteration. To prove that there is no
11659 // signed/unsigned wrap, we need to check that
11660 // Start <= Last for step = 1 or Start >= Last for step = -1.
11661 ICmpInst::Predicate NoOverflowPred =
11663 if (Step == MinusOne)
11664 NoOverflowPred = ICmpInst::getSwappedPredicate(NoOverflowPred);
11665 const SCEV *Start = AR->getStart();
11666 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
11667 return std::nullopt;
11668
11669 // Everything is fine.
11670 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
11671}
11672
11673bool ScalarEvolution::isKnownPredicateViaConstantRanges(CmpPredicate Pred,
11674 SCEVUse LHS,
11675 SCEVUse RHS) {
11676 if (HasSameValue(LHS, RHS))
11677 return ICmpInst::isTrueWhenEqual(Pred);
11678
11679 auto CheckRange = [&](bool IsSigned) {
11680 auto RangeLHS = IsSigned ? getSignedRange(LHS) : getUnsignedRange(LHS);
11681 auto RangeRHS = IsSigned ? getSignedRange(RHS) : getUnsignedRange(RHS);
11682 return RangeLHS.icmp(Pred, RangeRHS);
11683 };
11684
11685 // The check at the top of the function catches the case where the values are
11686 // known to be equal.
11687 if (Pred == CmpInst::ICMP_EQ)
11688 return false;
11689
11690 if (Pred == CmpInst::ICMP_NE) {
11691 if (CheckRange(true) || CheckRange(false))
11692 return true;
11693 auto *Diff = getMinusSCEV(LHS, RHS);
11694 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
11695 }
11696
11697 return CheckRange(CmpInst::isSigned(Pred));
11698}
11699
11700bool ScalarEvolution::isKnownPredicateViaNoOverflow(CmpPredicate Pred,
11702 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
11703 // C1 and C2 are constant integers. If either X or Y are not add expressions,
11704 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
11705 // OutC1 and OutC2.
11706 auto MatchBinaryAddToConst = [this](SCEVUse X, SCEVUse Y, APInt &OutC1,
11707 APInt &OutC2,
11708 SCEV::NoWrapFlags ExpectedFlags) {
11709 SCEVUse XNonConstOp, XConstOp;
11710 SCEVUse YNonConstOp, YConstOp;
11711 SCEV::NoWrapFlags XFlagsPresent;
11712 SCEV::NoWrapFlags YFlagsPresent;
11713
11714 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
11715 XConstOp = getZero(X->getType());
11716 XNonConstOp = X;
11717 XFlagsPresent = ExpectedFlags;
11718 }
11719 if (!isa<SCEVConstant>(XConstOp))
11720 return false;
11721
11722 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
11723 YConstOp = getZero(Y->getType());
11724 YNonConstOp = Y;
11725 YFlagsPresent = ExpectedFlags;
11726 }
11727
11728 if (YNonConstOp != XNonConstOp)
11729 return false;
11730
11731 if (!isa<SCEVConstant>(YConstOp))
11732 return false;
11733
11734 // When matching ADDs with NUW flags (and unsigned predicates), only the
11735 // second ADD (with the larger constant) requires NUW.
11736 if ((YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11737 return false;
11738 if (ExpectedFlags != SCEV::FlagNUW &&
11739 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) {
11740 return false;
11741 }
11742
11743 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
11744 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
11745
11746 return true;
11747 };
11748
11749 APInt C1;
11750 APInt C2;
11751
11752 switch (Pred) {
11753 default:
11754 break;
11755
11756 case ICmpInst::ICMP_SGE:
11757 std::swap(LHS, RHS);
11758 [[fallthrough]];
11759 case ICmpInst::ICMP_SLE:
11760 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
11761 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
11762 return true;
11763
11764 break;
11765
11766 case ICmpInst::ICMP_SGT:
11767 std::swap(LHS, RHS);
11768 [[fallthrough]];
11769 case ICmpInst::ICMP_SLT:
11770 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
11771 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
11772 return true;
11773
11774 break;
11775
11776 case ICmpInst::ICMP_UGE:
11777 std::swap(LHS, RHS);
11778 [[fallthrough]];
11779 case ICmpInst::ICMP_ULE:
11780 // (X + C1) u<= (X + C2)<nuw> for C1 u<= C2.
11781 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ule(C2))
11782 return true;
11783
11784 break;
11785
11786 case ICmpInst::ICMP_UGT:
11787 std::swap(LHS, RHS);
11788 [[fallthrough]];
11789 case ICmpInst::ICMP_ULT:
11790 // (X + C1) u< (X + C2)<nuw> if C1 u< C2.
11791 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ult(C2))
11792 return true;
11793 break;
11794 }
11795
11796 return false;
11797}
11798
11799bool ScalarEvolution::isKnownPredicateViaSplitting(CmpPredicate Pred,
11801 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
11802 return false;
11803
11804 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
11805 // the stack can result in exponential time complexity.
11806 SaveAndRestore Restore(ProvingSplitPredicate, true);
11807
11808 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
11809 //
11810 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
11811 // isKnownPredicate. isKnownPredicate is more powerful, but also more
11812 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
11813 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
11814 // use isKnownPredicate later if needed.
11815 return isKnownNonNegative(RHS) &&
11818}
11819
11820bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, CmpPredicate Pred,
11821 const SCEV *LHS, const SCEV *RHS) {
11822 // No need to even try if we know the module has no guards.
11823 if (!HasGuards)
11824 return false;
11825
11826 return any_of(*BB, [&](const Instruction &I) {
11827 using namespace llvm::PatternMatch;
11828
11829 Value *Condition;
11831 m_Value(Condition))) &&
11832 isImpliedCond(Pred, LHS, RHS, Condition, false);
11833 });
11834}
11835
11836/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
11837/// protected by a conditional between LHS and RHS. This is used to
11838/// to eliminate casts.
11840 CmpPredicate Pred,
11841 const SCEV *LHS,
11842 const SCEV *RHS) {
11843 // Interpret a null as meaning no loop, where there is obviously no guard
11844 // (interprocedural conditions notwithstanding). Do not bother about
11845 // unreachable loops.
11846 if (!L || !DT.isReachableFromEntry(L->getHeader()))
11847 return true;
11848
11849 if (VerifyIR)
11850 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
11851 "This cannot be done on broken IR!");
11852
11853
11854 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11855 return true;
11856
11857 BasicBlock *Latch = L->getLoopLatch();
11858 if (!Latch)
11859 return false;
11860
11861 CondBrInst *LoopContinuePredicate =
11863 if (LoopContinuePredicate &&
11864 isImpliedCond(Pred, LHS, RHS, LoopContinuePredicate->getCondition(),
11865 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
11866 return true;
11867
11868 // We don't want more than one activation of the following loops on the stack
11869 // -- that can lead to O(n!) time complexity.
11870 if (WalkingBEDominatingConds)
11871 return false;
11872
11873 SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
11874
11875 // See if we can exploit a trip count to prove the predicate.
11876 const auto &BETakenInfo = getBackedgeTakenInfo(L);
11877 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
11878 if (LatchBECount != getCouldNotCompute()) {
11879 // We know that Latch branches back to the loop header exactly
11880 // LatchBECount times. This means the backdege condition at Latch is
11881 // equivalent to "{0,+,1} u< LatchBECount".
11882 Type *Ty = LatchBECount->getType();
11883 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
11884 const SCEV *LoopCounter =
11885 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
11886 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
11887 LatchBECount))
11888 return true;
11889 }
11890
11891 // Check conditions due to any @llvm.assume intrinsics.
11892 for (auto &AssumeVH : AC.assumptions()) {
11893 if (!AssumeVH)
11894 continue;
11895 auto *CI = cast<CallInst>(AssumeVH);
11896 if (!DT.dominates(CI, Latch->getTerminator()))
11897 continue;
11898
11899 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
11900 return true;
11901 }
11902
11903 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
11904 return true;
11905
11906 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
11907 DTN != HeaderDTN; DTN = DTN->getIDom()) {
11908 assert(DTN && "should reach the loop header before reaching the root!");
11909
11910 BasicBlock *BB = DTN->getBlock();
11911 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
11912 return true;
11913
11914 BasicBlock *PBB = BB->getSinglePredecessor();
11915 if (!PBB)
11916 continue;
11917
11919 if (!ContBr || ContBr->getSuccessor(0) == ContBr->getSuccessor(1))
11920 continue;
11921
11922 // If we have an edge `E` within the loop body that dominates the only
11923 // latch, the condition guarding `E` also guards the backedge. This
11924 // reasoning works only for loops with a single latch.
11925 // We're constructively (and conservatively) enumerating edges within the
11926 // loop body that dominate the latch. The dominator tree better agree
11927 // with us on this:
11928 assert(DT.dominates(BasicBlockEdge(PBB, BB), Latch) && "should be!");
11929 if (isImpliedCond(Pred, LHS, RHS, ContBr->getCondition(),
11930 BB != ContBr->getSuccessor(0)))
11931 return true;
11932 }
11933
11934 return false;
11935}
11936
11938 CmpPredicate Pred,
11939 const SCEV *LHS,
11940 const SCEV *RHS) {
11941 // Do not bother proving facts for unreachable code.
11942 if (!DT.isReachableFromEntry(BB))
11943 return true;
11944 if (VerifyIR)
11945 assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
11946 "This cannot be done on broken IR!");
11947
11948 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
11949 // the facts (a >= b && a != b) separately. A typical situation is when the
11950 // non-strict comparison is known from ranges and non-equality is known from
11951 // dominating predicates. If we are proving strict comparison, we always try
11952 // to prove non-equality and non-strict comparison separately.
11953 CmpPredicate NonStrictPredicate = ICmpInst::getNonStrictCmpPredicate(Pred);
11954 const bool ProvingStrictComparison =
11955 Pred != NonStrictPredicate.dropSameSign();
11956 bool ProvedNonStrictComparison = false;
11957 bool ProvedNonEquality = false;
11958
11959 auto SplitAndProve = [&](std::function<bool(CmpPredicate)> Fn) -> bool {
11960 if (!ProvedNonStrictComparison)
11961 ProvedNonStrictComparison = Fn(NonStrictPredicate);
11962 if (!ProvedNonEquality)
11963 ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
11964 if (ProvedNonStrictComparison && ProvedNonEquality)
11965 return true;
11966 return false;
11967 };
11968
11969 if (ProvingStrictComparison) {
11970 auto ProofFn = [&](CmpPredicate P) {
11971 return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
11972 };
11973 if (SplitAndProve(ProofFn))
11974 return true;
11975 }
11976
11977 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
11978 auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
11979 const Instruction *CtxI = &BB->front();
11980 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
11981 return true;
11982 if (ProvingStrictComparison) {
11983 auto ProofFn = [&](CmpPredicate P) {
11984 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
11985 };
11986 if (SplitAndProve(ProofFn))
11987 return true;
11988 }
11989 return false;
11990 };
11991
11992 // Starting at the block's predecessor, climb up the predecessor chain, as long
11993 // as there are predecessors that can be found that have unique successors
11994 // leading to the original block.
11995 const Loop *ContainingLoop = LI.getLoopFor(BB);
11996 const BasicBlock *PredBB;
11997 if (ContainingLoop && ContainingLoop->getHeader() == BB)
11998 PredBB = ContainingLoop->getLoopPredecessor();
11999 else
12000 PredBB = BB->getSinglePredecessor();
12001 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
12002 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
12003 const CondBrInst *BlockEntryPredicate =
12004 dyn_cast<CondBrInst>(Pair.first->getTerminator());
12005 if (!BlockEntryPredicate)
12006 continue;
12007
12008 if (ProveViaCond(BlockEntryPredicate->getCondition(),
12009 BlockEntryPredicate->getSuccessor(0) != Pair.second))
12010 return true;
12011 }
12012
12013 // Check conditions due to any @llvm.assume intrinsics.
12014 for (auto &AssumeVH : AC.assumptions()) {
12015 if (!AssumeVH)
12016 continue;
12017 auto *CI = cast<CallInst>(AssumeVH);
12018 if (!DT.dominates(CI, BB))
12019 continue;
12020
12021 if (ProveViaCond(CI->getArgOperand(0), false))
12022 return true;
12023 }
12024
12025 // Check conditions due to any @llvm.experimental.guard intrinsics.
12026 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
12027 F.getParent(), Intrinsic::experimental_guard);
12028 if (GuardDecl)
12029 for (const auto *GU : GuardDecl->users())
12030 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
12031 if (Guard->getFunction() == BB->getParent() && DT.dominates(Guard, BB))
12032 if (ProveViaCond(Guard->getArgOperand(0), false))
12033 return true;
12034 return false;
12035}
12036
12038 const SCEV *LHS,
12039 const SCEV *RHS) {
12040 // Interpret a null as meaning no loop, where there is obviously no guard
12041 // (interprocedural conditions notwithstanding).
12042 if (!L)
12043 return false;
12044
12045 // Both LHS and RHS must be available at loop entry.
12047 "LHS is not available at Loop Entry");
12049 "RHS is not available at Loop Entry");
12050
12051 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
12052 return true;
12053
12054 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
12055}
12056
12057bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12058 const SCEV *RHS,
12059 const Value *FoundCondValue, bool Inverse,
12060 const Instruction *CtxI) {
12061 // False conditions implies anything. Do not bother analyzing it further.
12062 if (FoundCondValue ==
12063 ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
12064 return true;
12065
12066 if (!PendingLoopPredicates.insert(FoundCondValue).second)
12067 return false;
12068
12069 llvm::scope_exit ClearOnExit(
12070 [&]() { PendingLoopPredicates.erase(FoundCondValue); });
12071
12072 // Recursively handle And and Or conditions.
12073 const Value *Op0, *Op1;
12074 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
12075 if (!Inverse)
12076 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12077 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12078 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
12079 if (Inverse)
12080 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12081 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12082 }
12083
12084 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
12085 if (!ICI) return false;
12086
12087 // Now that we found a conditional branch that dominates the loop or controls
12088 // the loop latch. Check to see if it is the comparison we are looking for.
12089 CmpPredicate FoundPred;
12090 if (Inverse)
12091 FoundPred = ICI->getInverseCmpPredicate();
12092 else
12093 FoundPred = ICI->getCmpPredicate();
12094
12095 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
12096 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
12097
12098 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
12099}
12100
12101bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12102 const SCEV *RHS, CmpPredicate FoundPred,
12103 const SCEV *FoundLHS, const SCEV *FoundRHS,
12104 const Instruction *CtxI) {
12105 // Balance the types.
12106 if (getTypeSizeInBits(LHS->getType()) <
12107 getTypeSizeInBits(FoundLHS->getType())) {
12108 // For unsigned and equality predicates, try to prove that both found
12109 // operands fit into narrow unsigned range. If so, try to prove facts in
12110 // narrow types.
12111 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
12112 !FoundRHS->getType()->isPointerTy()) {
12113 auto *NarrowType = LHS->getType();
12114 auto *WideType = FoundLHS->getType();
12115 auto BitWidth = getTypeSizeInBits(NarrowType);
12116 const SCEV *MaxValue = getZeroExtendExpr(
12118 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
12119 MaxValue) &&
12120 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
12121 MaxValue)) {
12122 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
12123 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
12124 // We cannot preserve samesign after truncation.
12125 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred.dropSameSign(),
12126 TruncFoundLHS, TruncFoundRHS, CtxI))
12127 return true;
12128 }
12129 }
12130
12131 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
12132 return false;
12133 if (CmpInst::isSigned(Pred)) {
12134 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
12135 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
12136 } else {
12137 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
12138 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
12139 }
12140 } else if (getTypeSizeInBits(LHS->getType()) >
12141 getTypeSizeInBits(FoundLHS->getType())) {
12142 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
12143 return false;
12144 if (CmpInst::isSigned(FoundPred)) {
12145 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
12146 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
12147 } else {
12148 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
12149 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
12150 }
12151 }
12152 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
12153 FoundRHS, CtxI);
12154}
12155
12156bool ScalarEvolution::isImpliedCondBalancedTypes(
12157 CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, CmpPredicate FoundPred,
12158 SCEVUse FoundLHS, SCEVUse FoundRHS, const Instruction *CtxI) {
12160 getTypeSizeInBits(FoundLHS->getType()) &&
12161 "Types should be balanced!");
12162 // Canonicalize the query to match the way instcombine will have
12163 // canonicalized the comparison.
12164 if (SimplifyICmpOperands(Pred, LHS, RHS))
12165 if (LHS == RHS)
12166 return CmpInst::isTrueWhenEqual(Pred);
12167 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
12168 if (FoundLHS == FoundRHS)
12169 return CmpInst::isFalseWhenEqual(FoundPred);
12170
12171 // Check to see if we can make the LHS or RHS match.
12172 if (LHS == FoundRHS || RHS == FoundLHS) {
12173 if (isa<SCEVConstant>(RHS)) {
12174 std::swap(FoundLHS, FoundRHS);
12175 FoundPred = ICmpInst::getSwappedCmpPredicate(FoundPred);
12176 } else {
12177 std::swap(LHS, RHS);
12179 }
12180 }
12181
12182 // Check whether the found predicate is the same as the desired predicate.
12183 if (auto P = CmpPredicate::getMatching(FoundPred, Pred))
12184 return isImpliedCondOperands(*P, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12185
12186 // Check whether swapping the found predicate makes it the same as the
12187 // desired predicate.
12188 if (auto P = CmpPredicate::getMatching(
12189 ICmpInst::getSwappedCmpPredicate(FoundPred), Pred)) {
12190 // We can write the implication
12191 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS
12192 // using one of the following ways:
12193 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS
12194 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS
12195 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS
12196 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS
12197 // Forms 1. and 2. require swapping the operands of one condition. Don't
12198 // do this if it would break canonical constant/addrec ordering.
12200 return isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P), RHS,
12201 LHS, FoundLHS, FoundRHS, CtxI);
12202 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
12203 return isImpliedCondOperands(*P, LHS, RHS, FoundRHS, FoundLHS, CtxI);
12204
12205 // There's no clear preference between forms 3. and 4., try both. Avoid
12206 // forming getNotSCEV of pointer values as the resulting subtract is
12207 // not legal.
12208 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() &&
12209 isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P),
12210 getNotSCEV(LHS), getNotSCEV(RHS), FoundLHS,
12211 FoundRHS, CtxI))
12212 return true;
12213
12214 if (!FoundLHS->getType()->isPointerTy() &&
12215 !FoundRHS->getType()->isPointerTy() &&
12216 isImpliedCondOperands(*P, LHS, RHS, getNotSCEV(FoundLHS),
12217 getNotSCEV(FoundRHS), CtxI))
12218 return true;
12219
12220 return false;
12221 }
12222
12223 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
12225 assert(P1 != P2 && "Handled earlier!");
12226 return CmpInst::isRelational(P2) &&
12228 };
12229 if (IsSignFlippedPredicate(Pred, FoundPred)) {
12230 // Unsigned comparison is the same as signed comparison when both the
12231 // operands are non-negative or negative.
12232 if (haveSameSign(FoundLHS, FoundRHS))
12233 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12234 // Create local copies that we can freely swap and canonicalize our
12235 // conditions to "le/lt".
12236 CmpPredicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
12237 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
12238 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
12239 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
12240 CanonicalPred = ICmpInst::getSwappedCmpPredicate(CanonicalPred);
12241 CanonicalFoundPred = ICmpInst::getSwappedCmpPredicate(CanonicalFoundPred);
12242 std::swap(CanonicalLHS, CanonicalRHS);
12243 std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
12244 }
12245 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
12246 "Must be!");
12247 assert((ICmpInst::isLT(CanonicalFoundPred) ||
12248 ICmpInst::isLE(CanonicalFoundPred)) &&
12249 "Must be!");
12250 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
12251 // Use implication:
12252 // x <u y && y >=s 0 --> x <s y.
12253 // If we can prove the left part, the right part is also proven.
12254 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
12255 CanonicalRHS, CanonicalFoundLHS,
12256 CanonicalFoundRHS);
12257 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
12258 // Use implication:
12259 // x <s y && y <s 0 --> x <u y.
12260 // If we can prove the left part, the right part is also proven.
12261 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
12262 CanonicalRHS, CanonicalFoundLHS,
12263 CanonicalFoundRHS);
12264 }
12265
12266 // Check if we can make progress by sharpening ranges.
12267 if (FoundPred == ICmpInst::ICMP_NE &&
12268 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
12269
12270 const SCEVConstant *C = nullptr;
12271 const SCEV *V = nullptr;
12272
12273 if (isa<SCEVConstant>(FoundLHS)) {
12274 C = cast<SCEVConstant>(FoundLHS);
12275 V = FoundRHS;
12276 } else {
12277 C = cast<SCEVConstant>(FoundRHS);
12278 V = FoundLHS;
12279 }
12280
12281 // The guarding predicate tells us that C != V. If the known range
12282 // of V is [C, t), we can sharpen the range to [C + 1, t). The
12283 // range we consider has to correspond to same signedness as the
12284 // predicate we're interested in folding.
12285
12286 APInt Min = ICmpInst::isSigned(Pred) ?
12288
12289 if (Min == C->getAPInt()) {
12290 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
12291 // This is true even if (Min + 1) wraps around -- in case of
12292 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
12293
12294 APInt SharperMin = Min + 1;
12295
12296 switch (Pred) {
12297 case ICmpInst::ICMP_SGE:
12298 case ICmpInst::ICMP_UGE:
12299 // We know V `Pred` SharperMin. If this implies LHS `Pred`
12300 // RHS, we're done.
12301 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
12302 CtxI))
12303 return true;
12304 [[fallthrough]];
12305
12306 case ICmpInst::ICMP_SGT:
12307 case ICmpInst::ICMP_UGT:
12308 // We know from the range information that (V `Pred` Min ||
12309 // V == Min). We know from the guarding condition that !(V
12310 // == Min). This gives us
12311 //
12312 // V `Pred` Min || V == Min && !(V == Min)
12313 // => V `Pred` Min
12314 //
12315 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
12316
12317 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
12318 return true;
12319 break;
12320
12321 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
12322 case ICmpInst::ICMP_SLE:
12323 case ICmpInst::ICMP_ULE:
12324 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12325 LHS, V, getConstant(SharperMin), CtxI))
12326 return true;
12327 [[fallthrough]];
12328
12329 case ICmpInst::ICMP_SLT:
12330 case ICmpInst::ICMP_ULT:
12331 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12332 LHS, V, getConstant(Min), CtxI))
12333 return true;
12334 break;
12335
12336 default:
12337 // No change
12338 break;
12339 }
12340 }
12341 }
12342
12343 // Check whether the actual condition is beyond sufficient.
12344 if (FoundPred == ICmpInst::ICMP_EQ)
12345 if (ICmpInst::isTrueWhenEqual(Pred))
12346 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12347 return true;
12348 if (Pred == ICmpInst::ICMP_NE)
12349 if (!ICmpInst::isTrueWhenEqual(FoundPred))
12350 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12351 return true;
12352
12353 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS))
12354 return true;
12355
12356 // Otherwise assume the worst.
12357 return false;
12358}
12359
12360bool ScalarEvolution::splitBinaryAdd(SCEVUse Expr, SCEVUse &L, SCEVUse &R,
12361 SCEV::NoWrapFlags &Flags) {
12362 if (!match(Expr, m_scev_Add(m_SCEV(L), m_SCEV(R))))
12363 return false;
12364
12365 Flags = cast<SCEVAddExpr>(Expr)->getNoWrapFlags();
12366 return true;
12367}
12368
12369std::optional<APInt>
12371 // We avoid subtracting expressions here because this function is usually
12372 // fairly deep in the call stack (i.e. is called many times).
12373
12374 unsigned BW = getTypeSizeInBits(More->getType());
12375 APInt Diff(BW, 0);
12376 APInt DiffMul(BW, 1);
12377 // Try various simplifications to reduce the difference to a constant. Limit
12378 // the number of allowed simplifications to keep compile-time low.
12379 for (unsigned I = 0; I < 8; ++I) {
12380 if (More == Less)
12381 return Diff;
12382
12383 // Reduce addrecs with identical steps to their start value.
12385 const auto *LAR = cast<SCEVAddRecExpr>(Less);
12386 const auto *MAR = cast<SCEVAddRecExpr>(More);
12387
12388 if (LAR->getLoop() != MAR->getLoop())
12389 return std::nullopt;
12390
12391 // We look at affine expressions only; not for correctness but to keep
12392 // getStepRecurrence cheap.
12393 if (!LAR->isAffine() || !MAR->isAffine())
12394 return std::nullopt;
12395
12396 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
12397 return std::nullopt;
12398
12399 Less = LAR->getStart();
12400 More = MAR->getStart();
12401 continue;
12402 }
12403
12404 // Try to match a common constant multiply.
12405 auto MatchConstMul =
12406 [](const SCEV *S) -> std::optional<std::pair<const SCEV *, APInt>> {
12407 const APInt *C;
12408 const SCEV *Op;
12409 if (match(S, m_scev_Mul(m_scev_APInt(C), m_SCEV(Op))))
12410 return {{Op, *C}};
12411 return std::nullopt;
12412 };
12413 if (auto MatchedMore = MatchConstMul(More)) {
12414 if (auto MatchedLess = MatchConstMul(Less)) {
12415 if (MatchedMore->second == MatchedLess->second) {
12416 More = MatchedMore->first;
12417 Less = MatchedLess->first;
12418 DiffMul *= MatchedMore->second;
12419 continue;
12420 }
12421 }
12422 }
12423
12424 // Try to cancel out common factors in two add expressions.
12426 auto Add = [&](const SCEV *S, int Mul) {
12427 if (auto *C = dyn_cast<SCEVConstant>(S)) {
12428 if (Mul == 1) {
12429 Diff += C->getAPInt() * DiffMul;
12430 } else {
12431 assert(Mul == -1);
12432 Diff -= C->getAPInt() * DiffMul;
12433 }
12434 } else
12435 Multiplicity[S] += Mul;
12436 };
12437 auto Decompose = [&](const SCEV *S, int Mul) {
12438 if (isa<SCEVAddExpr>(S)) {
12439 for (const SCEV *Op : S->operands())
12440 Add(Op, Mul);
12441 } else
12442 Add(S, Mul);
12443 };
12444 Decompose(More, 1);
12445 Decompose(Less, -1);
12446
12447 // Check whether all the non-constants cancel out, or reduce to new
12448 // More/Less values.
12449 const SCEV *NewMore = nullptr, *NewLess = nullptr;
12450 for (const auto &[S, Mul] : Multiplicity) {
12451 if (Mul == 0)
12452 continue;
12453 if (Mul == 1) {
12454 if (NewMore)
12455 return std::nullopt;
12456 NewMore = S;
12457 } else if (Mul == -1) {
12458 if (NewLess)
12459 return std::nullopt;
12460 NewLess = S;
12461 } else
12462 return std::nullopt;
12463 }
12464
12465 // Values stayed the same, no point in trying further.
12466 if (NewMore == More || NewLess == Less)
12467 return std::nullopt;
12468
12469 More = NewMore;
12470 Less = NewLess;
12471
12472 // Reduced to constant.
12473 if (!More && !Less)
12474 return Diff;
12475
12476 // Left with variable on only one side, bail out.
12477 if (!More || !Less)
12478 return std::nullopt;
12479 }
12480
12481 // Did not reduce to constant.
12482 return std::nullopt;
12483}
12484
12485bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
12486 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12487 const SCEV *FoundRHS, const Instruction *CtxI) {
12488 // Try to recognize the following pattern:
12489 //
12490 // FoundRHS = ...
12491 // ...
12492 // loop:
12493 // FoundLHS = {Start,+,W}
12494 // context_bb: // Basic block from the same loop
12495 // known(Pred, FoundLHS, FoundRHS)
12496 //
12497 // If some predicate is known in the context of a loop, it is also known on
12498 // each iteration of this loop, including the first iteration. Therefore, in
12499 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
12500 // prove the original pred using this fact.
12501 if (!CtxI)
12502 return false;
12503 const BasicBlock *ContextBB = CtxI->getParent();
12504 // Make sure AR varies in the context block.
12505 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
12506 const Loop *L = AR->getLoop();
12507 const auto *Latch = L->getLoopLatch();
12508 // Make sure that context belongs to the loop and executes on 1st iteration
12509 // (if it ever executes at all).
12510 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12511 return false;
12512 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
12513 return false;
12514 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
12515 }
12516
12517 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
12518 const Loop *L = AR->getLoop();
12519 const auto *Latch = L->getLoopLatch();
12520 // Make sure that context belongs to the loop and executes on 1st iteration
12521 // (if it ever executes at all).
12522 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12523 return false;
12524 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
12525 return false;
12526 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
12527 }
12528
12529 return false;
12530}
12531
12532bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(CmpPredicate Pred,
12533 const SCEV *LHS,
12534 const SCEV *RHS,
12535 const SCEV *FoundLHS,
12536 const SCEV *FoundRHS) {
12537 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
12538 return false;
12539
12540 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
12541 if (!AddRecLHS)
12542 return false;
12543
12544 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12545 if (!AddRecFoundLHS)
12546 return false;
12547
12548 // We'd like to let SCEV reason about control dependencies, so we constrain
12549 // both the inequalities to be about add recurrences on the same loop. This
12550 // way we can use isLoopEntryGuardedByCond later.
12551
12552 const Loop *L = AddRecFoundLHS->getLoop();
12553 if (L != AddRecLHS->getLoop())
12554 return false;
12555
12556 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
12557 //
12558 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
12559 // ... (2)
12560 //
12561 // Informal proof for (2), assuming (1) [*]:
12562 //
12563 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
12564 //
12565 // Then
12566 //
12567 // FoundLHS s< FoundRHS s< INT_MIN - C
12568 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
12569 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
12570 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
12571 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
12572 // <=> FoundLHS + C s< FoundRHS + C
12573 //
12574 // [*]: (1) can be proved by ruling out overflow.
12575 //
12576 // [**]: This can be proved by analyzing all the four possibilities:
12577 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
12578 // (A s>= 0, B s>= 0).
12579 //
12580 // Note:
12581 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
12582 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
12583 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
12584 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
12585 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
12586 // C)".
12587
12588 std::optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
12589 if (!LDiff)
12590 return false;
12591 std::optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
12592 if (!RDiff || *LDiff != *RDiff)
12593 return false;
12594
12595 if (LDiff->isMinValue())
12596 return true;
12597
12598 APInt FoundRHSLimit;
12599
12600 if (Pred == CmpInst::ICMP_ULT) {
12601 FoundRHSLimit = -(*RDiff);
12602 } else {
12603 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
12604 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
12605 }
12606
12607 // Try to prove (1) or (2), as needed.
12608 return isAvailableAtLoopEntry(FoundRHS, L) &&
12609 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
12610 getConstant(FoundRHSLimit));
12611}
12612
12613bool ScalarEvolution::isImpliedViaMerge(CmpPredicate Pred, const SCEV *LHS,
12614 const SCEV *RHS, const SCEV *FoundLHS,
12615 const SCEV *FoundRHS, unsigned Depth) {
12616 const PHINode *LPhi = nullptr, *RPhi = nullptr;
12617
12618 llvm::scope_exit ClearOnExit([&]() {
12619 if (LPhi) {
12620 bool Erased = PendingMerges.erase(LPhi);
12621 assert(Erased && "Failed to erase LPhi!");
12622 (void)Erased;
12623 }
12624 if (RPhi) {
12625 bool Erased = PendingMerges.erase(RPhi);
12626 assert(Erased && "Failed to erase RPhi!");
12627 (void)Erased;
12628 }
12629 });
12630
12631 // Find respective Phis and check that they are not being pending.
12632 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
12633 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
12634 if (!PendingMerges.insert(Phi).second)
12635 return false;
12636 LPhi = Phi;
12637 }
12638 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
12639 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
12640 // If we detect a loop of Phi nodes being processed by this method, for
12641 // example:
12642 //
12643 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
12644 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
12645 //
12646 // we don't want to deal with a case that complex, so return conservative
12647 // answer false.
12648 if (!PendingMerges.insert(Phi).second)
12649 return false;
12650 RPhi = Phi;
12651 }
12652
12653 // If none of LHS, RHS is a Phi, nothing to do here.
12654 if (!LPhi && !RPhi)
12655 return false;
12656
12657 // If there is a SCEVUnknown Phi we are interested in, make it left.
12658 if (!LPhi) {
12659 std::swap(LHS, RHS);
12660 std::swap(FoundLHS, FoundRHS);
12661 std::swap(LPhi, RPhi);
12663 }
12664
12665 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
12666 const BasicBlock *LBB = LPhi->getParent();
12667 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12668
12669 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
12670 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
12671 isImpliedCondOperandsViaRanges(Pred, S1, S2, Pred, FoundLHS, FoundRHS) ||
12672 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
12673 };
12674
12675 if (RPhi && RPhi->getParent() == LBB) {
12676 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
12677 // If we compare two Phis from the same block, and for each entry block
12678 // the predicate is true for incoming values from this block, then the
12679 // predicate is also true for the Phis.
12680 for (const BasicBlock *IncBB : predecessors(LBB)) {
12681 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12682 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
12683 if (!ProvedEasily(L, R))
12684 return false;
12685 }
12686 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
12687 // Case two: RHS is also a Phi from the same basic block, and it is an
12688 // AddRec. It means that there is a loop which has both AddRec and Unknown
12689 // PHIs, for it we can compare incoming values of AddRec from above the loop
12690 // and latch with their respective incoming values of LPhi.
12691 // TODO: Generalize to handle loops with many inputs in a header.
12692 if (LPhi->getNumIncomingValues() != 2) return false;
12693
12694 auto *RLoop = RAR->getLoop();
12695 auto *Predecessor = RLoop->getLoopPredecessor();
12696 assert(Predecessor && "Loop with AddRec with no predecessor?");
12697 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
12698 if (!ProvedEasily(L1, RAR->getStart()))
12699 return false;
12700 auto *Latch = RLoop->getLoopLatch();
12701 assert(Latch && "Loop with AddRec with no latch?");
12702 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
12703 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
12704 return false;
12705 } else {
12706 // In all other cases go over inputs of LHS and compare each of them to RHS,
12707 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
12708 // At this point RHS is either a non-Phi, or it is a Phi from some block
12709 // different from LBB.
12710 for (const BasicBlock *IncBB : predecessors(LBB)) {
12711 // Check that RHS is available in this block.
12712 if (!dominates(RHS, IncBB))
12713 return false;
12714 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12715 // Make sure L does not refer to a value from a potentially previous
12716 // iteration of a loop.
12717 if (!properlyDominates(L, LBB))
12718 return false;
12719 // Addrecs are considered to properly dominate their loop, so are missed
12720 // by the previous check. Discard any values that have computable
12721 // evolution in this loop.
12722 if (auto *Loop = LI.getLoopFor(LBB))
12724 return false;
12725 if (!ProvedEasily(L, RHS))
12726 return false;
12727 }
12728 }
12729 return true;
12730}
12731
12732bool ScalarEvolution::isImpliedCondOperandsViaShift(CmpPredicate Pred,
12733 const SCEV *LHS,
12734 const SCEV *RHS,
12735 const SCEV *FoundLHS,
12736 const SCEV *FoundRHS) {
12737 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make
12738 // sure that we are dealing with same LHS.
12739 if (RHS == FoundRHS) {
12740 std::swap(LHS, RHS);
12741 std::swap(FoundLHS, FoundRHS);
12743 }
12744 if (LHS != FoundLHS)
12745 return false;
12746
12747 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
12748 if (!SUFoundRHS)
12749 return false;
12750
12751 Value *Shiftee, *ShiftValue;
12752
12753 using namespace PatternMatch;
12754 if (match(SUFoundRHS->getValue(),
12755 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
12756 auto *ShifteeS = getSCEV(Shiftee);
12757 // Prove one of the following:
12758 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
12759 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
12760 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12761 // ---> LHS <s RHS
12762 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12763 // ---> LHS <=s RHS
12764 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
12765 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
12766 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
12767 if (isKnownNonNegative(ShifteeS))
12768 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
12769 }
12770
12771 return false;
12772}
12773
12774bool ScalarEvolution::isImpliedCondOperandsViaMatchingDiff(
12775 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12776 const SCEV *FoundRHS) {
12777 // Only valid for equality predicates: (A == B) implies (C == D) when
12778 // the SCEV difference A - B equals C - D (they check the same
12779 // underlying relationship at every iteration).
12780 if (!ICmpInst::isEquality(Pred))
12781 return false;
12782
12783 // Restrict to cases involving loop recurrences - that's where this
12784 // pattern arises (correlated IV comparisons). This avoids calling
12785 // getMinusSCEV on arbitrary non-loop expressions.
12787 (!isa<SCEVAddRecExpr>(FoundLHS) && !isa<SCEVAddRecExpr>(FoundRHS)))
12788 return false;
12789
12790 // AddRecs from different loops can never produce matching differences.
12791 const SCEVAddRecExpr *QueryAddRec = dyn_cast<SCEVAddRecExpr>(LHS);
12792 if (!QueryAddRec)
12793 QueryAddRec = cast<SCEVAddRecExpr>(RHS);
12794 const SCEVAddRecExpr *FoundAddRec = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12795 if (!FoundAddRec)
12796 FoundAddRec = cast<SCEVAddRecExpr>(FoundRHS);
12797 if (QueryAddRec->getLoop() != FoundAddRec->getLoop())
12798 return false;
12799
12800 // If the strides differ, the differences can never match.
12801 if (QueryAddRec->getStepRecurrence(*this) !=
12802 FoundAddRec->getStepRecurrence(*this))
12803 return false;
12804
12805 // Compute differences. For pointer-typed operands sharing the same base,
12806 // getMinusSCEV strips the common base and returns an integer SCEV.
12807 // For example, {base,+,8} - (base+8*n) = {-8n,+,8}
12808 const SCEV *FoundDiff = getMinusSCEV(FoundLHS, FoundRHS);
12809 if (isa<SCEVCouldNotCompute>(FoundDiff))
12810 return false;
12811
12812 const SCEV *Diff = getMinusSCEV(LHS, RHS);
12813 if (isa<SCEVCouldNotCompute>(Diff))
12814 return false;
12815
12816 return Diff == FoundDiff;
12817}
12818
12819bool ScalarEvolution::isImpliedCondOperands(CmpPredicate Pred, const SCEV *LHS,
12820 const SCEV *RHS,
12821 const SCEV *FoundLHS,
12822 const SCEV *FoundRHS,
12823 const Instruction *CtxI) {
12824 return isImpliedCondOperandsViaRanges(Pred, LHS, RHS, Pred, FoundLHS,
12825 FoundRHS) ||
12826 isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS,
12827 FoundRHS) ||
12828 isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS) ||
12829 isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12830 CtxI) ||
12831 isImpliedCondOperandsViaMatchingDiff(Pred, LHS, RHS, FoundLHS,
12832 FoundRHS) ||
12833 isImpliedCondOperandsHelper(Pred, LHS, RHS, FoundLHS, FoundRHS);
12834}
12835
12836/// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
12837template <typename MinMaxExprType>
12838static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
12839 const SCEV *Candidate) {
12840 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12841 if (!MinMaxExpr)
12842 return false;
12843
12844 return is_contained(MinMaxExpr->operands(), Candidate);
12845}
12846
12848 CmpPredicate Pred, const SCEV *LHS,
12849 const SCEV *RHS) {
12850 // If both sides are affine addrecs for the same loop, with equal
12851 // steps, and we know the recurrences don't wrap, then we only
12852 // need to check the predicate on the starting values.
12853
12854 if (!ICmpInst::isRelational(Pred))
12855 return false;
12856
12857 const SCEV *LStart, *RStart, *Step;
12858 const Loop *L;
12859 if (!match(LHS,
12860 m_scev_AffineAddRec(m_SCEV(LStart), m_SCEV(Step), m_Loop(L))) ||
12862 m_SpecificLoop(L))))
12863 return false;
12868 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
12869 return false;
12870
12871 return SE.isKnownPredicate(Pred, LStart, RStart);
12872}
12873
12874/// Is LHS `Pred` RHS true because one of them is an AddRec that is known not to
12875/// go below its own start value?
12877 CmpPredicate Pred,
12878 const SCEV *LHS,
12879 const SCEV *RHS) {
12880 // Normalize to (AddRec Pred Start).
12883 std::swap(LHS, RHS);
12884 }
12885
12886 // The recurrence is equal to Start in the first iteration, so only the
12887 // non-strict predicate holds.
12888 if (Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE)
12889 return false;
12890
12891 const auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
12892 if (!AR || AR->getStart() != RHS)
12893 return false;
12894
12895 return SE.getMonotonicPredicateType(AR, Pred) ==
12897}
12898
12899/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
12900/// expression?
12902 const SCEV *LHS, const SCEV *RHS) {
12903 switch (Pred) {
12904 default:
12905 return false;
12906
12907 case ICmpInst::ICMP_SGE:
12908 std::swap(LHS, RHS);
12909 [[fallthrough]];
12910 case ICmpInst::ICMP_SLE:
12911 return
12912 // min(A, ...) <= A
12914 // A <= max(A, ...)
12916
12917 case ICmpInst::ICMP_UGE:
12918 std::swap(LHS, RHS);
12919 [[fallthrough]];
12920 case ICmpInst::ICMP_ULE:
12921 return
12922 // min(A, ...) <= A
12923 // FIXME: what about umin_seq?
12925 // A <= max(A, ...)
12927
12928 case ICmpInst::ICMP_UGT:
12929 std::swap(LHS, RHS);
12930 [[fallthrough]];
12931 case ICmpInst::ICMP_ULT:
12932 // umin(Ops) u<= each Op, so proving Op u< RHS for any Op proves
12933 // umin(Ops) u< RHS.
12934 //
12935 // Use computeConstantDifference instead of the more powerful
12936 // isKnownPredicate to keep this check cheap: isKnownPredicateViaMinOrMax
12937 // is called from isKnownViaNonRecursiveReasoning, so recursing into
12938 // the full predicate prover would be expensive.
12939 if (const auto *Min = dyn_cast<SCEVUMinExpr>(LHS)) {
12940 for (SCEVUse Op : Min->operands()) {
12941 std::optional<APInt> Diff = SE.computeConstantDifference(RHS, Op);
12942 // When Op and RHS share a common base differing by a
12943 // constant offset D (RHS - Op = D), Op u< RHS holds iff D != 0 and
12944 // RHS >= D (unsigned), i.e. the subtraction doesn't underflow.
12945 if (Diff && !Diff->isZero() && SE.getUnsignedRangeMin(RHS).uge(*Diff))
12946 return true;
12947 }
12948 }
12949 return false;
12950 }
12951
12952 llvm_unreachable("covered switch fell through?!");
12953}
12954
12955bool ScalarEvolution::isImpliedViaOperations(CmpPredicate Pred, const SCEV *LHS,
12956 const SCEV *RHS,
12957 const SCEV *FoundLHS,
12958 const SCEV *FoundRHS,
12959 unsigned Depth) {
12962 "LHS and RHS have different sizes?");
12963 assert(getTypeSizeInBits(FoundLHS->getType()) ==
12964 getTypeSizeInBits(FoundRHS->getType()) &&
12965 "FoundLHS and FoundRHS have different sizes?");
12966 // We want to avoid hurting the compile time with analysis of too big trees.
12968 return false;
12969
12970 // We only want to work with GT comparison so far.
12971 if (ICmpInst::isLT(Pred)) {
12973 std::swap(LHS, RHS);
12974 std::swap(FoundLHS, FoundRHS);
12975 }
12976
12978
12979 // For unsigned, try to reduce it to corresponding signed comparison.
12980 if (P == ICmpInst::ICMP_UGT)
12981 // We can replace unsigned predicate with its signed counterpart if all
12982 // involved values are non-negative.
12983 // TODO: We could have better support for unsigned.
12984 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
12985 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
12986 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
12987 // use this fact to prove that LHS and RHS are non-negative.
12988 const SCEV *MinusOne = getMinusOne(LHS->getType());
12989 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
12990 FoundRHS) &&
12991 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
12992 FoundRHS))
12994 }
12995
12996 if (P != ICmpInst::ICMP_SGT)
12997 return false;
12998
12999 auto GetOpFromSExt = [&](const SCEV *S) -> const SCEV * {
13000 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
13001 return Ext->getOperand();
13002 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
13003 // the constant in some cases.
13004 return S;
13005 };
13006
13007 // Acquire values from extensions.
13008 auto *OrigLHS = LHS;
13009 auto *OrigFoundLHS = FoundLHS;
13010 LHS = GetOpFromSExt(LHS);
13011 FoundLHS = GetOpFromSExt(FoundLHS);
13012
13013 // Is the SGT predicate can be proved trivially or using the found context.
13014 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
13015 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
13016 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
13017 FoundRHS, Depth + 1);
13018 };
13019
13020 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
13021 // We want to avoid creation of any new non-constant SCEV. Since we are
13022 // going to compare the operands to RHS, we should be certain that we don't
13023 // need any size extensions for this. So let's decline all cases when the
13024 // sizes of types of LHS and RHS do not match.
13025 // TODO: Maybe try to get RHS from sext to catch more cases?
13027 return false;
13028
13029 // Should not overflow.
13030 if (!LHSAddExpr->hasNoSignedWrap())
13031 return false;
13032
13033 SCEVUse LL = LHSAddExpr->getOperand(0);
13034 SCEVUse LR = LHSAddExpr->getOperand(1);
13035 auto *MinusOne = getMinusOne(RHS->getType());
13036
13037 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
13038 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
13039 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
13040 };
13041 // Try to prove the following rule:
13042 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
13043 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
13044 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
13045 return true;
13046 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
13047 Value *LL, *LR;
13048 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
13049
13050 using namespace llvm::PatternMatch;
13051
13052 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
13053 // Rules for division.
13054 // We are going to perform some comparisons with Denominator and its
13055 // derivative expressions. In general case, creating a SCEV for it may
13056 // lead to a complex analysis of the entire graph, and in particular it
13057 // can request trip count recalculation for the same loop. This would
13058 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
13059 // this, we only want to create SCEVs that are constants in this section.
13060 // So we bail if Denominator is not a constant.
13061 if (!isa<ConstantInt>(LR))
13062 return false;
13063
13064 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
13065
13066 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
13067 // then a SCEV for the numerator already exists and matches with FoundLHS.
13068 auto *Numerator = getExistingSCEV(LL);
13069 if (!Numerator || Numerator->getType() != FoundLHS->getType())
13070 return false;
13071
13072 // Make sure that the numerator matches with FoundLHS and the denominator
13073 // is positive.
13074 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
13075 return false;
13076
13077 auto *DTy = Denominator->getType();
13078 auto *FRHSTy = FoundRHS->getType();
13079 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
13080 // One of types is a pointer and another one is not. We cannot extend
13081 // them properly to a wider type, so let us just reject this case.
13082 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
13083 // to avoid this check.
13084 return false;
13085
13086 // Given that:
13087 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
13088 auto *WTy = getWiderType(DTy, FRHSTy);
13089 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
13090 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
13091
13092 // Try to prove the following rule:
13093 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
13094 // For example, given that FoundLHS > 2. It means that FoundLHS is at
13095 // least 3. If we divide it by Denominator < 4, we will have at least 1.
13096 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
13097 if (isKnownNonPositive(RHS) &&
13098 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
13099 return true;
13100
13101 // Try to prove the following rule:
13102 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
13103 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
13104 // If we divide it by Denominator > 2, then:
13105 // 1. If FoundLHS is negative, then the result is 0.
13106 // 2. If FoundLHS is non-negative, then the result is non-negative.
13107 // Anyways, the result is non-negative.
13108 auto *MinusOne = getMinusOne(WTy);
13109 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
13110 if (isKnownNegative(RHS) &&
13111 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
13112 return true;
13113 }
13114 }
13115
13116 // If our expression contained SCEVUnknown Phis, and we split it down and now
13117 // need to prove something for them, try to prove the predicate for every
13118 // possible incoming values of those Phis.
13119 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
13120 return true;
13121
13122 return false;
13123}
13124
13126 const SCEV *RHS) {
13127 // zext x u<= sext x, sext x s<= zext x
13128 const SCEV *Op;
13129 switch (Pred) {
13130 case ICmpInst::ICMP_SGE:
13131 std::swap(LHS, RHS);
13132 [[fallthrough]];
13133 case ICmpInst::ICMP_SLE: {
13134 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt.
13135 return match(LHS, m_scev_SExt(m_SCEV(Op))) &&
13137 }
13138 case ICmpInst::ICMP_UGE:
13139 std::swap(LHS, RHS);
13140 [[fallthrough]];
13141 case ICmpInst::ICMP_ULE: {
13142 // If operand >=u 0 then ZExt == SExt. If operand <u 0 then ZExt <u SExt.
13143 return match(LHS, m_scev_ZExt(m_SCEV(Op))) &&
13145 }
13146 default:
13147 return false;
13148 };
13149 llvm_unreachable("unhandled case");
13150}
13151
13152bool ScalarEvolution::isKnownViaNonRecursiveReasoning(CmpPredicate Pred,
13153 SCEVUse LHS,
13154 SCEVUse RHS) {
13155 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
13156 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
13157 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
13158 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
13160 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
13161}
13162
13163bool ScalarEvolution::isImpliedCondOperandsHelper(CmpPredicate Pred,
13164 const SCEV *LHS,
13165 const SCEV *RHS,
13166 const SCEV *FoundLHS,
13167 const SCEV *FoundRHS) {
13168 switch (Pred) {
13169 default:
13170 llvm_unreachable("Unexpected CmpPredicate value!");
13171 case ICmpInst::ICMP_EQ:
13172 case ICmpInst::ICMP_NE:
13173 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
13174 return true;
13175 break;
13176 case ICmpInst::ICMP_SLT:
13177 case ICmpInst::ICMP_SLE:
13178 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
13179 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
13180 return true;
13181 break;
13182 case ICmpInst::ICMP_SGT:
13183 case ICmpInst::ICMP_SGE:
13184 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
13185 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
13186 return true;
13187 break;
13188 case ICmpInst::ICMP_ULT:
13189 case ICmpInst::ICMP_ULE:
13190 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
13191 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
13192 return true;
13193 break;
13194 case ICmpInst::ICMP_UGT:
13195 case ICmpInst::ICMP_UGE:
13196 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
13197 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
13198 return true;
13199 break;
13200 }
13201
13202 // Maybe it can be proved via operations?
13203 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
13204 return true;
13205
13206 return false;
13207}
13208
13209bool ScalarEvolution::isImpliedCondOperandsViaRanges(
13210 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, CmpPredicate FoundPred,
13211 const SCEV *FoundLHS, const SCEV *FoundRHS) {
13212 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
13213 // The restriction on `FoundRHS` be lifted easily -- it exists only to
13214 // reduce the compile time impact of this optimization.
13215 return false;
13216
13217 std::optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
13218 if (!Addend)
13219 return false;
13220
13221 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
13222
13223 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
13224 // antecedent "`FoundLHS` `FoundPred` `FoundRHS`".
13225 ConstantRange FoundLHSRange =
13226 ConstantRange::makeExactICmpRegion(FoundPred, ConstFoundRHS);
13227
13228 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
13229 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
13230
13231 // We can also compute the range of values for `LHS` that satisfy the
13232 // consequent, "`LHS` `Pred` `RHS`":
13233 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
13234 // The antecedent implies the consequent if every value of `LHS` that
13235 // satisfies the antecedent also satisfies the consequent.
13236 return LHSRange.icmp(Pred, ConstRHS);
13237}
13238
13239bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
13240 bool IsSigned) {
13241 assert(isKnownPositive(Stride) && "Positive stride expected!");
13242
13243 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13244 const SCEV *One = getOne(Stride->getType());
13245
13246 if (IsSigned) {
13247 APInt MaxRHS = getSignedRangeMax(RHS);
13248 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
13249 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13250
13251 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
13252 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
13253 }
13254
13255 APInt MaxRHS = getUnsignedRangeMax(RHS);
13256 APInt MaxValue = APInt::getMaxValue(BitWidth);
13257 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13258
13259 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
13260 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
13261}
13262
13263bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
13264 bool IsSigned) {
13265
13266 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13267 const SCEV *One = getOne(Stride->getType());
13268
13269 if (IsSigned) {
13270 APInt MinRHS = getSignedRangeMin(RHS);
13271 APInt MinValue = APInt::getSignedMinValue(BitWidth);
13272 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13273
13274 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
13275 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
13276 }
13277
13278 APInt MinRHS = getUnsignedRangeMin(RHS);
13279 APInt MinValue = APInt::getMinValue(BitWidth);
13280 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13281
13282 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
13283 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
13284}
13285
13287 // umin(N, 1) + floor((N - umin(N, 1)) / D)
13288 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
13289 // expression fixes the case of N=0.
13290 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
13291 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
13292 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
13293}
13294
13295const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
13296 const SCEV *Stride,
13297 const SCEV *End,
13298 unsigned BitWidth,
13299 bool IsSigned) {
13300 // The logic in this function assumes we can represent a positive stride.
13301 // If we can't, the backedge-taken count must be zero.
13302 if (IsSigned && BitWidth == 1)
13303 return getZero(Stride->getType());
13304
13305 // This code below only been closely audited for negative strides in the
13306 // unsigned comparison case, it may be correct for signed comparison, but
13307 // that needs to be established.
13308 if (IsSigned && isKnownNegative(Stride))
13309 return getCouldNotCompute();
13310
13311 // Calculate the maximum backedge count based on the range of values
13312 // permitted by Start, End, and Stride.
13313 APInt MinStart =
13314 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
13315
13316 APInt MinStride =
13317 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
13318
13319 // We assume either the stride is positive, or the backedge-taken count
13320 // is zero. So force StrideForMaxBECount to be at least one.
13321 APInt One(BitWidth, 1);
13322 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
13323 : APIntOps::umax(One, MinStride);
13324
13325 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
13326 : APInt::getMaxValue(BitWidth);
13327 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
13328
13329 // Although End can be a MAX expression we estimate MaxEnd considering only
13330 // the case End = RHS of the loop termination condition. This is safe because
13331 // in the other case (End - Start) is zero, leading to a zero maximum backedge
13332 // taken count.
13333 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
13334 : APIntOps::umin(getUnsignedRangeMax(End), Limit);
13335
13336 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
13337 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
13338 : APIntOps::umax(MaxEnd, MinStart);
13339
13340 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */,
13341 getConstant(StrideForMaxBECount) /* Step */);
13342}
13343
13345ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
13346 const Loop *L, bool IsSigned,
13347 bool ControlsOnlyExit, bool AllowPredicates) {
13349
13351 bool PredicatedIV = false;
13352 if (!IV) {
13353 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
13354 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
13355 if (AR && AR->getLoop() == L && AR->isAffine()) {
13356 auto canProveNUW = [&]() {
13357 // We can use the comparison to infer no-wrap flags only if it fully
13358 // controls the loop exit.
13359 if (!ControlsOnlyExit)
13360 return false;
13361
13362 if (!isLoopInvariant(RHS, L))
13363 return false;
13364
13365 if (!isKnownNonZero(AR->getStepRecurrence(*this)))
13366 // We need the sequence defined by AR to strictly increase in the
13367 // unsigned integer domain for the logic below to hold.
13368 return false;
13369
13370 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
13371 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
13372 // If RHS <=u Limit, then there must exist a value V in the sequence
13373 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
13374 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned
13375 // overflow occurs. This limit also implies that a signed comparison
13376 // (in the wide bitwidth) is equivalent to an unsigned comparison as
13377 // the high bits on both sides must be zero.
13378 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
13379 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
13380 Limit = Limit.zext(OuterBitWidth);
13381 return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit);
13382 };
13383 auto Flags = AR->getNoWrapFlags();
13384 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
13385 Flags = setFlags(Flags, SCEV::FlagNUW);
13386
13387 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
13388 if (AR->hasNoUnsignedWrap()) {
13389 // Emulate what getZeroExtendExpr would have done during construction
13390 // if we'd been able to infer the fact just above at that time.
13391 const SCEV *Step = AR->getStepRecurrence(*this);
13392 Type *Ty = ZExt->getType();
13393 auto *S = getAddRecExpr(
13395 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
13397 }
13398 }
13399 }
13400 }
13401
13402
13403 if (!IV && AllowPredicates) {
13404 // Try to make this an AddRec using runtime tests, in the first X
13405 // iterations of this loop, where X is the SCEV expression found by the
13406 // algorithm below.
13407 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13408 PredicatedIV = true;
13409 }
13410
13411 // Avoid weird loops
13412 if (!IV || IV->getLoop() != L || !IV->isAffine())
13413 return getCouldNotCompute();
13414
13415 // A precondition of this method is that the condition being analyzed
13416 // reaches an exiting branch which dominates the latch. Given that, we can
13417 // assume that an increment which violates the nowrap specification and
13418 // produces poison must cause undefined behavior when the resulting poison
13419 // value is branched upon and thus we can conclude that the backedge is
13420 // taken no more often than would be required to produce that poison value.
13421 // Note that a well defined loop can exit on the iteration which violates
13422 // the nowrap specification if there is another exit (either explicit or
13423 // implicit/exceptional) which causes the loop to execute before the
13424 // exiting instruction we're analyzing would trigger UB.
13425 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13426 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13428
13429 const SCEV *Stride = IV->getStepRecurrence(*this);
13430
13431 bool PositiveStride = isKnownPositive(Stride);
13432
13433 // Whether the IV may reach the maximum value before the exit is taken.
13434 bool IVMayOverflow = true;
13435
13436 // Avoid negative or zero stride values.
13437 if (!PositiveStride) {
13438 // We can compute the correct backedge taken count for loops with unknown
13439 // strides if we can prove that the loop is not an infinite loop with side
13440 // effects. Here's the loop structure we are trying to handle -
13441 //
13442 // i = start
13443 // do {
13444 // A[i] = i;
13445 // i += s;
13446 // } while (i < end);
13447 //
13448 // The backedge taken count for such loops is evaluated as -
13449 // (max(end, start + stride) - start - 1) /u stride
13450 //
13451 // The additional preconditions that we need to check to prove correctness
13452 // of the above formula is as follows -
13453 //
13454 // a) IV is either nuw or nsw depending upon signedness (indicated by the
13455 // NoWrap flag).
13456 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13457 // no side effects within the loop)
13458 // c) loop has a single static exit (with no abnormal exits)
13459 //
13460 // Precondition a) implies that if the stride is negative, this is a single
13461 // trip loop. The backedge taken count formula reduces to zero in this case.
13462 //
13463 // Precondition b) and c) combine to imply that if rhs is invariant in L,
13464 // then a zero stride means the backedge can't be taken without executing
13465 // undefined behavior.
13466 //
13467 // The positive stride case is the same as isKnownPositive(Stride) returning
13468 // true (original behavior of the function).
13469 //
13470 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
13472 return getCouldNotCompute();
13473
13474 if (!isKnownNonZero(Stride)) {
13475 // If we have a step of zero, and RHS isn't invariant in L, we don't know
13476 // if it might eventually be greater than start and if so, on which
13477 // iteration. We can't even produce a useful upper bound.
13478 if (!isLoopInvariant(RHS, L))
13479 return getCouldNotCompute();
13480
13481 // We allow a potentially zero stride, but we need to divide by stride
13482 // below. Since the loop can't be infinite and this check must control
13483 // the sole exit, we can infer the exit must be taken on the first
13484 // iteration (e.g. backedge count = 0) if the stride is zero. Given that,
13485 // we know the numerator in the divides below must be zero, so we can
13486 // pick an arbitrary non-zero value for the denominator (e.g. stride)
13487 // and produce the right result.
13488 // FIXME: Handle the case where Stride is poison?
13489 auto wouldZeroStrideBeUB = [&]() {
13490 // Proof by contradiction. Suppose the stride were zero. If we can
13491 // prove that the backedge *is* taken on the first iteration, then since
13492 // we know this condition controls the sole exit, we must have an
13493 // infinite loop. We can't have a (well defined) infinite loop per
13494 // check just above.
13495 // Note: The (Start - Stride) term is used to get the start' term from
13496 // (start' + stride,+,stride). Remember that we only care about the
13497 // result of this expression when stride == 0 at runtime.
13498 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
13499 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
13500 };
13501 if (!wouldZeroStrideBeUB()) {
13502 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13503 }
13504 }
13505 } else {
13506 // Avoid proven overflow cases: this will ensure that the backedge taken
13507 // count will not generate any unsigned overflow.
13508 IVMayOverflow = canIVOverflowOnLT(RHS, Stride, IsSigned);
13509 if (IVMayOverflow && !NoWrap)
13510 return getCouldNotCompute();
13511 }
13512
13513 // On all paths just preceeding, we established the following invariant:
13514 // IV can be assumed not to overflow up to and including the exiting
13515 // iteration. We proved this in one of two ways:
13516 // 1) We can show overflow doesn't occur before the exiting iteration
13517 // 1a) canIVOverflowOnLT, and b) step of one
13518 // 2) We can show that if overflow occurs, the loop must execute UB
13519 // before any possible exit.
13520 // Note that we have not yet proved RHS invariant (in general).
13521
13522 const SCEV *Start = IV->getStart();
13523
13524 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
13525 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
13526 // Use integer-typed versions for actual computation; we can't subtract
13527 // pointers in general.
13528 const SCEV *OrigStart = Start;
13529 const SCEV *OrigRHS = RHS;
13530 if (Start->getType()->isPointerTy()) {
13531 Start = getPtrToAddrExpr(Start);
13532 if (isa<SCEVCouldNotCompute>(Start))
13533 return Start;
13534 }
13535 if (RHS->getType()->isPointerTy()) {
13538 return RHS;
13539 }
13540
13541 const SCEV *End = nullptr, *BECount = nullptr,
13542 *BECountIfBackedgeTaken = nullptr;
13543 if (!isLoopInvariant(RHS, L)) {
13544 const auto *RHSAddRec = dyn_cast<SCEVAddRecExpr>(RHS);
13545 if (PositiveStride && RHSAddRec != nullptr && RHSAddRec->getLoop() == L &&
13546 any(RHSAddRec->getNoWrapFlags())) {
13547 // The structure of loop we are trying to calculate backedge count of:
13548 //
13549 // left = left_start
13550 // right = right_start
13551 //
13552 // while(left < right){
13553 // ... do something here ...
13554 // left += s1; // stride of left is s1 (s1 > 0)
13555 // right += s2; // stride of right is s2 (s2 < 0)
13556 // }
13557 //
13558
13559 const SCEV *RHSStart = RHSAddRec->getStart();
13560 const SCEV *RHSStride = RHSAddRec->getStepRecurrence(*this);
13561
13562 // If Stride - RHSStride is positive and does not overflow, we can write
13563 // backedge count as ->
13564 // ceil((End - Start) /u (Stride - RHSStride))
13565 // Where, End = max(RHSStart, Start)
13566
13567 // Check if RHSStride < 0 and Stride - RHSStride will not overflow.
13568 if (isKnownNegative(RHSStride) &&
13569 willNotOverflow(Instruction::Sub, /*Signed=*/true, Stride,
13570 RHSStride)) {
13571
13572 const SCEV *Denominator = getMinusSCEV(Stride, RHSStride);
13573 if (isKnownPositive(Denominator)) {
13574 End = IsSigned ? getSMaxExpr(RHSStart, Start)
13575 : getUMaxExpr(RHSStart, Start);
13576
13577 // We can do this because End >= Start, as End = max(RHSStart, Start)
13578 const SCEV *Delta = getMinusSCEV(End, Start);
13579
13580 BECount = getUDivCeilSCEV(Delta, Denominator);
13581 BECountIfBackedgeTaken =
13582 getUDivCeilSCEV(getMinusSCEV(RHSStart, Start), Denominator);
13583 }
13584 }
13585 }
13586 if (BECount == nullptr) {
13587 // If we cannot calculate ExactBECount, we can calculate the MaxBECount,
13588 // given the start, stride and max value for the end bound of the
13589 // loop (RHS), and the fact that IV does not overflow (which is
13590 // checked above).
13591 const SCEV *MaxBECount = computeMaxBECountForLT(
13592 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
13593 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
13594 MaxBECount, false /*MaxOrZero*/, Predicates);
13595 }
13596 } else {
13597 // Let End = max(RHS,Start). We use the expression (End-Start)/Stride to
13598 // describe the backedge count: if the backedge is taken at least once then
13599 // End is RHS, and if not End is Start so we get a backedge count of zero.
13600 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
13601 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!");
13602 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
13603 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
13604 // Can we prove Start - Stride < RHS, and either Start - Stride < Start or
13605 // (via !IVMayOverflow) that RHS + Stride - 1 does not overflow?
13606 if ((!IVMayOverflow ||
13607 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart)) &&
13608 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
13609 // In this case, we can use a refined formula for computing backedge
13610 // taken count. The general formula remains:
13611 // "End-Start /uceiling Stride"
13612 // We want to use the alternate formula:
13613 // "((RHS - 1) - (Start - Stride)) /u Stride"
13614 // Let's do a quick case analysis to show these are equivalent under
13615 // our preconditions.
13616 // * For RHS <= Start (End is Start), the backedge-taken count must be
13617 // zero. Together with the precondition "Start - Stride < RHS", we have
13618 // "Start - Stride < RHS <= Start". Subtracting Start - Stride from
13619 // all sides we get "0 < RHS - (Start - Stride) <= Stride".
13620 // Subtracting 1 we get "0 <= (RHS - 1) - (Start - Stride) < Stride".
13621 // So dividing that by Stride gives zero.
13622 //
13623 // * For RHS > Start (End is RHS), the backedge count must be
13624 // "RHS-Start /uceil Stride", so it is sufficient to show that the
13625 // numerator "((RHS - 1) - (Start - Stride))" does not overflow.
13626 //
13627 // If "Start - Stride < Start" holds, we have
13628 // "RHS > Start > Start - Stride". As such
13629 // "RHS - (Start - Stride) - 1" does not overflow, which is the
13630 // reassociated numerator.
13631 //
13632 // Otherwise !IVMayOverflow guarantees "RHS + (Stride - 1) <= MaxV",
13633 // where MaxV is the maximum signed/unsigned value. Let MinV be the
13634 // matching minimum value. "Start >= MinV" gives
13635 // "RHS + (Stride - 1) - Start <= MaxV - MinV", and as "MaxV - MinV" is
13636 // the largest unsigned value, the reassociated numerator does not
13637 // overflow.
13638 const SCEV *MinusOne = getMinusOne(Stride->getType());
13639 const SCEV *Numerator =
13640 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
13641 BECount = getUDivExpr(Numerator, Stride);
13642 }
13643
13644 if (!BECount) {
13645 auto canProveRHSGreaterThanEqualStart = [&]() {
13646 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
13647 const SCEV *GuardedRHS = applyLoopGuards(OrigRHS, L);
13648 const SCEV *GuardedStart = applyLoopGuards(OrigStart, L);
13649
13650 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart) ||
13651 isKnownPredicate(CondGE, GuardedRHS, GuardedStart))
13652 return true;
13653
13654 // (RHS > Start - 1) implies RHS >= Start.
13655 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
13656 // "Start - 1" doesn't overflow.
13657 // * For signed comparison, if Start - 1 does overflow, it's equal
13658 // to INT_MAX, and "RHS >s INT_MAX" is trivially false.
13659 // * For unsigned comparison, if Start - 1 does overflow, it's equal
13660 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
13661 //
13662 // FIXME: Should isLoopEntryGuardedByCond do this for us?
13663 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13664 auto *StartMinusOne =
13665 getAddExpr(OrigStart, getMinusOne(OrigStart->getType()));
13666 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
13667 };
13668
13669 // If we know that RHS >= Start in the context of loop, then we know
13670 // that max(RHS, Start) = RHS at this point.
13671 if (canProveRHSGreaterThanEqualStart()) {
13672 End = RHS;
13673 } else {
13674 // If RHS < Start, the backedge will be taken zero times. So in
13675 // general, we can write the backedge-taken count as:
13676 //
13677 // RHS >= Start ? ceil(RHS - Start) / Stride : 0
13678 //
13679 // We convert it to the following to make it more convenient for SCEV:
13680 //
13681 // ceil(max(RHS, Start) - Start) / Stride
13682 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
13683
13684 // See what would happen if we assume the backedge is taken. This is
13685 // used to compute MaxBECount.
13686 BECountIfBackedgeTaken =
13687 getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
13688 }
13689
13690 // At this point, we know:
13691 //
13692 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
13693 // 2. The index variable doesn't overflow.
13694 //
13695 // Therefore, we know N exists such that
13696 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
13697 // doesn't overflow.
13698 //
13699 // Using this information, try to prove whether the addition in
13700 // "(Start - End) + (Stride - 1)" has unsigned overflow.
13701 //
13702 // If the IV cannot overflow, RHS is at least Stride - 1 below the maximum
13703 // value, so the distance End - Start is at most UMAX - (Stride - 1) and
13704 // the (Stride - 1) addition below cannot overflow.
13705 const SCEV *One = getOne(Stride->getType());
13706 bool MayAddOverflow = IVMayOverflow && [&] {
13707 if (isKnownToBeAPowerOfTwo(Stride)) {
13708 // Suppose Stride is a power of two, and Start/End are unsigned
13709 // integers. Let UMAX be the largest representable unsigned
13710 // integer.
13711 //
13712 // By the preconditions of this function, we know
13713 // "(Start + Stride * N) >= End", and this doesn't overflow.
13714 // As a formula:
13715 //
13716 // End <= (Start + Stride * N) <= UMAX
13717 //
13718 // Subtracting Start from all the terms:
13719 //
13720 // End - Start <= Stride * N <= UMAX - Start
13721 //
13722 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore:
13723 //
13724 // End - Start <= Stride * N <= UMAX
13725 //
13726 // Stride * N is a multiple of Stride. Therefore,
13727 //
13728 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
13729 //
13730 // Since Stride is a power of two, UMAX + 1 is divisible by
13731 // Stride. Therefore, UMAX mod Stride == Stride - 1. So we can
13732 // write:
13733 //
13734 // End - Start <= Stride * N <= UMAX - Stride - 1
13735 //
13736 // Dropping the middle term:
13737 //
13738 // End - Start <= UMAX - Stride - 1
13739 //
13740 // Adding Stride - 1 to both sides:
13741 //
13742 // (End - Start) + (Stride - 1) <= UMAX
13743 //
13744 // In other words, the addition doesn't have unsigned overflow.
13745 //
13746 // A similar proof works if we treat Start/End as signed values.
13747 // Just rewrite steps before "End - Start <= Stride * N <= UMAX"
13748 // to use signed max instead of unsigned max. Note that we're
13749 // trying to prove a lack of unsigned overflow in either case.
13750 return false;
13751 }
13752 if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
13753 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End
13754 // - 1. If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1
13755 // <u End. If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End -
13756 // 1 <s End.
13757 //
13758 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 ==
13759 // End.
13760 return false;
13761 }
13762 return true;
13763 }();
13764
13765 const SCEV *Delta = getMinusSCEV(End, Start);
13766 if (!MayAddOverflow) {
13767 // floor((D + (S - 1)) / S)
13768 // We prefer this formulation if it's legal because it's fewer
13769 // operations.
13770 BECount =
13771 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13772 } else {
13773 BECount = getUDivCeilSCEV(Delta, Stride);
13774 }
13775 }
13776 }
13777
13778 const SCEV *ConstantMaxBECount;
13779 bool MaxOrZero = false;
13780 if (isa<SCEVConstant>(BECount)) {
13781 ConstantMaxBECount = BECount;
13782 } else if (BECountIfBackedgeTaken &&
13783 isa<SCEVConstant>(BECountIfBackedgeTaken)) {
13784 // If we know exactly how many times the backedge will be taken if it's
13785 // taken at least once, then the backedge count will either be that or
13786 // zero.
13787 ConstantMaxBECount = BECountIfBackedgeTaken;
13788 MaxOrZero = true;
13789 } else {
13790 ConstantMaxBECount = computeMaxBECountForLT(
13791 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
13792 }
13793
13794 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
13795 !isa<SCEVCouldNotCompute>(BECount))
13796 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
13797
13798 const SCEV *SymbolicMaxBECount =
13799 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13800 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
13801 Predicates);
13802}
13803
13804ScalarEvolution::ExitLimit ScalarEvolution::howManyGreaterThans(
13805 const SCEV *LHS, const SCEV *RHS, const Loop *L, bool IsSigned,
13806 bool ControlsOnlyExit, bool AllowPredicates) {
13808 // We handle only IV > Invariant
13809 if (!isLoopInvariant(RHS, L))
13810 return getCouldNotCompute();
13811
13812 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
13813 if (!IV && AllowPredicates)
13814 // Try to make this an AddRec using runtime tests, in the first X
13815 // iterations of this loop, where X is the SCEV expression found by the
13816 // algorithm below.
13817 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13818
13819 // Avoid weird loops
13820 if (!IV || IV->getLoop() != L || !IV->isAffine())
13821 return getCouldNotCompute();
13822
13823 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13824 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13826
13827 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
13828
13829 // Avoid negative or zero stride values
13830 if (!isKnownPositive(Stride))
13831 return getCouldNotCompute();
13832
13833 // Avoid proven overflow cases: this will ensure that the backedge taken count
13834 // will not generate any unsigned overflow. Relaxed no-overflow conditions
13835 // exploit NoWrapFlags, allowing to optimize in presence of undefined
13836 // behaviors like the case of C language.
13837 bool MayAddOverflow = false;
13838 const SCEV *Start = IV->getStart();
13839 const SCEV *End = RHS;
13840 if (!Stride->isOne() && canIVOverflowOnGT(RHS, Stride, IsSigned)) {
13841 if (!NoWrap)
13842 return getCouldNotCompute();
13843 MayAddOverflow = true;
13844 }
13845
13846 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
13847 // If we know that Start >= RHS in the context of loop, then we know that
13848 // min(RHS, Start) = RHS at this point.
13850 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
13851 End = RHS;
13852 else
13853 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
13854 }
13855
13856 if (Start->getType()->isPointerTy()) {
13857 Start = getPtrToAddrExpr(Start);
13858 if (isa<SCEVCouldNotCompute>(Start))
13859 return Start;
13860 }
13861 if (End->getType()->isPointerTy()) {
13862 End = getPtrToAddrExpr(End);
13863 if (isa<SCEVCouldNotCompute>(End))
13864 return End;
13865 }
13866
13867 const SCEV *Delta = getMinusSCEV(Start, End);
13868 const SCEV *BECount;
13869 if (MayAddOverflow) {
13870 // The ceiling division instead needs Start >= End, so that (Start - End) is
13871 // the exact unsigned distance between them.
13873 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, End))
13874 return getCouldNotCompute();
13875 BECount = getUDivCeilSCEV(Delta, Stride);
13876 } else {
13877 // Compute ((Start - End) + (Stride - 1)) / Stride, if the IV cannot
13878 // overflow as it requires fewer operations.
13879 const SCEV *One = getOne(Stride->getType());
13880 BECount = getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13881 }
13882
13883 APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
13885
13886 APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
13887 : getUnsignedRangeMin(Stride);
13888
13889 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
13890 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
13891 : APInt::getMinValue(BitWidth) + (MinStride - 1);
13892
13893 // Although End can be a MIN expression we estimate MinEnd considering only
13894 // the case End = RHS. This is safe because in the other case (Start - End)
13895 // is zero, leading to a zero maximum backedge taken count.
13896 APInt MinEnd =
13897 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
13898 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
13899
13900 const SCEV *ConstantMaxBECount =
13901 isa<SCEVConstant>(BECount)
13902 ? BECount
13903 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd),
13904 getConstant(MinStride));
13905
13906 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount))
13907 ConstantMaxBECount = BECount;
13908 const SCEV *SymbolicMaxBECount =
13909 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13910
13911 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
13912 Predicates);
13913}
13914
13916 ScalarEvolution &SE) const {
13917 if (Range.isFullSet()) // Infinite loop.
13918 return SE.getCouldNotCompute();
13919
13920 // If the start is a non-zero constant, shift the range to simplify things.
13921 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
13922 if (!SC->getValue()->isZero()) {
13924 Operands[0] = SE.getZero(SC->getType());
13925 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
13927 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
13928 return ShiftedAddRec->getNumIterationsInRange(
13929 Range.subtract(SC->getAPInt()), SE);
13930 // This is strange and shouldn't happen.
13931 return SE.getCouldNotCompute();
13932 }
13933
13934 // The only time we can solve this is when we have all constant indices.
13935 // Otherwise, we cannot determine the overflow conditions.
13937 return SE.getCouldNotCompute();
13938
13939 // Okay at this point we know that all elements of the chrec are constants and
13940 // that the start element is zero.
13941
13942 // First check to see if the range contains zero. If not, the first
13943 // iteration exits.
13944 unsigned BitWidth = SE.getTypeSizeInBits(getType());
13945 if (!Range.contains(APInt(BitWidth, 0)))
13946 return SE.getZero(getType());
13947
13948 if (isAffine()) {
13949 // If this is an affine expression then we have this situation:
13950 // Solve {0,+,A} in Range === Ax in Range
13951
13952 // We know that zero is in the range. If A is positive then we know that
13953 // the upper value of the range must be the first possible exit value.
13954 // If A is negative then the lower of the range is the last possible loop
13955 // value. Also note that we already checked for a full range.
13956 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
13957 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
13958
13959 // The exit value should be (End+A)/A.
13960 APInt ExitVal = (End + A).udiv(A);
13961 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
13962
13963 // Evaluate at the exit value. If we really did fall out of the valid
13964 // range, then we computed our trip count, otherwise wrap around or other
13965 // things must have happened.
13966 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
13967 if (Range.contains(Val->getValue()))
13968 return SE.getCouldNotCompute(); // Something strange happened
13969
13970 // Ensure that the previous value is in the range.
13971 assert(Range.contains(
13973 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
13974 "Linear scev computation is off in a bad way!");
13975 return SE.getConstant(ExitValue);
13976 }
13977
13978 if (isQuadratic()) {
13979 if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
13980 return SE.getConstant(*S);
13981 }
13982
13983 return SE.getCouldNotCompute();
13984}
13985
13986const SCEVAddRecExpr *
13988 assert(getNumOperands() > 1 && "AddRec with zero step?");
13989 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
13990 // but in this case we cannot guarantee that the value returned will be an
13991 // AddRec because SCEV does not have a fixed point where it stops
13992 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
13993 // may happen if we reach arithmetic depth limit while simplifying. So we
13994 // construct the returned value explicitly.
13996 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
13997 // (this + Step) is {A+B,+,B+C,+...,+,N}.
13998 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
13999 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
14000 // We know that the last operand is not a constant zero (otherwise it would
14001 // have been popped out earlier). This guarantees us that if the result has
14002 // the same last operand, then it will also not be popped out, meaning that
14003 // the returned value will be an AddRec.
14004 const SCEV *Last = getOperand(getNumOperands() - 1);
14005 assert(!Last->isZero() && "Recurrency with zero step?");
14006 Ops.push_back(Last);
14009}
14010
14011// Return true when S contains at least an undef value.
14013 return SCEVExprContains(
14014 S, [](const SCEV *S) { return match(S, m_scev_UndefOrPoison()); });
14015}
14016
14017// Return true when S contains a value that is a nullptr.
14019 return SCEVExprContains(S, [](const SCEV *S) {
14020 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
14021 return SU->getValue() == nullptr;
14022 return false;
14023 });
14024}
14025
14026/// Return the size of an element read or written by Inst.
14028 Type *Ty;
14029 Type *PtrTy;
14030 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
14031 Ty = Store->getValueOperand()->getType();
14032 PtrTy = Store->getPointerOperandType();
14033 } else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
14034 Ty = Load->getType();
14035 PtrTy = Load->getPointerOperandType();
14036 } else {
14037 return nullptr;
14038 }
14039
14040 Type *ETy = getEffectiveSCEVType(PtrTy);
14041 return getSizeOfExpr(ETy, Ty);
14042}
14043
14044//===----------------------------------------------------------------------===//
14045// SCEVCallbackVH Class Implementation
14046//===----------------------------------------------------------------------===//
14047
14049 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14050 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
14051 SE->ConstantEvolutionLoopExitValue.erase(PN);
14052 SE->eraseValueFromMap(getValPtr());
14053 // this now dangles!
14054}
14055
14056void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
14057 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14058
14059 // Forget all the expressions associated with users of the old value,
14060 // so that future queries will recompute the expressions using the new
14061 // value.
14062 SE->forgetValue(getValPtr());
14063 // this now dangles!
14064}
14065
14066ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
14067 : CallbackVH(V), SE(se) {}
14068
14069//===----------------------------------------------------------------------===//
14070// ScalarEvolution Class Implementation
14071//===----------------------------------------------------------------------===//
14072
14075 LoopInfo &LI)
14076 : F(F), DL(F.getDataLayout()), TLI(TLI), AC(AC), DT(DT), LI(LI),
14077 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
14078 LoopDispositions(64), BlockDispositions(64) {
14079 // To use guards for proving predicates, we need to scan every instruction in
14080 // relevant basic blocks, and not just terminators. Doing this is a waste of
14081 // time if the IR does not actually contain any calls to
14082 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
14083 //
14084 // This pessimizes the case where a pass that preserves ScalarEvolution wants
14085 // to _add_ guards to the module when there weren't any before, and wants
14086 // ScalarEvolution to optimize based on those guards. For now we prefer to be
14087 // efficient in lieu of being smart in that rather obscure case.
14088
14089 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
14090 F.getParent(), Intrinsic::experimental_guard);
14091 HasGuards = GuardDecl && !GuardDecl->use_empty();
14092}
14093
14095 : F(Arg.F), DL(Arg.DL), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC),
14096 DT(Arg.DT), LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
14097 ValueExprMap(std::move(Arg.ValueExprMap)),
14098 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
14099 PendingMerges(std::move(Arg.PendingMerges)),
14100 ConstantMultipleCache(std::move(Arg.ConstantMultipleCache)),
14101 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
14102 PredicatedBackedgeTakenCounts(
14103 std::move(Arg.PredicatedBackedgeTakenCounts)),
14104 BECountUsers(std::move(Arg.BECountUsers)),
14105 ConstantEvolutionLoopExitValue(
14106 std::move(Arg.ConstantEvolutionLoopExitValue)),
14107 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
14108 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
14109 LoopDispositions(std::move(Arg.LoopDispositions)),
14110 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
14111 BlockDispositions(std::move(Arg.BlockDispositions)),
14112 SCEVUsers(std::move(Arg.SCEVUsers)),
14113 UnsignedRanges(std::move(Arg.UnsignedRanges)),
14114 SignedRanges(std::move(Arg.SignedRanges)),
14115 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
14116 UniquePreds(std::move(Arg.UniquePreds)),
14117 SCEVAllocator(std::move(Arg.SCEVAllocator)),
14118 ConstantSCEVs(std::move(Arg.ConstantSCEVs)),
14119 LoopUsers(std::move(Arg.LoopUsers)),
14120 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
14121 FirstUnknown(Arg.FirstUnknown) {
14122 Arg.FirstUnknown = nullptr;
14123}
14124
14126 // Iterate through all the SCEVUnknown instances and call their
14127 // destructors, so that they release their references to their values.
14128 for (SCEVUnknown *U = FirstUnknown; U;) {
14129 SCEVUnknown *Tmp = U;
14130 U = U->Next;
14131 Tmp->~SCEVUnknown();
14132 }
14133 FirstUnknown = nullptr;
14134
14135 ExprValueMap.clear();
14136 ValueExprMap.clear();
14137 HasRecMap.clear();
14138 BackedgeTakenCounts.clear();
14139 PredicatedBackedgeTakenCounts.clear();
14140
14141 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
14142 assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
14143 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
14144 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
14145}
14146
14150
14151/// When printing a top-level SCEV for trip counts, it's helpful to include
14152/// a type for constants which are otherwise hard to disambiguate.
14153static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV* S) {
14154 if (isa<SCEVConstant>(S))
14155 OS << *S->getType() << " ";
14156 OS << *S;
14157}
14158
14160 const Loop *L) {
14161 // Print all inner loops first
14162 for (Loop *I : *L)
14163 PrintLoopInfo(OS, SE, I);
14164
14165 OS << "Loop ";
14166 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14167 OS << ": ";
14168
14169 SmallVector<BasicBlock *, 8> ExitingBlocks;
14170 L->getExitingBlocks(ExitingBlocks);
14171 if (ExitingBlocks.size() != 1)
14172 OS << "<multiple exits> ";
14173
14174 auto *BTC = SE->getBackedgeTakenCount(L);
14175 if (!isa<SCEVCouldNotCompute>(BTC)) {
14176 OS << "backedge-taken count is ";
14177 PrintSCEVWithTypeHint(OS, BTC);
14178 } else
14179 OS << "Unpredictable backedge-taken count.";
14180 OS << "\n";
14181
14182 if (ExitingBlocks.size() > 1)
14183 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14184 OS << " exit count for " << ExitingBlock->getName() << ": ";
14185 const SCEV *EC = SE->getExitCount(L, ExitingBlock);
14186 PrintSCEVWithTypeHint(OS, EC);
14187 if (isa<SCEVCouldNotCompute>(EC)) {
14188 // Retry with predicates.
14190 EC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates);
14191 if (!isa<SCEVCouldNotCompute>(EC)) {
14192 OS << "\n predicated exit count for " << ExitingBlock->getName()
14193 << ": ";
14194 PrintSCEVWithTypeHint(OS, EC);
14195 OS << "\n Predicates:\n";
14196 for (const auto *P : Predicates)
14197 P->print(OS, 4);
14198 }
14199 }
14200 OS << "\n";
14201 }
14202
14203 OS << "Loop ";
14204 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14205 OS << ": ";
14206
14207 auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
14208 if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
14209 OS << "constant max backedge-taken count is ";
14210 PrintSCEVWithTypeHint(OS, ConstantBTC);
14212 OS << ", actual taken count either this or zero.";
14213 } else {
14214 OS << "Unpredictable constant max backedge-taken count. ";
14215 }
14216
14217 OS << "\n"
14218 "Loop ";
14219 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14220 OS << ": ";
14221
14222 auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
14223 if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
14224 OS << "symbolic max backedge-taken count is ";
14225 PrintSCEVWithTypeHint(OS, SymbolicBTC);
14227 OS << ", actual taken count either this or zero.";
14228 } else {
14229 OS << "Unpredictable symbolic max backedge-taken count. ";
14230 }
14231 OS << "\n";
14232
14233 if (ExitingBlocks.size() > 1)
14234 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14235 OS << " symbolic max exit count for " << ExitingBlock->getName() << ": ";
14236 auto *ExitBTC = SE->getExitCount(L, ExitingBlock,
14238 PrintSCEVWithTypeHint(OS, ExitBTC);
14239 if (isa<SCEVCouldNotCompute>(ExitBTC)) {
14240 // Retry with predicates.
14242 ExitBTC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates,
14244 if (!isa<SCEVCouldNotCompute>(ExitBTC)) {
14245 OS << "\n predicated symbolic max exit count for "
14246 << ExitingBlock->getName() << ": ";
14247 PrintSCEVWithTypeHint(OS, ExitBTC);
14248 OS << "\n Predicates:\n";
14249 for (const auto *P : Predicates)
14250 P->print(OS, 4);
14251 }
14252 }
14253 OS << "\n";
14254 }
14255
14257 auto *PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
14258 if (PBT != BTC) {
14259 OS << "Loop ";
14260 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14261 OS << ": ";
14262 if (!isa<SCEVCouldNotCompute>(PBT)) {
14263 OS << "Predicated backedge-taken count is ";
14264 PrintSCEVWithTypeHint(OS, PBT);
14265 } else
14266 OS << "Unpredictable predicated backedge-taken count.";
14267 OS << "\n";
14268 OS << " Predicates:\n";
14269 for (const auto *P : Preds)
14270 P->print(OS, 4);
14271 }
14272 Preds.clear();
14273
14274 auto *PredConstantMax =
14276 if (PredConstantMax != ConstantBTC) {
14277 OS << "Loop ";
14278 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14279 OS << ": ";
14280 if (!isa<SCEVCouldNotCompute>(PredConstantMax)) {
14281 OS << "Predicated constant max backedge-taken count is ";
14282 PrintSCEVWithTypeHint(OS, PredConstantMax);
14283 } else
14284 OS << "Unpredictable predicated constant max backedge-taken count.";
14285 OS << "\n";
14286 OS << " Predicates:\n";
14287 for (const auto *P : Preds)
14288 P->print(OS, 4);
14289 }
14290 Preds.clear();
14291
14292 auto *PredSymbolicMax =
14294 if (SymbolicBTC != PredSymbolicMax) {
14295 OS << "Loop ";
14296 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14297 OS << ": ";
14298 if (!isa<SCEVCouldNotCompute>(PredSymbolicMax)) {
14299 OS << "Predicated symbolic max backedge-taken count is ";
14300 PrintSCEVWithTypeHint(OS, PredSymbolicMax);
14301 } else
14302 OS << "Unpredictable predicated symbolic max backedge-taken count.";
14303 OS << "\n";
14304 OS << " Predicates:\n";
14305 for (const auto *P : Preds)
14306 P->print(OS, 4);
14307 }
14308
14310 OS << "Loop ";
14311 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14312 OS << ": ";
14313 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
14314 }
14315}
14316
14317namespace llvm {
14318// Note: these overloaded operators need to be in the llvm namespace for them
14319// to be resolved correctly. If we put them outside the llvm namespace, the
14320//
14321// OS << ": " << SE.getLoopDisposition(SV, InnerL);
14322//
14323// code below "breaks" and start printing raw enum values as opposed to the
14324// string values.
14327 switch (LD) {
14329 OS << "Variant";
14330 break;
14332 OS << "Invariant";
14333 break;
14335 OS << "Uniform";
14336 break;
14338 OS << "Computable";
14339 break;
14340 }
14341 return OS;
14342}
14343
14346 switch (BD) {
14348 OS << "DoesNotDominate";
14349 break;
14351 OS << "Dominates";
14352 break;
14354 OS << "ProperlyDominates";
14355 break;
14356 }
14357 return OS;
14358}
14359} // namespace llvm
14360
14362 // ScalarEvolution's implementation of the print method is to print
14363 // out SCEV values of all instructions that are interesting. Doing
14364 // this potentially causes it to create new SCEV objects though,
14365 // which technically conflicts with the const qualifier. This isn't
14366 // observable from outside the class though, so casting away the
14367 // const isn't dangerous.
14368 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14369
14370 if (ClassifyExpressions) {
14371 OS << "Classifying expressions for: ";
14372 F.printAsOperand(OS, /*PrintType=*/false);
14373 OS << "\n";
14374 for (Instruction &I : instructions(F))
14375 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
14376 OS << I << '\n';
14377 OS << " --> ";
14378 const SCEV *SV = SE.getSCEV(&I);
14379 SV->print(OS);
14380 if (!isa<SCEVCouldNotCompute>(SV)) {
14381 OS << " U: ";
14382 SE.getUnsignedRange(SV).print(OS);
14383 OS << " S: ";
14384 SE.getSignedRange(SV).print(OS);
14385 }
14386
14387 const Loop *L = LI.getLoopFor(I.getParent());
14388
14389 SCEVUse AtUse = SE.getSCEVAtScope(SV, L);
14390 if (AtUse != SV) {
14391 OS << " --> ";
14392 OS << AtUse;
14393 if (!isa<SCEVCouldNotCompute>(AtUse)) {
14394 OS << " U: ";
14395 SE.getUnsignedRange(AtUse).print(OS);
14396 OS << " S: ";
14397 SE.getSignedRange(AtUse).print(OS);
14398 }
14399 }
14400
14401 if (L) {
14402 OS << "\t\t" "Exits: ";
14403 SCEVUse ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
14404 if (!SE.isLoopInvariant(ExitValue, L)) {
14405 OS << "<<Unknown>>";
14406 } else {
14407 OS << ExitValue;
14408 }
14409
14410 ListSeparator LS(", ", "\t\tLoopDispositions: { ");
14411 for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
14412 OS << LS;
14413 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14414 OS << ": " << SE.getLoopDisposition(SV, Iter);
14415 }
14416
14417 for (const auto *InnerL : depth_first(L)) {
14418 if (InnerL == L)
14419 continue;
14420 OS << LS;
14421 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14422 OS << ": " << SE.getLoopDisposition(SV, InnerL);
14423 }
14424
14425 OS << " }";
14426 }
14427
14428 OS << "\n";
14429 }
14430 }
14431
14432 OS << "Determining loop execution counts for: ";
14433 F.printAsOperand(OS, /*PrintType=*/false);
14434 OS << "\n";
14435 for (Loop *I : LI)
14436 PrintLoopInfo(OS, &SE, I);
14437}
14438
14441 auto &Values = LoopDispositions[S];
14442 for (auto &V : Values) {
14443 if (V.getPointer() == L)
14444 return V.getInt();
14445 }
14446 Values.emplace_back(L, LoopVariant);
14447 LoopDisposition D = computeLoopDisposition(S, L);
14448 auto &Values2 = LoopDispositions[S];
14449 for (auto &V : llvm::reverse(Values2)) {
14450 if (V.getPointer() == L) {
14451 V.setInt(D);
14452 break;
14453 }
14454 }
14455 return D;
14456}
14457
14459ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
14460 switch (S->getSCEVType()) {
14461 case scConstant:
14462 case scVScale:
14463 return LoopInvariant;
14464 case scAddRecExpr: {
14465 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14466
14467 // If L is the addrec's loop, it's computable.
14468 if (AR->getLoop() == L)
14469 return LoopComputable;
14470
14471 // Add recurrences are never invariant in the function-body (null loop).
14472 if (!L)
14473 return LoopVariant;
14474
14475 // Everything that is not defined at loop entry is variant.
14476 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) {
14477 if (L->contains(AR->getLoop()) &&
14478 llvm::all_of(AR->operands(),
14479 [&](const SCEV *Op) { return isLoopUniform(Op, L); }))
14480 return LoopUniform;
14481
14482 return LoopVariant;
14483 }
14484 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
14485 " dominate the contained loop's header?");
14486
14487 // This recurrence is invariant w.r.t. L if AR's loop contains L.
14488 if (AR->getLoop()->contains(L))
14489 return LoopInvariant;
14490
14491 // This recurrence is variant w.r.t. L if any of its operands
14492 // are variant.
14493 for (SCEVUse Op : AR->operands())
14494 if (!isLoopInvariant(Op, L))
14495 return LoopVariant;
14496
14497 // Otherwise it's loop-invariant.
14498 return LoopInvariant;
14499 }
14500 case scTruncate:
14501 case scZeroExtend:
14502 case scSignExtend:
14503 case scPtrToAddr:
14504 case scAddExpr:
14505 case scMulExpr:
14506 case scUDivExpr:
14507 case scUMaxExpr:
14508 case scSMaxExpr:
14509 case scUMinExpr:
14510 case scSMinExpr:
14511 case scSequentialUMinExpr: {
14512 bool HasVarying = false;
14513 bool HasUniform = false;
14514 for (SCEVUse Op : S->operands()) {
14516 if (D == LoopVariant)
14517 return LoopVariant;
14518 if (D == LoopComputable)
14519 HasVarying = true;
14520 if (D == LoopUniform)
14521 HasUniform = true;
14522 }
14523 return HasVarying ? (HasUniform ? LoopVariant : LoopComputable)
14524 : (HasUniform ? LoopUniform : LoopInvariant);
14525 }
14526 case scUnknown:
14527 // All non-instruction values are loop invariant. All instructions are loop
14528 // invariant if they are not contained in the specified loop.
14529 // Instructions are never considered invariant in the function body
14530 // (null loop) because they are defined within the "loop".
14532 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
14533 return LoopInvariant;
14534 case scCouldNotCompute:
14535 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14536 }
14537 llvm_unreachable("Unknown SCEV kind!");
14538}
14539
14540bool ScalarEvolution::isLoopUniform(const SCEV *S, const Loop *L) {
14542 return D == LoopUniform || D == LoopInvariant;
14543}
14544
14546 return getLoopDisposition(S, L) == LoopInvariant;
14547}
14548
14550 return getLoopDisposition(S, L) == LoopComputable;
14551}
14552
14555 auto &Values = BlockDispositions[S];
14556 for (auto &V : Values) {
14557 if (V.getPointer() == BB)
14558 return V.getInt();
14559 }
14560 Values.emplace_back(BB, DoesNotDominateBlock);
14561 BlockDisposition D = computeBlockDisposition(S, BB);
14562 auto &Values2 = BlockDispositions[S];
14563 for (auto &V : llvm::reverse(Values2)) {
14564 if (V.getPointer() == BB) {
14565 V.setInt(D);
14566 break;
14567 }
14568 }
14569 return D;
14570}
14571
14573ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
14574 switch (S->getSCEVType()) {
14575 case scConstant:
14576 case scVScale:
14578 case scAddRecExpr: {
14579 // This uses a "dominates" query instead of "properly dominates" query
14580 // to test for proper dominance too, because the instruction which
14581 // produces the addrec's value is a PHI, and a PHI effectively properly
14582 // dominates its entire containing block.
14583 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14584 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
14585 return DoesNotDominateBlock;
14586
14587 // Fall through into SCEVNAryExpr handling.
14588 [[fallthrough]];
14589 }
14590 case scTruncate:
14591 case scZeroExtend:
14592 case scSignExtend:
14593 case scPtrToAddr:
14594 case scAddExpr:
14595 case scMulExpr:
14596 case scUDivExpr:
14597 case scUMaxExpr:
14598 case scSMaxExpr:
14599 case scUMinExpr:
14600 case scSMinExpr:
14601 case scSequentialUMinExpr: {
14602 bool Proper = true;
14603 for (const SCEV *NAryOp : S->operands()) {
14605 if (D == DoesNotDominateBlock)
14606 return DoesNotDominateBlock;
14607 if (D == DominatesBlock)
14608 Proper = false;
14609 }
14610 return Proper ? ProperlyDominatesBlock : DominatesBlock;
14611 }
14612 case scUnknown:
14613 if (Instruction *I =
14615 if (I->getParent() == BB)
14616 return DominatesBlock;
14617 if (DT.properlyDominates(I->getParent(), BB))
14619 return DoesNotDominateBlock;
14620 }
14622 case scCouldNotCompute:
14623 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14624 }
14625 llvm_unreachable("Unknown SCEV kind!");
14626}
14627
14628bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
14629 return getBlockDisposition(S, BB) >= DominatesBlock;
14630}
14631
14634}
14635
14636bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
14637 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
14638}
14639
14640void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
14641 bool Predicated) {
14642 auto &BECounts =
14643 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14644 auto It = BECounts.find(L);
14645 if (It != BECounts.end()) {
14646 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
14647 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14648 if (!isa<SCEVConstant>(S)) {
14649 auto UserIt = BECountUsers.find(S);
14650 assert(UserIt != BECountUsers.end());
14651 UserIt->second.erase({L, Predicated});
14652 }
14653 }
14654 }
14655 BECounts.erase(It);
14656 }
14657}
14658
14659void ScalarEvolution::forgetMemoizedResults(ArrayRef<SCEVUse> SCEVs) {
14660 SmallPtrSet<const SCEV *, 8> ToForget(llvm::from_range, SCEVs);
14661 SmallVector<SCEVUse, 8> Worklist(ToForget.begin(), ToForget.end());
14662
14663 while (!Worklist.empty()) {
14664 const SCEV *Curr = Worklist.pop_back_val();
14665 auto Users = SCEVUsers.find(Curr);
14666 if (Users != SCEVUsers.end())
14667 for (const auto *User : Users->second)
14668 if (ToForget.insert(User).second)
14669 Worklist.push_back(User);
14670 }
14671
14672 for (const auto *S : ToForget)
14673 forgetMemoizedResultsImpl(S);
14674
14675 PredicatedSCEVRewrites.remove_if(
14676 [&](const auto &Entry) { return ToForget.count(Entry.first.first); });
14677}
14678
14679void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
14680 LoopDispositions.erase(S);
14681 BlockDispositions.erase(S);
14682 UnsignedRanges.erase(S);
14683 SignedRanges.erase(S);
14684 HasRecMap.erase(S);
14685 ConstantMultipleCache.erase(S);
14686
14687 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
14688 UnsignedWrapViaInductionTried.erase(AR);
14689 SignedWrapViaInductionTried.erase(AR);
14690 }
14691
14692 auto ExprIt = ExprValueMap.find(S);
14693 if (ExprIt != ExprValueMap.end()) {
14694 for (Value *V : ExprIt->second) {
14695 auto ValueIt = ValueExprMap.find_as(V);
14696 if (ValueIt != ValueExprMap.end())
14697 ValueExprMap.erase(ValueIt);
14698 }
14699 ExprValueMap.erase(ExprIt);
14700 }
14701
14702 auto ScopeIt = ValuesAtScopes.find(S);
14703 if (ScopeIt != ValuesAtScopes.end()) {
14704 for (const auto &Pair : ScopeIt->second)
14705 if (!isa_and_nonnull<SCEVConstant>(Pair.second))
14706 llvm::erase(ValuesAtScopesUsers[Pair.second.getPointer()],
14707 std::make_pair(Pair.first, S));
14708 ValuesAtScopes.erase(ScopeIt);
14709 }
14710
14711 auto ScopeUserIt = ValuesAtScopesUsers.find(S);
14712 if (ScopeUserIt != ValuesAtScopesUsers.end()) {
14713 for (const auto &Pair : ScopeUserIt->second)
14714 // The recorded value at scope is a use of S, which may carry no-wrap
14715 // flags that are not part of this key.
14716 llvm::erase_if(ValuesAtScopes[Pair.second], [&](const auto &LS) {
14717 return LS.first == Pair.first && LS.second.getPointer() == S;
14718 });
14719 ValuesAtScopesUsers.erase(ScopeUserIt);
14720 }
14721
14722 auto BEUsersIt = BECountUsers.find(S);
14723 if (BEUsersIt != BECountUsers.end()) {
14724 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
14725 auto Copy = BEUsersIt->second;
14726 for (const auto &Pair : Copy)
14727 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
14728 BECountUsers.erase(BEUsersIt);
14729 }
14730
14731 auto FoldUser = FoldCacheUser.find(S);
14732 if (FoldUser != FoldCacheUser.end())
14733 for (auto &KV : FoldUser->second)
14734 FoldCache.erase(KV);
14735 FoldCacheUser.erase(S);
14736}
14737
14738void
14739ScalarEvolution::getUsedLoops(const SCEV *S,
14740 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
14741 struct FindUsedLoops {
14742 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
14743 : LoopsUsed(LoopsUsed) {}
14744 SmallPtrSetImpl<const Loop *> &LoopsUsed;
14745 bool follow(const SCEV *S) {
14746 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
14747 LoopsUsed.insert(AR->getLoop());
14748 return true;
14749 }
14750
14751 bool isDone() const { return false; }
14752 };
14753
14754 FindUsedLoops F(LoopsUsed);
14755 SCEVTraversal<FindUsedLoops>(F).visitAll(S);
14756}
14757
14758void ScalarEvolution::getReachableBlocks(
14761 Worklist.push_back(&F.getEntryBlock());
14762 while (!Worklist.empty()) {
14763 BasicBlock *BB = Worklist.pop_back_val();
14764 if (!Reachable.insert(BB).second)
14765 continue;
14766
14767 Value *Cond;
14768 BasicBlock *TrueBB, *FalseBB;
14769 if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
14770 m_BasicBlock(FalseBB)))) {
14771 if (auto *C = dyn_cast<ConstantInt>(Cond)) {
14772 Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
14773 continue;
14774 }
14775
14776 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14777 const SCEV *L = getSCEV(Cmp->getOperand(0));
14778 const SCEV *R = getSCEV(Cmp->getOperand(1));
14779 if (isKnownPredicateViaConstantRanges(Cmp->getCmpPredicate(), L, R)) {
14780 Worklist.push_back(TrueBB);
14781 continue;
14782 }
14783 if (isKnownPredicateViaConstantRanges(Cmp->getInverseCmpPredicate(), L,
14784 R)) {
14785 Worklist.push_back(FalseBB);
14786 continue;
14787 }
14788 }
14789 }
14790
14791 append_range(Worklist, successors(BB));
14792 }
14793}
14794
14796 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14797 ScalarEvolution SE2(F, TLI, AC, DT, LI);
14798
14799 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
14800
14801 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
14802 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
14803 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
14804
14805 const SCEV *visitConstant(const SCEVConstant *Constant) {
14806 return SE.getConstant(Constant->getAPInt());
14807 }
14808
14809 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14810 return SE.getUnknown(Expr->getValue());
14811 }
14812
14813 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
14814 return SE.getCouldNotCompute();
14815 }
14816 };
14817
14818 SCEVMapper SCM(SE2);
14819 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
14820 SE2.getReachableBlocks(ReachableBlocks, F);
14821
14822 auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
14823 if (containsUndefs(Old) || containsUndefs(New)) {
14824 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
14825 // not propagate undef aggressively). This means we can (and do) fail
14826 // verification in cases where a transform makes a value go from "undef"
14827 // to "undef+1" (say). The transform is fine, since in both cases the
14828 // result is "undef", but SCEV thinks the value increased by 1.
14829 return nullptr;
14830 }
14831
14832 // Unless VerifySCEVStrict is set, we only compare constant deltas.
14833 const SCEV *Delta = SE2.getMinusSCEV(Old, New);
14834 if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
14835 return nullptr;
14836
14837 return Delta;
14838 };
14839
14840 while (!LoopStack.empty()) {
14841 auto *L = LoopStack.pop_back_val();
14842 llvm::append_range(LoopStack, *L);
14843
14844 // Only verify BECounts in reachable loops. For an unreachable loop,
14845 // any BECount is legal.
14846 if (!ReachableBlocks.contains(L->getHeader()))
14847 continue;
14848
14849 // Only verify cached BECounts. Computing new BECounts may change the
14850 // results of subsequent SCEV uses.
14851 auto It = BackedgeTakenCounts.find(L);
14852 if (It == BackedgeTakenCounts.end())
14853 continue;
14854
14855 auto *CurBECount =
14856 SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
14857 auto *NewBECount = SE2.getBackedgeTakenCount(L);
14858
14859 if (CurBECount == SE2.getCouldNotCompute() ||
14860 NewBECount == SE2.getCouldNotCompute()) {
14861 // NB! This situation is legal, but is very suspicious -- whatever pass
14862 // change the loop to make a trip count go from could not compute to
14863 // computable or vice-versa *should have* invalidated SCEV. However, we
14864 // choose not to assert here (for now) since we don't want false
14865 // positives.
14866 continue;
14867 }
14868
14869 if (SE.getTypeSizeInBits(CurBECount->getType()) >
14870 SE.getTypeSizeInBits(NewBECount->getType()))
14871 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
14872 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
14873 SE.getTypeSizeInBits(NewBECount->getType()))
14874 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
14875
14876 const SCEV *Delta = GetDelta(CurBECount, NewBECount);
14877 if (Delta && !Delta->isZero()) {
14878 dbgs() << "Trip Count for " << *L << " Changed!\n";
14879 dbgs() << "Old: " << *CurBECount << "\n";
14880 dbgs() << "New: " << *NewBECount << "\n";
14881 dbgs() << "Delta: " << *Delta << "\n";
14882 std::abort();
14883 }
14884 }
14885
14886 // Collect all valid loops currently in LoopInfo.
14887 SmallPtrSet<Loop *, 32> ValidLoops;
14888 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
14889 while (!Worklist.empty()) {
14890 Loop *L = Worklist.pop_back_val();
14891 if (ValidLoops.insert(L).second)
14892 Worklist.append(L->begin(), L->end());
14893 }
14894 for (const auto &KV : ValueExprMap) {
14895#ifndef NDEBUG
14896 // Check for SCEV expressions referencing invalid/deleted loops.
14897 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14898 assert(ValidLoops.contains(AR->getLoop()) &&
14899 "AddRec references invalid loop");
14900 }
14901#endif
14902
14903 // Check that the value is also part of the reverse map.
14904 auto It = ExprValueMap.find(KV.second);
14905 if (It == ExprValueMap.end() || !It->second.contains(KV.first)) {
14906 dbgs() << "Value " << *KV.first
14907 << " is in ValueExprMap but not in ExprValueMap\n";
14908 std::abort();
14909 }
14910
14911 if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
14912 if (!ReachableBlocks.contains(I->getParent()))
14913 continue;
14914 const SCEV *OldSCEV = SCM.visit(KV.second);
14915 const SCEV *NewSCEV = SE2.getSCEV(I);
14916 const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14917 if (Delta && !Delta->isZero()) {
14918 dbgs() << "SCEV for value " << *I << " changed!\n"
14919 << "Old: " << *OldSCEV << "\n"
14920 << "New: " << *NewSCEV << "\n"
14921 << "Delta: " << *Delta << "\n";
14922 std::abort();
14923 }
14924 }
14925 }
14926
14927 for (const auto &KV : ExprValueMap) {
14928 for (Value *V : KV.second) {
14929 const SCEV *S = ValueExprMap.lookup(V);
14930 if (!S) {
14931 dbgs() << "Value " << *V
14932 << " is in ExprValueMap but not in ValueExprMap\n";
14933 std::abort();
14934 }
14935 if (S != KV.first) {
14936 dbgs() << "Value " << *V << " mapped to " << *S << " rather than "
14937 << *KV.first << "\n";
14938 std::abort();
14939 }
14940 }
14941 }
14942
14943 // Verify integrity of SCEV users.
14944 for (const auto &S : UniqueSCEVs) {
14945 for (SCEVUse Op : S.operands()) {
14946 // We do not store dependencies of constants.
14947 if (isa<SCEVConstant>(Op))
14948 continue;
14949 auto It = SCEVUsers.find(Op);
14950 if (It != SCEVUsers.end() && It->second.count(&S))
14951 continue;
14952 dbgs() << "Use of operand " << *Op << " by user " << S
14953 << " is not being tracked!\n";
14954 std::abort();
14955 }
14956 }
14957
14958 // Verify integrity of ValuesAtScopes users.
14959 for (const auto &ValueAndVec : ValuesAtScopes) {
14960 const SCEV *Value = ValueAndVec.first;
14961 for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
14962 const Loop *L = LoopAndValueAtScope.first;
14963 SCEVUse ValueAtScope = LoopAndValueAtScope.second;
14964 if (!isa<SCEVConstant>(ValueAtScope)) {
14965 auto It = ValuesAtScopesUsers.find(ValueAtScope.getPointer());
14966 if (It != ValuesAtScopesUsers.end() &&
14967 is_contained(It->second, std::make_pair(L, Value)))
14968 continue;
14969 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14970 << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
14971 std::abort();
14972 }
14973 }
14974 }
14975
14976 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
14977 const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
14978 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
14979 const Loop *L = LoopAndValue.first;
14980 const SCEV *Value = LoopAndValue.second;
14982 auto It = ValuesAtScopes.find(Value);
14983 // The recorded value at scope may carry no-wrap flags that are not part
14984 // of the key it is recorded under.
14985 if (It != ValuesAtScopes.end() && any_of(It->second, [&](const auto &LS) {
14986 return LS.first == L && LS.second.getPointer() == ValueAtScope;
14987 }))
14988 continue;
14989 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14990 << *ValueAtScope << " missing in ValuesAtScopes\n";
14991 std::abort();
14992 }
14993 }
14994
14995 // Verify integrity of BECountUsers.
14996 auto VerifyBECountUsers = [&](bool Predicated) {
14997 auto &BECounts =
14998 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14999 for (const auto &LoopAndBEInfo : BECounts) {
15000 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
15001 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
15002 if (!isa<SCEVConstant>(S)) {
15003 auto UserIt = BECountUsers.find(S);
15004 if (UserIt != BECountUsers.end() &&
15005 UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
15006 continue;
15007 dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
15008 << " missing from BECountUsers\n";
15009 std::abort();
15010 }
15011 }
15012 }
15013 }
15014 };
15015 VerifyBECountUsers(/* Predicated */ false);
15016 VerifyBECountUsers(/* Predicated */ true);
15017
15018 // Verify intergity of loop disposition cache.
15019 for (auto &[S, Values] : LoopDispositions) {
15020 for (auto [Loop, CachedDisposition] : Values) {
15021 const auto RecomputedDisposition = SE2.getLoopDisposition(S, Loop);
15022 if (CachedDisposition != RecomputedDisposition) {
15023 dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
15024 << " is incorrect: cached " << CachedDisposition << ", actual "
15025 << RecomputedDisposition << "\n";
15026 std::abort();
15027 }
15028 }
15029 }
15030
15031 // Verify integrity of the block disposition cache.
15032 for (auto &[S, Values] : BlockDispositions) {
15033 for (auto [BB, CachedDisposition] : Values) {
15034 const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
15035 if (CachedDisposition != RecomputedDisposition) {
15036 dbgs() << "Cached disposition of " << *S << " for block %"
15037 << BB->getName() << " is incorrect: cached " << CachedDisposition
15038 << ", actual " << RecomputedDisposition << "\n";
15039 std::abort();
15040 }
15041 }
15042 }
15043
15044 // Verify FoldCache/FoldCacheUser caches.
15045 for (auto [FoldID, Expr] : FoldCache) {
15046 auto I = FoldCacheUser.find(Expr);
15047 if (I == FoldCacheUser.end()) {
15048 dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
15049 << "!\n";
15050 std::abort();
15051 }
15052 if (!is_contained(I->second, FoldID)) {
15053 dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
15054 std::abort();
15055 }
15056 }
15057 for (auto [Expr, IDs] : FoldCacheUser) {
15058 for (auto &FoldID : IDs) {
15059 const SCEV *S = FoldCache.lookup(FoldID);
15060 if (!S) {
15061 dbgs() << "Missing entry in FoldCache for expression " << *Expr
15062 << "!\n";
15063 std::abort();
15064 }
15065 if (S != Expr) {
15066 dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: " << *S
15067 << " != " << *Expr << "!\n";
15068 std::abort();
15069 }
15070 }
15071 }
15072
15073 // Verify that ConstantMultipleCache computations are correct. We check that
15074 // cached multiples and recomputed multiples are multiples of each other to
15075 // verify correctness. It is possible that a recomputed multiple is different
15076 // from the cached multiple due to strengthened no wrap flags or changes in
15077 // KnownBits computations.
15078 for (auto [S, Multiple] : ConstantMultipleCache) {
15079 APInt RecomputedMultiple = SE2.getConstantMultiple(S);
15080 if ((Multiple != 0 && RecomputedMultiple != 0 &&
15081 Multiple.urem(RecomputedMultiple) != 0 &&
15082 RecomputedMultiple.urem(Multiple) != 0)) {
15083 dbgs() << "Incorrect cached computation in ConstantMultipleCache for "
15084 << *S << " : Computed " << RecomputedMultiple
15085 << " but cache contains " << Multiple << "!\n";
15086 std::abort();
15087 }
15088 }
15089}
15090
15092 Function &F, const PreservedAnalyses &PA,
15093 FunctionAnalysisManager::Invalidator &Inv) {
15094 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
15095 // of its dependencies is invalidated.
15096 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
15097 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
15098 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
15099 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
15100 Inv.invalidate<LoopAnalysis>(F, PA);
15101}
15102
15103AnalysisKey ScalarEvolutionAnalysis::Key;
15104
15107 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
15108 auto &AC = AM.getResult<AssumptionAnalysis>(F);
15109 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
15110 auto &LI = AM.getResult<LoopAnalysis>(F);
15111 return ScalarEvolution(F, TLI, AC, DT, LI);
15112}
15113
15119
15122 // For compatibility with opt's -analyze feature under legacy pass manager
15123 // which was not ported to NPM. This keeps tests using
15124 // update_analyze_test_checks.py working.
15125 OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
15126 << F.getName() << "':\n";
15128 return PreservedAnalyses::all();
15129}
15130
15132 "Scalar Evolution Analysis", false, true)
15138 "Scalar Evolution Analysis", false, true)
15139
15140char ScalarEvolutionWrapperPass::ID = 0;
15141
15143
15145 SE.reset(new ScalarEvolution(
15147 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
15149 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
15150 return false;
15151}
15152
15154
15156 SE->print(OS);
15157}
15158
15160 if (!VerifySCEV)
15161 return;
15162
15163 SE->verify();
15164}
15165
15173
15175 const SCEV *RHS) {
15176 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
15177}
15178
15179const SCEVPredicate *
15181 const SCEV *LHS, const SCEV *RHS) {
15183 assert(LHS->getType() == RHS->getType() &&
15184 "Type mismatch between LHS and RHS");
15185 // Unique this node based on the arguments
15186 ID.AddInteger(SCEVPredicate::P_Compare);
15187 ID.AddInteger(Pred);
15188 ID.AddPointer(LHS);
15189 ID.AddPointer(RHS);
15191 if (const auto *S = UniquePreds.lookup(ID, Token))
15192 return S;
15193 SCEVComparePredicate *Eq = new (SCEVAllocator)
15194 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
15195 UniquePreds.insert(Eq, Token);
15196 return Eq;
15197}
15198
15200 const SCEVAddRecExpr *AR,
15203 // Unique this node based on the arguments
15205 ID.AddPointer(AR);
15206 ID.AddInteger(AddedFlags);
15208 if (const auto *S = UniquePreds.lookup(ID, Token))
15209 return S;
15210 auto *OF = new (SCEVAllocator)
15211 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
15212 UniquePreds.insert(OF, Token);
15213 return OF;
15214}
15215
15216namespace {
15217
15218class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
15219public:
15220
15221 /// Rewrites \p S in the context of a loop L and the SCEV predication
15222 /// infrastructure.
15223 ///
15224 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
15225 /// equivalences present in \p Pred.
15226 ///
15227 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
15228 /// \p NewPreds such that the result will be an AddRecExpr.
15229 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
15231 const SCEVPredicate *Pred) {
15232 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
15233 return Rewriter.visit(S);
15234 }
15235
15236 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
15237 if (Pred) {
15238 if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
15239 for (const auto *Pred : U->getPredicates())
15240 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
15241 if (IPred->getLHS() == Expr &&
15242 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15243 return IPred->getRHS();
15244 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
15245 if (IPred->getLHS() == Expr &&
15246 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15247 return IPred->getRHS();
15248 }
15249 }
15250 return convertToAddRecWithPreds(Expr);
15251 }
15252
15253 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
15254 const SCEV *Operand = visit(Expr->getOperand());
15255 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15256 if (AR && AR->getLoop() == L && AR->isAffine()) {
15257 // This couldn't be folded because the operand didn't have the nuw
15258 // flag. Add the nusw flag as an assumption that we could make.
15259 const SCEV *Step = AR->getStepRecurrence(SE);
15260 Type *Ty = Expr->getType();
15261 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
15262 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
15263 SE.getSignExtendExpr(Step, Ty), L,
15264 AR->getNoWrapFlags());
15265 }
15266 return SE.getZeroExtendExpr(Operand, Expr->getType());
15267 }
15268
15269 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
15270 const SCEV *Operand = visit(Expr->getOperand());
15271 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15272 if (AR && AR->getLoop() == L && AR->isAffine()) {
15273 // This couldn't be folded because the operand didn't have the nsw
15274 // flag. Add the nssw flag as an assumption that we could make.
15275 const SCEV *Step = AR->getStepRecurrence(SE);
15276 Type *Ty = Expr->getType();
15277 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
15278 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
15279 SE.getSignExtendExpr(Step, Ty), L,
15280 AR->getNoWrapFlags());
15281 }
15282 return SE.getSignExtendExpr(Operand, Expr->getType());
15283 }
15284
15285private:
15286 explicit SCEVPredicateRewriter(
15287 const Loop *L, ScalarEvolution &SE,
15288 SmallVectorImpl<const SCEVPredicate *> *NewPreds,
15289 const SCEVPredicate *Pred)
15290 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
15291
15292 bool addOverflowAssumption(const SCEVPredicate *P) {
15293 if (!NewPreds) {
15294 // Check if we've already made this assumption.
15295 return Pred && Pred->implies(P, SE);
15296 }
15297 NewPreds->push_back(P);
15298 return true;
15299 }
15300
15301 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
15303 auto *A = SE.getWrapPredicate(AR, AddedFlags);
15304 return addOverflowAssumption(A);
15305 }
15306
15307 // If \p Expr represents a PHINode, we try to see if it can be represented
15308 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
15309 // to add this predicate as a runtime overflow check, we return the AddRec.
15310 // If \p Expr does not meet these conditions (is not a PHI node, or we
15311 // couldn't create an AddRec for it, or couldn't add the predicate), we just
15312 // return \p Expr.
15313 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
15314 if (!isa<PHINode>(Expr->getValue()))
15315 return Expr;
15316 std::optional<
15317 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
15318 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
15319 if (!PredicatedRewrite)
15320 return Expr;
15321 for (const auto *P : PredicatedRewrite->second){
15322 // Wrap predicates from outer loops are not supported.
15323 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
15324 if (L != WP->getExpr()->getLoop())
15325 return Expr;
15326 }
15327 if (!addOverflowAssumption(P))
15328 return Expr;
15329 }
15330 return PredicatedRewrite->first;
15331 }
15332
15333 SmallVectorImpl<const SCEVPredicate *> *NewPreds;
15334 const SCEVPredicate *Pred;
15335 const Loop *L;
15336};
15337
15338} // end anonymous namespace
15339
15340const SCEV *
15342 const SCEVPredicate &Preds) {
15343 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
15344}
15345
15347 const SCEV *S, const Loop *L,
15350 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
15351 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
15352
15353 if (!AddRec)
15354 return nullptr;
15355
15356 // Check if any of the transformed predicates is known to be false. In that
15357 // case, it doesn't make sense to convert to a predicated AddRec, as the
15358 // versioned loop will never execute.
15359 for (const SCEVPredicate *Pred : TransformPreds) {
15360 auto *WrapPred = dyn_cast<SCEVWrapPredicate>(Pred);
15361 if (!WrapPred || WrapPred->getFlags() != SCEVWrapPredicate::IncrementNSSW)
15362 continue;
15363
15364 const SCEVAddRecExpr *AddRecToCheck = WrapPred->getExpr();
15365 const SCEV *ExitCount = getBackedgeTakenCount(AddRecToCheck->getLoop());
15366 if (isa<SCEVCouldNotCompute>(ExitCount))
15367 continue;
15368
15369 const SCEV *Step = AddRecToCheck->getStepRecurrence(*this);
15370 if (!Step->isOne())
15371 continue;
15372
15373 ExitCount = getTruncateOrSignExtend(ExitCount, Step->getType());
15374 const SCEV *Add = getAddExpr(AddRecToCheck->getStart(), ExitCount);
15375 if (isKnownPredicate(CmpInst::ICMP_SLT, Add, AddRecToCheck->getStart()))
15376 return nullptr;
15377 }
15378
15379 // Since the transformation was successful, we can now transfer the SCEV
15380 // predicates.
15381 Preds.append(TransformPreds.begin(), TransformPreds.end());
15382
15383 return AddRec;
15384}
15385
15386/// SCEV predicates
15390
15392 const ICmpInst::Predicate Pred,
15393 const SCEV *LHS, const SCEV *RHS)
15394 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
15395 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
15396 assert(LHS != RHS && "LHS and RHS are the same SCEV");
15397}
15398
15400 ScalarEvolution &SE) const {
15401 const auto *Op = dyn_cast<SCEVComparePredicate>(N);
15402
15403 if (!Op)
15404 return false;
15405
15406 if (Pred != ICmpInst::ICMP_EQ)
15407 return false;
15408
15409 return Op->LHS == LHS && Op->RHS == RHS;
15410}
15411
15412bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
15413
15415 if (Pred == ICmpInst::ICMP_EQ)
15416 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
15417 else
15418 OS.indent(Depth) << "Compare predicate: " << *LHS << " " << Pred << ") "
15419 << *RHS << "\n";
15420
15421}
15422
15424 const SCEVAddRecExpr *AR,
15425 IncrementWrapFlags Flags)
15426 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
15427
15428const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
15429
15431 ScalarEvolution &SE) const {
15432 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
15433 if (!Op || setFlags(Flags, Op->Flags) != Flags)
15434 return false;
15435
15436 if (Op->AR == AR)
15437 return true;
15438
15439 if (Flags != SCEVWrapPredicate::IncrementNSSW &&
15441 return false;
15442
15443 const SCEV *Start = AR->getStart();
15444 const SCEV *OpStart = Op->AR->getStart();
15445 if (Start->getType()->isPointerTy() != OpStart->getType()->isPointerTy())
15446 return false;
15447
15448 // Reject pointers to different address spaces.
15449 if (Start->getType()->isPointerTy() && Start->getType() != OpStart->getType())
15450 return false;
15451
15452 // NUSW/NSSW on a wider-type AddRec does not imply the same on a
15453 // narrower-type AddRec.
15454 if (SE.getTypeSizeInBits(AR->getType()) >
15455 SE.getTypeSizeInBits(Op->AR->getType()))
15456 return false;
15457
15458 const SCEV *Step = AR->getStepRecurrence(SE);
15459 const SCEV *OpStep = Op->AR->getStepRecurrence(SE);
15460 if (!SE.isKnownPositive(Step) || !SE.isKnownPositive(OpStep))
15461 return false;
15462
15463 // If both steps are positive, this implies N, if N's start and step are
15464 // ULE/SLE (for NSUW/NSSW) than this'.
15465 Type *WiderTy = SE.getWiderType(Step->getType(), OpStep->getType());
15466 Step = SE.getNoopOrZeroExtend(Step, WiderTy);
15467 OpStep = SE.getNoopOrZeroExtend(OpStep, WiderTy);
15468
15469 bool IsNUW = Flags == SCEVWrapPredicate::IncrementNUSW;
15470 OpStart = IsNUW ? SE.getNoopOrZeroExtend(OpStart, WiderTy)
15471 : SE.getNoopOrSignExtend(OpStart, WiderTy);
15472 Start = IsNUW ? SE.getNoopOrZeroExtend(Start, WiderTy)
15473 : SE.getNoopOrSignExtend(Start, WiderTy);
15475 return SE.isKnownPredicate(Pred, OpStep, Step) &&
15476 SE.isKnownPredicate(Pred, OpStart, Start);
15477}
15478
15480 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
15481 IncrementWrapFlags IFlags = Flags;
15482
15483 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
15484 IFlags = clearFlags(IFlags, IncrementNSSW);
15485
15486 return IFlags == IncrementAnyWrap;
15487}
15488
15489void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
15490 OS.indent(Depth) << *getExpr() << " Added Flags: ";
15492 OS << "<nusw>";
15494 OS << "<nssw>";
15495 OS << "\n";
15496}
15497
15500 ScalarEvolution &SE) {
15501 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
15502 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
15503
15504 // We can safely transfer the NSW flag as NSSW.
15505 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
15506 ImpliedFlags = IncrementNSSW;
15507
15508 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
15509 // If the increment is positive, the SCEV NUW flag will also imply the
15510 // WrapPredicate NUSW flag.
15511 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
15512 if (Step->getValue()->getValue().isNonNegative())
15513 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
15514 }
15515
15516 return ImpliedFlags;
15517}
15518
15519/// Union predicates don't get cached so create a dummy set ID for it.
15521 ScalarEvolution &SE)
15523 for (const auto *P : Preds)
15524 add(P, SE);
15525}
15526
15528 return all_of(Preds,
15529 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
15530}
15531
15533 ScalarEvolution &SE) const {
15534 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
15535 return all_of(Set->Preds, [this, &SE](const SCEVPredicate *I) {
15536 return this->implies(I, SE);
15537 });
15538
15539 if (any_of(Preds,
15540 [N, &SE](const SCEVPredicate *I) { return I->implies(N, SE); }))
15541 return true;
15542
15543 // A wrap predicate may be implied by a wrap predicate in Preds after applying
15544 // equal predicates.
15545 const auto *NWrap = dyn_cast<SCEVWrapPredicate>(N);
15546 if (!NWrap)
15547 return false;
15548 const Loop *L = NWrap->getExpr()->getLoop();
15549 return any_of(Preds, [&](const SCEVPredicate *I) {
15550 const auto *IWrap = dyn_cast<SCEVWrapPredicate>(I);
15551 if (!IWrap)
15552 return false;
15553 const auto *RewrittenAR = dyn_cast<SCEVAddRecExpr>(
15554 SE.rewriteUsingPredicate(IWrap->getExpr(), L, *this));
15555 return RewrittenAR &&
15556 SE.getWrapPredicate(RewrittenAR, IWrap->getFlags())->implies(N, SE);
15557 });
15558}
15559
15561 for (const auto *Pred : Preds)
15562 Pred->print(OS, Depth);
15563}
15564
15565void SCEVUnionPredicate::add(const SCEVPredicate *N, ScalarEvolution &SE) {
15566 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
15567 for (const auto *Pred : Set->Preds)
15568 add(Pred, SE);
15569 return;
15570 }
15571
15572 // Implication checks are quadratic in the number of predicates. Stop doing
15573 // them if there are many predicates, as they should be too expensive to use
15574 // anyway at that point.
15575 bool CheckImplies = Preds.size() < 16;
15576
15577 // Only add predicate if it is not already implied by this union predicate.
15578 if (CheckImplies && implies(N, SE))
15579 return;
15580
15581 // Build a new vector containing the current predicates, except the ones that
15582 // are implied by the new predicate N.
15584 for (auto *P : Preds) {
15585 if (CheckImplies && N->implies(P, SE))
15586 continue;
15587 PrunedPreds.push_back(P);
15588 }
15589 Preds = std::move(PrunedPreds);
15590 Preds.push_back(N);
15591}
15592
15594 Loop &L)
15595 : SE(SE), L(L) {
15597 Preds = std::make_unique<SCEVUnionPredicate>(Empty, SE);
15598}
15599
15601 for (const SCEV *Op : Ops)
15602 // We do not expect that forgetting cached data for SCEVConstants will ever
15603 // open any prospects for sharpening or introduce any correctness issues,
15604 // so we don't bother storing their dependencies.
15605 if (!isa<SCEVConstant>(Op))
15606 SCEVUsers[Op].insert(User);
15607}
15608
15610 const SCEV *Expr = SE.getSCEV(V);
15611 return getPredicatedSCEV(Expr);
15612}
15613
15615 RewriteEntry &Entry = RewriteMap[Expr];
15616
15617 // If we already have an entry and the version matches, return it.
15618 if (Entry.second && Generation == Entry.first)
15619 return Entry.second;
15620
15621 // We found an entry but it's stale. Rewrite the stale entry
15622 // according to the current predicate.
15623 if (Entry.second)
15624 Expr = Entry.second;
15625
15626 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
15627 Entry = {Generation, NewSCEV};
15628
15629 return NewSCEV;
15630}
15631
15633 if (!BackedgeCount) {
15635 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
15636 for (const auto *P : Preds)
15637 addPredicate(*P);
15638 }
15639 return BackedgeCount;
15640}
15641
15643 if (!SymbolicMaxBackedgeCount) {
15645 SymbolicMaxBackedgeCount =
15646 SE.getPredicatedSymbolicMaxBackedgeTakenCount(&L, Preds);
15647 for (const auto *P : Preds)
15648 addPredicate(*P);
15649 }
15650 return SymbolicMaxBackedgeCount;
15651}
15652
15654 if (!SmallConstantMaxTripCount) {
15656 SmallConstantMaxTripCount = SE.getSmallConstantMaxTripCount(&L, &Preds);
15657 for (const auto *P : Preds)
15658 addPredicate(*P);
15659 }
15660 return *SmallConstantMaxTripCount;
15661}
15662
15664 if (Preds->implies(&Pred, SE))
15665 return;
15666
15667 SmallVector<const SCEVPredicate *, 4> NewPreds(Preds->getPredicates());
15668 NewPreds.push_back(&Pred);
15669 Preds = std::make_unique<SCEVUnionPredicate>(NewPreds, SE);
15670 updateGeneration();
15671}
15672
15675 for (const SCEVPredicate *P : Preds)
15676 addPredicate(*P);
15677}
15678
15680 return *Preds;
15681}
15682
15683void PredicatedScalarEvolution::updateGeneration() {
15684 // If the generation number wrapped recompute everything.
15685 if (++Generation == 0) {
15686 for (auto &II : RewriteMap) {
15687 const SCEV *Rewritten = II.second.second;
15688 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
15689 }
15690 }
15691}
15692
15695 const auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V));
15696 if (!AR)
15697 return false;
15698
15700 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
15701
15703}
15704
15707 const SCEV *Expr = this->getSCEV(V);
15709 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
15710
15711 if (!New)
15712 return nullptr;
15713
15714 if (ExtraPreds) {
15715 ExtraPreds->append(NewPreds);
15716 return New;
15717 }
15718
15719 addPredicates(NewPreds);
15720
15721 RewriteMap[SE.getSCEV(V)] = {Generation, New};
15722 return New;
15723}
15724
15727 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
15728 Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates(),
15729 SE)),
15730 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {}
15731
15733 // For each block.
15734 for (auto *BB : L.getBlocks())
15735 for (auto &I : *BB) {
15736 if (!SE.isSCEVable(I.getType()))
15737 continue;
15738
15739 auto *Expr = SE.getSCEV(&I);
15740 auto II = RewriteMap.find(Expr);
15741
15742 if (II == RewriteMap.end())
15743 continue;
15744
15745 // Don't print things that are not interesting.
15746 if (II->second.second == Expr)
15747 continue;
15748
15749 OS.indent(Depth) << "[PSE]" << I << ":\n";
15750 OS.indent(Depth + 2) << *Expr << "\n";
15751 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
15752 }
15753}
15754
15757 BasicBlock *Header = L->getHeader();
15758 BasicBlock *Pred = L->getLoopPredecessor();
15759 LoopGuards Guards(SE);
15760 if (!Pred)
15761 return Guards;
15763 collectFromBlock(SE, Guards, Header, Pred, VisitedBlocks);
15764 return Guards;
15765}
15766
15767void ScalarEvolution::LoopGuards::collectFromPHI(
15771 unsigned Depth) {
15772 if (!SE.isSCEVable(Phi.getType()))
15773 return;
15774
15775 using MinMaxPattern = std::pair<const SCEVConstant *, SCEVTypes>;
15776 auto GetMinMaxConst = [&](unsigned IncomingIdx) -> MinMaxPattern {
15777 const BasicBlock *InBlock = Phi.getIncomingBlock(IncomingIdx);
15778 if (!VisitedBlocks.insert(InBlock).second)
15779 return {nullptr, scCouldNotCompute};
15780
15781 // Avoid analyzing unreachable blocks so that we don't get trapped
15782 // traversing cycles with ill-formed dominance or infinite cycles
15783 if (!SE.DT.isReachableFromEntry(InBlock))
15784 return {nullptr, scCouldNotCompute};
15785
15786 auto [G, Inserted] = IncomingGuards.try_emplace(InBlock, LoopGuards(SE));
15787 if (Inserted)
15788 collectFromBlock(SE, G->second, Phi.getParent(), InBlock, VisitedBlocks,
15789 Depth + 1);
15790 auto &RewriteMap = G->second.RewriteMap;
15791 if (RewriteMap.empty())
15792 return {nullptr, scCouldNotCompute};
15793 auto S = RewriteMap.find(SE.getSCEV(Phi.getIncomingValue(IncomingIdx)));
15794 if (S == RewriteMap.end())
15795 return {nullptr, scCouldNotCompute};
15796 auto *SM = dyn_cast_if_present<SCEVMinMaxExpr>(S->second);
15797 if (!SM)
15798 return {nullptr, scCouldNotCompute};
15799 if (const SCEVConstant *C0 = dyn_cast<SCEVConstant>(SM->getOperand(0)))
15800 return {C0, SM->getSCEVType()};
15801 return {nullptr, scCouldNotCompute};
15802 };
15803 auto MergeMinMaxConst = [](MinMaxPattern P1,
15804 MinMaxPattern P2) -> MinMaxPattern {
15805 auto [C1, T1] = P1;
15806 auto [C2, T2] = P2;
15807 if (!C1 || !C2 || T1 != T2)
15808 return {nullptr, scCouldNotCompute};
15809 switch (T1) {
15810 case scUMaxExpr:
15811 return {C1->getAPInt().ult(C2->getAPInt()) ? C1 : C2, T1};
15812 case scSMaxExpr:
15813 return {C1->getAPInt().slt(C2->getAPInt()) ? C1 : C2, T1};
15814 case scUMinExpr:
15815 return {C1->getAPInt().ugt(C2->getAPInt()) ? C1 : C2, T1};
15816 case scSMinExpr:
15817 return {C1->getAPInt().sgt(C2->getAPInt()) ? C1 : C2, T1};
15818 default:
15819 llvm_unreachable("Trying to merge non-MinMaxExpr SCEVs.");
15820 }
15821 };
15822 auto P = GetMinMaxConst(0);
15823 for (unsigned int In = 1; In < Phi.getNumIncomingValues(); In++) {
15824 if (!P.first)
15825 break;
15826 P = MergeMinMaxConst(P, GetMinMaxConst(In));
15827 }
15828 if (P.first) {
15829 const SCEV *LHS = SE.getSCEV(const_cast<PHINode *>(&Phi));
15830 SmallVector<SCEVUse, 2> Ops({P.first, LHS});
15831 const SCEV *RHS = SE.getMinMaxExpr(P.second, Ops);
15832 Guards.RewriteMap.insert({LHS, RHS});
15833 }
15834}
15835
15836// Return a new SCEV that modifies \p Expr to the closest number divides by
15837// \p Divisor and less or equal than Expr. For now, only handle constant
15838// Expr.
15840 const APInt &DivisorVal,
15841 ScalarEvolution &SE) {
15842 const APInt *ExprVal;
15843 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15844 DivisorVal.isNonPositive())
15845 return Expr;
15846 APInt Rem = ExprVal->urem(DivisorVal);
15847 // return the SCEV: Expr - Expr % Divisor
15848 return SE.getConstant(*ExprVal - Rem);
15849}
15850
15851// Return a new SCEV that modifies \p Expr to the closest number divides by
15852// \p Divisor and greater or equal than Expr. For now, only handle constant
15853// Expr.
15854static const SCEV *getNextSCEVDivisibleByDivisor(const SCEV *Expr,
15855 const APInt &DivisorVal,
15856 ScalarEvolution &SE) {
15857 const APInt *ExprVal;
15858 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15859 DivisorVal.isNonPositive())
15860 return Expr;
15861 APInt Rem = ExprVal->urem(DivisorVal);
15862 if (Rem.isZero())
15863 return Expr;
15864 // return the SCEV: Expr + Divisor - Expr % Divisor
15865 return SE.getConstant(*ExprVal + DivisorVal - Rem);
15866}
15867
15869 ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS,
15872 // If we have LHS == 0, check if LHS is computing a property of some unknown
15873 // SCEV %v which we can rewrite %v to express explicitly.
15875 return false;
15876 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
15877 // explicitly express that.
15878 const SCEVUnknown *URemLHS = nullptr;
15879 const SCEV *URemRHS = nullptr;
15880 if (!match(LHS, m_scev_URem(m_SCEVUnknown(URemLHS), m_SCEV(URemRHS), SE)))
15881 return false;
15882
15883 const SCEV *Multiple =
15884 SE.getMulExpr(SE.getUDivExpr(URemLHS, URemRHS), URemRHS);
15885 DivInfo[URemLHS] = Multiple;
15886 if (auto *C = dyn_cast<SCEVConstant>(URemRHS))
15887 Multiples[URemLHS] = C->getAPInt();
15888 return true;
15889}
15890
15891// Check if the condition is a divisibility guard (A % B == 0).
15892static bool isDivisibilityGuard(const SCEV *LHS, const SCEV *RHS,
15893 ScalarEvolution &SE) {
15894 const SCEV *X, *Y;
15895 return match(LHS, m_scev_URem(m_SCEV(X), m_SCEV(Y), SE)) && RHS->isZero();
15896}
15897
15898// Apply divisibility by \p Divisor on MinMaxExpr with constant values,
15899// recursively. This is done by aligning up/down the constant value to the
15900// Divisor.
15901static const SCEV *applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr,
15902 APInt Divisor,
15903 ScalarEvolution &SE) {
15904 // Return true if \p Expr is a MinMax SCEV expression with a non-negative
15905 // constant operand. If so, return in \p SCTy the SCEV type and in \p RHS
15906 // the non-constant operand and in \p LHS the constant operand.
15907 auto IsMinMaxSCEVWithNonNegativeConstant =
15908 [&](const SCEV *Expr, SCEVTypes &SCTy, const SCEV *&LHS,
15909 const SCEV *&RHS) {
15910 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr)) {
15911 if (MinMax->getNumOperands() != 2)
15912 return false;
15913 if (auto *C = dyn_cast<SCEVConstant>(MinMax->getOperand(0))) {
15914 if (C->getAPInt().isNegative())
15915 return false;
15916 SCTy = MinMax->getSCEVType();
15917 LHS = MinMax->getOperand(0);
15918 RHS = MinMax->getOperand(1);
15919 return true;
15920 }
15921 }
15922 return false;
15923 };
15924
15925 const SCEV *MinMaxLHS = nullptr, *MinMaxRHS = nullptr;
15926 SCEVTypes SCTy;
15927 if (!IsMinMaxSCEVWithNonNegativeConstant(MinMaxExpr, SCTy, MinMaxLHS,
15928 MinMaxRHS))
15929 return MinMaxExpr;
15930 auto IsMin = isa<SCEVSMinExpr>(MinMaxExpr) || isa<SCEVUMinExpr>(MinMaxExpr);
15931 assert(SE.isKnownNonNegative(MinMaxLHS) && "Expected non-negative operand!");
15932 auto *DivisibleExpr =
15933 IsMin ? getPreviousSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE)
15934 : getNextSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE);
15936 applyDivisibilityOnMinMaxExpr(MinMaxRHS, Divisor, SE), DivisibleExpr};
15937 return SE.getMinMaxExpr(SCTy, Ops);
15938}
15939
15940void ScalarEvolution::LoopGuards::collectFromBlock(
15941 ScalarEvolution &SE, ScalarEvolution::LoopGuards &Guards,
15942 const BasicBlock *Block, const BasicBlock *Pred,
15943 SmallPtrSetImpl<const BasicBlock *> &VisitedBlocks, unsigned Depth) {
15944
15946
15947 SmallVector<SCEVUse> ExprsToRewrite;
15948 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
15949 const SCEV *RHS,
15950 DenseMap<const SCEV *, const SCEV *> &RewriteMap,
15951 const LoopGuards &DivGuards) {
15952 // WARNING: It is generally unsound to apply any wrap flags to the proposed
15953 // replacement SCEV which isn't directly implied by the structure of that
15954 // SCEV. In particular, using contextual facts to imply flags is *NOT*
15955 // legal. See the scoping rules for flags in the header to understand why.
15956
15957 // Puts rewrite rule \p From -> \p To into the rewrite map. Also if \p From
15958 // and \p FromRewritten are the same (i.e. there has been no rewrite
15959 // registered for \p From), then puts this value in the list of rewritten
15960 // expressions.
15961 auto AddRewrite = [&](const SCEV *From, const SCEV *FromRewritten,
15962 const SCEV *To) {
15963 if (From == FromRewritten)
15964 ExprsToRewrite.push_back(From);
15965 RewriteMap[From] = To;
15966 };
15967
15968 // Checks whether \p S has already been rewritten. In that case returns the
15969 // existing rewrite because we want to chain further rewrites onto the
15970 // already rewritten value. Otherwise returns \p S.
15971 auto GetMaybeRewritten = [&](const SCEV *S) {
15972 return RewriteMap.lookup_or(S, S);
15973 };
15974
15975 // Check for a condition of the form (-C1 + X < C2). InstCombine will
15976 // create this form when combining two checks of the form (X u< C2 + C1) and
15977 // (X >=u C1).
15978 auto MatchRangeCheckIdiom = [&](ICmpInst::Predicate Pred,
15979 const SCEV *MatchLHS,
15980 const SCEV *MatchRHS) {
15981 const SCEVConstant *C1;
15982 const SCEVUnknown *LHSUnknown;
15983 auto *C2 = dyn_cast<SCEVConstant>(MatchRHS);
15984 if (!match(MatchLHS,
15985 m_scev_Add(m_SCEVConstant(C1), m_SCEVUnknown(LHSUnknown))) ||
15986 !C2)
15987 return false;
15988
15989 auto ExactRegion =
15990 ConstantRange::makeExactICmpRegion(Pred, C2->getAPInt())
15991 .sub(C1->getAPInt());
15992
15993 // Tighten the raw range with what we already know about LHSUnknown
15994 // from prior guards recorded in RewriteMap, or from SCEV's own range
15995 // analysis.
15996 const SCEV *RewrittenLHS = GetMaybeRewritten(LHSUnknown);
15997 ExactRegion = ExactRegion.intersectWith(SE.getUnsignedRange(RewrittenLHS),
15999
16000 // Bail if the guard is inconsistent with prior facts, or if the range
16001 // is still not a monotonic non-wrapping interval after tightening.
16002 if (ExactRegion.isEmptySet() || ExactRegion.isWrappedSet() ||
16003 ExactRegion.isFullSet())
16004 return false;
16005
16006 const SCEV *RegionMin = SE.getConstant(ExactRegion.getUnsignedMin());
16007 const SCEV *RegionMax = SE.getConstant(ExactRegion.getUnsignedMax());
16008 const SCEV *ClampedLHS =
16009 SE.getUMaxExpr(RegionMin, SE.getUMinExpr(RewrittenLHS, RegionMax));
16010 AddRewrite(LHSUnknown, RewrittenLHS, ClampedLHS);
16011 return true;
16012 };
16013 if (MatchRangeCheckIdiom(Predicate, LHS, RHS))
16014 return;
16015
16016 // Do not apply information for constants or if RHS contains an AddRec.
16018 return;
16019
16020 // If RHS is SCEVUnknown, make sure the information is applied to it.
16022 std::swap(LHS, RHS);
16024 }
16025
16026 const SCEV *RewrittenLHS = GetMaybeRewritten(LHS);
16027 // Apply divisibility information when computing the constant multiple.
16028 const APInt &DividesBy =
16029 SE.getConstantMultiple(DivGuards.rewrite(RewrittenLHS));
16030
16031 // Collect rewrites for LHS and its transitive operands based on the
16032 // condition.
16033 // For min/max expressions, also apply the guard to its operands:
16034 // 'min(a, b) >= c' -> '(a >= c) and (b >= c)',
16035 // 'min(a, b) > c' -> '(a > c) and (b > c)',
16036 // 'max(a, b) <= c' -> '(a <= c) and (b <= c)',
16037 // 'max(a, b) < c' -> '(a < c) and (b < c)'.
16038
16039 // We cannot express strict predicates in SCEV, so instead we replace them
16040 // with non-strict ones against plus or minus one of RHS depending on the
16041 // predicate.
16042 const SCEV *One = SE.getOne(RHS->getType());
16043 switch (Predicate) {
16044 case CmpInst::ICMP_ULT:
16045 if (RHS->getType()->isPointerTy())
16046 return;
16047 RHS = SE.getUMaxExpr(RHS, One);
16048 [[fallthrough]];
16049 case CmpInst::ICMP_SLT: {
16050 RHS = SE.getMinusSCEV(RHS, One);
16051 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16052 break;
16053 }
16054 case CmpInst::ICMP_UGT:
16055 case CmpInst::ICMP_SGT:
16056 RHS = SE.getAddExpr(RHS, One);
16057 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16058 break;
16059 case CmpInst::ICMP_ULE:
16060 case CmpInst::ICMP_SLE:
16061 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16062 break;
16063 case CmpInst::ICMP_UGE:
16064 case CmpInst::ICMP_SGE:
16065 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16066 break;
16067 default:
16068 break;
16069 }
16070
16071 SmallVector<SCEVUse, 16> Worklist(1, LHS);
16072 SmallPtrSet<const SCEV *, 16> Visited;
16073
16074 auto EnqueueOperands = [&Worklist](const SCEVNAryExpr *S) {
16075 append_range(Worklist, S->operands());
16076 };
16077
16078 while (!Worklist.empty()) {
16079 const SCEV *From = Worklist.pop_back_val();
16080 if (isa<SCEVConstant>(From))
16081 continue;
16082 if (!Visited.insert(From).second)
16083 continue;
16084 const SCEV *FromRewritten = GetMaybeRewritten(From);
16085 const SCEV *To = nullptr;
16086
16087 switch (Predicate) {
16088 case CmpInst::ICMP_ULT:
16089 case CmpInst::ICMP_ULE:
16090 To = SE.getUMinExpr(FromRewritten, RHS);
16091 if (auto *UMax = dyn_cast<SCEVUMaxExpr>(FromRewritten))
16092 EnqueueOperands(UMax);
16093 break;
16094 case CmpInst::ICMP_SLT:
16095 case CmpInst::ICMP_SLE:
16096 To = SE.getSMinExpr(FromRewritten, RHS);
16097 if (auto *SMax = dyn_cast<SCEVSMaxExpr>(FromRewritten))
16098 EnqueueOperands(SMax);
16099 break;
16100 case CmpInst::ICMP_UGT:
16101 case CmpInst::ICMP_UGE:
16102 To = SE.getUMaxExpr(FromRewritten, RHS);
16103 if (auto *UMin = dyn_cast<SCEVUMinExpr>(FromRewritten))
16104 EnqueueOperands(UMin);
16105 break;
16106 case CmpInst::ICMP_SGT:
16107 case CmpInst::ICMP_SGE:
16108 To = SE.getSMaxExpr(FromRewritten, RHS);
16109 if (auto *SMin = dyn_cast<SCEVSMinExpr>(FromRewritten))
16110 EnqueueOperands(SMin);
16111 break;
16112 case CmpInst::ICMP_EQ:
16114 To = RHS;
16115 break;
16116 case CmpInst::ICMP_NE:
16117 if (match(RHS, m_scev_Zero())) {
16118 const SCEV *OneAlignedUp =
16119 getNextSCEVDivisibleByDivisor(One, DividesBy, SE);
16120 To = SE.getUMaxExpr(FromRewritten, OneAlignedUp);
16121 } else {
16122 // LHS != RHS can be rewritten as (LHS - RHS) = UMax(1, LHS - RHS),
16123 // but creating the subtraction eagerly is expensive. Track the
16124 // inequalities in a separate map, and materialize the rewrite lazily
16125 // when encountering a suitable subtraction while re-writing.
16126 if (LHS->getType()->isPointerTy()) {
16127 LHS = SE.getPtrToAddrExpr(LHS);
16128 RHS = SE.getPtrToAddrExpr(RHS);
16130 break;
16131 }
16132 const SCEVConstant *C;
16133 const SCEV *A, *B;
16136 RHS = A;
16137 LHS = B;
16138 }
16139 if (LHS > RHS)
16140 std::swap(LHS, RHS);
16141 Guards.NotEqual.insert({LHS, RHS});
16142 continue;
16143 }
16144 break;
16145 default:
16146 break;
16147 }
16148
16149 if (To)
16150 AddRewrite(From, FromRewritten, To);
16151 }
16152 };
16153
16155 // First, collect information from assumptions dominating the loop.
16156 for (auto &AssumeVH : SE.AC.assumptions()) {
16157 if (!AssumeVH)
16158 continue;
16159 auto *AssumeI = cast<CallInst>(AssumeVH);
16160 if (!SE.DT.dominates(AssumeI, Block))
16161 continue;
16162 Terms.emplace_back(AssumeI->getOperand(0), true);
16163 }
16164
16165 // Second, collect information from llvm.experimental.guards dominating the loop.
16166 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
16167 SE.F.getParent(), Intrinsic::experimental_guard);
16168 if (GuardDecl)
16169 for (const auto *GU : GuardDecl->users())
16170 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
16171 if (Guard->getFunction() == Block->getParent() &&
16172 SE.DT.dominates(Guard, Block))
16173 Terms.emplace_back(Guard->getArgOperand(0), true);
16174
16175 // Third, collect conditions from dominating branches. Starting at the loop
16176 // predecessor, climb up the predecessor chain, as long as there are
16177 // predecessors that can be found that have unique successors leading to the
16178 // original header.
16179 // TODO: share this logic with isLoopEntryGuardedByCond.
16180 unsigned NumCollectedConditions = 0;
16182 std::pair<const BasicBlock *, const BasicBlock *> Pair(Pred, Block);
16183 for (; Pair.first;
16184 Pair = SE.getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
16185 VisitedBlocks.insert(Pair.second);
16186 const CondBrInst *LoopEntryPredicate =
16187 dyn_cast<CondBrInst>(Pair.first->getTerminator());
16188 if (!LoopEntryPredicate)
16189 continue;
16190
16191 Terms.emplace_back(LoopEntryPredicate->getCondition(),
16192 LoopEntryPredicate->getSuccessor(0) == Pair.second);
16193 NumCollectedConditions++;
16194
16195 // If we are recursively collecting guards stop after 2
16196 // conditions to limit compile-time impact for now.
16197 if (Depth > 0 && NumCollectedConditions == 2)
16198 break;
16199 }
16200 // Finally, if we stopped climbing the predecessor chain because
16201 // there wasn't a unique one to continue, try to collect conditions
16202 // for PHINodes by recursively following all of their incoming
16203 // blocks and try to merge the found conditions to build a new one
16204 // for the Phi.
16205 if (Pair.second->hasNPredecessorsOrMore(2) &&
16207 SmallDenseMap<const BasicBlock *, LoopGuards> IncomingGuards;
16208 for (auto &Phi : Pair.second->phis())
16209 collectFromPHI(SE, Guards, Phi, VisitedBlocks, IncomingGuards, Depth);
16210 }
16211
16212 // Now apply the information from the collected conditions to
16213 // Guards.RewriteMap. Conditions are processed in reverse order, so the
16214 // earliest conditions is processed first, except guards with divisibility
16215 // information, which are moved to the back. This ensures the SCEVs with the
16216 // shortest dependency chains are constructed first.
16218 GuardsToProcess;
16219 for (auto [Term, EnterIfTrue] : reverse(Terms)) {
16220 SmallVector<Value *, 8> Worklist;
16221 SmallPtrSet<Value *, 8> Visited;
16222 Worklist.push_back(Term);
16223 while (!Worklist.empty()) {
16224 Value *Cond = Worklist.pop_back_val();
16225 if (!Visited.insert(Cond).second)
16226 continue;
16227
16228 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
16229 auto Predicate =
16230 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
16231 const auto *LHS = SE.getSCEV(Cmp->getOperand(0));
16232 const auto *RHS = SE.getSCEV(Cmp->getOperand(1));
16233 // If LHS is a constant, apply information to the other expression.
16234 // TODO: If LHS is not a constant, check if using CompareSCEVComplexity
16235 // can improve results.
16236 if (isa<SCEVConstant>(LHS)) {
16237 std::swap(LHS, RHS);
16239 }
16240 GuardsToProcess.emplace_back(Predicate, LHS, RHS);
16241 continue;
16242 }
16243
16244 Value *L, *R;
16245 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
16246 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
16247 Worklist.push_back(L);
16248 Worklist.push_back(R);
16249 }
16250 }
16251 }
16252
16253 // Process divisibility guards in reverse order to populate DivGuards early.
16254 DenseMap<const SCEV *, APInt> Multiples;
16255 LoopGuards DivGuards(SE);
16256 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess) {
16257 if (!isDivisibilityGuard(LHS, RHS, SE))
16258 continue;
16259 collectDivisibilityInformation(Predicate, LHS, RHS, DivGuards.RewriteMap,
16260 Multiples, SE);
16261 }
16262
16263 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess)
16264 CollectCondition(Predicate, LHS, RHS, Guards.RewriteMap, DivGuards);
16265
16266 // Apply divisibility information last. This ensures it is applied to the
16267 // outermost expression after other rewrites for the given value.
16268 for (const auto &[K, Divisor] : Multiples) {
16269 const SCEV *DivisorSCEV = SE.getConstant(Divisor);
16270 Guards.RewriteMap[K] =
16272 Guards.rewrite(K), Divisor, SE),
16273 DivisorSCEV),
16274 DivisorSCEV);
16275 ExprsToRewrite.push_back(K);
16276 }
16277
16278 // Let the rewriter preserve NUW/NSW flags if the unsigned/signed ranges of
16279 // the replacement expressions are contained in the ranges of the replaced
16280 // expressions.
16281 Guards.PreserveNUW = true;
16282 Guards.PreserveNSW = true;
16283 for (const SCEV *Expr : ExprsToRewrite) {
16284 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16285 Guards.PreserveNUW &=
16286 SE.getUnsignedRange(Expr).contains(SE.getUnsignedRange(RewriteTo));
16287 Guards.PreserveNSW &=
16288 SE.getSignedRange(Expr).contains(SE.getSignedRange(RewriteTo));
16289 }
16290
16291 // Now that all rewrite information is collect, rewrite the collected
16292 // expressions with the information in the map. This applies information to
16293 // sub-expressions.
16294 if (ExprsToRewrite.size() > 1) {
16295 for (const SCEV *Expr : ExprsToRewrite) {
16296 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16297 Guards.RewriteMap.erase(Expr);
16298 Guards.RewriteMap.insert({Expr, Guards.rewrite(RewriteTo)});
16299 }
16300 }
16301}
16302
16304 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
16305 /// in the map. It skips AddRecExpr because we cannot guarantee that the
16306 /// replacement is loop invariant in the loop of the AddRec.
16307 class SCEVLoopGuardRewriter
16308 : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
16311
16313
16314 public:
16315 SCEVLoopGuardRewriter(ScalarEvolution &SE,
16316 const ScalarEvolution::LoopGuards &Guards)
16317 : SCEVRewriteVisitor(SE), Map(Guards.RewriteMap),
16318 NotEqual(Guards.NotEqual) {
16319 if (Guards.PreserveNUW)
16320 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNUW);
16321 if (Guards.PreserveNSW)
16322 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNSW);
16323 }
16324
16325 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
16326
16327 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
16328 return Map.lookup_or(Expr, Expr);
16329 }
16330
16331 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
16332 if (const SCEV *S = Map.lookup(Expr))
16333 return S;
16334
16335 // If we didn't find the extact ZExt expr in the map, check if there's
16336 // an entry for a smaller ZExt we can use instead.
16337 Type *Ty = Expr->getType();
16338 const SCEV *Op = Expr->getOperand(0);
16339 unsigned Bitwidth = Ty->getScalarSizeInBits() / 2;
16340 while (Bitwidth % 8 == 0 && Bitwidth >= 8 &&
16341 Bitwidth > Op->getType()->getScalarSizeInBits()) {
16342 Type *NarrowTy = IntegerType::get(SE.getContext(), Bitwidth);
16343 auto *NarrowExt = SE.getZeroExtendExpr(Op, NarrowTy);
16344 if (const SCEV *S = Map.lookup(NarrowExt))
16345 return SE.getZeroExtendExpr(S, Ty);
16346 Bitwidth = Bitwidth / 2;
16347 }
16348
16350 Expr);
16351 }
16352
16353 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
16354 if (const SCEV *S = Map.lookup(Expr))
16355 return S;
16357 Expr);
16358 }
16359
16360 const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
16361 if (const SCEV *S = Map.lookup(Expr))
16362 return S;
16364 }
16365
16366 const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
16367 if (const SCEV *S = Map.lookup(Expr))
16368 return S;
16370 }
16371
16372 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
16373 if (const SCEV *S = Map.lookup(Expr))
16374 return S;
16375
16376 // Helper to check if S is a subtraction (A - B) where A != B, and if so,
16377 // return UMax(S, 1).
16378 auto RewriteSubtraction = [&](const SCEV *S) -> const SCEV * {
16379 SCEVUse LHS, RHS;
16380 if (MatchBinarySub(S, LHS, RHS)) {
16381 if (LHS > RHS)
16382 std::swap(LHS, RHS);
16383 if (NotEqual.contains({LHS, RHS})) {
16384 const SCEV *OneAlignedUp = getNextSCEVDivisibleByDivisor(
16385 SE.getOne(S->getType()), SE.getConstantMultiple(S), SE);
16386 return SE.getUMaxExpr(OneAlignedUp, S);
16387 }
16388 }
16389 return nullptr;
16390 };
16391
16392 // Check if Expr itself is a subtraction pattern with guard info.
16393 if (const SCEV *Rewritten = RewriteSubtraction(Expr))
16394 return Rewritten;
16395
16396 // Trip count expressions sometimes consist of adding 3 operands, i.e.
16397 // (Const + A + B). There may be guard info for A + B, and if so, apply
16398 // it.
16399 // TODO: Could more generally apply guards to Add sub-expressions.
16400 if (isa<SCEVConstant>(Expr->getOperand(0))) {
16401 if (Expr->getNumOperands() == 3) {
16402 const SCEV *Add =
16403 SE.getAddExpr(Expr->getOperand(1), Expr->getOperand(2));
16404 if (const SCEV *Rewritten = RewriteSubtraction(Add))
16405 return SE.getAddExpr(
16406 Expr->getOperand(0), Rewritten,
16407 ScalarEvolution::maskFlags(Expr->getNoWrapFlags(), FlagMask));
16408 if (const SCEV *S = Map.lookup(Add))
16409 return SE.getAddExpr(Expr->getOperand(0), S);
16410 }
16411
16412 // For expressions of the form (Const + A), check if we have guard info
16413 // for (Const + 1 + A), and rewrite to ((Const + 1 + A) - 1). This makes
16414 // sure we don't lose information when rewriting expressions based on
16415 // back-edge taken counts in some cases.
16416 if (Expr->getNumOperands() == 2) {
16417 const SCEV *S = nullptr;
16418 // Handle (-1 + 1 + A) without constructing SCEVs.
16419 if (match(Expr->getOperand(0), m_scev_AllOnes())) {
16420 S = Map.lookup(Expr->getOperand(1));
16421 } else {
16422 const SCEV *NewC =
16423 SE.getAddExpr(Expr->getOperand(0), SE.getOne(Expr->getType()));
16424 S = Map.lookup(SE.getAddExpr(NewC, Expr->getOperand(1)));
16425 }
16426 if (S)
16427 return SE.getAddExpr(S, SE.getMinusOne(Expr->getType()));
16428 }
16429 }
16431 bool Changed = false;
16432 for (SCEVUse Op : Expr->operands()) {
16433 Operands.push_back(
16435 Changed |= Op != Operands.back();
16436 }
16437 // We are only replacing operands with equivalent values, so transfer the
16438 // flags from the original expression.
16439 return !Changed ? Expr
16440 : SE.getAddExpr(Operands,
16442 Expr->getNoWrapFlags(), FlagMask));
16443 }
16444
16445 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
16447 bool Changed = false;
16448 for (SCEVUse Op : Expr->operands()) {
16449 Operands.push_back(
16451 Changed |= Op != Operands.back();
16452 }
16453 // We are only replacing operands with equivalent values, so transfer the
16454 // flags from the original expression.
16455 return !Changed ? Expr
16456 : SE.getMulExpr(Operands,
16458 Expr->getNoWrapFlags(), FlagMask));
16459 }
16460 };
16461
16462 if (RewriteMap.empty() && NotEqual.empty())
16463 return Expr;
16464
16465 SCEVLoopGuardRewriter Rewriter(SE, *this);
16466 return Rewriter.visit(Expr);
16467}
16468
16469const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
16470 return applyLoopGuards(Expr, LoopGuards::collect(L, *this));
16471}
16472
16474 const LoopGuards &Guards) {
16475 return Guards.rewrite(Expr);
16476}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
constexpr LLT S1
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
@ PostInc
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:678
This file contains the declarations for the subclasses of Constant, which represent the different fla...
SmallPtrSet< const BasicBlock *, 8 > VisitedBlocks
This file defines the DenseMap class.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
static bool isSigned(unsigned Opcode)
This file defines a hash set that can be used to remove duplication of nodes in a graph.
#define op(i)
Hexagon Common GEP
Value * getPointer(Value *Ptr)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This defines the Use class.
iv Induction Variable Users
Definition IVUsers.cpp:48
static 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:539
#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 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:250
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:299
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition DenseMap.h:133
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive,...
Definition DenseMap.h:236
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:219
iterator end()
Definition DenseMap.h:141
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:214
void swap(DerivedT &RHS)
Definition DenseMap.h:437
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
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:348
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:1069
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:309
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:306
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:313
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:255
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
iterator_range< user_iterator > users()
Definition Value.h:426
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition Value.h:543
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.