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 "AnalysisOptions.h"
62#include "llvm/ADT/APInt.h"
63#include "llvm/ADT/ArrayRef.h"
64#include "llvm/ADT/DenseMap.h"
66#include "llvm/ADT/FoldingSet.h"
67#include "llvm/ADT/STLExtras.h"
68#include "llvm/ADT/ScopeExit.h"
69#include "llvm/ADT/Sequence.h"
72#include "llvm/ADT/Statistic.h"
74#include "llvm/ADT/StringRef.h"
84#include "llvm/Config/llvm-config.h"
85#include "llvm/IR/Argument.h"
86#include "llvm/IR/BasicBlock.h"
87#include "llvm/IR/CFG.h"
88#include "llvm/IR/Constant.h"
90#include "llvm/IR/Constants.h"
91#include "llvm/IR/DataLayout.h"
93#include "llvm/IR/Dominators.h"
94#include "llvm/IR/Function.h"
95#include "llvm/IR/GlobalAlias.h"
96#include "llvm/IR/GlobalValue.h"
98#include "llvm/IR/InstrTypes.h"
99#include "llvm/IR/Instruction.h"
100#include "llvm/IR/Instructions.h"
102#include "llvm/IR/Intrinsics.h"
103#include "llvm/IR/LLVMContext.h"
104#include "llvm/IR/Operator.h"
105#include "llvm/IR/PatternMatch.h"
106#include "llvm/IR/Type.h"
107#include "llvm/IR/Use.h"
108#include "llvm/IR/User.h"
109#include "llvm/IR/Value.h"
110#include "llvm/IR/Verifier.h"
112#include "llvm/Pass.h"
113#include "llvm/Support/Casting.h"
116#include "llvm/Support/Debug.h"
122#include <algorithm>
123#include <cassert>
124#include <climits>
125#include <cstdint>
126#include <cstdlib>
127#include <map>
128#include <memory>
129#include <numeric>
130#include <optional>
131#include <tuple>
132#include <utility>
133#include <vector>
134
135using namespace llvm;
136using namespace PatternMatch;
137using namespace SCEVPatternMatch;
138
139#define DEBUG_TYPE "scalar-evolution"
140
141STATISTIC(NumExitCountsComputed,
142 "Number of loop exits with predictable exit counts");
143STATISTIC(NumExitCountsNotComputed,
144 "Number of loop exits without predictable exit counts");
145STATISTIC(NumBruteForceTripCountsComputed,
146 "Number of loops with trip counts computed by force");
147
148#ifdef EXPENSIVE_CHECKS
149bool llvm::VerifySCEV = true;
150#else
151bool llvm::VerifySCEV = false;
152#endif
153
155 "verify-scev", cl::Hidden, cl::location(VerifySCEV),
156 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
157
158//===----------------------------------------------------------------------===//
159// SCEV class definitions
160//===----------------------------------------------------------------------===//
161
163 // Leaf nodes are always their own canonical.
164 switch (getSCEVType()) {
165 case scConstant:
166 case scVScale:
167 case scUnknown:
168 CanonicalSCEV = this;
169 return;
170 default:
171 break;
172 }
173
174 // For all other expressions, check whether any immediate operand has a
175 // different canonical. Since operands are always created before their parent,
176 // their canonical pointers are already set — no recursion needed.
177 if (all_of(operands(), [](SCEVUse Op) { return Op.isCanonical(); })) {
178 CanonicalSCEV = this;
179 return;
180 }
181
183 map_range(operands(), [](SCEVUse Op) { return Op.getCanonical(); }));
184 // Rebuild the expression from the canonical operands, stripping use flags.
185 CanonicalSCEV = SE.getWithOperands(this, CanonOps);
186}
187
188//===----------------------------------------------------------------------===//
189// Implementation of the SCEV class.
190//
191
192#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
194 print(dbgs());
195 dbgs() << '\n';
196}
197#endif
198
199void SCEV::print(raw_ostream &OS) const {
200 switch (getSCEVType()) {
201 case scConstant:
202 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
203 return;
204 case scVScale:
205 OS << "vscale";
206 return;
207 case scPtrToAddr: {
208 const SCEVCastExpr *PtrCast = cast<SCEVCastExpr>(this);
209 SCEVUse Op = PtrCast->getOperand();
210 OS << "(ptrtoaddr " << *Op->getType() << " " << Op << " to "
211 << *PtrCast->getType() << ")";
212 return;
213 }
214 case scTruncate: {
216 SCEVUse Op = Trunc->getOperand();
217 OS << "(trunc " << *Op->getType() << " " << Op << " to "
218 << *Trunc->getType() << ")";
219 return;
220 }
221 case scZeroExtend: {
223 SCEVUse Op = ZExt->getOperand();
224 OS << "(zext " << *Op->getType() << " " << Op << " to " << *ZExt->getType()
225 << ")";
226 return;
227 }
228 case scSignExtend: {
230 SCEVUse Op = SExt->getOperand();
231 OS << "(sext " << *Op->getType() << " " << Op << " to " << *SExt->getType()
232 << ")";
233 return;
234 }
235 case scAddRecExpr: {
236 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
237 OS << "{" << AR->getOperand(0);
238 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
239 OS << ",+," << AR->getOperand(i);
240 OS << "}<";
241 if (AR->hasNoUnsignedWrap())
242 OS << "nuw><";
243 if (AR->hasNoSignedWrap())
244 OS << "nsw><";
245 if (AR->hasNoSelfWrap() && !AR->hasNoUnsignedWrap() &&
246 !AR->hasNoSignedWrap())
247 OS << "nw><";
248 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
249 OS << ">";
250 return;
251 }
252 case scAddExpr:
253 case scMulExpr:
254 case scUMaxExpr:
255 case scSMaxExpr:
256 case scUMinExpr:
257 case scSMinExpr:
259 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
260 const char *OpStr = nullptr;
261 switch (NAry->getSCEVType()) {
262 case scAddExpr: OpStr = " + "; break;
263 case scMulExpr: OpStr = " * "; break;
264 case scUMaxExpr: OpStr = " umax "; break;
265 case scSMaxExpr: OpStr = " smax "; break;
266 case scUMinExpr:
267 OpStr = " umin ";
268 break;
269 case scSMinExpr:
270 OpStr = " smin ";
271 break;
273 OpStr = " umin_seq ";
274 break;
275 default:
276 llvm_unreachable("There are no other nary expression types.");
277 }
278 OS << "(" << llvm::interleaved(NAry->operands(), OpStr) << ")";
279 switch (NAry->getSCEVType()) {
280 case scAddExpr:
281 case scMulExpr:
282 if (NAry->hasNoUnsignedWrap())
283 OS << "<nuw>";
284 if (NAry->hasNoSignedWrap())
285 OS << "<nsw>";
286 break;
287 default:
288 // Nothing to print for other nary expressions.
289 break;
290 }
291 return;
292 }
293 case scUDivExpr: {
294 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
295 OS << "(" << UDiv->getLHS() << " /u " << UDiv->getRHS() << ")";
296 return;
297 }
298 case scUnknown:
299 cast<SCEVUnknown>(this)->getValue()->printAsOperand(OS, false);
300 return;
302 OS << "***COULDNOTCOMPUTE***";
303 return;
304 }
305 llvm_unreachable("Unknown SCEV kind!");
306}
307
309 switch (getSCEVType()) {
310 case scConstant:
311 case scVScale:
312 case scUnknown:
313 return {};
314 case scPtrToAddr:
315 case scTruncate:
316 case scZeroExtend:
317 case scSignExtend:
318 return cast<SCEVCastExpr>(this)->operands();
319 case scAddRecExpr:
320 case scAddExpr:
321 case scMulExpr:
322 case scUMaxExpr:
323 case scSMaxExpr:
324 case scUMinExpr:
325 case scSMinExpr:
327 return cast<SCEVNAryExpr>(this)->operands();
328 case scUDivExpr:
329 return cast<SCEVUDivExpr>(this)->operands();
331 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
332 }
333 llvm_unreachable("Unknown SCEV kind!");
334}
335
336bool SCEV::isZero() const { return match(this, m_scev_Zero()); }
337
338bool SCEV::isOne() const { return match(this, m_scev_One()); }
339
340bool SCEV::isAllOnesValue() const { return match(this, m_scev_AllOnes()); }
341
344 if (!Mul) return false;
345
346 // If there is a constant factor, it will be first.
347 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
348 if (!SC) return false;
349
350 // Return true if the value is negative, this matches things like (-42 * V).
351 return SC->getAPInt().isNegative();
352}
353
356
358 return S->getSCEVType() == scCouldNotCompute;
359}
360
362 auto &Entry = ConstantSCEVs[V];
363 if (Entry)
364 return Entry;
365
368 ID.AddPointer(V);
370 if (SCEVConstant *S =
371 static_cast<SCEVConstant *>(UniqueSCEVs.lookup(ID, Token)))
372 return Entry = S;
373 SCEVConstant *S =
374 new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
375 UniqueSCEVs.insert(S, Token);
376 S->computeAndSetCanonical(*this);
377 return Entry = S;
378}
379
381 return getConstant(ConstantInt::get(getContext(), Val));
382}
383
384const SCEV *
387 // TODO: Avoid implicit trunc?
388 // See https://github.com/llvm/llvm-project/issues/112510.
389 return getConstant(
390 ConstantInt::get(ITy, V, isSigned, /*ImplicitTrunc=*/true));
391}
392
396 ID.AddPointer(Ty);
398 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
399 return S;
400 SCEV *S = new (SCEVAllocator) SCEVVScale(ID.Intern(SCEVAllocator), Ty);
401 UniqueSCEVs.insert(S, Token);
402 S->computeAndSetCanonical(*this);
403 return S;
404}
405
407 SCEVFlags Flags) {
408 const SCEV *Res = getConstant(Ty, EC.getKnownMinValue());
409 if (EC.isScalable())
410 Res = getMulExpr(Res, getVScale(Ty), Flags);
411 return Res;
412}
413
415 SCEVUse op, Type *ty)
416 : SCEV(ID, SCEVTy, computeExpressionSize(op), ty), Op(op) {}
417
418SCEVPtrToAddrExpr::SCEVPtrToAddrExpr(const FoldingSetNodeIDRef ID,
419 const SCEV *Op, Type *ITy)
420 : SCEVCastExpr(ID, scPtrToAddr, Op, ITy) {
421 assert(getOperand()->getType()->isPointerTy() && getType()->isIntegerTy() &&
422 "Must be a non-bit-width-changing pointer-to-integer cast!");
423}
424
429
430SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
431 Type *ty)
433 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
434 "Cannot truncate non-integer value!");
435}
436
437SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
438 Type *ty)
440 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
441 "Cannot zero extend non-integer value!");
442}
443
444SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
445 Type *ty)
447 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
448 "Cannot sign extend non-integer value!");
449}
450
452 // Clear this SCEVUnknown from various maps.
453 SE->forgetMemoizedResults({this});
454
455 // Remove this SCEVUnknown from the uniquing map.
456 SE->UniqueSCEVs.erase(this);
457
458 // Release the value.
459 setValPtr(nullptr);
460}
461
462void SCEVUnknown::allUsesReplacedWith(Value *New) {
463 // Clear this SCEVUnknown from various maps.
464 SE->forgetMemoizedResults({this});
465
466 // Remove this SCEVUnknown from the uniquing map.
467 SE->UniqueSCEVs.erase(this);
468
469 // Replace the value pointer in case someone is still using this SCEVUnknown.
470 setValPtr(New);
471}
472
473//===----------------------------------------------------------------------===//
474// SCEV Utilities
475//===----------------------------------------------------------------------===//
476
477/// Compare the two values \p LV and \p RV in terms of their "complexity" where
478/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
479/// operands in SCEV expressions.
480static int compareValueComplexity(const AnalysisOptions &Opts,
481 const LoopInfo *const LI, Value *LV,
482 Value *RV, unsigned Depth) {
483 if (Depth > Opts.scalar_evolution_max_value_compare_depth)
484 return 0;
485
486 // Order pointer values after integer values. This helps SCEVExpander form
487 // GEPs.
488 bool LIsPointer = LV->getType()->isPointerTy(),
489 RIsPointer = RV->getType()->isPointerTy();
490 if (LIsPointer != RIsPointer)
491 return (int)LIsPointer - (int)RIsPointer;
492
493 // Compare getValueID values.
494 unsigned LID = LV->getValueID(), RID = RV->getValueID();
495 if (LID != RID)
496 return (int)LID - (int)RID;
497
498 // Sort arguments by their position.
499 if (const auto *LA = dyn_cast<Argument>(LV)) {
500 const auto *RA = cast<Argument>(RV);
501 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
502 return (int)LArgNo - (int)RArgNo;
503 }
504
505 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
506 const auto *RGV = cast<GlobalValue>(RV);
507
508 if (auto L = LGV->getLinkage() - RGV->getLinkage())
509 return L;
510
511 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
512 auto LT = GV->getLinkage();
513 return !(GlobalValue::isPrivateLinkage(LT) ||
515 };
516
517 // Use the names to distinguish the two values, but only if the
518 // names are semantically important.
519 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
520 return LGV->getName().compare(RGV->getName());
521 }
522
523 // For instructions, compare their loop depth, and their operand count. This
524 // is pretty loose.
525 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
526 const auto *RInst = cast<Instruction>(RV);
527
528 // Compare loop depths.
529 const BasicBlock *LParent = LInst->getParent(),
530 *RParent = RInst->getParent();
531 if (LParent != RParent) {
532 unsigned LDepth = LI->getLoopDepth(LParent),
533 RDepth = LI->getLoopDepth(RParent);
534 if (LDepth != RDepth)
535 return (int)LDepth - (int)RDepth;
536 }
537
538 // Compare the number of operands.
539 unsigned LNumOps = LInst->getNumOperands(),
540 RNumOps = RInst->getNumOperands();
541 if (LNumOps != RNumOps)
542 return (int)LNumOps - (int)RNumOps;
543
544 for (unsigned Idx : seq(LNumOps)) {
545 int Result = compareValueComplexity(Opts, LI, LInst->getOperand(Idx),
546 RInst->getOperand(Idx), Depth + 1);
547 if (Result != 0)
548 return Result;
549 }
550 }
551
552 return 0;
553}
554
555// Return negative, zero, or positive, if LHS is less than, equal to, or greater
556// than RHS, respectively. A three-way result allows recursive comparisons to be
557// more efficient. The result is a total order.
558static int compareSCEVComplexity(const AnalysisOptions &Opts,
559 const LoopInfo *const LI, SCEVUse LHS,
561 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
562 if (LHS == RHS)
563 return 0;
564
565 if (LHS.getPointer() == RHS.getPointer())
566 return (int)LHS.getUseNoWrapFlags() - (int)RHS.getUseNoWrapFlags();
567
568 // Primarily, sort the SCEVs by their getSCEVType().
569 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
570 if (LType != RType)
571 return (int)LType - (int)RType;
572
573 // Aside from the getSCEVType() ordering, the particular ordering
574 // isn't very important except that it's beneficial to be consistent,
575 // so that (a + b) and (b + a) don't end up as different expressions.
576 switch (LType) {
577 case scUnknown: {
578 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
579 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
580
581 if (int X = compareValueComplexity(Opts, LI, LU->getValue(), RU->getValue(),
582 /*Depth=*/0))
583 return X;
584 return LU->getOrderID() < RU->getOrderID() ? -1 : 1;
585 }
586
587 case scConstant: {
590
591 // Compare constant values.
592 const APInt &LA = LC->getAPInt();
593 const APInt &RA = RC->getAPInt();
594 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
595 if (LBitWidth != RBitWidth)
596 return (int)LBitWidth - (int)RBitWidth;
597 return LA.ult(RA) ? -1 : 1;
598 }
599
600 case scVScale: {
601 const auto *LTy = cast<IntegerType>(cast<SCEVVScale>(LHS)->getType());
602 const auto *RTy = cast<IntegerType>(cast<SCEVVScale>(RHS)->getType());
603 return LTy->getBitWidth() - RTy->getBitWidth();
604 }
605
606 case scAddRecExpr: {
609
610 // There is always a dominance between two recs that are used by one SCEV,
611 // so we can safely sort recs by loop header dominance. We require such
612 // order in getAddExpr.
613 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
614 if (LLoop != RLoop) {
615 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
616 assert(LHead != RHead && "Two loops share the same header?");
617 if (DT.dominates(LHead, RHead))
618 return 1;
619 assert(DT.dominates(RHead, LHead) &&
620 "No dominance between recurrences used by one SCEV?");
621 return -1;
622 }
623
624 [[fallthrough]];
625 }
626
627 case scTruncate:
628 case scZeroExtend:
629 case scSignExtend:
630 case scPtrToAddr:
631 case scAddExpr:
632 case scMulExpr:
633 case scUDivExpr:
634 case scSMaxExpr:
635 case scUMaxExpr:
636 case scSMinExpr:
637 case scUMinExpr:
639 ArrayRef<SCEVUse> LOps = LHS->operands();
640 ArrayRef<SCEVUse> ROps = RHS->operands();
641
642 // Lexicographically compare n-ary-like expressions.
643 unsigned LNumOps = LOps.size(), RNumOps = ROps.size();
644 if (LNumOps != RNumOps)
645 return (int)LNumOps - (int)RNumOps;
646
647 for (unsigned i = 0; i != LNumOps; ++i) {
648 auto X = compareSCEVComplexity(Opts, LI, LOps[i], ROps[i], DT);
649 if (X != 0)
650 return X;
651 }
652
653 assert(isa<SCEVCastExpr>(LHS) && "distinct SCEVs compare equal");
654 unsigned LBitWidth = cast<IntegerType>(LHS->getType())->getBitWidth();
655 unsigned RBitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
656 assert(LBitWidth != RBitWidth && "distinct SCEVs compare equal");
657 return (int)LBitWidth - (int)RBitWidth;
658 }
659
661 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
662 }
663 llvm_unreachable("Unknown SCEV kind!");
664}
665
666/// Given a list of SCEV objects, order them by their complexity, and group
667/// objects of the same complexity together by value. When this routine is
668/// finished, we know that any duplicates in the vector are consecutive and that
669/// complexity is monotonically increasing.
670///
671/// Note that we go take special precautions to ensure that we get deterministic
672/// results from this routine. In other words, we don't want the results of
673/// this to depend on where the addresses of various SCEV objects happened to
674/// land in memory.
675static void groupByComplexity(const AnalysisOptions &Opts,
677 DominatorTree &DT) {
678 if (Ops.size() < 2) return; // Noop
679
680 // Whether LHS has provably less complexity than RHS.
681 auto IsLessComplex = [&](SCEVUse LHS, SCEVUse RHS) {
682 return compareSCEVComplexity(Opts, LI, LHS, RHS, DT) < 0;
683 };
684 if (Ops.size() == 2) {
685 // This is the common case, which also happens to be trivially simple.
686 // Special case it.
687 SCEVUse &LHS = Ops[0], &RHS = Ops[1];
688 if (IsLessComplex(RHS, LHS))
689 std::swap(LHS, RHS);
690 return;
691 }
692
693 llvm::sort(Ops, IsLessComplex);
694}
695
696/// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
697/// least -scalar-evolution-huge-expr-threshold nodes).
698static bool hasHugeExpression(const AnalysisOptions &Opts,
700 return any_of(Ops, [&](const SCEV *S) {
701 return S->getExpressionSize() >= Opts.scalar_evolution_huge_expr_threshold;
702 });
703}
704
705/// Performs a number of common optimizations on the passed \p Ops. If the
706/// whole expression reduces down to a single operand, it will be returned.
707///
708/// The following optimizations are performed:
709/// * Fold constants using the \p Fold function.
710/// * Remove identity constants satisfying \p IsIdentity.
711/// * If a constant satisfies \p IsAbsorber, return it.
712/// * Sort operands by complexity.
713template <typename FoldT, typename IsIdentityT, typename IsAbsorberT>
714static const SCEV *
715constantFoldAndGroupOps(const AnalysisOptions &Opts, ScalarEvolution &SE,
716 LoopInfo &LI, DominatorTree &DT,
717 SmallVectorImpl<SCEVUse> &Ops, FoldT Fold,
718 IsIdentityT IsIdentity, IsAbsorberT IsAbsorber) {
719 const SCEVConstant *Folded = nullptr;
720 for (unsigned Idx = 0; Idx < Ops.size();) {
721 const SCEV *Op = Ops[Idx];
722 if (const auto *C = dyn_cast<SCEVConstant>(Op)) {
723 if (!Folded)
724 Folded = C;
725 else
727 SE.getConstant(Fold(Folded->getAPInt(), C->getAPInt())));
728 Ops.erase(Ops.begin() + Idx);
729 continue;
730 }
731 ++Idx;
732 }
733
734 if (Ops.empty()) {
735 assert(Folded && "Must have folded value");
736 return Folded;
737 }
738
739 if (Folded && IsAbsorber(Folded->getAPInt()))
740 return Folded;
741
742 groupByComplexity(Opts, Ops, &LI, DT);
743 if (Folded && !IsIdentity(Folded->getAPInt()))
744 Ops.insert(Ops.begin(), Folded);
745
746 return Ops.size() == 1 ? Ops[0] : nullptr;
747}
748
749//===----------------------------------------------------------------------===//
750// Simple SCEV method implementations
751//===----------------------------------------------------------------------===//
752
753/// Compute BC(It, K). The result has width W. Assume, K > 0.
754static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
755 ScalarEvolution &SE,
756 Type *ResultTy) {
757 // Handle the simplest case efficiently.
758 if (K == 1)
759 return SE.getTruncateOrZeroExtend(It, ResultTy);
760
761 // We are using the following formula for BC(It, K):
762 //
763 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
764 //
765 // Suppose, W is the bitwidth of the return value. We must be prepared for
766 // overflow. Hence, we must assure that the result of our computation is
767 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
768 // safe in modular arithmetic.
769 //
770 // However, this code doesn't use exactly that formula; the formula it uses
771 // is something like the following, where T is the number of factors of 2 in
772 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
773 // exponentiation:
774 //
775 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
776 //
777 // This formula is trivially equivalent to the previous formula. However,
778 // this formula can be implemented much more efficiently. The trick is that
779 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
780 // arithmetic. To do exact division in modular arithmetic, all we have
781 // to do is multiply by the inverse. Therefore, this step can be done at
782 // width W.
783 //
784 // The next issue is how to safely do the division by 2^T. The way this
785 // is done is by doing the multiplication step at a width of at least W + T
786 // bits. This way, the bottom W+T bits of the product are accurate. Then,
787 // when we perform the division by 2^T (which is equivalent to a right shift
788 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
789 // truncated out after the division by 2^T.
790 //
791 // In comparison to just directly using the first formula, this technique
792 // is much more efficient; using the first formula requires W * K bits,
793 // but this formula less than W + K bits. Also, the first formula requires
794 // a division step, whereas this formula only requires multiplies and shifts.
795 //
796 // It doesn't matter whether the subtraction step is done in the calculation
797 // width or the input iteration count's width; if the subtraction overflows,
798 // the result must be zero anyway. We prefer here to do it in the width of
799 // the induction variable because it helps a lot for certain cases; CodeGen
800 // isn't smart enough to ignore the overflow, which leads to much less
801 // efficient code if the width of the subtraction is wider than the native
802 // register width.
803 //
804 // (It's possible to not widen at all by pulling out factors of 2 before
805 // the multiplication; for example, K=2 can be calculated as
806 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
807 // extra arithmetic, so it's not an obvious win, and it gets
808 // much more complicated for K > 3.)
809
810 // Protection from insane SCEVs; this bound is conservative,
811 // but it probably doesn't matter.
812 if (K > 1000)
813 return SE.getCouldNotCompute();
814
815 unsigned W = SE.getTypeSizeInBits(ResultTy);
816
817 // Calculate K! / 2^T and T; we divide out the factors of two before
818 // multiplying for calculating K! / 2^T to avoid overflow.
819 // Other overflow doesn't matter because we only care about the bottom
820 // W bits of the result.
821 APInt OddFactorial(W, 1);
822 unsigned T = 1;
823 for (unsigned i = 3; i <= K; ++i) {
824 unsigned TwoFactors = countr_zero(i);
825 T += TwoFactors;
826 OddFactorial *= (i >> TwoFactors);
827 }
828
829 // We need at least W + T bits for the multiplication step
830 unsigned CalculationBits = W + T;
831
832 // Calculate 2^T, at width T+W.
833 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
834
835 // Calculate the multiplicative inverse of K! / 2^T;
836 // this multiplication factor will perform the exact division by
837 // K! / 2^T.
838 APInt MultiplyFactor = OddFactorial.multiplicativeInverse();
839
840 // Calculate the product, at width T+W
841 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
842 CalculationBits);
843 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
844 for (unsigned i = 1; i != K; ++i) {
845 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
846 Dividend = SE.getMulExpr(Dividend,
847 SE.getTruncateOrZeroExtend(S, CalculationTy));
848 }
849
850 // Divide by 2^T
851 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
852
853 // Truncate the result, and divide by K! / 2^T.
854
855 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
856 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
857}
858
859/// Return the value of this chain of recurrences at the specified iteration
860/// number. We can evaluate this recurrence by multiplying each element in the
861/// chain by the binomial coefficient corresponding to it. In other words, we
862/// can evaluate {A,+,B,+,C,+,D} as:
863///
864/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
865///
866/// where BC(It, k) stands for binomial coefficient.
868 ScalarEvolution &SE) const {
869 return evaluateAtIteration(operands(), It, SE);
870}
871
873 const SCEV *It, ScalarEvolution &SE,
874 SCEVFlags UseFlags) {
875 assert(Operands.size() > 0);
876 assert((Operands.size() == 2 || UseFlags == SCEV::FlagNone) &&
877 "use-specific flags only supported for affine AddRecs");
878 SCEVUse Result = Operands[0].getPointer();
879 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
880 // The computation is correct in the face of overflow provided that the
881 // multiplication is performed _after_ the evaluation of the binomial
882 // coefficient.
883 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
884 if (isa<SCEVCouldNotCompute>(Coeff))
885 return Coeff;
886
887 SCEVUse Mul = SE.getMulExpr(Operands[i].getPointer(), Coeff,
888 {SCEV::FlagNone, UseFlags});
889 Result = SE.getAddExpr(Result, Mul, {SCEV::FlagNone, UseFlags});
890 }
891 return Result;
892}
893
895 const SCEV *BTC = SE.getBackedgeTakenCount(getLoop());
897 return BTC;
898 // The loop reaches iteration BTC, so the value this recurrence computes there
899 // is the value it had, and that did not wrap.
900 return evaluateAtIteration(operands(), BTC, SE,
903}
904
905//===----------------------------------------------------------------------===//
906// SCEV Expression folder implementations
907//===----------------------------------------------------------------------===//
908
909/// The SCEVCastSinkingRewriter takes a scalar evolution expression,
910/// which computes a pointer-typed value, and rewrites the whole expression
911/// tree so that *all* the computations are done on integers, and the only
912/// pointer-typed operands in the expression are SCEVUnknown.
913/// The CreatePtrCast callback is invoked to create the actual conversion
914/// (ptrtoint or ptrtoaddr) at the SCEVUnknown leaves.
916 : public SCEVRewriteVisitor<SCEVCastSinkingRewriter> {
918 using ConversionFn = function_ref<const SCEV *(const SCEVUnknown *)>;
919 Type *TargetTy;
920 ConversionFn CreatePtrCast;
921
922public:
924 ConversionFn CreatePtrCast)
925 : Base(SE), TargetTy(TargetTy), CreatePtrCast(std::move(CreatePtrCast)) {}
926
927 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
928 Type *TargetTy, ConversionFn CreatePtrCast) {
929 SCEVCastSinkingRewriter Rewriter(SE, TargetTy, std::move(CreatePtrCast));
930 return Rewriter.visit(Scev);
931 }
932
933 const SCEV *visit(const SCEV *S) {
934 Type *STy = S->getType();
935 // If the expression is not pointer-typed, just keep it as-is.
936 if (!STy->isPointerTy())
937 return S;
938 // Else, recursively sink the cast down into it.
939 return Base::visit(S);
940 }
941
942 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
943 // Preserve wrap flags on rewritten SCEVAddExpr, which the default
944 // implementation drops.
946 bool Changed = false;
947 for (SCEVUse Op : Expr->operands()) {
948 Operands.push_back(visit(Op.getPointer()));
949 Changed |= Op.getPointer() != Operands.back();
950 }
951 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
952 }
953
954 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
955 assert(Expr->getType()->isPointerTy() &&
956 "Should only reach pointer-typed SCEVUnknown's.");
957 // Perform some basic constant folding. If the operand of the cast is a
958 // null pointer, don't create a cast SCEV expression (that will be left
959 // as-is), but produce a zero constant.
961 return SE.getZero(TargetTy);
962 return CreatePtrCast(Expr);
963 }
964};
965
967 assert(Op->getType()->isPointerTy() && "Op must be a pointer");
968
969 // Treat pointers with unstable representation conservatively, since the
970 // address bits may change.
971 if (DL.hasUnstableRepresentation(Op->getType()))
972 return getCouldNotCompute();
973
974 Type *Ty = DL.getAddressType(Op->getType());
975
976 // Use the rewriter to sink the cast down to SCEVUnknown leaves.
977 // The rewriter handles null pointer constant folding.
979 Op, *this, Ty, [this, Ty](const SCEVUnknown *U) {
982 ID.AddPointer(U);
983 ID.AddPointer(Ty);
985 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
986 return S;
987 SCEV *S = new (SCEVAllocator)
988 SCEVPtrToAddrExpr(ID.Intern(SCEVAllocator), U, Ty);
989 UniqueSCEVs.insert(S, Token);
990 S->computeAndSetCanonical(*this);
991 registerUser(S, {U});
992 return static_cast<const SCEV *>(S);
993 });
994 assert(IntOp->getType()->isIntegerTy() &&
995 "We must have succeeded in sinking the cast, "
996 "and ending up with an integer-typed expression!");
997 return IntOp;
998}
999
1001 unsigned Depth) {
1002 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1003 "This is not a truncating conversion!");
1004 assert(isSCEVable(Ty) &&
1005 "This is not a conversion to a SCEVable type!");
1006 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1007 Ty = getEffectiveSCEVType(Ty);
1008
1011 ID.AddPointer(Op.getOpaqueValue());
1012 ID.AddPointer(Ty);
1014 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1015 return S;
1016
1017 // Fold if the operand is constant.
1018 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1019 return getConstant(
1020 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1021
1022 // trunc(trunc(x)) --> trunc(x)
1024 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1025
1026 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1028 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1029
1030 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1032 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1033
1034 if (Depth > Opts.scalar_evolution_max_cast_depth) {
1035 SCEV *S =
1036 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1037 UniqueSCEVs.insert(S, Token);
1038 S->computeAndSetCanonical(*this);
1039 registerUser(S, Op);
1040 return S;
1041 }
1042
1043 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1044 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1045 // if after transforming we have at most one truncate, not counting truncates
1046 // that replace other casts.
1048 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1050 unsigned numTruncs = 0;
1051 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1052 ++i) {
1053 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1054 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1056 numTruncs++;
1057 Operands.push_back(S);
1058 }
1059 if (numTruncs < 2) {
1060 if (isa<SCEVAddExpr>(Op))
1061 return getAddExpr(Operands);
1062 if (isa<SCEVMulExpr>(Op))
1063 return getMulExpr(Operands);
1064 llvm_unreachable("Unexpected SCEV type for Op.");
1065 }
1066 // Although we checked in the beginning that ID is not in the cache, it is
1067 // possible that during recursion and different modification ID was inserted
1068 // into the cache. So if we find it, just return it.
1069 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1070 return S;
1071 }
1072
1073 // If the input value is a chrec scev, truncate the chrec's operands.
1074 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1076 for (const SCEV *Op : AddRec->operands())
1077 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1078 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagNone);
1079 }
1080
1081 // Return zero if truncating to known zeros.
1082 uint32_t MinTrailingZeros = getMinTrailingZeros(Op);
1083 if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1084 return getZero(Ty);
1085
1086 // The cast wasn't folded; create an explicit cast node. We can reuse
1087 // the existing insert position since if we get here, we won't have
1088 // made any changes which would invalidate it.
1089 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1090 Op, Ty);
1091 UniqueSCEVs.insert(S, Token);
1092 S->computeAndSetCanonical(*this);
1093 registerUser(S, Op);
1094 return S;
1095}
1096
1097// Get the limit of a recurrence such that incrementing by Step cannot cause
1098// signed overflow as long as the value of the recurrence within the
1099// loop does not exceed this limit before incrementing.
1100static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1102 ScalarEvolution *SE) {
1103 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1104 if (SE->isKnownPositive(Step)) {
1107 SE->getSignedRangeMax(Step));
1108 }
1109 if (SE->isKnownNegative(Step)) {
1112 SE->getSignedRangeMin(Step));
1113 }
1114 return nullptr;
1115}
1116
1117// Get the limit of a recurrence such that incrementing by Step cannot cause
1118// unsigned overflow as long as the value of the recurrence within the loop does
1119// not exceed this limit before incrementing.
1122 ScalarEvolution *SE) {
1123 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1125
1127 SE->getUnsignedRangeMax(Step));
1128}
1129
1130namespace {
1131
1132struct ExtendOpTraitsBase {
1133 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(SCEVUse, Type *,
1134 unsigned);
1135};
1136
1137// Used to make code generic over signed and unsigned overflow.
1138template <typename ExtendOp> struct ExtendOpTraits {
1139 // Members present:
1140 //
1141 // static const SCEVFlags WrapType;
1142 //
1143 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1144 //
1145 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1146 // ICmpInst::Predicate *Pred,
1147 // ScalarEvolution *SE);
1148};
1149
1150template <>
1151struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1152 static const SCEVFlags WrapType = SCEV::FlagNSW;
1153
1154 static const GetExtendExprTy GetExtendExpr;
1155
1156 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1157 ICmpInst::Predicate *Pred,
1158 ScalarEvolution *SE) {
1159 return getSignedOverflowLimitForStep(Step, Pred, SE);
1160 }
1161};
1162
1163const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1165
1166template <>
1167struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1168 static const SCEVFlags WrapType = SCEV::FlagNUW;
1169
1170 static const GetExtendExprTy GetExtendExpr;
1171
1172 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1173 ICmpInst::Predicate *Pred,
1174 ScalarEvolution *SE) {
1175 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1176 }
1177};
1178
1179const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1181
1182} // end anonymous namespace
1183
1184// The recurrence AR has been shown to have no signed/unsigned wrap or something
1185// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1186// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1187// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1188// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1189// expression "Step + sext/zext(PreIncAR)" is congruent with
1190// "sext/zext(PostIncAR)"
1191template <typename ExtendOpTy>
1193 ScalarEvolution *SE, unsigned Depth) {
1194 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1195 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1196
1197 const Loop *L = AR->getLoop();
1198 const SCEV *Start = AR->getStart();
1199 const SCEV *Step = AR->getStepRecurrence(*SE);
1200
1201 // Check for a simple looking step prior to loop entry.
1202 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1203 if (!SA)
1204 return nullptr;
1205
1206 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1207 // subtraction is expensive. For this purpose, perform a quick and dirty
1208 // difference, by checking for Step in the operand list. Note, that
1209 // SA might have repeated ops, like %a + %a + ..., so only remove one.
1210 SmallVector<SCEVUse, 4> DiffOps(SA->operands());
1211 for (auto It = DiffOps.begin(); It != DiffOps.end(); ++It)
1212 if (*It == Step) {
1213 DiffOps.erase(It);
1214 break;
1215 }
1216
1217 if (DiffOps.size() == SA->getNumOperands())
1218 return nullptr;
1219
1220 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1221 // `Step`:
1222
1223 // 1. NSW/NUW flags on the step increment.
1224 auto PreStartFlags =
1226 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1228 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagNone));
1229
1230 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1231 // "S+X does not sign/unsign-overflow".
1232 //
1233
1234 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1235 if (PreAR && any(PreAR->getNoWrapFlags(WrapType)) &&
1236 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1237 return PreStart;
1238
1239 // 2. Direct overflow check on the step operation's expression.
1240 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1241 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1242 const SCEV *OperandExtendedStart =
1243 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1244 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1245 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1246 if (PreAR && any(AR->getNoWrapFlags(WrapType))) {
1247 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1248 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1249 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1250 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1251 }
1252 return PreStart;
1253 }
1254
1255 // 3. Loop precondition.
1257 const SCEV *OverflowLimit =
1258 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1259
1260 if (OverflowLimit &&
1261 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1262 return PreStart;
1263
1264 return nullptr;
1265}
1266
1267// Get the normalized zero or sign extended expression for this AddRec's Start.
1268template <typename ExtendOpTy>
1269static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1270 ScalarEvolution *SE,
1271 unsigned Depth) {
1272 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1273
1274 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, SE, Depth);
1275 if (!PreStart)
1276 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1277
1278 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1279 Depth),
1280 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1281}
1282
1283// Try to prove away overflow by looking at "nearby" add recurrences. A
1284// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1285// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1286//
1287// Formally:
1288//
1289// {S,+,X} == {S-T,+,X} + T
1290// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1291//
1292// If ({S-T,+,X} + T) does not overflow ... (1)
1293//
1294// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1295//
1296// If {S-T,+,X} does not overflow ... (2)
1297//
1298// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1299// == {Ext(S-T)+Ext(T),+,Ext(X)}
1300//
1301// If (S-T)+T does not overflow ... (3)
1302//
1303// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1304// == {Ext(S),+,Ext(X)} == LHS
1305//
1306// Thus, if (1), (2) and (3) are true for some T, then
1307// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1308//
1309// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1310// does not overflow" restricted to the 0th iteration. Therefore we only need
1311// to check for (1) and (2).
1312//
1313// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1314// is `Delta` (defined below).
1315template <typename ExtendOpTy>
1316bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1317 const SCEV *Step,
1318 const Loop *L) {
1319 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1320
1321 // We restrict `Start` to a constant to prevent SCEV from spending too much
1322 // time here. It is correct (but more expensive) to continue with a
1323 // non-constant `Start` and do a general SCEV subtraction to compute
1324 // `PreStart` below.
1325 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1326 if (!StartC)
1327 return false;
1328
1329 APInt StartAI = StartC->getAPInt();
1330
1331 for (unsigned Delta : {-2, -1, 1, 2}) {
1332 const SCEV *PreStart = getConstant(StartAI - Delta);
1333 const auto *PreAR = static_cast<SCEVAddRecExpr *>(
1334 findExistingSCEVInCache(scAddRecExpr, {PreStart, Step}, L));
1335
1336 // Give up if we don't already have the add recurrence we need because
1337 // actually constructing an add recurrence is relatively expensive.
1338 if (PreAR && any(PreAR->getNoWrapFlags(WrapType))) { // proves (2)
1339 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1341 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1342 DeltaS, &Pred, this);
1343 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1344 return true;
1345 }
1346 }
1347
1348 return false;
1349}
1350
1351// Finds an integer D for an expression (C + x + y + ...) such that the top
1352// level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1353// unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1354// maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1355// the (C + x + y + ...) expression is \p WholeAddExpr.
1357 const SCEVConstant *ConstantTerm,
1358 const SCEVAddExpr *WholeAddExpr) {
1359 const APInt &C = ConstantTerm->getAPInt();
1360 const unsigned BitWidth = C.getBitWidth();
1361 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1362 uint32_t TZ = BitWidth;
1363 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1364 TZ = std::min(TZ, SE.getMinTrailingZeros(WholeAddExpr->getOperand(I)));
1365 if (TZ) {
1366 // Set D to be as many least significant bits of C as possible while still
1367 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1368 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1369 }
1370 return APInt(BitWidth, 0);
1371}
1372
1373// Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1374// level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1375// number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1376// ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1378 const APInt &ConstantStart,
1379 const SCEV *Step) {
1380 const unsigned BitWidth = ConstantStart.getBitWidth();
1381 const uint32_t TZ = SE.getMinTrailingZeros(Step);
1382 if (TZ)
1383 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1384 : ConstantStart;
1385 return APInt(BitWidth, 0);
1386}
1387
1389 const ScalarEvolution::FoldID &ID, const SCEV *S,
1392 &FoldCacheUser) {
1393 auto I = FoldCache.insert({ID, S});
1394 if (!I.second) {
1395 // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1396 // entry.
1397 auto &UserIDs = FoldCacheUser[I.first->second];
1398 assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
1399 for (unsigned I = 0; I != UserIDs.size(); ++I)
1400 if (UserIDs[I] == ID) {
1401 std::swap(UserIDs[I], UserIDs.back());
1402 break;
1403 }
1404 UserIDs.pop_back();
1405 I.first->second = S;
1406 }
1407 FoldCacheUser[S].push_back(ID);
1408}
1409
1411 unsigned Depth) {
1412 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1413 "This is not an extending conversion!");
1414 assert(isSCEVable(Ty) &&
1415 "This is not a conversion to a SCEVable type!");
1416 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1417 Ty = getEffectiveSCEVType(Ty);
1418
1419 FoldID ID(scZeroExtend, Op, Ty);
1420 if (const SCEV *S = FoldCache.lookup(ID))
1421 return S;
1422
1423 const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1425 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1426 return S;
1427}
1428
1430 unsigned Depth) {
1431 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1432 "This is not an extending conversion!");
1433 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1434 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1435
1436 // Fold if the operand is constant.
1437 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1438 return getConstant(SC->getAPInt().zext(getTypeSizeInBits(Ty)));
1439
1440 // zext(zext(x)) --> zext(x)
1442 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1443
1444 // If the operand is an affine AddRec with the no-unsigned-wrap flag, the
1445 // zero-extension distributes over the recurrence.
1446 const SCEV *Start, *Step;
1447 const Loop *L;
1448 if (Depth <= Opts.scalar_evolution_max_cast_depth &&
1449 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1450 const auto *AR = cast<SCEVAddRecExpr>(Op);
1451 if (AR->hasNoUnsignedWrap()) {
1452 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1453 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1454 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1455 }
1456 }
1457
1458 // Before doing any expensive analysis, check to see if we've already
1459 // computed a SCEV for this Op and Ty.
1462 ID.AddPointer(Op.getOpaqueValue());
1463 ID.AddPointer(Ty);
1465 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1466 return S;
1467 if (Depth > Opts.scalar_evolution_max_cast_depth) {
1468 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1469 Op, Ty);
1470 UniqueSCEVs.insert(S, Token);
1471 S->computeAndSetCanonical(*this);
1472 registerUser(S, Op);
1473 return S;
1474 }
1475
1476 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1478 // It's possible the bits taken off by the truncate were all zero bits. If
1479 // so, we should be able to simplify this further.
1480 const SCEV *X = ST->getOperand();
1482 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1483 unsigned NewBits = getTypeSizeInBits(Ty);
1484 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1485 CR.zextOrTrunc(NewBits)))
1486 return getTruncateOrZeroExtend(X, Ty, Depth);
1487 }
1488
1489 // If the input value is a chrec scev, and we can prove that the value
1490 // did not overflow the old, smaller, value, we can zero extend all of the
1491 // operands (often constants). This allows analysis of something like
1492 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1493 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1494 const auto *AR = cast<SCEVAddRecExpr>(Op);
1495 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1496
1497 // The no-unsigned-wrap case is handled before the uniquing lookup above.
1498
1499 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1500 // Note that this serves two purposes: It filters out loops that are
1501 // simply not analyzable, and it covers the case where this code is
1502 // being called from within backedge-taken count analysis, such that
1503 // attempting to ask for the backedge-taken count would likely result
1504 // in infinite recursion. In the later case, the analysis code will
1505 // cope with a conservative value, and it will take care to purge
1506 // that value once it has finished.
1507 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1508 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1509 // Manually compute the final value for AR, checking for overflow.
1510
1511 // Check whether the backedge-taken count can be losslessly casted to
1512 // the addrec's type. The count is always unsigned.
1513 const SCEV *CastedMaxBECount =
1514 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1515 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1516 CastedMaxBECount, MaxBECount->getType(), Depth);
1517 if (MaxBECount == RecastedMaxBECount) {
1518 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1519 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1520 const SCEV *ZMul =
1521 getMulExpr(CastedMaxBECount, Step, SCEV::FlagNone, Depth + 1);
1522 const SCEV *ZAdd = getZeroExtendExpr(
1523 getAddExpr(Start, ZMul, SCEV::FlagNone, Depth + 1), WideTy,
1524 Depth + 1);
1525 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1526 const SCEV *WideMaxBECount =
1527 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1528 const SCEV *OperandExtendedAdd =
1529 getAddExpr(WideStart,
1530 getMulExpr(WideMaxBECount,
1531 getZeroExtendExpr(Step, WideTy, Depth + 1),
1532 SCEV::FlagNone, Depth + 1),
1533 SCEV::FlagNone, Depth + 1);
1534 if (ZAdd == OperandExtendedAdd) {
1535 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1536 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1537 // Return the expression with the addrec on the outside.
1538 Start =
1540 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1541 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1542 }
1543 // Similar to above, only this time treat the step value as signed.
1544 // This covers loops that count down.
1545 OperandExtendedAdd =
1546 getAddExpr(WideStart,
1547 getMulExpr(WideMaxBECount,
1548 getSignExtendExpr(Step, WideTy, Depth + 1),
1549 SCEV::FlagNone, Depth + 1),
1550 SCEV::FlagNone, Depth + 1);
1551 if (ZAdd == OperandExtendedAdd) {
1552 // Cache knowledge of AR NW, which is propagated to this AddRec.
1553 // Negative step causes unsigned wrap, but it still can't self-wrap.
1554 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1555 // Return the expression with the addrec on the outside.
1556 Start =
1558 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1559 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1560 }
1561 }
1562 }
1563
1564 // Normally, in the cases we can prove no-overflow via a
1565 // backedge guarding condition, we can also compute a backedge
1566 // taken count for the loop. The exceptions are assumptions and
1567 // guards present in the loop -- SCEV is not great at exploiting
1568 // these to compute max backedge taken counts, but can still use
1569 // these to prove lack of overflow. Use this fact to avoid
1570 // doing extra work that may not pay off.
1571 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1572 !AC.assumptions().empty()) {
1573
1574 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1575 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1576 if (AR->hasNoUnsignedWrap()) {
1577 // Same as nuw case above - duplicated here to avoid a compile time
1578 // issue. It's not clear that the order of checks does matter, but
1579 // it's one of two issue possible causes for a change which was
1580 // reverted. Be conservative for the moment.
1581 Start =
1583 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1584 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1585 }
1586
1587 // For a negative step, we can extend the operands iff doing so only
1588 // traverses values in the range zext([0,UINT_MAX]).
1589 if (isKnownNegative(Step)) {
1590 const SCEV *N =
1594 // Cache knowledge of AR NW, which is propagated to this
1595 // AddRec. Negative step causes unsigned wrap, but it
1596 // still can't self-wrap.
1597 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1598 // Return the expression with the addrec on the outside.
1599 Start =
1601 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1602 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1603 }
1604 }
1605 }
1606
1607 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1608 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1609 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1610 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1611 const APInt &C = SC->getAPInt();
1612 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1613 if (D != 0) {
1614 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1615 const SCEV *SResidual =
1616 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1617 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1618 return getAddExpr(SZExtD, SZExtR, SCEV::FlagNSW | SCEV::FlagNUW,
1619 Depth + 1);
1620 }
1621 }
1622
1623 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1624 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1625 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1626 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1627 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1628 }
1629 }
1630
1631 // zext(A % B) --> zext(A) % zext(B)
1632 {
1633 const SCEV *LHS;
1634 const SCEV *RHS;
1635 if (match(Op, m_scev_URem(m_SCEV(LHS), m_SCEV(RHS), *this)))
1636 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1637 getZeroExtendExpr(RHS, Ty, Depth + 1));
1638 }
1639
1640 // zext(A / B) --> zext(A) / zext(B).
1641 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1642 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1643 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1644
1645 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1646 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1647 if (SA->hasNoUnsignedWrap()) {
1648 // If the addition does not unsign overflow then we can, by definition,
1649 // commute the zero extension with the addition operation.
1651 for (SCEVUse Op : SA->operands())
1652 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1653 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1654 }
1655
1656 const APInt *C, *C2;
1657 // zext (C + A)<nsw> -> (sext(C) + sext(A))<nsw> if zext (C + A)<nsw> >=s 0.
1658 // Currently the non-negative check is done manually, as isKnownNonNegative
1659 // is too expensive.
1660 if (SA->hasNoSignedWrap() &&
1662 m_scev_SMax(m_scev_APInt(C2), m_SCEV()))) &&
1663 C->isNegative() && !C->isMinSignedValue() && C2->sge(C->abs())) {
1664 assert(isKnownNonNegative(SA) && "incorrectly determined non-negative");
1665 return getAddExpr(getSignExtendExpr(SA->getOperand(0), Ty, Depth + 1),
1666 getSignExtendExpr(SA->getOperand(1), Ty, Depth + 1),
1667 SCEV::FlagNSW, Depth + 1);
1668 }
1669
1670 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1671 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1672 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1673 //
1674 // Often address arithmetics contain expressions like
1675 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1676 // This transformation is useful while proving that such expressions are
1677 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1678 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1679 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1680 if (D != 0) {
1681 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1682 const SCEV *SResidual =
1684 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1685 return getAddExpr(SZExtD, SZExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1686 Depth + 1);
1687 }
1688 }
1689 }
1690
1691 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1692 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1693 if (SM->hasNoUnsignedWrap()) {
1694 // If the multiply does not unsign overflow then we can, by definition,
1695 // commute the zero extension with the multiply operation.
1697 for (SCEVUse Op : SM->operands())
1698 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1699 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1700 }
1701
1702 // zext(2^K * (trunc X to iN)) to iM ->
1703 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1704 //
1705 // Proof:
1706 //
1707 // zext(2^K * (trunc X to iN)) to iM
1708 // = zext((trunc X to iN) << K) to iM
1709 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1710 // (because shl removes the top K bits)
1711 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1712 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1713 //
1714 const APInt *C;
1715 const SCEV *TruncRHS;
1716 if (match(SM,
1717 m_scev_Mul(m_scev_APInt(C), m_scev_Trunc(m_SCEV(TruncRHS)))) &&
1718 C->isPowerOf2()) {
1719 int NewTruncBits =
1720 getTypeSizeInBits(SM->getOperand(1)->getType()) - C->logBase2();
1721 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1722 return getMulExpr(
1723 getZeroExtendExpr(SM->getOperand(0), Ty),
1724 getZeroExtendExpr(getTruncateExpr(TruncRHS, NewTruncTy), Ty),
1725 SCEV::FlagNUW, Depth + 1);
1726 }
1727 }
1728
1729 // zext(umin(x, y)) -> umin(zext(x), zext(y))
1730 // zext(umax(x, y)) -> umax(zext(x), zext(y))
1734 for (SCEVUse Operand : MinMax->operands())
1735 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1737 return getUMinExpr(Operands);
1738 return getUMaxExpr(Operands);
1739 }
1740
1741 // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
1743 assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!");
1745 for (SCEVUse Operand : MinMax->operands())
1746 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1747 return getUMinExpr(Operands, /*Sequential*/ true);
1748 }
1749
1750 // The cast wasn't folded; create an explicit cast node.
1751 // Recompute the insert position, as it may have been invalidated.
1752 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1753 return S;
1754 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1755 Op, Ty);
1756 UniqueSCEVs.insert(S, Token);
1757 S->computeAndSetCanonical(*this);
1758 registerUser(S, Op);
1759 return S;
1760}
1761
1763 unsigned Depth) {
1764 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1765 "This is not an extending conversion!");
1766 assert(isSCEVable(Ty) &&
1767 "This is not a conversion to a SCEVable type!");
1768 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1769 Ty = getEffectiveSCEVType(Ty);
1770
1771 FoldID ID(scSignExtend, Op, Ty);
1772 if (const SCEV *S = FoldCache.lookup(ID))
1773 return S;
1774
1775 const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
1777 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1778 return S;
1779}
1780
1782 unsigned Depth) {
1783 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1784 "This is not an extending conversion!");
1785 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1786 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1787 Ty = getEffectiveSCEVType(Ty);
1788
1789 // Fold if the operand is constant.
1790 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1791 return getConstant(SC->getAPInt().sext(getTypeSizeInBits(Ty)));
1792
1793 // sext(sext(x)) --> sext(x)
1795 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1796
1797 // sext(zext(x)) --> zext(x)
1799 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1800
1801 // If the operand is an affine AddRec with the no-signed-wrap flag, the
1802 // sign-extension distributes over the recurrence.
1803 const SCEV *Start, *Step;
1804 const Loop *L;
1805 if (Depth <= Opts.scalar_evolution_max_cast_depth &&
1806 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1807 const auto *AR = cast<SCEVAddRecExpr>(Op);
1808 if (AR->hasNoSignedWrap()) {
1809 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
1810 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1811 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1812 }
1813 }
1814
1815 // Before doing any expensive analysis, check to see if we've already
1816 // computed a SCEV for this Op and Ty.
1819 ID.AddPointer(Op.getOpaqueValue());
1820 ID.AddPointer(Ty);
1822 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1823 return S;
1824 // Limit recursion depth.
1825 if (Depth > Opts.scalar_evolution_max_cast_depth) {
1826 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1827 Op, Ty);
1828 UniqueSCEVs.insert(S, Token);
1829 S->computeAndSetCanonical(*this);
1830 registerUser(S, Op);
1831 return S;
1832 }
1833
1834 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1836 // It's possible the bits taken off by the truncate were all sign bits. If
1837 // so, we should be able to simplify this further.
1838 const SCEV *X = ST->getOperand();
1840 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1841 unsigned NewBits = getTypeSizeInBits(Ty);
1842 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1843 CR.sextOrTrunc(NewBits)))
1844 return getTruncateOrSignExtend(X, Ty, Depth);
1845 }
1846
1847 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1848 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1849 if (SA->hasNoSignedWrap()) {
1850 // If the addition does not sign overflow then we can, by definition,
1851 // commute the sign extension with the addition operation.
1853 for (SCEVUse Op : SA->operands())
1854 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1855 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1856 }
1857
1858 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1859 // if D + (C - D + x + y + ...) could be proven to not signed wrap
1860 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1861 //
1862 // For instance, this will bring two seemingly different expressions:
1863 // 1 + sext(5 + 20 * %x + 24 * %y) and
1864 // sext(6 + 20 * %x + 24 * %y)
1865 // to the same form:
1866 // 2 + sext(4 + 20 * %x + 24 * %y)
1867 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1868 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1869 if (D != 0) {
1870 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1871 const SCEV *SResidual =
1873 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1874 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1875 Depth + 1);
1876 }
1877 }
1878 }
1879 // If the input value is a chrec scev, and we can prove that the value
1880 // did not overflow the old, smaller, value, we can sign extend all of the
1881 // operands (often constants). This allows analysis of something like
1882 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1883 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1884 const auto *AR = cast<SCEVAddRecExpr>(Op);
1885 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1886
1887 // The no-signed-wrap case is handled before the uniquing lookup above.
1888
1889 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1890 // Note that this serves two purposes: It filters out loops that are
1891 // simply not analyzable, and it covers the case where this code is
1892 // being called from within backedge-taken count analysis, such that
1893 // attempting to ask for the backedge-taken count would likely result
1894 // in infinite recursion. In the later case, the analysis code will
1895 // cope with a conservative value, and it will take care to purge
1896 // that value once it has finished.
1897 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1898 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1899 // Manually compute the final value for AR, checking for
1900 // overflow.
1901
1902 // Check whether the backedge-taken count can be losslessly casted to
1903 // the addrec's type. The count is always unsigned.
1904 const SCEV *CastedMaxBECount =
1905 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1906 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1907 CastedMaxBECount, MaxBECount->getType(), Depth);
1908 if (MaxBECount == RecastedMaxBECount) {
1909 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1910 // Check whether Start+Step*MaxBECount has no signed overflow.
1911 const SCEV *SMul =
1912 getMulExpr(CastedMaxBECount, Step, SCEV::FlagNone, Depth + 1);
1913 const SCEV *SAdd = getSignExtendExpr(
1914 getAddExpr(Start, SMul, SCEV::FlagNone, Depth + 1), WideTy,
1915 Depth + 1);
1916 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
1917 const SCEV *WideMaxBECount =
1918 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1919 const SCEV *OperandExtendedAdd =
1920 getAddExpr(WideStart,
1921 getMulExpr(WideMaxBECount,
1922 getSignExtendExpr(Step, WideTy, Depth + 1),
1923 SCEV::FlagNone, Depth + 1),
1924 SCEV::FlagNone, Depth + 1);
1925 if (SAdd == OperandExtendedAdd) {
1926 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1927 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
1928 // Return the expression with the addrec on the outside.
1929 Start =
1931 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1932 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1933 }
1934 // Similar to above, only this time treat the step value as unsigned.
1935 // This covers loops that count up with an unsigned step.
1936 OperandExtendedAdd =
1937 getAddExpr(WideStart,
1938 getMulExpr(WideMaxBECount,
1939 getZeroExtendExpr(Step, WideTy, Depth + 1),
1940 SCEV::FlagNone, Depth + 1),
1941 SCEV::FlagNone, Depth + 1);
1942 if (SAdd == OperandExtendedAdd) {
1943 // If AR wraps around then
1944 //
1945 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
1946 // => SAdd != OperandExtendedAdd
1947 //
1948 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1949 // (SAdd == OperandExtendedAdd => AR is NW)
1950
1951 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1952
1953 // Return the expression with the addrec on the outside.
1954 Start =
1956 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1957 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1958 }
1959 }
1960 }
1961
1962 auto NewFlags = proveNoSignedWrapViaInduction(AR);
1963 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1964 if (AR->hasNoSignedWrap()) {
1965 // Same as nsw case above - duplicated here to avoid a compile time
1966 // issue. It's not clear that the order of checks does matter, but
1967 // it's one of two issue possible causes for a change which was
1968 // reverted. Be conservative for the moment.
1969 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
1970 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1971 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1972 }
1973
1974 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
1975 // if D + (C - D + Step * n) could be proven to not signed wrap
1976 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1977 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1978 const APInt &C = SC->getAPInt();
1979 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1980 if (D != 0) {
1981 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1982 const SCEV *SResidual =
1983 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1984 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1985 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1986 Depth + 1);
1987 }
1988 }
1989
1990 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1991 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
1992 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
1993 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1994 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1995 }
1996 }
1997
1998 // If the input value is provably positive and we could not simplify
1999 // away the sext build a zext instead.
2001 return getZeroExtendExpr(Op, Ty, Depth + 1);
2002
2003 // sext(smin(x, y)) -> smin(sext(x), sext(y))
2004 // sext(smax(x, y)) -> smax(sext(x), sext(y))
2008 for (SCEVUse Operand : MinMax->operands())
2009 Operands.push_back(getSignExtendExpr(Operand, Ty));
2011 return getSMinExpr(Operands);
2012 return getSMaxExpr(Operands);
2013 }
2014
2015 // The cast wasn't folded; create an explicit cast node.
2016 // Recompute the insert position, as it may have been invalidated.
2017 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
2018 return S;
2019 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2020 Op, Ty);
2021 UniqueSCEVs.insert(S, Token);
2022 S->computeAndSetCanonical(*this);
2023 registerUser(S, Op);
2024 return S;
2025}
2026
2028 switch (Kind) {
2029 case scTruncate:
2030 return getTruncateExpr(Op, Ty);
2031 case scZeroExtend:
2032 return getZeroExtendExpr(Op, Ty);
2033 case scSignExtend:
2034 return getSignExtendExpr(Op, Ty);
2035 case scPtrToAddr: {
2036 const SCEV *Expr = getPtrToAddrExpr(Op);
2037 assert(Expr->getType() == Ty && "requested type must match");
2038 return Expr;
2039 }
2040 default:
2041 llvm_unreachable("Not a SCEV cast expression!");
2042 }
2043}
2044
2045/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2046/// unspecified bits out to the given type.
2048 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2049 "This is not an extending conversion!");
2050 assert(isSCEVable(Ty) &&
2051 "This is not a conversion to a SCEVable type!");
2052 Ty = getEffectiveSCEVType(Ty);
2053
2054 // Sign-extend negative constants.
2055 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2056 if (SC->getAPInt().isNegative())
2057 return getSignExtendExpr(Op, Ty);
2058
2059 // Peel off a truncate cast.
2061 const SCEV *NewOp = T->getOperand();
2062 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2063 return getAnyExtendExpr(NewOp, Ty);
2064 return getTruncateOrNoop(NewOp, Ty);
2065 }
2066
2067 // Next try a zext cast. If the cast is folded, use it.
2068 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2069 if (!isa<SCEVZeroExtendExpr>(ZExt))
2070 return ZExt;
2071
2072 // Next try a sext cast. If the cast is folded, use it.
2073 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2074 if (!isa<SCEVSignExtendExpr>(SExt))
2075 return SExt;
2076
2077 // Force the cast to be folded into the operands of an addrec.
2078 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2080 for (const SCEV *Op : AR->operands())
2081 Ops.push_back(getAnyExtendExpr(Op, Ty));
2082 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2083 }
2084
2085 // If the expression is obviously signed, use the sext cast value.
2086 if (isa<SCEVSMaxExpr>(Op))
2087 return SExt;
2088
2089 // Absent any other information, use the zext cast value.
2090 return ZExt;
2091}
2092
2093/// Process the given Ops list, which is a list of operands to be added under
2094/// the given scale, update the given map. This is a helper function for
2095/// getAddRecExpr. As an example of what it does, given a sequence of operands
2096/// that would form an add expression like this:
2097///
2098/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2099///
2100/// where A and B are constants, update the map with these values:
2101///
2102/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2103///
2104/// and add 13 + A*B*29 to AccumulatedConstant.
2105/// This will allow getAddRecExpr to produce this:
2106///
2107/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2108///
2109/// This form often exposes folding opportunities that are hidden in
2110/// the original operand list.
2111///
2112/// Return true iff it appears that any interesting folding opportunities
2113/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2114/// the common case where no interesting opportunities are present, and
2115/// is also used as a check to avoid infinite recursion.
2116static bool
2119 APInt &AccumulatedConstant, ArrayRef<SCEVUse> Ops,
2120 const APInt &Scale, ScalarEvolution &SE) {
2121 bool Interesting = false;
2122
2123 // Iterate over the add operands. They are sorted, with constants first.
2124 unsigned i = 0;
2125 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2126 ++i;
2127 // Pull a buried constant out to the outside.
2128 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2129 Interesting = true;
2130 AccumulatedConstant += Scale * C->getAPInt();
2131 }
2132
2133 // Next comes everything else. We're especially interested in multiplies
2134 // here, but they're in the middle, so just visit the rest with one loop.
2135 for (; i != Ops.size(); ++i) {
2137 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2138 APInt NewScale =
2139 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2140 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2141 // A multiplication of a constant with another add; recurse.
2142 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2143 Interesting |= CollectAddOperandsWithScales(
2144 M, NewOps, AccumulatedConstant, Add->operands(), NewScale, SE);
2145 } else {
2146 // A multiplication of a constant with some other value. Update
2147 // the map.
2148 SmallVector<SCEVUse, 4> MulOps(drop_begin(Mul->operands()));
2149 const SCEV *Key = SE.getMulExpr(MulOps)->getCanonical();
2150 auto Pair = M.insert({Key, NewScale});
2151 if (Pair.second) {
2152 NewOps.push_back(Pair.first->first);
2153 } else {
2154 Pair.first->second += NewScale;
2155 // The map already had an entry for this value, which may indicate
2156 // a folding opportunity.
2157 Interesting = true;
2158 }
2159 }
2160 } else {
2161 // An ordinary operand. Update the map.
2162 auto Pair = M.insert({Ops[i]->getCanonical(), Scale});
2163 if (Pair.second) {
2164 NewOps.push_back(Pair.first->first);
2165 } else {
2166 Pair.first->second += Scale;
2167 // The map already had an entry for this value, which may indicate
2168 // a folding opportunity.
2169 Interesting = true;
2170 }
2171 }
2172 }
2173
2174 return Interesting;
2175}
2176
2178 const SCEV *LHS, const SCEV *RHS,
2179 const Instruction *CtxI) {
2180 auto Operation = [this, BinOp](SCEVUse L, SCEVUse R) -> const SCEV * {
2181 switch (BinOp) {
2182 default:
2183 llvm_unreachable("Unsupported binary op");
2184 case Instruction::Add:
2185 return getAddExpr(L, R);
2186 case Instruction::Sub:
2187 return getMinusSCEV(L, R);
2188 case Instruction::Mul:
2189 return getMulExpr(L, R);
2190 }
2191 };
2192
2193 const SCEV *(ScalarEvolution::*Extension)(SCEVUse, Type *, unsigned) =
2196
2197 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2198 auto *NarrowTy = cast<IntegerType>(LHS->getType());
2199 auto *WideTy =
2200 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2201
2202 const SCEV *A = (this->*Extension)(Operation(LHS, RHS), WideTy, 0);
2203 const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2204 const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2205 const SCEV *B = Operation(LHSB, RHSB);
2206 if (A == B)
2207 return true;
2208 // Can we use context to prove the fact we need?
2209 if (!CtxI)
2210 return false;
2211 // TODO: Support mul.
2212 if (BinOp == Instruction::Mul)
2213 return false;
2214 auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2215 // TODO: Lift this limitation.
2216 if (!RHSC)
2217 return false;
2218 APInt C = RHSC->getAPInt();
2219 unsigned NumBits = C.getBitWidth();
2220 bool IsSub = (BinOp == Instruction::Sub);
2221 bool IsNegativeConst = (Signed && C.isNegative());
2222 // Compute the direction and magnitude by which we need to check overflow.
2223 bool OverflowDown = IsSub ^ IsNegativeConst;
2224 APInt Magnitude = C;
2225 if (IsNegativeConst) {
2226 if (C == APInt::getSignedMinValue(NumBits))
2227 // TODO: SINT_MIN on inversion gives the same negative value, we don't
2228 // want to deal with that.
2229 return false;
2230 Magnitude = -C;
2231 }
2232
2234 if (OverflowDown) {
2235 // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2236 APInt Min = Signed ? APInt::getSignedMinValue(NumBits)
2237 : APInt::getMinValue(NumBits);
2238 APInt Limit = Min + Magnitude;
2239 return isKnownPredicateAt(Pred, getConstant(Limit), LHS, CtxI);
2240 } else {
2241 // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2242 APInt Max = Signed ? APInt::getSignedMaxValue(NumBits)
2243 : APInt::getMaxValue(NumBits);
2244 APInt Limit = Max - Magnitude;
2245 return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2246 }
2247}
2248
2250 const OverflowingBinaryOperator *OBO) {
2251 // It cannot be done any better.
2252 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2253 return std::nullopt;
2254
2256
2257 if (OBO->hasNoUnsignedWrap())
2259 if (OBO->hasNoSignedWrap())
2261
2262 bool Deduced = false;
2263
2265 const SCEV *LHS = getSCEV(OBO->getOperand(0));
2266 const SCEV *RHS = getSCEV(OBO->getOperand(1));
2267
2268 bool CanUseNSW = true;
2269 const APInt *ShiftAmt;
2270 // Treat `shl %a, C` as `mul %a, 1 << C`.
2271 if (match(OBO, m_Shl(m_Value(), m_APInt(ShiftAmt)))) {
2272 unsigned BitWidth = ShiftAmt->getBitWidth();
2273 if (ShiftAmt->uge(BitWidth))
2274 return std::nullopt;
2275 // NSW only transfers if the shift amount is < BitWidth - 1, as INT_MIN * -1
2276 // overflows.
2277 CanUseNSW = ShiftAmt->ult(BitWidth - 1);
2278 Opcode = Instruction::Mul;
2280 } else if (Opcode != Instruction::Add && Opcode != Instruction::Sub &&
2281 Opcode != Instruction::Mul) {
2282 return std::nullopt;
2283 }
2284
2285 const Instruction *CtxI =
2286 Opts.scalar_evolution_use_context_for_no_wrap_flag_strenghening
2288 : nullptr;
2289 if (!OBO->hasNoUnsignedWrap() &&
2290 willNotOverflow(Opcode, /* Signed */ false, LHS, RHS, CtxI)) {
2292 Deduced = true;
2293 }
2294
2295 if (CanUseNSW && !OBO->hasNoSignedWrap() &&
2296 willNotOverflow(Opcode, /* Signed */ true, LHS, RHS, CtxI)) {
2298 Deduced = true;
2299 }
2300
2301 if (Deduced)
2302 return Flags;
2303 return std::nullopt;
2304}
2305
2306// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2307// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2308// can't-overflow flags for the operation if possible.
2311 using namespace std::placeholders;
2312
2313 using OBO = OverflowingBinaryOperator;
2314
2315 bool CanAnalyze =
2317 (void)CanAnalyze;
2318 assert(CanAnalyze && "don't call from other places!");
2319
2320 SCEVFlags SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2321 SCEVFlags SignOrUnsignWrap =
2322 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2323
2324 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2325 auto IsKnownNonNegative = [&](SCEVUse U) {
2326 return SE->isKnownNonNegative(U);
2327 };
2328
2329 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2330 Flags = ScalarEvolution::setFlags(Flags, SignOrUnsignMask);
2331
2332 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2333
2334 if (SignOrUnsignWrap != SignOrUnsignMask &&
2335 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2336 isa<SCEVConstant>(Ops[0])) {
2337
2338 auto Opcode = [&] {
2339 switch (Type) {
2340 case scAddExpr:
2341 return Instruction::Add;
2342 case scMulExpr:
2343 return Instruction::Mul;
2344 default:
2345 llvm_unreachable("Unexpected SCEV op.");
2346 }
2347 }();
2348
2349 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2350
2351 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2352 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2353 auto NSWRegion =
2354 ConstantRange::makeExactNoWrapRegion(Opcode, C, OBO::NoSignedWrap);
2355 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2357 }
2358
2359 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2360 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2361 auto NUWRegion =
2362 ConstantRange::makeExactNoWrapRegion(Opcode, C, OBO::NoUnsignedWrap);
2363 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2365 }
2366 }
2367
2368 // <0,+,nonnegative><nw> is also nuw
2369 // TODO: Add corresponding nsw case
2371 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2372 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2374
2375 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2377 Ops.size() == 2) {
2378 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2379 if (UDiv->getOperand(1) == Ops[1])
2381 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2382 if (UDiv->getOperand(1) == Ops[0])
2384 }
2385
2386 return Flags;
2387}
2388
2390 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2391}
2392
2393/// Get a canonical add expression, or something simpler if possible.
2395 SCEVFlagsPair Flags, unsigned Depth) {
2396 SCEVFlags ExprFlags = Flags.ExprFlags;
2397 SCEVFlags UseFlags = Flags.UseFlags;
2398 assert(!(ExprFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2399 "only nuw or nsw allowed");
2400 assert(!(UseFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2401 "only nuw or nsw allowed");
2402 assert(!Ops.empty() && "Cannot get empty add!");
2403 if (Ops.size() == 1) return Ops[0];
2404#ifndef NDEBUG
2405 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2406 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2407 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2408 "SCEVAddExpr operand types don't match!");
2409 unsigned NumPtrs = count_if(
2410 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2411 assert(NumPtrs <= 1 && "add has at most one pointer operand");
2412#endif
2413
2415 Opts, *this, LI, DT, Ops,
2416 [](const APInt &C1, const APInt &C2) { return C1 + C2; },
2417 [](const APInt &C) { return C.isZero(); }, // identity
2418 [](const APInt &C) { return false; }); // absorber
2419 if (Folded)
2420 return Folded;
2421
2422#ifndef NDEBUG
2423 // Keep track of operands after constant folding, for verification when adding
2424 // use-specific flags.
2425 const SmallVector<SCEVUse, 8> OrigOps(Ops.begin(), Ops.end());
2426#endif
2427
2428 unsigned Idx = isa<SCEVConstant>(Ops[0]) ? 1 : 0;
2429
2430 // Delay expensive flag strengthening until necessary.
2431 auto ComputeFlags = [this, ExprFlags](ArrayRef<SCEVUse> Ops) {
2432 return StrengthenNoWrapFlags(this, scAddExpr, Ops, ExprFlags);
2433 };
2434
2435 // Limit recursion calls depth.
2436 if (Depth > Opts.scalar_evolution_max_arith_depth ||
2437 hasHugeExpression(Opts, Ops))
2438 return {getOrCreateAddExpr(Ops, ComputeFlags(Ops)), UseFlags};
2439
2440 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2441 // Don't strengthen flags if we have no new information.
2442 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2443 if (Add->getNoWrapFlags(ExprFlags) != ExprFlags)
2444 Add->setNoWrapFlags(ComputeFlags(Ops));
2445 return {S, UseFlags};
2446 }
2447
2448 // Okay, check to see if the same value occurs in the operand list more than
2449 // once. If so, merge them together into an multiply expression. Since we
2450 // sorted the list, these values are required to be adjacent.
2451 Type *Ty = Ops[0]->getType();
2452 bool FoundMatch = false;
2453 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2454 if (SCEVUse Op = SCEVUse::getCommon(Ops[i], Ops[i + 1])) {
2455 // X + Y + Y --> X + Y*2
2456 // Scan ahead to count how many equal operands there are.
2457 unsigned Count = 2;
2458 for (; i + Count != e; ++Count) {
2459 SCEVUse Common = SCEVUse::getCommon(Op, Ops[i + Count]);
2460 if (!Common)
2461 break;
2462 Op = Common;
2463 }
2464 // Merge the values into a multiply.
2465 SCEVUse Scale = getConstant(Ty, Count);
2466 SCEVUse Mul = getMulExpr(Scale, Op, SCEV::FlagNone, Depth + 1);
2467 if (Ops.size() == Count)
2468 return Mul;
2469 Ops[i] = Mul;
2470 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2471 --i; e -= Count - 1;
2472 FoundMatch = true;
2473 }
2474 if (FoundMatch)
2475 return getAddExpr(Ops, ExprFlags, Depth + 1);
2476
2477 // Check for truncates. If all the operands are truncated from the same
2478 // type, see if factoring out the truncate would permit the result to be
2479 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2480 // if the contents of the resulting outer trunc fold to something simple.
2481 auto FindTruncSrcType = [&]() -> Type * {
2482 // We're ultimately looking to fold an addrec of truncs and muls of only
2483 // constants and truncs, so if we find any other types of SCEV
2484 // as operands of the addrec then we bail and return nullptr here.
2485 // Otherwise, we return the type of the operand of a trunc that we find.
2486 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2487 return T->getOperand()->getType();
2488 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2489 SCEVUse LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2490 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2491 return T->getOperand()->getType();
2492 }
2493 return nullptr;
2494 };
2495 if (auto *SrcType = FindTruncSrcType()) {
2496 SmallVector<SCEVUse, 8> LargeOps;
2497 bool Ok = true;
2498 // Check all the operands to see if they can be represented in the
2499 // source type of the truncate.
2500 for (const SCEV *Op : Ops) {
2502 if (T->getOperand()->getType() != SrcType) {
2503 Ok = false;
2504 break;
2505 }
2506 LargeOps.push_back(T->getOperand());
2507 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Op)) {
2508 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2509 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Op)) {
2510 SmallVector<SCEVUse, 8> LargeMulOps;
2511 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2512 if (const SCEVTruncateExpr *T =
2513 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2514 if (T->getOperand()->getType() != SrcType) {
2515 Ok = false;
2516 break;
2517 }
2518 LargeMulOps.push_back(T->getOperand());
2519 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2520 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2521 } else {
2522 Ok = false;
2523 break;
2524 }
2525 }
2526 if (Ok)
2527 LargeOps.push_back(
2528 getMulExpr(LargeMulOps, SCEV::FlagNone, Depth + 1));
2529 } else {
2530 Ok = false;
2531 break;
2532 }
2533 }
2534 if (Ok) {
2535 // Evaluate the expression in the larger type.
2536 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagNone, Depth + 1);
2537 // If it folds to something simple, use it. Otherwise, don't.
2538 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2539 return getTruncateExpr(Fold, Ty);
2540 }
2541 }
2542
2543 if (Ops.size() == 2) {
2544 // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2545 // C2 can be folded in a way that allows retaining wrapping flags of (X +
2546 // C1).
2547 const SCEV *A = Ops[0];
2548 const SCEV *B = Ops[1];
2549 auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2550 auto *C = dyn_cast<SCEVConstant>(A);
2551 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2552 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2553 auto C2 = C->getAPInt();
2554 SCEVFlags PreservedFlags = SCEV::FlagNone;
2555
2556 APInt ConstAdd = C1 + C2;
2557 auto AddFlags = AddExpr->getNoWrapFlags();
2558 // Adding a smaller constant is NUW if the original AddExpr was NUW.
2560 ConstAdd.ule(C1)) {
2561 PreservedFlags =
2563 }
2564
2565 // Adding a constant with the same sign and small magnitude is NSW, if the
2566 // original AddExpr was NSW.
2568 C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2569 ConstAdd.abs().ule(C1.abs())) {
2570 PreservedFlags =
2572 }
2573
2574 if (PreservedFlags != SCEV::FlagNone) {
2575 SmallVector<SCEVUse, 4> NewOps(AddExpr->operands());
2576 NewOps[0] = getConstant(ConstAdd);
2577 return getAddExpr(NewOps, PreservedFlags);
2578 }
2579 }
2580
2581 // Try to push the constant operand into a ZExt: A + zext (-A + B) -> zext
2582 // (B), if trunc (A) + -A + B does not unsigned-wrap.
2583 const SCEVAddExpr *InnerAdd;
2584 if (match(B, m_scev_ZExt(m_scev_Add(InnerAdd)))) {
2585 const SCEV *NarrowA = getTruncateExpr(A, InnerAdd->getType());
2586 if (NarrowA == getNegativeSCEV(InnerAdd->getOperand(0)) &&
2587 getZeroExtendExpr(NarrowA, B->getType()) == A &&
2588 hasFlags(StrengthenNoWrapFlags(this, scAddExpr, {NarrowA, InnerAdd},
2590 SCEV::FlagNUW)) {
2591 return getZeroExtendExpr(getAddExpr(NarrowA, InnerAdd), B->getType());
2592 }
2593 }
2594 }
2595
2596 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2597 const SCEV *Y;
2598 if (Ops.size() == 2 &&
2599 match(Ops[0],
2601 m_scev_URem(m_scev_Specific(Ops[1]), m_SCEV(Y), *this))))
2602 return getMulExpr(Y, getUDivExpr(Ops[1], Y));
2603
2604 // Skip past any other cast SCEVs.
2605 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2606 ++Idx;
2607
2608 // If there are add operands they would be next.
2609 if (Idx < Ops.size()) {
2610 bool DeletedAdd = false;
2611 // If the original flags and all inlined SCEVAddExprs are NUW, use the
2612 // common NUW flag for expression after inlining. Other flags cannot be
2613 // preserved, because they may depend on the original order of operations.
2614 SCEVFlags CommonFlags = maskFlags(ExprFlags, SCEV::FlagNUW);
2615 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2616 if (Ops.size() > Opts.scev_addops_inline_threshold ||
2617 Add->getNumOperands() > Opts.scev_addops_inline_threshold)
2618 break;
2619 // If we have an add, expand the add operands onto the end of the operands
2620 // list.
2621 Ops.erase(Ops.begin()+Idx);
2622 append_range(Ops, Add->operands());
2623 DeletedAdd = true;
2624 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2625 }
2626
2627 // If we deleted at least one add, we added operands to the end of the list,
2628 // and they are not necessarily sorted. Recurse to resort and resimplify
2629 // any operands we just acquired.
2630 if (DeletedAdd)
2631 return getAddExpr(Ops, CommonFlags, Depth + 1);
2632 }
2633
2634 // Skip over the add expression until we get to a multiply.
2635 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2636 ++Idx;
2637
2638 // Check to see if there are any folding opportunities present with
2639 // operands multiplied by constant values.
2640 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2641 uint64_t BitWidth = getTypeSizeInBits(Ty);
2644 APInt AccumulatedConstant(BitWidth, 0);
2645 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2646 Ops, APInt(BitWidth, 1), *this)) {
2647 struct APIntCompare {
2648 bool operator()(const APInt &LHS, const APInt &RHS) const {
2649 return LHS.ult(RHS);
2650 }
2651 };
2652
2653 // Some interesting folding opportunity is present, so its worthwhile to
2654 // re-generate the operands list. Group the operands by constant scale,
2655 // to avoid multiplying by the same constant scale multiple times.
2656 std::map<APInt, SmallVector<SCEVUse, 4>, APIntCompare> MulOpLists;
2657 for (SCEVUse NewOp : NewOps)
2658 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2659 // Re-generate the operands list.
2660 Ops.clear();
2661 if (AccumulatedConstant != 0)
2662 Ops.push_back(getConstant(AccumulatedConstant));
2663 for (auto &MulOp : MulOpLists) {
2664 if (MulOp.first == 1) {
2665 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagNone, Depth + 1));
2666 } else if (MulOp.first != 0) {
2667 Ops.push_back(
2668 getMulExpr(getConstant(MulOp.first),
2669 getAddExpr(MulOp.second, SCEV::FlagNone, Depth + 1),
2670 SCEV::FlagNone, Depth + 1));
2671 }
2672 }
2673 if (Ops.empty())
2674 return getZero(Ty);
2675 if (Ops.size() == 1)
2676 return Ops[0];
2677 return getAddExpr(Ops, SCEV::FlagNone, Depth + 1);
2678 }
2679 }
2680
2681 // Given a SCEVMulExpr and an operand index, return the product of all
2682 // operands except the one at OpIdx.
2683 auto StripFactor = [&](const SCEVMulExpr *M, unsigned OpIdx) -> SCEVUse {
2684 if (M->getNumOperands() == 2)
2685 return M->getOperand(OpIdx == 0);
2686 SmallVector<SCEVUse, 4> Remaining(M->operands().take_front(OpIdx));
2687 append_range(Remaining, M->operands().drop_front(OpIdx + 1));
2688 return getMulExpr(Remaining, SCEV::FlagNone, Depth + 1);
2689 };
2690
2691 // If we are adding something to a multiply expression, make sure the
2692 // something is not already an operand of the multiply. If so, merge it into
2693 // the multiply.
2694 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2695 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2696 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2697 // Scan all terms to find every occurrence of common factor MulOpSCEV
2698 // and fold them in one shot:
2699 // A1*X + A2*X + ... + An*X --> X * (A1 + A2 + ... + An)
2700 SCEVUse MulOpSCEV = Mul->getOperand(MulOp);
2701 if (isa<SCEVConstant>(MulOpSCEV))
2702 continue;
2703
2704 // Cofactors: 1 for bare addends matching MulOpSCEV, or the
2705 // remaining product for multiply terms containing MulOpSCEV.
2706 SmallVector<SCEVUse, 4> Cofactors;
2707 SmallVector<unsigned, 4> DeadIndices;
2708 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) {
2709 if (SCEVUse Common = SCEVUse::getCommon(MulOpSCEV, Ops[AddOp])) {
2710 // W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2711 MulOpSCEV = Common;
2712 Cofactors.push_back(getOne(Ty));
2713 DeadIndices.push_back(AddOp);
2714 continue;
2715 }
2716
2717 if (AddOp <= Idx || !isa<SCEVMulExpr>(Ops[AddOp]))
2718 continue;
2719
2720 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[AddOp]);
2721 for (unsigned OMulOp = 0, OE = OtherMul->getNumOperands(); OMulOp != OE;
2722 ++OMulOp) {
2723 if (SCEVUse Common =
2724 SCEVUse::getCommon(MulOpSCEV, OtherMul->getOperand(OMulOp))) {
2725 // (A*B*C) + (A*D*E) --> A * (B*C + D*E)
2726 MulOpSCEV = Common;
2727 Cofactors.push_back(StripFactor(OtherMul, OMulOp));
2728 DeadIndices.push_back(AddOp);
2729 break;
2730 }
2731 }
2732 }
2733
2734 // Fold all collected cofactors with the anchor multiply's cofactor:
2735 // MulOpSCEV * (Cofactor_1 + ... + Cofactor_n + AnchorCofactor)
2736 if (!Cofactors.empty()) {
2737 Cofactors.push_back(StripFactor(Mul, MulOp));
2738
2739 SCEVUse InnerSum = getAddExpr(Cofactors, SCEV::FlagNone, Depth + 1);
2740 SCEVUse OuterMul =
2741 getMulExpr(MulOpSCEV, InnerSum, SCEV::FlagNone, Depth + 1);
2742
2743 // DeadIndices does not include Idx (the anchor), hence +1.
2744 if (Ops.size() == DeadIndices.size() + 1)
2745 return OuterMul;
2746
2747 // Erase Ops[Idx] first, then erase DeadIndices in reverse order.
2748 // The -1 adjustment accounts for the shift from removing Idx;
2749 // reverse order means each erasure only shifts later positions,
2750 // which have already been processed.
2751 Ops.erase(Ops.begin() + Idx);
2752 for (unsigned Dead : reverse(DeadIndices))
2753 Ops.erase(Ops.begin() + (Dead > Idx ? Dead - 1 : Dead));
2754
2755 Ops.push_back(OuterMul);
2756 return getAddExpr(Ops, SCEV::FlagNone, Depth + 1);
2757 }
2758 }
2759 }
2760
2761 // If there are any add recurrences in the operands list, see if any other
2762 // added values are loop invariant. If so, we can fold them into the
2763 // recurrence.
2764 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2765 ++Idx;
2766
2767 // Scan over all recurrences, trying to fold loop invariants into them.
2768 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2769 // Scan all of the other operands to this add and add them to the vector if
2770 // they are loop invariant w.r.t. the recurrence.
2772 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2773 const Loop *AddRecLoop = AddRec->getLoop();
2774 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2775 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2776 LIOps.push_back(Ops[i]);
2777 Ops.erase(Ops.begin()+i);
2778 --i; --e;
2779 }
2780
2781 // If we found some loop invariants, fold them into the recurrence.
2782 if (!LIOps.empty()) {
2783 // Compute nowrap flags for the addition of the loop-invariant ops and
2784 // the addrec. Temporarily push it as an operand for that purpose. These
2785 // flags are valid in the scope of the addrec only.
2786 LIOps.push_back(AddRec);
2787 SCEVFlags Flags = ComputeFlags(LIOps);
2788 LIOps.pop_back();
2789
2790 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2791 LIOps.push_back(AddRec->getStart());
2792
2793 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2794
2795 // It is not in general safe to propagate flags valid on an add within
2796 // the addrec scope to one outside it. We must prove that the inner
2797 // scope is guaranteed to execute if the outer one does to be able to
2798 // safely propagate. We know the program is undefined if poison is
2799 // produced on the inner scoped addrec. We also know that *for this use*
2800 // the outer scoped add can't overflow (because of the flags we just
2801 // computed for the inner scoped add) without the program being undefined.
2802 // Proving that entry to the outer scope neccesitates entry to the inner
2803 // scope, thus proves the program undefined if the flags would be violated
2804 // in the outer scope.
2805 SCEVFlags AddFlags = Flags;
2806 if (AddFlags != SCEV::FlagNone) {
2807 auto *DefI = getDefiningScopeBound(LIOps);
2808 auto *ReachI = &*AddRecLoop->getHeader()->begin();
2809 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2810 AddFlags = SCEV::FlagNone;
2811 }
2812 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2813
2814 // Build the new addrec. Propagate the NUW and NSW flags if both the
2815 // outer add and the inner addrec are guaranteed to have no overflow.
2816 // Always propagate NW.
2817 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2818 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2819
2820 // If all of the other operands were loop invariant, we are done.
2821 if (Ops.size() == 1) return NewRec;
2822
2823 // Otherwise, add the folded AddRec by the non-invariant parts.
2824 for (unsigned i = 0;; ++i)
2825 if (Ops[i] == AddRec) {
2826 Ops[i] = NewRec;
2827 break;
2828 }
2829 return getAddExpr(Ops, SCEV::FlagNone, Depth + 1);
2830 }
2831
2832 // Okay, if there weren't any loop invariants to be folded, check to see if
2833 // there are multiple AddRec's with the same loop induction variable being
2834 // added together. If so, we can fold them.
2835 for (unsigned OtherIdx = Idx+1;
2836 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2837 ++OtherIdx) {
2838 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2839 // so that the 1st found AddRecExpr is dominated by all others.
2840 assert(DT.dominates(
2841 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2842 AddRec->getLoop()->getHeader()) &&
2843 "AddRecExprs are not sorted in reverse dominance order?");
2844 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2845 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2846 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2847 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2848 ++OtherIdx) {
2849 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2850 if (OtherAddRec->getLoop() == AddRecLoop) {
2851 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2852 i != e; ++i) {
2853 if (i >= AddRecOps.size()) {
2854 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
2855 break;
2856 }
2857 AddRecOps[i] =
2858 getAddExpr(AddRecOps[i], OtherAddRec->getOperand(i),
2859 SCEV::FlagNone, Depth + 1);
2860 }
2861 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2862 }
2863 }
2864 // Step size has changed, so we cannot guarantee no self-wraparound.
2865 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagNone);
2866 return getAddExpr(Ops, SCEV::FlagNone, Depth + 1);
2867 }
2868 }
2869
2870 // Otherwise couldn't fold anything into this recurrence. Move onto the
2871 // next one.
2872 }
2873
2874 // Okay, it looks like we really DO need an add expr. Check to see if we
2875 // already have one, otherwise create a new one.
2876 assert((UseFlags == SCEV::FlagNone || equal(OrigOps, Ops)) &&
2877 "Tried to add SCEVUse flags after operands changed");
2878 return {getOrCreateAddExpr(Ops, ComputeFlags(Ops)), UseFlags};
2879}
2880
2881const SCEV *ScalarEvolution::getOrCreateAddExpr(ArrayRef<SCEVUse> Ops,
2882 SCEVFlags Flags) {
2885 for (SCEVUse Op : Ops)
2886 ID.AddPointer(Op.getOpaqueValue());
2888 SCEVAddExpr *S = static_cast<SCEVAddExpr *>(UniqueSCEVs.lookup(ID, Token));
2889 if (!S) {
2890 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
2892 S = new (SCEVAllocator)
2893 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2894 UniqueSCEVs.insert(S, Token);
2895 S->computeAndSetCanonical(*this);
2896 registerUser(S, Ops);
2897 }
2898 S->setNoWrapFlags(Flags);
2899 return S;
2900}
2901
2902const SCEV *ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<SCEVUse> Ops,
2903 const Loop *L,
2904 SCEVFlags Flags) {
2905 FoldingSetNodeID ID;
2906 ID.AddInteger(scAddRecExpr);
2907 for (SCEVUse Op : Ops)
2908 ID.AddPointer(Op.getOpaqueValue());
2909 ID.AddPointer(L);
2910 FoldingSetInsertToken Token;
2911 SCEVAddRecExpr *S =
2912 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.lookup(ID, Token));
2913 if (!S) {
2914 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
2916 S = new (SCEVAllocator)
2917 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2918 UniqueSCEVs.insert(S, Token);
2919 S->computeAndSetCanonical(*this);
2920 LoopUsers[L].push_back(S);
2921 registerUser(S, Ops);
2922 }
2923 setNoWrapFlags(S, Flags);
2924 return S;
2925}
2926
2927const SCEV *ScalarEvolution::getOrCreateMulExpr(ArrayRef<SCEVUse> Ops,
2928 SCEVFlags Flags) {
2929 FoldingSetNodeID ID;
2930 ID.AddInteger(scMulExpr);
2931 for (SCEVUse Op : Ops)
2932 ID.AddPointer(Op.getOpaqueValue());
2933 FoldingSetInsertToken Token;
2934 SCEVMulExpr *S = static_cast<SCEVMulExpr *>(UniqueSCEVs.lookup(ID, Token));
2935 if (!S) {
2936 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
2938 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2939 O, Ops.size());
2940 UniqueSCEVs.insert(S, Token);
2941 S->computeAndSetCanonical(*this);
2942 registerUser(S, Ops);
2943 }
2944 S->setNoWrapFlags(Flags);
2945 return S;
2946}
2947
2948const SCEV *ScalarEvolution::getOrCreateUDivExpr(SCEVUse LHS, SCEVUse RHS) {
2949 FoldingSetNodeID ID;
2950 ID.AddInteger(scUDivExpr);
2951 ID.AddPointer(LHS.getOpaqueValue());
2952 ID.AddPointer(RHS.getOpaqueValue());
2953 FoldingSetInsertToken Token;
2954 SCEV *S = UniqueSCEVs.lookup(ID, Token);
2955 if (!S) {
2956 S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), LHS, RHS);
2957 UniqueSCEVs.insert(S, Token);
2958 S->computeAndSetCanonical(*this);
2959 registerUser(S, {LHS, RHS});
2960 }
2961 return S;
2962}
2963
2964static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2965 uint64_t k = i*j;
2966 if (j > 1 && k / j != i) Overflow = true;
2967 return k;
2968}
2969
2970/// Compute the result of "n choose k", the binomial coefficient. If an
2971/// intermediate computation overflows, Overflow will be set and the return will
2972/// be garbage. Overflow is not cleared on absence of overflow.
2973static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2974 // We use the multiplicative formula:
2975 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2976 // At each iteration, we take the n-th term of the numeral and divide by the
2977 // (k-n)th term of the denominator. This division will always produce an
2978 // integral result, and helps reduce the chance of overflow in the
2979 // intermediate computations. However, we can still overflow even when the
2980 // final result would fit.
2981
2982 if (n == 0 || n == k) return 1;
2983 if (k > n) return 0;
2984
2985 if (k > n/2)
2986 k = n-k;
2987
2988 uint64_t r = 1;
2989 for (uint64_t i = 1; i <= k; ++i) {
2990 r = umul_ov(r, n-(i-1), Overflow);
2991 r /= i;
2992 }
2993 return r;
2994}
2995
2996/// Determine if any of the operands in this SCEV are a constant or if
2997/// any of the add or multiply expressions in this SCEV contain a constant.
2998static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2999 struct FindConstantInAddMulChain {
3000 bool FoundConstant = false;
3001
3002 bool follow(const SCEV *S) {
3003 FoundConstant |= isa<SCEVConstant>(S);
3004 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3005 }
3006
3007 bool isDone() const {
3008 return FoundConstant;
3009 }
3010 };
3011
3012 FindConstantInAddMulChain F;
3014 ST.visitAll(StartExpr);
3015 return F.FoundConstant;
3016}
3017
3018/// Get a canonical multiply expression, or something simpler if possible.
3020 SCEVFlagsPair Flags, unsigned Depth) {
3021 SCEVFlags ExprFlags = Flags.ExprFlags;
3022 SCEVFlags UseFlags = Flags.UseFlags;
3023 assert(ExprFlags == maskFlags(ExprFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3024 "only nuw or nsw allowed");
3025 assert(UseFlags == maskFlags(UseFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3026 "only nuw or nsw allowed");
3027 assert(!Ops.empty() && "Cannot get empty mul!");
3028 if (Ops.size() == 1) return Ops[0];
3029#ifndef NDEBUG
3030 Type *ETy = Ops[0]->getType();
3031 assert(!ETy->isPointerTy());
3032 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3033 assert(Ops[i]->getType() == ETy &&
3034 "SCEVMulExpr operand types don't match!");
3035#endif
3036
3038 Opts, *this, LI, DT, Ops,
3039 [](const APInt &C1, const APInt &C2) { return C1 * C2; },
3040 [](const APInt &C) { return C.isOne(); }, // identity
3041 [](const APInt &C) { return C.isZero(); }); // absorber
3042 if (Folded)
3043 return Folded;
3044
3045#ifndef NDEBUG
3046 // Keep track of operands after constant folding, for verification when adding
3047 // use-specific flags.
3048 const SmallVector<SCEVUse, 8> OrigOps(Ops.begin(), Ops.end());
3049#endif
3050
3051 // Delay expensive flag strengthening until necessary.
3052 auto ComputeFlags = [this, ExprFlags](const ArrayRef<SCEVUse> Ops) {
3053 return StrengthenNoWrapFlags(this, scMulExpr, Ops, ExprFlags);
3054 };
3055
3056 // Limit recursion calls depth.
3057 if (Depth > Opts.scalar_evolution_max_arith_depth ||
3058 hasHugeExpression(Opts, Ops))
3059 return {getOrCreateMulExpr(Ops, ComputeFlags(Ops)), UseFlags};
3060
3061 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3062 // Don't strengthen flags if we have no new information.
3063 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3064 if (Mul->getNoWrapFlags(ExprFlags) != ExprFlags)
3065 Mul->setNoWrapFlags(ComputeFlags(Ops));
3066 return {S, UseFlags};
3067 }
3068
3069 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3070 if (Ops.size() == 2) {
3071 // C1*(C2+V) -> C1*C2 + C1*V
3072 // If any of Add's ops are Adds or Muls with a constant, apply this
3073 // transformation as well.
3074 //
3075 // TODO: There are some cases where this transformation is not
3076 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
3077 // this transformation should be narrowed down.
3078 const SCEV *Op0, *Op1;
3079 if (match(Ops[1], m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))) &&
3081 const SCEV *LHS = getMulExpr(LHSC, Op0, SCEV::FlagNone, Depth + 1);
3082 const SCEV *RHS = getMulExpr(LHSC, Op1, SCEV::FlagNone, Depth + 1);
3083 return getAddExpr(LHS, RHS, SCEV::FlagNone, Depth + 1);
3084 }
3085
3086 if (Ops[0]->isAllOnesValue()) {
3087 // If we have a mul by -1 of an add, try distributing the -1 among the
3088 // add operands.
3089 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3091 bool AnyFolded = false;
3092 for (const SCEV *AddOp : Add->operands()) {
3093 const SCEV *Mul =
3094 getMulExpr(Ops[0], SCEVUse(AddOp), SCEV::FlagNone, Depth + 1);
3095 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3096 NewOps.push_back(Mul);
3097 }
3098 if (AnyFolded)
3099 return getAddExpr(NewOps, SCEV::FlagNone, Depth + 1);
3100 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3101 // Negation preserves a recurrence's no self-wrap property.
3103 for (const SCEV *AddRecOp : AddRec->operands())
3104 Operands.push_back(getMulExpr(Ops[0], SCEVUse(AddRecOp),
3105 SCEV::FlagNone, Depth + 1));
3106 // Let M be the minimum representable signed value. AddRec with nsw
3107 // multiplied by -1 can have signed overflow if and only if it takes a
3108 // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3109 // maximum signed value. In all other cases signed overflow is
3110 // impossible.
3111 auto FlagsMask = SCEV::FlagNW;
3112 if (AddRec->hasNoSignedWrap()) {
3113 auto MinInt =
3114 APInt::getSignedMinValue(getTypeSizeInBits(AddRec->getType()));
3115 if (getSignedRangeMin(AddRec) != MinInt)
3117 }
3118 return getAddRecExpr(Operands, AddRec->getLoop(),
3119 AddRec->getNoWrapFlags(FlagsMask));
3120 }
3121 }
3122
3123 // Try to push the constant operand into a ZExt: C * zext (A + B) ->
3124 // zext (C*A + C*B) if trunc (C) * (A + B) does not unsigned-wrap.
3125 const SCEVAddExpr *InnerAdd;
3126 if (match(Ops[1], m_scev_ZExt(m_scev_Add(InnerAdd)))) {
3127 const SCEV *NarrowC = getTruncateExpr(LHSC, InnerAdd->getType());
3128 if (isa<SCEVConstant>(InnerAdd->getOperand(0)) &&
3129 getZeroExtendExpr(NarrowC, Ops[1]->getType()) == LHSC &&
3130 hasFlags(StrengthenNoWrapFlags(this, scMulExpr, {NarrowC, InnerAdd},
3132 SCEV::FlagNUW)) {
3133 const SCEV *Res =
3134 getMulExpr(NarrowC, InnerAdd, SCEV::FlagNUW, Depth + 1);
3135 return getZeroExtendExpr(Res, Ops[1]->getType(), Depth + 1);
3136 };
3137 }
3138
3139 // Try to fold (C1 * D /u C2) -> C1/C2 * D, if C1 and C2 are powers-of-2,
3140 // D is a multiple of C2, and C1 is a multiple of C2. If C2 is a multiple
3141 // of C1, fold to (D /u (C2 /u C1)).
3142 const SCEV *D;
3143 APInt C1V = LHSC->getAPInt();
3144 // (C1 * D /u C2) == -1 * -C1 * D /u C2 when C1 != INT_MIN. Don't treat -1
3145 // as -1 * 1, as it won't enable additional folds.
3146 if (C1V.isNegative() && !C1V.isMinSignedValue() && !C1V.isAllOnes())
3147 C1V = C1V.abs();
3148 const SCEVConstant *C2;
3149 if (C1V.isPowerOf2() &&
3151 C2->getAPInt().isPowerOf2() &&
3152 C1V.logBase2() <= getMinTrailingZeros(D)) {
3153 const SCEV *NewMul = nullptr;
3154 if (C1V.uge(C2->getAPInt())) {
3155 NewMul = getMulExpr(getUDivExpr(getConstant(C1V), C2), D);
3156 } else if (C2->getAPInt().logBase2() <= getMinTrailingZeros(D)) {
3157 assert(C1V.ugt(1) && "C1 <= 1 should have been folded earlier");
3158 NewMul = getUDivExpr(D, getUDivExpr(C2, getConstant(C1V)));
3159 }
3160 if (NewMul)
3161 return C1V == LHSC->getAPInt() ? NewMul : getNegativeSCEV(NewMul);
3162 }
3163 }
3164 }
3165
3166 // Skip over the add expression until we get to a multiply.
3167 unsigned Idx = 0;
3168 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3169 ++Idx;
3170
3171 // If there are mul operands inline them all into this expression.
3172 if (Idx < Ops.size()) {
3173 bool DeletedMul = false;
3174 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3175 if (Ops.size() > Opts.scev_mulops_inline_threshold)
3176 break;
3177 // If we have an mul, expand the mul operands onto the end of the
3178 // operands list.
3179 Ops.erase(Ops.begin()+Idx);
3180 append_range(Ops, Mul->operands());
3181 DeletedMul = true;
3182 }
3183
3184 // If we deleted at least one mul, we added operands to the end of the
3185 // list, and they are not necessarily sorted. Recurse to resort and
3186 // resimplify any operands we just acquired.
3187 if (DeletedMul)
3188 return getMulExpr(Ops, SCEV::FlagNone, Depth + 1);
3189 }
3190
3191 // If there are any add recurrences in the operands list, see if any other
3192 // added values are loop invariant. If so, we can fold them into the
3193 // recurrence.
3194 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3195 ++Idx;
3196
3197 // Scan over all recurrences, trying to fold loop invariants into them.
3198 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3199 // Scan all of the other operands to this mul and add them to the vector
3200 // if they are loop invariant w.r.t. the recurrence.
3202 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3203 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3204 if (isAvailableAtLoopEntry(Ops[i], AddRec->getLoop())) {
3205 LIOps.push_back(Ops[i]);
3206 Ops.erase(Ops.begin()+i);
3207 --i; --e;
3208 }
3209
3210 // If we found some loop invariants, fold them into the recurrence.
3211 if (!LIOps.empty()) {
3212 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3214 NewOps.reserve(AddRec->getNumOperands());
3215 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagNone, Depth + 1);
3216
3217 // If both the mul and addrec are nuw, we can preserve nuw.
3218 // If both the mul and addrec are nsw, we can only preserve nsw if either
3219 // a) they are also nuw, or
3220 // b) all multiplications of addrec operands with scale are nsw.
3221 SCEVFlags Flags = AddRec->getNoWrapFlags(ComputeFlags({Scale, AddRec}));
3222
3223 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3224 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3225 SCEV::FlagNone, Depth + 1));
3226
3227 if (hasFlags(Flags, SCEV::FlagNSW) && !hasFlags(Flags, SCEV::FlagNUW)) {
3229 Instruction::Mul, getSignedRange(Scale),
3231 if (!NSWRegion.contains(getSignedRange(AddRec->getOperand(i))))
3232 Flags = clearFlags(Flags, SCEV::FlagNSW);
3233 }
3234 }
3235
3236 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(), Flags);
3237
3238 // If all of the other operands were loop invariant, we are done.
3239 if (Ops.size() == 1) return NewRec;
3240
3241 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3242 for (unsigned i = 0;; ++i)
3243 if (Ops[i] == AddRec) {
3244 Ops[i] = NewRec;
3245 break;
3246 }
3247 return getMulExpr(Ops, SCEV::FlagNone, Depth + 1);
3248 }
3249
3250 // Okay, if there weren't any loop invariants to be folded, check to see
3251 // if there are multiple AddRec's with the same loop induction variable
3252 // being multiplied together. If so, we can fold them.
3253
3254 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3255 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3256 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3257 // ]]],+,...up to x=2n}.
3258 // Note that the arguments to choose() are always integers with values
3259 // known at compile time, never SCEV objects.
3260 //
3261 // The implementation avoids pointless extra computations when the two
3262 // addrec's are of different length (mathematically, it's equivalent to
3263 // an infinite stream of zeros on the right).
3264 bool OpsModified = false;
3265 for (unsigned OtherIdx = Idx+1;
3266 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3267 ++OtherIdx) {
3268 const SCEVAddRecExpr *OtherAddRec =
3269 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3270 if (!OtherAddRec || OtherAddRec->getLoop() != AddRec->getLoop())
3271 continue;
3272
3273 // Limit max number of arguments to avoid creation of unreasonably big
3274 // SCEVAddRecs with very complex operands.
3275 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3276 Opts.scalar_evolution_max_add_rec_size ||
3277 hasHugeExpression(Opts, {AddRec, OtherAddRec}))
3278 continue;
3279
3280 bool Overflow = false;
3281 Type *Ty = AddRec->getType();
3282 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3283 SmallVector<SCEVUse, 7> AddRecOps;
3284 for (int x = 0, xe = AddRec->getNumOperands() +
3285 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3287 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3288 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3289 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3290 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3291 z < ze && !Overflow; ++z) {
3292 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3293 uint64_t Coeff;
3294 if (LargerThan64Bits)
3295 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3296 else
3297 Coeff = Coeff1*Coeff2;
3298 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3299 const SCEV *Term1 = AddRec->getOperand(y-z);
3300 const SCEV *Term2 = OtherAddRec->getOperand(z);
3301 SumOps.push_back(
3302 getMulExpr(CoeffTerm, Term1, Term2, SCEV::FlagNone, Depth + 1));
3303 }
3304 }
3305 if (SumOps.empty())
3306 SumOps.push_back(getZero(Ty));
3307 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagNone, Depth + 1));
3308 }
3309 if (!Overflow) {
3310 const SCEV *NewAddRec =
3311 getAddRecExpr(AddRecOps, AddRec->getLoop(), SCEV::FlagNone);
3312 if (Ops.size() == 2) return NewAddRec;
3313 Ops[Idx] = NewAddRec;
3314 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3315 OpsModified = true;
3316 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3317 if (!AddRec)
3318 break;
3319 }
3320 }
3321 if (OpsModified)
3322 return getMulExpr(Ops, SCEV::FlagNone, Depth + 1);
3323
3324 // Otherwise couldn't fold anything into this recurrence. Move onto the
3325 // next one.
3326 }
3327
3328 // Okay, it looks like we really DO need an mul expr. Check to see if we
3329 // already have one, otherwise create a new one.
3330 assert((UseFlags == SCEV::FlagNone || equal(OrigOps, Ops)) &&
3331 "Tried to add SCEVUse flags after operands changed");
3332 return {getOrCreateMulExpr(Ops, ComputeFlags(Ops)), UseFlags};
3333}
3334
3335/// Represents an unsigned remainder expression based on unsigned division.
3337 assert(getEffectiveSCEVType(LHS->getType()) ==
3338 getEffectiveSCEVType(RHS->getType()) &&
3339 "SCEVURemExpr operand types don't match!");
3340
3341 // Short-circuit easy cases
3342 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3343 // If constant is one, the result is trivial
3344 if (RHSC->getValue()->isOne())
3345 return getZero(LHS->getType()); // X urem 1 --> 0
3346
3347 // If constant is a power of two, fold into a zext(trunc(LHS)).
3348 if (RHSC->getAPInt().isPowerOf2()) {
3349 Type *FullTy = LHS->getType();
3350 Type *TruncTy =
3351 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3352 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3353 }
3354 }
3355
3356 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3357 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3358 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3359 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3360}
3361
3362/// Get a canonical unsigned division expression, or something simpler if
3363/// possible.
3365 assert(!LHS->getType()->isPointerTy() &&
3366 "SCEVUDivExpr operand can't be pointer!");
3367 assert(LHS->getType() == RHS->getType() &&
3368 "SCEVUDivExpr operand types don't match!");
3369
3370 if (SCEV *S = findExistingSCEVInCache(scUDivExpr, {LHS, RHS}))
3371 return S;
3372
3373 // 0 udiv Y == 0
3374 if (match(LHS, m_scev_Zero()))
3375 return LHS;
3376
3377 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3378 if (RHSC->getValue()->isOne())
3379 return LHS; // X udiv 1 --> x
3380 // If the denominator is zero, the result of the udiv is undefined. Don't
3381 // try to analyze it, because the resolution chosen here may differ from
3382 // the resolution chosen in other parts of the compiler.
3383 if (!RHSC->getValue()->isZero()) {
3384 // Determine if the division can be folded into the operands of
3385 // its operands.
3386 // TODO: Generalize this to non-constants by using known-bits information.
3387 Type *Ty = LHS->getType();
3388 unsigned LZ = RHSC->getAPInt().countl_zero();
3389 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3390 // For non-power-of-two values, effectively round the value up to the
3391 // nearest power of two.
3392 if (!RHSC->getAPInt().isPowerOf2())
3393 ++MaxShiftAmt;
3394 IntegerType *ExtTy =
3395 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3396 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3397 if (const SCEVConstant *Step =
3398 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3399 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3400 const APInt &StepInt = Step->getAPInt();
3401 const APInt &DivInt = RHSC->getAPInt();
3402 if (!StepInt.urem(DivInt) &&
3403 getZeroExtendExpr(AR, ExtTy) ==
3404 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3405 getZeroExtendExpr(Step, ExtTy), AR->getLoop(),
3406 SCEV::FlagNone)) {
3408 for (const SCEV *Op : AR->operands())
3409 Operands.push_back(getUDivExpr(Op, RHS));
3410 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3411 }
3412 /// Get a canonical UDivExpr for a recurrence.
3413 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3414 const APInt *StartRem;
3415 if (!DivInt.urem(StepInt) && match(getURemExpr(AR->getStart(), Step),
3416 m_scev_APInt(StartRem))) {
3417 bool NoWrap =
3418 getZeroExtendExpr(AR, ExtTy) ==
3419 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3420 getZeroExtendExpr(Step, ExtTy), AR->getLoop(),
3422
3423 // With N <= C and both N, C as powers-of-2, the transformation
3424 // {X,+,N}/C => {(X - X%N),+,N}/C preserves division results even
3425 // if wrapping occurs, as the division results remain equivalent for
3426 // all offsets in [[(X - X%N), X).
3427 bool CanFoldWithWrap = StepInt.ule(DivInt) && // N <= C
3428 StepInt.isPowerOf2() && DivInt.isPowerOf2();
3429 // Only fold if the subtraction can be folded in the start
3430 // expression.
3431 const SCEV *NewStart =
3432 getMinusSCEV(AR->getStart(), getConstant(*StartRem));
3433 if (*StartRem != 0 && (NoWrap || CanFoldWithWrap) &&
3434 !isa<SCEVAddExpr>(NewStart)) {
3435 const SCEV *NewLHS =
3436 getAddRecExpr(NewStart, Step, AR->getLoop(),
3437 NoWrap ? SCEV::FlagNW : SCEV::FlagNone);
3438 if (LHS != NewLHS)
3439 return getUDivExpr(NewLHS, RHS);
3440 }
3441 }
3442 }
3443 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3444 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3445 if (M->hasNoUnsignedWrap()) {
3446 // Find an operand that's safely divisible.
3447 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3448 const SCEV *Op = M->getOperand(i);
3449 const SCEV *Div = getUDivExpr(Op, RHSC);
3450 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3451 SmallVector<SCEVUse, 4> Operands(M->operands());
3452 Operands[i] = Div;
3453 return getMulExpr(Operands);
3454 }
3455 }
3456
3457 // Even if it's not divisible, try to remove a common factor.
3458 if (const auto *LHSC = dyn_cast<SCEVConstant>(M->getOperand(0))) {
3459 APInt Factor = APIntOps::GreatestCommonDivisor(LHSC->getAPInt(),
3460 RHSC->getAPInt());
3461 if (!Factor.isIntN(1)) {
3462 SmallVector<SCEVUse, 2> NewOperands;
3463 NewOperands.push_back(getConstant(LHSC->getAPInt().udiv(Factor)));
3464 append_range(NewOperands, M->operands().drop_front());
3465 const SCEV *NewMul = getMulExpr(NewOperands);
3466 return getUDivExpr(NewMul,
3467 getConstant(RHSC->getAPInt().udiv(Factor)));
3468 }
3469 }
3470 }
3471 }
3472
3473 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3474 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3475 if (auto *DivisorConstant =
3476 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3477 bool Overflow = false;
3478 APInt NewRHS =
3479 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3480 if (Overflow) {
3481 return getConstant(RHSC->getType(), 0, false);
3482 }
3483 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3484 }
3485 }
3486
3487 // (A+B)/C --> (A/C + B/C) if the add does not unsigned wrap and A/C and
3488 // B/C can be folded.
3489 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3490 if (A->hasNoUnsignedWrap()) {
3492 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3493 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3494 if (isa<SCEVUDivExpr>(Op) ||
3495 getMulExpr(Op, RHS) != A->getOperand(i))
3496 break;
3497 Operands.push_back(Op);
3498 }
3499 if (Operands.size() == A->getNumOperands())
3500 return getAddExpr(Operands);
3501 }
3502 }
3503
3504 // ((N - M) + (M * A)) / N --> ((N - 1) + (M * A)) / N
3505 // This is an idiom for rounding A up to the next multiple of N, where A
3506 // is aready known to be a multiple of M. In this case, instcombine can
3507 // see that some low bits of the added constant are unused, so can clear
3508 // them, but we want to canonicalise to set the low bits. This makes the
3509 // pattern easier to match, without needing to check for known bits in
3510 // A*M.
3511 const APInt &N = RHSC->getAPInt();
3512 const APInt *NMinusM, *M;
3513 const SCEV *A;
3514 if (match(LHS, m_scev_Add(m_scev_APInt(NMinusM),
3515 m_scev_Mul(m_scev_APInt(M), m_SCEV(A))))) {
3516 if (N.isPowerOf2() && M->isPowerOf2() && M->ult(N) &&
3517 *NMinusM == N - *M) {
3518 return getUDivExpr(
3520 RHS);
3521 }
3522 }
3523
3524 // Fold if both operands are constant.
3525 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3526 return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3527 }
3528 }
3529
3530 // ((-C + (C smax %x)) /u %x) evaluates to zero, for any positive constant C.
3531 const APInt *NegC, *C;
3532 if (match(LHS,
3535 NegC->isNegative() && !NegC->isMinSignedValue() && *C == -*NegC)
3536 return getZero(LHS->getType());
3537
3538 // (%a * %b)<nuw> / %b -> %a
3539 const auto *Mul = dyn_cast<SCEVMulExpr>(LHS);
3540 if (Mul && Mul->hasNoUnsignedWrap()) {
3541 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3542 if (Mul->getOperand(i) == RHS) {
3544 append_range(Operands, Mul->operands().take_front(i));
3545 append_range(Operands, Mul->operands().drop_front(i + 1));
3546 return getMulExpr(Operands);
3547 }
3548 }
3549 }
3550
3551 // TODO: Generalize to handle any common factors.
3552 // udiv (mul nuw a, vscale), (mul nuw b, vscale) --> udiv a, b
3553 const SCEV *NewLHS, *NewRHS;
3554 if (match(LHS, m_scev_c_NUWMul(m_SCEV(NewLHS), m_SCEVVScale())) &&
3555 match(RHS, m_scev_c_NUWMul(m_SCEV(NewRHS), m_SCEVVScale())))
3556 return getUDivExpr(NewLHS, NewRHS);
3557
3558 return getOrCreateUDivExpr(LHS, RHS);
3559}
3560
3561/// Get a canonical unsigned division expression, or something simpler if
3562/// possible. There is no representation for an exact udiv in SCEV IR, but we
3563/// can attempt to optimize it prior to construction.
3565 // Currently there is no exact specific logic.
3566
3567 return getUDivExpr(LHS, RHS);
3568}
3569
3570/// Get an add recurrence expression for the specified loop. Simplify the
3571/// expression as much as possible.
3573 const Loop *L, SCEVFlagsPair Flags) {
3575 Operands.push_back(Start);
3576 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3577 if (StepChrec->getLoop() == L) {
3578 append_range(Operands, StepChrec->operands());
3579 // The use flags describe the two-operand recurrence, not the flattened
3580 // one built here, so drop them just like the expression's NUW/NSW.
3581 return getAddRecExpr(Operands, L,
3582 maskFlags(Flags.ExprFlags, SCEV::FlagNW));
3583 }
3584
3585 Operands.push_back(Step);
3586 return getAddRecExpr(Operands, L, Flags);
3587}
3588
3589/// Get an add recurrence expression for the specified loop. Simplify the
3590/// expression as much as possible.
3592 const Loop *L, SCEVFlagsPair NWFlags) {
3593 SCEVFlags ExprFlags = NWFlags.ExprFlags;
3594 SCEVFlags UseFlags = NWFlags.UseFlags;
3595 assert(!(UseFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
3596 "only nuw or nsw allowed");
3597 if (Operands.size() == 1) return Operands[0];
3598#ifndef NDEBUG
3600 for (const SCEV *Op : llvm::drop_begin(Operands)) {
3601 assert(getEffectiveSCEVType(Op->getType()) == ETy &&
3602 "SCEVAddRecExpr operand types don't match!");
3603 assert(!Op->getType()->isPointerTy() && "Step must be integer");
3604 }
3605 for (const SCEV *Op : Operands)
3607 "SCEVAddRecExpr operand is not available at loop entry!");
3608#endif
3609
3610 if (Operands.back()->isZero()) {
3611 Operands.pop_back();
3612 return getAddRecExpr(Operands, L, SCEV::FlagNone); // {X,+,0} --> X
3613 }
3614
3615 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3616 // use that information to infer NUW and NSW flags. However, computing a
3617 // BE count requires calling getAddRecExpr, so we may not yet have a
3618 // meaningful BE count at this point (and if we don't, we'd be stuck
3619 // with a SCEVCouldNotCompute as the cached BE count).
3620
3621 ExprFlags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, ExprFlags);
3622
3623 return {getOrCreateAddRecExpr(Operands, L, ExprFlags), UseFlags};
3624}
3625
3627 ArrayRef<SCEVUse> IndexExprs) {
3628 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3629 // getSCEV(Base)->getType() has the same address space as Base->getType()
3630 // because SCEV::getType() preserves the address space.
3631 GEPNoWrapFlags BaseNW = GEP->getNoWrapFlags();
3632 GEPNoWrapFlags OffsetNW = GEP->getNoWrapFlags();
3633 if (BaseNW != GEPNoWrapFlags::none()) {
3634 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3635 // but to do that, we have to ensure that said flag is valid in the entire
3636 // defined scope of the SCEV.
3637 // TODO: non-instructions have global scope. We might be able to prove
3638 // some global scope cases
3639 auto *GEPI = dyn_cast<Instruction>(GEP);
3640 if (!GEPI || !isSCEVExprNeverPoison(GEPI)) {
3641 BaseNW = OffsetNW = GEPNoWrapFlags::none();
3642 } else if (any_of(IndexExprs, [&](const SCEVUse &IndexExpr) {
3643 const SCEV *Idx = IndexExpr;
3644 return !isa<SCEVConstant>(Idx) &&
3645 !isGuaranteedToTransferExecutionTo(
3646 getDefiningScopeBound({Idx}), GEPI);
3647 })) {
3648 // The offset flags should not take into account the base pointer
3649 // defining scope, as the offset only depends on the indices. Thus,
3650 // derive the scope bound for the offset flags from each index operand
3651 // individually.
3652 OffsetNW = GEPNoWrapFlags::none();
3653 }
3654 }
3655
3656 return getGEPExpr(BaseExpr, IndexExprs, GEP->getSourceElementType(), BaseNW,
3657 OffsetNW);
3658}
3659
3661 ArrayRef<SCEVUse> IndexExprs,
3662 Type *SrcElementTy,
3663 GEPNoWrapFlags BaseNW,
3664 GEPNoWrapFlags OffsetNW) {
3665 SCEVFlags OffsetWrap = SCEV::FlagNone;
3666 if (OffsetNW.hasNoUnsignedSignedWrap())
3667 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNSW);
3668 if (OffsetNW.hasNoUnsignedWrap())
3669 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNUW);
3670
3671 Type *CurTy = BaseExpr->getType();
3672 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3673 bool FirstIter = true;
3675 for (SCEVUse IndexExpr : IndexExprs) {
3676 // Compute the (potentially symbolic) offset in bytes for this index.
3677 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3678 // For a struct, add the member offset.
3679 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3680 unsigned FieldNo = Index->getZExtValue();
3681 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3682 Offsets.push_back(FieldOffset);
3683
3684 // Update CurTy to the type of the field at Index.
3685 CurTy = STy->getTypeAtIndex(Index);
3686 } else {
3687 // Update CurTy to its element type.
3688 if (FirstIter) {
3689 assert(isa<PointerType>(CurTy) &&
3690 "The first index of a GEP indexes a pointer");
3691 CurTy = SrcElementTy;
3692 FirstIter = false;
3693 } else {
3694 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3695 }
3696 // For an array, add the element offset, explicitly scaled.
3697 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3698 // Getelementptr indices are signed.
3699 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3700
3701 // Multiply the index by the element size to compute the element offset.
3702 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3703 Offsets.push_back(LocalOffset);
3704 }
3705 }
3706
3707 // Handle degenerate case of GEP without offsets.
3708 if (Offsets.empty())
3709 return BaseExpr;
3710
3711 // Add the offsets together, assuming nsw if inbounds.
3712 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3713 // Add the base address and the offset. We cannot use the nsw flag, as the
3714 // base address is unsigned. However, if we know that the offset is
3715 // non-negative, we can use nuw.
3716 bool NUW = BaseNW.hasNoUnsignedWrap() ||
3718 SCEVFlags BaseWrap = NUW ? SCEV::FlagNUW : SCEV::FlagNone;
3719 const SCEV *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3720 assert(BaseExpr->getType() == GEPExpr->getType() &&
3721 "GEP should not change type mid-flight.");
3722 return GEPExpr;
3723}
3724
3725SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3727 const Loop *L) {
3728 assert((SCEVType != scAddRecExpr || L) &&
3729 "L must be passed to find existing AddRecs");
3731 ID.AddInteger(SCEVType);
3732 for (SCEVUse Op : Ops)
3733 ID.AddPointer(Op.getOpaqueValue());
3734 if (L)
3735 ID.AddPointer(L);
3737 return UniqueSCEVs.lookup(ID, Token);
3738}
3739
3740const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3741 SCEVFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagNone;
3742 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3743}
3744
3747 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3748 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3749 if (Ops.size() == 1) return Ops[0];
3750#ifndef NDEBUG
3751 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3752 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3753 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3754 "Operand types don't match!");
3755 assert(Ops[0]->getType()->isPointerTy() ==
3756 Ops[i]->getType()->isPointerTy() &&
3757 "min/max should be consistently pointerish");
3758 }
3759#endif
3760
3761 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3762 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3763
3765 Opts, *this, LI, DT, Ops,
3766 [&](const APInt &C1, const APInt &C2) {
3767 switch (Kind) {
3768 case scSMaxExpr:
3769 return APIntOps::smax(C1, C2);
3770 case scSMinExpr:
3771 return APIntOps::smin(C1, C2);
3772 case scUMaxExpr:
3773 return APIntOps::umax(C1, C2);
3774 case scUMinExpr:
3775 return APIntOps::umin(C1, C2);
3776 default:
3777 llvm_unreachable("Unknown SCEV min/max opcode");
3778 }
3779 },
3780 [&](const APInt &C) {
3781 // identity
3782 if (IsMax)
3783 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3784 else
3785 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3786 },
3787 [&](const APInt &C) {
3788 // absorber
3789 if (IsMax)
3790 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3791 else
3792 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3793 });
3794 if (Folded)
3795 return Folded;
3796
3797 // Check if we have created the same expression before.
3798 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3799 return S;
3800 }
3801
3802 // Find the first operation of the same kind
3803 unsigned Idx = 0;
3804 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3805 ++Idx;
3806
3807 // Check to see if one of the operands is of the same kind. If so, expand its
3808 // operands onto our operand list, and recurse to simplify.
3809 if (Idx < Ops.size()) {
3810 bool DeletedAny = false;
3811 while (Ops[Idx]->getSCEVType() == Kind) {
3812 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3813 Ops.erase(Ops.begin()+Idx);
3814 append_range(Ops, SMME->operands());
3815 DeletedAny = true;
3816 }
3817
3818 if (DeletedAny)
3819 return getMinMaxExpr(Kind, Ops);
3820 }
3821
3822 // Okay, check to see if the same value occurs in the operand list twice. If
3823 // so, delete one. Since we sorted the list, these values are required to
3824 // be adjacent.
3829 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3830 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3831 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3832 if (SCEVUse Common = SCEVUse::getCommon(Ops[i], Ops[i + 1]))
3833 Ops[i] = Ops[i + 1] = Common;
3834 if (Ops[i] == Ops[i + 1] ||
3835 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3836 // X op Y op Y --> X op Y
3837 // X op Y --> X, if we know X, Y are ordered appropriately
3838 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3839 --i;
3840 --e;
3841 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3842 Ops[i + 1])) {
3843 // X op Y --> Y, if we know X, Y are ordered appropriately
3844 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3845 --i;
3846 --e;
3847 }
3848 }
3849
3850 if (Ops.size() == 1) return Ops[0];
3851
3852 assert(!Ops.empty() && "Reduced smax down to nothing!");
3853
3854 // Okay, it looks like we really DO need an expr. Check to see if we
3855 // already have one, otherwise create a new one.
3857 ID.AddInteger(Kind);
3858 for (SCEVUse Op : Ops)
3859 ID.AddPointer(Op.getOpaqueValue());
3861 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
3862 if (ExistingSCEV)
3863 return ExistingSCEV;
3864 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3866 SCEV *S = new (SCEVAllocator)
3867 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3868
3869 UniqueSCEVs.insert(S, Token);
3870 S->computeAndSetCanonical(*this);
3871 registerUser(S, Ops);
3872 return S;
3873}
3874
3875namespace {
3876
3877class SCEVSequentialMinMaxDeduplicatingVisitor final
3878 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
3879 std::optional<const SCEV *>> {
3880 using RetVal = std::optional<const SCEV *>;
3881
3882 ScalarEvolution &SE;
3883 const SCEVTypes RootKind; // Must be a sequential min/max expression.
3884 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
3886
3887 bool canRecurseInto(SCEVTypes Kind) const {
3888 // We can only recurse into the SCEV expression of the same effective type
3889 // as the type of our root SCEV expression.
3890 return RootKind == Kind || NonSequentialRootKind == Kind;
3891 };
3892
3893 RetVal visit(const SCEV *S) {
3894 // Has the whole operand been seen already?
3895 if (!SeenOps.insert(S).second)
3896 return std::nullopt;
3898 SCEVTypes Kind = S->getSCEVType();
3899
3900 if (!canRecurseInto(Kind))
3901 return S;
3902
3903 auto *NAry = cast<SCEVNAryExpr>(S);
3904 SmallVector<SCEVUse> NewOps;
3905 bool Changed = visit(Kind, NAry->operands(), NewOps);
3906
3907 if (!Changed)
3908 return S;
3909 if (NewOps.empty())
3910 return std::nullopt;
3911
3913 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
3914 : SE.getMinMaxExpr(Kind, NewOps);
3915 }
3916 return S;
3917 }
3918
3919public:
3920 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
3921 SCEVTypes RootKind)
3922 : SE(SE), RootKind(RootKind),
3923 NonSequentialRootKind(
3924 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
3925 RootKind)) {}
3926
3927 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<SCEVUse> OrigOps,
3928 SmallVectorImpl<SCEVUse> &NewOps) {
3929 bool Changed = false;
3931 Ops.reserve(OrigOps.size());
3932
3933 for (const SCEV *Op : OrigOps) {
3934 RetVal NewOp = visit(Op);
3935 if (NewOp != Op)
3936 Changed = true;
3937 if (NewOp)
3938 Ops.emplace_back(*NewOp);
3939 }
3940
3941 if (Changed)
3942 NewOps = std::move(Ops);
3943 return Changed;
3944 }
3945};
3946
3947} // namespace
3948
3950 switch (Kind) {
3951 case scConstant:
3952 case scVScale:
3953 case scTruncate:
3954 case scZeroExtend:
3955 case scSignExtend:
3956 case scPtrToAddr:
3957 case scAddExpr:
3958 case scMulExpr:
3959 case scUDivExpr:
3960 case scAddRecExpr:
3961 case scUMaxExpr:
3962 case scSMaxExpr:
3963 case scUMinExpr:
3964 case scSMinExpr:
3965 case scUnknown:
3966 // If any operand is poison, the whole expression is poison.
3967 return true;
3969 // FIXME: if the *first* operand is poison, the whole expression is poison.
3970 return false; // Pessimistically, say that it does not propagate poison.
3971 case scCouldNotCompute:
3972 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
3973 }
3974 llvm_unreachable("Unknown SCEV kind!");
3975}
3976
3977namespace {
3978// The only way poison may be introduced in a SCEV expression is from a
3979// poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
3980// not SCEVConstant). Notably, SCEVFlags on SCEV nodes can *not*
3981// introduce poison -- they encode guaranteed, non-speculated knowledge. The
3982// flags of a SCEVUse can, as they only hold where it is used.
3983//
3984// Additionally, all SCEV nodes propagate poison from inputs to outputs,
3985// with the notable exception of umin_seq, where only poison from the first
3986// operand is (unconditionally) propagated.
3987struct SCEVPoisonCollector {
3988 bool LookThroughMaybePoisonBlocking;
3989 SmallPtrSet<const SCEVUnknown *, 4> MaybePoison;
3990 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
3991 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
3992
3993 bool follow(const SCEV *S) {
3994 if (!LookThroughMaybePoisonBlocking &&
3996 return false;
3997
3998 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
3999 if (!isGuaranteedNotToBePoison(SU->getValue()))
4000 MaybePoison.insert(SU);
4001 }
4002 return true;
4003 }
4004 bool isDone() const { return false; }
4005};
4006} // namespace
4007
4008/// Return true if S is poison given that AssumedPoison is already poison.
4009static bool impliesPoison(SCEVUse AssumedPoison, const SCEV *S) {
4010 // AssumedPoison may be poison due to its use flags alone.
4011 if (!AssumedPoison.isCanonical())
4012 return false;
4013
4014 // First collect all SCEVs that might result in AssumedPoison to be poison.
4015 // We need to look through potentially poison-blocking operations here,
4016 // because we want to find all SCEVs that *might* result in poison, not only
4017 // those that are *required* to.
4018 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4019 visitAll(AssumedPoison, PC1);
4020
4021 // AssumedPoison is never poison. As the assumption is false, the implication
4022 // is true. Don't bother walking the other SCEV in this case.
4023 if (PC1.MaybePoison.empty())
4024 return true;
4025
4026 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4027 // as well. We cannot look through potentially poison-blocking operations
4028 // here, as their arguments only *may* make the result poison.
4029 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4030 visitAll(S, PC2);
4031
4032 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4033 // it will also make S poison by being part of PC2.MaybePoison.
4034 return llvm::set_is_subset(PC1.MaybePoison, PC2.MaybePoison);
4035}
4036
4038 SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4039 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4040 visitAll(S, PC);
4041 for (const SCEVUnknown *SU : PC.MaybePoison)
4042 Result.insert(SU->getValue());
4043}
4044
4046 const SCEV *S, Instruction *I,
4047 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
4048 // If the instruction cannot be poison, it's always safe to reuse.
4050 return true;
4051
4052 // Otherwise, it is possible that I is more poisonous that S. Collect the
4053 // poison-contributors of S, and then check whether I has any additional
4054 // poison-contributors. Poison that is contributed through poison-generating
4055 // flags is handled by dropping those flags instead.
4057 getPoisonGeneratingValues(PoisonVals, S);
4058
4059 SmallVector<Value *> Worklist;
4061 Worklist.push_back(I);
4062 unsigned NumVisitedInsts = 0;
4063 const unsigned InstLimit = std::max<unsigned>(16, S->getExpressionSize());
4064 while (!Worklist.empty()) {
4065 Value *V = Worklist.pop_back_val();
4066 if (!Visited.insert(V).second)
4067 continue;
4068
4069 // Either the value can't be poison, or the S would also be poison if it
4070 // is.
4071 if (PoisonVals.contains(V) || ::isGuaranteedNotToBePoison(V))
4072 continue;
4073
4074 // Avoid walking large instruction graphs.
4075 if (++NumVisitedInsts > InstLimit)
4076 return false;
4077
4078 auto *I = dyn_cast<Instruction>(V);
4079 if (!I)
4080 return false;
4081
4082 // Disjoint or instructions are interpreted as adds by SCEV. However, we
4083 // can't replace an arbitrary add with disjoint or, even if we drop the
4084 // flag. We would need to convert the or into an add.
4085 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
4086 if (PDI->isDisjoint())
4087 return false;
4088
4089 // FIXME: Ignore vscale, even though it technically could be poison. Do this
4090 // because SCEV currently assumes it can't be poison. Remove this special
4091 // case once we proper model when vscale can be poison.
4092 if (auto *II = dyn_cast<IntrinsicInst>(I);
4093 II && II->getIntrinsicID() == Intrinsic::vscale)
4094 continue;
4095
4096 if (canCreatePoison(cast<Operator>(I), /*ConsiderFlagsAndMetadata*/ false))
4097 return false;
4098
4099 // If the instruction can't create poison, we can recurse to its operands.
4100 if (I->hasPoisonGeneratingAnnotations())
4101 DropPoisonGeneratingInsts.push_back(I);
4102
4103 llvm::append_range(Worklist, I->operands());
4104 }
4105 return true;
4106}
4107
4108const SCEV *
4111 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4112 "Not a SCEVSequentialMinMaxExpr!");
4113 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4114 if (Ops.size() == 1)
4115 return Ops[0];
4116#ifndef NDEBUG
4117 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4118 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4119 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4120 "Operand types don't match!");
4121 assert(Ops[0]->getType()->isPointerTy() ==
4122 Ops[i]->getType()->isPointerTy() &&
4123 "min/max should be consistently pointerish");
4124 }
4125#endif
4126
4127 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4128 // so we can *NOT* do any kind of sorting of the expressions!
4129
4130 // Check if we have created the same expression before.
4131 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4132 return S;
4133
4134 // FIXME: there are *some* simplifications that we can do here.
4135
4136 // Keep only the first instance of an operand.
4137 {
4138 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4139 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4140 if (Changed)
4141 return getSequentialMinMaxExpr(Kind, Ops);
4142 }
4143
4144 // Check to see if one of the operands is of the same kind. If so, expand its
4145 // operands onto our operand list, and recurse to simplify.
4146 {
4147 unsigned Idx = 0;
4148 bool DeletedAny = false;
4149 while (Idx < Ops.size()) {
4150 if (Ops[Idx]->getSCEVType() != Kind) {
4151 ++Idx;
4152 continue;
4153 }
4154 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4155 Ops.erase(Ops.begin() + Idx);
4156 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4157 SMME->operands().end());
4158 DeletedAny = true;
4159 }
4160
4161 if (DeletedAny)
4162 return getSequentialMinMaxExpr(Kind, Ops);
4163 }
4164
4165 const SCEV *SaturationPoint;
4167 switch (Kind) {
4169 SaturationPoint = getZero(Ops[0]->getType());
4170 Pred = ICmpInst::ICMP_ULE;
4171 break;
4172 default:
4173 llvm_unreachable("Not a sequential min/max type.");
4174 }
4175
4176 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4178 continue;
4179 // We can replace %x umin_seq %y with %x umin %y if either:
4180 // * %y being poison implies %x is also poison.
4181 // * %x cannot be the saturating value (e.g. zero for umin).
4182 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4183 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4184 SaturationPoint)) {
4185 SmallVector<SCEVUse, 2> SeqOps = {Ops[i - 1], Ops[i]};
4186 Ops[i - 1] = getMinMaxExpr(
4188 SeqOps);
4189 Ops.erase(Ops.begin() + i);
4190 return getSequentialMinMaxExpr(Kind, Ops);
4191 }
4192 // Fold %x umin_seq %y to %x if %x ule %y.
4193 // TODO: We might be able to prove the predicate for a later operand.
4194 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4195 Ops.erase(Ops.begin() + i);
4196 return getSequentialMinMaxExpr(Kind, Ops);
4197 }
4198 }
4199
4200 // Okay, it looks like we really DO need an expr. Check to see if we
4201 // already have one, otherwise create a new one.
4203 ID.AddInteger(Kind);
4204 for (SCEVUse Op : Ops)
4205 ID.AddPointer(Op.getOpaqueValue());
4207 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
4208 if (ExistingSCEV)
4209 return ExistingSCEV;
4210
4211 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4213 SCEV *S = new (SCEVAllocator)
4214 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4215
4216 UniqueSCEVs.insert(S, Token);
4217 S->computeAndSetCanonical(*this);
4218 registerUser(S, Ops);
4219 return S;
4220}
4221
4226
4230
4235
4239
4244
4248
4250 bool Sequential) {
4251 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4252 return getUMinExpr(Ops, Sequential);
4253}
4254
4260
4261const SCEV *
4263 const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4264 if (Size.isScalable())
4265 Res = getMulExpr(Res, getVScale(IntTy));
4266 return Res;
4267}
4268
4270 return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4271}
4272
4274 return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4275}
4276
4278 StructType *STy,
4279 unsigned FieldNo) {
4280 // We can bypass creating a target-independent constant expression and then
4281 // folding it back into a ConstantInt. This is just a compile-time
4282 // optimization.
4283 const StructLayout *SL = getDataLayout().getStructLayout(STy);
4284 assert(!SL->getSizeInBits().isScalable() &&
4285 "Cannot get offset for structure containing scalable vector types");
4286 return getConstant(IntTy, SL->getElementOffset(FieldNo));
4287}
4288
4290 // Don't attempt to do anything other than create a SCEVUnknown object
4291 // here. createSCEV only calls getUnknown after checking for all other
4292 // interesting possibilities, and any other code that calls getUnknown
4293 // is doing so in order to hide a value from SCEV canonicalization.
4294
4297 ID.AddPointer(V);
4299 if (SCEV *S = UniqueSCEVs.lookup(ID, Token)) {
4300 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4301 "Stale SCEVUnknown in uniquing map!");
4302 return S;
4303 }
4304 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4305 FirstUnknown, NextUnknownOrderID++);
4306 FirstUnknown = cast<SCEVUnknown>(S);
4307 UniqueSCEVs.insert(S, Token);
4308 S->computeAndSetCanonical(*this);
4309 return S;
4310}
4311
4312//===----------------------------------------------------------------------===//
4313// Basic SCEV Analysis and PHI Idiom Recognition Code
4314//
4315
4316/// Test if values of the given type are analyzable within the SCEV
4317/// framework. This primarily includes integer types, and it can optionally
4318/// include pointer types if the ScalarEvolution class has access to
4319/// target-specific information.
4321 // Integers and pointers are always SCEVable.
4322 return Ty->isIntOrPtrTy();
4323}
4324
4325/// Return the size in bits of the specified type, for which isSCEVable must
4326/// return true.
4328 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4329 if (Ty->isPointerTy())
4331 return getDataLayout().getTypeSizeInBits(Ty);
4332}
4333
4334/// Return a type with the same bitwidth as the given type and which represents
4335/// how SCEV will treat the given type, for which isSCEVable must return
4336/// true. For pointer types, this is the pointer index sized integer type.
4338 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4339
4340 if (Ty->isIntegerTy())
4341 return Ty;
4342
4343 // The only other support type is pointer.
4344 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4345 return getDataLayout().getIndexType(Ty);
4346}
4347
4349 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4350}
4351
4353 const SCEV *B) {
4354 /// For a valid use point to exist, the defining scope of one operand
4355 /// must dominate the other.
4356 bool PreciseA, PreciseB;
4357 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4358 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4359 if (!PreciseA || !PreciseB)
4360 // Can't tell.
4361 return false;
4362 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4363 DT.dominates(ScopeB, ScopeA);
4364}
4365
4367 return CouldNotCompute.get();
4368}
4369
4370bool ScalarEvolution::checkValidity(const SCEV *S) const {
4371 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4372 auto *SU = dyn_cast<SCEVUnknown>(S);
4373 return SU && SU->getValue() == nullptr;
4374 });
4375
4376 return !ContainsNulls;
4377}
4378
4380 auto [I, Inserted] = HasRecMap.try_emplace(S);
4381 if (Inserted)
4382 I->second = SCEVExprContains(
4383 S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4384 return I->second;
4385}
4386
4387/// Return the ValueOffsetPair set for \p S. \p S can be represented
4388/// by the value and offset from any ValueOffsetPair in the set.
4389ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4390 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4391 if (SI == ExprValueMap.end())
4392 return {};
4393 return SI->second;
4394}
4395
4396/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4397/// cannot be used separately. eraseValueFromMap should be used to remove
4398/// V from ValueExprMap and ExprValueMap at the same time.
4399void ScalarEvolution::eraseValueFromMap(Value *V) {
4400 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4401 if (I != ValueExprMap.end()) {
4402 auto EVIt = ExprValueMap.find(I->second);
4403 assert(is_contained(EVIt->second, V) && "Value not in ExprValueMap?");
4404 llvm::erase(EVIt->second, V);
4405 ValueExprMap.erase(I);
4406 }
4407}
4408
4409void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4410 // A recursive query may have already computed the SCEV. It should be
4411 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4412 // inferred nowrap flags.
4413 if (ValueExprMap.insert({SCEVCallbackVH(V, this), S}).second)
4414 ExprValueMap[S].push_back(V);
4415}
4416
4417/// Return an existing SCEV if it exists, otherwise analyze the expression and
4418/// create a new one.
4420 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4421
4422 if (const SCEV *S = getExistingSCEV(V))
4423 return S;
4424 return createSCEVIter(V);
4425}
4426
4428 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4429
4430 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4431 if (I != ValueExprMap.end()) {
4432 const SCEV *S = I->second;
4433 assert(checkValidity(S) &&
4434 "existing SCEV has not been properly invalidated");
4435 return S;
4436 }
4437 return nullptr;
4438}
4439
4440/// Return a SCEV corresponding to -V = -1*V
4442 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4443 return getConstant(
4444 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4445
4446 Type *Ty = V->getType();
4447 Ty = getEffectiveSCEVType(Ty);
4448 return getMulExpr(V, getMinusOne(Ty), Flags);
4449}
4450
4451/// If Expr computes ~A, return A else return nullptr
4452static const SCEV *MatchNotExpr(const SCEV *Expr) {
4453 const SCEV *MulOp;
4454 if (match(Expr, m_scev_Add(m_scev_AllOnes(),
4455 m_scev_Mul(m_scev_AllOnes(), m_SCEV(MulOp)))))
4456 return MulOp;
4457 return nullptr;
4458}
4459
4460/// Return a SCEV corresponding to ~V = -1-V
4462 assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4463
4464 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4465 return getConstant(
4466 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4467
4468 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4469 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4470 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4471 SmallVector<SCEVUse, 2> MatchedOperands;
4472 for (const SCEV *Operand : MME->operands()) {
4473 const SCEV *Matched = MatchNotExpr(Operand);
4474 if (!Matched)
4475 return (const SCEV *)nullptr;
4476 MatchedOperands.push_back(Matched);
4477 }
4478 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4479 MatchedOperands);
4480 };
4481 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4482 return Replaced;
4483 }
4484
4485 Type *Ty = V->getType();
4486 Ty = getEffectiveSCEVType(Ty);
4487 return getMinusSCEV(getMinusOne(Ty), V);
4488}
4489
4491 assert(P->getType()->isPointerTy());
4492
4493 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4494 // The base of an AddRec is the first operand.
4495 SmallVector<SCEVUse> Ops{AddRec->operands()};
4496 Ops[0] = removePointerBase(Ops[0]);
4497 // Don't try to transfer nowrap flags for now. We could in some cases
4498 // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4499 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagNone);
4500 }
4501 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4502 // The base of an Add is the pointer operand.
4503 SmallVector<SCEVUse> Ops{Add->operands()};
4504 SCEVUse *PtrOp = nullptr;
4505 for (SCEVUse &AddOp : Ops) {
4506 if (AddOp->getType()->isPointerTy()) {
4507 assert(!PtrOp && "Cannot have multiple pointer ops");
4508 PtrOp = &AddOp;
4509 }
4510 }
4511 *PtrOp = removePointerBase(*PtrOp);
4512 // Don't try to transfer nowrap flags for now. We could in some cases
4513 // (for example, if the pointer operand of the Add is a SCEVUnknown).
4514 return getAddExpr(Ops);
4515 }
4516 // Any other expression must be a pointer base.
4517 return getZero(P->getType());
4518}
4519
4521 SCEVFlags Flags, unsigned Depth) {
4522 // Fast path: X - X --> 0.
4523 if (SCEVUse::getCommon(LHS, RHS))
4524 return getZero(LHS->getType());
4525
4526 // If we subtract two pointers with different pointer bases, bail.
4527 // Eventually, we're going to add an assertion to getMulExpr that we
4528 // can't multiply by a pointer.
4529 if (RHS->getType()->isPointerTy()) {
4530 if (!LHS->getType()->isPointerTy() ||
4531 getPointerBase(LHS) != getPointerBase(RHS))
4532 return getCouldNotCompute();
4533 LHS = removePointerBase(LHS);
4534 RHS = removePointerBase(RHS);
4535 }
4536
4537 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4538 // makes it so that we cannot make much use of NUW.
4539 auto AddFlags = SCEV::FlagNone;
4540 const bool RHSIsNotMinSigned =
4542 if (hasFlags(Flags, SCEV::FlagNSW)) {
4543 // Let M be the minimum representable signed value. Then (-1)*RHS
4544 // signed-wraps if and only if RHS is M. That can happen even for
4545 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4546 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4547 // (-1)*RHS, we need to prove that RHS != M.
4548 //
4549 // If LHS is non-negative and we know that LHS - RHS does not
4550 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4551 // either by proving that RHS > M or that LHS >= 0.
4552 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4553 AddFlags = SCEV::FlagNSW;
4554 }
4555 }
4556
4557 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4558 // RHS is NSW and LHS >= 0.
4559 //
4560 // The difficulty here is that the NSW flag may have been proven
4561 // relative to a loop that is to be found in a recurrence in LHS and
4562 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4563 // larger scope than intended.
4564 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagNone;
4565
4566 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4567}
4568
4570 unsigned Depth) {
4571 Type *SrcTy = V->getType();
4572 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4573 "Cannot truncate or zero extend with non-integer arguments!");
4574 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4575 return V; // No conversion
4576 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4577 return getTruncateExpr(V, Ty, Depth);
4578 return getZeroExtendExpr(V, Ty, Depth);
4579}
4580
4582 unsigned Depth) {
4583 Type *SrcTy = V->getType();
4584 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4585 "Cannot truncate or zero extend with non-integer arguments!");
4586 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4587 return V; // No conversion
4588 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4589 return getTruncateExpr(V, Ty, Depth);
4590 return getSignExtendExpr(V, Ty, Depth);
4591}
4592
4594 Type *SrcTy = V->getType();
4595 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4596 "Cannot noop or zero extend with non-integer arguments!");
4598 "getNoopOrZeroExtend cannot truncate!");
4599 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4600 return V; // No conversion
4601 return getZeroExtendExpr(V, Ty);
4602}
4603
4605 Type *SrcTy = V->getType();
4606 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4607 "Cannot noop or sign extend with non-integer arguments!");
4609 "getNoopOrSignExtend cannot truncate!");
4610 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4611 return V; // No conversion
4612 return getSignExtendExpr(V, Ty);
4613}
4614
4616 Type *SrcTy = V->getType();
4617 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4618 "Cannot noop or any extend with non-integer arguments!");
4620 "getNoopOrAnyExtend cannot truncate!");
4621 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4622 return V; // No conversion
4623 return getAnyExtendExpr(V, Ty);
4624}
4625
4627 Type *SrcTy = V->getType();
4628 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4629 "Cannot truncate or noop with non-integer arguments!");
4631 "getTruncateOrNoop cannot extend!");
4632 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4633 return V; // No conversion
4634 return getTruncateExpr(V, Ty);
4635}
4636
4638 const SCEV *RHS) {
4639 const SCEV *PromotedLHS = LHS;
4640 const SCEV *PromotedRHS = RHS;
4641
4642 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4643 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4644 else
4645 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4646
4647 return getUMaxExpr(PromotedLHS, PromotedRHS);
4648}
4649
4651 const SCEV *RHS,
4652 bool Sequential) {
4653 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4654 return getUMinFromMismatchedTypes(Ops, Sequential);
4655}
4656
4657const SCEV *
4659 bool Sequential) {
4660 assert(!Ops.empty() && "At least one operand must be!");
4661 // Trivial case.
4662 if (Ops.size() == 1)
4663 return Ops[0];
4664
4665 // Find the max type first.
4666 Type *MaxType = nullptr;
4667 for (SCEVUse S : Ops)
4668 if (MaxType)
4669 MaxType = getWiderType(MaxType, S->getType());
4670 else
4671 MaxType = S->getType();
4672 assert(MaxType && "Failed to find maximum type!");
4673
4674 // Extend all ops to max type.
4675 SmallVector<SCEVUse, 2> PromotedOps;
4676 for (SCEVUse S : Ops)
4677 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4678
4679 // Generate umin.
4680 return getUMinExpr(PromotedOps, Sequential);
4681}
4682
4684 // A pointer operand may evaluate to a nonpointer expression, such as null.
4685 if (!V->getType()->isPointerTy())
4686 return V;
4687
4688 while (true) {
4689 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4690 V = AddRec->getStart();
4691 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4692 const SCEV *PtrOp = nullptr;
4693 for (const SCEV *AddOp : Add->operands()) {
4694 if (AddOp->getType()->isPointerTy()) {
4695 assert(!PtrOp && "Cannot have multiple pointer ops");
4696 PtrOp = AddOp;
4697 }
4698 }
4699 assert(PtrOp && "Must have pointer op");
4700 V = PtrOp;
4701 } else // Not something we can look further into.
4702 return V;
4703 }
4704}
4705
4706/// Push users of the given Instruction onto the given Worklist.
4710 // Push the def-use children onto the Worklist stack.
4711 for (User *U : I->users()) {
4712 auto *UserInsn = cast<Instruction>(U);
4713 if (Visited.insert(UserInsn).second)
4714 Worklist.push_back(UserInsn);
4715 }
4716}
4717
4718namespace {
4719
4720/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4721/// expression in case its Loop is L. If it is not L then
4722/// if IgnoreOtherLoops is true then use AddRec itself
4723/// otherwise rewrite cannot be done.
4724/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4725class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4726public:
4727 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4728 bool IgnoreOtherLoops = true) {
4729 SCEVInitRewriter Rewriter(L, SE);
4730 const SCEV *Result = Rewriter.visit(S);
4731 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4732 return SE.getCouldNotCompute();
4733 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4734 ? SE.getCouldNotCompute()
4735 : Result;
4736 }
4737
4738 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4739 if (!SE.isLoopInvariant(Expr, L))
4740 SeenLoopVariantSCEVUnknown = true;
4741 return Expr;
4742 }
4743
4744 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4745 // Only re-write AddRecExprs for this loop.
4746 if (Expr->getLoop() == L)
4747 return Expr->getStart();
4748 SeenOtherLoops = true;
4749 return Expr;
4750 }
4751
4752 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4753
4754 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4755
4756private:
4757 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4758 : SCEVRewriteVisitor(SE), L(L) {}
4759
4760 const Loop *L;
4761 bool SeenLoopVariantSCEVUnknown = false;
4762 bool SeenOtherLoops = false;
4763};
4764
4765/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4766/// increment expression in case its Loop is L. If it is not L then
4767/// use AddRec itself.
4768/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4769class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4770public:
4771 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4772 SCEVPostIncRewriter Rewriter(L, SE);
4773 const SCEV *Result = Rewriter.visit(S);
4774 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4775 ? SE.getCouldNotCompute()
4776 : Result;
4777 }
4778
4779 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4780 if (!SE.isLoopInvariant(Expr, L))
4781 SeenLoopVariantSCEVUnknown = true;
4782 return Expr;
4783 }
4784
4785 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4786 // Only re-write AddRecExprs for this loop.
4787 if (Expr->getLoop() == L)
4788 return Expr->getPostIncExpr(SE);
4789 SeenOtherLoops = true;
4790 return Expr;
4791 }
4792
4793 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4794
4795 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4796
4797private:
4798 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4799 : SCEVRewriteVisitor(SE), L(L) {}
4800
4801 const Loop *L;
4802 bool SeenLoopVariantSCEVUnknown = false;
4803 bool SeenOtherLoops = false;
4804};
4805
4806/// This class evaluates the compare condition by matching it against the
4807/// condition of loop latch. If there is a match we assume a true value
4808/// for the condition while building SCEV nodes.
4809class SCEVBackedgeConditionFolder
4810 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4811public:
4812 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4813 ScalarEvolution &SE) {
4814 bool IsPosBECond = false;
4815 Value *BECond = nullptr;
4816 if (BasicBlock *Latch = L->getLoopLatch()) {
4817 if (CondBrInst *BI = dyn_cast<CondBrInst>(Latch->getTerminator())) {
4818 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4819 "Both outgoing branches should not target same header!");
4820 BECond = BI->getCondition();
4821 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4822 } else {
4823 return S;
4824 }
4825 }
4826 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4827 return Rewriter.visit(S);
4828 }
4829
4830 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4831 const SCEV *Result = Expr;
4832 bool InvariantF = SE.isLoopInvariant(Expr, L);
4833
4834 if (!InvariantF) {
4836 switch (I->getOpcode()) {
4837 case Instruction::Select: {
4838 SelectInst *SI = cast<SelectInst>(I);
4839 std::optional<const SCEV *> Res =
4840 compareWithBackedgeCondition(SI->getCondition());
4841 if (Res) {
4842 bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
4843 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4844 }
4845 break;
4846 }
4847 default: {
4848 std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4849 if (Res)
4850 Result = *Res;
4851 break;
4852 }
4853 }
4854 }
4855 return Result;
4856 }
4857
4858private:
4859 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4860 bool IsPosBECond, ScalarEvolution &SE)
4861 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4862 IsPositiveBECond(IsPosBECond) {}
4863
4864 std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4865
4866 const Loop *L;
4867 /// Loop back condition.
4868 Value *BackedgeCond = nullptr;
4869 /// Set to true if loop back is on positive branch condition.
4870 bool IsPositiveBECond;
4871};
4872
4873std::optional<const SCEV *>
4874SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4875
4876 // If value matches the backedge condition for loop latch,
4877 // then return a constant evolution node based on loopback
4878 // branch taken.
4879 if (BackedgeCond == IC)
4880 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4882 return std::nullopt;
4883}
4884
4885class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4886public:
4887 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4888 ScalarEvolution &SE) {
4889 SCEVShiftRewriter Rewriter(L, SE);
4890 const SCEV *Result = Rewriter.visit(S);
4891 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4892 }
4893
4894 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4895 // Only allow AddRecExprs for this loop.
4896 if (!SE.isLoopInvariant(Expr, L))
4897 Valid = false;
4898 return Expr;
4899 }
4900
4901 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4902 if (Expr->getLoop() == L && Expr->isAffine())
4903 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4904 Valid = false;
4905 return Expr;
4906 }
4907
4908 bool isValid() { return Valid; }
4909
4910private:
4911 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4912 : SCEVRewriteVisitor(SE), L(L) {}
4913
4914 const Loop *L;
4915 bool Valid = true;
4916};
4917
4918} // end anonymous namespace
4919
4920void ScalarEvolution::inferNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4921 if (!AR->isAffine())
4922 return;
4923
4924 // Force computation of ranges, which will also perform range-based flag
4925 // inference.
4926 if (!AR->hasNoSignedWrap())
4927 (void)getSignedRange(AR);
4928
4929 if (!AR->hasNoUnsignedWrap())
4930 (void)getUnsignedRange(AR);
4931
4932 if (!AR->hasNoSelfWrap()) {
4933 const SCEV *BECount = getConstantMaxBackedgeTakenCount(AR->getLoop());
4934 if (const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(BECount)) {
4935 ConstantRange StepCR = getSignedRange(AR->getStepRecurrence(*this));
4936 const APInt &BECountAP = BECountMax->getAPInt();
4937 unsigned NoOverflowBitWidth =
4938 BECountAP.getActiveBits() + StepCR.getMinSignedBits();
4939 if (NoOverflowBitWidth <= getTypeSizeInBits(AR->getType()))
4940 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
4941 }
4942 }
4943}
4944
4946ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4948
4949 if (AR->hasNoSignedWrap())
4950 return Result;
4951
4952 if (!AR->isAffine())
4953 return Result;
4954
4955 // This function can be expensive, only try to prove NSW once per AddRec.
4956 if (!SignedWrapViaInductionTried.insert(AR).second)
4957 return Result;
4958
4959 const SCEV *Step = AR->getStepRecurrence(*this);
4960 const Loop *L = AR->getLoop();
4961
4962 // Check whether the backedge-taken count is SCEVCouldNotCompute.
4963 // Note that this serves two purposes: It filters out loops that are
4964 // simply not analyzable, and it covers the case where this code is
4965 // being called from within backedge-taken count analysis, such that
4966 // attempting to ask for the backedge-taken count would likely result
4967 // in infinite recursion. In the later case, the analysis code will
4968 // cope with a conservative value, and it will take care to purge
4969 // that value once it has finished.
4970 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4971
4972 // Normally, in the cases we can prove no-overflow via a
4973 // backedge guarding condition, we can also compute a backedge
4974 // taken count for the loop. The exceptions are assumptions and
4975 // guards present in the loop -- SCEV is not great at exploiting
4976 // these to compute max backedge taken counts, but can still use
4977 // these to prove lack of overflow. Use this fact to avoid
4978 // doing extra work that may not pay off.
4979
4980 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4981 AC.assumptions().empty())
4982 return Result;
4983
4984 // If the backedge is guarded by a comparison with the pre-inc value the
4985 // addrec is safe. Also, if the entry is guarded by a comparison with the
4986 // start value and the backedge is guarded by a comparison with the post-inc
4987 // value, the addrec is safe.
4989 const SCEV *OverflowLimit =
4990 getSignedOverflowLimitForStep(Step, &Pred, this);
4991 if (OverflowLimit &&
4992 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
4993 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
4994 Result = setFlags(Result, SCEV::FlagNSW);
4995 }
4996 return Result;
4997}
4999ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5001
5002 if (AR->hasNoUnsignedWrap())
5003 return Result;
5004
5005 if (!AR->isAffine())
5006 return Result;
5007
5008 // This function can be expensive, only try to prove NUW once per AddRec.
5009 if (!UnsignedWrapViaInductionTried.insert(AR).second)
5010 return Result;
5011
5012 const SCEV *Step = AR->getStepRecurrence(*this);
5013 const Loop *L = AR->getLoop();
5014
5015 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5016 // Note that this serves two purposes: It filters out loops that are
5017 // simply not analyzable, and it covers the case where this code is
5018 // being called from within backedge-taken count analysis, such that
5019 // attempting to ask for the backedge-taken count would likely result
5020 // in infinite recursion. In the later case, the analysis code will
5021 // cope with a conservative value, and it will take care to purge
5022 // that value once it has finished.
5023 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5024
5025 // Normally, in the cases we can prove no-overflow via a
5026 // backedge guarding condition, we can also compute a backedge
5027 // taken count for the loop. The exceptions are assumptions and
5028 // guards present in the loop -- SCEV is not great at exploiting
5029 // these to compute max backedge taken counts, but can still use
5030 // these to prove lack of overflow. Use this fact to avoid
5031 // doing extra work that may not pay off.
5032
5033 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5034 AC.assumptions().empty())
5035 return Result;
5036
5037 // If the backedge is guarded by a comparison with the pre-inc value the
5038 // addrec is safe. Also, if the entry is guarded by a comparison with the
5039 // start value and the backedge is guarded by a comparison with the post-inc
5040 // value, the addrec is safe.
5041 if (isKnownPositive(Step)) {
5043 const SCEV *OverflowLimit =
5045 if (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5046 isKnownOnEveryIteration(Pred, AR, OverflowLimit))
5047 Result = setFlags(Result, SCEV::FlagNUW);
5048 }
5049 return Result;
5050}
5051
5052namespace {
5053
5054/// Represents an abstract binary operation. This may exist as a
5055/// normal instruction or constant expression, or may have been
5056/// derived from an expression tree.
5057struct BinaryOp {
5058 unsigned Opcode;
5059 Value *LHS;
5060 Value *RHS;
5061 bool IsNSW = false;
5062 bool IsNUW = false;
5063
5064 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5065 /// constant expression.
5066 Operator *Op = nullptr;
5067
5068 explicit BinaryOp(Operator *Op)
5069 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5070 Op(Op) {
5071 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5072 IsNSW = OBO->hasNoSignedWrap();
5073 IsNUW = OBO->hasNoUnsignedWrap();
5074 }
5075 }
5076
5077 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5078 bool IsNUW = false)
5079 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5080};
5081
5082} // end anonymous namespace
5083
5084/// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
5085static std::optional<BinaryOp> MatchBinaryOp(Value *V,
5086 const DominatorTree &DT) {
5087 auto *Op = dyn_cast<Operator>(V);
5088 if (!Op)
5089 return std::nullopt;
5090
5091 // Implementation detail: all the cleverness here should happen without
5092 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5093 // SCEV expressions when possible, and we should not break that.
5094
5095 switch (Op->getOpcode()) {
5096 case Instruction::Add:
5097 case Instruction::Sub:
5098 case Instruction::Mul:
5099 case Instruction::UDiv:
5100 case Instruction::URem:
5101 case Instruction::And:
5102 case Instruction::AShr:
5103 case Instruction::Shl:
5104 return BinaryOp(Op);
5105
5106 case Instruction::Or: {
5107 // Convert or disjoint into add nuw nsw.
5108 if (cast<PossiblyDisjointInst>(Op)->isDisjoint()) {
5109 BinaryOp BinOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
5110 /*IsNSW=*/true, /*IsNUW=*/true);
5111 // Keep the reference to the original instruction so that we can later
5112 // check whether it can produce poison value or not.
5113 BinOp.Op = Op;
5114 return BinOp;
5115 }
5116 return BinaryOp(Op);
5117 }
5118
5119 case Instruction::Xor:
5120 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5121 // If the RHS of the xor is a signmask, then this is just an add.
5122 // Instcombine turns add of signmask into xor as a strength reduction step.
5123 if (RHSC->getValue().isSignMask())
5124 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5125 // Binary `xor` is a bit-wise `add`.
5126 if (V->getType()->isIntegerTy(1))
5127 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5128 return BinaryOp(Op);
5129
5130 case Instruction::LShr:
5131 // Turn logical shift right of a constant into a unsigned divide.
5132 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5133 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5134
5135 // If the shift count is not less than the bitwidth, the result of
5136 // the shift is undefined. Don't try to analyze it, because the
5137 // resolution chosen here may differ from the resolution chosen in
5138 // other parts of the compiler.
5139 if (SA->getValue().ult(BitWidth)) {
5140 Constant *X =
5141 ConstantInt::get(SA->getContext(),
5142 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5143 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5144 }
5145 }
5146 return BinaryOp(Op);
5147
5148 case Instruction::ExtractValue: {
5149 auto *EVI = cast<ExtractValueInst>(Op);
5150 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5151 break;
5152
5153 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5154 if (!WO)
5155 break;
5156
5157 Instruction::BinaryOps BinOp = WO->getBinaryOp();
5158 bool Signed = WO->isSigned();
5159 // TODO: Should add nuw/nsw flags for mul as well.
5160 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5161 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5162
5163 // Now that we know that all uses of the arithmetic-result component of
5164 // CI are guarded by the overflow check, we can go ahead and pretend
5165 // that the arithmetic is non-overflowing.
5166 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5167 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5168 }
5169
5170 default:
5171 break;
5172 }
5173
5174 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5175 // semantics as a Sub, return a binary sub expression.
5176 if (auto *II = dyn_cast<IntrinsicInst>(V))
5177 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5178 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5179
5180 return std::nullopt;
5181}
5182
5183/// Helper function to createAddRecFromPHIWithCasts. We have a phi
5184/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5185/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5186/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5187/// follows one of the following patterns:
5188/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5189/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5190/// If the SCEV expression of \p Op conforms with one of the expected patterns
5191/// we return the type of the truncation operation, and indicate whether the
5192/// truncated type should be treated as signed/unsigned by setting
5193/// \p Signed to true/false, respectively.
5194static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5195 bool &Signed, ScalarEvolution &SE) {
5196 // The case where Op == SymbolicPHI (that is, with no type conversions on
5197 // the way) is handled by the regular add recurrence creating logic and
5198 // would have already been triggered in createAddRecForPHI. Reaching it here
5199 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5200 // because one of the other operands of the SCEVAddExpr updating this PHI is
5201 // not invariant).
5202 //
5203 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5204 // this case predicates that allow us to prove that Op == SymbolicPHI will
5205 // be added.
5206 if (Op == SymbolicPHI)
5207 return nullptr;
5208
5209 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5210 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5211 if (SourceBits != NewBits)
5212 return nullptr;
5213
5214 if (match(Op, m_scev_SExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5215 Signed = true;
5216 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5217 }
5218 if (match(Op, m_scev_ZExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5219 Signed = false;
5220 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5221 }
5222 return nullptr;
5223}
5224
5225static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5226 if (!PN->getType()->isIntegerTy())
5227 return nullptr;
5228 const Loop *L = LI.getLoopFor(PN->getParent());
5229 if (!L || L->getHeader() != PN->getParent())
5230 return nullptr;
5231 return L;
5232}
5233
5234// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5235// computation that updates the phi follows the following pattern:
5236// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5237// which correspond to a phi->trunc->sext/zext->add->phi update chain.
5238// If so, try to see if it can be rewritten as an AddRecExpr under some
5239// Predicates. If successful, return them as a pair. Also cache the results
5240// of the analysis.
5241//
5242// Example usage scenario:
5243// Say the Rewriter is called for the following SCEV:
5244// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5245// where:
5246// %X = phi i64 (%Start, %BEValue)
5247// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5248// and call this function with %SymbolicPHI = %X.
5249//
5250// The analysis will find that the value coming around the backedge has
5251// the following SCEV:
5252// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5253// Upon concluding that this matches the desired pattern, the function
5254// will return the pair {NewAddRec, SmallPredsVec} where:
5255// NewAddRec = {%Start,+,%Step}
5256// SmallPredsVec = {P1, P2, P3} as follows:
5257// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5258// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5259// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5260// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5261// under the predicates {P1,P2,P3}.
5262// This predicated rewrite will be cached in PredicatedSCEVRewrites:
5263// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5264//
5265// TODO's:
5266//
5267// 1) Extend the Induction descriptor to also support inductions that involve
5268// casts: When needed (namely, when we are called in the context of the
5269// vectorizer induction analysis), a Set of cast instructions will be
5270// populated by this method, and provided back to isInductionPHI. This is
5271// needed to allow the vectorizer to properly record them to be ignored by
5272// the cost model and to avoid vectorizing them (otherwise these casts,
5273// which are redundant under the runtime overflow checks, will be
5274// vectorized, which can be costly).
5275//
5276// 2) Support additional induction/PHISCEV patterns: We also want to support
5277// inductions where the sext-trunc / zext-trunc operations (partly) occur
5278// after the induction update operation (the induction increment):
5279//
5280// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5281// which correspond to a phi->add->trunc->sext/zext->phi update chain.
5282//
5283// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5284// which correspond to a phi->trunc->add->sext/zext->phi update chain.
5285//
5286// 3) Outline common code with createAddRecFromPHI to avoid duplication.
5287std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5288ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5290
5291 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5292 // return an AddRec expression under some predicate.
5293
5294 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5295 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5296 assert(L && "Expecting an integer loop header phi");
5297
5298 // The loop may have multiple entrances or multiple exits; we can analyze
5299 // this phi as an addrec if it has a unique entry value and a unique
5300 // backedge value.
5301 Value *BEValueV = nullptr, *StartValueV = nullptr;
5302 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5303 Value *V = PN->getIncomingValue(i);
5304 if (L->contains(PN->getIncomingBlock(i))) {
5305 if (!BEValueV) {
5306 BEValueV = V;
5307 } else if (BEValueV != V) {
5308 BEValueV = nullptr;
5309 break;
5310 }
5311 } else if (!StartValueV) {
5312 StartValueV = V;
5313 } else if (StartValueV != V) {
5314 StartValueV = nullptr;
5315 break;
5316 }
5317 }
5318 if (!BEValueV || !StartValueV)
5319 return std::nullopt;
5320
5321 const SCEV *BEValue = getSCEV(BEValueV);
5322
5323 // If the value coming around the backedge is an add with the symbolic
5324 // value we just inserted, possibly with casts that we can ignore under
5325 // an appropriate runtime guard, then we found a simple induction variable!
5326 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5327 if (!Add)
5328 return std::nullopt;
5329
5330 // If there is a single occurrence of the symbolic value, possibly
5331 // casted, replace it with a recurrence.
5332 unsigned FoundIndex = Add->getNumOperands();
5333 Type *TruncTy = nullptr;
5334 bool Signed;
5335 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5336 if ((TruncTy =
5337 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5338 if (FoundIndex == e) {
5339 FoundIndex = i;
5340 break;
5341 }
5342
5343 if (FoundIndex == Add->getNumOperands())
5344 return std::nullopt;
5345
5346 // Create an add with everything but the specified operand.
5348 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5349 if (i != FoundIndex)
5350 Ops.push_back(Add->getOperand(i));
5351 const SCEV *Accum = getAddExpr(Ops);
5352
5353 // The runtime checks will not be valid if the step amount is
5354 // varying inside the loop.
5355 if (!isLoopInvariant(Accum, L))
5356 return std::nullopt;
5357
5358 // *** Part2: Create the predicates
5359
5360 // Analysis was successful: we have a phi-with-cast pattern for which we
5361 // can return an AddRec expression under the following predicates:
5362 //
5363 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5364 // fits within the truncated type (does not overflow) for i = 0 to n-1.
5365 // P2: An Equal predicate that guarantees that
5366 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5367 // P3: An Equal predicate that guarantees that
5368 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5369 //
5370 // As we next prove, the above predicates guarantee that:
5371 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5372 //
5373 //
5374 // More formally, we want to prove that:
5375 // Expr(i+1) = Start + (i+1) * Accum
5376 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5377 //
5378 // Given that:
5379 // 1) Expr(0) = Start
5380 // 2) Expr(1) = Start + Accum
5381 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5382 // 3) Induction hypothesis (step i):
5383 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5384 //
5385 // Proof:
5386 // Expr(i+1) =
5387 // = Start + (i+1)*Accum
5388 // = (Start + i*Accum) + Accum
5389 // = Expr(i) + Accum
5390 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5391 // :: from step i
5392 //
5393 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5394 //
5395 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5396 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
5397 // + Accum :: from P3
5398 //
5399 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5400 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5401 //
5402 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5403 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5404 //
5405 // By induction, the same applies to all iterations 1<=i<n:
5406 //
5407
5408 // Create a truncated addrec for which we will add a no overflow check (P1).
5409 const SCEV *StartVal = getSCEV(StartValueV);
5410 const SCEV *PHISCEV =
5411 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5412 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagNone);
5413
5414 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5415 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5416 // will be constant.
5417 //
5418 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5419 // add P1.
5420 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5424 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5425 Predicates.push_back(AddRecPred);
5426 }
5427
5428 // Create the Equal Predicates P2,P3:
5429
5430 // It is possible that the predicates P2 and/or P3 are computable at
5431 // compile time due to StartVal and/or Accum being constants.
5432 // If either one is, then we can check that now and escape if either P2
5433 // or P3 is false.
5434
5435 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5436 // for each of StartVal and Accum
5437 auto getExtendedExpr = [&](const SCEV *Expr,
5438 bool CreateSignExtend) -> const SCEV * {
5439 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5440 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5441 const SCEV *ExtendedExpr =
5442 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5443 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5444 return ExtendedExpr;
5445 };
5446
5447 // Given:
5448 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5449 // = getExtendedExpr(Expr)
5450 // Determine whether the predicate P: Expr == ExtendedExpr
5451 // is known to be false at compile time
5452 auto PredIsKnownFalse = [&](const SCEV *Expr,
5453 const SCEV *ExtendedExpr) -> bool {
5454 return Expr != ExtendedExpr &&
5455 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5456 };
5457
5458 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5459 if (PredIsKnownFalse(StartVal, StartExtended)) {
5460 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5461 return std::nullopt;
5462 }
5463
5464 // The Step is always Signed (because the overflow checks are either
5465 // NSSW or NUSW)
5466 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5467 if (PredIsKnownFalse(Accum, AccumExtended)) {
5468 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5469 return std::nullopt;
5470 }
5471
5472 auto AppendPredicate = [&](const SCEV *Expr,
5473 const SCEV *ExtendedExpr) -> void {
5474 if (Expr != ExtendedExpr &&
5475 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5476 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5477 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5478 Predicates.push_back(Pred);
5479 }
5480 };
5481
5482 AppendPredicate(StartVal, StartExtended);
5483 AppendPredicate(Accum, AccumExtended);
5484
5485 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5486 // which the casts had been folded away. The caller can rewrite SymbolicPHI
5487 // into NewAR if it will also add the runtime overflow checks specified in
5488 // Predicates.
5489 const SCEV *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagNone);
5490
5491 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5492 std::make_pair(NewAR, Predicates);
5493 // Remember the result of the analysis for this SCEV at this locayyytion.
5494 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5495 return PredRewrite;
5496}
5497
5498std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5500 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5501 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5502 if (!L)
5503 return std::nullopt;
5504
5505 // Check to see if we already analyzed this PHI.
5506 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5507 if (I != PredicatedSCEVRewrites.end()) {
5508 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5509 I->second;
5510 // Analysis was done before and failed to create an AddRec:
5511 if (Rewrite.first == SymbolicPHI)
5512 return std::nullopt;
5513 // Analysis was done before and succeeded to create an AddRec under
5514 // a predicate:
5515 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5516 assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5517 return Rewrite;
5518 }
5519
5520 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5521 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5522
5523 // Record in the cache that the analysis failed
5524 if (!Rewrite) {
5526 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5527 return std::nullopt;
5528 }
5529
5530 return Rewrite;
5531}
5532
5533// FIXME: This utility is currently required because the Rewriter currently
5534// does not rewrite this expression:
5535// {0, +, (sext ix (trunc iy to ix) to iy)}
5536// into {0, +, %step},
5537// even when the following Equal predicate exists:
5538// "%step == (sext ix (trunc iy to ix) to iy)".
5540 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2,
5541 ArrayRef<const SCEVPredicate *> NoWrapPreds) const {
5542 if (AR1 == AR2)
5543 return true;
5544
5545 SCEVUnionPredicate NoWrapUnionPred(NoWrapPreds, SE);
5546 SCEVUnionPredicate AllPreds = Preds->getUnionWith(&NoWrapUnionPred, SE);
5547 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5548 if (Expr1 != Expr2 &&
5549 !AllPreds.implies(SE.getEqualPredicate(Expr1, Expr2), SE) &&
5550 !AllPreds.implies(SE.getEqualPredicate(Expr2, Expr1), SE))
5551 return false;
5552 return true;
5553 };
5554
5555 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5556 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5557 return false;
5558 return true;
5559}
5560
5562 ScalarEvolution &SE) {
5563 SCEVFlags Flags = SCEV::FlagNone;
5564 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
5565 // If the increment has any nowrap flags, then we know the address
5566 // space cannot be wrapped around.
5567 if (NW != GEPNoWrapFlags::none())
5569 // If the GEP is nuw or nusw with non-negative offset, we know that
5570 // no unsigned wrap occurs. We cannot set the nsw flag as only the
5571 // offset is treated as signed, while the base is unsigned.
5572 if (NW.hasNoUnsignedWrap() ||
5573 (NW.hasNoUnsignedSignedWrap() && SE.isKnownNonNegative(Accum)))
5575
5576 return Flags;
5577}
5578
5579/// A helper function for createAddRecFromPHI to handle simple cases.
5580///
5581/// This function tries to find an AddRec expression for the simplest (yet most
5582/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5583/// If it fails, createAddRecFromPHI will use a more general, but slow,
5584/// technique for finding the AddRec expression.
5585const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5586 Value *BEValueV,
5587 Value *StartValueV) {
5588 const Loop *L = LI.getLoopFor(PN->getParent());
5589 assert(L && L->getHeader() == PN->getParent());
5590 assert(BEValueV && StartValueV);
5591
5592 const SCEV *Accum = nullptr;
5594 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5595 if (BO->Opcode != Instruction::Add)
5596 return nullptr;
5597
5598 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5599 Accum = getSCEV(BO->RHS);
5600 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5601 Accum = getSCEV(BO->LHS);
5602
5603 if (!Accum)
5604 return nullptr;
5605
5606 if (BO->IsNUW)
5607 Flags = setFlags(Flags, SCEV::FlagNUW);
5608 if (BO->IsNSW)
5609 Flags = setFlags(Flags, SCEV::FlagNSW);
5610 } else {
5611 // Handle pointer induction variable: PN = PHI(Start, gep PN,
5612 // LoopInvariant).
5613 auto *GEP = dyn_cast<GEPOperator>(BEValueV);
5614 if (!GEP || GEP->getPointerOperand() != PN || GEP->getNumIndices() != 1)
5615 return nullptr;
5616 Value *Idx = *GEP->idx_begin();
5617 if (!L->isLoopInvariant(Idx))
5618 return nullptr;
5619
5620 Type *IntIdxTy = getEffectiveSCEVType(GEP->getType());
5621 Accum = getMulExpr(getTruncateOrSignExtend(getSCEV(Idx), IntIdxTy),
5622 getSizeOfExpr(IntIdxTy, GEP->getSourceElementType()));
5623 Flags = getNoWrapFlagsForGEP(GEP, Accum, *this);
5624 }
5625
5626 const SCEV *StartVal = getSCEV(StartValueV);
5627 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5628 insertValueToMap(PN, PHISCEV);
5629
5630 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5631 inferNoWrapViaConstantRanges(AR);
5632
5633 // We can add Flags to the post-inc expression only if we
5634 // know that it is *undefined behavior* for BEValueV to
5635 // overflow.
5636 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5637 assert(isLoopInvariant(Accum, L) &&
5638 "Accum is defined outside L, but is not invariant?");
5639 if (isAddRecNeverPoison(BEInst, L))
5640 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5641 }
5642
5643 return PHISCEV;
5644}
5645
5646const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5647 const Loop *L = LI.getLoopFor(PN->getParent());
5648 if (!L || L->getHeader() != PN->getParent())
5649 return nullptr;
5650
5651 // The loop may have multiple entrances or multiple exits; we can analyze
5652 // this phi as an addrec if it has a unique entry value and a unique
5653 // backedge value.
5654 Value *BEValueV = nullptr, *StartValueV = nullptr;
5655 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5656 Value *V = PN->getIncomingValue(i);
5657 if (L->contains(PN->getIncomingBlock(i))) {
5658 if (!BEValueV) {
5659 BEValueV = V;
5660 } else if (BEValueV != V) {
5661 BEValueV = nullptr;
5662 break;
5663 }
5664 } else if (!StartValueV) {
5665 StartValueV = V;
5666 } else if (StartValueV != V) {
5667 StartValueV = nullptr;
5668 break;
5669 }
5670 }
5671 if (!BEValueV || !StartValueV)
5672 return nullptr;
5673
5674 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5675 "PHI node already processed?");
5676
5677 // First, try to find AddRec expression without creating a fictituos symbolic
5678 // value for PN.
5679 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5680 return S;
5681
5682 // Handle PHI node value symbolically.
5683 const SCEV *SymbolicName = getUnknown(PN);
5684 insertValueToMap(PN, SymbolicName);
5685
5686 // Using this symbolic name for the PHI, analyze the value coming around
5687 // the back-edge.
5688 const SCEV *BEValue = getSCEV(BEValueV);
5689
5690 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5691 // has a special value for the first iteration of the loop.
5692
5693 // If the value coming around the backedge is an add with the symbolic
5694 // value we just inserted, then we found a simple induction variable!
5695 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5696 // If there is a single occurrence of the symbolic value, replace it
5697 // with a recurrence.
5698 unsigned FoundIndex = Add->getNumOperands();
5699 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5700 if (Add->getOperand(i) == SymbolicName)
5701 if (FoundIndex == e) {
5702 FoundIndex = i;
5703 break;
5704 }
5705
5706 if (FoundIndex != Add->getNumOperands()) {
5707 // Create an add with everything but the specified operand.
5709 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5710 if (i != FoundIndex)
5711 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5712 L, *this));
5713 const SCEV *Accum = getAddExpr(Ops);
5714
5715 // This is not a valid addrec if the step amount is varying each
5716 // loop iteration, but is not itself an addrec in this loop.
5717 if (isLoopInvariant(Accum, L) ||
5718 (isa<SCEVAddRecExpr>(Accum) &&
5719 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5721
5722 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5723 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5724 if (BO->IsNUW)
5725 Flags = setFlags(Flags, SCEV::FlagNUW);
5726 if (BO->IsNSW)
5727 Flags = setFlags(Flags, SCEV::FlagNSW);
5728 }
5729 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5730 if (GEP->getOperand(0) == PN)
5731 Flags = getNoWrapFlagsForGEP(GEP, Accum, *this);
5732
5733 // We cannot transfer nuw and nsw flags from subtraction
5734 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5735 // for instance.
5736 }
5737
5738 const SCEV *StartVal = getSCEV(StartValueV);
5739 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5740
5741 // Okay, for the entire analysis of this edge we assumed the PHI
5742 // to be symbolic. We now need to go back and purge all of the
5743 // entries for the scalars that use the symbolic expression.
5744 forgetMemoizedResults({SymbolicName});
5745 insertValueToMap(PN, PHISCEV);
5746
5747 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5748 inferNoWrapViaConstantRanges(AR);
5749
5750 // We can add Flags to the post-inc expression only if we
5751 // know that it is *undefined behavior* for BEValueV to
5752 // overflow.
5753 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5754 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5755 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5756
5757 return PHISCEV;
5758 }
5759 }
5760 } else {
5761 // Otherwise, this could be a loop like this:
5762 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5763 // In this case, j = {1,+,1} and BEValue is j.
5764 // Because the other in-value of i (0) fits the evolution of BEValue
5765 // i really is an addrec evolution.
5766 //
5767 // We can generalize this saying that i is the shifted value of BEValue
5768 // by one iteration:
5769 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5770
5771 // Do not allow refinement in rewriting of BEValue.
5772 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5773 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5774 if (Shifted != getCouldNotCompute() && Start != getCouldNotCompute() &&
5775 isGuaranteedNotToCauseUB(Shifted) && ::impliesPoison(Shifted, Start)) {
5776 const SCEV *StartVal = getSCEV(StartValueV);
5777 if (Start == StartVal) {
5778 // Okay, for the entire analysis of this edge we assumed the PHI
5779 // to be symbolic. We now need to go back and purge all of the
5780 // entries for the scalars that use the symbolic expression.
5781 forgetMemoizedResults({SymbolicName});
5782 insertValueToMap(PN, Shifted);
5783 return Shifted;
5784 }
5785 }
5786 }
5787
5788 // Remove the temporary PHI node SCEV that has been inserted while intending
5789 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5790 // as it will prevent later (possibly simpler) SCEV expressions to be added
5791 // to the ValueExprMap.
5792 eraseValueFromMap(PN);
5793
5794 return nullptr;
5795}
5796
5797// Try to match a control flow sequence that branches out at BI and merges back
5798// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5799// match.
5801 Value *&C, Value *&LHS, Value *&RHS) {
5802 C = BI->getCondition();
5803
5804 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5805 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5806
5807 Use &LeftUse = Merge->getOperandUse(0);
5808 Use &RightUse = Merge->getOperandUse(1);
5809
5810 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5811 LHS = LeftUse;
5812 RHS = RightUse;
5813 return true;
5814 }
5815
5816 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5817 LHS = RightUse;
5818 RHS = LeftUse;
5819 return true;
5820 }
5821
5822 return false;
5823}
5824
5826 Value *&Cond, Value *&LHS,
5827 Value *&RHS) {
5828 auto IsReachable =
5829 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5830 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5831 // Try to match
5832 //
5833 // br %cond, label %left, label %right
5834 // left:
5835 // br label %merge
5836 // right:
5837 // br label %merge
5838 // merge:
5839 // V = phi [ %x, %left ], [ %y, %right ]
5840 //
5841 // as "select %cond, %x, %y"
5842
5843 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5844 assert(IDom && "At least the entry block should dominate PN");
5845
5846 auto *BI = dyn_cast<CondBrInst>(IDom->getTerminator());
5847 return BI && BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS);
5848 }
5849 return false;
5850}
5851
5852const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5853 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5854 if (getOperandsForSelectLikePHI(DT, PN, Cond, LHS, RHS) &&
5857 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5858
5859 return nullptr;
5860}
5861
5863 BinaryOperator *CommonInst = nullptr;
5864 // Check if instructions are identical.
5865 for (Value *Incoming : PN->incoming_values()) {
5866 auto *IncomingInst = dyn_cast<BinaryOperator>(Incoming);
5867 if (!IncomingInst)
5868 return nullptr;
5869 if (CommonInst) {
5870 if (!CommonInst->isIdenticalToWhenDefined(IncomingInst))
5871 return nullptr; // Not identical, give up
5872 } else {
5873 // Remember binary operator
5874 CommonInst = IncomingInst;
5875 }
5876 }
5877 return CommonInst;
5878}
5879
5880/// Returns SCEV for the first operand of a phi if all phi operands have
5881/// identical opcodes and operands
5882/// eg.
5883/// a: %add = %a + %b
5884/// br %c
5885/// b: %add1 = %a + %b
5886/// br %c
5887/// c: %phi = phi [%add, a], [%add1, b]
5888/// scev(%phi) => scev(%add)
5889const SCEV *
5890ScalarEvolution::createNodeForPHIWithIdenticalOperands(PHINode *PN) {
5891 BinaryOperator *CommonInst = getCommonInstForPHI(PN);
5892 if (!CommonInst)
5893 return nullptr;
5894
5895 // Check if SCEV exprs for instructions are identical.
5896 const SCEV *CommonSCEV = getSCEV(CommonInst);
5897 bool SCEVExprsIdentical =
5899 [this, CommonSCEV](Value *V) { return CommonSCEV == getSCEV(V); });
5900 return SCEVExprsIdentical ? CommonSCEV : nullptr;
5901}
5902
5903const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5904 if (const SCEV *S = createAddRecFromPHI(PN))
5905 return S;
5906
5907 // We do not allow simplifying phi (undef, X) to X here, to avoid reusing the
5908 // phi node for X.
5910 PN, {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
5911 /*UseInstrInfo=*/true, /*CanUseUndef=*/false}))
5912 return getSCEV(V);
5913
5914 if (const SCEV *S = createNodeForPHIWithIdenticalOperands(PN))
5915 return S;
5916
5917 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5918 return S;
5919
5920 // If it's not a loop phi, we can't handle it yet.
5921 return getUnknown(PN);
5922}
5923
5924bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
5925 SCEVTypes RootKind) {
5926 struct FindClosure {
5927 const SCEV *OperandToFind;
5928 const SCEVTypes RootKind; // Must be a sequential min/max expression.
5929 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
5930
5931 bool Found = false;
5932
5933 bool canRecurseInto(SCEVTypes Kind) const {
5934 // We can only recurse into the SCEV expression of the same effective type
5935 // as the type of our root SCEV expression, and into zero-extensions.
5936 return RootKind == Kind || NonSequentialRootKind == Kind ||
5937 scZeroExtend == Kind;
5938 };
5939
5940 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
5941 : OperandToFind(OperandToFind), RootKind(RootKind),
5942 NonSequentialRootKind(
5944 RootKind)) {}
5945
5946 bool follow(const SCEV *S) {
5947 Found = S == OperandToFind;
5948
5949 return !isDone() && canRecurseInto(S->getSCEVType());
5950 }
5951
5952 bool isDone() const { return Found; }
5953 };
5954
5955 FindClosure FC(OperandToFind, RootKind);
5956 visitAll(Root, FC);
5957 return FC.Found;
5958}
5959
5960std::optional<const SCEV *>
5961ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
5962 ICmpInst *Cond,
5963 Value *TrueVal,
5964 Value *FalseVal) {
5965 // Try to match some simple smax or umax patterns.
5966 auto *ICI = Cond;
5967
5968 Value *LHS = ICI->getOperand(0);
5969 Value *RHS = ICI->getOperand(1);
5970
5971 switch (ICI->getPredicate()) {
5972 case ICmpInst::ICMP_SLT:
5973 case ICmpInst::ICMP_SLE:
5974 case ICmpInst::ICMP_ULT:
5975 case ICmpInst::ICMP_ULE:
5976 std::swap(LHS, RHS);
5977 [[fallthrough]];
5978 case ICmpInst::ICMP_SGT:
5979 case ICmpInst::ICMP_SGE:
5980 case ICmpInst::ICMP_UGT:
5981 case ICmpInst::ICMP_UGE:
5982 // a > b ? a+x : b+x -> max(a, b)+x
5983 // a > b ? b+x : a+x -> min(a, b)+x
5985 bool Signed = ICI->isSigned();
5986 const SCEV *LA = getSCEV(TrueVal);
5987 const SCEV *RA = getSCEV(FalseVal);
5988 const SCEV *LS = getSCEV(LHS);
5989 const SCEV *RS = getSCEV(RHS);
5990 if (LA->getType()->isPointerTy()) {
5991 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
5992 // Need to make sure we can't produce weird expressions involving
5993 // negated pointers.
5994 if (LA == LS && RA == RS)
5995 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
5996 if (LA == RS && RA == LS)
5997 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
5998 }
5999 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6000 if (Op->getType()->isPointerTy()) {
6003 return Op;
6004 }
6005 if (Signed)
6006 Op = getNoopOrSignExtend(Op, Ty);
6007 else
6008 Op = getNoopOrZeroExtend(Op, Ty);
6009 return Op;
6010 };
6011 LS = CoerceOperand(LS);
6012 RS = CoerceOperand(RS);
6014 break;
6015 const SCEV *LDiff = getMinusSCEV(LA, LS);
6016 const SCEV *RDiff = getMinusSCEV(RA, RS);
6017 if (LDiff == RDiff)
6018 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6019 LDiff);
6020 LDiff = getMinusSCEV(LA, RS);
6021 RDiff = getMinusSCEV(RA, LS);
6022 if (LDiff == RDiff)
6023 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6024 LDiff);
6025 }
6026 break;
6027 case ICmpInst::ICMP_NE:
6028 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
6029 std::swap(TrueVal, FalseVal);
6030 [[fallthrough]];
6031 case ICmpInst::ICMP_EQ:
6032 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
6035 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6036 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y
6037 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y
6038 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6039 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y
6040 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6041 return getAddExpr(getUMaxExpr(X, C), Y);
6042 }
6043 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
6044 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
6045 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
6046 // -> umin_seq(x, umin (..., umin_seq(...), ...))
6048 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6049 const SCEV *X = getSCEV(LHS);
6050 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6051 X = ZExt->getOperand();
6052 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6053 const SCEV *FalseValExpr = getSCEV(FalseVal);
6054 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6055 return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6056 /*Sequential=*/true);
6057 }
6058 }
6059 break;
6060 default:
6061 break;
6062 }
6063
6064 return std::nullopt;
6065}
6066
6067static std::optional<const SCEV *>
6069 const SCEV *TrueExpr, const SCEV *FalseExpr) {
6070 assert(CondExpr->getType()->isIntegerTy(1) &&
6071 TrueExpr->getType() == FalseExpr->getType() &&
6072 TrueExpr->getType()->isIntegerTy(1) &&
6073 "Unexpected operands of a select.");
6074
6075 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
6076 // --> C + (umin_seq cond, x - C)
6077 //
6078 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
6079 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6080 // --> C + (umin_seq ~cond, x - C)
6081
6082 // FIXME: while we can't legally model the case where both of the hands
6083 // are fully variable, we only require that the *difference* is constant.
6084 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6085 return std::nullopt;
6086
6087 const SCEV *X, *C;
6088 if (isa<SCEVConstant>(TrueExpr)) {
6089 CondExpr = SE->getNotSCEV(CondExpr);
6090 X = FalseExpr;
6091 C = TrueExpr;
6092 } else {
6093 X = TrueExpr;
6094 C = FalseExpr;
6095 }
6096 return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6097 /*Sequential=*/true));
6098}
6099
6100static std::optional<const SCEV *>
6102 Value *FalseVal) {
6103 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6104 return std::nullopt;
6105
6106 const auto *SECond = SE->getSCEV(Cond);
6107 const auto *SETrue = SE->getSCEV(TrueVal);
6108 const auto *SEFalse = SE->getSCEV(FalseVal);
6109 return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6110}
6111
6112const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6113 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6114 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6115 assert(TrueVal->getType() == FalseVal->getType() &&
6116 V->getType() == TrueVal->getType() &&
6117 "Types of select hands and of the result must match.");
6118
6119 // For now, only deal with i1-typed `select`s.
6120 if (!V->getType()->isIntegerTy(1))
6121 return getUnknown(V);
6122
6123 if (std::optional<const SCEV *> S =
6124 createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6125 return *S;
6126
6127 return getUnknown(V);
6128}
6129
6130const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6131 Value *TrueVal,
6132 Value *FalseVal) {
6133 // Handle "constant" branch or select. This can occur for instance when a
6134 // loop pass transforms an inner loop and moves on to process the outer loop.
6135 if (auto *CI = dyn_cast<ConstantInt>(Cond))
6136 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6137
6138 if (auto *I = dyn_cast<Instruction>(V)) {
6139 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6140 if (std::optional<const SCEV *> S =
6141 createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6142 TrueVal, FalseVal))
6143 return *S;
6144 }
6145 }
6146
6147 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6148}
6149
6150/// Expand GEP instructions into add and multiply operations. This allows them
6151/// to be analyzed by regular SCEV code.
6152const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6153 assert(GEP->getSourceElementType()->isSized() &&
6154 "GEP source element type must be sized");
6155
6156 SmallVector<SCEVUse, 4> IndexExprs;
6157 for (Value *Index : GEP->indices())
6158 IndexExprs.push_back(getSCEV(Index));
6159 return getGEPExpr(GEP, IndexExprs);
6160}
6161
6162APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S,
6163 const Instruction *CtxI) {
6165 auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6166 return TrailingZeros >= BitWidth
6168 : APInt::getOneBitSet(BitWidth, TrailingZeros);
6169 };
6170 auto GetGCDMultiple = [this, CtxI](const SCEVNAryExpr *N) {
6171 // The result is GCD of all operands results.
6172 APInt Res = getConstantMultiple(N->getOperand(0), CtxI);
6173 for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6175 Res, getConstantMultiple(N->getOperand(I), CtxI));
6176 return Res;
6177 };
6178
6179 switch (S->getSCEVType()) {
6180 case scConstant:
6181 return cast<SCEVConstant>(S)->getAPInt();
6182 case scPtrToAddr:
6183 return getConstantMultiple(cast<SCEVCastExpr>(S)->getOperand());
6184 case scUDivExpr:
6185 case scVScale:
6186 return APInt(BitWidth, 1);
6187 case scTruncate: {
6188 // Only multiples that are a power of 2 will hold after truncation.
6189 const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6190 uint32_t TZ = getMinTrailingZeros(T->getOperand(), CtxI);
6191 return GetShiftedByZeros(TZ);
6192 }
6193 case scZeroExtend: {
6194 const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(S);
6195 return getConstantMultiple(Z->getOperand(), CtxI).zext(BitWidth);
6196 }
6197 case scSignExtend: {
6198 // Only multiples that are a power of 2 will hold after sext.
6199 const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6200 uint32_t TZ = getMinTrailingZeros(E->getOperand(), CtxI);
6201 return GetShiftedByZeros(TZ);
6202 }
6203 case scMulExpr: {
6204 const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6205 if (M->hasNoUnsignedWrap()) {
6206 // The result is the product of all operand results.
6207 APInt Res = getConstantMultiple(M->getOperand(0), CtxI);
6208 for (const SCEV *Operand : M->operands().drop_front())
6209 Res = Res * getConstantMultiple(Operand, CtxI);
6210 return Res;
6211 }
6212
6213 // If there are no wrap guarentees, find the trailing zeros, which is the
6214 // sum of trailing zeros for all its operands.
6215 uint32_t TZ = 0;
6216 for (const SCEV *Operand : M->operands())
6217 TZ += getMinTrailingZeros(Operand, CtxI);
6218 return GetShiftedByZeros(TZ);
6219 }
6220 case scAddExpr:
6221 case scAddRecExpr: {
6222 const SCEVNAryExpr *N = cast<SCEVNAryExpr>(S);
6223 if (N->hasNoUnsignedWrap())
6224 return GetGCDMultiple(N);
6225 // Find the trailing bits, which is the minimum of its operands.
6226 uint32_t TZ = getMinTrailingZeros(N->getOperand(0), CtxI);
6227 for (const SCEV *Operand : N->operands().drop_front())
6228 TZ = std::min(TZ, getMinTrailingZeros(Operand, CtxI));
6229 return GetShiftedByZeros(TZ);
6230 }
6231 case scUMaxExpr:
6232 case scSMaxExpr:
6233 case scUMinExpr:
6234 case scSMinExpr:
6236 return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6237 case scUnknown: {
6238 // Ask ValueTracking for known bits. SCEVUnknown only become available at
6239 // the point their underlying IR instruction has been defined. If CtxI was
6240 // not provided, use:
6241 // * the first instruction in the entry block if it is an argument
6242 // * the instruction itself otherwise.
6243 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6244 if (!CtxI) {
6245 if (isa<Argument>(U->getValue()))
6246 CtxI = &*F.getEntryBlock().begin();
6247 else if (auto *I = dyn_cast<Instruction>(U->getValue()))
6248 CtxI = I;
6249 }
6250 unsigned Known =
6251 computeKnownBits(U->getValue(),
6252 SimplifyQuery(getDataLayout(), &DT, &AC, CtxI)
6253 .allowEphemerals(true))
6254 .countMinTrailingZeros();
6255 return GetShiftedByZeros(Known);
6256 }
6257 case scCouldNotCompute:
6258 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6259 }
6260 llvm_unreachable("Unknown SCEV kind!");
6261}
6262
6264 const Instruction *CtxI) {
6265 // Skip looking up and updating the cache if there is a context instruction,
6266 // as the result will only be valid in the specified context.
6267 if (CtxI)
6268 return getConstantMultipleImpl(S, CtxI);
6269
6270 auto I = ConstantMultipleCache.find(S);
6271 if (I != ConstantMultipleCache.end())
6272 return I->second;
6273
6274 APInt Result = getConstantMultipleImpl(S, CtxI);
6275 auto InsertPair = ConstantMultipleCache.insert({S, Result});
6276 assert(InsertPair.second && "Should insert a new key");
6277 return InsertPair.first->second;
6278}
6279
6281 APInt Multiple = getConstantMultiple(S);
6282 return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6283}
6284
6286 const Instruction *CtxI) {
6287 return std::min(getConstantMultiple(S, CtxI).countTrailingZeros(),
6288 (unsigned)getTypeSizeInBits(S->getType()));
6289}
6290
6291/// Helper method to assign a range to V from metadata present in the IR.
6292static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6294 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6295 return getConstantRangeFromMetadata(*MD);
6296 if (const auto *CB = dyn_cast<CallBase>(V))
6297 if (std::optional<ConstantRange> Range = CB->getRange())
6298 return Range;
6299 }
6300 if (auto *A = dyn_cast<Argument>(V))
6301 if (std::optional<ConstantRange> Range = A->getRange())
6302 return Range;
6303
6304 return std::nullopt;
6305}
6306
6308 SCEVFlags NWFlags = Flags & SCEV::FlagsNoWrapMask;
6309 if (AddRec->getNoWrapFlags(NWFlags) != NWFlags) {
6310 AddRec->setNoWrapFlags(NWFlags);
6311 UnsignedRanges.erase(AddRec);
6312 SignedRanges.erase(AddRec);
6313 ConstantMultipleCache.erase(AddRec);
6314 }
6315}
6316
6317ConstantRange ScalarEvolution::
6318getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6319 const DataLayout &DL = getDataLayout();
6320
6321 unsigned BitWidth = getTypeSizeInBits(U->getType());
6322 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6323
6324 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6325 // use information about the trip count to improve our available range. Note
6326 // that the trip count independent cases are already handled by known bits.
6327 // WARNING: The definition of recurrence used here is subtly different than
6328 // the one used by AddRec (and thus most of this file). Step is allowed to
6329 // be arbitrarily loop varying here, where AddRec allows only loop invariant
6330 // and other addrecs in the same loop (for non-affine addrecs). The code
6331 // below intentionally handles the case where step is not loop invariant.
6332 auto *P = dyn_cast<PHINode>(U->getValue());
6333 if (!P)
6334 return FullSet;
6335
6336 // Make sure that no Phi input comes from an unreachable block. Otherwise,
6337 // even the values that are not available in these blocks may come from them,
6338 // and this leads to false-positive recurrence test.
6339 for (auto *Pred : predecessors(P->getParent()))
6340 if (!DT.isReachableFromEntry(Pred))
6341 return FullSet;
6342
6343 BinaryOperator *BO;
6344 Value *Start, *Step;
6345 if (!matchSimpleRecurrence(P, BO, Start, Step))
6346 return FullSet;
6347
6348 // If we found a recurrence in reachable code, we must be in a loop. Note
6349 // that BO might be in some subloop of L, and that's completely okay.
6350 auto *L = LI.getLoopFor(P->getParent());
6351 assert(L && L->getHeader() == P->getParent());
6352 if (!L->contains(BO->getParent()))
6353 // NOTE: This bailout should be an assert instead. However, asserting
6354 // the condition here exposes a case where LoopFusion is querying SCEV
6355 // with malformed loop information during the midst of the transform.
6356 // There doesn't appear to be an obvious fix, so for the moment bailout
6357 // until the caller issue can be fixed. PR49566 tracks the bug.
6358 return FullSet;
6359
6360 // TODO: Extend to other opcodes such as mul, and div
6361 switch (BO->getOpcode()) {
6362 default:
6363 return FullSet;
6364 case Instruction::AShr:
6365 case Instruction::LShr:
6366 case Instruction::Shl:
6367 break;
6368 };
6369
6370 if (BO->getOperand(0) != P)
6371 // TODO: Handle the power function forms some day.
6372 return FullSet;
6373
6374 unsigned TC = getSmallConstantMaxTripCount(L);
6375 if (!TC || TC >= BitWidth)
6376 return FullSet;
6377
6378 auto KnownStart = computeKnownBits(Start, DL, &AC, nullptr, &DT);
6379 auto KnownStep = computeKnownBits(Step, DL, &AC, nullptr, &DT);
6380 assert(KnownStart.getBitWidth() == BitWidth &&
6381 KnownStep.getBitWidth() == BitWidth);
6382
6383 // Compute total shift amount, being careful of overflow and bitwidths.
6384 auto MaxShiftAmt = KnownStep.getMaxValue();
6385 APInt TCAP(BitWidth, TC-1);
6386 bool Overflow = false;
6387 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6388 if (Overflow)
6389 return FullSet;
6390
6391 switch (BO->getOpcode()) {
6392 default:
6393 llvm_unreachable("filtered out above");
6394 case Instruction::AShr: {
6395 // For each ashr, three cases:
6396 // shift = 0 => unchanged value
6397 // saturation => 0 or -1
6398 // other => a value closer to zero (of the same sign)
6399 // Thus, the end value is closer to zero than the start.
6400 auto KnownEnd = KnownBits::ashr(KnownStart,
6401 KnownBits::makeConstant(TotalShift));
6402 if (KnownStart.isNonNegative())
6403 // Analogous to lshr (simply not yet canonicalized)
6404 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6405 KnownStart.getMaxValue() + 1);
6406 if (KnownStart.isNegative())
6407 // End >=u Start && End <=s Start
6408 return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6409 KnownEnd.getMaxValue() + 1);
6410 break;
6411 }
6412 case Instruction::LShr: {
6413 // For each lshr, three cases:
6414 // shift = 0 => unchanged value
6415 // saturation => 0
6416 // other => a smaller positive number
6417 // Thus, the low end of the unsigned range is the last value produced.
6418 auto KnownEnd = KnownBits::lshr(KnownStart,
6419 KnownBits::makeConstant(TotalShift));
6420 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6421 KnownStart.getMaxValue() + 1);
6422 }
6423 case Instruction::Shl: {
6424 // Iff no bits are shifted out, value increases on every shift.
6425 auto KnownEnd = KnownBits::shl(KnownStart,
6426 KnownBits::makeConstant(TotalShift));
6427 if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6428 return ConstantRange(KnownStart.getMinValue(),
6429 KnownEnd.getMaxValue() + 1);
6430 break;
6431 }
6432 };
6433 return FullSet;
6434}
6435
6436// The goal of this function is to check if recursively visiting the operands
6437// of this PHI might lead to an infinite loop. If we do see such a loop,
6438// there's no good way to break it, so we avoid analyzing such cases.
6439//
6440// getRangeRef previously used a visited set to avoid infinite loops, but this
6441// caused other issues: the result was dependent on the order of getRangeRef
6442// calls, and the interaction with createSCEVIter could cause a stack overflow
6443// in some cases (see issue #148253).
6444//
6445// FIXME: The way this is implemented is overly conservative; this checks
6446// for a few obviously safe patterns, but anything that doesn't lead to
6447// recursion is fine.
6449 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6451 return true;
6452
6453 if (all_of(PHI->operands(),
6454 [&](Value *Operand) { return DT.dominates(Operand, PHI); }))
6455 return true;
6456
6457 return false;
6458}
6459
6460const ConstantRange &
6461ScalarEvolution::getRangeRefIter(const SCEV *S,
6462 ScalarEvolution::RangeSignHint SignHint) {
6463 DenseMap<const SCEV *, ConstantRange> &Cache =
6464 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6465 : SignedRanges;
6466 SmallVector<SCEVUse> WorkList;
6467 SmallPtrSet<const SCEV *, 8> Seen;
6468
6469 // Add Expr to the worklist, if Expr is either an N-ary expression or a
6470 // SCEVUnknown PHI node.
6471 auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6472 if (!Seen.insert(Expr).second)
6473 return;
6474 if (Cache.contains(Expr))
6475 return;
6476 switch (Expr->getSCEVType()) {
6477 case scUnknown:
6479 break;
6480 [[fallthrough]];
6481 case scConstant:
6482 case scVScale:
6483 case scTruncate:
6484 case scZeroExtend:
6485 case scSignExtend:
6486 case scPtrToAddr:
6487 case scAddExpr:
6488 case scMulExpr:
6489 case scUDivExpr:
6490 case scAddRecExpr:
6491 case scUMaxExpr:
6492 case scSMaxExpr:
6493 case scUMinExpr:
6494 case scSMinExpr:
6496 WorkList.push_back(Expr);
6497 break;
6498 case scCouldNotCompute:
6499 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6500 }
6501 };
6502 AddToWorklist(S);
6503
6504 // Build worklist by queuing operands of N-ary expressions and phi nodes.
6505 for (unsigned I = 0; I != WorkList.size(); ++I) {
6506 const SCEV *P = WorkList[I];
6507 auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6508 // If it is not a `SCEVUnknown`, just recurse into operands.
6509 if (!UnknownS) {
6510 for (const SCEV *Op : P->operands())
6511 AddToWorklist(Op);
6512 continue;
6513 }
6514 // `SCEVUnknown`'s require special treatment.
6515 if (PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6516 if (!RangeRefPHIAllowedOperands(DT, P))
6517 continue;
6518 for (auto &Op : reverse(P->operands()))
6519 AddToWorklist(getSCEV(Op));
6520 }
6521 }
6522
6523 if (!WorkList.empty()) {
6524 // Use getRangeRef to compute ranges for items in the worklist in reverse
6525 // order. This will force ranges for earlier operands to be computed before
6526 // their users in most cases.
6527 for (const SCEV *P : reverse(drop_begin(WorkList))) {
6528 getRangeRef(P, SignHint);
6529 }
6530 }
6531
6532 return getRangeRef(S, SignHint, 0);
6533}
6534
6535const APInt *ScalarEvolution::getConstantAPIntOrNull(const SCEV *S) {
6536 if (const auto *C = dyn_cast<SCEVConstant>(S))
6537 return &C->getAPInt();
6538 return nullptr;
6539}
6540
6541/// Determine the range for a particular SCEV. If SignHint is
6542/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6543/// with a "cleaner" unsigned (resp. signed) representation.
6544const ConstantRange &ScalarEvolution::getRangeRef(
6545 const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6546 DenseMap<const SCEV *, ConstantRange> &Cache =
6547 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6548 : SignedRanges;
6550 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6552
6553 // See if we've computed this range already.
6554 auto I = Cache.find(S);
6555 if (I != Cache.end())
6556 return I->second;
6557
6558 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6559 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6560
6561 // Switch to iteratively computing the range for S, if it is part of a deeply
6562 // nested expression.
6563 if (Depth > Opts.scev_range_iter_threshold)
6564 return getRangeRefIter(S, SignHint);
6565
6566 unsigned BitWidth = getTypeSizeInBits(S->getType());
6567 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6568 using OBO = OverflowingBinaryOperator;
6569
6570 // If the value has known zeros, the maximum value will have those known zeros
6571 // as well.
6572 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6573 APInt Multiple = getNonZeroConstantMultiple(S);
6574 APInt Remainder = APInt::getMaxValue(BitWidth).urem(Multiple);
6575 if (!Remainder.isZero())
6576 ConservativeResult =
6577 ConstantRange(APInt::getMinValue(BitWidth),
6578 APInt::getMaxValue(BitWidth) - Remainder + 1);
6579 }
6580 else {
6581 uint32_t TZ = getMinTrailingZeros(S);
6582 if (TZ != 0) {
6583 ConservativeResult = ConstantRange(
6585 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6586 }
6587 }
6588
6589 switch (S->getSCEVType()) {
6590 case scConstant:
6591 llvm_unreachable("Already handled above.");
6592 case scVScale:
6593 return setRange(S, SignHint, getVScaleRange(&F, BitWidth));
6594 case scTruncate: {
6595 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6596 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6597 return setRange(
6598 Trunc, SignHint,
6599 ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6600 }
6601 case scZeroExtend: {
6602 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6603 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6604 return setRange(
6605 ZExt, SignHint,
6606 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6607 }
6608 case scSignExtend: {
6609 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6610 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6611 return setRange(
6612 SExt, SignHint,
6613 ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6614 }
6615 case scPtrToAddr: {
6616 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6617 ConstantRange X = getRangeRef(Cast->getOperand(), SignHint, Depth + 1);
6618 return setRange(Cast, SignHint, X);
6619 }
6620 case scAddExpr: {
6621 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6622 // Check if this is a URem pattern: A - (A / B) * B, which is always < B.
6623 const SCEV *URemLHS = nullptr, *URemRHS = nullptr;
6624 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED &&
6625 match(S, m_scev_URem(m_SCEV(URemLHS), m_SCEV(URemRHS), *this))) {
6626 ConstantRange LHSRange = getRangeRef(URemLHS, SignHint, Depth + 1);
6627 ConstantRange RHSRange = getRangeRef(URemRHS, SignHint, Depth + 1);
6628 ConservativeResult =
6629 ConservativeResult.intersectWith(LHSRange.urem(RHSRange), RangeType);
6630 }
6631 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6632 unsigned WrapType = OBO::AnyWrap;
6633 if (Add->hasNoSignedWrap())
6634 WrapType |= OBO::NoSignedWrap;
6635 if (Add->hasNoUnsignedWrap())
6636 WrapType |= OBO::NoUnsignedWrap;
6637 for (const SCEV *Op : drop_begin(Add->operands()))
6638 X = X.addWithNoWrap(getRangeRef(Op, SignHint, Depth + 1), WrapType,
6639 RangeType);
6640 return setRange(Add, SignHint,
6641 ConservativeResult.intersectWith(X, RangeType));
6642 }
6643 case scMulExpr: {
6644 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6645 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6646 for (const SCEV *Op : drop_begin(Mul->operands()))
6647 X = X.multiply(getRangeRef(Op, SignHint, Depth + 1));
6648 return setRange(Mul, SignHint,
6649 ConservativeResult.intersectWith(X, RangeType));
6650 }
6651 case scUDivExpr: {
6652 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6653 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6654 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6655 return setRange(UDiv, SignHint,
6656 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6657 }
6658 case scAddRecExpr: {
6659 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6660 // If there's no unsigned wrap, the value will never be less than its
6661 // initial value.
6662 if (AddRec->hasNoUnsignedWrap()) {
6663 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6664 if (!UnsignedMinValue.isZero())
6665 ConservativeResult = ConservativeResult.intersectWith(
6666 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6667 }
6668
6669 // If there's no signed wrap, and all the operands except initial value have
6670 // the same sign or zero, the value won't ever be:
6671 // 1: smaller than initial value if operands are non negative,
6672 // 2: bigger than initial value if operands are non positive.
6673 // For both cases, value can not cross signed min/max boundary.
6674 if (AddRec->hasNoSignedWrap()) {
6675 bool AllNonNeg = true;
6676 bool AllNonPos = true;
6677 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6678 if (!isKnownNonNegative(AddRec->getOperand(i)))
6679 AllNonNeg = false;
6680 if (!isKnownNonPositive(AddRec->getOperand(i)))
6681 AllNonPos = false;
6682 }
6683 if (AllNonNeg)
6684 ConservativeResult = ConservativeResult.intersectWith(
6687 RangeType);
6688 else if (AllNonPos)
6689 ConservativeResult = ConservativeResult.intersectWith(
6691 getSignedRangeMax(AddRec->getStart()) +
6692 1),
6693 RangeType);
6694 }
6695
6696 // TODO: non-affine addrec
6697 if (AddRec->isAffine()) {
6698 const SCEV *MaxBEScev =
6700 if (!isa<SCEVCouldNotCompute>(MaxBEScev)) {
6701 APInt MaxBECount = cast<SCEVConstant>(MaxBEScev)->getAPInt();
6702
6703 // Adjust MaxBECount to the same bitwidth as AddRec. We can truncate if
6704 // MaxBECount's active bits are all <= AddRec's bit width.
6705 if (MaxBECount.getBitWidth() > BitWidth &&
6706 MaxBECount.getActiveBits() <= BitWidth)
6707 MaxBECount = MaxBECount.trunc(BitWidth);
6708 else if (MaxBECount.getBitWidth() < BitWidth)
6709 MaxBECount = MaxBECount.zext(BitWidth);
6710
6711 if (MaxBECount.getBitWidth() == BitWidth) {
6712 auto [RangeFromAffine, Flags] = getRangeForAffineAR(
6713 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6714 ConservativeResult =
6715 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6716 const_cast<SCEVAddRecExpr *>(AddRec)->setNoWrapFlags(Flags);
6717
6718 auto RangeFromFactoring = getRangeViaFactoring(
6719 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6720 ConservativeResult =
6721 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6722 }
6723 }
6724
6725 // Now try symbolic BE count and more powerful methods.
6726 if (Opts.scalar_evolution_use_expensive_range_sharpening) {
6727 const SCEV *SymbolicMaxBECount =
6729 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6730 getTypeSizeInBits(MaxBEScev->getType()) <= BitWidth &&
6731 AddRec->hasNoSelfWrap()) {
6732 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6733 AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6734 ConservativeResult =
6735 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6736 }
6737 }
6738 }
6739
6740 return setRange(AddRec, SignHint, std::move(ConservativeResult));
6741 }
6742 case scUMaxExpr:
6743 case scSMaxExpr:
6744 case scUMinExpr:
6745 case scSMinExpr:
6746 case scSequentialUMinExpr: {
6748 switch (S->getSCEVType()) {
6749 case scUMaxExpr:
6750 ID = Intrinsic::umax;
6751 break;
6752 case scSMaxExpr:
6753 ID = Intrinsic::smax;
6754 break;
6755 case scUMinExpr:
6757 ID = Intrinsic::umin;
6758 break;
6759 case scSMinExpr:
6760 ID = Intrinsic::smin;
6761 break;
6762 default:
6763 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6764 }
6765
6766 const auto *NAry = cast<SCEVNAryExpr>(S);
6767 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
6768 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6769 X = X.intrinsic(
6770 ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
6771 return setRange(S, SignHint,
6772 ConservativeResult.intersectWith(X, RangeType));
6773 }
6774 case scUnknown: {
6775 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6776 Value *V = U->getValue();
6777
6778 // Check if the IR explicitly contains !range metadata.
6779 std::optional<ConstantRange> MDRange = GetRangeFromMetadata(V);
6780 if (MDRange)
6781 ConservativeResult =
6782 ConservativeResult.intersectWith(*MDRange, RangeType);
6783
6784 // Use facts about recurrences in the underlying IR. Note that add
6785 // recurrences are AddRecExprs and thus don't hit this path. This
6786 // primarily handles shift recurrences.
6787 auto CR = getRangeForUnknownRecurrence(U);
6788 ConservativeResult = ConservativeResult.intersectWith(CR);
6789
6790 // See if ValueTracking can give us a useful range.
6791 const DataLayout &DL = getDataLayout();
6792 KnownBits Known = computeKnownBits(V, DL, &AC, nullptr, &DT);
6793 if (Known.getBitWidth() != BitWidth)
6794 Known = Known.zextOrTrunc(BitWidth);
6795
6796 // ValueTracking may be able to compute a tighter result for the number of
6797 // sign bits than for the value of those sign bits.
6798 unsigned NS = ComputeNumSignBits(V, DL, &AC, nullptr, &DT);
6799 if (U->getType()->isPointerTy()) {
6800 // NS counts the sign bits of the whole pointer; drop those above the
6801 // index bits.
6802 unsigned PtrIdxDiff =
6803 DL.getPointerTypeSizeInBits(U->getType()) - BitWidth;
6804 NS = NS > PtrIdxDiff ? NS - PtrIdxDiff : 1;
6805 }
6806
6807 if (NS > 1) {
6808 // If we know any of the sign bits, we know all of the sign bits.
6809 if (!Known.Zero.getHiBits(NS).isZero())
6810 Known.Zero.setHighBits(NS);
6811 if (!Known.One.getHiBits(NS).isZero())
6812 Known.One.setHighBits(NS);
6813 }
6814
6815 if (Known.getMinValue() != Known.getMaxValue() + 1)
6816 ConservativeResult = ConservativeResult.intersectWith(
6817 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6818 RangeType);
6819 if (NS > 1)
6820 ConservativeResult = ConservativeResult.intersectWith(
6821 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6822 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6823 RangeType);
6824
6825 if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
6826 // Strengthen the range if the underlying IR value is a
6827 // global/alloca/heap allocation using the size of the object.
6828 bool CanBeNull;
6829 uint64_t DerefBytes = V->getPointerDereferenceableBytes(
6830 DL, CanBeNull, /*CanBeFreed=*/nullptr);
6831 if (DerefBytes > 1 && isUIntN(BitWidth, DerefBytes)) {
6832 // The highest address the object can start is DerefBytes bytes before
6833 // the end (unsigned max value). If this value is not a multiple of the
6834 // alignment, the last possible start value is the next lowest multiple
6835 // of the alignment. Note: The computations below cannot overflow,
6836 // because if they would there's no possible start address for the
6837 // object.
6838 APInt MaxVal =
6839 APInt::getMaxValue(BitWidth) - APInt(BitWidth, DerefBytes);
6840 uint64_t Align = U->getValue()->getPointerAlignment(DL).value();
6841 uint64_t Rem = MaxVal.urem(Align);
6842 MaxVal -= APInt(BitWidth, Rem);
6843 APInt MinVal = APInt::getZero(BitWidth);
6844 if (llvm::isKnownNonZero(V, DL))
6845 MinVal = Align;
6846 ConservativeResult = ConservativeResult.intersectWith(
6847 ConstantRange::getNonEmpty(MinVal, MaxVal + 1), RangeType);
6848 }
6849 }
6850
6851 // A range of Phi is a subset of union of all ranges of its input.
6852 if (PHINode *Phi = dyn_cast<PHINode>(V)) {
6853 // SCEVExpander sometimes creates SCEVUnknowns that are secretly
6854 // AddRecs; return the range for the corresponding AddRec.
6855 if (auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V)))
6856 return getRangeRef(AR, SignHint, Depth + 1);
6857
6858 // Make sure that we do not run over cycled Phis.
6859 if (RangeRefPHIAllowedOperands(DT, Phi)) {
6860 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6861
6862 for (const auto &Op : Phi->operands()) {
6863 auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
6864 RangeFromOps = RangeFromOps.unionWith(OpRange, RangeType);
6865 // No point to continue if we already have a full set.
6866 if (RangeFromOps.isFullSet())
6867 break;
6868 }
6869 ConservativeResult =
6870 ConservativeResult.intersectWith(RangeFromOps, RangeType);
6871 }
6872 }
6873
6874 const APInt *TrueC, *FalseC;
6875 if (match(V, m_Select(m_Value(), m_APInt(TrueC), m_APInt(FalseC))))
6876 ConservativeResult = ConservativeResult.intersectWith(
6877 ConstantRange(*TrueC).unionWith(*FalseC, RangeType), RangeType);
6878
6879 // vscale can't be equal to zero
6880 if (const auto *II = dyn_cast<IntrinsicInst>(V))
6881 if (II->getIntrinsicID() == Intrinsic::vscale) {
6882 ConstantRange Disallowed = APInt::getZero(BitWidth);
6883 ConservativeResult = ConservativeResult.difference(Disallowed);
6884 }
6885
6886 return setRange(U, SignHint, std::move(ConservativeResult));
6887 }
6888 case scCouldNotCompute:
6889 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6890 }
6891
6892 return setRange(S, SignHint, std::move(ConservativeResult));
6893}
6894
6895// Given a StartRange, Step and MaxBECount for an expression compute a range of
6896// values that the expression can take. Initially, the expression has a value
6897// from StartRange and then is changed by Step up to MaxBECount times. Signed
6898// argument defines if we treat Step as signed or unsigned. The second return
6899// value indicates that no wrapping occurred.
6900static std::pair<ConstantRange, bool>
6902 const APInt &MaxBECount, bool Signed) {
6903 unsigned BitWidth = Step.getBitWidth();
6904 assert(BitWidth == StartRange.getBitWidth() &&
6905 BitWidth == MaxBECount.getBitWidth() && "mismatched bit widths");
6906 // If either Step or MaxBECount is 0, then the expression won't change, and we
6907 // just need to return the initial range.
6908 if (Step == 0 || MaxBECount == 0)
6909 return {StartRange, true};
6910
6911 // If we don't know anything about the initial value (i.e. StartRange is
6912 // FullRange), then we don't know anything about the final range either.
6913 // Return FullRange.
6914 if (StartRange.isFullSet())
6915 return {ConstantRange::getFull(BitWidth), false};
6916
6917 // If Step is signed and negative, then we use its absolute value, but we also
6918 // note that we're moving in the opposite direction.
6919 bool Descending = Signed && Step.isNegative();
6920
6921 if (Signed)
6922 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
6923 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
6924 // This equations hold true due to the well-defined wrap-around behavior of
6925 // APInt.
6926 Step = Step.abs();
6927
6928 // Check if Offset is more than full span of BitWidth. If it is, the
6929 // expression is guaranteed to overflow.
6930 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
6931 return {ConstantRange::getFull(BitWidth), false};
6932
6933 // Offset is by how much the expression can change. Checks above guarantee no
6934 // overflow here.
6935 APInt Offset = Step * MaxBECount;
6936
6937 // Minimum value of the final range will match the minimal value of StartRange
6938 // if the expression is increasing and will be decreased by Offset otherwise.
6939 // Maximum value of the final range will match the maximal value of StartRange
6940 // if the expression is decreasing and will be increased by Offset otherwise.
6941 APInt StartLower = StartRange.getLower();
6942 APInt StartUpper = StartRange.getUpper() - 1;
6943 bool Overflow;
6944 APInt MovedBoundary;
6945 if (Signed) {
6946 // This does not use sadd_ov, as we want to check overflow for a signed
6947 // start with an unsigned offset.
6948 if (Descending) {
6949 MovedBoundary = StartLower - std::move(Offset);
6950 Overflow = MovedBoundary.sgt(StartLower) || StartRange.isSignWrappedSet();
6951 } else {
6952 MovedBoundary = StartUpper + std::move(Offset);
6953 Overflow = MovedBoundary.slt(StartUpper) || StartRange.isSignWrappedSet();
6954 }
6955 } else {
6956 MovedBoundary = StartUpper.uadd_ov(std::move(Offset), Overflow);
6957 Overflow |= StartRange.isWrappedSet();
6958 }
6959
6960 // It's possible that the new minimum/maximum value will fall into the initial
6961 // range (due to wrap around). This means that the expression can take any
6962 // value in this bitwidth, and we have to return full range.
6963 if (StartRange.contains(MovedBoundary))
6964 return {ConstantRange::getFull(BitWidth), false};
6965
6966 APInt NewLower =
6967 Descending ? std::move(MovedBoundary) : std::move(StartLower);
6968 APInt NewUpper =
6969 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
6970 NewUpper += 1;
6971
6972 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
6973 return {ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)),
6974 !Overflow};
6975}
6976
6977std::pair<ConstantRange, SCEVFlags>
6978ScalarEvolution::getRangeForAffineAR(const SCEV *Start, const SCEV *Step,
6979 const APInt &MaxBECount) {
6980 assert(getTypeSizeInBits(Start->getType()) ==
6981 getTypeSizeInBits(Step->getType()) &&
6982 getTypeSizeInBits(Start->getType()) == MaxBECount.getBitWidth() &&
6983 "mismatched bit widths");
6984
6985 // First, consider step signed.
6986 ConstantRange StartSRange = getSignedRange(Start);
6987 ConstantRange StepSRange = getSignedRange(Step);
6988
6989 // If Step can be both positive and negative, we need to find ranges for the
6990 // maximum absolute step values in both directions and union them.
6991 auto [SR, NSW] = getRangeForAffineARHelper(
6992 StepSRange.getSignedMin(), StartSRange, MaxBECount, /*Signed=*/true);
6993 // A singleton step has identical signed bounds, so the second computation
6994 // would produce the same range and no-wrap result.
6995 if (!StepSRange.isSingleElement()) {
6996 auto [SRMax, NSWMax] = getRangeForAffineARHelper(
6997 StepSRange.getSignedMax(), StartSRange, MaxBECount, /*Signed=*/true);
6998 SR = SR.unionWith(SRMax);
6999 NSW &= NSWMax;
7000 }
7001
7002 // Next, consider step unsigned.
7003 auto [UR, NUW] = getRangeForAffineARHelper(
7004 getUnsignedRangeMax(Step), getUnsignedRange(Start), MaxBECount,
7005 /*Signed=*/false);
7006
7008 if (NUW)
7010 if (NSW)
7012
7013 // Finally, intersect signed and unsigned ranges.
7014 return {SR.intersectWith(UR, ConstantRange::Smallest), Flags};
7015}
7016
7017ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
7018 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
7019 ScalarEvolution::RangeSignHint SignHint) {
7020 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
7021 assert(AddRec->hasNoSelfWrap() &&
7022 "This only works for non-self-wrapping AddRecs!");
7023 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
7024 const SCEV *Step = AddRec->getStepRecurrence(*this);
7025 // Only deal with constant step to save compile time.
7026 if (!isa<SCEVConstant>(Step))
7027 return ConstantRange::getFull(BitWidth);
7028 // Let's make sure that we can prove that we do not self-wrap during
7029 // MaxBECount iterations. We need this because MaxBECount is a maximum
7030 // iteration count estimate, and we might infer nw from some exit for which we
7031 // do not know max exit count (or any other side reasoning).
7032 // TODO: Turn into assert at some point.
7033 if (getTypeSizeInBits(MaxBECount->getType()) >
7034 getTypeSizeInBits(AddRec->getType()))
7035 return ConstantRange::getFull(BitWidth);
7036 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
7037 const SCEV *RangeWidth = getMinusOne(AddRec->getType());
7038 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
7039 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
7040 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
7041 MaxItersWithoutWrap))
7042 return ConstantRange::getFull(BitWidth);
7043
7044 ICmpInst::Predicate LEPred =
7046 ICmpInst::Predicate GEPred =
7048 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7049
7050 // We know that there is no self-wrap. Let's take Start and End values and
7051 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7052 // the iteration. They either lie inside the range [Min(Start, End),
7053 // Max(Start, End)] or outside it:
7054 //
7055 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
7056 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
7057 //
7058 // No self wrap flag guarantees that the intermediate values cannot be BOTH
7059 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7060 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7061 // Start <= End and step is positive, or Start >= End and step is negative.
7062 const SCEV *Start = applyLoopGuards(AddRec->getStart(), AddRec->getLoop());
7063 ConstantRange StartRange = getRangeRef(Start, SignHint);
7064 ConstantRange EndRange = getRangeRef(End, SignHint);
7065 ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7066 // If they already cover full iteration space, we will know nothing useful
7067 // even if we prove what we want to prove.
7068 if (RangeBetween.isFullSet())
7069 return RangeBetween;
7070 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7071 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7072 : RangeBetween.isWrappedSet();
7073 if (IsWrappedSet)
7074 return ConstantRange::getFull(BitWidth);
7075
7076 if (isKnownPositive(Step) &&
7077 isKnownPredicateViaConstantRanges(LEPred, Start, End))
7078 return RangeBetween;
7079 if (isKnownNegative(Step) &&
7080 isKnownPredicateViaConstantRanges(GEPred, Start, End))
7081 return RangeBetween;
7082 return ConstantRange::getFull(BitWidth);
7083}
7084
7085ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7086 const SCEV *Step,
7087 const APInt &MaxBECount) {
7088 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7089 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7090
7091 unsigned BitWidth = MaxBECount.getBitWidth();
7092 assert(getTypeSizeInBits(Start->getType()) == BitWidth &&
7093 getTypeSizeInBits(Step->getType()) == BitWidth &&
7094 "mismatched bit widths");
7095
7096 struct SelectPattern {
7097 Value *Condition = nullptr;
7098 APInt TrueValue;
7099 APInt FalseValue;
7100
7101 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7102 const SCEV *S) {
7103 std::optional<unsigned> CastOp;
7104 APInt Offset(BitWidth, 0);
7105
7107 "Should be!");
7108
7109 // Peel off a constant offset. In the future we could consider being
7110 // smarter here and handle {Start+Step,+,Step} too.
7111 const APInt *Off;
7112 if (match(S, m_scev_Add(m_scev_APInt(Off), m_SCEV(S))))
7113 Offset = *Off;
7114
7115 // Peel off a cast operation
7116 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7117 CastOp = SCast->getSCEVType();
7118 S = SCast->getOperand();
7119 }
7120
7121 using namespace llvm::PatternMatch;
7122
7123 auto *SU = dyn_cast<SCEVUnknown>(S);
7124 const APInt *TrueVal, *FalseVal;
7125 if (!SU ||
7126 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7127 m_APInt(FalseVal)))) {
7128 Condition = nullptr;
7129 return;
7130 }
7131
7132 TrueValue = *TrueVal;
7133 FalseValue = *FalseVal;
7134
7135 // Re-apply the cast we peeled off earlier
7136 if (CastOp)
7137 switch (*CastOp) {
7138 default:
7139 llvm_unreachable("Unknown SCEV cast type!");
7140
7141 case scTruncate:
7142 TrueValue = TrueValue.trunc(BitWidth);
7143 FalseValue = FalseValue.trunc(BitWidth);
7144 break;
7145 case scZeroExtend:
7146 TrueValue = TrueValue.zext(BitWidth);
7147 FalseValue = FalseValue.zext(BitWidth);
7148 break;
7149 case scSignExtend:
7150 TrueValue = TrueValue.sext(BitWidth);
7151 FalseValue = FalseValue.sext(BitWidth);
7152 break;
7153 }
7154
7155 // Re-apply the constant offset we peeled off earlier
7156 TrueValue += Offset;
7157 FalseValue += Offset;
7158 }
7159
7160 bool isRecognized() { return Condition != nullptr; }
7161 };
7162
7163 SelectPattern StartPattern(*this, BitWidth, Start);
7164 if (!StartPattern.isRecognized())
7165 return ConstantRange::getFull(BitWidth);
7166
7167 SelectPattern StepPattern(*this, BitWidth, Step);
7168 if (!StepPattern.isRecognized())
7169 return ConstantRange::getFull(BitWidth);
7170
7171 if (StartPattern.Condition != StepPattern.Condition) {
7172 // We don't handle this case today; but we could, by considering four
7173 // possibilities below instead of two. I'm not sure if there are cases where
7174 // that will help over what getRange already does, though.
7175 return ConstantRange::getFull(BitWidth);
7176 }
7177
7178 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7179 // construct arbitrary general SCEV expressions here. This function is called
7180 // from deep in the call stack, and calling getSCEV (on a sext instruction,
7181 // say) can end up caching a suboptimal value.
7182
7183 // FIXME: without the explicit `this` receiver below, MSVC errors out with
7184 // C2352 and C2512 (otherwise it isn't needed).
7185
7186 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7187 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7188 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7189 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7190
7191 ConstantRange TrueRange =
7192 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount).first;
7193 ConstantRange FalseRange =
7194 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount).first;
7195
7196 return TrueRange.unionWith(FalseRange);
7197}
7198
7199SCEVFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7200 if (isa<ConstantExpr>(V))
7201 return SCEV::FlagNone;
7202 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7203
7204 // Return early if there are no flags to propagate to the SCEV.
7206 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(BinOp);
7207 PDI && PDI->isDisjoint()) {
7209 } else {
7210 if (BinOp->hasNoUnsignedWrap())
7212 if (BinOp->hasNoSignedWrap())
7214 }
7215 if (Flags == SCEV::FlagNone)
7216 return SCEV::FlagNone;
7217
7218 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagNone;
7219}
7220
7221const Instruction *
7222ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7223 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7224 return &*AddRec->getLoop()->getHeader()->begin();
7225 if (auto *U = dyn_cast<SCEVUnknown>(S))
7226 if (auto *I = dyn_cast<Instruction>(U->getValue()))
7227 return I;
7228 return nullptr;
7229}
7230
7231const Instruction *ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops,
7232 bool &Precise) {
7233 Precise = true;
7234 // Do a bounded search of the def relation of the requested SCEVs.
7235 SmallPtrSet<const SCEV *, 16> Visited;
7236 SmallVector<SCEVUse> Worklist;
7237 auto pushOp = [&](const SCEV *S) {
7238 if (!Visited.insert(S).second)
7239 return;
7240 // Threshold of 30 here is arbitrary.
7241 if (Visited.size() > 30) {
7242 Precise = false;
7243 return;
7244 }
7245 Worklist.push_back(S);
7246 };
7247
7248 for (SCEVUse S : Ops)
7249 pushOp(S);
7250
7251 const Instruction *Bound = nullptr;
7252 while (!Worklist.empty()) {
7253 SCEVUse S = Worklist.pop_back_val();
7254 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7255 if (!Bound || DT.dominates(Bound, DefI))
7256 Bound = DefI;
7257 } else {
7258 for (SCEVUse Op : S->operands())
7259 pushOp(Op);
7260 }
7261 }
7262 return Bound ? Bound : &*F.getEntryBlock().begin();
7263}
7264
7265const Instruction *
7266ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops) {
7267 bool Discard;
7268 return getDefiningScopeBound(Ops, Discard);
7269}
7270
7271bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7272 const Instruction *B) {
7273 if (A->getParent() == B->getParent() &&
7275 B->getIterator()))
7276 return true;
7277
7278 auto *BLoop = LI.getLoopFor(B->getParent());
7279 if (BLoop && BLoop->getHeader() == B->getParent() &&
7280 BLoop->getLoopPreheader() == A->getParent() &&
7282 A->getParent()->end()) &&
7283 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7284 B->getIterator()))
7285 return true;
7286 return false;
7287}
7288
7290 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ true);
7291 visitAll(Op, PC);
7292 return PC.MaybePoison.empty();
7293}
7294
7296 return !SCEVExprContains(Op, [this](const SCEV *S) {
7297 const SCEV *Op1;
7298 bool M = match(S, m_scev_UDiv(m_SCEV(), m_SCEV(Op1)));
7299 // The UDiv may be UB if the divisor is poison or zero. Unless the divisor
7300 // is a non-zero constant, we have to assume the UDiv may be UB.
7301 return M && (!isKnownNonZero(Op1) || !isGuaranteedNotToBePoison(Op1));
7302 });
7303}
7304
7305bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7306 // Only proceed if we can prove that I does not yield poison.
7308 return false;
7309
7310 // At this point we know that if I is executed, then it does not wrap
7311 // according to at least one of NSW or NUW. If I is not executed, then we do
7312 // not know if the calculation that I represents would wrap. Multiple
7313 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7314 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7315 // derived from other instructions that map to the same SCEV. We cannot make
7316 // that guarantee for cases where I is not executed. So we need to find a
7317 // upper bound on the defining scope for the SCEV, and prove that I is
7318 // executed every time we enter that scope. When the bounding scope is a
7319 // loop (the common case), this is equivalent to proving I executes on every
7320 // iteration of that loop.
7321 SmallVector<SCEVUse> SCEVOps;
7322 for (const Use &Op : I->operands()) {
7323 // I could be an extractvalue from a call to an overflow intrinsic.
7324 // TODO: We can do better here in some cases.
7325 if (isSCEVable(Op->getType()))
7326 SCEVOps.push_back(getSCEV(Op));
7327 }
7328 auto *DefI = getDefiningScopeBound(SCEVOps);
7329 return isGuaranteedToTransferExecutionTo(DefI, I);
7330}
7331
7332bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7333 // If we know that \c I can never be poison period, then that's enough.
7334 if (isSCEVExprNeverPoison(I))
7335 return true;
7336
7337 // If the loop only has one exit, then we know that, if the loop is entered,
7338 // any instruction dominating that exit will be executed. If any such
7339 // instruction would result in UB, the addrec cannot be poison.
7340 //
7341 // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7342 // also handles uses outside the loop header (they just need to dominate the
7343 // single exit).
7344
7345 auto *ExitingBB = L->getExitingBlock();
7346 if (!ExitingBB || !loopHasNoAbnormalExits(L))
7347 return false;
7348
7349 SmallPtrSet<const Value *, 16> KnownPoison;
7351
7352 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
7353 // things that are known to be poison under that assumption go on the
7354 // Worklist.
7355 KnownPoison.insert(I);
7356 Worklist.push_back(I);
7357
7358 while (!Worklist.empty()) {
7359 const Instruction *Poison = Worklist.pop_back_val();
7360
7361 for (const Use &U : Poison->uses()) {
7362 const Instruction *PoisonUser = cast<Instruction>(U.getUser());
7363 if (mustTriggerUB(PoisonUser, KnownPoison) &&
7364 DT.dominates(PoisonUser->getParent(), ExitingBB))
7365 return true;
7366
7367 if (propagatesPoison(U) && L->contains(PoisonUser))
7368 if (KnownPoison.insert(PoisonUser).second)
7369 Worklist.push_back(PoisonUser);
7370 }
7371 }
7372
7373 return false;
7374}
7375
7376ScalarEvolution::LoopProperties
7377ScalarEvolution::getLoopProperties(const Loop *L) {
7378 using LoopProperties = ScalarEvolution::LoopProperties;
7379
7380 auto Itr = LoopPropertiesCache.find(L);
7381 if (Itr == LoopPropertiesCache.end()) {
7382 auto HasSideEffects = [](Instruction *I) {
7383 if (auto *SI = dyn_cast<StoreInst>(I))
7384 return !SI->isSimple();
7385
7386 if (I->mayThrow())
7387 return true;
7388
7389 // Non-volatile memset / memcpy do not count as side-effect for forward
7390 // progress.
7391 if (auto *MI = dyn_cast<MemIntrinsic>(I))
7392 if (!MI->isVolatile())
7393 return false;
7394
7395 // Droppable intrinsics only model a memory write; they are not progress.
7396 if (I->isDroppable())
7397 return false;
7398
7399 return I->mayWriteToMemory();
7400 };
7401
7402 LoopProperties LP = {/* HasNoAbnormalExits */ true,
7403 /*HasNoSideEffects*/ true};
7404
7405 for (auto *BB : L->getBlocks())
7406 for (auto &I : *BB) {
7408 LP.HasNoAbnormalExits = false;
7409 if (HasSideEffects(&I))
7410 LP.HasNoSideEffects = false;
7411 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7412 break; // We're already as pessimistic as we can get.
7413 }
7414
7415 auto InsertPair = LoopPropertiesCache.insert({L, LP});
7416 assert(InsertPair.second && "We just checked!");
7417 Itr = InsertPair.first;
7418 }
7419
7420 return Itr->second;
7421}
7422
7424 // A mustprogress loop without side effects must be finite.
7425 // TODO: The check used here is very conservative. It's only *specific*
7426 // side effects which are well defined in infinite loops.
7427 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7428}
7429
7430const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7431 // Worklist item with a Value and a bool indicating whether all operands have
7432 // been visited already.
7435
7436 Stack.emplace_back(V, false);
7437 while (!Stack.empty()) {
7438 auto E = Stack.back();
7439 Value *CurV = E.getPointer();
7440
7441 if (getExistingSCEV(CurV)) {
7442 Stack.pop_back();
7443 continue;
7444 }
7445
7447 const SCEV *CreatedSCEV = nullptr;
7448 // If all operands have been visited already, create the SCEV.
7449 if (E.getInt()) {
7450 CreatedSCEV = createSCEV(CurV);
7451 } else {
7452 // Otherwise get the operands we need to create SCEV's for before creating
7453 // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7454 // just use it.
7455 CreatedSCEV = getOperandsToCreate(CurV, Ops);
7456 }
7457
7458 if (CreatedSCEV) {
7459 insertValueToMap(CurV, CreatedSCEV);
7460 Stack.pop_back();
7461 } else {
7462 Stack.back().setInt(true);
7463 // Queue its operands which need to be constructed.
7464 for (Value *Op : Ops)
7465 Stack.emplace_back(Op, false);
7466 }
7467 }
7468
7469 return getExistingSCEV(V);
7470}
7471
7472const SCEV *
7473ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7474 if (!isSCEVable(V->getType()))
7475 return getUnknown(V);
7476
7477 if (Instruction *I = dyn_cast<Instruction>(V)) {
7478 // Don't attempt to analyze instructions in blocks that aren't
7479 // reachable. Such instructions don't matter, and they aren't required
7480 // to obey basic rules for definitions dominating uses which this
7481 // analysis depends on.
7482 if (!DT.isReachableFromEntry(I->getParent()))
7483 return getUnknown(PoisonValue::get(V->getType()));
7484 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7485 return getConstant(CI);
7486 else if (isa<GlobalAlias>(V))
7487 return getUnknown(V);
7488 else if (!isa<ConstantExpr>(V))
7489 return getUnknown(V);
7490
7492 if (auto BO = MatchBinaryOp(U, DT)) {
7493 bool IsConstArg = isa<ConstantInt>(BO->RHS);
7494 switch (BO->Opcode) {
7495 case Instruction::Add:
7496 case Instruction::Mul: {
7497 // For additions and multiplications, traverse add/mul chains for which we
7498 // can potentially create a single SCEV, to reduce the number of
7499 // get{Add,Mul}Expr calls.
7500 do {
7501 if (BO->Op) {
7502 if (BO->Op != V && getExistingSCEV(BO->Op)) {
7503 Ops.push_back(BO->Op);
7504 break;
7505 }
7506 }
7507 Ops.push_back(BO->RHS);
7508 auto NewBO = MatchBinaryOp(BO->LHS, DT);
7509 if (!NewBO ||
7510 (BO->Opcode == Instruction::Add &&
7511 (NewBO->Opcode != Instruction::Add &&
7512 NewBO->Opcode != Instruction::Sub)) ||
7513 (BO->Opcode == Instruction::Mul &&
7514 NewBO->Opcode != Instruction::Mul)) {
7515 Ops.push_back(BO->LHS);
7516 break;
7517 }
7518 // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7519 // requires a SCEV for the LHS.
7520 if (BO->Op && (BO->IsNSW || BO->IsNUW)) {
7521 auto *I = dyn_cast<Instruction>(BO->Op);
7522 if (I && programUndefinedIfPoison(I)) {
7523 Ops.push_back(BO->LHS);
7524 break;
7525 }
7526 }
7527 BO = NewBO;
7528 } while (true);
7529 return nullptr;
7530 }
7531 case Instruction::Sub:
7532 case Instruction::UDiv:
7533 case Instruction::URem:
7534 break;
7535 case Instruction::AShr:
7536 case Instruction::Shl:
7537 case Instruction::Xor:
7538 if (!IsConstArg)
7539 return nullptr;
7540 break;
7541 case Instruction::And:
7542 case Instruction::Or:
7543 if (!IsConstArg && !BO->LHS->getType()->isIntegerTy(1))
7544 return nullptr;
7545 break;
7546 case Instruction::LShr:
7547 return getUnknown(V);
7548 default:
7549 llvm_unreachable("Unhandled binop");
7550 break;
7551 }
7552
7553 Ops.push_back(BO->LHS);
7554 Ops.push_back(BO->RHS);
7555 return nullptr;
7556 }
7557
7558 switch (U->getOpcode()) {
7559 case Instruction::Trunc:
7560 case Instruction::ZExt:
7561 case Instruction::SExt:
7562 case Instruction::PtrToAddr:
7563 case Instruction::PtrToInt:
7564 Ops.push_back(U->getOperand(0));
7565 return nullptr;
7566
7567 case Instruction::BitCast:
7568 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
7569 Ops.push_back(U->getOperand(0));
7570 return nullptr;
7571 }
7572 return getUnknown(V);
7573
7574 case Instruction::SDiv:
7575 case Instruction::SRem:
7576 Ops.push_back(U->getOperand(0));
7577 Ops.push_back(U->getOperand(1));
7578 return nullptr;
7579
7580 case Instruction::GetElementPtr:
7581 assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7582 "GEP source element type must be sized");
7583 llvm::append_range(Ops, U->operands());
7584 return nullptr;
7585
7586 case Instruction::IntToPtr:
7587 return getUnknown(V);
7588
7589 case Instruction::PHI:
7590 // getNodeForPHI has four ways to turn a PHI into a SCEV; retrieve the
7591 // relevant nodes for each of them.
7592 //
7593 // The first is just to call simplifyInstruction, and get something back
7594 // that isn't a PHI.
7596 cast<PHINode>(U),
7597 {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
7598 /*UseInstrInfo=*/true, /*CanUseUndef=*/false})) {
7599 assert(V);
7600 Ops.push_back(V);
7601 return nullptr;
7602 }
7603 // The second is createNodeForPHIWithIdenticalOperands: this looks for
7604 // operands which all perform the same operation, but haven't been
7605 // CSE'ed for whatever reason.
7606 if (BinaryOperator *BO = getCommonInstForPHI(cast<PHINode>(U))) {
7607 assert(BO);
7608 Ops.push_back(BO);
7609 return nullptr;
7610 }
7611 // The third is createNodeFromSelectLikePHI; this takes a PHI which
7612 // is equivalent to a select, and analyzes it like a select.
7613 {
7614 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
7616 assert(Cond);
7617 assert(LHS);
7618 assert(RHS);
7619 if (auto *CondICmp = dyn_cast<ICmpInst>(Cond)) {
7620 Ops.push_back(CondICmp->getOperand(0));
7621 Ops.push_back(CondICmp->getOperand(1));
7622 }
7623 Ops.push_back(Cond);
7624 Ops.push_back(LHS);
7625 Ops.push_back(RHS);
7626 return nullptr;
7627 }
7628 }
7629 // The fourth way is createAddRecFromPHI. It's complicated to handle here,
7630 // so just construct it recursively.
7631 //
7632 // In addition to getNodeForPHI, also construct nodes which might be needed
7633 // by getRangeRef.
7635 for (Value *V : cast<PHINode>(U)->operands())
7636 Ops.push_back(V);
7637 return nullptr;
7638 }
7639 return nullptr;
7640
7641 case Instruction::Select: {
7642 // Check if U is a select that can be simplified to a SCEVUnknown.
7643 auto CanSimplifyToUnknown = [this, U]() {
7644 if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
7645 return false;
7646
7647 auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
7648 if (!ICI)
7649 return false;
7650 Value *LHS = ICI->getOperand(0);
7651 Value *RHS = ICI->getOperand(1);
7652 if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7653 ICI->getPredicate() == CmpInst::ICMP_NE) {
7655 return true;
7656 } else if (getTypeSizeInBits(LHS->getType()) >
7657 getTypeSizeInBits(U->getType()))
7658 return true;
7659 return false;
7660 };
7661 if (CanSimplifyToUnknown())
7662 return getUnknown(U);
7663
7664 llvm::append_range(Ops, U->operands());
7665 return nullptr;
7666 break;
7667 }
7668 case Instruction::Call:
7669 case Instruction::Invoke:
7670 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7671 Ops.push_back(RV);
7672 return nullptr;
7673 }
7674
7675 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7676 switch (II->getIntrinsicID()) {
7677 case Intrinsic::abs:
7678 Ops.push_back(II->getArgOperand(0));
7679 return nullptr;
7680 case Intrinsic::umax:
7681 case Intrinsic::umin:
7682 case Intrinsic::smax:
7683 case Intrinsic::smin:
7684 case Intrinsic::usub_sat:
7685 case Intrinsic::uadd_sat:
7686 Ops.push_back(II->getArgOperand(0));
7687 Ops.push_back(II->getArgOperand(1));
7688 return nullptr;
7689 case Intrinsic::start_loop_iterations:
7690 case Intrinsic::annotation:
7691 case Intrinsic::ptr_annotation:
7692 Ops.push_back(II->getArgOperand(0));
7693 return nullptr;
7694 default:
7695 break;
7696 }
7697 }
7698 break;
7699 }
7700
7701 return nullptr;
7702}
7703
7704const SCEV *ScalarEvolution::createSCEV(Value *V) {
7705 if (!isSCEVable(V->getType()))
7706 return getUnknown(V);
7707
7708 if (Instruction *I = dyn_cast<Instruction>(V)) {
7709 // Don't attempt to analyze instructions in blocks that aren't
7710 // reachable. Such instructions don't matter, and they aren't required
7711 // to obey basic rules for definitions dominating uses which this
7712 // analysis depends on.
7713 if (!DT.isReachableFromEntry(I->getParent()))
7714 return getUnknown(PoisonValue::get(V->getType()));
7715 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7716 return getConstant(CI);
7717 else if (isa<GlobalAlias>(V))
7718 return getUnknown(V);
7719 else if (!isa<ConstantExpr>(V))
7720 return getUnknown(V);
7721
7722 const SCEV *LHS;
7723 const SCEV *RHS;
7724
7726 if (auto BO = MatchBinaryOp(U, DT)) {
7727 switch (BO->Opcode) {
7728 case Instruction::Add: {
7729 // The simple thing to do would be to just call getSCEV on both operands
7730 // and call getAddExpr with the result. However if we're looking at a
7731 // bunch of things all added together, this can be quite inefficient,
7732 // because it leads to N-1 getAddExpr calls for N ultimate operands.
7733 // Instead, gather up all the operands and make a single getAddExpr call.
7734 // LLVM IR canonical form means we need only traverse the left operands.
7736 do {
7737 if (BO->Op) {
7738 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7739 AddOps.push_back(OpSCEV);
7740 break;
7741 }
7742
7743 // If a NUW or NSW flag can be applied to the SCEV for this
7744 // addition, then compute the SCEV for this addition by itself
7745 // with a separate call to getAddExpr. We need to do that
7746 // instead of pushing the operands of the addition onto AddOps,
7747 // since the flags are only known to apply to this particular
7748 // addition - they may not apply to other additions that can be
7749 // formed with operands from AddOps.
7750 const SCEV *RHS = getSCEV(BO->RHS);
7751 SCEVFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7752 if (Flags != SCEV::FlagNone) {
7753 const SCEV *LHS = getSCEV(BO->LHS);
7754 if (BO->Opcode == Instruction::Sub)
7755 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7756 else
7757 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7758 break;
7759 }
7760 }
7761
7762 if (BO->Opcode == Instruction::Sub)
7763 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7764 else
7765 AddOps.push_back(getSCEV(BO->RHS));
7766
7767 auto NewBO = MatchBinaryOp(BO->LHS, DT);
7768 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7769 NewBO->Opcode != Instruction::Sub)) {
7770 AddOps.push_back(getSCEV(BO->LHS));
7771 break;
7772 }
7773 BO = NewBO;
7774 } while (true);
7775
7776 return getAddExpr(AddOps);
7777 }
7778
7779 case Instruction::Mul: {
7781 do {
7782 if (BO->Op) {
7783 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7784 MulOps.push_back(OpSCEV);
7785 break;
7786 }
7787
7788 SCEVFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7789 if (Flags != SCEV::FlagNone) {
7790 LHS = getSCEV(BO->LHS);
7791 RHS = getSCEV(BO->RHS);
7792 MulOps.push_back(getMulExpr(LHS, RHS, Flags));
7793 break;
7794 }
7795 }
7796
7797 MulOps.push_back(getSCEV(BO->RHS));
7798 auto NewBO = MatchBinaryOp(BO->LHS, DT);
7799 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7800 MulOps.push_back(getSCEV(BO->LHS));
7801 break;
7802 }
7803 BO = NewBO;
7804 } while (true);
7805
7806 return getMulExpr(MulOps);
7807 }
7808 case Instruction::UDiv:
7809 LHS = getSCEV(BO->LHS);
7810 RHS = getSCEV(BO->RHS);
7811 return getUDivExpr(LHS, RHS);
7812 case Instruction::URem:
7813 LHS = getSCEV(BO->LHS);
7814 RHS = getSCEV(BO->RHS);
7815 return getURemExpr(LHS, RHS);
7816 case Instruction::Sub: {
7818 if (BO->Op)
7819 Flags = getNoWrapFlagsFromUB(BO->Op);
7820
7821 // Try to use ptrtoaddr for subtracts with at least one ptrtoint
7822 // operand. While we don't model ptrtoint directly in SCEV, the
7823 // difference between two pointer addresses is well-defined.
7824 Value *PtrLHS = nullptr, *PtrRHS = nullptr;
7825 bool HasPtrLHS = match(BO->LHS, m_PtrToInt(m_Value(PtrLHS)));
7826 bool HasPtrRHS = match(BO->RHS, m_PtrToInt(m_Value(PtrRHS)));
7827 if (HasPtrLHS || HasPtrRHS) {
7828 // Convert a ptrtoint operand (OrigOp) to ptrtoaddr of its pointer
7829 // PtrOp. When only one side is ptrtoint (BothPtr is false), skip
7830 // SCEVUnknown pointers since wrapping them in ptrtoaddr adds no
7831 // useful structure.
7832 auto GetOp = [&](bool HasPtr, Value *PtrOp, Value *OrigOp,
7833 bool BothPtr) -> const SCEV * {
7834 if (!HasPtr)
7835 return getSCEV(OrigOp);
7836 const SCEV *PtrSCEV = getSCEV(PtrOp);
7837 if (BothPtr || !isa<SCEVUnknown>(PtrSCEV)) {
7838 const SCEV *Addr = getPtrToAddrExpr(PtrSCEV);
7839 if (!isa<SCEVCouldNotCompute>(Addr) &&
7840 getTypeSizeInBits(OrigOp->getType()) <=
7841 getTypeSizeInBits(Addr->getType()))
7842 return getTruncateOrNoop(Addr, OrigOp->getType());
7843 }
7844 return getSCEV(OrigOp);
7845 };
7846 const SCEV *L = GetOp(HasPtrLHS, PtrLHS, BO->LHS, HasPtrRHS);
7847 const SCEV *R = GetOp(HasPtrRHS, PtrRHS, BO->RHS, HasPtrLHS);
7848 return getMinusSCEV(L, R, Flags);
7849 }
7850
7851 LHS = getSCEV(BO->LHS);
7852 RHS = getSCEV(BO->RHS);
7853 return getMinusSCEV(LHS, RHS, Flags);
7854 }
7855 case Instruction::And:
7856 // For an expression like x&255 that merely masks off the high bits,
7857 // use zext(trunc(x)) as the SCEV expression.
7858 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7859 if (CI->isZero())
7860 return getSCEV(BO->RHS);
7861 if (CI->isMinusOne())
7862 return getSCEV(BO->LHS);
7863 const APInt &A = CI->getValue();
7864
7865 // Instcombine's ShrinkDemandedConstant may strip bits out of
7866 // constants, obscuring what would otherwise be a low-bits mask.
7867 // Use computeKnownBits to compute what ShrinkDemandedConstant
7868 // knew about to reconstruct a low-bits mask value.
7869 unsigned LZ = A.countl_zero();
7870 unsigned TZ = A.countr_zero();
7871 unsigned BitWidth = A.getBitWidth();
7872 KnownBits Known(BitWidth);
7873 computeKnownBits(BO->LHS, Known, getDataLayout(), &AC, nullptr, &DT);
7874
7875 APInt EffectiveMask =
7876 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
7877 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
7878 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
7879 const SCEV *LHS = getSCEV(BO->LHS);
7880 const SCEV *ShiftedLHS = nullptr;
7881 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
7882 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
7883 // For an expression like (x * 8) & 8, simplify the multiply.
7884 unsigned MulZeros = OpC->getAPInt().countr_zero();
7885 unsigned GCD = std::min(MulZeros, TZ);
7886 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
7888 MulOps.push_back(getConstant(OpC->getAPInt().ashr(GCD)));
7889 append_range(MulOps, LHSMul->operands().drop_front());
7890 const SCEV *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
7891 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
7892 }
7893 }
7894 if (!ShiftedLHS)
7895 ShiftedLHS = getUDivExpr(LHS, MulCount);
7896 return getMulExpr(
7898 getTruncateExpr(ShiftedLHS,
7899 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
7900 BO->LHS->getType()),
7901 MulCount);
7902 }
7903 }
7904 // Binary `and` is a bit-wise `umin`.
7905 if (BO->LHS->getType()->isIntegerTy(1)) {
7906 LHS = getSCEV(BO->LHS);
7907 RHS = getSCEV(BO->RHS);
7908 return getUMinExpr(LHS, RHS);
7909 }
7910 break;
7911
7912 case Instruction::Or:
7913 // Binary `or` is a bit-wise `umax`.
7914 if (BO->LHS->getType()->isIntegerTy(1)) {
7915 LHS = getSCEV(BO->LHS);
7916 RHS = getSCEV(BO->RHS);
7917 return getUMaxExpr(LHS, RHS);
7918 }
7919 break;
7920
7921 case Instruction::Xor:
7922 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7923 // If the RHS of xor is -1, then this is a not operation.
7924 if (CI->isMinusOne())
7925 return getNotSCEV(getSCEV(BO->LHS));
7926
7927 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
7928 // This is a variant of the check for xor with -1, and it handles
7929 // the case where instcombine has trimmed non-demanded bits out
7930 // of an xor with -1.
7931 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
7932 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
7933 if (LBO->getOpcode() == Instruction::And &&
7934 LCI->getValue() == CI->getValue())
7935 if (const SCEVZeroExtendExpr *Z =
7937 Type *UTy = BO->LHS->getType();
7938 const SCEV *Z0 = Z->getOperand();
7939 Type *Z0Ty = Z0->getType();
7940 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
7941
7942 // If C is a low-bits mask, the zero extend is serving to
7943 // mask off the high bits. Complement the operand and
7944 // re-apply the zext.
7945 if (CI->getValue().isMask(Z0TySize))
7946 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
7947
7948 // If C is a single bit, it may be in the sign-bit position
7949 // before the zero-extend. In this case, represent the xor
7950 // using an add, which is equivalent, and re-apply the zext.
7951 APInt Trunc = CI->getValue().trunc(Z0TySize);
7952 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
7953 Trunc.isSignMask())
7955 UTy);
7956 }
7957 }
7958 break;
7959
7960 case Instruction::Shl:
7961 // Turn shift left of a constant amount into a multiply.
7962 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
7963 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
7964
7965 // If the shift count is not less than the bitwidth, the result of
7966 // the shift is undefined. Don't try to analyze it, because the
7967 // resolution chosen here may differ from the resolution chosen in
7968 // other parts of the compiler.
7969 if (SA->getValue().uge(BitWidth))
7970 break;
7971
7972 // We can safely preserve the nuw flag in all cases. It's also safe to
7973 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
7974 // requires special handling. It can be preserved as long as we're not
7975 // left shifting by bitwidth - 1.
7976 auto Flags = SCEV::FlagNone;
7977 if (BO->Op) {
7978 auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
7979 if (any(MulFlags & SCEV::FlagNSW) &&
7980 (any(MulFlags & SCEV::FlagNUW) ||
7981 SA->getValue().ult(BitWidth - 1)))
7983 if (any(MulFlags & SCEV::FlagNUW))
7985 }
7986
7987 ConstantInt *X = ConstantInt::get(
7988 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
7989 return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
7990 }
7991 break;
7992
7993 case Instruction::AShr:
7994 // AShr X, C, where C is a constant.
7995 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
7996 if (!CI)
7997 break;
7998
7999 Type *OuterTy = BO->LHS->getType();
8001 // If the shift count is not less than the bitwidth, the result of
8002 // the shift is undefined. Don't try to analyze it, because the
8003 // resolution chosen here may differ from the resolution chosen in
8004 // other parts of the compiler.
8005 if (CI->getValue().uge(BitWidth))
8006 break;
8007
8008 if (CI->isZero())
8009 return getSCEV(BO->LHS); // shift by zero --> noop
8010
8011 uint64_t AShrAmt = CI->getZExtValue();
8012 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
8013
8014 Operator *L = dyn_cast<Operator>(BO->LHS);
8015 const SCEV *AddTruncateExpr = nullptr;
8016 ConstantInt *ShlAmtCI = nullptr;
8017 const SCEV *AddConstant = nullptr;
8018
8019 if (L && L->getOpcode() == Instruction::Add) {
8020 // X = Shl A, n
8021 // Y = Add X, c
8022 // Z = AShr Y, m
8023 // n, c and m are constants.
8024
8025 Operator *LShift = dyn_cast<Operator>(L->getOperand(0));
8026 ConstantInt *AddOperandCI = dyn_cast<ConstantInt>(L->getOperand(1));
8027 if (LShift && LShift->getOpcode() == Instruction::Shl) {
8028 if (AddOperandCI) {
8029 const SCEV *ShlOp0SCEV = getSCEV(LShift->getOperand(0));
8030 ShlAmtCI = dyn_cast<ConstantInt>(LShift->getOperand(1));
8031 // since we truncate to TruncTy, the AddConstant should be of the
8032 // same type, so create a new Constant with type same as TruncTy.
8033 // Also, the Add constant should be shifted right by AShr amount.
8034 APInt AddOperand = AddOperandCI->getValue().ashr(AShrAmt);
8035 AddConstant = getConstant(AddOperand.trunc(BitWidth - AShrAmt));
8036 // we model the expression as sext(add(trunc(A), c << n)), since the
8037 // sext(trunc) part is already handled below, we create a
8038 // AddExpr(TruncExp) which will be used later.
8039 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8040 }
8041 }
8042 } else if (L && L->getOpcode() == Instruction::Shl) {
8043 // X = Shl A, n
8044 // Y = AShr X, m
8045 // Both n and m are constant.
8046
8047 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
8048 ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
8049 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8050 }
8051
8052 if (AddTruncateExpr && ShlAmtCI) {
8053 // We can merge the two given cases into a single SCEV statement,
8054 // incase n = m, the mul expression will be 2^0, so it gets resolved to
8055 // a simpler case. The following code handles the two cases:
8056 //
8057 // 1) For a two-shift sext-inreg, i.e. n = m,
8058 // use sext(trunc(x)) as the SCEV expression.
8059 //
8060 // 2) When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
8061 // expression. We already checked that ShlAmt < BitWidth, so
8062 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
8063 // ShlAmt - AShrAmt < Amt.
8064 const APInt &ShlAmt = ShlAmtCI->getValue();
8065 if (ShlAmt.ult(BitWidth) && ShlAmt.uge(AShrAmt)) {
8066 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
8067 ShlAmtCI->getZExtValue() - AShrAmt);
8068 const SCEV *CompositeExpr =
8069 getMulExpr(AddTruncateExpr, getConstant(Mul));
8070 if (L->getOpcode() != Instruction::Shl)
8071 CompositeExpr = getAddExpr(CompositeExpr, AddConstant);
8072
8073 return getSignExtendExpr(CompositeExpr, OuterTy);
8074 }
8075 }
8076 break;
8077 }
8078 }
8079
8080 switch (U->getOpcode()) {
8081 case Instruction::Trunc:
8082 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
8083
8084 case Instruction::ZExt:
8085 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8086
8087 case Instruction::SExt:
8088 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
8089 // The NSW flag of a subtract does not always survive the conversion to
8090 // A + (-1)*B. By pushing sign extension onto its operands we are much
8091 // more likely to preserve NSW and allow later AddRec optimisations.
8092 //
8093 // NOTE: This is effectively duplicating this logic from getSignExtend:
8094 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
8095 // but by that point the NSW information has potentially been lost.
8096 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
8097 Type *Ty = U->getType();
8098 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
8099 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
8100 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
8101 }
8102 }
8103 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8104
8105 case Instruction::BitCast:
8106 // BitCasts are no-op casts so we just eliminate the cast.
8107 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
8108 return getSCEV(U->getOperand(0));
8109 break;
8110
8111 case Instruction::PtrToAddr: {
8112 const SCEV *IntOp = getPtrToAddrExpr(getSCEV(U->getOperand(0)));
8113 if (isa<SCEVCouldNotCompute>(IntOp))
8114 return getUnknown(V);
8115 return IntOp;
8116 }
8117
8118 case Instruction::PtrToInt:
8119 // SCEV only models ptrtoaddr.
8120 return getUnknown(V);
8121
8122 case Instruction::IntToPtr:
8123 // Just don't deal with inttoptr casts.
8124 return getUnknown(V);
8125
8126 case Instruction::SDiv:
8127 // If both operands are non-negative, this is just an udiv.
8128 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8129 isKnownNonNegative(getSCEV(U->getOperand(1))))
8130 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8131 break;
8132
8133 case Instruction::SRem:
8134 // If both operands are non-negative, this is just an urem.
8135 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8136 isKnownNonNegative(getSCEV(U->getOperand(1))))
8137 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8138 break;
8139
8140 case Instruction::GetElementPtr:
8141 return createNodeForGEP(cast<GEPOperator>(U));
8142
8143 case Instruction::PHI:
8144 return createNodeForPHI(cast<PHINode>(U));
8145
8146 case Instruction::Select:
8147 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
8148 U->getOperand(2));
8149
8150 case Instruction::Call:
8151 case Instruction::Invoke:
8152 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
8153 return getSCEV(RV);
8154
8155 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
8156 switch (II->getIntrinsicID()) {
8157 case Intrinsic::abs:
8158 return getAbsExpr(
8159 getSCEV(II->getArgOperand(0)),
8160 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
8161 case Intrinsic::umax:
8162 LHS = getSCEV(II->getArgOperand(0));
8163 RHS = getSCEV(II->getArgOperand(1));
8164 return getUMaxExpr(LHS, RHS);
8165 case Intrinsic::umin:
8166 LHS = getSCEV(II->getArgOperand(0));
8167 RHS = getSCEV(II->getArgOperand(1));
8168 return getUMinExpr(LHS, RHS);
8169 case Intrinsic::smax:
8170 LHS = getSCEV(II->getArgOperand(0));
8171 RHS = getSCEV(II->getArgOperand(1));
8172 return getSMaxExpr(LHS, RHS);
8173 case Intrinsic::smin:
8174 LHS = getSCEV(II->getArgOperand(0));
8175 RHS = getSCEV(II->getArgOperand(1));
8176 return getSMinExpr(LHS, RHS);
8177 case Intrinsic::usub_sat: {
8178 const SCEV *X = getSCEV(II->getArgOperand(0));
8179 const SCEV *Y = getSCEV(II->getArgOperand(1));
8180 const SCEV *ClampedY = getUMinExpr(X, Y);
8181 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
8182 }
8183 case Intrinsic::uadd_sat: {
8184 const SCEV *X = getSCEV(II->getArgOperand(0));
8185 const SCEV *Y = getSCEV(II->getArgOperand(1));
8186 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
8187 return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
8188 }
8189 case Intrinsic::start_loop_iterations:
8190 case Intrinsic::annotation:
8191 case Intrinsic::ptr_annotation:
8192 // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8193 // just eqivalent to the first operand for SCEV purposes.
8194 return getSCEV(II->getArgOperand(0));
8195 case Intrinsic::vscale:
8196 return getVScale(II->getType());
8197 default:
8198 break;
8199 }
8200 }
8201 break;
8202 }
8203
8204 return getUnknown(V);
8205}
8206
8207//===----------------------------------------------------------------------===//
8208// Iteration Count Computation Code
8209//
8210
8212 if (isa<SCEVCouldNotCompute>(ExitCount))
8213 return getCouldNotCompute();
8214
8215 auto *ExitCountType = ExitCount->getType();
8216 assert(ExitCountType->isIntegerTy());
8217 auto *EvalTy = Type::getIntNTy(ExitCountType->getContext(),
8218 1 + ExitCountType->getScalarSizeInBits());
8219 return getTripCountFromExitCount(ExitCount, EvalTy, nullptr);
8220}
8221
8223 Type *EvalTy,
8224 const Loop *L) {
8225 if (isa<SCEVCouldNotCompute>(ExitCount))
8226 return getCouldNotCompute();
8227
8228 unsigned ExitCountSize = getTypeSizeInBits(ExitCount->getType());
8229 unsigned EvalSize = EvalTy->getPrimitiveSizeInBits();
8230
8231 auto CanAddOneWithoutOverflow = [&]() {
8232 ConstantRange ExitCountRange =
8233 getRangeRef(ExitCount, RangeSignHint::HINT_RANGE_UNSIGNED);
8234 if (!ExitCountRange.contains(APInt::getMaxValue(ExitCountSize)))
8235 return true;
8236
8237 return L && isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
8238 getMinusOne(ExitCount->getType()));
8239 };
8240
8241 // If we need to zero extend the backedge count, check if we can add one to
8242 // it prior to zero extending without overflow. Provided this is safe, it
8243 // allows better simplification of the +1.
8244 if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8245 return getZeroExtendExpr(
8246 getAddExpr(ExitCount, getOne(ExitCount->getType())), EvalTy);
8247
8248 // Get the total trip count from the count by adding 1. This may wrap.
8249 return getAddExpr(getTruncateOrZeroExtend(ExitCount, EvalTy), getOne(EvalTy));
8250}
8251
8252static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8253 if (!ExitCount)
8254 return 0;
8255
8256 ConstantInt *ExitConst = ExitCount->getValue();
8257
8258 // Guard against huge trip counts.
8259 if (ExitConst->getValue().getActiveBits() > 32)
8260 return 0;
8261
8262 // In case of integer overflow, this returns 0, which is correct.
8263 return ((unsigned)ExitConst->getZExtValue()) + 1;
8264}
8265
8267 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
8268 return getConstantTripCount(ExitCount);
8269}
8270
8271unsigned
8273 const BasicBlock *ExitingBlock) {
8274 assert(ExitingBlock && "Must pass a non-null exiting block!");
8275 assert(L->isLoopExiting(ExitingBlock) &&
8276 "Exiting block must actually branch out of the loop!");
8277 const SCEVConstant *ExitCount =
8278 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
8279 return getConstantTripCount(ExitCount);
8280}
8281
8283 const Loop *L, SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8284
8285 const auto *MaxExitCount =
8286 Predicates ? getPredicatedConstantMaxBackedgeTakenCount(L, *Predicates)
8288 return getConstantTripCount(dyn_cast<SCEVConstant>(MaxExitCount));
8289}
8290
8292 SmallVector<BasicBlock *, 8> ExitingBlocks;
8293 L->getExitingBlocks(ExitingBlocks);
8294
8295 // An exit with an uncomputable exit count makes the result 1.
8296 if (ExitingBlocks.empty() ||
8297 any_of(ExitingBlocks, [this, L](BasicBlock *ExitingBB) {
8298 return isa<SCEVCouldNotCompute>(getExitCount(L, ExitingBB));
8299 }))
8300 return 1;
8301
8302 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
8303 unsigned Res = 0;
8304 for (BasicBlock *ExitingBB : ExitingBlocks)
8305 Res = std::gcd(
8306 Res, getSmallConstantTripMultiple(getExitCount(L, ExitingBB), Guards));
8307 return Res;
8308}
8309
8310unsigned ScalarEvolution::getSmallConstantTripMultiple(const SCEV *ExitCount,
8311 LoopGuards &Guards) {
8312 assert(!isa<SCEVCouldNotCompute>(ExitCount) && "Must be computable!");
8313
8314 // Get the trip count
8315 const SCEV *TCExpr =
8316 getTripCountFromExitCount(applyLoopGuards(ExitCount, Guards));
8317
8318 APInt Multiple = getNonZeroConstantMultiple(TCExpr);
8319 // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8320 // the greatest power of 2 divisor less than 2^32.
8321 return Multiple.getActiveBits() > 32
8322 ? 1U << std::min(31U, Multiple.countTrailingZeros())
8323 : (unsigned)Multiple.getZExtValue();
8324}
8325
8327 const SCEV *ExitCount) {
8328 if (isa<SCEVCouldNotCompute>(ExitCount))
8329 return 1;
8330
8331 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
8332 return getSmallConstantTripMultiple(ExitCount, Guards);
8333}
8334
8335/// Returns the largest constant divisor of the trip count of this loop as a
8336/// normal unsigned value, if possible. This means that the actual trip count is
8337/// always a multiple of the returned value (don't forget the trip count could
8338/// very well be zero as well!).
8339///
8340/// Returns 1 if the trip count is unknown or not guaranteed to be the
8341/// multiple of a constant (which is also the case if the trip count is simply
8342/// constant, use getSmallConstantTripCount for that case), Will also return 1
8343/// if the trip count is very large (>= 2^32).
8344///
8345/// As explained in the comments for getSmallConstantTripCount, this assumes
8346/// that control exits the loop via ExitingBlock.
8347unsigned
8349 const BasicBlock *ExitingBlock) {
8350 assert(ExitingBlock && "Must pass a non-null exiting block!");
8351 assert(L->isLoopExiting(ExitingBlock) &&
8352 "Exiting block must actually branch out of the loop!");
8353 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8354 return getSmallConstantTripMultiple(L, ExitCount);
8355}
8356
8358 const BasicBlock *ExitingBlock,
8359 ExitCountKind Kind) {
8360 switch (Kind) {
8361 case Exact:
8362 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8363 case SymbolicMaximum:
8364 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8365 case ConstantMaximum:
8366 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8367 };
8368 llvm_unreachable("Invalid ExitCountKind!");
8369}
8370
8372 const Loop *L, const BasicBlock *ExitingBlock,
8374 switch (Kind) {
8375 case Exact:
8376 return getPredicatedBackedgeTakenInfo(L).getExact(ExitingBlock, this,
8377 Predicates);
8378 case SymbolicMaximum:
8379 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this,
8380 Predicates);
8381 case ConstantMaximum:
8382 return getPredicatedBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this,
8383 Predicates);
8384 };
8385 llvm_unreachable("Invalid ExitCountKind!");
8386}
8387
8390 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8391}
8392
8394 ExitCountKind Kind) {
8395 switch (Kind) {
8396 case Exact:
8397 return getBackedgeTakenInfo(L).getExact(L, this);
8398 case ConstantMaximum:
8399 return getBackedgeTakenInfo(L).getConstantMax(this);
8400 case SymbolicMaximum:
8401 return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8402 };
8403 llvm_unreachable("Invalid ExitCountKind!");
8404}
8405
8408 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(L, this, &Preds);
8409}
8410
8413 return getPredicatedBackedgeTakenInfo(L).getConstantMax(this, &Preds);
8414}
8415
8417 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8418}
8419
8420/// Push PHI nodes in the header of the given loop onto the given Worklist.
8421static void PushLoopPHIs(const Loop *L,
8424 BasicBlock *Header = L->getHeader();
8425
8426 // Push all Loop-header PHIs onto the Worklist stack.
8427 for (PHINode &PN : Header->phis())
8428 if (Visited.insert(&PN).second)
8429 Worklist.push_back(&PN);
8430}
8431
8432ScalarEvolution::BackedgeTakenInfo &
8433ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8434 auto &BTI = getBackedgeTakenInfo(L);
8435 if (BTI.hasFullInfo())
8436 return BTI;
8437
8438 auto Pair = PredicatedBackedgeTakenCounts.try_emplace(L);
8439
8440 if (!Pair.second)
8441 return Pair.first->second;
8442
8443 BackedgeTakenInfo Result =
8444 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8445
8446 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8447}
8448
8449ScalarEvolution::BackedgeTakenInfo &
8450ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8451 // Initially insert an invalid entry for this loop. If the insertion
8452 // succeeds, proceed to actually compute a backedge-taken count and
8453 // update the value. The temporary CouldNotCompute value tells SCEV
8454 // code elsewhere that it shouldn't attempt to request a new
8455 // backedge-taken count, which could result in infinite recursion.
8456 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8457 BackedgeTakenCounts.try_emplace(L);
8458 if (!Pair.second)
8459 return Pair.first->second;
8460
8461 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8462 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8463 // must be cleared in this scope.
8464 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8465
8466 // Now that we know more about the trip count for this loop, forget any
8467 // existing SCEV values for PHI nodes in this loop since they are only
8468 // conservative estimates made without the benefit of trip count
8469 // information. This invalidation is not necessary for correctness, and is
8470 // only done to produce more precise results.
8471 if (Result.hasAnyInfo()) {
8472 // Invalidate any expression using an addrec in this loop.
8473 SmallVector<SCEVUse, 8> ToForget;
8474 auto LoopUsersIt = LoopUsers.find(L);
8475 if (LoopUsersIt != LoopUsers.end())
8476 append_range(ToForget, LoopUsersIt->second);
8477 forgetMemoizedResults(ToForget);
8478
8479 // Invalidate constant-evolved loop header phis.
8480 for (PHINode &PN : L->getHeader()->phis())
8481 ConstantEvolutionLoopExitValue.erase(&PN);
8482 }
8483
8484 // Re-lookup the insert position, since the call to
8485 // computeBackedgeTakenCount above could result in a
8486 // recusive call to getBackedgeTakenInfo (on a different
8487 // loop), which would invalidate the iterator computed
8488 // earlier.
8489 return BackedgeTakenCounts.find(L)->second = std::move(Result);
8490}
8491
8493 // This method is intended to forget all info about loops. It should
8494 // invalidate caches as if the following happened:
8495 // - The trip counts of all loops have changed arbitrarily
8496 // - Every llvm::Value has been updated in place to produce a different
8497 // result.
8498 BackedgeTakenCounts.clear();
8499 PredicatedBackedgeTakenCounts.clear();
8500 BECountUsers.clear();
8501 LoopPropertiesCache.clear();
8502 ConstantEvolutionLoopExitValue.clear();
8503 ValueExprMap.clear();
8504 ValuesAtScopes.clear();
8505 ValuesAtScopesUsers.clear();
8506 LoopDispositions.clear();
8507 BlockDispositions.clear();
8508 UnsignedRanges.clear();
8509 SignedRanges.clear();
8510 ExprValueMap.clear();
8511 HasRecMap.clear();
8512 ConstantMultipleCache.clear();
8513 PredicatedSCEVRewrites.clear();
8514 FoldCache.clear();
8515 FoldCacheUser.clear();
8516}
8517void ScalarEvolution::visitAndClearUsers(
8520 SmallVectorImpl<SCEVUse> &ToForget) {
8521 // Nothing can be invalidated if no value has a SCEV yet.
8522 if (ValueExprMap.empty()) {
8523 Worklist.clear();
8524 return;
8525 }
8526 while (!Worklist.empty()) {
8527 Instruction *I = Worklist.pop_back_val();
8528 if (!isSCEVable(I->getType()) && !isa<WithOverflowInst>(I))
8529 continue;
8530
8532 ValueExprMap.find_as(static_cast<Value *>(I));
8533 if (It != ValueExprMap.end()) {
8534 ToForget.push_back(It->second);
8535 eraseValueFromMap(It->first);
8536 if (PHINode *PN = dyn_cast<PHINode>(I))
8537 ConstantEvolutionLoopExitValue.erase(PN);
8538 }
8539
8540 PushDefUseChildren(I, Worklist, Visited);
8541 }
8542}
8543
8545 SmallVector<const Loop *, 16> LoopWorklist(1, L);
8548 SmallVector<SCEVUse, 16> ToForget;
8549
8550 // Iterate over all the loops and sub-loops to drop SCEV information.
8551 while (!LoopWorklist.empty()) {
8552 auto *CurrL = LoopWorklist.pop_back_val();
8553
8554 // Drop any stored trip count value.
8555 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8556 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8557
8558 // Drop information about predicated SCEV rewrites for this loop.
8559 PredicatedSCEVRewrites.remove_if(
8560 [&](const auto &Entry) { return Entry.first.second == CurrL; });
8561
8562 auto LoopUsersItr = LoopUsers.find(CurrL);
8563 if (LoopUsersItr != LoopUsers.end())
8564 llvm::append_range(ToForget, LoopUsersItr->second);
8565
8566 // Drop information about expressions based on loop-header PHIs.
8567 PushLoopPHIs(CurrL, Worklist, Visited);
8568 visitAndClearUsers(Worklist, Visited, ToForget);
8569
8570 LoopPropertiesCache.erase(CurrL);
8571 // Forget all contained loops too, to avoid dangling entries in the
8572 // ValuesAtScopes map.
8573 LoopWorklist.append(CurrL->begin(), CurrL->end());
8574 }
8575 forgetMemoizedResults(ToForget);
8576}
8577
8579 forgetLoop(L->getOutermostLoop());
8580}
8581
8584 if (!I) return;
8585
8586 // Drop information about expressions based on loop-header PHIs.
8589 SmallVector<SCEVUse, 8> ToForget;
8590 Worklist.push_back(I);
8591 Visited.insert(I);
8592 visitAndClearUsers(Worklist, Visited, ToForget);
8593
8594 forgetMemoizedResults(ToForget);
8595}
8596
8600 SmallVector<SCEVUse, 8> ToForget;
8601 for (Value *V : Values)
8602 if (auto *I = dyn_cast<Instruction>(V))
8603 if (Visited.insert(I).second)
8604 Worklist.push_back(I);
8605 visitAndClearUsers(Worklist, Visited, ToForget);
8606
8607 forgetMemoizedResults(ToForget);
8608}
8609
8611 // If SCEV looked through a trivial LCSSA phi node, we might have SCEV's
8612 // directly using a SCEVUnknown/SCEVAddRec defined in the loop. After an
8613 // extra predecessor is added, this is no longer valid. Find all Unknowns and
8614 // AddRecs defined in the loop and invalidate any SCEV's making use of them.
8615 auto InvalidateValue = [&](Value *Val) {
8616 if (!isSCEVable(Val->getType()))
8617 return;
8618 if (const SCEV *S = getExistingSCEV(Val)) {
8619 struct InvalidationRootCollector {
8620 Loop *L;
8622
8623 InvalidationRootCollector(Loop *L) : L(L) {}
8624
8625 bool follow(const SCEV *S) {
8626 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
8627 if (auto *I = dyn_cast<Instruction>(SU->getValue()))
8628 if (L->contains(I))
8629 Roots.push_back(S);
8630 } else if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
8631 if (L->contains(AddRec->getLoop()))
8632 Roots.push_back(S);
8633 }
8634 return true;
8635 }
8636 bool isDone() const { return false; }
8637 };
8638
8639 InvalidationRootCollector C(L);
8640 visitAll(S, C);
8641 forgetMemoizedResults(C.Roots);
8642 }
8643 };
8644
8645 InvalidateValue(V);
8646
8647 // If V has a non-SCEV-able type (e.g. {i64, i1} from a with.overflow
8648 // intrinsic), its users (e.g. extractvalue) may have stale SCEV
8649 // expressions referencing loop-internal values.
8650 if (!isSCEVable(V->getType()) &&
8651 any_of(V->incoming_values(), IsaPred<WithOverflowInst>))
8652 for (User *U : V->users())
8653 InvalidateValue(U);
8654 // Also perform the normal invalidation.
8655 forgetValue(V);
8656}
8657
8658void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8659
8661 // Unless a specific value is passed to invalidation, completely clear both
8662 // caches.
8663 if (!V) {
8664 BlockDispositions.clear();
8665 LoopDispositions.clear();
8666 return;
8667 }
8668
8669 if (!isSCEVable(V->getType()))
8670 return;
8671
8672 const SCEV *S = getExistingSCEV(V);
8673 if (!S)
8674 return;
8675
8676 // Invalidate the block and loop dispositions cached for S. Dispositions of
8677 // S's users may change if S's disposition changes (i.e. a user may change to
8678 // loop-invariant, if S changes to loop invariant), so also invalidate
8679 // dispositions of S's users recursively.
8680 SmallVector<SCEVUse, 8> Worklist = {S};
8682 while (!Worklist.empty()) {
8683 const SCEV *Curr = Worklist.pop_back_val();
8684 bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8685 bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8686 if (!LoopDispoRemoved && !BlockDispoRemoved)
8687 continue;
8688 auto Users = SCEVUsers.find(Curr);
8689 if (Users != SCEVUsers.end())
8690 for (const auto *User : Users->second)
8691 if (Seen.insert(User).second)
8692 Worklist.push_back(User);
8693 }
8694}
8695
8696/// Get the exact loop backedge taken count considering all loop exits. A
8697/// computable result can only be returned for loops with all exiting blocks
8698/// dominating the latch. howFarToZero assumes that the limit of each loop test
8699/// is never skipped. This is a valid assumption as long as the loop exits via
8700/// that test. For precise results, it is the caller's responsibility to specify
8701/// the relevant loop exiting block using getExact(ExitingBlock, SE).
8702const SCEV *ScalarEvolution::BackedgeTakenInfo::getExact(
8703 const Loop *L, ScalarEvolution *SE,
8705 // If any exits were not computable, the loop is not computable.
8706 if (!isComplete() || ExitNotTaken.empty())
8707 return SE->getCouldNotCompute();
8708
8709 const BasicBlock *Latch = L->getLoopLatch();
8710 // All exiting blocks we have collected must dominate the only backedge.
8711 if (!Latch)
8712 return SE->getCouldNotCompute();
8713
8714 // All exiting blocks we have gathered dominate loop's latch, so exact trip
8715 // count is simply a minimum out of all these calculated exit counts.
8717 for (const auto &ENT : ExitNotTaken) {
8718 const SCEV *BECount = ENT.ExactNotTaken;
8719 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8720 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8721 "We should only have known counts for exiting blocks that dominate "
8722 "latch!");
8723
8724 Ops.push_back(BECount);
8725
8726 if (Preds)
8727 append_range(*Preds, ENT.Predicates);
8728
8729 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8730 "Predicate should be always true!");
8731 }
8732
8733 // If an earlier exit exits on the first iteration (exit count zero), then
8734 // a later poison exit count should not propagate into the result. This are
8735 // exactly the semantics provided by umin_seq.
8736 return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8737}
8738
8739const ScalarEvolution::ExitNotTakenInfo *
8740ScalarEvolution::BackedgeTakenInfo::getExitNotTaken(
8741 const BasicBlock *ExitingBlock,
8742 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8743 for (const auto &ENT : ExitNotTaken)
8744 if (ENT.ExitingBlock == ExitingBlock) {
8745 if (ENT.hasAlwaysTruePredicate())
8746 return &ENT;
8747 else if (Predicates) {
8748 append_range(*Predicates, ENT.Predicates);
8749 return &ENT;
8750 }
8751 }
8752
8753 return nullptr;
8754}
8755
8756/// getConstantMax - Get the constant max backedge taken count for the loop.
8757const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8758 ScalarEvolution *SE,
8759 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8760 if (!getConstantMax())
8761 return SE->getCouldNotCompute();
8762
8763 for (const auto &ENT : ExitNotTaken)
8764 if (!ENT.hasAlwaysTruePredicate()) {
8765 if (!Predicates)
8766 return SE->getCouldNotCompute();
8767 append_range(*Predicates, ENT.Predicates);
8768 }
8769
8770 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8771 isa<SCEVConstant>(getConstantMax())) &&
8772 "No point in having a non-constant max backedge taken count!");
8773 return getConstantMax();
8774}
8775
8776const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8777 const Loop *L, ScalarEvolution *SE,
8778 SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8779 if (!SymbolicMax) {
8780 // Form an expression for the maximum exit count possible for this loop. We
8781 // merge the max and exact information to approximate a version of
8782 // getConstantMaxBackedgeTakenCount which isn't restricted to just
8783 // constants.
8784 SmallVector<SCEVUse, 4> ExitCounts;
8785
8786 for (const auto &ENT : ExitNotTaken) {
8787 const SCEV *ExitCount = ENT.SymbolicMaxNotTaken;
8788 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
8789 assert(SE->DT.dominates(ENT.ExitingBlock, L->getLoopLatch()) &&
8790 "We should only have known counts for exiting blocks that "
8791 "dominate latch!");
8792 ExitCounts.push_back(ExitCount);
8793 if (Predicates)
8794 append_range(*Predicates, ENT.Predicates);
8795
8796 assert((Predicates || ENT.hasAlwaysTruePredicate()) &&
8797 "Predicate should be always true!");
8798 }
8799 }
8800 if (ExitCounts.empty())
8801 SymbolicMax = SE->getCouldNotCompute();
8802 else
8803 SymbolicMax =
8804 SE->getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
8805 }
8806 return SymbolicMax;
8807}
8808
8809bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8810 ScalarEvolution *SE) const {
8811 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8812 return !ENT.hasAlwaysTruePredicate();
8813 };
8814 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8815}
8816
8819
8821 const SCEV *E, const SCEV *ConstantMaxNotTaken,
8822 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8826 // If we prove the max count is zero, so is the symbolic bound. This happens
8827 // in practice due to differences in a) how context sensitive we've chosen
8828 // to be and b) how we reason about bounds implied by UB.
8829 if (ConstantMaxNotTaken->isZero()) {
8830 this->ExactNotTaken = E = ConstantMaxNotTaken;
8831 this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
8832 }
8833
8836 "Exact is not allowed to be less precise than Constant Max");
8839 "Exact is not allowed to be less precise than Symbolic Max");
8842 "Symbolic Max is not allowed to be less precise than Constant Max");
8845 "No point in having a non-constant max backedge taken count!");
8847 for (const auto PredList : PredLists)
8848 for (const auto *P : PredList) {
8849 if (SeenPreds.contains(P))
8850 continue;
8851 assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!");
8852 SeenPreds.insert(P);
8853 Predicates.push_back(P);
8854 }
8855 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8856 "Backedge count should be int");
8858 !ConstantMaxNotTaken->getType()->isPointerTy()) &&
8859 "Max backedge count should be int");
8860}
8861
8869
8870/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8871/// computable exit into a persistent ExitNotTakenInfo array.
8872ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8874 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
8875 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8876 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8877
8878 ExitNotTaken.reserve(ExitCounts.size());
8879 std::transform(ExitCounts.begin(), ExitCounts.end(),
8880 std::back_inserter(ExitNotTaken),
8881 [&](const EdgeExitInfo &EEI) {
8882 BasicBlock *ExitBB = EEI.first;
8883 const ExitLimit &EL = EEI.second;
8884 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
8885 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
8886 EL.Predicates);
8887 });
8888 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
8889 isa<SCEVConstant>(ConstantMax)) &&
8890 "No point in having a non-constant max backedge taken count!");
8891}
8892
8893/// Compute the number of times the backedge of the specified loop will execute.
8894ScalarEvolution::BackedgeTakenInfo
8895ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
8896 bool AllowPredicates) {
8897 SmallVector<BasicBlock *, 8> ExitingBlocks;
8898 L->getExitingBlocks(ExitingBlocks);
8899
8900 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8901
8903 bool CouldComputeBECount = true;
8904 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
8905 const SCEV *MustExitMaxBECount = nullptr;
8906 const SCEV *MayExitMaxBECount = nullptr;
8907 bool MustExitMaxOrZero = false;
8908 bool IsOnlyExit = ExitingBlocks.size() == 1;
8909
8910 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
8911 // and compute maxBECount.
8912 // Do a union of all the predicates here.
8913 for (BasicBlock *ExitBB : ExitingBlocks) {
8914 // We canonicalize untaken exits to br (constant), ignore them so that
8915 // proving an exit untaken doesn't negatively impact our ability to reason
8916 // about the loop as whole.
8917 if (auto *BI = dyn_cast<CondBrInst>(ExitBB->getTerminator()))
8918 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
8919 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8920 if (ExitIfTrue == CI->isZero())
8921 continue;
8922 }
8923
8924 ExitLimit EL = computeExitLimit(L, ExitBB, IsOnlyExit, AllowPredicates);
8925
8926 assert((AllowPredicates || EL.Predicates.empty()) &&
8927 "Predicated exit limit when predicates are not allowed!");
8928
8929 // 1. For each exit that can be computed, add an entry to ExitCounts.
8930 // CouldComputeBECount is true only if all exits can be computed.
8931 if (EL.ExactNotTaken != getCouldNotCompute())
8932 ++NumExitCountsComputed;
8933 else
8934 // We couldn't compute an exact value for this exit, so
8935 // we won't be able to compute an exact value for the loop.
8936 CouldComputeBECount = false;
8937 // Remember exit count if either exact or symbolic is known. Because
8938 // Exact always implies symbolic, only check symbolic.
8939 if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
8940 ExitCounts.emplace_back(ExitBB, EL);
8941 else {
8942 assert(EL.ExactNotTaken == getCouldNotCompute() &&
8943 "Exact is known but symbolic isn't?");
8944 ++NumExitCountsNotComputed;
8945 }
8946
8947 // 2. Derive the loop's MaxBECount from each exit's max number of
8948 // non-exiting iterations. Partition the loop exits into two kinds:
8949 // LoopMustExits and LoopMayExits.
8950 //
8951 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
8952 // is a LoopMayExit. If any computable LoopMustExit is found, then
8953 // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
8954 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
8955 // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
8956 // any
8957 // computable EL.ConstantMaxNotTaken.
8958 if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
8959 DT.dominates(ExitBB, Latch)) {
8960 if (!MustExitMaxBECount) {
8961 MustExitMaxBECount = EL.ConstantMaxNotTaken;
8962 MustExitMaxOrZero = EL.MaxOrZero;
8963 } else {
8964 MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
8965 EL.ConstantMaxNotTaken);
8966 }
8967 } else if (MayExitMaxBECount != getCouldNotCompute()) {
8968 if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
8969 MayExitMaxBECount = EL.ConstantMaxNotTaken;
8970 else {
8971 MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
8972 EL.ConstantMaxNotTaken);
8973 }
8974 }
8975 }
8976 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
8977 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
8978 // The loop backedge will be taken the maximum or zero times if there's
8979 // a single exit that must be taken the maximum or zero times.
8980 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
8981
8982 // Remember which SCEVs are used in exit limits for invalidation purposes.
8983 // We only care about non-constant SCEVs here, so we can ignore
8984 // EL.ConstantMaxNotTaken
8985 // and MaxBECount, which must be SCEVConstant.
8986 for (const auto &Pair : ExitCounts) {
8987 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
8988 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
8989 if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
8990 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
8991 {L, AllowPredicates});
8992 }
8993 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
8994 MaxBECount, MaxOrZero);
8995}
8996
8997ScalarEvolution::ExitLimit
8998ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
8999 bool IsOnlyExit, bool AllowPredicates) {
9000 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
9001 // If our exiting block does not dominate the latch, then its connection with
9002 // loop's exit limit may be far from trivial.
9003 const BasicBlock *Latch = L->getLoopLatch();
9004 if (!Latch || !DT.dominates(ExitingBlock, Latch))
9005 return getCouldNotCompute();
9006
9007 Instruction *Term = ExitingBlock->getTerminator();
9008 if (CondBrInst *BI = dyn_cast<CondBrInst>(Term)) {
9009 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9010 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
9011 "It should have one successor in loop and one exit block!");
9012 // Proceed to the next level to examine the exit condition expression.
9013 return computeExitLimitFromCond(L, BI->getCondition(), ExitIfTrue,
9014 /*ControlsOnlyExit=*/IsOnlyExit,
9015 AllowPredicates);
9016 }
9017
9018 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
9019 // For switch, make sure that there is a single exit from the loop.
9020 BasicBlock *Exit = nullptr;
9021 for (auto *SBB : successors(ExitingBlock))
9022 if (!L->contains(SBB)) {
9023 if (Exit) // Multiple exit successors.
9024 return getCouldNotCompute();
9025 Exit = SBB;
9026 }
9027 assert(Exit && "Exiting block must have at least one exit");
9028 return computeExitLimitFromSingleExitSwitch(
9029 L, SI, Exit, /*ControlsOnlyExit=*/IsOnlyExit);
9030 }
9031
9032 return getCouldNotCompute();
9033}
9034
9036 const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9037 bool AllowPredicates) {
9038 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
9039 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
9040 ControlsOnlyExit, AllowPredicates);
9041}
9042
9043std::optional<ScalarEvolution::ExitLimit>
9044ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
9045 bool ExitIfTrue, bool ControlsOnlyExit,
9046 bool AllowPredicates) {
9047 (void)this->L;
9048 (void)this->ExitIfTrue;
9049 (void)this->AllowPredicates;
9050
9051 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9052 this->AllowPredicates == AllowPredicates &&
9053 "Variance in assumed invariant key components!");
9054 auto Itr = TripCountMap.find({ExitCond, ControlsOnlyExit});
9055 if (Itr == TripCountMap.end())
9056 return std::nullopt;
9057 return Itr->second;
9058}
9059
9060void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
9061 bool ExitIfTrue,
9062 bool ControlsOnlyExit,
9063 bool AllowPredicates,
9064 const ExitLimit &EL) {
9065 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9066 this->AllowPredicates == AllowPredicates &&
9067 "Variance in assumed invariant key components!");
9068
9069 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsOnlyExit}, EL});
9070 assert(InsertResult.second && "Expected successful insertion!");
9071 (void)InsertResult;
9072 (void)ExitIfTrue;
9073}
9074
9075ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
9076 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9077 bool ControlsOnlyExit, bool AllowPredicates) {
9078
9079 if (auto MaybeEL = Cache.find(L, ExitCond, ExitIfTrue, ControlsOnlyExit,
9080 AllowPredicates))
9081 return *MaybeEL;
9082
9083 ExitLimit EL = computeExitLimitFromCondImpl(
9084 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates);
9085 Cache.insert(L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates, EL);
9086 return EL;
9087}
9088
9089ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
9090 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9091 bool ControlsOnlyExit, bool AllowPredicates) {
9092 // Handle BinOp conditions (And, Or).
9093 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
9094 Cache, L, ExitCond, ExitIfTrue, AllowPredicates))
9095 return *LimitFromBinOp;
9096
9097 // With an icmp, it may be feasible to compute an exact backedge-taken count.
9098 // Proceed to the next level to examine the icmp.
9099 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
9100 ExitLimit EL =
9101 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsOnlyExit);
9102 if (EL.hasFullInfo() || !AllowPredicates)
9103 return EL;
9104
9105 // Try again, but use SCEV predicates this time.
9106 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue,
9107 ControlsOnlyExit,
9108 /*AllowPredicates=*/true);
9109 }
9110
9111 // Check for a constant condition. These are normally stripped out by
9112 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
9113 // preserve the CFG and is temporarily leaving constant conditions
9114 // in place.
9115 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
9116 if (ExitIfTrue == !CI->getZExtValue())
9117 // The backedge is always taken.
9118 return getCouldNotCompute();
9119 // The backedge is never taken.
9120 return getZero(CI->getType());
9121 }
9122
9123 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
9124 // with a constant step, we can form an equivalent icmp predicate and figure
9125 // out how many iterations will be taken before we exit.
9126 const WithOverflowInst *WO;
9127 const APInt *C;
9128 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
9129 match(WO->getRHS(), m_APInt(C))) {
9130 ConstantRange NWR =
9132 WO->getNoWrapKind());
9134 APInt NewRHSC, Offset;
9135 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
9136 if (!ExitIfTrue)
9138 auto *LHS = getSCEV(WO->getLHS());
9139 if (Offset != 0)
9141 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
9142 ControlsOnlyExit, AllowPredicates);
9143 if (EL.hasAnyInfo())
9144 return EL;
9145 }
9146
9147 // If it's not an integer or pointer comparison then compute it the hard way.
9148 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9149}
9150
9151std::optional<ScalarEvolution::ExitLimit>
9152ScalarEvolution::computeExitLimitFromCondFromBinOp(ExitLimitCacheTy &Cache,
9153 const Loop *L,
9154 Value *ExitCond,
9155 bool ExitIfTrue,
9156 bool AllowPredicates) {
9157 // Check if the controlling expression for this loop is an And or Or.
9158 Value *Op0, *Op1;
9159 bool IsAnd;
9160 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
9161 IsAnd = true;
9162 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
9163 IsAnd = false;
9164 else
9165 return std::nullopt;
9166
9167 // A sub-condition of a non-trivial binop never solely controls the exit,
9168 // whether we exit always depends on both conditions.
9169 ExitLimit EL0 = computeExitLimitFromCondCached(
9170 Cache, L, Op0, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9171 ExitLimit EL1 = computeExitLimitFromCondCached(
9172 Cache, L, Op1, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9173
9174 // EitherMayExit is true in these two cases:
9175 // br (and Op0 Op1), loop, exit
9176 // br (or Op0 Op1), exit, loop
9177 bool EitherMayExit = IsAnd ^ ExitIfTrue;
9178
9179 const SCEV *BECount = getCouldNotCompute();
9180 const SCEV *ConstantMaxBECount = getCouldNotCompute();
9181 const SCEV *SymbolicMaxBECount = getCouldNotCompute();
9182 if (EitherMayExit) {
9183 bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
9184 // Both conditions must be same for the loop to continue executing.
9185 // Choose the less conservative count.
9186 if (EL0.ExactNotTaken != getCouldNotCompute() &&
9187 EL1.ExactNotTaken != getCouldNotCompute()) {
9188 BECount = getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken,
9189 UseSequentialUMin);
9190 }
9191 if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
9192 ConstantMaxBECount = EL1.ConstantMaxNotTaken;
9193 else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
9194 ConstantMaxBECount = EL0.ConstantMaxNotTaken;
9195 else
9196 ConstantMaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
9197 EL1.ConstantMaxNotTaken);
9198 if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
9199 SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
9200 else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
9201 SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
9202 else
9203 SymbolicMaxBECount = getUMinFromMismatchedTypes(
9204 EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
9205 } else {
9206 // Both conditions must be same at the same time for the loop to exit.
9207 // For now, be conservative.
9208 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
9209 BECount = EL0.ExactNotTaken;
9210 }
9211
9212 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
9213 // to be more aggressive when computing BECount than when computing
9214 // ConstantMaxBECount. In these cases it is possible for EL0.ExactNotTaken
9215 // and
9216 // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
9217 // EL1.ConstantMaxNotTaken to not.
9218 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
9219 !isa<SCEVCouldNotCompute>(BECount))
9220 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
9221 if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
9222 SymbolicMaxBECount =
9223 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
9224 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
9225 {ArrayRef(EL0.Predicates), ArrayRef(EL1.Predicates)});
9226}
9227
9228ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9229 const Loop *L, ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9230 bool AllowPredicates) {
9231 // If the condition was exit on true, convert the condition to exit on false
9232 CmpPredicate Pred;
9233 if (!ExitIfTrue)
9234 Pred = ExitCond->getCmpPredicate();
9235 else
9236 Pred = ExitCond->getInverseCmpPredicate();
9237 const ICmpInst::Predicate OriginalPred = Pred;
9238
9239 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
9240 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
9241
9242 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsOnlyExit,
9243 AllowPredicates);
9244 if (EL.hasAnyInfo())
9245 return EL;
9246
9247 auto *ExhaustiveCount =
9248 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9249
9250 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
9251 return ExhaustiveCount;
9252
9253 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
9254 ExitCond->getOperand(1), L, OriginalPred);
9255}
9256ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9257 const Loop *L, CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS,
9258 bool ControlsOnlyExit, bool AllowPredicates) {
9259
9260 // Try to evaluate any dependencies out of the loop.
9261 LHS = getSCEVAtScope(LHS, L);
9262 RHS = getSCEVAtScope(RHS, L);
9263
9264 // At this point, we would like to compute how many iterations of the
9265 // loop the predicate will return true for these inputs.
9266 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
9267 // If there is a loop-invariant, force it into the RHS.
9268 std::swap(LHS, RHS);
9270 }
9271
9272 bool ControllingFiniteLoop = ControlsOnlyExit && loopHasNoAbnormalExits(L) &&
9274 // Simplify the operands before analyzing them.
9275 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0);
9276
9277 // If we have a comparison of a chrec against a constant, try to use value
9278 // ranges to answer this query.
9279 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
9280 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
9281 if (AddRec->getLoop() == L) {
9282 // Form the constant range.
9283 ConstantRange CompRange =
9284 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
9285
9286 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
9287 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
9288 }
9289
9290 // If this loop must exit based on this condition (or execute undefined
9291 // behaviour), see if we can improve wrap flags. This is essentially
9292 // a must execute style proof.
9293 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
9294 // If we can prove the test sequence produced must repeat the same values
9295 // on self-wrap of the IV, then we can infer that IV doesn't self wrap
9296 // because if it did, we'd have an infinite (undefined) loop.
9297 // TODO: We can peel off any functions which are invertible *in L*. Loop
9298 // invariant terms are effectively constants for our purposes here.
9299 SCEVUse InnerLHS = LHS;
9300 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
9301 InnerLHS = ZExt->getOperand();
9302 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS);
9303 AR && !AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
9304 isKnownToBeAPowerOfTwo(AR->getStepRecurrence(*this), /*OrZero=*/true,
9305 /*OrNegative=*/true)) {
9306 auto Flags = AR->getNoWrapFlags();
9307 Flags = setFlags(Flags, SCEV::FlagNW);
9310 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9311 }
9312
9313 // For a slt/ult condition with a positive step, can we prove nsw/nuw?
9314 // From no-self-wrap, this follows trivially from the fact that every
9315 // (un)signed-wrapped, but not self-wrapped value must be LT than the
9316 // last value before (un)signed wrap. Since we know that last value
9317 // didn't exit, nor will any smaller one.
9319 auto WrapType = Pred == ICmpInst::ICMP_SLT ? SCEV::FlagNSW : SCEV::FlagNUW;
9320 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9321 AR && AR->getLoop() == L && AR->isAffine() &&
9322 !AR->getNoWrapFlags(WrapType) && AR->hasNoSelfWrap() &&
9323 isKnownPositive(AR->getStepRecurrence(*this))) {
9324 auto Flags = AR->getNoWrapFlags();
9325 Flags = setFlags(Flags, WrapType);
9328 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9329 }
9330 }
9331 }
9332
9333 switch (Pred) {
9334 case ICmpInst::ICMP_NE: { // while (X != Y)
9335 // Convert to: while (X-Y != 0)
9336 if (LHS->getType()->isPointerTy()) {
9339 return LHS;
9340 }
9341 if (RHS->getType()->isPointerTy()) {
9344 return RHS;
9345 }
9346 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit,
9347 AllowPredicates);
9348 if (EL.hasAnyInfo())
9349 return EL;
9350 break;
9351 }
9352 case ICmpInst::ICMP_EQ: { // while (X == Y)
9353 // Convert to: while (X-Y == 0)
9354 if (LHS->getType()->isPointerTy()) {
9357 return LHS;
9358 }
9359 if (RHS->getType()->isPointerTy()) {
9362 return RHS;
9363 }
9364 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
9365 if (EL.hasAnyInfo()) return EL;
9366 break;
9367 }
9368 case ICmpInst::ICMP_SLE:
9369 case ICmpInst::ICMP_ULE:
9370 // Since the loop is finite, an invariant RHS cannot include the boundary
9371 // value, otherwise it would loop forever.
9372 if (!Opts.scalar_evolution_finite_loop || !ControllingFiniteLoop ||
9373 !isLoopInvariant(RHS, L)) {
9374 // Otherwise, perform the addition in a wider type, to avoid overflow.
9375 // If the LHS is an addrec with the appropriate nowrap flag, the
9376 // extension will be sunk into it and the exit count can be analyzed.
9377 auto *OldType = dyn_cast<IntegerType>(LHS->getType());
9378 if (!OldType)
9379 break;
9380 // Prefer doubling the bitwidth over adding a single bit to make it more
9381 // likely that we use a legal type.
9382 auto *NewType =
9383 Type::getIntNTy(OldType->getContext(), OldType->getBitWidth() * 2);
9384 if (ICmpInst::isSigned(Pred)) {
9385 LHS = getSignExtendExpr(LHS, NewType);
9386 RHS = getSignExtendExpr(RHS, NewType);
9387 } else {
9388 LHS = getZeroExtendExpr(LHS, NewType);
9389 RHS = getZeroExtendExpr(RHS, NewType);
9390 }
9391 }
9393 [[fallthrough]];
9394 case ICmpInst::ICMP_SLT:
9395 case ICmpInst::ICMP_ULT: { // while (X < Y)
9396 bool IsSigned = ICmpInst::isSigned(Pred);
9397 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, /*Invert=*/false,
9398 ControlsOnlyExit, AllowPredicates);
9399 if (EL.hasAnyInfo())
9400 return EL;
9401 break;
9402 }
9403 case ICmpInst::ICMP_SGE:
9404 case ICmpInst::ICMP_UGE:
9405 // Since the loop is finite, an invariant RHS cannot include the boundary
9406 // value, otherwise it would loop forever.
9407 if (!Opts.scalar_evolution_finite_loop || !ControllingFiniteLoop ||
9408 !isLoopInvariant(RHS, L))
9409 break;
9411 [[fallthrough]];
9412 case ICmpInst::ICMP_SGT:
9413 case ICmpInst::ICMP_UGT: { // while (X > Y)
9414 // "X > Y" is analyzed as the equivalent "~X < ~Y".
9415 bool IsSigned = ICmpInst::isSigned(Pred);
9416 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, /*Invert=*/true,
9417 ControlsOnlyExit, AllowPredicates);
9418 if (EL.hasAnyInfo())
9419 return EL;
9420 break;
9421 }
9422 default:
9423 break;
9424 }
9425
9426 return getCouldNotCompute();
9427}
9428
9429ScalarEvolution::ExitLimit
9430ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
9431 SwitchInst *Switch,
9432 BasicBlock *ExitingBlock,
9433 bool ControlsOnlyExit) {
9434 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
9435
9436 // Give up if the exit is the default dest of a switch.
9437 if (Switch->getDefaultDest() == ExitingBlock)
9438 return getCouldNotCompute();
9439
9440 assert(L->contains(Switch->getDefaultDest()) &&
9441 "Default case must not exit the loop!");
9442 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
9443 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
9444
9445 // while (X != Y) --> while (X-Y != 0)
9446 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit);
9447 if (EL.hasAnyInfo())
9448 return EL;
9449
9450 return getCouldNotCompute();
9451}
9452
9453static ConstantInt *
9455 ScalarEvolution &SE) {
9456 const SCEV *InVal = SE.getConstant(C);
9457 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
9459 "Evaluation of SCEV at constant didn't fold correctly?");
9460 return cast<SCEVConstant>(Val)->getValue();
9461}
9462
9463ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
9464 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
9465 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
9466 if (!RHS)
9467 return getCouldNotCompute();
9468
9469 const BasicBlock *Latch = L->getLoopLatch();
9470 if (!Latch)
9471 return getCouldNotCompute();
9472
9473 const BasicBlock *Predecessor = L->getLoopPredecessor();
9474 if (!Predecessor)
9475 return getCouldNotCompute();
9476
9477 // Return true if V is of the form "LHS `shift_op` <positive constant>".
9478 // Return LHS in OutLHS, shift_op in OutOpCode, and the shift amount in
9479 // OutShiftAmt.
9480 auto MatchPositiveShift = [](Value *V, Value *&OutLHS,
9481 Instruction::BinaryOps &OutOpCode,
9482 unsigned &OutShiftAmt) {
9483 using namespace PatternMatch;
9484
9485 ConstantInt *ShiftAmt;
9486 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9487 OutOpCode = Instruction::LShr;
9488 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9489 OutOpCode = Instruction::AShr;
9490 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9491 OutOpCode = Instruction::Shl;
9492 else
9493 return false;
9494
9495 uint64_t Amt = ShiftAmt->getValue().getLimitedValue();
9496 if (Amt == 0 || Amt >= OutLHS->getType()->getScalarSizeInBits())
9497 return false;
9498 OutShiftAmt = Amt;
9499 return true;
9500 };
9501
9502 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
9503 //
9504 // loop:
9505 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
9506 // %iv.shifted = lshr i32 %iv, <positive constant>
9507 //
9508 // Return true on a successful match. Return the corresponding PHI node (%iv
9509 // above) in PNOut, the opcode of the shift operation in OpCodeOut, and the
9510 // shift amount in ShiftAmtOut.
9511 auto MatchShiftRecurrence = [&](Value *V, PHINode *&PNOut,
9512 Instruction::BinaryOps &OpCodeOut,
9513 unsigned &ShiftAmtOut) {
9514 std::optional<Instruction::BinaryOps> PostShiftOpCode;
9515
9516 {
9518 Value *V;
9519 unsigned Amt;
9520
9521 // If we encounter a shift instruction, "peel off" the shift operation,
9522 // and remember that we did so. Later when we inspect %iv's backedge
9523 // value, we will make sure that the backedge value uses the same
9524 // operation.
9525 //
9526 // Note: the peeled shift operation does not have to be the same
9527 // instruction as the one feeding into the PHI's backedge value. We only
9528 // really care about it being the same *kind* of shift instruction --
9529 // that's all that is required for our later inferences to hold.
9530 if (MatchPositiveShift(LHS, V, OpC, Amt)) {
9531 PostShiftOpCode = OpC;
9532 LHS = V;
9533 }
9534 }
9535
9536 PNOut = dyn_cast<PHINode>(LHS);
9537 if (!PNOut || PNOut->getParent() != L->getHeader())
9538 return false;
9539
9540 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
9541 Value *OpLHS;
9542
9543 return
9544 // The backedge value for the PHI node must be a shift by a positive
9545 // amount
9546 MatchPositiveShift(BEValue, OpLHS, OpCodeOut, ShiftAmtOut) &&
9547
9548 // of the PHI node itself
9549 OpLHS == PNOut &&
9550
9551 // and the kind of shift should be match the kind of shift we peeled
9552 // off, if any.
9553 (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9554 };
9555
9556 PHINode *PN;
9558 unsigned ShiftAmt;
9559 if (!MatchShiftRecurrence(LHS, PN, OpCode, ShiftAmt))
9560 return getCouldNotCompute();
9561
9562 const DataLayout &DL = getDataLayout();
9563
9564 // The key rationale for this optimization is that for some kinds of shift
9565 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
9566 // within a finite number of iterations. If the condition guarding the
9567 // backedge (in the sense that the backedge is taken if the condition is true)
9568 // is false for the value the shift recurrence stabilizes to, then we know
9569 // that the backedge is taken only a finite number of times.
9570
9571 ConstantInt *StableValue = nullptr;
9572 switch (OpCode) {
9573 default:
9574 llvm_unreachable("Impossible case!");
9575
9576 case Instruction::AShr: {
9577 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
9578 // bitwidth(K) iterations.
9579 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
9580 KnownBits Known = computeKnownBits(FirstValue, DL, &AC,
9581 Predecessor->getTerminator(), &DT);
9582 auto *Ty = cast<IntegerType>(RHS->getType());
9583 if (Known.isNonNegative())
9584 StableValue = ConstantInt::get(Ty, 0);
9585 else if (Known.isNegative())
9586 StableValue = ConstantInt::get(Ty, -1, true);
9587 else
9588 return getCouldNotCompute();
9589
9590 break;
9591 }
9592 case Instruction::LShr:
9593 case Instruction::Shl:
9594 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
9595 // stabilize to 0 in at most bitwidth(K) iterations.
9596 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
9597 break;
9598 }
9599
9600 auto *Result =
9601 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
9602 assert(Result->getType()->isIntegerTy(1) &&
9603 "Otherwise cannot be an operand to a branch instruction");
9604
9605 if (Result->isNullValue()) {
9606 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9607 unsigned MaxBTC = BitWidth;
9608
9609 // For right-shift recurrences (lshr/ashr with non-negative start), we can
9610 // compute a tighter max backedge-taken count from the range of the start
9611 // value. After k shifts of ShiftAmt, value = start >> (k * ShiftAmt).
9612 // The value reaches 0 (the stable value) when k * ShiftAmt >=
9613 // activeBits(start), so max BTC = ceil(activeBits(maxStart) / ShiftAmt).
9614 if (OpCode == Instruction::LShr || OpCode == Instruction::AShr) {
9615 Value *StartValue = PN->getIncomingValueForBlock(Predecessor);
9616 const SCEV *StartSCEV = getSCEV(StartValue);
9617 APInt MaxStart = getUnsignedRangeMax(StartSCEV);
9618 if (MaxStart.isStrictlyPositive()) {
9619 unsigned ActiveBits = MaxStart.getActiveBits();
9620 unsigned RangeBTC = divideCeil(ActiveBits, ShiftAmt);
9621 MaxBTC = std::min(MaxBTC, RangeBTC);
9622 }
9623 }
9624
9625 const SCEV *UpperBound =
9627 return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
9628 }
9629
9630 return getCouldNotCompute();
9631}
9632
9633/// Return true if we can constant fold an instruction of the specified type,
9634/// assuming that all operands were constants.
9635static bool canConstantFold(const Instruction *I,
9636 const TargetLibraryInfo *TLI) {
9640 return true;
9641
9642 if (const CallInst *CI = dyn_cast<CallInst>(I))
9643 if (const Function *F = CI->getCalledFunction())
9644 return canConstantFoldCallTo(CI, F, TLI);
9645 return false;
9646}
9647
9648/// Determine whether this instruction can constant evolve within this loop
9649/// assuming its operands can all constant evolve.
9650static bool canConstantEvolve(Instruction *I, const Loop *L,
9651 const TargetLibraryInfo *TLI) {
9652 // An instruction outside of the loop can't be derived from a loop PHI.
9653 if (!L->contains(I)) return false;
9654
9655 if (isa<PHINode>(I)) {
9656 // We don't currently keep track of the control flow needed to evaluate
9657 // PHIs, so we cannot handle PHIs inside of loops.
9658 return L->getHeader() == I->getParent();
9659 }
9660
9661 // If we won't be able to constant fold this expression even if the operands
9662 // are constants, bail early.
9663 return canConstantFold(I, TLI);
9664}
9665
9666/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
9667/// recursing through each instruction operand until reaching a loop header phi.
9668static PHINode *
9669getConstantEvolvingPHIOperands(const AnalysisOptions &Opts,
9670 Instruction *UseInst, const Loop *L,
9672 const TargetLibraryInfo *TLI, unsigned Depth) {
9673 if (Depth > Opts.scalar_evolution_max_constant_evolving_depth)
9674 return nullptr;
9675
9676 // Otherwise, we can evaluate this instruction if all of its operands are
9677 // constant or derived from a PHI node themselves.
9678 PHINode *PHI = nullptr;
9679 for (Value *Op : UseInst->operands()) {
9680 if (isa<Constant>(Op)) continue;
9681
9683 if (!OpInst || !canConstantEvolve(OpInst, L, TLI))
9684 return nullptr;
9685
9686 PHINode *P = dyn_cast<PHINode>(OpInst);
9687 if (!P)
9688 // If this operand is already visited, reuse the prior result.
9689 // We may have P != PHI if this is the deepest point at which the
9690 // inconsistent paths meet.
9691 P = PHIMap.lookup(OpInst);
9692 if (!P) {
9693 // Recurse and memoize the results, whether a phi is found or not.
9694 // This recursive call invalidates pointers into PHIMap.
9695 P = getConstantEvolvingPHIOperands(Opts, OpInst, L, PHIMap, TLI,
9696 Depth + 1);
9697 PHIMap[OpInst] = P;
9698 }
9699 if (!P)
9700 return nullptr; // Not evolving from PHI
9701 if (PHI && PHI != P)
9702 return nullptr; // Evolving from multiple different PHIs.
9703 PHI = P;
9704 }
9705 // This is a expression evolving from a constant PHI!
9706 return PHI;
9707}
9708
9709/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9710/// in the loop that V is derived from. We allow arbitrary operations along the
9711/// way, but the operands of an operation must either be constants or a value
9712/// derived from a constant PHI. If this expression does not fit with these
9713/// constraints, return null.
9714static PHINode *getConstantEvolvingPHI(const AnalysisOptions &Opts, Value *V,
9715 const Loop *L,
9716 const TargetLibraryInfo *TLI) {
9718 if (!I || !canConstantEvolve(I, L, TLI))
9719 return nullptr;
9720
9721 if (PHINode *PN = dyn_cast<PHINode>(I))
9722 return PN;
9723
9724 // Record non-constant instructions contained by the loop.
9726 return getConstantEvolvingPHIOperands(Opts, I, L, PHIMap, TLI, 0);
9727}
9728
9729/// EvaluateExpression - Given an expression that passes the
9730/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9731/// in the loop has the value PHIVal. If we can't fold this expression for some
9732/// reason, return null.
9735 const DataLayout &DL,
9736 const TargetLibraryInfo *TLI) {
9737 // Convenient constant check, but redundant for recursive calls.
9738 if (Constant *C = dyn_cast<Constant>(V)) return C;
9740 if (!I) return nullptr;
9741
9742 if (Constant *C = Vals.lookup(I)) return C;
9743
9744 // An instruction inside the loop depends on a value outside the loop that we
9745 // weren't given a mapping for, or a value such as a call inside the loop.
9746 if (!canConstantEvolve(I, L, TLI))
9747 return nullptr;
9748
9749 // An unmapped PHI can be due to a branch or another loop inside this loop,
9750 // or due to this not being the initial iteration through a loop where we
9751 // couldn't compute the evolution of this particular PHI last time.
9752 if (isa<PHINode>(I)) return nullptr;
9753
9754 std::vector<Constant*> Operands(I->getNumOperands());
9755
9756 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9757 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9758 if (!Operand) {
9759 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9760 if (!Operands[i]) return nullptr;
9761 continue;
9762 }
9763 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9764 Vals[Operand] = C;
9765 if (!C) return nullptr;
9766 Operands[i] = C;
9767 }
9768
9770 /*AllowNonDeterministic=*/false);
9771}
9772
9773
9774// If every incoming value to PN except the one for BB is a specific Constant,
9775// return that, else return nullptr.
9777 Constant *IncomingVal = nullptr;
9778
9779 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9780 if (PN->getIncomingBlock(i) == BB)
9781 continue;
9782
9783 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
9784 if (!CurrentVal)
9785 return nullptr;
9786
9787 if (IncomingVal != CurrentVal) {
9788 if (IncomingVal)
9789 return nullptr;
9790 IncomingVal = CurrentVal;
9791 }
9792 }
9793
9794 return IncomingVal;
9795}
9796
9797/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9798/// in the header of its containing loop, we know the loop executes a
9799/// constant number of times, and the PHI node is just a recurrence
9800/// involving constants, fold it.
9801Constant *
9802ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9803 const APInt &BEs,
9804 const Loop *L) {
9805 auto [I, Inserted] = ConstantEvolutionLoopExitValue.try_emplace(PN);
9806 if (!Inserted)
9807 return I->second;
9808
9809 if (BEs.ugt(Opts.scalar_evolution_max_iterations))
9810 return nullptr; // Not going to evaluate it.
9811
9812 Constant *&RetVal = I->second;
9813
9814 DenseMap<Instruction *, Constant *> CurrentIterVals;
9815 BasicBlock *Header = L->getHeader();
9816 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9817
9818 BasicBlock *Latch = L->getLoopLatch();
9819 if (!Latch)
9820 return nullptr;
9821
9822 for (PHINode &PHI : Header->phis()) {
9823 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9824 CurrentIterVals[&PHI] = StartCST;
9825 }
9826 if (!CurrentIterVals.count(PN))
9827 return RetVal = nullptr;
9828
9829 Value *BEValue = PN->getIncomingValueForBlock(Latch);
9830
9831 // Execute the loop symbolically to determine the exit value.
9832 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
9833 "BEs is <= -scalar-evolution-max-iterations which is an 'unsigned'!");
9834
9835 unsigned NumIterations = BEs.getZExtValue(); // must be in range
9836 unsigned IterationNum = 0;
9837 const DataLayout &DL = getDataLayout();
9838 for (; ; ++IterationNum) {
9839 if (IterationNum == NumIterations)
9840 return RetVal = CurrentIterVals[PN]; // Got exit value!
9841
9842 // Compute the value of the PHIs for the next iteration.
9843 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9844 DenseMap<Instruction *, Constant *> NextIterVals;
9845 Constant *NextPHI =
9846 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9847 if (!NextPHI)
9848 return nullptr; // Couldn't evaluate!
9849 NextIterVals[PN] = NextPHI;
9850
9851 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9852
9853 // Also evaluate the other PHI nodes. However, we don't get to stop if we
9854 // cease to be able to evaluate one of them or if they stop evolving,
9855 // because that doesn't necessarily prevent us from computing PN.
9857 for (const auto &I : CurrentIterVals) {
9858 PHINode *PHI = dyn_cast<PHINode>(I.first);
9859 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
9860 PHIsToCompute.emplace_back(PHI, I.second);
9861 }
9862 // We use two distinct loops because EvaluateExpression may invalidate any
9863 // iterators into CurrentIterVals.
9864 for (const auto &I : PHIsToCompute) {
9865 PHINode *PHI = I.first;
9866 Constant *&NextPHI = NextIterVals[PHI];
9867 if (!NextPHI) { // Not already computed.
9868 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9869 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9870 }
9871 if (NextPHI != I.second)
9872 StoppedEvolving = false;
9873 }
9874
9875 // If all entries in CurrentIterVals == NextIterVals then we can stop
9876 // iterating, the loop can't continue to change.
9877 if (StoppedEvolving)
9878 return RetVal = CurrentIterVals[PN];
9879
9880 CurrentIterVals.swap(NextIterVals);
9881 }
9882}
9883
9884const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
9885 Value *Cond,
9886 bool ExitWhen) {
9887 PHINode *PN = getConstantEvolvingPHI(Opts, Cond, L, &TLI);
9888 if (!PN) return getCouldNotCompute();
9889
9890 // If the loop is canonicalized, the PHI will have exactly two entries.
9891 // That's the only form we support here.
9892 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
9893
9894 DenseMap<Instruction *, Constant *> CurrentIterVals;
9895 BasicBlock *Header = L->getHeader();
9896 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9897
9898 BasicBlock *Latch = L->getLoopLatch();
9899 assert(Latch && "Should follow from NumIncomingValues == 2!");
9900
9901 for (PHINode &PHI : Header->phis()) {
9902 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9903 CurrentIterVals[&PHI] = StartCST;
9904 }
9905 if (!CurrentIterVals.count(PN))
9906 return getCouldNotCompute();
9907
9908 // Okay, we find a PHI node that defines the trip count of this loop. Execute
9909 // the loop symbolically to determine when the condition gets a value of
9910 // "ExitWhen".
9911 unsigned MaxIterations =
9912 Opts.scalar_evolution_max_iterations; // Limit analysis.
9913 const DataLayout &DL = getDataLayout();
9914 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
9915 auto *CondVal = dyn_cast_or_null<ConstantInt>(
9916 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
9917
9918 // Couldn't symbolically evaluate.
9919 if (!CondVal) return getCouldNotCompute();
9920
9921 if (CondVal->getValue() == uint64_t(ExitWhen)) {
9922 ++NumBruteForceTripCountsComputed;
9923 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
9924 }
9925
9926 // Update all the PHI nodes for the next iteration.
9927 DenseMap<Instruction *, Constant *> NextIterVals;
9928
9929 // Create a list of which PHIs we need to compute. We want to do this before
9930 // calling EvaluateExpression on them because that may invalidate iterators
9931 // into CurrentIterVals.
9932 SmallVector<PHINode *, 8> PHIsToCompute;
9933 for (const auto &I : CurrentIterVals) {
9934 PHINode *PHI = dyn_cast<PHINode>(I.first);
9935 if (!PHI || PHI->getParent() != Header) continue;
9936 PHIsToCompute.push_back(PHI);
9937 }
9938 for (PHINode *PHI : PHIsToCompute) {
9939 Constant *&NextPHI = NextIterVals[PHI];
9940 if (NextPHI) continue; // Already computed!
9941
9942 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9943 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9944 }
9945 CurrentIterVals.swap(NextIterVals);
9946 }
9947
9948 // Too many iterations were needed to evaluate.
9949 return getCouldNotCompute();
9950}
9951
9953 if (isa<SCEVConstant>(V))
9954 return V;
9955
9956 auto &Values = ValuesAtScopes[V];
9957 // Check to see if we've folded this expression at this loop before.
9958 for (auto &LS : Values)
9959 if (LS.first == L)
9960 return LS.second ? LS.second : SCEVUse(V);
9961
9962 Values.emplace_back(L, nullptr);
9963
9964 // Otherwise compute it.
9965 SCEVUse C = computeSCEVAtScope(V, L);
9966 for (auto &LS : reverse(ValuesAtScopes[V]))
9967 if (LS.first == L) {
9968 LS.second = C;
9969 // Record the dependency under the bare expression: invalidation walks
9970 // expressions, and any use flags on C do not change which expression
9971 // this is the value at scope of.
9972 if (!isa<SCEVConstant>(C))
9973 ValuesAtScopesUsers[C.getPointer()].push_back({L, V});
9974 break;
9975 }
9976 return C;
9977}
9978
9980 const BasicBlock *ExitingBlock) {
9981 SCEVUse ExitValue = getSCEVAtScope(V, L->getParentLoop());
9982 if (!isLoopInvariant(ExitValue, L)) {
9983 // If we failed to evaluate it in the outer scope, try to evaluate an
9984 // addrec for the specific exit.
9985 // TODO: Generalize this to other expressions.
9986 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
9987 if (!isa<SCEVCouldNotCompute>(ExitCount))
9988 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V))
9989 if (AddRec->getLoop() == L)
9990 ExitValue = AddRec->evaluateAtIteration(ExitCount, *this);
9991 }
9992 return ExitValue;
9993}
9994
9995/// This builds up a Constant using the ConstantExpr interface. That way, we
9996/// will return Constants for objects which aren't represented by a
9997/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
9998/// Returns NULL if the SCEV isn't representable as a Constant.
10000 switch (V->getSCEVType()) {
10001 case scCouldNotCompute:
10002 case scAddRecExpr:
10003 case scVScale:
10004 return nullptr;
10005 case scConstant:
10006 return cast<SCEVConstant>(V)->getValue();
10007 case scUnknown:
10009 case scPtrToAddr: {
10011 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
10012 return ConstantExpr::getPtrToAddr(CastOp, P2I->getType());
10013
10014 return nullptr;
10015 }
10016 case scTruncate: {
10018 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
10019 return ConstantExpr::getTrunc(CastOp, ST->getType());
10020 return nullptr;
10021 }
10022 case scAddExpr: {
10023 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
10024 Constant *C = nullptr;
10025 for (const SCEV *Op : SA->operands()) {
10027 if (!OpC)
10028 return nullptr;
10029 if (!C) {
10030 C = OpC;
10031 continue;
10032 }
10033 assert(!C->getType()->isPointerTy() &&
10034 "Can only have one pointer, and it must be last");
10035 if (OpC->getType()->isPointerTy()) {
10036 // The offsets have been converted to bytes. We can add bytes using
10037 // an i8 GEP.
10038 C = ConstantExpr::getPtrAdd(OpC, C);
10039 } else {
10040 C = ConstantExpr::getAdd(C, OpC);
10041 }
10042 }
10043 return C;
10044 }
10045 case scMulExpr:
10046 case scSignExtend:
10047 case scZeroExtend:
10048 case scUDivExpr:
10049 case scSMaxExpr:
10050 case scUMaxExpr:
10051 case scSMinExpr:
10052 case scUMinExpr:
10054 return nullptr;
10055 }
10056 llvm_unreachable("Unknown SCEV kind!");
10057}
10058
10059const SCEV *ScalarEvolution::getWithOperands(const SCEV *S,
10060 SmallVectorImpl<SCEVUse> &NewOps) {
10061 switch (S->getSCEVType()) {
10062 case scTruncate:
10063 case scZeroExtend:
10064 case scSignExtend:
10065 case scPtrToAddr:
10066 return getCastExpr(S->getSCEVType(), NewOps[0], S->getType());
10067 case scAddRecExpr: {
10068 auto *AddRec = cast<SCEVAddRecExpr>(S);
10069 return getAddRecExpr(NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags());
10070 }
10071 case scAddExpr:
10072 return getAddExpr(NewOps, cast<SCEVAddExpr>(S)->getNoWrapFlags());
10073 case scMulExpr:
10074 return getMulExpr(NewOps, cast<SCEVMulExpr>(S)->getNoWrapFlags());
10075 case scUDivExpr:
10076 return getUDivExpr(NewOps[0], NewOps[1]);
10077 case scUMaxExpr:
10078 case scSMaxExpr:
10079 case scUMinExpr:
10080 case scSMinExpr:
10081 return getMinMaxExpr(S->getSCEVType(), NewOps);
10083 return getSequentialMinMaxExpr(S->getSCEVType(), NewOps);
10084 case scConstant:
10085 case scVScale:
10086 case scUnknown:
10087 return S;
10088 case scCouldNotCompute:
10089 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10090 }
10091 llvm_unreachable("Unknown SCEV kind!");
10092}
10093
10094SCEVUse ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
10095 switch (V->getSCEVType()) {
10096 case scConstant:
10097 case scVScale:
10098 return V;
10099 case scAddRecExpr: {
10100 // If this is a loop recurrence for a loop that does not contain L, then we
10101 // are dealing with the final value computed by the loop.
10102 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(V);
10103 // First, attempt to evaluate each operand.
10104 // Avoid performing the look-up in the common case where the specified
10105 // expression has no loop-variant portions.
10106 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
10107 SCEVUse OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
10108 if (OpAtScope == AddRec->getOperand(i))
10109 continue;
10110
10111 // Okay, at least one of these operands is loop variant but might be
10112 // foldable. Build a new instance of the folded commutative expression.
10114 NewOps.reserve(AddRec->getNumOperands());
10115 append_range(NewOps, AddRec->operands().take_front(i));
10116 NewOps.push_back(OpAtScope);
10117 for (++i; i != e; ++i)
10118 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
10119
10120 const SCEV *FoldedRec = getAddRecExpr(
10121 NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags(SCEV::FlagNW));
10122 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
10123 // The addrec may be folded to a nonrecurrence, for example, if the
10124 // induction variable is multiplied by zero after constant folding. Go
10125 // ahead and return the folded value.
10126 if (!AddRec)
10127 return FoldedRec;
10128 break;
10129 }
10130
10131 // If the scope is outside the addrec's loop, evaluate it by using the
10132 // loop exit value of the addrec.
10133 if (!AddRec->getLoop()->contains(L)) {
10134 SCEVUse ExitValue = AddRec->getExitValue(*this);
10135 if (isa<SCEVCouldNotCompute>(ExitValue))
10136 return AddRec;
10137 return ExitValue;
10138 }
10139
10140 return AddRec;
10141 }
10142 case scTruncate:
10143 case scZeroExtend:
10144 case scSignExtend:
10145 case scPtrToAddr:
10146 case scAddExpr:
10147 case scMulExpr:
10148 case scUDivExpr:
10149 case scUMaxExpr:
10150 case scSMaxExpr:
10151 case scUMinExpr:
10152 case scSMinExpr:
10153 case scSequentialUMinExpr: {
10154 ArrayRef<SCEVUse> Ops = V->operands();
10155 // Avoid performing the look-up in the common case where the specified
10156 // expression has no loop-variant portions.
10157 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
10158 SCEVUse OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10159 if (OpAtScope != Ops[i].getPointer()) {
10160 // Okay, at least one of these operands is loop variant but might be
10161 // foldable. Build a new instance of the folded commutative expression.
10163 NewOps.reserve(Ops.size());
10164 append_range(NewOps, Ops.take_front(i));
10165 NewOps.push_back(OpAtScope);
10166
10167 for (++i; i != e; ++i) {
10168 OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10169 NewOps.push_back(OpAtScope);
10170 }
10171
10172 return getWithOperands(V, NewOps);
10173 }
10174 }
10175 // If we got here, all operands are loop invariant.
10176 return V;
10177 }
10178 case scUnknown: {
10179 // If this instruction is evolved from a constant-evolving PHI, compute the
10180 // exit value from the loop without using SCEVs.
10181 const SCEVUnknown *SU = cast<SCEVUnknown>(V);
10183 if (!I)
10184 return V; // This is some other type of SCEVUnknown, just return it.
10185
10186 if (PHINode *PN = dyn_cast<PHINode>(I)) {
10187 const Loop *CurrLoop = this->LI[I->getParent()];
10188 // Looking for loop exit value.
10189 if (CurrLoop && CurrLoop->getParentLoop() == L &&
10190 PN->getParent() == CurrLoop->getHeader()) {
10191 // Okay, there is no closed form solution for the PHI node. Check
10192 // to see if the loop that contains it has a known backedge-taken
10193 // count. If so, we may be able to force computation of the exit
10194 // value.
10195 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
10196 // This trivial case can show up in some degenerate cases where
10197 // the incoming IR has not yet been fully simplified.
10198 if (BackedgeTakenCount->isZero()) {
10199 Value *InitValue = nullptr;
10200 bool MultipleInitValues = false;
10201 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
10202 if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
10203 if (!InitValue)
10204 InitValue = PN->getIncomingValue(i);
10205 else if (InitValue != PN->getIncomingValue(i)) {
10206 MultipleInitValues = true;
10207 break;
10208 }
10209 }
10210 }
10211 if (!MultipleInitValues && InitValue)
10212 return getSCEV(InitValue);
10213 }
10214 // Do we have a loop invariant value flowing around the backedge
10215 // for a loop which must execute the backedge?
10216 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
10217 isKnownNonZero(BackedgeTakenCount) &&
10218 PN->getNumIncomingValues() == 2) {
10219
10220 unsigned InLoopPred =
10221 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
10222 Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
10223 if (CurrLoop->isLoopInvariant(BackedgeVal))
10224 return getSCEV(BackedgeVal);
10225 }
10226 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
10227 // Okay, we know how many times the containing loop executes. If
10228 // this is a constant evolving PHI node, get the final value at
10229 // the specified iteration number.
10230 Constant *RV =
10231 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
10232 if (RV)
10233 return getSCEV(RV);
10234 }
10235 }
10236 }
10237
10238 // Okay, this is an expression that we cannot symbolically evaluate
10239 // into a SCEV. Check to see if it's possible to symbolically evaluate
10240 // the arguments into constants, and if so, try to constant propagate the
10241 // result. This is particularly useful for computing loop exit values.
10242 if (!canConstantFold(I, &TLI))
10243 return V; // This is some other type of SCEVUnknown, just return it.
10244
10245 SmallVector<Constant *, 4> Operands;
10246 Operands.reserve(I->getNumOperands());
10247 bool MadeImprovement = false;
10248 for (Value *Op : I->operands()) {
10249 if (Constant *C = dyn_cast<Constant>(Op)) {
10250 Operands.push_back(C);
10251 continue;
10252 }
10253
10254 // If any of the operands is non-constant and if they are
10255 // non-integer and non-pointer, don't even try to analyze them
10256 // with scev techniques.
10257 if (!isSCEVable(Op->getType()))
10258 return V;
10259
10260 const SCEV *OrigV = getSCEV(Op);
10261 const SCEV *OpV = getSCEVAtScope(OrigV, L);
10262 MadeImprovement |= OrigV != OpV;
10263
10265 if (!C)
10266 return V;
10267 assert(C->getType() == Op->getType() && "Type mismatch");
10268 Operands.push_back(C);
10269 }
10270
10271 // Check to see if getSCEVAtScope actually made an improvement.
10272 if (!MadeImprovement)
10273 return V; // This is some other type of SCEVUnknown, just return it.
10274
10275 Constant *C = nullptr;
10276 const DataLayout &DL = getDataLayout();
10277 C = ConstantFoldInstOperands(I, Operands, DL, &TLI,
10278 /*AllowNonDeterministic=*/false);
10279 if (!C)
10280 return V;
10281 return getSCEV(C);
10282 }
10283 case scCouldNotCompute:
10284 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10285 }
10286 llvm_unreachable("Unknown SCEV type!");
10287}
10288
10290 return getSCEVAtScope(getSCEV(V), L);
10291}
10292
10293const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
10295 return stripInjectiveFunctions(ZExt->getOperand());
10297 return stripInjectiveFunctions(SExt->getOperand());
10298 return S;
10299}
10300
10301/// Finds the minimum unsigned root of the following equation:
10302///
10303/// A * X = B (mod N)
10304///
10305/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
10306/// A and B isn't important.
10307///
10308/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
10309static const SCEV *
10312 ScalarEvolution &SE, const Loop *L) {
10313 uint32_t BW = A.getBitWidth();
10314 assert(BW == SE.getTypeSizeInBits(B->getType()));
10315 assert(A != 0 && "A must be non-zero.");
10316
10317 // 1. D = gcd(A, N)
10318 //
10319 // The gcd of A and N may have only one prime factor: 2. The number of
10320 // trailing zeros in A is its multiplicity
10321 uint32_t Mult2 = A.countr_zero();
10322 // D = 2^Mult2
10323
10324 // 2. Check if B is divisible by D.
10325 //
10326 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
10327 // is not less than multiplicity of this prime factor for D.
10328 unsigned MinTZ = SE.getMinTrailingZeros(B);
10329 // Try again with the terminator of the loop predecessor for context-specific
10330 // result, if MinTZ s too small.
10331 if (MinTZ < Mult2 && L->getLoopPredecessor())
10332 MinTZ = SE.getMinTrailingZeros(B, L->getLoopPredecessor()->getTerminator());
10333 if (MinTZ < Mult2) {
10334 // Check if we can prove there's no remainder using URem.
10335 const SCEV *URem =
10336 SE.getURemExpr(B, SE.getConstant(APInt::getOneBitSet(BW, Mult2)));
10337 const SCEV *Zero = SE.getZero(B->getType());
10338 if (!SE.isKnownPredicate(CmpInst::ICMP_EQ, URem, Zero)) {
10339 // Try to add a predicate ensuring B is a multiple of 1 << Mult2.
10340 if (!Predicates)
10341 return SE.getCouldNotCompute();
10342
10343 // Avoid adding a predicate that is known to be false.
10344 if (SE.isKnownPredicate(CmpInst::ICMP_NE, URem, Zero))
10345 return SE.getCouldNotCompute();
10346 Predicates->push_back(SE.getEqualPredicate(URem, Zero));
10347 }
10348 }
10349
10350 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
10351 // modulo (N / D).
10352 //
10353 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
10354 // (N / D) in general. The inverse itself always fits into BW bits, though,
10355 // so we immediately truncate it.
10356 APInt AD = A.lshr(Mult2).trunc(BW - Mult2); // AD = A / D
10357 APInt I = AD.multiplicativeInverse().zext(BW);
10358
10359 // 4. Compute the minimum unsigned root of the equation:
10360 // I * (B / D) mod (N / D)
10361 // To simplify the computation, we factor out the divide by D:
10362 // (I * B mod N) / D
10363 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
10364 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
10365}
10366
10367/// For a given quadratic addrec, generate coefficients of the corresponding
10368/// quadratic equation, multiplied by a common value to ensure that they are
10369/// integers.
10370/// The returned value is a tuple { A, B, C, M, BitWidth }, where
10371/// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
10372/// were multiplied by, and BitWidth is the bit width of the original addrec
10373/// coefficients.
10374/// This function returns std::nullopt if the addrec coefficients are not
10375/// compile- time constants.
10376static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
10378 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
10379 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
10380 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
10381 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
10382 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
10383 << *AddRec << '\n');
10384
10385 // We currently can only solve this if the coefficients are constants.
10386 if (!LC || !MC || !NC) {
10387 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
10388 return std::nullopt;
10389 }
10390
10391 APInt L = LC->getAPInt();
10392 APInt M = MC->getAPInt();
10393 APInt N = NC->getAPInt();
10394 assert(!N.isZero() && "This is not a quadratic addrec");
10395
10396 unsigned BitWidth = LC->getAPInt().getBitWidth();
10397 unsigned NewWidth = BitWidth + 1;
10398 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
10399 << BitWidth << '\n');
10400 // The sign-extension (as opposed to a zero-extension) here matches the
10401 // extension used in SolveQuadraticEquationWrap (with the same motivation).
10402 N = N.sext(NewWidth);
10403 M = M.sext(NewWidth);
10404 L = L.sext(NewWidth);
10405
10406 // The increments are M, M+N, M+2N, ..., so the accumulated values are
10407 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
10408 // L+M, L+2M+N, L+3M+3N, ...
10409 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
10410 //
10411 // The equation Acc = 0 is then
10412 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
10413 // In a quadratic form it becomes:
10414 // N n^2 + (2M-N) n + 2L = 0.
10415
10416 APInt A = N;
10417 APInt B = 2 * M - A;
10418 APInt C = 2 * L;
10419 APInt T = APInt(NewWidth, 2);
10420 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
10421 << "x + " << C << ", coeff bw: " << NewWidth
10422 << ", multiplied by " << T << '\n');
10423 return std::make_tuple(A, B, C, T, BitWidth);
10424}
10425
10426/// Helper function to compare optional APInts:
10427/// (a) if X and Y both exist, return min(X, Y),
10428/// (b) if neither X nor Y exist, return std::nullopt,
10429/// (c) if exactly one of X and Y exists, return that value.
10430static std::optional<APInt> MinOptional(std::optional<APInt> X,
10431 std::optional<APInt> Y) {
10432 if (X && Y) {
10433 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
10434 APInt XW = X->sext(W);
10435 APInt YW = Y->sext(W);
10436 return XW.slt(YW) ? *X : *Y;
10437 }
10438 if (!X && !Y)
10439 return std::nullopt;
10440 return X ? *X : *Y;
10441}
10442
10443/// Helper function to truncate an optional APInt to a given BitWidth.
10444/// When solving addrec-related equations, it is preferable to return a value
10445/// that has the same bit width as the original addrec's coefficients. If the
10446/// solution fits in the original bit width, truncate it (except for i1).
10447/// Returning a value of a different bit width may inhibit some optimizations.
10448///
10449/// In general, a solution to a quadratic equation generated from an addrec
10450/// may require BW+1 bits, where BW is the bit width of the addrec's
10451/// coefficients. The reason is that the coefficients of the quadratic
10452/// equation are BW+1 bits wide (to avoid truncation when converting from
10453/// the addrec to the equation).
10454static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
10455 unsigned BitWidth) {
10456 if (!X)
10457 return std::nullopt;
10458 unsigned W = X->getBitWidth();
10460 return X->trunc(BitWidth);
10461 return X;
10462}
10463
10464/// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
10465/// iterations. The values L, M, N are assumed to be signed, and they
10466/// should all have the same bit widths.
10467/// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
10468/// where BW is the bit width of the addrec's coefficients.
10469/// If the calculated value is a BW-bit integer (for BW > 1), it will be
10470/// returned as such, otherwise the bit width of the returned value may
10471/// be greater than BW.
10472///
10473/// This function returns std::nullopt if
10474/// (a) the addrec coefficients are not constant, or
10475/// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
10476/// like x^2 = 5, no integer solutions exist, in other cases an integer
10477/// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
10478static std::optional<APInt>
10480 APInt A, B, C, M;
10481 unsigned BitWidth;
10482 auto T = GetQuadraticEquation(AddRec);
10483 if (!T)
10484 return std::nullopt;
10485
10486 std::tie(A, B, C, M, BitWidth) = *T;
10487 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
10488 std::optional<APInt> X =
10490 if (!X)
10491 return std::nullopt;
10492
10493 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
10495 if (!V->isZero())
10496 return std::nullopt;
10497
10498 return TruncIfPossible(X, BitWidth);
10499}
10500
10501/// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
10502/// iterations. The values M, N are assumed to be signed, and they
10503/// should all have the same bit widths.
10504/// Find the least n such that c(n) does not belong to the given range,
10505/// while c(n-1) does.
10506///
10507/// This function returns std::nullopt if
10508/// (a) the addrec coefficients are not constant, or
10509/// (b) SolveQuadraticEquationWrap was unable to find a solution for the
10510/// bounds of the range.
10511static std::optional<APInt>
10513 const ConstantRange &Range, ScalarEvolution &SE) {
10514 assert(AddRec->getOperand(0)->isZero() &&
10515 "Starting value of addrec should be 0");
10516 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
10517 << Range << ", addrec " << *AddRec << '\n');
10518 // This case is handled in getNumIterationsInRange. Here we can assume that
10519 // we start in the range.
10520 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
10521 "Addrec's initial value should be in range");
10522
10523 APInt A, B, C, M;
10524 unsigned BitWidth;
10525 auto T = GetQuadraticEquation(AddRec);
10526 if (!T)
10527 return std::nullopt;
10528
10529 // Be careful about the return value: there can be two reasons for not
10530 // returning an actual number. First, if no solutions to the equations
10531 // were found, and second, if the solutions don't leave the given range.
10532 // The first case means that the actual solution is "unknown", the second
10533 // means that it's known, but not valid. If the solution is unknown, we
10534 // cannot make any conclusions.
10535 // Return a pair: the optional solution and a flag indicating if the
10536 // solution was found.
10537 auto SolveForBoundary =
10538 [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
10539 // Solve for signed overflow and unsigned overflow, pick the lower
10540 // solution.
10541 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
10542 << Bound << " (before multiplying by " << M << ")\n");
10543 Bound *= M; // The quadratic equation multiplier.
10544
10545 std::optional<APInt> SO;
10546 if (BitWidth > 1) {
10547 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10548 "signed overflow\n");
10550 }
10551 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10552 "unsigned overflow\n");
10553 std::optional<APInt> UO =
10555
10556 auto LeavesRange = [&] (const APInt &X) {
10557 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
10559 if (Range.contains(V0->getValue()))
10560 return false;
10561 // X should be at least 1, so X-1 is non-negative.
10562 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
10564 if (Range.contains(V1->getValue()))
10565 return true;
10566 return false;
10567 };
10568
10569 // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
10570 // can be a solution, but the function failed to find it. We cannot treat it
10571 // as "no solution".
10572 if (!SO || !UO)
10573 return {std::nullopt, false};
10574
10575 // Check the smaller value first to see if it leaves the range.
10576 // At this point, both SO and UO must have values.
10577 std::optional<APInt> Min = MinOptional(SO, UO);
10578 if (LeavesRange(*Min))
10579 return { Min, true };
10580 std::optional<APInt> Max = Min == SO ? UO : SO;
10581 if (LeavesRange(*Max))
10582 return { Max, true };
10583
10584 // Solutions were found, but were eliminated, hence the "true".
10585 return {std::nullopt, true};
10586 };
10587
10588 std::tie(A, B, C, M, BitWidth) = *T;
10589 // Lower bound is inclusive, subtract 1 to represent the exiting value.
10590 APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
10591 APInt Upper = Range.getUpper().sext(A.getBitWidth());
10592 auto SL = SolveForBoundary(Lower);
10593 auto SU = SolveForBoundary(Upper);
10594 // If any of the solutions was unknown, no meaninigful conclusions can
10595 // be made.
10596 if (!SL.second || !SU.second)
10597 return std::nullopt;
10598
10599 // Claim: The correct solution is not some value between Min and Max.
10600 //
10601 // Justification: Assuming that Min and Max are different values, one of
10602 // them is when the first signed overflow happens, the other is when the
10603 // first unsigned overflow happens. Crossing the range boundary is only
10604 // possible via an overflow (treating 0 as a special case of it, modeling
10605 // an overflow as crossing k*2^W for some k).
10606 //
10607 // The interesting case here is when Min was eliminated as an invalid
10608 // solution, but Max was not. The argument is that if there was another
10609 // overflow between Min and Max, it would also have been eliminated if
10610 // it was considered.
10611 //
10612 // For a given boundary, it is possible to have two overflows of the same
10613 // type (signed/unsigned) without having the other type in between: this
10614 // can happen when the vertex of the parabola is between the iterations
10615 // corresponding to the overflows. This is only possible when the two
10616 // overflows cross k*2^W for the same k. In such case, if the second one
10617 // left the range (and was the first one to do so), the first overflow
10618 // would have to enter the range, which would mean that either we had left
10619 // the range before or that we started outside of it. Both of these cases
10620 // are contradictions.
10621 //
10622 // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
10623 // solution is not some value between the Max for this boundary and the
10624 // Min of the other boundary.
10625 //
10626 // Justification: Assume that we had such Max_A and Min_B corresponding
10627 // to range boundaries A and B and such that Max_A < Min_B. If there was
10628 // a solution between Max_A and Min_B, it would have to be caused by an
10629 // overflow corresponding to either A or B. It cannot correspond to B,
10630 // since Min_B is the first occurrence of such an overflow. If it
10631 // corresponded to A, it would have to be either a signed or an unsigned
10632 // overflow that is larger than both eliminated overflows for A. But
10633 // between the eliminated overflows and this overflow, the values would
10634 // cover the entire value space, thus crossing the other boundary, which
10635 // is a contradiction.
10636
10637 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
10638}
10639
10640ScalarEvolution::ExitLimit ScalarEvolution::howFarToZero(const SCEV *V,
10641 const Loop *L,
10642 bool ControlsOnlyExit,
10643 bool AllowPredicates) {
10644
10645 // This is only used for loops with a "x != y" exit test. The exit condition
10646 // is now expressed as a single expression, V = x-y. So the exit test is
10647 // effectively V != 0. We know and take advantage of the fact that this
10648 // expression only being used in a comparison by zero context.
10649
10651 // If the value is a constant
10652 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10653 // If the value is already zero, the branch will execute zero times.
10654 if (C->getValue()->isZero()) return C;
10655 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10656 }
10657
10658 const SCEVAddRecExpr *AddRec =
10659 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
10660
10661 if (!AddRec && AllowPredicates)
10662 // Try to make this an AddRec using runtime tests, in the first X
10663 // iterations of this loop, where X is the SCEV expression found by the
10664 // algorithm below.
10665 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
10666
10667 if (!AddRec || AddRec->getLoop() != L)
10668 return getCouldNotCompute();
10669
10670 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
10671 // the quadratic equation to solve it.
10672 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
10673 // We can only use this value if the chrec ends up with an exact zero
10674 // value at this index. When solving for "X*X != 5", for example, we
10675 // should not accept a root of 2.
10676 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
10677 const auto *R = cast<SCEVConstant>(getConstant(*S));
10678 return ExitLimit(R, R, R, false, Predicates);
10679 }
10680 return getCouldNotCompute();
10681 }
10682
10683 // Otherwise we can only handle this if it is affine.
10684 if (!AddRec->isAffine())
10685 return getCouldNotCompute();
10686
10687 // If this is an affine expression, the execution count of this branch is
10688 // the minimum unsigned root of the following equation:
10689 //
10690 // Start + Step*N = 0 (mod 2^BW)
10691 //
10692 // equivalent to:
10693 //
10694 // Step*N = -Start (mod 2^BW)
10695 //
10696 // where BW is the common bit width of Start and Step.
10697
10698 // Get the initial value for the loop.
10699 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
10700 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
10701
10702 if (!isLoopInvariant(Step, L))
10703 return getCouldNotCompute();
10704
10705 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
10706 // Specialize step for this loop so we get context sensitive facts below.
10707 const SCEV *StepWLG = applyLoopGuards(Step, Guards);
10708
10709 // For positive steps (counting up until unsigned overflow):
10710 // N = -Start/Step (as unsigned)
10711 // For negative steps (counting down to zero):
10712 // N = Start/-Step
10713 // First compute the unsigned distance from zero in the direction of Step.
10714 bool CountDown = isKnownNegative(StepWLG);
10715 if (!CountDown && !isKnownNonNegative(StepWLG))
10716 return getCouldNotCompute();
10717
10718 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
10719 // Handle unitary steps, which cannot wraparound.
10720 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10721 // N = Distance (as unsigned)
10722
10723 if (match(Step, m_CombineOr(m_scev_One(), m_scev_AllOnes()))) {
10724 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, Guards));
10725 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
10726
10727 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10728 // we end up with a loop whose backedge-taken count is n - 1. Detect this
10729 // case, and see if we can improve the bound.
10730 //
10731 // Explicitly handling this here is necessary because getUnsignedRange
10732 // isn't context-sensitive; it doesn't know that we only care about the
10733 // range inside the loop.
10734 const SCEV *Zero = getZero(Distance->getType());
10735 const SCEV *One = getOne(Distance->getType());
10736 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
10737 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
10738 // If Distance + 1 doesn't overflow, we can compute the maximum distance
10739 // as "unsigned_max(Distance + 1) - 1". Also apply the loop guards to
10740 // Distance + 1; the range of Distance itself may be a wrapped set even
10741 // when the guards bound Distance + 1 tightly.
10742 APInt Max = APIntOps::umin(
10743 getUnsignedRangeMax(applyLoopGuards(DistancePlusOne, Guards)),
10744 getUnsignedRangeMax(DistancePlusOne));
10745 MaxBECount = APIntOps::umin(MaxBECount, Max - 1);
10746 }
10747 return ExitLimit(Distance, getConstant(MaxBECount), Distance, false,
10748 Predicates);
10749 }
10750
10751 // If the condition controls loop exit (the loop exits only if the expression
10752 // is true) and the addition is no-wrap we can use unsigned divide to
10753 // compute the backedge count. In this case, the step may not divide the
10754 // distance, but we don't care because if the condition is "missed" the loop
10755 // will have undefined behavior due to wrapping.
10756 if (ControlsOnlyExit && AddRec->hasNoSelfWrap() &&
10757 loopHasNoAbnormalExits(AddRec->getLoop())) {
10758
10759 // If the stride is zero and the start is non-zero, the loop must be
10760 // infinite. In C++, most loops are finite by assumption, in which case the
10761 // step being zero implies UB must execute if the loop is entered.
10762 if (!(loopIsFiniteByAssumption(L) && isKnownNonZero(Start)) &&
10763 !isKnownNonZero(StepWLG))
10764 return getCouldNotCompute();
10765
10766 const SCEV *Exact =
10767 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10768 const SCEV *ConstantMax = getCouldNotCompute();
10769 if (Exact != getCouldNotCompute()) {
10770 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, Guards));
10771 ConstantMax =
10773 }
10774 const SCEV *SymbolicMax =
10775 isa<SCEVCouldNotCompute>(Exact) ? ConstantMax : Exact;
10776 return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
10777 }
10778
10779 // Solve the general equation.
10780 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
10781 if (!StepC || StepC->getValue()->isZero())
10782 return getCouldNotCompute();
10783 const SCEV *E = SolveLinEquationWithOverflow(
10784 StepC->getAPInt(), getNegativeSCEV(Start),
10785 AllowPredicates ? &Predicates : nullptr, *this, L);
10786
10787 const SCEV *M = E;
10788 if (E != getCouldNotCompute()) {
10789 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, Guards));
10790 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
10791 }
10792 auto *S = isa<SCEVCouldNotCompute>(E) ? M : E;
10793 return ExitLimit(E, M, S, false, Predicates);
10794}
10795
10796ScalarEvolution::ExitLimit
10797ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10798 // Loops that look like: while (X == 0) are very strange indeed. We don't
10799 // handle them yet except for the trivial case. This could be expanded in the
10800 // future as needed.
10801
10802 // If the value is a constant, check to see if it is known to be non-zero
10803 // already. If so, the backedge will execute zero times.
10804 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10805 if (!C->getValue()->isZero())
10806 return getZero(C->getType());
10807 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10808 }
10809
10810 // We could implement others, but I really doubt anyone writes loops like
10811 // this, and if they did, they would already be constant folded.
10812 return getCouldNotCompute();
10813}
10814
10815std::pair<const BasicBlock *, const BasicBlock *>
10816ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10817 const {
10818 // If the block has a unique predecessor, then there is no path from the
10819 // predecessor to the block that does not go through the direct edge
10820 // from the predecessor to the block.
10821 if (const BasicBlock *Pred = BB->getSinglePredecessor())
10822 return {Pred, BB};
10823
10824 // A loop's header is defined to be a block that dominates the loop.
10825 // If the header has a unique predecessor outside the loop, it must be
10826 // a block that has exactly one successor that can reach the loop.
10827 if (const Loop *L = LI.getLoopFor(BB))
10828 return {L->getLoopPredecessor(), L->getHeader()};
10829
10830 return {nullptr, BB};
10831}
10832
10833/// SCEV structural equivalence is usually sufficient for testing whether two
10834/// expressions are equal, however for the purposes of looking for a condition
10835/// guarding a loop, it can be useful to be a little more general, since a
10836/// front-end may have replicated the controlling expression.
10837static bool HasSameValue(const SCEV *A, const SCEV *B) {
10838 // Quick check to see if they are the same SCEV.
10839 if (A == B) return true;
10840
10841 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10842 // Not all instructions that are "identical" compute the same value. For
10843 // instance, two distinct alloca instructions allocating the same type are
10844 // identical and do not read memory; but compute distinct values.
10845 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
10846 };
10847
10848 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10849 // two different instructions with the same value. Check for this case.
10850 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
10851 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
10852 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
10853 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
10854 if (ComputesEqualValues(AI, BI))
10855 return true;
10856
10857 // Otherwise assume they may have a different value.
10858 return false;
10859}
10860
10861static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS) {
10862 const SCEV *Op0, *Op1;
10863 if (!match(S, m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))))
10864 return false;
10865 if (match(Op0, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10866 LHS = Op1;
10867 return true;
10868 }
10869 if (match(Op1, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10870 LHS = Op0;
10871 return true;
10872 }
10873 return false;
10874}
10875
10877 SCEVUse &RHS, unsigned Depth) {
10878 bool Changed = false;
10879 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
10880 // '0 != 0'.
10881 auto TrivialCase = [&](bool TriviallyTrue) {
10883 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
10884 return true;
10885 };
10886 // If we hit the max recursion limit bail out.
10887 if (Depth >= 3)
10888 return false;
10889
10890 const SCEV *NewLHS, *NewRHS;
10891 if (match(LHS, m_scev_c_Mul(m_SCEV(NewLHS), m_SCEVVScale())) &&
10892 match(RHS, m_scev_c_Mul(m_SCEV(NewRHS), m_SCEVVScale()))) {
10893 const SCEVMulExpr *LMul = cast<SCEVMulExpr>(LHS);
10894 const SCEVMulExpr *RMul = cast<SCEVMulExpr>(RHS);
10895
10896 // (X * vscale) pred (Y * vscale) ==> X pred Y
10897 // when both multiples are NSW.
10898 // (X * vscale) uicmp/eq/ne (Y * vscale) ==> X uicmp/eq/ne Y
10899 // when both multiples are NUW.
10900 if ((LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap()) ||
10901 (LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap() &&
10902 !ICmpInst::isSigned(Pred))) {
10903 LHS = NewLHS;
10904 RHS = NewRHS;
10905 Changed = true;
10906 }
10907 }
10908
10909 // Canonicalize a constant to the right side.
10910 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
10911 // Check for both operands constant.
10912 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
10913 if (!ICmpInst::compare(LHSC->getAPInt(), RHSC->getAPInt(), Pred))
10914 return TrivialCase(false);
10915 return TrivialCase(true);
10916 }
10917 // Otherwise swap the operands to put the constant on the right.
10918 std::swap(LHS, RHS);
10920 Changed = true;
10921 }
10922
10923 // (K + A) pred (K + B) --> A pred B
10924 // For equality, no flags are needed.
10925 // For signed, both adds must be NSW. For unsigned, both must be NUW.
10926 {
10927 const SCEVConstant *C = nullptr;
10928 if (match(LHS, m_scev_Add(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
10929 match(RHS, m_scev_Add(m_scev_Specific(C), m_SCEV(NewRHS)))) {
10930 const auto *LAdd = cast<SCEVAddExpr>(LHS);
10931 const auto *RAdd = cast<SCEVAddExpr>(RHS);
10932 bool BothNUW = LAdd->hasNoUnsignedWrap() && RAdd->hasNoUnsignedWrap();
10933 bool BothNSW = LAdd->hasNoSignedWrap() && RAdd->hasNoSignedWrap();
10934 if (ICmpInst::isEquality(Pred) || (ICmpInst::isSigned(Pred) && BothNSW) ||
10935 (ICmpInst::isUnsigned(Pred) && BothNUW)) {
10936 LHS = NewLHS;
10937 RHS = NewRHS;
10938 // Nothing follows about the signs of A and B themselves, as adding K
10939 // may move either A or B across the sign boundary, unless both adds are
10940 // guaranteed not to wrap in either domain.
10941 if (!(BothNUW && BothNSW))
10942 Pred = Pred.dropSameSign();
10943 Changed = true;
10944 }
10945 }
10946 }
10947
10948 // (C * A) pred (C * B) --> A pred B
10949 // For equality predicates, both muls must be NUW or both must be NSW
10950 // (either suffices to make multiplication by C injective; C == 0 is
10951 // impossible because SCEV folds 0 * X to 0).
10952 // For signed ordering, C must be positive and both muls must be NSW.
10953 // For unsigned ordering, both muls must be NUW.
10954 {
10955 const SCEVConstant *C = nullptr;
10956 if (match(LHS, m_scev_Mul(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
10957 match(RHS, m_scev_Mul(m_scev_Specific(C), m_SCEV(NewRHS)))) {
10958 const auto *LMul = cast<SCEVMulExpr>(LHS);
10959 const auto *RMul = cast<SCEVMulExpr>(RHS);
10960 bool BothNUW = LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap();
10961 bool BothNSW = LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap();
10962 if ((ICmpInst::isEquality(Pred) && (BothNUW || BothNSW)) ||
10963 (ICmpInst::isSigned(Pred) && BothNSW &&
10964 C->getAPInt().isStrictlyPositive()) ||
10965 (ICmpInst::isUnsigned(Pred) && BothNUW)) {
10966 LHS = NewLHS;
10967 RHS = NewRHS;
10968 Changed = true;
10969 }
10970 }
10971 }
10972
10973 // If we're comparing an addrec with a value which is loop-invariant in the
10974 // addrec's loop, put the addrec on the left. Also make a dominance check,
10975 // as both operands could be addrecs loop-invariant in each other's loop.
10976 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
10977 const Loop *L = AR->getLoop();
10978 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
10979 std::swap(LHS, RHS);
10981 Changed = true;
10982 }
10983 }
10984
10985 // If there's a constant operand, canonicalize comparisons with boundary
10986 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
10987 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
10988 const APInt &RA = RC->getAPInt();
10989
10990 bool SimplifiedByConstantRange = false;
10991
10992 if (!ICmpInst::isEquality(Pred)) {
10994 if (ExactCR.isFullSet())
10995 return TrivialCase(true);
10996 if (ExactCR.isEmptySet())
10997 return TrivialCase(false);
10998
10999 APInt NewRHS;
11000 CmpInst::Predicate NewPred;
11001 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
11002 ICmpInst::isEquality(NewPred)) {
11003 // We were able to convert an inequality to an equality.
11004 Pred = NewPred;
11005 RHS = getConstant(NewRHS);
11006 Changed = SimplifiedByConstantRange = true;
11007 }
11008 }
11009
11010 if (!SimplifiedByConstantRange) {
11011 switch (Pred) {
11012 default:
11013 break;
11014 case ICmpInst::ICMP_EQ:
11015 case ICmpInst::ICMP_NE:
11016 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
11017 if (RA.isZero() && MatchBinarySub(LHS, LHS, RHS))
11018 Changed = true;
11019 break;
11020
11021 // The "Should have been caught earlier!" messages refer to the fact
11022 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
11023 // should have fired on the corresponding cases, and canonicalized the
11024 // check to trivial case.
11025
11026 case ICmpInst::ICMP_UGE:
11027 assert(!RA.isMinValue() && "Should have been caught earlier!");
11028 Pred = ICmpInst::ICMP_UGT;
11029 RHS = getConstant(RA - 1);
11030 Changed = true;
11031 break;
11032 case ICmpInst::ICMP_ULE:
11033 assert(!RA.isMaxValue() && "Should have been caught earlier!");
11034 Pred = ICmpInst::ICMP_ULT;
11035 RHS = getConstant(RA + 1);
11036 Changed = true;
11037 break;
11038 case ICmpInst::ICMP_SGE:
11039 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
11040 Pred = ICmpInst::ICMP_SGT;
11041 RHS = getConstant(RA - 1);
11042 Changed = true;
11043 break;
11044 case ICmpInst::ICMP_SLE:
11045 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
11046 Pred = ICmpInst::ICMP_SLT;
11047 RHS = getConstant(RA + 1);
11048 Changed = true;
11049 break;
11050 }
11051 }
11052 }
11053
11054 // a /u b == 0 => a < b
11055 // a /u b != 0 => a >= b
11056 if (ICmpInst::isEquality(Pred) && RHS->isZero() &&
11057 match(LHS, m_scev_UDiv(m_SCEV(LHS), m_SCEV(RHS)))) {
11059 Changed = true;
11060 }
11061
11062 // Check for obvious equality.
11063 if (HasSameValue(LHS, RHS)) {
11064 if (ICmpInst::isTrueWhenEqual(Pred))
11065 return TrivialCase(true);
11067 return TrivialCase(false);
11068 }
11069
11070 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
11071 // adding or subtracting 1 from one of the operands.
11072 switch (Pred) {
11073 case ICmpInst::ICMP_SLE:
11074 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
11075 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11077 Pred = ICmpInst::ICMP_SLT;
11078 Changed = true;
11079 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
11080 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
11082 Pred = ICmpInst::ICMP_SLT;
11083 Changed = true;
11084 }
11085 break;
11086 case ICmpInst::ICMP_SGE:
11087 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
11088 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
11090 Pred = ICmpInst::ICMP_SGT;
11091 Changed = true;
11092 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
11093 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11095 Pred = ICmpInst::ICMP_SGT;
11096 Changed = true;
11097 }
11098 break;
11099 case ICmpInst::ICMP_ULE:
11100 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
11101 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11103 Pred = ICmpInst::ICMP_ULT;
11104 Changed = true;
11105 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
11106 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
11107 Pred = ICmpInst::ICMP_ULT;
11108 Changed = true;
11109 }
11110 break;
11111 case ICmpInst::ICMP_UGE:
11112 // If RHS is an op we can fold the -1, try that first.
11113 // Otherwise prefer LHS to preserve the nuw flag.
11114 if ((isa<SCEVConstant>(RHS) ||
11116 isa<SCEVConstant>(cast<SCEVNAryExpr>(RHS)->getOperand(0)))) &&
11117 !getUnsignedRangeMin(RHS).isMinValue()) {
11118 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11119 Pred = ICmpInst::ICMP_UGT;
11120 Changed = true;
11121 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
11122 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11124 Pred = ICmpInst::ICMP_UGT;
11125 Changed = true;
11126 } else if (!getUnsignedRangeMin(RHS).isMinValue()) {
11127 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11128 Pred = ICmpInst::ICMP_UGT;
11129 Changed = true;
11130 }
11131 break;
11132 default:
11133 break;
11134 }
11135
11136 // TODO: More simplifications are possible here.
11137
11138 // Recursively simplify until we either hit a recursion limit or nothing
11139 // changes.
11140 if (Changed)
11141 (void)SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1);
11142
11143 return Changed;
11144}
11145
11147 return getSignedRangeMax(S).isNegative();
11148}
11149
11153
11155 return !getSignedRangeMin(S).isNegative();
11156}
11157
11161
11163 // Query push down for cases where the unsigned range is
11164 // less than sufficient.
11165 if (const auto *SExt = dyn_cast<SCEVSignExtendExpr>(S))
11166 return isKnownNonZero(SExt->getOperand(0));
11167 return getUnsignedRangeMin(S) != 0;
11168}
11169
11171 bool OrNegative) {
11172 auto NonRecursive = [OrNegative](const SCEV *S) {
11173 if (auto *C = dyn_cast<SCEVConstant>(S))
11174 return C->getAPInt().isPowerOf2() ||
11175 (OrNegative && C->getAPInt().isNegatedPowerOf2());
11176
11177 // vscale is a power-of-two.
11178 return isa<SCEVVScale>(S);
11179 };
11180
11181 if (NonRecursive(S))
11182 return true;
11183
11184 auto *Mul = dyn_cast<SCEVMulExpr>(S);
11185 if (!Mul)
11186 return false;
11187 return all_of(Mul->operands(), NonRecursive) && (OrZero || isKnownNonZero(S));
11188}
11189
11191 const SCEV *S, uint64_t M,
11193 if (M == 0)
11194 return false;
11195 if (M == 1)
11196 return true;
11197
11198 // For a constant, check that "S % M == 0".
11199 if (auto *Cst = dyn_cast<SCEVConstant>(S)) {
11200 APInt C = Cst->getAPInt();
11201 return C.urem(M) == 0;
11202 }
11203
11204 // Basic tests have failed.
11205 // Check "S % M == 0" at compile time and record runtime Assumptions.
11206 auto *STy = dyn_cast<IntegerType>(S->getType());
11207 const SCEV *SmodM =
11208 getURemExpr(S, getConstant(ConstantInt::get(STy, M, false)));
11209 const SCEV *Zero = getZero(STy);
11210
11211 // Check whether "S % M == 0" is known at compile time.
11213 return true;
11214
11215 // Check whether "S % M != 0" is known at compile time.
11217 return false;
11218
11219 if (!Predicates)
11220 return false;
11221
11222 // Look through Add and AddRec expressions with nuw to improve the
11223 // precision of added predicates. S is a multiple of M if S starts with a
11224 // multiple of M and at every iteration step S only adds multiples of M.
11227 all_of(S->operands(),
11228 [&](SCEVUse Op) { return isKnownMultipleOf(Op, M, Predicates); }))
11229 return true;
11230
11231 // Similarly, look through Mul with nuw, where any operand being a
11232 // known-multiple is sufficient.
11233 if (auto *Mul = dyn_cast<SCEVMulExpr>(S))
11234 if (Mul->hasNoUnsignedWrap() && any_of(S->operands(), [&](SCEVUse Op) {
11235 return isKnownMultipleOf(Op, M, Predicates);
11236 }))
11237 return true;
11238
11239 // Similarly, look through MinMax, with no wrapping arithmetic to consider.
11240 if (isa<SCEVMinMaxExpr>(S) && all_of(S->operands(), [&](SCEVUse Op) {
11241 return isKnownMultipleOf(Op, M, Predicates);
11242 }))
11243 return true;
11244
11246
11247 // Detect redundant predicates.
11248 for (auto *A : *Predicates)
11249 if (A->implies(P, *this))
11250 return true;
11251
11252 // Only record non-redundant predicates.
11253 Predicates->push_back(P);
11254 return true;
11255}
11256
11258 return ((isKnownNonNegative(S1) && isKnownNonNegative(S2)) ||
11260}
11261
11262std::pair<const SCEV *, const SCEV *>
11264 // Compute SCEV on entry of loop L.
11265 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
11266 if (Start == getCouldNotCompute())
11267 return { Start, Start };
11268 // Compute post increment SCEV for loop L.
11269 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
11270 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
11271 return { Start, PostInc };
11272}
11273
11275 SCEVUse RHS) {
11276 // First collect all loops.
11278 getUsedLoops(LHS, LoopsUsed);
11279 getUsedLoops(RHS, LoopsUsed);
11280
11281 if (LoopsUsed.empty())
11282 return false;
11283
11284 // Domination relationship must be a linear order on collected loops.
11285#ifndef NDEBUG
11286 for (const auto *L1 : LoopsUsed)
11287 for (const auto *L2 : LoopsUsed)
11288 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
11289 DT.dominates(L2->getHeader(), L1->getHeader())) &&
11290 "Domination relationship is not a linear order");
11291#endif
11292
11293 const Loop *MDL =
11294 *llvm::max_element(LoopsUsed, [&](const Loop *L1, const Loop *L2) {
11295 return DT.properlyDominates(L1->getHeader(), L2->getHeader());
11296 });
11297
11298 // Get init and post increment value for LHS.
11299 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
11300 // if LHS contains unknown non-invariant SCEV then bail out.
11301 if (SplitLHS.first == getCouldNotCompute())
11302 return false;
11303 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
11304 // Get init and post increment value for RHS.
11305 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
11306 // if RHS contains unknown non-invariant SCEV then bail out.
11307 if (SplitRHS.first == getCouldNotCompute())
11308 return false;
11309 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
11310 // It is possible that init SCEV contains an invariant load but it does
11311 // not dominate MDL and is not available at MDL loop entry, so we should
11312 // check it here.
11313 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
11314 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
11315 return false;
11316
11317 // It seems backedge guard check is faster than entry one so in some cases
11318 // it can speed up whole estimation by short circuit
11319 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
11320 SplitRHS.second) &&
11321 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
11322}
11323
11325 SCEVUse RHS) {
11326 // Canonicalize the inputs first.
11327 (void)SimplifyICmpOperands(Pred, LHS, RHS);
11328
11329 return isKnownViaInduction(Pred, LHS, RHS) ||
11330 isKnownPredicateViaSplitting(Pred, LHS, RHS) ||
11331 isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
11332}
11333
11335 const SCEV *LHS,
11336 const SCEV *RHS) {
11337 if (isKnownPredicate(Pred, LHS, RHS))
11338 return true;
11340 return false;
11341 return std::nullopt;
11342}
11343
11345 const SCEV *RHS,
11346 const Instruction *CtxI) {
11347 // TODO: Analyze guards and assumes from Context's block.
11348 return isKnownPredicate(Pred, LHS, RHS) ||
11349 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
11350}
11351
11352std::optional<bool>
11354 const SCEV *RHS, const Instruction *CtxI) {
11355 std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
11356 if (KnownWithoutContext)
11357 return KnownWithoutContext;
11358
11359 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
11360 return true;
11362 CtxI->getParent(), ICmpInst::getInverseCmpPredicate(Pred), LHS, RHS))
11363 return false;
11364 return std::nullopt;
11365}
11366
11368 const SCEVAddRecExpr *LHS,
11369 const SCEV *RHS) {
11370 const Loop *L = LHS->getLoop();
11371 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
11372 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
11373}
11374
11375std::optional<ScalarEvolution::MonotonicPredicateType>
11377 ICmpInst::Predicate Pred) {
11378 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
11379
11380#ifndef NDEBUG
11381 // Verify an invariant: inverting the predicate should turn a monotonically
11382 // increasing change to a monotonically decreasing one, and vice versa.
11383 if (Result) {
11384 auto ResultSwapped =
11385 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
11386
11387 assert(*ResultSwapped != *Result &&
11388 "monotonicity should flip as we flip the predicate");
11389 }
11390#endif
11391
11392 return Result;
11393}
11394
11395std::optional<ScalarEvolution::MonotonicPredicateType>
11396ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
11397 ICmpInst::Predicate Pred) {
11398 // A zero step value for LHS means the induction variable is essentially a
11399 // loop invariant value. We don't really depend on the predicate actually
11400 // flipping from false to true (for increasing predicates, and the other way
11401 // around for decreasing predicates), all we care about is that *if* the
11402 // predicate changes then it only changes from false to true.
11403 //
11404 // A zero step value in itself is not very useful, but there may be places
11405 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
11406 // as general as possible.
11407
11408 // Only handle LE/LT/GE/GT predicates.
11409 if (!ICmpInst::isRelational(Pred))
11410 return std::nullopt;
11411
11412 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
11413 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
11414 "Should be greater or less!");
11415
11416 // Check that AR does not wrap.
11417 if (ICmpInst::isUnsigned(Pred)) {
11418 if (!LHS->hasNoUnsignedWrap())
11419 return std::nullopt;
11421 }
11423 "Relational predicate is either signed or unsigned!");
11424 if (!LHS->hasNoSignedWrap())
11425 return std::nullopt;
11426
11427 const SCEV *Step = LHS->getStepRecurrence(*this);
11428
11429 if (isKnownNonNegative(Step))
11431
11432 if (isKnownNonPositive(Step))
11434
11435 return std::nullopt;
11436}
11437
11438std::optional<ScalarEvolution::LoopInvariantPredicate>
11440 const SCEV *RHS, const Loop *L,
11441 const Instruction *CtxI) {
11442 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11443 if (!isLoopInvariant(RHS, L)) {
11444 if (!isLoopInvariant(LHS, L))
11445 return std::nullopt;
11446
11447 std::swap(LHS, RHS);
11449 }
11450
11451 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11452 if (!ArLHS || ArLHS->getLoop() != L)
11453 return std::nullopt;
11454
11455 // Even if both are valid, we need to consistently choose the unsigned or the
11456 // signed predicate for the monotonicity and backedge checks below, not
11457 // mixtures of both. For now, prefer the unsigned predicate.
11458 Pred = Pred.dropSameSign();
11459 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
11460 if (!MonotonicType)
11461 return std::nullopt;
11462 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
11463 // true as the loop iterates, and the backedge is control dependent on
11464 // "ArLHS `Pred` RHS" == true then we can reason as follows:
11465 //
11466 // * if the predicate was false in the first iteration then the predicate
11467 // is never evaluated again, since the loop exits without taking the
11468 // backedge.
11469 // * if the predicate was true in the first iteration then it will
11470 // continue to be true for all future iterations since it is
11471 // monotonically increasing.
11472 //
11473 // For both the above possibilities, we can replace the loop varying
11474 // predicate with its value on the first iteration of the loop (which is
11475 // loop invariant).
11476 //
11477 // A similar reasoning applies for a monotonically decreasing predicate, by
11478 // replacing true with false and false with true in the above two bullets.
11480 auto P = Increasing ? Pred : ICmpInst::getInverseCmpPredicate(Pred);
11481
11482 if (isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
11484 RHS);
11485
11486 if (!CtxI)
11487 return std::nullopt;
11488 // Try to prove via context.
11489 // TODO: Support other cases.
11490 switch (Pred) {
11491 default:
11492 break;
11493 case ICmpInst::ICMP_ULE:
11494 case ICmpInst::ICMP_ULT: {
11495 assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!");
11496 // Given preconditions
11497 // (1) ArLHS does not cross the border of positive and negative parts of
11498 // range because of:
11499 // - Positive step; (TODO: lift this limitation)
11500 // - nuw - does not cross zero boundary;
11501 // - nsw - does not cross SINT_MAX boundary;
11502 // (2) ArLHS <s RHS
11503 // (3) RHS >=s 0
11504 // we can replace the loop variant ArLHS <u RHS condition with loop
11505 // invariant Start(ArLHS) <u RHS.
11506 //
11507 // Because of (1) there are two options:
11508 // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
11509 // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
11510 // It means that ArLHS <s RHS <=> ArLHS <u RHS.
11511 // Because of (2) ArLHS <u RHS is trivially true.
11512 // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
11513 // We can strengthen this to Start(ArLHS) <u RHS.
11514 auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
11515 if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
11516 isKnownPositive(ArLHS->getStepRecurrence(*this)) &&
11517 isKnownNonNegative(RHS) &&
11518 isKnownPredicateAt(SignFlippedPred, ArLHS, RHS, CtxI))
11520 RHS);
11521 }
11522 }
11523
11524 return std::nullopt;
11525}
11526
11527std::optional<ScalarEvolution::LoopInvariantPredicate>
11529 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11530 const Instruction *CtxI, const SCEV *MaxIter) {
11532 Pred, LHS, RHS, L, CtxI, MaxIter))
11533 return LIP;
11534 if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
11535 // Number of iterations expressed as UMIN isn't always great for expressing
11536 // the value on the last iteration. If the straightforward approach didn't
11537 // work, try the following trick: if the a predicate is invariant for X, it
11538 // is also invariant for umin(X, ...). So try to find something that works
11539 // among subexpressions of MaxIter expressed as umin.
11540 for (SCEVUse Op : UMin->operands())
11542 Pred, LHS, RHS, L, CtxI, Op))
11543 return LIP;
11544 return std::nullopt;
11545}
11546
11547std::optional<ScalarEvolution::LoopInvariantPredicate>
11549 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11550 const Instruction *CtxI, const SCEV *MaxIter) {
11551 // Try to prove the following set of facts:
11552 // - The predicate is monotonic in the iteration space.
11553 // - If the check does not fail on the 1st iteration:
11554 // - No overflow will happen during first MaxIter iterations;
11555 // - It will not fail on the MaxIter'th iteration.
11556 // If the check does fail on the 1st iteration, we leave the loop and no
11557 // other checks matter.
11558
11559 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11560 if (!isLoopInvariant(RHS, L)) {
11561 if (!isLoopInvariant(LHS, L))
11562 return std::nullopt;
11563
11564 std::swap(LHS, RHS);
11566 }
11567
11568 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
11569 if (!AR || AR->getLoop() != L)
11570 return std::nullopt;
11571
11572 // Even if both are valid, we need to consistently chose the unsigned or the
11573 // signed predicate below, not mixtures of both. For now, prefer the unsigned
11574 // predicate.
11575 Pred = Pred.dropSameSign();
11576
11577 // The predicate must be relational (i.e. <, <=, >=, >).
11578 if (!ICmpInst::isRelational(Pred))
11579 return std::nullopt;
11580
11581 // TODO: Support steps other than +/- 1.
11582 const SCEV *Step = AR->getStepRecurrence(*this);
11583 auto *One = getOne(Step->getType());
11584 auto *MinusOne = getNegativeSCEV(One);
11585 if (Step != One && Step != MinusOne)
11586 return std::nullopt;
11587
11588 // Type mismatch here means that MaxIter is potentially larger than max
11589 // unsigned value in start type, which mean we cannot prove no wrap for the
11590 // indvar.
11591 if (AR->getType() != MaxIter->getType())
11592 return std::nullopt;
11593
11594 // Value of IV on suggested last iteration.
11595 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
11596 // Does it still meet the requirement?
11597 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
11598 return std::nullopt;
11599 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
11600 // not exceed max unsigned value of this type), this effectively proves
11601 // that there is no wrap during the iteration. To prove that there is no
11602 // signed/unsigned wrap, we need to check that
11603 // Start <= Last for step = 1 or Start >= Last for step = -1.
11604 ICmpInst::Predicate NoOverflowPred =
11606 if (Step == MinusOne)
11607 NoOverflowPred = ICmpInst::getSwappedPredicate(NoOverflowPred);
11608 const SCEV *Start = AR->getStart();
11609 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
11610 return std::nullopt;
11611
11612 // Everything is fine.
11613 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
11614}
11615
11616bool ScalarEvolution::isKnownPredicateViaConstantRanges(CmpPredicate Pred,
11617 SCEVUse LHS,
11618 SCEVUse RHS) {
11619 if (HasSameValue(LHS, RHS))
11620 return ICmpInst::isTrueWhenEqual(Pred);
11621
11622 auto CheckRange = [&](bool IsSigned) {
11623 auto RangeLHS = IsSigned ? getSignedRange(LHS) : getUnsignedRange(LHS);
11624 auto RangeRHS = IsSigned ? getSignedRange(RHS) : getUnsignedRange(RHS);
11625 return RangeLHS.icmp(Pred, RangeRHS);
11626 };
11627
11628 // The check at the top of the function catches the case where the values are
11629 // known to be equal.
11630 if (Pred == CmpInst::ICMP_EQ)
11631 return false;
11632
11633 if (Pred == CmpInst::ICMP_NE) {
11634 if (CheckRange(true) || CheckRange(false))
11635 return true;
11636 auto *Diff = getMinusSCEV(LHS, RHS);
11637 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
11638 }
11639
11640 return CheckRange(CmpInst::isSigned(Pred));
11641}
11642
11643bool ScalarEvolution::isKnownPredicateViaNoOverflow(CmpPredicate Pred,
11645 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
11646 // C1 and C2 are constant integers. If either X or Y are not add expressions,
11647 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
11648 // OutC1 and OutC2.
11649 auto MatchBinaryAddToConst = [this](SCEVUse X, SCEVUse Y, APInt &OutC1,
11650 APInt &OutC2, SCEVFlags ExpectedFlags) {
11651 SCEVUse XNonConstOp, XConstOp;
11652 SCEVUse YNonConstOp, YConstOp;
11653 SCEVFlags XFlagsPresent;
11654 SCEVFlags YFlagsPresent;
11655
11656 // Use nullptr for 0, to avoid creating a zero SCEV.
11657 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
11658 XConstOp = nullptr;
11659 XNonConstOp = X;
11660 XFlagsPresent = ExpectedFlags;
11661 }
11662 if (XConstOp && !isa<SCEVConstant>(XConstOp))
11663 return false;
11664
11665 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
11666 YConstOp = nullptr;
11667 YNonConstOp = Y;
11668 YFlagsPresent = ExpectedFlags;
11669 }
11670
11671 if (YNonConstOp != XNonConstOp)
11672 return false;
11673
11674 if (YConstOp && !isa<SCEVConstant>(YConstOp))
11675 return false;
11676
11677 // When matching ADDs with NUW flags (and unsigned predicates), only the
11678 // second ADD (with the larger constant) requires NUW.
11679 if ((YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11680 return false;
11682 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) {
11683 return false;
11684 }
11685
11686 OutC1 = XConstOp ? cast<SCEVConstant>(XConstOp)->getAPInt()
11687 : APInt::getZero(getTypeSizeInBits(X->getType()));
11688 OutC2 = YConstOp ? cast<SCEVConstant>(YConstOp)->getAPInt()
11689 : APInt::getZero(getTypeSizeInBits(Y->getType()));
11690
11691 return true;
11692 };
11693
11694 APInt C1;
11695 APInt C2;
11696
11697 switch (Pred) {
11698 default:
11699 break;
11700
11701 case ICmpInst::ICMP_SGE:
11702 std::swap(LHS, RHS);
11703 [[fallthrough]];
11704 case ICmpInst::ICMP_SLE:
11705 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
11706 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
11707 return true;
11708
11709 break;
11710
11711 case ICmpInst::ICMP_SGT:
11712 std::swap(LHS, RHS);
11713 [[fallthrough]];
11714 case ICmpInst::ICMP_SLT:
11715 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
11716 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
11717 return true;
11718
11719 break;
11720
11721 case ICmpInst::ICMP_UGE:
11722 std::swap(LHS, RHS);
11723 [[fallthrough]];
11724 case ICmpInst::ICMP_ULE:
11725 // (X + C1) u<= (X + C2)<nuw> for C1 u<= C2.
11726 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ule(C2))
11727 return true;
11728
11729 break;
11730
11731 case ICmpInst::ICMP_UGT:
11732 std::swap(LHS, RHS);
11733 [[fallthrough]];
11734 case ICmpInst::ICMP_ULT:
11735 // (X + C1) u< (X + C2)<nuw> if C1 u< C2.
11736 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ult(C2))
11737 return true;
11738 break;
11739 }
11740
11741 return false;
11742}
11743
11744bool ScalarEvolution::isKnownPredicateViaSplitting(CmpPredicate Pred,
11746 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
11747 return false;
11748
11749 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
11750 // the stack can result in exponential time complexity.
11751 SaveAndRestore Restore(ProvingSplitPredicate, true);
11752
11753 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
11754 //
11755 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
11756 // isKnownPredicate. isKnownPredicate is more powerful, but also more
11757 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
11758 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
11759 // use isKnownPredicate later if needed.
11760 return isKnownNonNegative(RHS) &&
11763}
11764
11765bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, CmpPredicate Pred,
11766 const SCEV *LHS, const SCEV *RHS) {
11767 // No need to even try if we know the module has no guards.
11768 if (!HasGuards)
11769 return false;
11770
11771 return any_of(*BB, [&](const Instruction &I) {
11772 using namespace llvm::PatternMatch;
11773
11774 Value *Condition;
11776 m_Value(Condition))) &&
11777 isImpliedCond(Pred, LHS, RHS, Condition, false);
11778 });
11779}
11780
11781/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
11782/// protected by a conditional between LHS and RHS. This is used to
11783/// to eliminate casts.
11785 CmpPredicate Pred,
11786 const SCEV *LHS,
11787 const SCEV *RHS) {
11788 // Interpret a null as meaning no loop, where there is obviously no guard
11789 // (interprocedural conditions notwithstanding). Do not bother about
11790 // unreachable loops.
11791 if (!L || !DT.isReachableFromEntry(L->getHeader()))
11792 return true;
11793
11794 if (Opts.scev_verify_ir)
11795 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
11796 "This cannot be done on broken IR!");
11797
11798
11799 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11800 return true;
11801
11802 BasicBlock *Latch = L->getLoopLatch();
11803 if (!Latch)
11804 return false;
11805
11806 CondBrInst *LoopContinuePredicate =
11808 if (LoopContinuePredicate &&
11809 isImpliedCond(Pred, LHS, RHS, LoopContinuePredicate->getCondition(),
11810 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
11811 return true;
11812
11813 // We don't want more than one activation of the following loops on the stack
11814 // -- that can lead to O(n!) time complexity.
11815 if (WalkingBEDominatingConds)
11816 return false;
11817
11818 SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
11819
11820 // See if we can exploit a trip count to prove the predicate.
11821 const auto &BETakenInfo = getBackedgeTakenInfo(L);
11822 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
11823 if (LatchBECount != getCouldNotCompute()) {
11824 // We know that Latch branches back to the loop header exactly
11825 // LatchBECount times. This means the backdege condition at Latch is
11826 // equivalent to "{0,+,1} u< LatchBECount".
11827 Type *Ty = LatchBECount->getType();
11828 auto NoWrapFlags = SCEVFlags(SCEV::FlagNUW | SCEV::FlagNW);
11829 const SCEV *LoopCounter =
11830 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
11831 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
11832 LatchBECount))
11833 return true;
11834 }
11835
11836 // Check conditions due to any @llvm.assume intrinsics.
11837 for (auto &AssumeVH : AC.assumptions()) {
11838 if (!AssumeVH)
11839 continue;
11840 auto *CI = cast<CallInst>(AssumeVH);
11841 if (!DT.dominates(CI, Latch->getTerminator()))
11842 continue;
11843
11844 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
11845 return true;
11846 }
11847
11848 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
11849 return true;
11850
11851 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
11852 DTN != HeaderDTN; DTN = DTN->getIDom()) {
11853 assert(DTN && "should reach the loop header before reaching the root!");
11854
11855 BasicBlock *BB = DTN->getBlock();
11856 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
11857 return true;
11858
11859 BasicBlock *PBB = BB->getSinglePredecessor();
11860 if (!PBB)
11861 continue;
11862
11864 if (!ContBr || ContBr->getSuccessor(0) == ContBr->getSuccessor(1))
11865 continue;
11866
11867 // If we have an edge `E` within the loop body that dominates the only
11868 // latch, the condition guarding `E` also guards the backedge. This
11869 // reasoning works only for loops with a single latch.
11870 // We're constructively (and conservatively) enumerating edges within the
11871 // loop body that dominate the latch. The dominator tree better agree
11872 // with us on this:
11873 assert(DT.dominates(BasicBlockEdge(PBB, BB), Latch) && "should be!");
11874 if (isImpliedCond(Pred, LHS, RHS, ContBr->getCondition(),
11875 BB != ContBr->getSuccessor(0)))
11876 return true;
11877 }
11878
11879 return false;
11880}
11881
11883 CmpPredicate Pred,
11884 const SCEV *LHS,
11885 const SCEV *RHS) {
11886 // Do not bother proving facts for unreachable code.
11887 if (!DT.isReachableFromEntry(BB))
11888 return true;
11889 if (Opts.scev_verify_ir)
11890 assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
11891 "This cannot be done on broken IR!");
11892
11893 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
11894 // the facts (a >= b && a != b) separately. A typical situation is when the
11895 // non-strict comparison is known from ranges and non-equality is known from
11896 // dominating predicates. If we are proving strict comparison, we always try
11897 // to prove non-equality and non-strict comparison separately.
11898 CmpPredicate NonStrictPredicate = ICmpInst::getNonStrictCmpPredicate(Pred);
11899 const bool ProvingStrictComparison =
11900 Pred != NonStrictPredicate.dropSameSign();
11901 const Instruction *CtxI = &BB->front();
11903
11904 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
11905 auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
11906 Conds.emplace_back(Condition, Inverse);
11907 return isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI);
11908 };
11909
11910 // Starting at the block's predecessor, climb up the predecessor chain, as long
11911 // as there are predecessors that can be found that have unique successors
11912 // leading to the original block.
11913 const Loop *ContainingLoop = LI.getLoopFor(BB);
11914 const BasicBlock *PredBB;
11915 if (ContainingLoop && ContainingLoop->getHeader() == BB)
11916 PredBB = ContainingLoop->getLoopPredecessor();
11917 else
11918 PredBB = BB->getSinglePredecessor();
11919 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
11920 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
11921 const CondBrInst *BlockEntryPredicate =
11922 dyn_cast<CondBrInst>(Pair.first->getTerminator());
11923 if (!BlockEntryPredicate)
11924 continue;
11925
11926 if (ProveViaCond(BlockEntryPredicate->getCondition(),
11927 BlockEntryPredicate->getSuccessor(0) != Pair.second))
11928 return true;
11929 }
11930
11931 // Check conditions due to any @llvm.assume intrinsics.
11932 for (auto &AssumeVH : AC.assumptions()) {
11933 if (!AssumeVH)
11934 continue;
11935 auto *CI = cast<CallInst>(AssumeVH);
11936 if (!DT.dominates(CI, BB))
11937 continue;
11938
11939 if (ProveViaCond(CI->getArgOperand(0), false))
11940 return true;
11941 }
11942
11943 // Check conditions due to any @llvm.experimental.guard intrinsics.
11944 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
11945 F.getParent(), Intrinsic::experimental_guard);
11946 if (GuardDecl)
11947 for (const auto *GU : GuardDecl->users())
11948 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
11949 if (Guard->getFunction() == BB->getParent() && DT.dominates(Guard, BB))
11950 if (ProveViaCond(Guard->getArgOperand(0), false))
11951 return true;
11952
11953 // First try to prove conditions directly, then fall back to proving via the
11954 // non-strict predicate and not-equal.
11955 if (!ProvingStrictComparison)
11956 return false;
11957 auto ProveViaAll = [&](CmpPredicate P) {
11958 return isKnownViaNonRecursiveReasoning(P, LHS, RHS) ||
11959 any_of(Conds, [&](const auto &C) {
11960 return isImpliedCond(P, LHS, RHS, C.first, C.second, CtxI);
11961 });
11962 };
11963 return ProveViaAll(NonStrictPredicate) && ProveViaAll(ICmpInst::ICMP_NE);
11964}
11965
11967 const SCEV *LHS,
11968 const SCEV *RHS) {
11969 // Interpret a null as meaning no loop, where there is obviously no guard
11970 // (interprocedural conditions notwithstanding).
11971 if (!L)
11972 return false;
11973
11974 // Both LHS and RHS must be available at loop entry.
11976 "LHS is not available at Loop Entry");
11978 "RHS is not available at Loop Entry");
11979
11980 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11981 return true;
11982
11983 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
11984}
11985
11986bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
11987 const SCEV *RHS,
11988 const Value *FoundCondValue, bool Inverse,
11989 const Instruction *CtxI) {
11990 // False conditions implies anything. Do not bother analyzing it further.
11991 if (FoundCondValue ==
11992 ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
11993 return true;
11994
11995 if (!PendingLoopPredicates.insert(FoundCondValue).second)
11996 return false;
11997
11998 llvm::scope_exit ClearOnExit(
11999 [&]() { PendingLoopPredicates.erase(FoundCondValue); });
12000
12001 // Recursively handle And and Or conditions.
12002 const Value *Op0, *Op1;
12003 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
12004 if (!Inverse)
12005 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12006 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12007 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
12008 if (Inverse)
12009 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12010 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12011 }
12012
12013 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
12014 if (!ICI) return false;
12015
12016 // Now that we found a conditional branch that dominates the loop or controls
12017 // the loop latch. Check to see if it is the comparison we are looking for.
12018 CmpPredicate FoundPred;
12019 if (Inverse)
12020 FoundPred = ICI->getInverseCmpPredicate();
12021 else
12022 FoundPred = ICI->getCmpPredicate();
12023
12024 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
12025 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
12026
12027 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
12028}
12029
12030bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12031 const SCEV *RHS, CmpPredicate FoundPred,
12032 const SCEV *FoundLHS, const SCEV *FoundRHS,
12033 const Instruction *CtxI) {
12034 // Balance the types.
12035 if (getTypeSizeInBits(LHS->getType()) <
12036 getTypeSizeInBits(FoundLHS->getType())) {
12037 // For unsigned and equality predicates, try to prove that both found
12038 // operands fit into narrow unsigned range. If so, try to prove facts in
12039 // narrow types.
12040 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
12041 !FoundRHS->getType()->isPointerTy()) {
12042 auto *NarrowType = LHS->getType();
12043 auto *WideType = FoundLHS->getType();
12044 auto BitWidth = getTypeSizeInBits(NarrowType);
12045 const SCEV *MaxValue = getZeroExtendExpr(
12047 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
12048 MaxValue) &&
12049 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
12050 MaxValue)) {
12051 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
12052 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
12053 // We cannot preserve samesign after truncation.
12054 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred.dropSameSign(),
12055 TruncFoundLHS, TruncFoundRHS, CtxI))
12056 return true;
12057 }
12058 }
12059
12060 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
12061 return false;
12062 if (CmpInst::isSigned(Pred)) {
12063 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
12064 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
12065 } else {
12066 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
12067 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
12068 }
12069 } else if (getTypeSizeInBits(LHS->getType()) >
12070 getTypeSizeInBits(FoundLHS->getType())) {
12071 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
12072 return false;
12073 if (CmpInst::isSigned(FoundPred)) {
12074 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
12075 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
12076 } else {
12077 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
12078 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
12079 }
12080 }
12081 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
12082 FoundRHS, CtxI);
12083}
12084
12085bool ScalarEvolution::isImpliedCondBalancedTypes(
12086 CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, CmpPredicate FoundPred,
12087 SCEVUse FoundLHS, SCEVUse FoundRHS, const Instruction *CtxI) {
12089 getTypeSizeInBits(FoundLHS->getType()) &&
12090 "Types should be balanced!");
12091 // Canonicalize the query to match the way instcombine will have
12092 // canonicalized the comparison.
12094 if (LHS == RHS)
12096 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
12097 if (FoundLHS == FoundRHS)
12098 return CmpInst::isFalseWhenEqual(FoundPred);
12099
12100 // Check to see if we can make the LHS or RHS match.
12101 if (LHS == FoundRHS || RHS == FoundLHS) {
12102 if (isa<SCEVConstant>(RHS)) {
12103 std::swap(FoundLHS, FoundRHS);
12104 FoundPred = ICmpInst::getSwappedCmpPredicate(FoundPred);
12105 } else {
12106 std::swap(LHS, RHS);
12108 }
12109 }
12110
12111 // Check whether the found predicate is the same as the desired predicate.
12112 if (auto P = CmpPredicate::getMatching(FoundPred, Pred))
12113 return isImpliedCondOperands(*P, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12114
12115 // Check whether swapping the found predicate makes it the same as the
12116 // desired predicate.
12117 if (auto P = CmpPredicate::getMatching(
12119 // We can write the implication
12120 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS
12121 // using one of the following ways:
12122 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS
12123 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS
12124 // Both require swapping the operands of one condition. Don't do this if it
12125 // would break canonical constant/addrec ordering.
12127 return isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P), RHS,
12128 LHS, FoundLHS, FoundRHS, CtxI);
12129 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
12130 return isImpliedCondOperands(*P, LHS, RHS, FoundRHS, FoundLHS, CtxI);
12131
12132 return false;
12133 }
12134
12135 // Try the query as is and with its operands swapped. E.g. "x >s -1" is
12136 // tried as "-1 <s x" too, to match the found condition "x <u y".
12137 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
12139 return CmpInst::isRelational(P2) &&
12141 };
12142 if (IsSignFlippedPredicate(Pred, FoundPred) &&
12143 isImpliedCondViaSignFlippedPred(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12144 return true;
12145 CmpPredicate SwappedPred = ICmpInst::getSwappedCmpPredicate(Pred);
12146 if (IsSignFlippedPredicate(SwappedPred, FoundPred) &&
12147 isImpliedCondViaSignFlippedPred(SwappedPred, RHS, LHS, FoundLHS, FoundRHS,
12148 CtxI))
12149 return true;
12150
12151 // Check if we can make progress by sharpening ranges.
12152 if (FoundPred == ICmpInst::ICMP_NE &&
12153 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
12154
12155 const SCEVConstant *C = nullptr;
12156 const SCEV *V = nullptr;
12157
12158 if (isa<SCEVConstant>(FoundLHS)) {
12159 C = cast<SCEVConstant>(FoundLHS);
12160 V = FoundRHS;
12161 } else {
12162 C = cast<SCEVConstant>(FoundRHS);
12163 V = FoundLHS;
12164 }
12165
12166 // The guarding predicate tells us that C != V. If the known range
12167 // of V is [C, t), we can sharpen the range to [C + 1, t). The
12168 // range we consider has to correspond to same signedness as the
12169 // predicate we're interested in folding.
12170
12171 APInt Min = ICmpInst::isSigned(Pred) ?
12173
12174 if (Min == C->getAPInt()) {
12175 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
12176 // This is true even if (Min + 1) wraps around -- in case of
12177 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
12178
12179 APInt SharperMin = Min + 1;
12180
12181 switch (Pred) {
12182 case ICmpInst::ICMP_SGE:
12183 case ICmpInst::ICMP_UGE:
12184 // We know V `Pred` SharperMin. If this implies LHS `Pred`
12185 // RHS, we're done.
12186 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
12187 CtxI))
12188 return true;
12189 [[fallthrough]];
12190
12191 case ICmpInst::ICMP_SGT:
12192 case ICmpInst::ICMP_UGT:
12193 // We know from the range information that (V `Pred` Min ||
12194 // V == Min). We know from the guarding condition that !(V
12195 // == Min). This gives us
12196 //
12197 // V `Pred` Min || V == Min && !(V == Min)
12198 // => V `Pred` Min
12199 //
12200 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
12201
12202 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
12203 return true;
12204 break;
12205
12206 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
12207 case ICmpInst::ICMP_SLE:
12208 case ICmpInst::ICMP_ULE:
12209 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12210 LHS, V, getConstant(SharperMin), CtxI))
12211 return true;
12212 [[fallthrough]];
12213
12214 case ICmpInst::ICMP_SLT:
12215 case ICmpInst::ICMP_ULT:
12216 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12217 LHS, V, getConstant(Min), CtxI))
12218 return true;
12219 break;
12220
12221 default:
12222 // No change
12223 break;
12224 }
12225 }
12226 }
12227
12228 // Check whether the actual condition is beyond sufficient.
12229 if (FoundPred == ICmpInst::ICMP_EQ)
12231 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12232 return true;
12233 if (Pred == ICmpInst::ICMP_NE)
12234 if (!ICmpInst::isTrueWhenEqual(FoundPred))
12235 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12236 return true;
12237
12238 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS))
12239 return true;
12240
12241 // Otherwise assume the worst.
12242 return false;
12243}
12244
12245bool ScalarEvolution::isImpliedCondViaSignFlippedPred(
12246 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12247 const SCEV *FoundRHS, const Instruction *CtxI) {
12248 CmpPredicate FoundPred = ICmpInst::getFlippedSignednessPredicate(Pred);
12249 // Unsigned comparison is the same as signed comparison when both the
12250 // operands are non-negative or negative.
12251 if (haveSameSign(FoundLHS, FoundRHS))
12252 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12253 // Canonicalize both conditions to "le/lt".
12256 FoundPred = ICmpInst::getSwappedCmpPredicate(FoundPred);
12257 std::swap(LHS, RHS);
12258 std::swap(FoundLHS, FoundRHS);
12259 }
12260 assert((ICmpInst::isLT(Pred) || ICmpInst::isLE(Pred)) && "Must be!");
12261 assert((ICmpInst::isLT(FoundPred) || ICmpInst::isLE(FoundPred)) &&
12262 "Must be!");
12263 if (ICmpInst::isSigned(Pred)) {
12264 // Use implication:
12265 // x <u y && y <=u 2^(n-1) --> x >=s 0,
12266 // x <=u y && y <u 2^(n-1) --> x >=s 0,
12267 // where n is the bit width of x and y.
12268 // In both cases x <u 2^(n-1), so x >=s 0.
12269 // y <=u 2^(n-1) means y >=s 0 or y == INT_MIN.
12270 // If the implication's left part holds, try proving the query from x >=s
12271 // 0.
12272 Type *Ty = FoundLHS->getType();
12273 unsigned BitWidth = getTypeSizeInBits(Ty);
12274 const SCEV *SignedMin = getConstant(APInt::getSignedMinValue(BitWidth));
12275 CmpPredicate BoundPred =
12277 if (isKnownViaNonRecursiveReasoning(BoundPred, FoundRHS, SignedMin)) {
12278 // x >=s 0, written as 0 <=s x, or as -1 <s x to match a strict query.
12279 const SCEV *Bound = ICmpInst::isLE(Pred) ? getZero(Ty) : getMinusOne(Ty);
12280 if (isImpliedCondOperands(Pred, LHS, RHS, Bound, FoundLHS, CtxI))
12281 return true;
12282 }
12283 }
12285 // Use implication:
12286 // x <u y && y >=s 0 --> x <s y.
12287 // If we can prove the left part, the right part is also proven.
12288 return isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS);
12289 }
12291 // Use implication:
12292 // x <s y && y <s 0 --> x <u y.
12293 // If we can prove the left part, the right part is also proven.
12294 return isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS);
12295 }
12296 return false;
12297}
12298
12299bool ScalarEvolution::splitBinaryAdd(SCEVUse Expr, SCEVUse &L, SCEVUse &R,
12300 SCEVFlags &Flags) {
12301 if (!match(Expr, m_scev_Add(m_SCEV(L), m_SCEV(R))))
12302 return false;
12303
12304 Flags = cast<SCEVAddExpr>(Expr)->getNoWrapFlags();
12305 return true;
12306}
12307
12308std::optional<APInt>
12310 // We avoid subtracting expressions here because this function is usually
12311 // fairly deep in the call stack (i.e. is called many times).
12312
12313 unsigned BW = getTypeSizeInBits(More->getType());
12314 APInt Diff(BW, 0);
12315 APInt DiffMul(BW, 1);
12316 // Try various simplifications to reduce the difference to a constant. Limit
12317 // the number of allowed simplifications to keep compile-time low.
12318 for (unsigned I = 0; I < 8; ++I) {
12319 if (More == Less)
12320 return Diff;
12321
12322 // Reduce addrecs with identical steps to their start value.
12324 const auto *LAR = cast<SCEVAddRecExpr>(Less);
12325 const auto *MAR = cast<SCEVAddRecExpr>(More);
12326
12327 if (LAR->getLoop() != MAR->getLoop())
12328 return std::nullopt;
12329
12330 // We look at affine expressions only; not for correctness but to keep
12331 // getStepRecurrence cheap.
12332 if (!LAR->isAffine() || !MAR->isAffine())
12333 return std::nullopt;
12334
12335 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
12336 return std::nullopt;
12337
12338 Less = LAR->getStart();
12339 More = MAR->getStart();
12340 continue;
12341 }
12342
12343 // Try to match a common constant multiply.
12344 auto MatchConstMul =
12345 [](const SCEV *S) -> std::optional<std::pair<const SCEV *, APInt>> {
12346 const APInt *C;
12347 const SCEV *Op;
12348 if (match(S, m_scev_Mul(m_scev_APInt(C), m_SCEV(Op))))
12349 return {{Op, *C}};
12350 return std::nullopt;
12351 };
12352 if (auto MatchedMore = MatchConstMul(More)) {
12353 if (auto MatchedLess = MatchConstMul(Less)) {
12354 if (MatchedMore->second == MatchedLess->second) {
12355 More = MatchedMore->first;
12356 Less = MatchedLess->first;
12357 DiffMul *= MatchedMore->second;
12358 continue;
12359 }
12360 }
12361 }
12362
12363 // Try to cancel out common factors in two add expressions.
12365 auto Add = [&](const SCEV *S, int Mul) {
12366 if (auto *C = dyn_cast<SCEVConstant>(S)) {
12367 if (Mul == 1) {
12368 Diff += C->getAPInt() * DiffMul;
12369 } else {
12370 assert(Mul == -1);
12371 Diff -= C->getAPInt() * DiffMul;
12372 }
12373 } else
12374 Multiplicity[S] += Mul;
12375 };
12376 auto Decompose = [&](const SCEV *S, int Mul) {
12377 if (isa<SCEVAddExpr>(S)) {
12378 for (const SCEV *Op : S->operands())
12379 Add(Op, Mul);
12380 } else
12381 Add(S, Mul);
12382 };
12383 Decompose(More, 1);
12384 Decompose(Less, -1);
12385
12386 // Check whether all the non-constants cancel out, or reduce to new
12387 // More/Less values.
12388 const SCEV *NewMore = nullptr, *NewLess = nullptr;
12389 for (const auto &[S, Mul] : Multiplicity) {
12390 if (Mul == 0)
12391 continue;
12392 if (Mul == 1) {
12393 if (NewMore)
12394 return std::nullopt;
12395 NewMore = S;
12396 } else if (Mul == -1) {
12397 if (NewLess)
12398 return std::nullopt;
12399 NewLess = S;
12400 } else
12401 return std::nullopt;
12402 }
12403
12404 // Values stayed the same, no point in trying further.
12405 if (NewMore == More || NewLess == Less)
12406 return std::nullopt;
12407
12408 More = NewMore;
12409 Less = NewLess;
12410
12411 // Reduced to constant.
12412 if (!More && !Less)
12413 return Diff;
12414
12415 // Left with variable on only one side, bail out.
12416 if (!More || !Less)
12417 return std::nullopt;
12418 }
12419
12420 // Did not reduce to constant.
12421 return std::nullopt;
12422}
12423
12424bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
12425 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12426 const SCEV *FoundRHS, const Instruction *CtxI) {
12427 // Try to recognize the following pattern:
12428 //
12429 // FoundRHS = ...
12430 // ...
12431 // loop:
12432 // FoundLHS = {Start,+,W}
12433 // context_bb: // Basic block from the same loop
12434 // known(Pred, FoundLHS, FoundRHS)
12435 //
12436 // If some predicate is known in the context of a loop, it is also known on
12437 // each iteration of this loop, including the first iteration. Therefore, in
12438 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
12439 // prove the original pred using this fact.
12440 if (!CtxI)
12441 return false;
12442 const BasicBlock *ContextBB = CtxI->getParent();
12443 // Make sure AR varies in the context block.
12444 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
12445 const Loop *L = AR->getLoop();
12446 const auto *Latch = L->getLoopLatch();
12447 // Make sure that context belongs to the loop and executes on 1st iteration
12448 // (if it ever executes at all).
12449 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12450 return false;
12451 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
12452 return false;
12453 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
12454 }
12455
12456 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
12457 const Loop *L = AR->getLoop();
12458 const auto *Latch = L->getLoopLatch();
12459 // Make sure that context belongs to the loop and executes on 1st iteration
12460 // (if it ever executes at all).
12461 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12462 return false;
12463 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
12464 return false;
12465 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
12466 }
12467
12468 return false;
12469}
12470
12471bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(CmpPredicate Pred,
12472 const SCEV *LHS,
12473 const SCEV *RHS,
12474 const SCEV *FoundLHS,
12475 const SCEV *FoundRHS) {
12477 return false;
12478
12479 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
12480 if (!AddRecLHS)
12481 return false;
12482
12483 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12484 if (!AddRecFoundLHS)
12485 return false;
12486
12487 // We'd like to let SCEV reason about control dependencies, so we constrain
12488 // both the inequalities to be about add recurrences on the same loop. This
12489 // way we can use isLoopEntryGuardedByCond later.
12490
12491 const Loop *L = AddRecFoundLHS->getLoop();
12492 if (L != AddRecLHS->getLoop())
12493 return false;
12494
12495 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
12496 //
12497 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
12498 // ... (2)
12499 //
12500 // Informal proof for (2), assuming (1) [*]:
12501 //
12502 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
12503 //
12504 // Then
12505 //
12506 // FoundLHS s< FoundRHS s< INT_MIN - C
12507 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
12508 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
12509 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
12510 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
12511 // <=> FoundLHS + C s< FoundRHS + C
12512 //
12513 // [*]: (1) can be proved by ruling out overflow.
12514 //
12515 // [**]: This can be proved by analyzing all the four possibilities:
12516 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
12517 // (A s>= 0, B s>= 0).
12518 //
12519 // Note:
12520 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
12521 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
12522 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
12523 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
12524 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
12525 // C)".
12526
12527 std::optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
12528 if (!LDiff)
12529 return false;
12530 std::optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
12531 if (!RDiff || *LDiff != *RDiff)
12532 return false;
12533
12534 if (LDiff->isMinValue())
12535 return true;
12536
12537 APInt FoundRHSLimit;
12538
12539 if (Pred == CmpInst::ICMP_ULT) {
12540 FoundRHSLimit = -(*RDiff);
12541 } else {
12542 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
12543 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
12544 }
12545
12546 // Try to prove (1) or (2), as needed.
12547 return isAvailableAtLoopEntry(FoundRHS, L) &&
12548 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
12549 getConstant(FoundRHSLimit));
12550}
12551
12552bool ScalarEvolution::isImpliedViaMerge(CmpPredicate Pred, const SCEV *LHS,
12553 const SCEV *RHS, const SCEV *FoundLHS,
12554 const SCEV *FoundRHS, unsigned Depth) {
12555 const PHINode *LPhi = nullptr, *RPhi = nullptr;
12556
12557 llvm::scope_exit ClearOnExit([&]() {
12558 if (LPhi) {
12559 bool Erased = PendingMerges.erase(LPhi);
12560 assert(Erased && "Failed to erase LPhi!");
12561 (void)Erased;
12562 }
12563 if (RPhi) {
12564 bool Erased = PendingMerges.erase(RPhi);
12565 assert(Erased && "Failed to erase RPhi!");
12566 (void)Erased;
12567 }
12568 });
12569
12570 // Find respective Phis and check that they are not being pending.
12571 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
12572 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
12573 if (!PendingMerges.insert(Phi).second)
12574 return false;
12575 LPhi = Phi;
12576 }
12577 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
12578 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
12579 // If we detect a loop of Phi nodes being processed by this method, for
12580 // example:
12581 //
12582 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
12583 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
12584 //
12585 // we don't want to deal with a case that complex, so return conservative
12586 // answer false.
12587 if (!PendingMerges.insert(Phi).second)
12588 return false;
12589 RPhi = Phi;
12590 }
12591
12592 // If none of LHS, RHS is a Phi, nothing to do here.
12593 if (!LPhi && !RPhi)
12594 return false;
12595
12596 // If there is a SCEVUnknown Phi we are interested in, make it left.
12597 if (!LPhi) {
12598 std::swap(LHS, RHS);
12599 std::swap(FoundLHS, FoundRHS);
12600 std::swap(LPhi, RPhi);
12602 }
12603
12604 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
12605 const BasicBlock *LBB = LPhi->getParent();
12606 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12607
12608 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
12609 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
12610 isImpliedCondOperandsViaRanges(Pred, S1, S2, Pred, FoundLHS, FoundRHS) ||
12611 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
12612 };
12613
12614 if (RPhi && RPhi->getParent() == LBB) {
12615 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
12616 // If we compare two Phis from the same block, and for each entry block
12617 // the predicate is true for incoming values from this block, then the
12618 // predicate is also true for the Phis.
12619 for (const BasicBlock *IncBB : predecessors(LBB)) {
12620 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12621 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
12622 if (!ProvedEasily(L, R))
12623 return false;
12624 }
12625 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
12626 // Case two: RHS is also a Phi from the same basic block, and it is an
12627 // AddRec. It means that there is a loop which has both AddRec and Unknown
12628 // PHIs, for it we can compare incoming values of AddRec from above the loop
12629 // and latch with their respective incoming values of LPhi.
12630 // TODO: Generalize to handle loops with many inputs in a header.
12631 if (LPhi->getNumIncomingValues() != 2) return false;
12632
12633 auto *RLoop = RAR->getLoop();
12634 auto *Predecessor = RLoop->getLoopPredecessor();
12635 assert(Predecessor && "Loop with AddRec with no predecessor?");
12636 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
12637 if (!ProvedEasily(L1, RAR->getStart()))
12638 return false;
12639 auto *Latch = RLoop->getLoopLatch();
12640 assert(Latch && "Loop with AddRec with no latch?");
12641 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
12642 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
12643 return false;
12644 } else {
12645 // In all other cases go over inputs of LHS and compare each of them to RHS,
12646 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
12647 // At this point RHS is either a non-Phi, or it is a Phi from some block
12648 // different from LBB.
12649 for (const BasicBlock *IncBB : predecessors(LBB)) {
12650 // Check that RHS is available in this block.
12651 if (!dominates(RHS, IncBB))
12652 return false;
12653 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12654 // Make sure L does not refer to a value from a potentially previous
12655 // iteration of a loop.
12656 if (!properlyDominates(L, LBB))
12657 return false;
12658 // Addrecs are considered to properly dominate their loop, so are missed
12659 // by the previous check. Discard any values that have computable
12660 // evolution in this loop.
12661 if (auto *Loop = LI.getLoopFor(LBB))
12663 return false;
12664 if (!ProvedEasily(L, RHS))
12665 return false;
12666 }
12667 }
12668 return true;
12669}
12670
12671bool ScalarEvolution::isImpliedCondOperandsViaShift(CmpPredicate Pred,
12672 const SCEV *LHS,
12673 const SCEV *RHS,
12674 const SCEV *FoundLHS,
12675 const SCEV *FoundRHS) {
12676 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make
12677 // sure that we are dealing with same LHS.
12678 if (RHS == FoundRHS) {
12679 std::swap(LHS, RHS);
12680 std::swap(FoundLHS, FoundRHS);
12682 }
12683 if (LHS != FoundLHS)
12684 return false;
12685
12686 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
12687 if (!SUFoundRHS)
12688 return false;
12689
12690 Value *Shiftee, *ShiftValue;
12691
12692 using namespace PatternMatch;
12693 if (match(SUFoundRHS->getValue(),
12694 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
12695 auto *ShifteeS = getSCEV(Shiftee);
12696 // Prove one of the following:
12697 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
12698 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
12699 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12700 // ---> LHS <s RHS
12701 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12702 // ---> LHS <=s RHS
12704 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
12706 if (isKnownNonNegative(ShifteeS))
12707 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
12708 }
12709
12710 return false;
12711}
12712
12713bool ScalarEvolution::isImpliedCondOperandsViaMatchingDiff(
12714 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12715 const SCEV *FoundRHS) {
12716 // Only valid for equality predicates: (A == B) implies (C == D) when
12717 // the SCEV difference A - B equals C - D (they check the same
12718 // underlying relationship at every iteration).
12720 return false;
12721
12722 // Restrict to cases involving loop recurrences - that's where this
12723 // pattern arises (correlated IV comparisons). This avoids calling
12724 // getMinusSCEV on arbitrary non-loop expressions.
12726 (!isa<SCEVAddRecExpr>(FoundLHS) && !isa<SCEVAddRecExpr>(FoundRHS)))
12727 return false;
12728
12729 // AddRecs from different loops can never produce matching differences.
12730 const SCEVAddRecExpr *QueryAddRec = dyn_cast<SCEVAddRecExpr>(LHS);
12731 if (!QueryAddRec)
12732 QueryAddRec = cast<SCEVAddRecExpr>(RHS);
12733 const SCEVAddRecExpr *FoundAddRec = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12734 if (!FoundAddRec)
12735 FoundAddRec = cast<SCEVAddRecExpr>(FoundRHS);
12736 if (QueryAddRec->getLoop() != FoundAddRec->getLoop())
12737 return false;
12738
12739 // If the strides differ, the differences can never match.
12740 if (QueryAddRec->getStepRecurrence(*this) !=
12741 FoundAddRec->getStepRecurrence(*this))
12742 return false;
12743
12744 // Compute differences. For pointer-typed operands sharing the same base,
12745 // getMinusSCEV strips the common base and returns an integer SCEV.
12746 // For example, {base,+,8} - (base+8*n) = {-8n,+,8}
12747 const SCEV *FoundDiff = getMinusSCEV(FoundLHS, FoundRHS);
12748 if (isa<SCEVCouldNotCompute>(FoundDiff))
12749 return false;
12750
12751 const SCEV *Diff = getMinusSCEV(LHS, RHS);
12752 if (isa<SCEVCouldNotCompute>(Diff))
12753 return false;
12754
12755 return Diff == FoundDiff;
12756}
12757
12758bool ScalarEvolution::isImpliedCondOperands(CmpPredicate Pred, const SCEV *LHS,
12759 const SCEV *RHS,
12760 const SCEV *FoundLHS,
12761 const SCEV *FoundRHS,
12762 const Instruction *CtxI) {
12763 return isImpliedCondOperandsViaRanges(Pred, LHS, RHS, Pred, FoundLHS,
12764 FoundRHS) ||
12765 isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS,
12766 FoundRHS) ||
12767 isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS) ||
12768 isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12769 CtxI) ||
12770 isImpliedCondOperandsViaMatchingDiff(Pred, LHS, RHS, FoundLHS,
12771 FoundRHS) ||
12772 isImpliedCondOperandsHelper(Pred, LHS, RHS, FoundLHS, FoundRHS);
12773}
12774
12775/// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
12776template <typename MinMaxExprType>
12777static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
12778 const SCEV *Candidate) {
12779 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12780 if (!MinMaxExpr)
12781 return false;
12782
12783 return is_contained(MinMaxExpr->operands(), Candidate);
12784}
12785
12787 CmpPredicate Pred, const SCEV *LHS,
12788 const SCEV *RHS) {
12789 // If both sides are affine addrecs for the same loop, with equal
12790 // steps, and we know the recurrences don't wrap, then we only
12791 // need to check the predicate on the starting values.
12792
12794 return false;
12795
12796 const SCEV *LStart, *RStart, *Step;
12797 const Loop *L;
12798 if (!match(LHS,
12799 m_scev_AffineAddRec(m_SCEV(LStart), m_SCEV(Step), m_Loop(L))) ||
12801 m_SpecificLoop(L))))
12802 return false;
12806 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
12807 return false;
12808
12809 return SE.isKnownPredicate(Pred, LStart, RStart);
12810}
12811
12812/// Is LHS `Pred` RHS true because one of them is an AddRec that is known not to
12813/// go below its own start value?
12816 const SCEV *LHS,
12817 const SCEV *RHS) {
12818 // Normalize to (AddRec Pred Start).
12821 std::swap(LHS, RHS);
12822 }
12823
12824 // The recurrence is equal to Start in the first iteration, so only the
12825 // non-strict predicate holds.
12827 return false;
12828
12829 const auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
12830 if (!AR || AR->getStart() != RHS)
12831 return false;
12832
12833 return SE.getMonotonicPredicateType(AR, Pred) ==
12835}
12836
12837/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
12838/// expression?
12840 const SCEV *LHS, const SCEV *RHS) {
12841 switch (Pred) {
12842 default:
12843 return false;
12844
12845 case ICmpInst::ICMP_SGE:
12846 std::swap(LHS, RHS);
12847 [[fallthrough]];
12848 case ICmpInst::ICMP_SLE:
12849 return
12850 // min(A, ...) <= A
12852 // A <= max(A, ...)
12854
12855 case ICmpInst::ICMP_UGE:
12856 std::swap(LHS, RHS);
12857 [[fallthrough]];
12858 case ICmpInst::ICMP_ULE:
12859 return
12860 // min(A, ...) <= A
12861 // FIXME: what about umin_seq?
12863 // A <= max(A, ...)
12865
12866 case ICmpInst::ICMP_UGT:
12867 std::swap(LHS, RHS);
12868 [[fallthrough]];
12869 case ICmpInst::ICMP_ULT:
12870 // umin(Ops) u<= each Op, so proving Op u< RHS for any Op proves
12871 // umin(Ops) u< RHS.
12872 //
12873 // Use computeConstantDifference instead of the more powerful
12874 // isKnownPredicate to keep this check cheap: isKnownPredicateViaMinOrMax
12875 // is called from isKnownViaNonRecursiveReasoning, so recursing into
12876 // the full predicate prover would be expensive.
12877 if (const auto *Min = dyn_cast<SCEVUMinExpr>(LHS)) {
12878 for (SCEVUse Op : Min->operands()) {
12879 std::optional<APInt> Diff = SE.computeConstantDifference(RHS, Op);
12880 // When Op and RHS share a common base differing by a
12881 // constant offset D (RHS - Op = D), Op u< RHS holds iff D != 0 and
12882 // RHS >= D (unsigned), i.e. the subtraction doesn't underflow.
12883 if (Diff && !Diff->isZero() && SE.getUnsignedRangeMin(RHS).uge(*Diff))
12884 return true;
12885 }
12886 }
12887 return false;
12888 }
12889
12890 llvm_unreachable("covered switch fell through?!");
12891}
12892
12893bool ScalarEvolution::isImpliedViaOperations(CmpPredicate Pred, const SCEV *LHS,
12894 const SCEV *RHS,
12895 const SCEV *FoundLHS,
12896 const SCEV *FoundRHS,
12897 unsigned Depth) {
12900 "LHS and RHS have different sizes?");
12901 assert(getTypeSizeInBits(FoundLHS->getType()) ==
12902 getTypeSizeInBits(FoundRHS->getType()) &&
12903 "FoundLHS and FoundRHS have different sizes?");
12904 // We want to avoid hurting the compile time with analysis of too big trees.
12905 if (Depth > Opts.scalar_evolution_max_scev_operations_implication_depth)
12906 return false;
12907
12908 // We only want to work with GT comparison so far.
12909 if (ICmpInst::isLT(Pred)) {
12911 std::swap(LHS, RHS);
12912 std::swap(FoundLHS, FoundRHS);
12913 }
12914
12915 CmpInst::Predicate P = Pred.getPreferredSignedPredicate();
12916
12917 // For unsigned, try to reduce it to corresponding signed comparison.
12918 if (P == ICmpInst::ICMP_UGT)
12919 // We can replace unsigned predicate with its signed counterpart if all
12920 // involved values are non-negative.
12921 // TODO: We could have better support for unsigned.
12922 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
12923 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
12924 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
12925 // use this fact to prove that LHS and RHS are non-negative.
12926 const SCEV *MinusOne = getMinusOne(LHS->getType());
12927 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
12928 FoundRHS) &&
12929 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
12930 FoundRHS))
12932 }
12933
12934 if (P != ICmpInst::ICMP_SGT)
12935 return false;
12936
12937 auto GetOpFromSExt = [&](const SCEV *S) -> const SCEV * {
12938 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
12939 return Ext->getOperand();
12940 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
12941 // the constant in some cases.
12942 return S;
12943 };
12944
12945 // Acquire values from extensions.
12946 auto *OrigLHS = LHS;
12947 auto *OrigFoundLHS = FoundLHS;
12948 LHS = GetOpFromSExt(LHS);
12949 FoundLHS = GetOpFromSExt(FoundLHS);
12950
12951 // Is the SGT predicate can be proved trivially or using the found context.
12952 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
12953 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
12954 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
12955 FoundRHS, Depth + 1);
12956 };
12957
12958 SCEVUse LL;
12959 SCEVUse LR;
12960 if (match(LHS, m_scev_NSWAdd(m_SCEV(LL), m_SCEV(LR)))) {
12961 // We want to avoid creation of any new non-constant SCEV. Since we are
12962 // going to compare the operands to RHS, we should be certain that we don't
12963 // need any size extensions for this. So let's decline all cases when the
12964 // sizes of types of LHS and RHS do not match.
12965 // TODO: Maybe try to get RHS from sext to catch more cases?
12967 return false;
12968
12969 auto *MinusOne = getMinusOne(RHS->getType());
12970
12971 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
12972 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
12973 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
12974 };
12975 // Try to prove the following rule:
12976 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
12977 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
12978 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
12979 return true;
12980 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
12981 Value *LL, *LR;
12982 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
12983
12984 using namespace llvm::PatternMatch;
12985
12986 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
12987 // Rules for division.
12988 // We are going to perform some comparisons with Denominator and its
12989 // derivative expressions. In general case, creating a SCEV for it may
12990 // lead to a complex analysis of the entire graph, and in particular it
12991 // can request trip count recalculation for the same loop. This would
12992 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
12993 // this, we only want to create SCEVs that are constants in this section.
12994 // So we bail if Denominator is not a constant.
12995 if (!isa<ConstantInt>(LR))
12996 return false;
12997
12998 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
12999
13000 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
13001 // then a SCEV for the numerator already exists and matches with FoundLHS.
13002 auto *Numerator = getExistingSCEV(LL);
13003 if (!Numerator || Numerator->getType() != FoundLHS->getType())
13004 return false;
13005
13006 // Make sure that the numerator matches with FoundLHS and the denominator
13007 // is positive.
13008 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
13009 return false;
13010
13011 auto *DTy = Denominator->getType();
13012 auto *FRHSTy = FoundRHS->getType();
13013 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
13014 // One of types is a pointer and another one is not. We cannot extend
13015 // them properly to a wider type, so let us just reject this case.
13016 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
13017 // to avoid this check.
13018 return false;
13019
13020 // Given that:
13021 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
13022 auto *WTy = getWiderType(DTy, FRHSTy);
13023 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
13024 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
13025
13026 // Try to prove the following rule:
13027 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
13028 // For example, given that FoundLHS > 2. It means that FoundLHS is at
13029 // least 3. If we divide it by Denominator < 4, we will have at least 1.
13030 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
13031 if (isKnownNonPositive(RHS) &&
13032 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
13033 return true;
13034
13035 // Try to prove the following rule:
13036 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
13037 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
13038 // If we divide it by Denominator > 2, then:
13039 // 1. If FoundLHS is negative, then the result is 0.
13040 // 2. If FoundLHS is non-negative, then the result is non-negative.
13041 // Anyways, the result is non-negative.
13042 auto *MinusOne = getMinusOne(WTy);
13043 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
13044 if (isKnownNegative(RHS) &&
13045 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
13046 return true;
13047 }
13048 }
13049
13050 // If our expression contained SCEVUnknown Phis, and we split it down and now
13051 // need to prove something for them, try to prove the predicate for every
13052 // possible incoming values of those Phis.
13053 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
13054 return true;
13055
13056 return false;
13057}
13058
13060 const SCEV *RHS) {
13061 // zext x u<= sext x, sext x s<= zext x
13062 const SCEV *Op;
13063 switch (Pred) {
13064 case ICmpInst::ICMP_SGE:
13065 std::swap(LHS, RHS);
13066 [[fallthrough]];
13067 case ICmpInst::ICMP_SLE: {
13068 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt.
13069 return match(LHS, m_scev_SExt(m_SCEV(Op))) &&
13071 }
13072 case ICmpInst::ICMP_UGE:
13073 std::swap(LHS, RHS);
13074 [[fallthrough]];
13075 case ICmpInst::ICMP_ULE: {
13076 // If operand >=u 0 then ZExt == SExt. If operand <u 0 then ZExt <u SExt.
13077 return match(LHS, m_scev_ZExt(m_SCEV(Op))) &&
13079 }
13080 default:
13081 return false;
13082 };
13083 llvm_unreachable("unhandled case");
13084}
13085
13086bool ScalarEvolution::isKnownViaNonRecursiveReasoning(CmpPredicate Pred,
13087 SCEVUse LHS,
13088 SCEVUse RHS) {
13090 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
13094 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
13095}
13096
13097bool ScalarEvolution::isImpliedCondOperandsHelper(CmpPredicate Pred,
13098 const SCEV *LHS,
13099 const SCEV *RHS,
13100 const SCEV *FoundLHS,
13101 const SCEV *FoundRHS) {
13103 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
13104 return true;
13105 } else {
13107 if (isKnownViaNonRecursiveReasoning(NonStrictPred, LHS, FoundLHS) &&
13108 isKnownViaNonRecursiveReasoning(
13109 ICmpInst::getSwappedPredicate(NonStrictPred), RHS, FoundRHS))
13110 return true;
13111 }
13112
13113 // Maybe it can be proved via operations?
13114 return isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS);
13115}
13116
13117bool ScalarEvolution::isImpliedCondOperandsViaRanges(
13118 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, CmpPredicate FoundPred,
13119 const SCEV *FoundLHS, const SCEV *FoundRHS) {
13120 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
13121 // The restriction on `FoundRHS` be lifted easily -- it exists only to
13122 // reduce the compile time impact of this optimization.
13123 return false;
13124
13125 std::optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
13126 if (!Addend)
13127 return false;
13128
13129 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
13130
13131 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
13132 // antecedent "`FoundLHS` `FoundPred` `FoundRHS`".
13133 ConstantRange FoundLHSRange =
13134 ConstantRange::makeExactICmpRegion(FoundPred, ConstFoundRHS);
13135
13136 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
13137 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
13138
13139 // We can also compute the range of values for `LHS` that satisfy the
13140 // consequent, "`LHS` `Pred` `RHS`":
13141 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
13142 // The antecedent implies the consequent if every value of `LHS` that
13143 // satisfies the antecedent also satisfies the consequent.
13144 return LHSRange.icmp(Pred, ConstRHS);
13145}
13146
13147bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
13148 bool IsSigned, bool Invert) {
13149 assert(isKnownPositive(Stride) && "Positive stride expected!");
13150
13151 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13152 const SCEV *One = getOne(Stride->getType());
13153
13154 if (IsSigned) {
13155 APInt MaxRHS = getRangeMax(RHS, /*IsSigned=*/true, Invert);
13156 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
13157 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13158
13159 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
13160 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
13161 }
13162
13163 APInt MaxRHS = getRangeMax(RHS, /*IsSigned=*/false, Invert);
13164 APInt MaxValue = APInt::getMaxValue(BitWidth);
13165 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13166
13167 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
13168 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
13169}
13170
13172 // umin(N, 1) + floor((N - umin(N, 1)) / D)
13173 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
13174 // expression fixes the case of N=0.
13175 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
13176 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
13177 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
13178}
13179
13180const SCEV *
13181ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, const SCEV *Stride,
13182 const SCEV *End, unsigned BitWidth,
13183 bool IsSigned, bool Invert) {
13184 // The logic in this function assumes we can represent a positive stride.
13185 // If we can't, the backedge-taken count must be zero.
13186 if (IsSigned && BitWidth == 1)
13187 return getZero(Stride->getType());
13188
13189 // This code below only been closely audited for negative strides in the
13190 // unsigned comparison case, it may be correct for signed comparison, but
13191 // that needs to be established.
13192 if (IsSigned && isKnownNegative(Stride))
13193 return getCouldNotCompute();
13194
13195 // Calculate the maximum backedge count based on the range of values
13196 // permitted by Start, End, and Stride. If Invert is true, both Start and End
13197 // need inverting. Stride was already negated by the caller.
13198 APInt MinStart = getRangeMin(Start, IsSigned, Invert);
13199
13200 APInt MinStride =
13201 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
13202
13203 // We assume either the stride is positive, or the backedge-taken count
13204 // is zero. So force StrideForMaxBECount to be at least one.
13205 APInt One(BitWidth, 1);
13206 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
13207 : APIntOps::umax(One, MinStride);
13208
13209 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
13210 : APInt::getMaxValue(BitWidth);
13211 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
13212
13213 // Although End can be a MAX expression we estimate MaxEnd considering only
13214 // the case End = RHS of the loop termination condition. This is safe because
13215 // in the other case (End - Start) is zero, leading to a zero maximum backedge
13216 // taken count.
13217 APInt MaxEnd = getRangeMax(End, IsSigned, Invert);
13218 MaxEnd =
13219 IsSigned ? APIntOps::smin(MaxEnd, Limit) : APIntOps::umin(MaxEnd, Limit);
13220
13221 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
13222 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
13223 : APIntOps::umax(MaxEnd, MinStart);
13224
13225 APInt Delta = MaxEnd - MinStart;
13226
13227 // Try to refine Delta in case End - Start (or Start - End if Invert) gives a
13228 // tighter bound after folding.
13229 const SCEV *DeltaExpr =
13230 Invert ? getMinusSCEV(Start, End) : getMinusSCEV(End, Start);
13231 Delta = APIntOps::umin(Delta, getUnsignedRangeMax(DeltaExpr));
13232
13233 return getUDivCeilSCEV(getConstant(Delta), getConstant(StrideForMaxBECount));
13234}
13235
13237ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
13238 const Loop *L, bool IsSigned, bool Invert,
13239 bool ControlsOnlyExit, bool AllowPredicates) {
13241
13242 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
13243
13244 // FIXME: Extend the non-invariant RHS analysis to greater-than comparisons.
13245 if (Invert && !isLoopInvariant(RHS, L))
13246 return getCouldNotCompute();
13247
13249 bool PredicatedIV = false;
13250 // FIXME: Generalize the NUW inference below to decreasing IVs.
13251 if (!IV && !Invert) {
13252 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
13253 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
13254 if (AR && AR->getLoop() == L && AR->isAffine()) {
13255 auto canProveNUW = [&]() {
13256 // We can use the comparison to infer no-wrap flags only if it fully
13257 // controls the loop exit.
13258 if (!ControlsOnlyExit)
13259 return false;
13260
13261 if (!isLoopInvariant(RHS, L))
13262 return false;
13263
13264 if (!isKnownNonZero(AR->getStepRecurrence(*this)))
13265 // We need the sequence defined by AR to strictly increase in the
13266 // unsigned integer domain for the logic below to hold.
13267 return false;
13268
13269 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
13270 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
13271 // If RHS <=u Limit, then there must exist a value V in the sequence
13272 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
13273 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned
13274 // overflow occurs. This limit also implies that a signed comparison
13275 // (in the wide bitwidth) is equivalent to an unsigned comparison as
13276 // the high bits on both sides must be zero.
13277 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
13278 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
13279 Limit = Limit.zext(OuterBitWidth);
13280 return getUnsignedRangeMax(applyLoopGuards(RHS, Guards)).ule(Limit);
13281 };
13282 auto Flags = AR->getNoWrapFlags();
13283 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
13284 Flags = setFlags(Flags, SCEV::FlagNUW);
13285
13286 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
13287 if (AR->hasNoUnsignedWrap()) {
13288 // Emulate what getZeroExtendExpr would have done during construction
13289 // if we'd been able to infer the fact just above at that time.
13290 const SCEV *Step = AR->getStepRecurrence(*this);
13291 Type *Ty = ZExt->getType();
13292 const SCEV *S = getAddRecExpr(
13294 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
13296 }
13297 }
13298 }
13299 }
13300
13301 if (!IV && AllowPredicates) {
13302 // Try to make this an AddRec using runtime tests, in the first X
13303 // iterations of this loop, where X is the SCEV expression found by the
13304 // algorithm below.
13305 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13306 PredicatedIV = true;
13307 }
13308
13309 // Avoid weird loops
13310 if (!IV || IV->getLoop() != L || !IV->isAffine())
13311 return getCouldNotCompute();
13312
13313 // A precondition of this method is that the condition being analyzed
13314 // reaches an exiting branch which dominates the latch. Given that, we can
13315 // assume that an increment which violates the nowrap specification and
13316 // produces poison must cause undefined behavior when the resulting poison
13317 // value is branched upon and thus we can conclude that the backedge is
13318 // taken no more often than would be required to produce that poison value.
13319 // Note that a well defined loop can exit on the iteration which violates
13320 // the nowrap specification if there is another exit (either explicit or
13321 // implicit/exceptional) which causes the loop to execute before the
13322 // exiting instruction we're analyzing would trigger UB.
13323 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13324 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13325 // Reverse the ordering for greater-than comparisons.
13327 if (Invert)
13329
13330 // The step of ~IV is the negated step of IV.
13331 const SCEV *Stride = IV->getStepRecurrence(*this);
13332 if (Invert)
13333 Stride = getNegativeSCEV(Stride);
13334 const SCEV *GuardedStride = Stride;
13335
13336 // Whether the IV may reach the maximum (or minimum if inverted) value
13337 // before the exit is taken.
13338 bool IVMayOverflow = true;
13339
13340 bool PositiveStride = isKnownPositive(Stride);
13341 // A dominating guard may prove the stride positive.
13342 if (!PositiveStride) {
13343 const SCEV *LoopGuardedStride = applyLoopGuards(Stride, Guards);
13344 if (isKnownPositive(LoopGuardedStride)) {
13345 GuardedStride = LoopGuardedStride;
13346 PositiveStride = true;
13347 // Encode the context-sensitive stride > 0 fact into the expression
13348 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13349 }
13350 }
13351
13352 // Avoid negative or zero stride values.
13353 if (!PositiveStride) {
13354 // FIXME: Generalize the unknown-stride analysis to decreasing IVs.
13355 if (Invert)
13356 return getCouldNotCompute();
13357
13358 // We can compute the correct backedge taken count for loops with unknown
13359 // strides if we can prove that the loop is not an infinite loop with side
13360 // effects. Here's the loop structure we are trying to handle -
13361 //
13362 // i = start
13363 // do {
13364 // A[i] = i;
13365 // i += s;
13366 // } while (i < end);
13367 //
13368 // The backedge taken count for such loops is evaluated as -
13369 // (max(end, start + stride) - start - 1) /u stride
13370 //
13371 // The additional preconditions that we need to check to prove correctness
13372 // of the above formula is as follows -
13373 //
13374 // a) IV is either nuw or nsw depending upon signedness (indicated by the
13375 // NoWrap flag).
13376 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13377 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13378 // no side effects within the loop) or a predicate is added to ensure
13379 // stride is positive.
13380 // c) loop has a single static exit (with no abnormal exits)
13381 //
13382 // Precondition a) implies that if the stride is negative, this is a single
13383 // trip loop. The backedge taken count formula reduces to zero in this case.
13384 //
13385 // Precondition b) and c) combine to imply that if rhs is invariant in L,
13386 // then a zero stride means the backedge can't be taken without executing
13387 // undefined behavior.
13388 //
13389 // The positive stride case is the same as isKnownPositive(Stride) returning
13390 // true (original behavior of the function).
13391 //
13392 if (PredicatedIV || !NoWrap || !loopHasNoAbnormalExits(L))
13393 return getCouldNotCompute();
13394
13395 if (!loopIsFiniteByAssumption(L)) {
13396 // If the loop may be infinite, add a predicate ensuring Stride is
13397 // positive, to guarantee forward progress.
13398 if (!AllowPredicates || !isLoopInvariant(Stride, L))
13399 return getCouldNotCompute();
13400
13401 const SCEV *Zero = getZero(Stride->getType());
13402 const SCEVPredicate *P =
13404 Predicates.push_back(P);
13405 // When the predicate holds (Stride > 0), umax(Stride, 1) == Stride,
13406 // so the result is unchanged. To prevent div by zero.
13407 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13408 } else if (!isKnownNonZero(Stride)) {
13409 // If we have a step of zero, and RHS isn't invariant in L, we don't know
13410 // if it might eventually be greater than start and if so, on which
13411 // iteration. We can't even produce a useful upper bound.
13412 if (!isLoopInvariant(RHS, L))
13413 return getCouldNotCompute();
13414
13415 // We allow a potentially zero stride, but we need to divide by stride
13416 // below. Since the loop can't be infinite and this check must control
13417 // the sole exit, we can infer the exit must be taken on the first
13418 // iteration (e.g. backedge count = 0) if the stride is zero. Given that,
13419 // we know the numerator in the divides below must be zero, so we can
13420 // pick an arbitrary non-zero value for the denominator (e.g. stride)
13421 // and produce the right result.
13422 // FIXME: Handle the case where Stride is poison?
13423 auto wouldZeroStrideBeUB = [&]() {
13424 // Proof by contradiction. Suppose the stride were zero. If we can
13425 // prove that the backedge *is* taken on the first iteration, then since
13426 // we know this condition controls the sole exit, we must have an
13427 // infinite loop. We can't have a (well defined) infinite loop per
13428 // check just above.
13429 // Note: The (Start - Stride) term is used to get the start' term from
13430 // (start' + stride,+,stride). Remember that we only care about the
13431 // result of this expression when stride == 0 at runtime.
13432 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
13433 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
13434 };
13435 if (!wouldZeroStrideBeUB()) {
13436 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13437 }
13438 }
13439 } else {
13440 // Avoid proven overflow cases: this will ensure that the backedge taken
13441 // count will not generate any unsigned overflow.
13442 IVMayOverflow = canIVOverflowOnLT(RHS, GuardedStride, IsSigned, Invert) &&
13443 canIVOverflowOnLT(applyLoopGuards(RHS, Guards),
13444 GuardedStride, IsSigned, Invert);
13445 if (IVMayOverflow && !NoWrap)
13446 return getCouldNotCompute();
13447 }
13448
13449 // On all paths just preceeding, we established the following invariant:
13450 // IV can be assumed not to overflow up to and including the exiting
13451 // iteration. We proved this in one of two ways:
13452 // 1) We can show overflow doesn't occur before the exiting iteration
13453 // 1a) canIVOverflowOnLT, and b) step of one
13454 // 2) We can show that if overflow occurs, the loop must execute UB
13455 // before any possible exit.
13456 // Note that we have not yet proved RHS invariant (in general).
13457
13458 const SCEV *Start = IV->getStart();
13459
13460 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
13461 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
13462 // Use integer-typed versions for actual computation; we can't subtract
13463 // pointers in general.
13464 const SCEV *OrigStart = Start;
13465 const SCEV *OrigRHS = RHS;
13466 if (Start->getType()->isPointerTy()) {
13467 Start = getPtrToAddrExpr(Start);
13468 if (isa<SCEVCouldNotCompute>(Start))
13469 return Start;
13470 }
13471 if (RHS->getType()->isPointerTy()) {
13474 return RHS;
13475 }
13476
13477 const SCEV *End = nullptr, *BECount = getCouldNotCompute(),
13478 *BECountIfBackedgeTaken = getCouldNotCompute();
13479 if (!isLoopInvariant(RHS, L)) {
13480 assert(!Invert && "RHS must be loop-invariant for Invert");
13481 const auto *RHSAddRec = dyn_cast<SCEVAddRecExpr>(RHS);
13482 if (PositiveStride && RHSAddRec != nullptr && RHSAddRec->getLoop() == L &&
13483 any(RHSAddRec->getNoWrapFlags())) {
13484 // The structure of loop we are trying to calculate backedge count of:
13485 //
13486 // left = left_start
13487 // right = right_start
13488 //
13489 // while(left < right){
13490 // ... do something here ...
13491 // left += s1; // stride of left is s1 (s1 > 0)
13492 // right += s2; // stride of right is s2 (s2 < 0)
13493 // }
13494 //
13495
13496 const SCEV *RHSStart = RHSAddRec->getStart();
13497 const SCEV *RHSStride = RHSAddRec->getStepRecurrence(*this);
13498
13499 // If Stride - RHSStride is positive and does not overflow, we can write
13500 // backedge count as ->
13501 // ceil((End - Start) /u (Stride - RHSStride))
13502 // Where, End = max(RHSStart, Start)
13503
13504 // Check if RHSStride < 0 and Stride - RHSStride will not overflow.
13505 if (isKnownNegative(RHSStride) &&
13506 willNotOverflow(Instruction::Sub, /*Signed=*/true, Stride,
13507 RHSStride)) {
13508
13509 const SCEV *Denominator = getMinusSCEV(Stride, RHSStride);
13510 if (isKnownPositive(Denominator)) {
13511 End = IsSigned ? getSMaxExpr(RHSStart, Start)
13512 : getUMaxExpr(RHSStart, Start);
13513
13514 // We can do this because End >= Start, as End = max(RHSStart, Start)
13515 const SCEV *Delta = getMinusSCEV(End, Start);
13516
13517 BECount = getUDivCeilSCEV(Delta, Denominator);
13518 BECountIfBackedgeTaken =
13519 getUDivCeilSCEV(getMinusSCEV(RHSStart, Start), Denominator);
13520 }
13521 }
13522 }
13523 } else {
13524 // Let End = max(RHS,Start). We use the expression (End-Start)/Stride to
13525 // describe the backedge count: if the backedge is taken at least once then
13526 // End is RHS, and if not End is Start so we get a backedge count of zero.
13527 // Inverted, End is min(RHS, Start).
13528 //
13529 // AddingStrideMinusOneMayOverflow has the following preconditions:
13530 //
13531 // 1. Start <= End, signed if IsSigned (inverted: End <= Start)
13532 // 2. The index variable doesn't overflow.
13533 //
13534 // Therefore, we know N exists such that
13535 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
13536 // doesn't overflow.
13537 //
13538 // Using this information, try to prove whether the addition in
13539 // "(End - Start) + (Stride - 1)" has unsigned overflow.
13540 //
13541 // If the IV cannot overflow, RHS is at least Stride - 1 below the maximum
13542 // value, so the distance End - Start is at most UMAX - (Stride - 1) and
13543 // the (Stride - 1) addition below cannot overflow.
13544 const SCEV *One = getOne(Stride->getType());
13545 bool AddingStrideMinusOneMayOverflow = IVMayOverflow && [&] {
13546 if (isKnownToBeAPowerOfTwo(Stride)) {
13547 // Suppose Stride is a power of two, and Start/End are unsigned
13548 // integers. Let UMAX be the largest representable unsigned
13549 // integer.
13550 //
13551 // By the preconditions of this function, we know
13552 // "(Start + Stride * N) >= End", and this doesn't overflow.
13553 // As a formula:
13554 //
13555 // End <= (Start + Stride * N) <= UMAX
13556 //
13557 // Subtracting Start from all the terms:
13558 //
13559 // End - Start <= Stride * N <= UMAX - Start
13560 //
13561 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore:
13562 //
13563 // End - Start <= Stride * N <= UMAX
13564 //
13565 // Stride * N is a multiple of Stride. Therefore,
13566 //
13567 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
13568 //
13569 // Since Stride is a power of two, UMAX + 1 is divisible by
13570 // Stride. Therefore, UMAX mod Stride == Stride - 1. So we can
13571 // write:
13572 //
13573 // End - Start <= Stride * N <= UMAX - Stride - 1
13574 //
13575 // Dropping the middle term:
13576 //
13577 // End - Start <= UMAX - Stride - 1
13578 //
13579 // Adding Stride - 1 to both sides:
13580 //
13581 // (End - Start) + (Stride - 1) <= UMAX
13582 //
13583 // In other words, the addition doesn't have unsigned overflow.
13584 //
13585 // A similar proof works if we treat Start/End as signed values.
13586 // Just rewrite steps before "End - Start <= Stride * N <= UMAX"
13587 // to use signed max instead of unsigned max. Note that we're
13588 // trying to prove a lack of unsigned overflow in either case.
13589 // Inverted: "Start - End <= Stride * N <= Start - MIN <= UMAX", same.
13590 return false;
13591 }
13592 if (!Invert && (Start == Stride || Start == getMinusSCEV(Stride, One))) {
13593 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End
13594 // - 1. If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1
13595 // <u End. If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End -
13596 // 1 <s End.
13597 //
13598 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 ==
13599 // End.
13600 //
13601 // Both need Start to be the smaller value, so neither applies inverted.
13602 return false;
13603 }
13604 return true;
13605 }();
13606
13607 // If inverted, the analyzed values are complements: "~V - Offset" is "~(V +
13608 // Offset)" and "~To - ~From" is "From - To".
13609 auto StepBack = [&](const SCEV *V, const SCEV *Offset) -> const SCEV * {
13610 if (Invert)
13611 return getAddExpr(V, Offset);
13612 return getMinusSCEV(V, Offset);
13613 };
13614 auto Distance = [&](const SCEV *From, const SCEV *To) {
13615 return Invert ? getMinusSCEV(From, To) : getMinusSCEV(To, From);
13616 };
13617
13618 const SCEV *OrigPrevStart = StepBack(OrigStart, Stride);
13619 assert(isAvailableAtLoopEntry(OrigPrevStart, L) && "Must be!");
13620 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
13621 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
13622 // Can we prove Start - Stride < RHS, and either Start - Stride < Start or
13623 // (via !AddingStrideMinusOneMayOverflow) that (RHS - Start) + (Stride - 1)
13624 // does not overflow?
13625 if ((!AddingStrideMinusOneMayOverflow ||
13626 isLoopEntryGuardedByCond(L, Cond, OrigPrevStart, OrigStart)) &&
13627 isLoopEntryGuardedByCond(L, Cond, OrigPrevStart, OrigRHS)) {
13628 // In this case, we can use a refined formula for computing backedge
13629 // taken count. The general formula remains:
13630 // "End-Start /uceiling Stride"
13631 // We want to use the alternate formula:
13632 // "((RHS - 1) - (Start - Stride)) /u Stride"
13633 // Let's do a quick case analysis to show these are equivalent under
13634 // our preconditions. When inverted, the proof uses complemented Start,
13635 // RHS and End; Stride remains positive.
13636 // * For RHS <= Start (End is Start), the backedge-taken count must be
13637 // zero. Together with the precondition "Start - Stride < RHS", we have
13638 // "Start - Stride < RHS <= Start". Subtracting Start - Stride from
13639 // all sides we get "0 < RHS - (Start - Stride) <= Stride".
13640 // Subtracting 1 we get "0 <= (RHS - 1) - (Start - Stride) < Stride".
13641 // So dividing that by Stride gives zero.
13642 //
13643 // * For RHS > Start (End is RHS), the backedge count must be
13644 // "RHS-Start /uceil Stride", so it is sufficient to show that the
13645 // numerator "((RHS - 1) - (Start - Stride))" does not overflow.
13646 //
13647 // If "Start - Stride < Start" holds, we have
13648 // "RHS > Start > Start - Stride". As such
13649 // "RHS - (Start - Stride) - 1" does not overflow, which is the
13650 // reassociated numerator.
13651 //
13652 // Otherwise !AddingStrideMinusOneMayOverflow guarantees that
13653 // "(End - Start) + (Stride - 1)" does not overflow unsigned. Here
13654 // "End" is "RHS", as "RHS > Start", so this is the reassociated
13655 // numerator. Neither sub-term wraps unsigned: "RHS - Start"
13656 // due to "RHS > Start", and "Stride - 1", as Stride is non-zero.
13657 const SCEV *Numerator =
13658 getMinusSCEV(Distance(StepBack(Start, Stride), RHS), One);
13659 BECount = getUDivExpr(Numerator, Stride);
13660 }
13661
13662 if (isa<SCEVCouldNotCompute>(BECount)) {
13663 auto canProveRHSIsAtOrBeyondStart = [&]() {
13664 // Inverted, the claim is "Start >= RHS". Reverse the comparisons below
13665 // by swapping their operands rather than their predicates:
13666 // isLoopEntryGuardedByCond is sensitive to operand order and loses the
13667 // proof if the IV bound moves to the other side.
13668 auto SwapIfInverted = [&](const SCEV *A, const SCEV *B) {
13669 return Invert ? std::pair(B, A) : std::pair(A, B);
13670 };
13671
13672 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
13673 const SCEV *GuardedRHS = applyLoopGuards(OrigRHS, Guards);
13674 const SCEV *GuardedStart = applyLoopGuards(OrigStart, Guards);
13675 if (Invert)
13676 std::swap(GuardedRHS, GuardedStart);
13677
13678 auto [GELHS, GERHS] = SwapIfInverted(OrigRHS, OrigStart);
13679 if (isLoopEntryGuardedByCond(L, CondGE, GELHS, GERHS) ||
13680 isKnownPredicate(CondGE, GuardedRHS, GuardedStart))
13681 return true;
13682
13683 if ((GuardedRHS != GELHS || GuardedStart != GERHS) &&
13684 isKnownPredicate(CondGE, GELHS, GERHS))
13685 return true;
13686
13687 // (RHS > Start - 1) implies RHS >= Start.
13688 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
13689 // "Start - 1" doesn't overflow.
13690 // * For signed comparison, if Start - 1 does overflow, it's equal
13691 // to INT_MAX, and "RHS >s INT_MAX" is trivially false.
13692 // * For unsigned comparison, if Start - 1 does overflow, it's equal
13693 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
13694 //
13695 // FIXME: Should isLoopEntryGuardedByCond do this for us?
13696 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13697 auto [GTLHS, GTRHS] = SwapIfInverted(OrigRHS, StepBack(OrigStart, One));
13698 return isLoopEntryGuardedByCond(L, CondGT, GTLHS, GTRHS);
13699 };
13700
13701 // If we know that RHS >= Start in the context of loop, then we know
13702 // that max(RHS, Start) = RHS at this point.
13703 if (canProveRHSIsAtOrBeyondStart()) {
13704 End = RHS;
13705 } else {
13706 // If RHS < Start, the backedge will be taken zero times. So in
13707 // general, we can write the backedge-taken count as:
13708 //
13709 // RHS >= Start ? ceil(RHS - Start) / Stride : 0
13710 //
13711 // We convert it to the following to make it more convenient for SCEV:
13712 //
13713 // ceil(max(RHS, Start) - Start) / Stride
13714 //
13715 // Inverted, this is ceil(Start - min(RHS, Start)) / Stride.
13716 if (Invert)
13717 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
13718 else
13719 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
13720
13721 // See what would happen if we assume the backedge is taken. This is
13722 // used to compute MaxBECount.
13723 BECountIfBackedgeTaken = getUDivCeilSCEV(Distance(Start, RHS), Stride);
13724 }
13725
13726 const SCEV *Delta = Distance(Start, End);
13727 if (!AddingStrideMinusOneMayOverflow) {
13728 // floor((D + (S - 1)) / S)
13729 // We prefer this formulation if it's legal because it's fewer
13730 // operations.
13731 BECount =
13732 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13733 } else {
13734 BECount = getUDivCeilSCEV(Delta, Stride);
13735 }
13736 }
13737 }
13738
13739 const SCEV *ConstantMaxBECount;
13740 bool MaxOrZero = false;
13741 if (isa<SCEVConstant>(BECount)) {
13742 ConstantMaxBECount = BECount;
13743 } else {
13744 ConstantMaxBECount = computeMaxBECountForLT(
13745 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned,
13746 Invert);
13747 // If we know exactly how many times the backedge will be taken if it's
13748 // taken at least once, then the backedge count will either be that or
13749 // zero. If that count exceeds the range-based bound, the backedge can
13750 // never be taken.
13751 const APInt *IfTaken, *RangeMax;
13752 if (match(BECountIfBackedgeTaken, m_scev_APInt(IfTaken))) {
13753 if (match(ConstantMaxBECount, m_scev_APInt(RangeMax)) &&
13754 IfTaken->ugt(*RangeMax)) {
13755 ConstantMaxBECount = getZero(BECountIfBackedgeTaken->getType());
13756 } else {
13757 ConstantMaxBECount = BECountIfBackedgeTaken;
13758 MaxOrZero = true;
13759 }
13760 }
13761 }
13762
13763 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
13764 !isa<SCEVCouldNotCompute>(BECount))
13765 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
13766
13767 const SCEV *SymbolicMaxBECount =
13768 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13769 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
13770 Predicates);
13771}
13772
13774 ScalarEvolution &SE) const {
13775 if (Range.isFullSet()) // Infinite loop.
13776 return SE.getCouldNotCompute();
13777
13778 // If the start is a non-zero constant, shift the range to simplify things.
13779 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
13780 if (!SC->getValue()->isZero()) {
13782 Operands[0] = SE.getZero(SC->getType());
13783 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
13785 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
13786 return ShiftedAddRec->getNumIterationsInRange(
13787 Range.subtract(SC->getAPInt()), SE);
13788 // This is strange and shouldn't happen.
13789 return SE.getCouldNotCompute();
13790 }
13791
13792 // The only time we can solve this is when we have all constant indices.
13793 // Otherwise, we cannot determine the overflow conditions.
13795 return SE.getCouldNotCompute();
13796
13797 // Okay at this point we know that all elements of the chrec are constants and
13798 // that the start element is zero.
13799
13800 // First check to see if the range contains zero. If not, the first
13801 // iteration exits.
13802 unsigned BitWidth = SE.getTypeSizeInBits(getType());
13803 if (!Range.contains(APInt(BitWidth, 0)))
13804 return SE.getZero(getType());
13805
13806 if (isAffine()) {
13807 // If this is an affine expression then we have this situation:
13808 // Solve {0,+,A} in Range === Ax in Range
13809
13810 // We know that zero is in the range. If A is positive then we know that
13811 // the upper value of the range must be the first possible exit value.
13812 // If A is negative then the lower of the range is the last possible loop
13813 // value. Also note that we already checked for a full range.
13814 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
13815 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
13816
13817 // The exit value should be (End+A)/A.
13818 APInt ExitVal = (End + A).udiv(A);
13819 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
13820
13821 // Evaluate at the exit value. If we really did fall out of the valid
13822 // range, then we computed our trip count, otherwise wrap around or other
13823 // things must have happened.
13824 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
13825 if (Range.contains(Val->getValue()))
13826 return SE.getCouldNotCompute(); // Something strange happened
13827
13828 // Ensure that the previous value is in the range.
13829 assert(Range.contains(
13831 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
13832 "Linear scev computation is off in a bad way!");
13833 return SE.getConstant(ExitValue);
13834 }
13835
13836 if (isQuadratic()) {
13837 if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
13838 return SE.getConstant(*S);
13839 }
13840
13841 return SE.getCouldNotCompute();
13842}
13843
13844const SCEVAddRecExpr *
13846 assert(getNumOperands() > 1 && "AddRec with zero step?");
13847 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
13848 // but in this case we cannot guarantee that the value returned will be an
13849 // AddRec because SCEV does not have a fixed point where it stops
13850 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
13851 // may happen if we reach arithmetic depth limit while simplifying. So we
13852 // construct the returned value explicitly.
13854 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
13855 // (this + Step) is {A+B,+,B+C,+...,+,N}.
13856 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
13857 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
13858 // We know that the last operand is not a constant zero (otherwise it would
13859 // have been popped out earlier). This guarantees us that if the result has
13860 // the same last operand, then it will also not be popped out, meaning that
13861 // the returned value will be an AddRec.
13862 const SCEV *Last = getOperand(getNumOperands() - 1);
13863 assert(!Last->isZero() && "Recurrency with zero step?");
13864 Ops.push_back(Last);
13866}
13867
13868// Return true when S contains at least an undef value.
13870 return SCEVExprContains(
13871 S, [](const SCEV *S) { return match(S, m_scev_UndefOrPoison()); });
13872}
13873
13874// Return true when S contains a value that is a nullptr.
13876 return SCEVExprContains(S, [](const SCEV *S) {
13877 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
13878 return SU->getValue() == nullptr;
13879 return false;
13880 });
13881}
13882
13883/// Return the size of an element read or written by Inst.
13885 if (!isa<LoadInst, StoreInst>(Inst))
13886 return nullptr;
13888 return getSizeOfExpr(ETy, getLoadStoreType(Inst));
13889}
13890
13891//===----------------------------------------------------------------------===//
13892// SCEVCallbackVH Class Implementation
13893//===----------------------------------------------------------------------===//
13894
13896 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
13897 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
13898 SE->ConstantEvolutionLoopExitValue.erase(PN);
13899 SE->eraseValueFromMap(getValPtr());
13900 // this now dangles!
13901}
13902
13903void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
13904 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
13905
13906 // Forget all the expressions associated with users of the old value,
13907 // so that future queries will recompute the expressions using the new
13908 // value.
13909 SE->forgetValue(getValPtr());
13910 // this now dangles!
13911}
13912
13913ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
13914 : CallbackVH(V), SE(se) {}
13915
13916//===----------------------------------------------------------------------===//
13917// ScalarEvolution Class Implementation
13918//===----------------------------------------------------------------------===//
13919
13922 LoopInfo &LI)
13923 : Opts(getAnalysisOptions(F)), F(F), DL(F.getDataLayout()), TLI(TLI),
13924 AC(AC), DT(DT), LI(LI), CouldNotCompute(new SCEVCouldNotCompute()),
13925 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64) {
13926 // To use guards for proving predicates, we need to scan every instruction in
13927 // relevant basic blocks, and not just terminators. Doing this is a waste of
13928 // time if the IR does not actually contain any calls to
13929 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
13930 //
13931 // This pessimizes the case where a pass that preserves ScalarEvolution wants
13932 // to _add_ guards to the module when there weren't any before, and wants
13933 // ScalarEvolution to optimize based on those guards. For now we prefer to be
13934 // efficient in lieu of being smart in that rather obscure case.
13935
13936 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
13937 F.getParent(), Intrinsic::experimental_guard);
13938 HasGuards = GuardDecl && !GuardDecl->use_empty();
13939}
13940
13942 : Opts(Arg.Opts), F(Arg.F), DL(Arg.DL), HasGuards(Arg.HasGuards),
13943 TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), LI(Arg.LI),
13944 CouldNotCompute(std::move(Arg.CouldNotCompute)),
13945 ValueExprMap(std::move(Arg.ValueExprMap)),
13946 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
13947 PendingMerges(std::move(Arg.PendingMerges)),
13948 ConstantMultipleCache(std::move(Arg.ConstantMultipleCache)),
13949 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
13950 PredicatedBackedgeTakenCounts(
13951 std::move(Arg.PredicatedBackedgeTakenCounts)),
13952 BECountUsers(std::move(Arg.BECountUsers)),
13953 ConstantEvolutionLoopExitValue(
13954 std::move(Arg.ConstantEvolutionLoopExitValue)),
13955 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
13956 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
13957 LoopDispositions(std::move(Arg.LoopDispositions)),
13958 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
13959 BlockDispositions(std::move(Arg.BlockDispositions)),
13960 SCEVUsers(std::move(Arg.SCEVUsers)),
13961 UnsignedRanges(std::move(Arg.UnsignedRanges)),
13962 SignedRanges(std::move(Arg.SignedRanges)),
13963 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
13964 UniquePreds(std::move(Arg.UniquePreds)),
13965 SCEVAllocator(std::move(Arg.SCEVAllocator)),
13966 ConstantSCEVs(std::move(Arg.ConstantSCEVs)),
13967 LoopUsers(std::move(Arg.LoopUsers)),
13968 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
13969 FirstUnknown(Arg.FirstUnknown),
13970 NextUnknownOrderID(Arg.NextUnknownOrderID) {
13971 Arg.FirstUnknown = nullptr;
13972}
13973
13975 // Iterate through all the SCEVUnknown instances and call their
13976 // destructors, so that they release their references to their values.
13977 for (SCEVUnknown *U = FirstUnknown; U;) {
13978 SCEVUnknown *Tmp = U;
13979 U = U->Next;
13980 Tmp->~SCEVUnknown();
13981 }
13982 FirstUnknown = nullptr;
13983
13984 ExprValueMap.clear();
13985 ValueExprMap.clear();
13986 HasRecMap.clear();
13987 BackedgeTakenCounts.clear();
13988 PredicatedBackedgeTakenCounts.clear();
13989
13990 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
13991 assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
13992 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
13993 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
13994}
13995
13999
14000/// When printing a top-level SCEV for trip counts, it's helpful to include
14001/// a type for constants which are otherwise hard to disambiguate.
14002static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV* S) {
14003 if (isa<SCEVConstant>(S))
14004 OS << *S->getType() << " ";
14005 OS << *S;
14006}
14007
14009 const Loop *L) {
14010 // Print all inner loops first
14011 for (Loop *I : *L)
14012 PrintLoopInfo(OS, SE, I);
14013
14014 OS << "Loop ";
14015 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14016 OS << ": ";
14017
14018 SmallVector<BasicBlock *, 8> ExitingBlocks;
14019 L->getExitingBlocks(ExitingBlocks);
14020 if (ExitingBlocks.size() != 1)
14021 OS << "<multiple exits> ";
14022
14023 auto *BTC = SE->getBackedgeTakenCount(L);
14024 if (!isa<SCEVCouldNotCompute>(BTC)) {
14025 OS << "backedge-taken count is ";
14026 PrintSCEVWithTypeHint(OS, BTC);
14027 } else
14028 OS << "Unpredictable backedge-taken count.";
14029 OS << "\n";
14030
14031 if (ExitingBlocks.size() > 1)
14032 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14033 OS << " exit count for " << ExitingBlock->getName() << ": ";
14034 const SCEV *EC = SE->getExitCount(L, ExitingBlock);
14035 PrintSCEVWithTypeHint(OS, EC);
14036 if (isa<SCEVCouldNotCompute>(EC)) {
14037 // Retry with predicates.
14039 EC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates);
14040 if (!isa<SCEVCouldNotCompute>(EC)) {
14041 OS << "\n predicated exit count for " << ExitingBlock->getName()
14042 << ": ";
14043 PrintSCEVWithTypeHint(OS, EC);
14044 OS << "\n Predicates:\n";
14045 for (const auto *P : Predicates)
14046 P->print(OS, 4);
14047 }
14048 }
14049 OS << "\n";
14050 }
14051
14052 OS << "Loop ";
14053 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14054 OS << ": ";
14055
14056 auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
14057 if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
14058 OS << "constant max backedge-taken count is ";
14059 PrintSCEVWithTypeHint(OS, ConstantBTC);
14061 OS << ", actual taken count either this or zero.";
14062 } else {
14063 OS << "Unpredictable constant max backedge-taken count. ";
14064 }
14065
14066 OS << "\n"
14067 "Loop ";
14068 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14069 OS << ": ";
14070
14071 auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
14072 if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
14073 OS << "symbolic max backedge-taken count is ";
14074 PrintSCEVWithTypeHint(OS, SymbolicBTC);
14076 OS << ", actual taken count either this or zero.";
14077 } else {
14078 OS << "Unpredictable symbolic max backedge-taken count. ";
14079 }
14080 OS << "\n";
14081
14082 if (ExitingBlocks.size() > 1)
14083 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14084 OS << " symbolic max exit count for " << ExitingBlock->getName() << ": ";
14085 auto *ExitBTC = SE->getExitCount(L, ExitingBlock,
14087 PrintSCEVWithTypeHint(OS, ExitBTC);
14088 if (isa<SCEVCouldNotCompute>(ExitBTC)) {
14089 // Retry with predicates.
14091 ExitBTC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates,
14093 if (!isa<SCEVCouldNotCompute>(ExitBTC)) {
14094 OS << "\n predicated symbolic max exit count for "
14095 << ExitingBlock->getName() << ": ";
14096 PrintSCEVWithTypeHint(OS, ExitBTC);
14097 OS << "\n Predicates:\n";
14098 for (const auto *P : Predicates)
14099 P->print(OS, 4);
14100 }
14101 }
14102 OS << "\n";
14103 }
14104
14106 auto *PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
14107 if (PBT != BTC) {
14108 OS << "Loop ";
14109 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14110 OS << ": ";
14111 if (!isa<SCEVCouldNotCompute>(PBT)) {
14112 OS << "Predicated backedge-taken count is ";
14113 PrintSCEVWithTypeHint(OS, PBT);
14114 } else
14115 OS << "Unpredictable predicated backedge-taken count.";
14116 OS << "\n";
14117 OS << " Predicates:\n";
14118 for (const auto *P : Preds)
14119 P->print(OS, 4);
14120 }
14121 Preds.clear();
14122
14123 auto *PredConstantMax =
14125 if (PredConstantMax != ConstantBTC) {
14126 OS << "Loop ";
14127 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14128 OS << ": ";
14129 if (!isa<SCEVCouldNotCompute>(PredConstantMax)) {
14130 OS << "Predicated constant max backedge-taken count is ";
14131 PrintSCEVWithTypeHint(OS, PredConstantMax);
14132 } else
14133 OS << "Unpredictable predicated constant max backedge-taken count.";
14134 OS << "\n";
14135 OS << " Predicates:\n";
14136 for (const auto *P : Preds)
14137 P->print(OS, 4);
14138 }
14139 Preds.clear();
14140
14141 auto *PredSymbolicMax =
14143 if (SymbolicBTC != PredSymbolicMax) {
14144 OS << "Loop ";
14145 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14146 OS << ": ";
14147 if (!isa<SCEVCouldNotCompute>(PredSymbolicMax)) {
14148 OS << "Predicated symbolic max backedge-taken count is ";
14149 PrintSCEVWithTypeHint(OS, PredSymbolicMax);
14150 } else
14151 OS << "Unpredictable predicated symbolic max backedge-taken count.";
14152 OS << "\n";
14153 OS << " Predicates:\n";
14154 for (const auto *P : Preds)
14155 P->print(OS, 4);
14156 }
14157
14159 OS << "Loop ";
14160 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14161 OS << ": ";
14162 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
14163 }
14164}
14165
14166namespace llvm {
14167// Note: these overloaded operators need to be in the llvm namespace for them
14168// to be resolved correctly. If we put them outside the llvm namespace, the
14169//
14170// OS << ": " << SE.getLoopDisposition(SV, InnerL);
14171//
14172// code below "breaks" and start printing raw enum values as opposed to the
14173// string values.
14176 switch (LD) {
14178 OS << "Variant";
14179 break;
14181 OS << "Invariant";
14182 break;
14184 OS << "Uniform";
14185 break;
14187 OS << "Computable";
14188 break;
14189 }
14190 return OS;
14191}
14192
14195 switch (BD) {
14197 OS << "DoesNotDominate";
14198 break;
14200 OS << "Dominates";
14201 break;
14203 OS << "ProperlyDominates";
14204 break;
14205 }
14206 return OS;
14207}
14208} // namespace llvm
14209
14211 // ScalarEvolution's implementation of the print method is to print
14212 // out SCEV values of all instructions that are interesting. Doing
14213 // this potentially causes it to create new SCEV objects though,
14214 // which technically conflicts with the const qualifier. This isn't
14215 // observable from outside the class though, so casting away the
14216 // const isn't dangerous.
14217 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14218
14219 if (Opts.scalar_evolution_classify_expressions) {
14220 OS << "Classifying expressions for: ";
14221 F.printAsOperand(OS, /*PrintType=*/false);
14222 OS << "\n";
14223 for (Instruction &I : instructions(F))
14224 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
14225 OS << I << '\n';
14226 OS << " --> ";
14227 const SCEV *SV = SE.getSCEV(&I);
14228 SV->print(OS);
14229 if (!isa<SCEVCouldNotCompute>(SV)) {
14230 OS << " U: ";
14231 SE.getUnsignedRange(SV).print(OS);
14232 OS << " S: ";
14233 SE.getSignedRange(SV).print(OS);
14234 }
14235
14236 const Loop *L = LI.getLoopFor(I.getParent());
14237
14238 SCEVUse AtUse = SE.getSCEVAtScope(SV, L);
14239 if (AtUse != SV) {
14240 OS << " --> ";
14241 OS << AtUse;
14242 if (!isa<SCEVCouldNotCompute>(AtUse)) {
14243 OS << " U: ";
14244 SE.getUnsignedRange(AtUse).print(OS);
14245 OS << " S: ";
14246 SE.getSignedRange(AtUse).print(OS);
14247 }
14248 }
14249
14250 if (L) {
14251 OS << "\t\t" "Exits: ";
14252 SCEVUse ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
14253 if (!SE.isLoopInvariant(ExitValue, L)) {
14254 OS << "<<Unknown>>";
14255 } else {
14256 OS << ExitValue;
14257 }
14258
14259 ListSeparator LS(", ", "\t\tLoopDispositions: { ");
14260 for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
14261 OS << LS;
14262 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14263 OS << ": " << SE.getLoopDisposition(SV, Iter);
14264 }
14265
14266 for (const auto *InnerL : depth_first(L)) {
14267 if (InnerL == L)
14268 continue;
14269 OS << LS;
14270 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14271 OS << ": " << SE.getLoopDisposition(SV, InnerL);
14272 }
14273
14274 OS << " }";
14275 }
14276
14277 OS << "\n";
14278 }
14279 }
14280
14281 OS << "Determining loop execution counts for: ";
14282 F.printAsOperand(OS, /*PrintType=*/false);
14283 OS << "\n";
14284 for (Loop *I : LI)
14285 PrintLoopInfo(OS, &SE, I);
14286}
14287
14290 if (isa<SCEVConstant>(S))
14291 return LoopInvariant;
14292
14293 auto &Values = LoopDispositions[S];
14294 for (auto &V : Values) {
14295 if (V.getPointer() == L)
14296 return V.getInt();
14297 }
14298 Values.emplace_back(L, LoopVariant);
14299 LoopDisposition D = computeLoopDisposition(S, L);
14300 auto &Values2 = LoopDispositions[S];
14301 for (auto &V : llvm::reverse(Values2)) {
14302 if (V.getPointer() == L) {
14303 V.setInt(D);
14304 break;
14305 }
14306 }
14307 return D;
14308}
14309
14311ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
14312 switch (S->getSCEVType()) {
14313 case scConstant:
14314 case scVScale:
14315 return LoopInvariant;
14316 case scAddRecExpr: {
14317 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14318
14319 // If L is the addrec's loop, it's computable.
14320 if (AR->getLoop() == L)
14321 return LoopComputable;
14322
14323 // Add recurrences are never invariant in the function-body (null loop).
14324 if (!L)
14325 return LoopVariant;
14326
14327 // Everything that is not defined at loop entry is variant.
14328 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) {
14329 if (L->contains(AR->getLoop()) &&
14330 llvm::all_of(AR->operands(),
14331 [&](const SCEV *Op) { return isLoopUniform(Op, L); }))
14332 return LoopUniform;
14333
14334 return LoopVariant;
14335 }
14336 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
14337 " dominate the contained loop's header?");
14338
14339 // This recurrence is invariant w.r.t. L if AR's loop contains L.
14340 if (AR->getLoop()->contains(L))
14341 return LoopInvariant;
14342
14343 // This recurrence is variant w.r.t. L if any of its operands
14344 // are variant.
14345 for (SCEVUse Op : AR->operands())
14346 if (!isLoopInvariant(Op, L))
14347 return LoopVariant;
14348
14349 // Otherwise it's loop-invariant.
14350 return LoopInvariant;
14351 }
14352 case scTruncate:
14353 case scZeroExtend:
14354 case scSignExtend:
14355 case scPtrToAddr:
14356 case scAddExpr:
14357 case scMulExpr:
14358 case scUDivExpr:
14359 case scUMaxExpr:
14360 case scSMaxExpr:
14361 case scUMinExpr:
14362 case scSMinExpr:
14363 case scSequentialUMinExpr: {
14364 bool HasVarying = false;
14365 bool HasUniform = false;
14366 for (SCEVUse Op : S->operands()) {
14368 if (D == LoopVariant)
14369 return LoopVariant;
14370 if (D == LoopComputable)
14371 HasVarying = true;
14372 if (D == LoopUniform)
14373 HasUniform = true;
14374 }
14375 return HasVarying ? (HasUniform ? LoopVariant : LoopComputable)
14376 : (HasUniform ? LoopUniform : LoopInvariant);
14377 }
14378 case scUnknown:
14379 // All non-instruction values are loop invariant. All instructions are loop
14380 // invariant if they are not contained in the specified loop.
14381 // Instructions are never considered invariant in the function body
14382 // (null loop) because they are defined within the "loop".
14384 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
14385 return LoopInvariant;
14386 case scCouldNotCompute:
14387 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14388 }
14389 llvm_unreachable("Unknown SCEV kind!");
14390}
14391
14392bool ScalarEvolution::isLoopUniform(const SCEV *S, const Loop *L) {
14394 return D == LoopUniform || D == LoopInvariant;
14395}
14396
14398 return getLoopDisposition(S, L) == LoopInvariant;
14399}
14400
14402 return getLoopDisposition(S, L) == LoopComputable;
14403}
14404
14407 if (isa<SCEVConstant>(S))
14409
14410 auto &Values = BlockDispositions[S];
14411 for (auto &V : Values) {
14412 if (V.getPointer() == BB)
14413 return V.getInt();
14414 }
14415 Values.emplace_back(BB, DoesNotDominateBlock);
14416 BlockDisposition D = computeBlockDisposition(S, BB);
14417 auto &Values2 = BlockDispositions[S];
14418 for (auto &V : llvm::reverse(Values2)) {
14419 if (V.getPointer() == BB) {
14420 V.setInt(D);
14421 break;
14422 }
14423 }
14424 return D;
14425}
14426
14428ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
14429 switch (S->getSCEVType()) {
14430 case scConstant:
14431 case scVScale:
14433 case scAddRecExpr: {
14434 // This uses a "dominates" query instead of "properly dominates" query
14435 // to test for proper dominance too, because the instruction which
14436 // produces the addrec's value is a PHI, and a PHI effectively properly
14437 // dominates its entire containing block.
14438 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14439 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
14440 return DoesNotDominateBlock;
14441
14442 // Fall through into SCEVNAryExpr handling.
14443 [[fallthrough]];
14444 }
14445 case scTruncate:
14446 case scZeroExtend:
14447 case scSignExtend:
14448 case scPtrToAddr:
14449 case scAddExpr:
14450 case scMulExpr:
14451 case scUDivExpr:
14452 case scUMaxExpr:
14453 case scSMaxExpr:
14454 case scUMinExpr:
14455 case scSMinExpr:
14456 case scSequentialUMinExpr: {
14457 bool Proper = true;
14458 for (const SCEV *NAryOp : S->operands()) {
14460 if (D == DoesNotDominateBlock)
14461 return DoesNotDominateBlock;
14462 if (D == DominatesBlock)
14463 Proper = false;
14464 }
14465 return Proper ? ProperlyDominatesBlock : DominatesBlock;
14466 }
14467 case scUnknown:
14468 if (Instruction *I =
14470 if (I->getParent() == BB)
14471 return DominatesBlock;
14472 if (DT.properlyDominates(I->getParent(), BB))
14474 return DoesNotDominateBlock;
14475 }
14477 case scCouldNotCompute:
14478 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14479 }
14480 llvm_unreachable("Unknown SCEV kind!");
14481}
14482
14483bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
14484 return getBlockDisposition(S, BB) >= DominatesBlock;
14485}
14486
14489}
14490
14491void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
14492 bool Predicated) {
14493 auto &BECounts =
14494 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14495 auto It = BECounts.find(L);
14496 if (It != BECounts.end()) {
14497 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
14498 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14499 if (!isa<SCEVConstant>(S)) {
14500 auto UserIt = BECountUsers.find(S);
14501 assert(UserIt != BECountUsers.end());
14502 UserIt->second.erase({L, Predicated});
14503 }
14504 }
14505 }
14506 BECounts.erase(It);
14507 }
14508}
14509
14510void ScalarEvolution::forgetMemoizedResults(ArrayRef<SCEVUse> SCEVs) {
14511 SmallPtrSet<const SCEV *, 8> ToForget(llvm::from_range, SCEVs);
14512 SmallVector<SCEVUse, 8> Worklist(ToForget.begin(), ToForget.end());
14513
14514 while (!Worklist.empty()) {
14515 const SCEV *Curr = Worklist.pop_back_val();
14516 auto Users = SCEVUsers.find(Curr);
14517 if (Users != SCEVUsers.end())
14518 for (const auto *User : Users->second)
14519 if (ToForget.insert(User).second)
14520 Worklist.push_back(User);
14521 }
14522
14523 for (const auto *S : ToForget)
14524 forgetMemoizedResultsImpl(S);
14525
14526 PredicatedSCEVRewrites.remove_if(
14527 [&](const auto &Entry) { return ToForget.count(Entry.first.first); });
14528}
14529
14530void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
14531 LoopDispositions.erase(S);
14532 BlockDispositions.erase(S);
14533 UnsignedRanges.erase(S);
14534 SignedRanges.erase(S);
14535 HasRecMap.erase(S);
14536 ConstantMultipleCache.erase(S);
14537
14538 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
14539 UnsignedWrapViaInductionTried.erase(AR);
14540 SignedWrapViaInductionTried.erase(AR);
14541 }
14542
14543 auto ExprIt = ExprValueMap.find(S);
14544 if (ExprIt != ExprValueMap.end()) {
14545 for (Value *V : ExprIt->second) {
14546 auto ValueIt = ValueExprMap.find_as(V);
14547 if (ValueIt != ValueExprMap.end())
14548 ValueExprMap.erase(ValueIt);
14549 }
14550 ExprValueMap.erase(ExprIt);
14551 }
14552
14553 auto ScopeIt = ValuesAtScopes.find(S);
14554 if (ScopeIt != ValuesAtScopes.end()) {
14555 for (const auto &Pair : ScopeIt->second)
14556 if (!isa_and_nonnull<SCEVConstant>(Pair.second))
14557 llvm::erase(ValuesAtScopesUsers[Pair.second.getPointer()],
14558 std::make_pair(Pair.first, S));
14559 ValuesAtScopes.erase(ScopeIt);
14560 }
14561
14562 auto ScopeUserIt = ValuesAtScopesUsers.find(S);
14563 if (ScopeUserIt != ValuesAtScopesUsers.end()) {
14564 for (const auto &Pair : ScopeUserIt->second)
14565 // The recorded value at scope is a use of S, which may carry no-wrap
14566 // flags that are not part of this key.
14567 llvm::erase_if(ValuesAtScopes[Pair.second], [&](const auto &LS) {
14568 return LS.first == Pair.first && LS.second.getPointer() == S;
14569 });
14570 ValuesAtScopesUsers.erase(ScopeUserIt);
14571 }
14572
14573 auto BEUsersIt = BECountUsers.find(S);
14574 if (BEUsersIt != BECountUsers.end()) {
14575 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
14576 auto Copy = BEUsersIt->second;
14577 for (const auto &Pair : Copy)
14578 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
14579 BECountUsers.erase(BEUsersIt);
14580 }
14581
14582 auto FoldUser = FoldCacheUser.find(S);
14583 if (FoldUser != FoldCacheUser.end()) {
14584 for (auto &KV : FoldUser->second)
14585 FoldCache.erase(KV);
14586 FoldCacheUser.erase(FoldUser);
14587 }
14588}
14589
14590void
14591ScalarEvolution::getUsedLoops(const SCEV *S,
14592 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
14593 struct FindUsedLoops {
14594 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
14595 : LoopsUsed(LoopsUsed) {}
14596 SmallPtrSetImpl<const Loop *> &LoopsUsed;
14597 bool follow(const SCEV *S) {
14598 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
14599 LoopsUsed.insert(AR->getLoop());
14600 return true;
14601 }
14602
14603 bool isDone() const { return false; }
14604 };
14605
14606 FindUsedLoops F(LoopsUsed);
14607 SCEVTraversal<FindUsedLoops>(F).visitAll(S);
14608}
14609
14610void ScalarEvolution::getReachableBlocks(
14613 Worklist.push_back(&F.getEntryBlock());
14614 while (!Worklist.empty()) {
14615 BasicBlock *BB = Worklist.pop_back_val();
14616 if (!Reachable.insert(BB).second)
14617 continue;
14618
14619 Value *Cond;
14620 BasicBlock *TrueBB, *FalseBB;
14621 if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
14622 m_BasicBlock(FalseBB)))) {
14623 if (auto *C = dyn_cast<ConstantInt>(Cond)) {
14624 Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
14625 continue;
14626 }
14627
14628 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14629 const SCEV *L = getSCEV(Cmp->getOperand(0));
14630 const SCEV *R = getSCEV(Cmp->getOperand(1));
14631 if (isKnownPredicateViaConstantRanges(Cmp->getCmpPredicate(), L, R)) {
14632 Worklist.push_back(TrueBB);
14633 continue;
14634 }
14635 if (isKnownPredicateViaConstantRanges(Cmp->getInverseCmpPredicate(), L,
14636 R)) {
14637 Worklist.push_back(FalseBB);
14638 continue;
14639 }
14640 }
14641 }
14642
14643 append_range(Worklist, successors(BB));
14644 }
14645}
14646
14648 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14649 ScalarEvolution SE2(F, TLI, AC, DT, LI);
14650
14651 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
14652
14653 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
14654 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
14655 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
14656
14657 const SCEV *visitConstant(const SCEVConstant *Constant) {
14658 return SE.getConstant(Constant->getAPInt());
14659 }
14660
14661 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14662 return SE.getUnknown(Expr->getValue());
14663 }
14664
14665 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
14666 return SE.getCouldNotCompute();
14667 }
14668 };
14669
14670 SCEVMapper SCM(SE2);
14671 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
14672 SE2.getReachableBlocks(ReachableBlocks, F);
14673
14674 auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
14675 if (containsUndefs(Old) || containsUndefs(New)) {
14676 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
14677 // not propagate undef aggressively). This means we can (and do) fail
14678 // verification in cases where a transform makes a value go from "undef"
14679 // to "undef+1" (say). The transform is fine, since in both cases the
14680 // result is "undef", but SCEV thinks the value increased by 1.
14681 return nullptr;
14682 }
14683
14684 // Unless -verify-scev-strict is set, we only compare constant deltas.
14685 const SCEV *Delta = SE2.getMinusSCEV(Old, New);
14686 if (!Opts.verify_scev_strict && !isa<SCEVConstant>(Delta))
14687 return nullptr;
14688
14689 return Delta;
14690 };
14691
14692 while (!LoopStack.empty()) {
14693 auto *L = LoopStack.pop_back_val();
14694 llvm::append_range(LoopStack, *L);
14695
14696 // Only verify BECounts in reachable loops. For an unreachable loop,
14697 // any BECount is legal.
14698 if (!ReachableBlocks.contains(L->getHeader()))
14699 continue;
14700
14701 // Only verify cached BECounts. Computing new BECounts may change the
14702 // results of subsequent SCEV uses.
14703 auto It = BackedgeTakenCounts.find(L);
14704 if (It == BackedgeTakenCounts.end())
14705 continue;
14706
14707 SCEVUse CurBECount =
14708 SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
14709 auto *NewBECount = SE2.getBackedgeTakenCount(L);
14710
14711 if (CurBECount == SE2.getCouldNotCompute() ||
14712 NewBECount == SE2.getCouldNotCompute()) {
14713 // NB! This situation is legal, but is very suspicious -- whatever pass
14714 // change the loop to make a trip count go from could not compute to
14715 // computable or vice-versa *should have* invalidated SCEV. However, we
14716 // choose not to assert here (for now) since we don't want false
14717 // positives.
14718 continue;
14719 }
14720
14721 if (SE.getTypeSizeInBits(CurBECount->getType()) >
14722 SE.getTypeSizeInBits(NewBECount->getType()))
14723 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
14724 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
14725 SE.getTypeSizeInBits(NewBECount->getType()))
14726 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
14727
14728 const SCEV *Delta = GetDelta(CurBECount, NewBECount);
14729 if (Delta && !Delta->isZero()) {
14730 dbgs() << "Trip Count for " << *L << " Changed!\n";
14731 dbgs() << "Old: " << *CurBECount << "\n";
14732 dbgs() << "New: " << *NewBECount << "\n";
14733 dbgs() << "Delta: " << *Delta << "\n";
14734 std::abort();
14735 }
14736 }
14737
14738 // Collect all valid loops currently in LoopInfo.
14739 SmallPtrSet<Loop *, 32> ValidLoops;
14740 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
14741 while (!Worklist.empty()) {
14742 Loop *L = Worklist.pop_back_val();
14743 if (ValidLoops.insert(L).second)
14744 Worklist.append(L->begin(), L->end());
14745 }
14746 for (const auto &KV : ValueExprMap) {
14747#ifndef NDEBUG
14748 // Check for SCEV expressions referencing invalid/deleted loops.
14749 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14750 assert(ValidLoops.contains(AR->getLoop()) &&
14751 "AddRec references invalid loop");
14752 }
14753#endif
14754
14755 // Check that the value is also part of the reverse map.
14756 auto It = ExprValueMap.find(KV.second);
14757 if (It == ExprValueMap.end() || !is_contained(It->second, KV.first)) {
14758 dbgs() << "Value " << *KV.first
14759 << " is in ValueExprMap but not in ExprValueMap\n";
14760 std::abort();
14761 }
14762
14763 if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
14764 if (!ReachableBlocks.contains(I->getParent()))
14765 continue;
14766 const SCEV *OldSCEV = SCM.visit(KV.second);
14767 const SCEV *NewSCEV = SE2.getSCEV(I);
14768 const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14769 if (Delta && !Delta->isZero()) {
14770 dbgs() << "SCEV for value " << *I << " changed!\n"
14771 << "Old: " << *OldSCEV << "\n"
14772 << "New: " << *NewSCEV << "\n"
14773 << "Delta: " << *Delta << "\n";
14774 std::abort();
14775 }
14776 }
14777 }
14778
14779 for (const auto &KV : ExprValueMap) {
14780 for (Value *V : KV.second) {
14781 const SCEV *S = ValueExprMap.lookup(V);
14782 if (!S) {
14783 dbgs() << "Value " << *V
14784 << " is in ExprValueMap but not in ValueExprMap\n";
14785 std::abort();
14786 }
14787 if (S != KV.first) {
14788 dbgs() << "Value " << *V << " mapped to " << *S << " rather than "
14789 << *KV.first << "\n";
14790 std::abort();
14791 }
14792 }
14793 }
14794
14795 // Verify integrity of SCEV users.
14796 for (const auto &S : UniqueSCEVs) {
14797 for (SCEVUse Op : S.operands()) {
14798 // We do not store dependencies of constants.
14799 if (isa<SCEVConstant>(Op))
14800 continue;
14801 auto It = SCEVUsers.find(Op);
14802 if (It != SCEVUsers.end() && It->second.count(&S))
14803 continue;
14804 dbgs() << "Use of operand " << *Op << " by user " << S
14805 << " is not being tracked!\n";
14806 std::abort();
14807 }
14808 }
14809
14810 // Verify integrity of ValuesAtScopes users.
14811 for (const auto &ValueAndVec : ValuesAtScopes) {
14812 const SCEV *Value = ValueAndVec.first;
14813 for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
14814 const Loop *L = LoopAndValueAtScope.first;
14815 SCEVUse ValueAtScope = LoopAndValueAtScope.second;
14816 if (!isa<SCEVConstant>(ValueAtScope)) {
14817 auto It = ValuesAtScopesUsers.find(ValueAtScope.getPointer());
14818 if (It != ValuesAtScopesUsers.end() &&
14819 is_contained(It->second, std::make_pair(L, Value)))
14820 continue;
14821 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14822 << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
14823 std::abort();
14824 }
14825 }
14826 }
14827
14828 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
14829 const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
14830 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
14831 const Loop *L = LoopAndValue.first;
14832 const SCEV *Value = LoopAndValue.second;
14834 auto It = ValuesAtScopes.find(Value);
14835 // The recorded value at scope may carry no-wrap flags that are not part
14836 // of the key it is recorded under.
14837 if (It != ValuesAtScopes.end() && any_of(It->second, [&](const auto &LS) {
14838 return LS.first == L && LS.second.getPointer() == ValueAtScope;
14839 }))
14840 continue;
14841 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14842 << *ValueAtScope << " missing in ValuesAtScopes\n";
14843 std::abort();
14844 }
14845 }
14846
14847 // Verify integrity of BECountUsers.
14848 auto VerifyBECountUsers = [&](bool Predicated) {
14849 auto &BECounts =
14850 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14851 for (const auto &LoopAndBEInfo : BECounts) {
14852 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
14853 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14854 if (!isa<SCEVConstant>(S)) {
14855 auto UserIt = BECountUsers.find(S);
14856 if (UserIt != BECountUsers.end() &&
14857 UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
14858 continue;
14859 dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
14860 << " missing from BECountUsers\n";
14861 std::abort();
14862 }
14863 }
14864 }
14865 }
14866 };
14867 VerifyBECountUsers(/* Predicated */ false);
14868 VerifyBECountUsers(/* Predicated */ true);
14869
14870 // Verify intergity of loop disposition cache.
14871 for (auto &[S, Values] : LoopDispositions) {
14872 for (auto [Loop, CachedDisposition] : Values) {
14873 const auto RecomputedDisposition = SE2.getLoopDisposition(S, Loop);
14874 if (CachedDisposition != RecomputedDisposition) {
14875 dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
14876 << " is incorrect: cached " << CachedDisposition << ", actual "
14877 << RecomputedDisposition << "\n";
14878 std::abort();
14879 }
14880 }
14881 }
14882
14883 // Verify integrity of the block disposition cache.
14884 for (auto &[S, Values] : BlockDispositions) {
14885 for (auto [BB, CachedDisposition] : Values) {
14886 const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
14887 if (CachedDisposition != RecomputedDisposition) {
14888 dbgs() << "Cached disposition of " << *S << " for block %"
14889 << BB->getName() << " is incorrect: cached " << CachedDisposition
14890 << ", actual " << RecomputedDisposition << "\n";
14891 std::abort();
14892 }
14893 }
14894 }
14895
14896 // Verify FoldCache/FoldCacheUser caches.
14897 for (auto [FoldID, Expr] : FoldCache) {
14898 auto I = FoldCacheUser.find(Expr);
14899 if (I == FoldCacheUser.end()) {
14900 dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
14901 << "!\n";
14902 std::abort();
14903 }
14904 if (!is_contained(I->second, FoldID)) {
14905 dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
14906 std::abort();
14907 }
14908 }
14909 for (auto [Expr, IDs] : FoldCacheUser) {
14910 for (auto &FoldID : IDs) {
14911 const SCEV *S = FoldCache.lookup(FoldID);
14912 if (!S) {
14913 dbgs() << "Missing entry in FoldCache for expression " << *Expr
14914 << "!\n";
14915 std::abort();
14916 }
14917 if (S != Expr) {
14918 dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: " << *S
14919 << " != " << *Expr << "!\n";
14920 std::abort();
14921 }
14922 }
14923 }
14924
14925 // Verify that ConstantMultipleCache computations are correct. We check that
14926 // cached multiples and recomputed multiples are multiples of each other to
14927 // verify correctness. It is possible that a recomputed multiple is different
14928 // from the cached multiple due to strengthened no wrap flags or changes in
14929 // KnownBits computations.
14930 for (auto [S, Multiple] : ConstantMultipleCache) {
14931 APInt RecomputedMultiple = SE2.getConstantMultiple(S);
14932 if ((Multiple != 0 && RecomputedMultiple != 0 &&
14933 Multiple.urem(RecomputedMultiple) != 0 &&
14934 RecomputedMultiple.urem(Multiple) != 0)) {
14935 dbgs() << "Incorrect cached computation in ConstantMultipleCache for "
14936 << *S << " : Computed " << RecomputedMultiple
14937 << " but cache contains " << Multiple << "!\n";
14938 std::abort();
14939 }
14940 }
14941}
14942
14944 Function &F, const PreservedAnalyses &PA,
14945 FunctionAnalysisManager::Invalidator &Inv) {
14946 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
14947 // of its dependencies is invalidated.
14948 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
14949 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
14950 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
14951 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
14952 Inv.invalidate<LoopAnalysis>(F, PA);
14953}
14954
14955AnalysisKey ScalarEvolutionAnalysis::Key;
14956
14959 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
14960 auto &AC = AM.getResult<AssumptionAnalysis>(F);
14961 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
14962 auto &LI = AM.getResult<LoopAnalysis>(F);
14963 return ScalarEvolution(F, TLI, AC, DT, LI);
14964}
14965
14971
14974 // For compatibility with opt's -analyze feature under legacy pass manager
14975 // which was not ported to NPM. This keeps tests using
14976 // update_analyze_test_checks.py working.
14977 OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
14978 << F.getName() << "':\n";
14980 return PreservedAnalyses::all();
14981}
14982
14984 "Scalar Evolution Analysis", false, true)
14990 "Scalar Evolution Analysis", false, true)
14991
14992char ScalarEvolutionWrapperPass::ID = 0;
14993
14995
14997 SE.reset(new ScalarEvolution(
14999 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
15001 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
15002 return false;
15003}
15004
15006
15008 SE->print(OS);
15009}
15010
15012 if (!VerifySCEV)
15013 return;
15014
15015 SE->verify();
15016}
15017
15025
15027 const SCEV *RHS) {
15028 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
15029}
15030
15031const SCEVPredicate *
15033 const SCEV *LHS, const SCEV *RHS) {
15035 assert(LHS->getType() == RHS->getType() &&
15036 "Type mismatch between LHS and RHS");
15037 // Unique this node based on the arguments
15038 ID.AddInteger(SCEVPredicate::P_Compare);
15039 ID.AddInteger(Pred);
15040 ID.AddPointer(LHS);
15041 ID.AddPointer(RHS);
15043 if (const auto *S = UniquePreds.lookup(ID, Token))
15044 return S;
15045 SCEVComparePredicate *Eq = new (SCEVAllocator)
15046 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
15047 UniquePreds.insert(Eq, Token);
15048 return Eq;
15049}
15050
15052 const SCEVAddRecExpr *AR,
15055 // Unique this node based on the arguments
15057 ID.AddPointer(AR);
15058 ID.AddInteger(AddedFlags);
15060 if (const auto *S = UniquePreds.lookup(ID, Token))
15061 return S;
15062 auto *OF = new (SCEVAllocator)
15063 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
15064 UniquePreds.insert(OF, Token);
15065 return OF;
15066}
15067
15068namespace {
15069
15070class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
15071public:
15072
15073 /// Rewrites \p S in the context of a loop L and the SCEV predication
15074 /// infrastructure.
15075 ///
15076 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
15077 /// equivalences present in \p Pred.
15078 ///
15079 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
15080 /// \p NewPreds such that the result will be an AddRecExpr.
15081 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
15083 const SCEVPredicate *Pred) {
15084 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
15085 return Rewriter.visit(S);
15086 }
15087
15088 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
15089 if (Pred) {
15090 if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
15091 for (const auto *Pred : U->getPredicates())
15092 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
15093 if (IPred->getLHS() == Expr &&
15094 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15095 return IPred->getRHS();
15096 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
15097 if (IPred->getLHS() == Expr &&
15098 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15099 return IPred->getRHS();
15100 }
15101 }
15102 return convertToAddRecWithPreds(Expr);
15103 }
15104
15105 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
15106 const SCEV *Operand = visit(Expr->getOperand());
15107 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15108 if (AR && AR->getLoop() == L && AR->isAffine()) {
15109 // This couldn't be folded because the operand didn't have the nuw
15110 // flag. Add the nusw flag as an assumption that we could make.
15111 const SCEV *Step = AR->getStepRecurrence(SE);
15112 Type *Ty = Expr->getType();
15113 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
15114 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
15115 SE.getSignExtendExpr(Step, Ty), L,
15116 AR->getNoWrapFlags());
15117 }
15118 return SE.getZeroExtendExpr(Operand, Expr->getType());
15119 }
15120
15121 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
15122 const SCEV *Operand = visit(Expr->getOperand());
15123 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15124 if (AR && AR->getLoop() == L && AR->isAffine()) {
15125 // This couldn't be folded because the operand didn't have the nsw
15126 // flag. Add the nssw flag as an assumption that we could make.
15127 const SCEV *Step = AR->getStepRecurrence(SE);
15128 Type *Ty = Expr->getType();
15129 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
15130 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
15131 SE.getSignExtendExpr(Step, Ty), L,
15132 AR->getNoWrapFlags());
15133 }
15134 return SE.getSignExtendExpr(Operand, Expr->getType());
15135 }
15136
15137private:
15138 explicit SCEVPredicateRewriter(
15139 const Loop *L, ScalarEvolution &SE,
15140 SmallVectorImpl<const SCEVPredicate *> *NewPreds,
15141 const SCEVPredicate *Pred)
15142 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
15143
15144 bool addOverflowAssumption(const SCEVPredicate *P) {
15145 if (!NewPreds) {
15146 // Check if we've already made this assumption.
15147 return Pred && Pred->implies(P, SE);
15148 }
15149 NewPreds->push_back(P);
15150 return true;
15151 }
15152
15153 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
15155 auto *A = SE.getWrapPredicate(AR, AddedFlags);
15156 return addOverflowAssumption(A);
15157 }
15158
15159 // If \p Expr represents a PHINode, we try to see if it can be represented
15160 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
15161 // to add this predicate as a runtime overflow check, we return the AddRec.
15162 // If \p Expr does not meet these conditions (is not a PHI node, or we
15163 // couldn't create an AddRec for it, or couldn't add the predicate), we just
15164 // return \p Expr.
15165 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
15166 if (!isa<PHINode>(Expr->getValue()))
15167 return Expr;
15168 std::optional<
15169 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
15170 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
15171 if (!PredicatedRewrite)
15172 return Expr;
15173 for (const auto *P : PredicatedRewrite->second){
15174 // Wrap predicates from outer loops are not supported.
15175 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
15176 if (L != WP->getExpr()->getLoop())
15177 return Expr;
15178 }
15179 if (!addOverflowAssumption(P))
15180 return Expr;
15181 }
15182 return PredicatedRewrite->first;
15183 }
15184
15185 SmallVectorImpl<const SCEVPredicate *> *NewPreds;
15186 const SCEVPredicate *Pred;
15187 const Loop *L;
15188};
15189
15190} // end anonymous namespace
15191
15192const SCEV *
15194 const SCEVPredicate &Preds) {
15195 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
15196}
15197
15199 const SCEV *S, const Loop *L,
15202 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
15203 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
15204
15205 if (!AddRec)
15206 return nullptr;
15207
15208 // Check if any of the transformed predicates is known to be false. In that
15209 // case, it doesn't make sense to convert to a predicated AddRec, as the
15210 // versioned loop will never execute.
15211 for (const SCEVPredicate *Pred : TransformPreds) {
15212 auto *WrapPred = dyn_cast<SCEVWrapPredicate>(Pred);
15213 if (!WrapPred || WrapPred->getFlags() != SCEVWrapPredicate::IncrementNSSW)
15214 continue;
15215
15216 const SCEVAddRecExpr *AddRecToCheck = WrapPred->getExpr();
15217 const SCEV *ExitCount = getBackedgeTakenCount(AddRecToCheck->getLoop());
15218 if (isa<SCEVCouldNotCompute>(ExitCount))
15219 continue;
15220
15221 const SCEV *Step = AddRecToCheck->getStepRecurrence(*this);
15222 if (!Step->isOne())
15223 continue;
15224
15225 ExitCount = getTruncateOrSignExtend(ExitCount, Step->getType());
15226 const SCEV *Add = getAddExpr(AddRecToCheck->getStart(), ExitCount);
15227 if (isKnownPredicate(CmpInst::ICMP_SLT, Add, AddRecToCheck->getStart()))
15228 return nullptr;
15229 }
15230
15231 // Since the transformation was successful, we can now transfer the SCEV
15232 // predicates.
15233 Preds.append(TransformPreds.begin(), TransformPreds.end());
15234
15235 return AddRec;
15236}
15237
15238/// SCEV predicates
15242
15244 const ICmpInst::Predicate Pred,
15245 const SCEV *LHS, const SCEV *RHS)
15246 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
15247 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
15248 assert(LHS != RHS && "LHS and RHS are the same SCEV");
15249}
15250
15252 ScalarEvolution &SE) const {
15253 const auto *Op = dyn_cast<SCEVComparePredicate>(N);
15254
15255 if (!Op)
15256 return false;
15257
15258 if (Op->LHS != LHS || Op->RHS != RHS)
15259 return false;
15260
15261 return ICmpInst::isImpliedByMatchingCmp(Pred, Op->Pred) == true;
15262}
15263
15264bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
15265
15267 if (Pred == ICmpInst::ICMP_EQ)
15268 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
15269 else
15270 OS.indent(Depth) << "Compare predicate: " << *LHS << " " << Pred << ") "
15271 << *RHS << "\n";
15272
15273}
15274
15276 const SCEVAddRecExpr *AR,
15277 IncrementWrapFlags Flags)
15278 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
15279
15280const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
15281
15283 ScalarEvolution &SE) const {
15284 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
15285 if (!Op || setFlags(Flags, Op->Flags) != Flags)
15286 return false;
15287
15288 if (Op->AR == AR)
15289 return true;
15290
15291 if (Flags != SCEVWrapPredicate::IncrementNSSW &&
15293 return false;
15294
15295 const SCEV *Start = AR->getStart();
15296 const SCEV *OpStart = Op->AR->getStart();
15297 if (Start->getType()->isPointerTy() != OpStart->getType()->isPointerTy())
15298 return false;
15299
15300 // Reject pointers to different address spaces.
15301 if (Start->getType()->isPointerTy() && Start->getType() != OpStart->getType())
15302 return false;
15303
15304 // NUSW/NSSW on a wider-type AddRec does not imply the same on a
15305 // narrower-type AddRec.
15306 if (SE.getTypeSizeInBits(AR->getType()) >
15307 SE.getTypeSizeInBits(Op->AR->getType()))
15308 return false;
15309
15310 const SCEV *Step = AR->getStepRecurrence(SE);
15311 const SCEV *OpStep = Op->AR->getStepRecurrence(SE);
15312 if (!SE.isKnownPositive(Step) || !SE.isKnownPositive(OpStep))
15313 return false;
15314
15315 // If both steps are positive, this implies N, if N's start and step are
15316 // ULE/SLE (for NSUW/NSSW) than this'.
15317 Type *WiderTy = SE.getWiderType(Step->getType(), OpStep->getType());
15318 Step = SE.getNoopOrZeroExtend(Step, WiderTy);
15319 OpStep = SE.getNoopOrZeroExtend(OpStep, WiderTy);
15320
15321 bool IsNUW = Flags == SCEVWrapPredicate::IncrementNUSW;
15322 OpStart = IsNUW ? SE.getNoopOrZeroExtend(OpStart, WiderTy)
15323 : SE.getNoopOrSignExtend(OpStart, WiderTy);
15324 Start = IsNUW ? SE.getNoopOrZeroExtend(Start, WiderTy)
15325 : SE.getNoopOrSignExtend(Start, WiderTy);
15327 return SE.isKnownPredicate(Pred, OpStep, Step) &&
15328 SE.isKnownPredicate(Pred, OpStart, Start);
15329}
15330
15332 SCEVFlags ScevFlags = AR->getNoWrapFlags();
15333 IncrementWrapFlags IFlags = Flags;
15334
15335 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
15336 IFlags = clearFlags(IFlags, IncrementNSSW);
15337
15338 return IFlags == IncrementAnyWrap;
15339}
15340
15341void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
15342 OS.indent(Depth) << *getExpr() << " Added Flags: ";
15344 OS << "<nusw>";
15346 OS << "<nssw>";
15347 OS << "\n";
15348}
15349
15350/// Union predicates don't get cached so create a dummy set ID for it.
15352 ScalarEvolution &SE)
15354 for (const auto *P : Preds)
15355 add(P, SE);
15356}
15357
15359 return all_of(Preds,
15360 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
15361}
15362
15364 ScalarEvolution &SE) const {
15365 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
15366 return all_of(Set->Preds, [this, &SE](const SCEVPredicate *I) {
15367 return this->implies(I, SE);
15368 });
15369
15370 if (any_of(Preds,
15371 [N, &SE](const SCEVPredicate *I) { return I->implies(N, SE); }))
15372 return true;
15373
15374 // A wrap predicate may be implied by a wrap predicate in Preds after applying
15375 // equal predicates.
15376 const auto *NWrap = dyn_cast<SCEVWrapPredicate>(N);
15377 if (!NWrap)
15378 return false;
15379 const Loop *L = NWrap->getExpr()->getLoop();
15380 return any_of(Preds, [&](const SCEVPredicate *I) {
15381 const auto *IWrap = dyn_cast<SCEVWrapPredicate>(I);
15382 if (!IWrap)
15383 return false;
15384 const auto *RewrittenAR = dyn_cast<SCEVAddRecExpr>(
15385 SE.rewriteUsingPredicate(IWrap->getExpr(), L, *this));
15386 return RewrittenAR &&
15387 SE.getWrapPredicate(RewrittenAR, IWrap->getFlags())->implies(N, SE);
15388 });
15389}
15390
15392 for (const auto *Pred : Preds)
15393 Pred->print(OS, Depth);
15394}
15395
15396void SCEVUnionPredicate::add(const SCEVPredicate *N, ScalarEvolution &SE) {
15397 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
15398 for (const auto *Pred : Set->Preds)
15399 add(Pred, SE);
15400 return;
15401 }
15402
15403 // Implication checks are quadratic in the number of predicates. Stop doing
15404 // them if there are many predicates, as they should be too expensive to use
15405 // anyway at that point.
15406 bool CheckImplies = Preds.size() < 16;
15407
15408 // Only add predicate if it is not already implied by this union predicate.
15409 if (CheckImplies && implies(N, SE))
15410 return;
15411
15412 // Build a new vector containing the current predicates, except the ones that
15413 // are implied by the new predicate N.
15415 for (auto *P : Preds) {
15416 if (CheckImplies && N->implies(P, SE))
15417 continue;
15418 PrunedPreds.push_back(P);
15419 }
15420 Preds = std::move(PrunedPreds);
15421 Preds.push_back(N);
15422}
15423
15425 Loop &L)
15426 : SE(SE), L(L) {
15428 Preds = std::make_unique<SCEVUnionPredicate>(Empty, SE);
15429}
15430
15432 for (const SCEV *Op : Ops)
15433 // We do not expect that forgetting cached data for SCEVConstants will ever
15434 // open any prospects for sharpening or introduce any correctness issues,
15435 // so we don't bother storing their dependencies.
15436 if (!isa<SCEVConstant>(Op))
15437 SCEVUsers[Op].insert(User);
15438}
15439
15441 const SCEV *Expr = SE.getSCEV(V);
15442 return getPredicatedSCEV(Expr);
15443}
15444
15446 RewriteEntry &Entry = RewriteMap[Expr];
15447
15448 // If we already have an entry and the version matches, return it.
15449 if (Entry.second && Generation == Entry.first)
15450 return Entry.second;
15451
15452 // We found an entry but it's stale. Rewrite the stale entry
15453 // according to the current predicate.
15454 if (Entry.second)
15455 Expr = Entry.second;
15456
15457 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
15458 Entry = {Generation, NewSCEV};
15459
15460 return NewSCEV;
15461}
15462
15464 if (!BackedgeCount) {
15466 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
15467 for (const auto *P : Preds)
15468 addPredicate(*P);
15469 }
15470 return BackedgeCount;
15471}
15472
15474 if (!SymbolicMaxBackedgeCount) {
15476 SymbolicMaxBackedgeCount =
15477 SE.getPredicatedSymbolicMaxBackedgeTakenCount(&L, Preds);
15478 for (const auto *P : Preds)
15479 addPredicate(*P);
15480 }
15481 return SymbolicMaxBackedgeCount;
15482}
15483
15485 if (!SmallConstantMaxTripCount) {
15487 SmallConstantMaxTripCount = SE.getSmallConstantMaxTripCount(&L, &Preds);
15488 for (const auto *P : Preds)
15489 addPredicate(*P);
15490 }
15491 return *SmallConstantMaxTripCount;
15492}
15493
15495 if (Preds->implies(&Pred, SE))
15496 return;
15497
15498 Preds = std::make_unique<SCEVUnionPredicate>(Preds->getUnionWith(&Pred, SE));
15499 updateGeneration();
15500}
15501
15504 for (const SCEVPredicate *P : Preds)
15505 addPredicate(*P);
15506}
15507
15509 return *Preds;
15510}
15511
15512void PredicatedScalarEvolution::updateGeneration() {
15513 // If the generation number wrapped recompute everything.
15514 if (++Generation == 0) {
15515 for (auto &II : RewriteMap) {
15516 const SCEV *Rewritten = II.second.second;
15517 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
15518 }
15519 }
15520}
15521
15524 const SCEV *Expr = this->getSCEV(V);
15526 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
15527
15528 if (!New)
15529 return nullptr;
15530
15531 if (ExtraPreds) {
15532 ExtraPreds->append(NewPreds);
15533 return New;
15534 }
15535
15536 addPredicates(NewPreds);
15537
15538 RewriteMap[SE.getSCEV(V)] = {Generation, New};
15539 return New;
15540}
15541
15544 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
15545 Preds(std::make_unique<SCEVUnionPredicate>(*Init.Preds)),
15546 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {}
15547
15549 // For each block.
15550 for (auto *BB : L.getBlocks())
15551 for (auto &I : *BB) {
15552 if (!SE.isSCEVable(I.getType()))
15553 continue;
15554
15555 auto *Expr = SE.getSCEV(&I);
15556 auto II = RewriteMap.find(Expr);
15557
15558 if (II == RewriteMap.end())
15559 continue;
15560
15561 // Don't print things that are not interesting.
15562 if (II->second.second == Expr)
15563 continue;
15564
15565 OS.indent(Depth) << "[PSE]" << I << ":\n";
15566 OS.indent(Depth + 2) << *Expr << "\n";
15567 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
15568 }
15569}
15570
15571void ScalarEvolution::LoopGuards::collectPending() {
15572 const Loop *L = PendingLoop;
15573 if (!L)
15574 return;
15575 PendingLoop = nullptr;
15576 BasicBlock *Pred = L->getLoopPredecessor();
15577 if (!Pred)
15578 return;
15580 collectFromBlock(SE, *this, L->getHeader(), Pred, VisitedBlocks);
15581}
15582
15583void ScalarEvolution::LoopGuards::collectFromPHI(
15587 unsigned Depth) {
15588 if (!SE.isSCEVable(Phi.getType()))
15589 return;
15590
15591 using MinMaxPattern = std::pair<const SCEVConstant *, SCEVTypes>;
15592 auto GetMinMaxConst = [&](unsigned IncomingIdx) -> MinMaxPattern {
15593 const BasicBlock *InBlock = Phi.getIncomingBlock(IncomingIdx);
15594 if (!VisitedBlocks.insert(InBlock).second)
15595 return {nullptr, scCouldNotCompute};
15596
15597 // Avoid analyzing unreachable blocks so that we don't get trapped
15598 // traversing cycles with ill-formed dominance or infinite cycles
15599 if (!SE.DT.isReachableFromEntry(InBlock))
15600 return {nullptr, scCouldNotCompute};
15601
15602 auto [G, Inserted] = IncomingGuards.try_emplace(InBlock, LoopGuards(SE));
15603 if (Inserted)
15604 collectFromBlock(SE, G->second, Phi.getParent(), InBlock, VisitedBlocks,
15605 Depth + 1);
15606 auto &RewriteMap = G->second.RewriteMap;
15607 if (RewriteMap.empty())
15608 return {nullptr, scCouldNotCompute};
15609 auto S = RewriteMap.find(SE.getSCEV(Phi.getIncomingValue(IncomingIdx)));
15610 if (S == RewriteMap.end())
15611 return {nullptr, scCouldNotCompute};
15612 auto *SM = dyn_cast_if_present<SCEVMinMaxExpr>(S->second);
15613 if (!SM)
15614 return {nullptr, scCouldNotCompute};
15615 if (const SCEVConstant *C0 = dyn_cast<SCEVConstant>(SM->getOperand(0)))
15616 return {C0, SM->getSCEVType()};
15617 return {nullptr, scCouldNotCompute};
15618 };
15619 auto MergeMinMaxConst = [](MinMaxPattern P1,
15620 MinMaxPattern P2) -> MinMaxPattern {
15621 auto [C1, T1] = P1;
15622 auto [C2, T2] = P2;
15623 if (!C1 || !C2 || T1 != T2)
15624 return {nullptr, scCouldNotCompute};
15625 switch (T1) {
15626 case scUMaxExpr:
15627 return {C1->getAPInt().ult(C2->getAPInt()) ? C1 : C2, T1};
15628 case scSMaxExpr:
15629 return {C1->getAPInt().slt(C2->getAPInt()) ? C1 : C2, T1};
15630 case scUMinExpr:
15631 return {C1->getAPInt().ugt(C2->getAPInt()) ? C1 : C2, T1};
15632 case scSMinExpr:
15633 return {C1->getAPInt().sgt(C2->getAPInt()) ? C1 : C2, T1};
15634 default:
15635 llvm_unreachable("Trying to merge non-MinMaxExpr SCEVs.");
15636 }
15637 };
15638 auto P = GetMinMaxConst(0);
15639 for (unsigned int In = 1; In < Phi.getNumIncomingValues(); In++) {
15640 if (!P.first)
15641 break;
15642 P = MergeMinMaxConst(P, GetMinMaxConst(In));
15643 }
15644 if (P.first) {
15645 const SCEV *LHS = SE.getSCEV(const_cast<PHINode *>(&Phi));
15646 SmallVector<SCEVUse, 2> Ops({P.first, LHS});
15647 const SCEV *RHS = SE.getMinMaxExpr(P.second, Ops);
15648 Guards.RewriteMap.insert({LHS, RHS});
15649 }
15650}
15651
15652// Return a new SCEV that modifies \p Expr to the closest number divides by
15653// \p Divisor and less or equal than Expr. For now, only handle constant
15654// Expr.
15656 const APInt &DivisorVal,
15657 ScalarEvolution &SE) {
15658 const APInt *ExprVal;
15659 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15660 DivisorVal.isNonPositive())
15661 return Expr;
15662 APInt Rem = ExprVal->urem(DivisorVal);
15663 // return the SCEV: Expr - Expr % Divisor
15664 return SE.getConstant(*ExprVal - Rem);
15665}
15666
15667// Return a new SCEV that modifies \p Expr to the closest number divides by
15668// \p Divisor and greater or equal than Expr. For now, only handle constant
15669// Expr.
15670static const SCEV *getNextSCEVDivisibleByDivisor(const SCEV *Expr,
15671 const APInt &DivisorVal,
15672 ScalarEvolution &SE) {
15673 const APInt *ExprVal;
15674 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15675 DivisorVal.isNonPositive())
15676 return Expr;
15677 APInt Rem = ExprVal->urem(DivisorVal);
15678 if (Rem.isZero())
15679 return Expr;
15680 // return the SCEV: Expr + Divisor - Expr % Divisor
15681 return SE.getConstant(*ExprVal + DivisorVal - Rem);
15682}
15683
15685 ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS,
15688 // If we have LHS == 0, check if LHS is computing a property of some unknown
15689 // SCEV %v which we can rewrite %v to express explicitly.
15691 return false;
15692 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
15693 // explicitly express that.
15694 const SCEVUnknown *URemLHS = nullptr;
15695 const SCEV *URemRHS = nullptr;
15696 if (!match(LHS, m_scev_URem(m_SCEVUnknown(URemLHS), m_SCEV(URemRHS), SE)))
15697 return false;
15698
15699 const SCEV *Multiple =
15700 SE.getMulExpr(SE.getUDivExpr(URemLHS, URemRHS), URemRHS);
15701 DivInfo[URemLHS] = Multiple;
15702 if (auto *C = dyn_cast<SCEVConstant>(URemRHS))
15703 Multiples[URemLHS] = C->getAPInt();
15704 return true;
15705}
15706
15707// Check if the condition is a divisibility guard (A % B == 0).
15708static bool isDivisibilityGuard(const SCEV *LHS, const SCEV *RHS,
15709 ScalarEvolution &SE) {
15710 const SCEV *X, *Y;
15711 return match(LHS, m_scev_URem(m_SCEV(X), m_SCEV(Y), SE)) && RHS->isZero();
15712}
15713
15714// Apply divisibility by \p Divisor on MinMaxExpr with constant values,
15715// recursively. This is done by aligning up/down the constant value to the
15716// Divisor.
15717static const SCEV *applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr,
15718 const APInt &Divisor,
15719 ScalarEvolution &SE) {
15720 // Only handle min/max expressions of a non-negative constant and another
15721 // operand.
15722 const SCEVConstant *C;
15723 const SCEV *Op;
15724 if (!match(MinMaxExpr, m_scev_MinMax(m_SCEVConstant(C), m_SCEV(Op))) ||
15725 C->getAPInt().isNegative())
15726 return MinMaxExpr;
15727 auto *DivisibleExpr = isa<SCEVSMinExpr, SCEVUMinExpr>(MinMaxExpr)
15728 ? getPreviousSCEVDivisibleByDivisor(C, Divisor, SE)
15729 : getNextSCEVDivisibleByDivisor(C, Divisor, SE);
15731 DivisibleExpr};
15732 return SE.getMinMaxExpr(MinMaxExpr->getSCEVType(), Ops);
15733}
15734
15735void ScalarEvolution::LoopGuards::collectFromBlock(
15736 ScalarEvolution &SE, ScalarEvolution::LoopGuards &Guards,
15737 const BasicBlock *Block, const BasicBlock *Pred,
15738 SmallPtrSetImpl<const BasicBlock *> &VisitedBlocks, unsigned Depth) {
15739
15741
15742 SmallVector<SCEVUse> ExprsToRewrite;
15743 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
15744 const SCEV *RHS,
15745 DenseMap<const SCEV *, const SCEV *> &RewriteMap,
15746 const LoopGuards &DivGuards) {
15747 // WARNING: It is generally unsound to apply any wrap flags to the proposed
15748 // replacement SCEV which isn't directly implied by the structure of that
15749 // SCEV. In particular, using contextual facts to imply flags is *NOT*
15750 // legal. See the scoping rules for flags in the header to understand why.
15751
15752 // Puts rewrite rule \p From -> \p To into the rewrite map. Also if \p From
15753 // and \p FromRewritten are the same (i.e. there has been no rewrite
15754 // registered for \p From), then puts this value in the list of rewritten
15755 // expressions.
15756 auto AddRewrite = [&](const SCEV *From, const SCEV *FromRewritten,
15757 const SCEV *To) {
15758 if (From == FromRewritten)
15759 ExprsToRewrite.push_back(From);
15760 RewriteMap[From] = To;
15761 };
15762
15763 // Checks whether \p S has already been rewritten. In that case returns the
15764 // existing rewrite because we want to chain further rewrites onto the
15765 // already rewritten value. Otherwise returns \p S.
15766 auto GetMaybeRewritten = [&](const SCEV *S) {
15767 return RewriteMap.lookup_or(S, S);
15768 };
15769
15770 // Check for a condition of the form (-C1 + X < C2). InstCombine will
15771 // create this form when combining two checks of the form (X u< C2 + C1) and
15772 // (X >=u C1).
15773 auto MatchRangeCheckIdiom = [&](ICmpInst::Predicate Pred,
15774 const SCEV *MatchLHS,
15775 const SCEV *MatchRHS) {
15776 const SCEVConstant *C1;
15777 const SCEVUnknown *LHSUnknown;
15778 auto *C2 = dyn_cast<SCEVConstant>(MatchRHS);
15779 if (!match(MatchLHS,
15780 m_scev_Add(m_SCEVConstant(C1), m_SCEVUnknown(LHSUnknown))) ||
15781 !C2)
15782 return false;
15783
15784 auto ExactRegion =
15786 .sub(C1->getAPInt());
15787
15788 // Tighten the raw range with what we already know about LHSUnknown
15789 // from prior guards recorded in RewriteMap, or from SCEV's own range
15790 // analysis.
15791 const SCEV *RewrittenLHS = GetMaybeRewritten(LHSUnknown);
15792 ExactRegion = ExactRegion.intersectWith(SE.getUnsignedRange(RewrittenLHS),
15794
15795 // Bail if the guard is inconsistent with prior facts, or if the range
15796 // is still not a monotonic non-wrapping interval after tightening.
15797 if (ExactRegion.isEmptySet() || ExactRegion.isWrappedSet() ||
15798 ExactRegion.isFullSet())
15799 return false;
15800
15801 const SCEV *RegionMin = SE.getConstant(ExactRegion.getUnsignedMin());
15802 const SCEV *RegionMax = SE.getConstant(ExactRegion.getUnsignedMax());
15803 const SCEV *ClampedLHS =
15804 SE.getUMaxExpr(RegionMin, SE.getUMinExpr(RewrittenLHS, RegionMax));
15805 AddRewrite(LHSUnknown, RewrittenLHS, ClampedLHS);
15806 return true;
15807 };
15808 if (MatchRangeCheckIdiom(Predicate, LHS, RHS))
15809 return;
15810
15811 // Do not apply information for constants or if RHS contains an AddRec.
15813 return;
15814
15815 // If RHS is SCEVUnknown, make sure the information is applied to it.
15817 std::swap(LHS, RHS);
15819 }
15820
15821 const SCEV *RewrittenLHS = GetMaybeRewritten(LHS);
15822 // Apply divisibility information when computing the constant multiple.
15823 const APInt &DividesBy =
15824 SE.getConstantMultiple(DivGuards.rewrite(RewrittenLHS));
15825
15826 // Collect rewrites for LHS and its transitive operands based on the
15827 // condition.
15828 // For min/max expressions, also apply the guard to its operands:
15829 // 'min(a, b) >= c' -> '(a >= c) and (b >= c)',
15830 // 'min(a, b) > c' -> '(a > c) and (b > c)',
15831 // 'max(a, b) <= c' -> '(a <= c) and (b <= c)',
15832 // 'max(a, b) < c' -> '(a < c) and (b < c)'.
15833
15834 // We cannot express strict predicates in SCEV, so instead we replace them
15835 // with non-strict ones against plus or minus one of RHS depending on the
15836 // predicate.
15837 const SCEV *One = SE.getOne(RHS->getType());
15838 switch (Predicate) {
15839 case CmpInst::ICMP_ULT:
15840 if (RHS->getType()->isPointerTy())
15841 return;
15842 RHS = SE.getUMaxExpr(RHS, One);
15843 [[fallthrough]];
15844 case CmpInst::ICMP_SLT: {
15845 RHS = SE.getMinusSCEV(RHS, One);
15846 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
15847 break;
15848 }
15849 case CmpInst::ICMP_UGT:
15850 case CmpInst::ICMP_SGT:
15851 RHS = SE.getAddExpr(RHS, One);
15852 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
15853 break;
15854 case CmpInst::ICMP_ULE:
15855 case CmpInst::ICMP_SLE:
15856 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
15857 break;
15858 case CmpInst::ICMP_UGE:
15859 case CmpInst::ICMP_SGE:
15860 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
15861 break;
15862 default:
15863 break;
15864 }
15865
15866 SmallVector<SCEVUse, 16> Worklist(1, LHS);
15867 SmallPtrSet<const SCEV *, 16> Visited;
15868
15869 auto EnqueueOperands = [&Worklist](const SCEVNAryExpr *S) {
15870 append_range(Worklist, S->operands());
15871 };
15872
15873 while (!Worklist.empty()) {
15874 const SCEV *From = Worklist.pop_back_val();
15875 if (isa<SCEVConstant>(From))
15876 continue;
15877 if (!Visited.insert(From).second)
15878 continue;
15879 const SCEV *FromRewritten = GetMaybeRewritten(From);
15880 const SCEV *To = nullptr;
15881
15882 switch (Predicate) {
15883 case CmpInst::ICMP_ULT:
15884 case CmpInst::ICMP_ULE:
15885 To = SE.getUMinExpr(FromRewritten, RHS);
15886 if (auto *UMax = dyn_cast<SCEVUMaxExpr>(FromRewritten))
15887 EnqueueOperands(UMax);
15888 break;
15889 case CmpInst::ICMP_SLT:
15890 case CmpInst::ICMP_SLE:
15891 To = SE.getSMinExpr(FromRewritten, RHS);
15892 if (auto *SMax = dyn_cast<SCEVSMaxExpr>(FromRewritten))
15893 EnqueueOperands(SMax);
15894 break;
15895 case CmpInst::ICMP_UGT:
15896 case CmpInst::ICMP_UGE:
15897 To = SE.getUMaxExpr(FromRewritten, RHS);
15898 if (auto *UMin = dyn_cast<SCEVUMinExpr>(FromRewritten))
15899 EnqueueOperands(UMin);
15900 break;
15901 case CmpInst::ICMP_SGT:
15902 case CmpInst::ICMP_SGE: {
15903 // From s>= RHS s>= 0 implies From u>= RHS, so an earlier
15904 // umax(C, From) with C u<= RHS is redundant. Drop it, as the range of
15905 // the umax may be much less precise than the one of From.
15906 const APInt *C, *RHSC;
15907 if (match(RHS, m_scev_APInt(RHSC)) && RHSC->isNonNegative() &&
15908 match(FromRewritten,
15910 C->ule(*RHSC))
15911 FromRewritten = From;
15912 To = SE.getSMaxExpr(FromRewritten, RHS);
15913 if (auto *SMin = dyn_cast<SCEVSMinExpr>(FromRewritten))
15914 EnqueueOperands(SMin);
15915 break;
15916 }
15917 case CmpInst::ICMP_EQ:
15919 To = RHS;
15920 break;
15921 case CmpInst::ICMP_NE:
15922 if (match(RHS, m_scev_Zero())) {
15923 const SCEV *OneAlignedUp =
15924 getNextSCEVDivisibleByDivisor(One, DividesBy, SE);
15925 To = SE.getUMaxExpr(FromRewritten, OneAlignedUp);
15926 } else {
15927 // LHS != RHS can be rewritten as (LHS - RHS) = UMax(1, LHS - RHS),
15928 // but creating the subtraction eagerly is expensive. Track the
15929 // inequalities in a separate map, and materialize the rewrite lazily
15930 // when encountering a suitable subtraction while re-writing.
15931 if (LHS->getType()->isPointerTy()) {
15932 LHS = SE.getPtrToAddrExpr(LHS);
15933 RHS = SE.getPtrToAddrExpr(RHS);
15935 break;
15936 }
15937 const SCEVConstant *C;
15938 const SCEV *A, *B;
15941 RHS = A;
15942 LHS = B;
15943 }
15944 if (LHS > RHS)
15945 std::swap(LHS, RHS);
15946 Guards.NotEqual.insert({LHS, RHS});
15947 continue;
15948 }
15949 break;
15950 default:
15951 break;
15952 }
15953
15954 if (To)
15955 AddRewrite(From, FromRewritten, To);
15956 }
15957 };
15958
15960 // First, collect information from assumptions dominating the loop.
15961 for (auto &AssumeVH : SE.AC.assumptions()) {
15962 if (!AssumeVH)
15963 continue;
15964 auto *AssumeI = cast<CallInst>(AssumeVH);
15965 if (!SE.DT.dominates(AssumeI, Block))
15966 continue;
15967 Terms.emplace_back(AssumeI->getOperand(0), true);
15968 }
15969
15970 // Second, collect information from llvm.experimental.guards dominating the loop.
15971 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
15972 SE.F.getParent(), Intrinsic::experimental_guard);
15973 if (GuardDecl)
15974 for (const auto *GU : GuardDecl->users())
15975 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
15976 if (Guard->getFunction() == Block->getParent() &&
15977 SE.DT.dominates(Guard, Block))
15978 Terms.emplace_back(Guard->getArgOperand(0), true);
15979
15980 // Third, collect conditions from dominating branches. Starting at the loop
15981 // predecessor, climb up the predecessor chain, as long as there are
15982 // predecessors that can be found that have unique successors leading to the
15983 // original header. If there is no such predecessor, continue at the
15984 // immediate dominator.
15985 // TODO: share this logic with isLoopEntryGuardedByCond.
15986 unsigned NumCollectedConditions = 0;
15987 unsigned NumDomTreeSteps = 0;
15989 std::pair<const BasicBlock *, const BasicBlock *> Pair(Pred, Block);
15990 for (;; Pair = SE.getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
15991 if (!Pair.first) {
15992 // At the first block without a unique predecessor, try to build
15993 // conditions for its phis by merging those of their incoming blocks.
15994 if (!NumDomTreeSteps &&
15995 Depth < SE.Opts.scalar_evolution_max_loop_guard_collection_depth) {
15996 SmallDenseMap<const BasicBlock *, LoopGuards> IncomingGuards;
15997 for (auto &Phi : Pair.second->phis())
15998 collectFromPHI(SE, Guards, Phi, VisitedBlocks, IncomingGuards, Depth);
15999 }
16000 const DomTreeNode *IDom = SE.DT.getNode(Pair.second)->getIDom();
16001 if (!IDom ||
16002 ++NumDomTreeSteps > SE.Opts.scalar_evolution_max_guard_dom_tree_steps)
16003 break;
16004 Pair.first = IDom->getBlock();
16005 continue;
16006 }
16007 VisitedBlocks.insert(Pair.second);
16008 const CondBrInst *LoopEntryPredicate =
16009 dyn_cast<CondBrInst>(Pair.first->getTerminator());
16010 if (!LoopEntryPredicate)
16011 continue;
16012
16013 Terms.emplace_back(LoopEntryPredicate->getCondition(),
16014 LoopEntryPredicate->getSuccessor(0) == Pair.second);
16015 NumCollectedConditions++;
16016
16017 // If we are recursively collecting guards stop after 2
16018 // conditions to limit compile-time impact for now.
16019 if (Depth > 0 && NumCollectedConditions == 2)
16020 break;
16021 }
16022
16023 // Now apply the information from the collected conditions to
16024 // Guards.RewriteMap. Conditions are processed in reverse order, so the
16025 // earliest conditions is processed first, except guards with divisibility
16026 // information, which are moved to the back. This ensures the SCEVs with the
16027 // shortest dependency chains are constructed first.
16029 GuardsToProcess;
16030 for (auto [Term, EnterIfTrue] : reverse(Terms)) {
16031 SmallVector<Value *, 8> Worklist;
16032 SmallPtrSet<Value *, 8> Visited;
16033 Worklist.push_back(Term);
16034 while (!Worklist.empty()) {
16035 Value *Cond = Worklist.pop_back_val();
16036 if (!Visited.insert(Cond).second)
16037 continue;
16038
16039 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
16040 auto Predicate =
16041 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
16042 const auto *LHS = SE.getSCEV(Cmp->getOperand(0));
16043 const auto *RHS = SE.getSCEV(Cmp->getOperand(1));
16044 // If LHS is a constant, apply information to the other expression.
16045 // TODO: If LHS is not a constant, check if using compareSCEVComplexity
16046 // can improve results.
16047 if (isa<SCEVConstant>(LHS)) {
16048 std::swap(LHS, RHS);
16050 }
16051 GuardsToProcess.emplace_back(Predicate, LHS, RHS);
16052 continue;
16053 }
16054
16055 Value *L, *R;
16056 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
16057 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
16058 Worklist.push_back(L);
16059 Worklist.push_back(R);
16060 }
16061 }
16062 }
16063
16064 // Process divisibility guards in reverse order to populate DivGuards early.
16065 DenseMap<const SCEV *, APInt> Multiples;
16066 LoopGuards DivGuards(SE);
16067 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess) {
16068 if (!isDivisibilityGuard(LHS, RHS, SE))
16069 continue;
16070 collectDivisibilityInformation(Predicate, LHS, RHS, DivGuards.RewriteMap,
16071 Multiples, SE);
16072 }
16073
16074 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess)
16075 CollectCondition(Predicate, LHS, RHS, Guards.RewriteMap, DivGuards);
16076
16077 // Apply divisibility information last. This ensures it is applied to the
16078 // outermost expression after other rewrites for the given value.
16079 for (const auto &[K, Divisor] : Multiples) {
16080 const SCEV *DivisorSCEV = SE.getConstant(Divisor);
16081 Guards.RewriteMap[K] =
16083 Guards.rewrite(K), Divisor, SE),
16084 DivisorSCEV),
16085 DivisorSCEV);
16086 ExprsToRewrite.push_back(K);
16087 }
16088
16089 // Let the rewriter preserve NUW/NSW flags if the unsigned/signed ranges of
16090 // the replacement expressions are contained in the ranges of the replaced
16091 // expressions.
16092 Guards.PreserveNUW = true;
16093 Guards.PreserveNSW = true;
16094 for (const SCEV *Expr : ExprsToRewrite) {
16095 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16096 Guards.PreserveNUW &=
16097 SE.getUnsignedRange(Expr).contains(SE.getUnsignedRange(RewriteTo));
16098 Guards.PreserveNSW &=
16099 SE.getSignedRange(Expr).contains(SE.getSignedRange(RewriteTo));
16100 }
16101
16102 // Now that all rewrite information is collect, rewrite the collected
16103 // expressions with the information in the map. This applies information to
16104 // sub-expressions. A collected expression is rewritten when it is first
16105 // looked up, so the rewrites of the expressions it contains are used once
16106 // they are final.
16107 if (ExprsToRewrite.size() > 1) {
16108 constexpr unsigned MaxDepth = 16;
16109 unsigned Depth = 0;
16110 SmallPtrSet<const SCEV *, 16> ToRewrite(llvm::from_range, ExprsToRewrite);
16111 std::function<const SCEV *(const SCEV *)> Lookup = [&](const SCEV *Expr) {
16112 if (Depth < MaxDepth && ToRewrite.erase(Expr)) {
16113 auto It = Guards.RewriteMap.find(Expr);
16114 assert(It != Guards.RewriteMap.end() && "Expected rewrite entry");
16115 const SCEV *RewriteTo = It->second;
16116 Guards.RewriteMap.erase(It);
16117 SaveAndRestore Nest(Depth, Depth + 1);
16118 const SCEV *Rewritten = Guards.rewrite(RewriteTo, Lookup);
16119 Guards.RewriteMap[Expr] = Rewritten;
16120 return Rewritten;
16121 }
16122 return Guards.RewriteMap.lookup(Expr);
16123 };
16124 for (const SCEV *Expr : ExprsToRewrite)
16125 Lookup(Expr);
16126 }
16127}
16128
16129const SCEV *ScalarEvolution::LoopGuards::rewrite(const SCEV *Expr) const {
16130 return rewrite(Expr, nullptr);
16131}
16132
16133const SCEV *ScalarEvolution::LoopGuards::rewrite(
16134 const SCEV *Expr, function_ref<const SCEV *(const SCEV *)> Lookup) const {
16135 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
16136 /// in the map. It skips AddRecExpr because we cannot guarantee that the
16137 /// replacement is loop invariant in the loop of the AddRec.
16138 class SCEVLoopGuardRewriter
16139 : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
16142 function_ref<const SCEV *(const SCEV *)> Lookup;
16143
16144 SCEVFlags FlagMask = SCEV::FlagNone;
16145
16146 const SCEV *lookup(const SCEV *Key) {
16147 return Lookup ? Lookup(Key) : Map.lookup(Key);
16148 }
16149
16150 public:
16151 SCEVLoopGuardRewriter(ScalarEvolution &SE,
16152 const ScalarEvolution::LoopGuards &Guards,
16153 function_ref<const SCEV *(const SCEV *)> Lookup)
16154 : SCEVRewriteVisitor(SE), Map(Guards.RewriteMap),
16155 NotEqual(Guards.NotEqual), Lookup(Lookup) {
16156 if (Guards.PreserveNUW)
16157 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNUW);
16158 if (Guards.PreserveNSW)
16159 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNSW);
16160 }
16161
16162 const SCEV *visit(const SCEV *Expr) {
16165 SCEVMulExpr>(Expr))
16166 if (const SCEV *S = lookup(Expr))
16167 return S;
16168 return SCEVRewriteVisitor::visit(Expr);
16169 }
16170
16171 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
16172
16173 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
16174 // If there is no replacement for the exact ZExt expr, check if there's
16175 // one for a smaller ZExt we can use instead.
16176 Type *Ty = Expr->getType();
16177 const SCEV *Op = Expr->getOperand(0);
16178 unsigned Bitwidth = Ty->getScalarSizeInBits() / 2;
16179 while (Bitwidth % 8 == 0 && Bitwidth >= 8 &&
16180 Bitwidth > Op->getType()->getScalarSizeInBits()) {
16181 Type *NarrowTy = IntegerType::get(SE.getContext(), Bitwidth);
16182 auto *NarrowExt = SE.getZeroExtendExpr(Op, NarrowTy);
16183 if (const SCEV *S = lookup(NarrowExt))
16184 return SE.getZeroExtendExpr(S, Ty);
16185 Bitwidth = Bitwidth / 2;
16186 }
16187
16189 }
16190
16191 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
16192 // Helper to check if S is a subtraction (A - B) where A != B, and if so,
16193 // return UMax(S, 1).
16194 auto RewriteSubtraction = [&](const SCEV *S) -> const SCEV * {
16195 SCEVUse LHS, RHS;
16196 if (MatchBinarySub(S, LHS, RHS)) {
16197 if (LHS > RHS)
16198 std::swap(LHS, RHS);
16199 if (NotEqual.contains({LHS, RHS})) {
16200 const SCEV *OneAlignedUp = getNextSCEVDivisibleByDivisor(
16201 SE.getOne(S->getType()), SE.getConstantMultiple(S), SE);
16202 return SE.getUMaxExpr(OneAlignedUp, S);
16203 }
16204 }
16205 return nullptr;
16206 };
16207
16208 // Check if Expr itself is a subtraction pattern with guard info.
16209 if (const SCEV *Rewritten = RewriteSubtraction(Expr))
16210 return Rewritten;
16211
16212 // Trip count expressions sometimes consist of adding 3 operands, i.e.
16213 // (Const + A + B). There may be guard info for A + B, and if so, apply
16214 // it.
16215 // TODO: Could more generally apply guards to Add sub-expressions.
16216 if (isa<SCEVConstant>(Expr->getOperand(0))) {
16217 if (Expr->getNumOperands() == 3) {
16218 const SCEV *Add =
16219 SE.getAddExpr(Expr->getOperand(1), Expr->getOperand(2));
16220 if (const SCEV *Rewritten = RewriteSubtraction(Add))
16221 return SE.getAddExpr(
16222 Expr->getOperand(0), Rewritten,
16223 ScalarEvolution::maskFlags(Expr->getNoWrapFlags(), FlagMask));
16224 if (const SCEV *S = lookup(Add))
16225 return SE.getAddExpr(Expr->getOperand(0), S);
16226 }
16227
16228 // For expressions of the form (Const + A), check if we have guard info
16229 // for (Const + 1 + A), and rewrite to ((Const + 1 + A) - 1). This makes
16230 // sure we don't lose information when rewriting expressions based on
16231 // back-edge taken counts in some cases.
16232 if (Expr->getNumOperands() == 2) {
16233 const SCEV *S = nullptr;
16234 // Handle (-1 + 1 + A) without constructing SCEVs.
16235 if (match(Expr->getOperand(0), m_scev_AllOnes())) {
16236 S = lookup(Expr->getOperand(1));
16237 } else {
16238 const SCEV *NewC =
16239 SE.getAddExpr(Expr->getOperand(0), SE.getOne(Expr->getType()));
16240 S = lookup(SE.getAddExpr(NewC, Expr->getOperand(1)));
16241 }
16242 if (S)
16243 return SE.getAddExpr(S, SE.getMinusOne(Expr->getType()));
16244 }
16245 }
16247 bool Changed = false;
16248 for (SCEVUse Op : Expr->operands()) {
16249 Operands.push_back(visit(Op));
16250 Changed |= Op != Operands.back();
16251 }
16252 // We are only replacing operands with equivalent values, so transfer the
16253 // flags from the original expression.
16254 return !Changed ? Expr
16255 : SE.getAddExpr(Operands,
16257 Expr->getNoWrapFlags(), FlagMask));
16258 }
16259
16260 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
16262 bool Changed = false;
16263 for (SCEVUse Op : Expr->operands()) {
16264 Operands.push_back(visit(Op));
16265 Changed |= Op != Operands.back();
16266 }
16267 // We are only replacing operands with equivalent values, so transfer the
16268 // flags from the original expression.
16269 return !Changed ? Expr
16270 : SE.getMulExpr(Operands,
16272 Expr->getNoWrapFlags(), FlagMask));
16273 }
16274 };
16275
16276 if (RewriteMap.empty() && NotEqual.empty())
16277 return Expr;
16278
16279 SCEVLoopGuardRewriter Rewriter(SE, *this, Lookup);
16280 return Rewriter.visit(Expr);
16281}
16282
16283const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
16284 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
16285 return applyLoopGuards(Expr, Guards);
16286}
16287
16289 LoopGuards &Guards) {
16290 // Loop guards never rewrite constants and AddRecs, so there is no need to
16291 // collect pending guards for them.
16293 return Expr;
16294 if (Guards.PendingLoop)
16295 Guards.collectPending();
16296 return Guards.rewrite(Expr);
16297}
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t 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
bpf unwind BPF Unwind Lower
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
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:702
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)
IRTranslator LLVM IR MI
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This defines the Use class.
iv Induction Variable Users
Definition IVUsers.cpp:48
static bool lookup(const GsymReader &GR, GsymDataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
static bool hasNoUnsignedWrap(BinaryOperator &I)
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:550
#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
if(PassOpts->AAPipeline)
#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
MachineBasicBlock * Folded
SmallVector< MachineOperand, 4 > Cond
int64_t C1
int64_t C0
unsigned ExpectedFlags
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 const Loop * isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI)
static unsigned getConstantTripCount(const SCEVConstant *ExitCount)
static const SCEV * getNextSCEVDivisibleByDivisor(const SCEV *Expr, const APInt &DivisorVal, ScalarEvolution &SE)
static PHINode * getConstantEvolvingPHIOperands(const AnalysisOptions &Opts, Instruction *UseInst, const Loop *L, DenseMap< Instruction *, PHINode * > &PHIMap, const TargetLibraryInfo *TLI, unsigned Depth)
getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by recursing through each instructi...
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 bool hasHugeExpression(const AnalysisOptions &Opts, ArrayRef< SCEVUse > Ops)
Returns true if Ops contains a huge SCEV (the subtree of S contains at least -scalar-evolution-huge-e...
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 std::optional< BinaryOp > MatchBinaryOp(Value *V, const DominatorTree &DT)
Try to map V into a BinaryOp, and return std::nullopt on failure.
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 BinaryOperator * getCommonInstForPHI(PHINode *PN)
static PHINode * getConstantEvolvingPHI(const AnalysisOptions &Opts, 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 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 bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, const SCEV *Candidate)
Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
static SCEVFlags getNoWrapFlagsForGEP(GEPOperator *GEP, const SCEV *Accum, ScalarEvolution &SE)
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 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 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 const SCEV * applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr, const APInt &Divisor, ScalarEvolution &SE)
static const SCEV * constantFoldAndGroupOps(const AnalysisOptions &Opts, 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 int compareValueComplexity(const AnalysisOptions &Opts, 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 bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
static const SCEV * getPreStartForExtend(const SCEVAddRecExpr *AR, ScalarEvolution *SE, unsigned Depth)
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 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 int compareSCEVComplexity(const AnalysisOptions &Opts, const LoopInfo *const LI, SCEVUse LHS, SCEVUse RHS, DominatorTree &DT)
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 CollectAddOperandsWithScales(SmallDenseMap< const SCEV *, 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 bool isKnownPredicateExtendIdiom(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
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 SCEVFlags StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, ArrayRef< SCEVUse > Ops, SCEVFlags Flags)
static void groupByComplexity(const AnalysisOptions &Opts, 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 APInt extractConstantWithoutWrapping(ScalarEvolution &SE, const SCEVConstant *ConstantTerm, const SCEVAddExpr *WholeAddExpr)
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 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< 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 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 bool scevUnconditionallyPropagatesPoisonFromOperands(SCEVTypes Kind)
static Constant * getOtherIncomingValue(PHINode *PN, BasicBlock *BB)
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.
virt reg Virtual Register Rewriter
static int Lookup(ArrayRef< TableEntry > Table, unsigned Opcode)
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:2018
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
APInt abs() const
Get the absolute value.
Definition APInt.h:1815
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:212
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1973
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
bool isNonPositive() const
Determine if this APInt Value is non-positive (<= 0).
Definition APInt.h:357
unsigned countTrailingZeros() const
Definition APInt.h:1667
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:352
unsigned logBase2() const
Definition APInt.h:1781
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:471
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1303
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
bool isSignBitSet() const
Determine if sign bit of this APInt is set.
Definition APInt.h:337
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1134
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition APInt.h:428
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
AnalysisUsage & addRequiredTransitive()
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
MutableArrayRef< WeakVH > assumptions()
Access the list of assumption handles currently tracked for this function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
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:463
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 getNonStrictPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
Definition InstrTypes.h:934
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...
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:1518
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.
bool isSingleElement() const
Return true if this set contains exactly one member.
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 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:44
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:794
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:757
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:762
bool empty() const
Definition DenseMap.h:716
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition DenseMap.h:678
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:793
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive,...
Definition DenseMap.h:779
void swap(DenseMapBase &RHS)
Definition DenseMap.h:975
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
DomTreeNodeBase * getIDom() const
NodeT * getBlock() const
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
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:314
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.
static LLVM_ABI std::optional< bool > isImpliedByMatchingCmp(CmpPredicate Pred1, CmpPredicate Pred2)
Determine if Pred1 implies Pred2 is true, false, or if nothing can be inferred about the implication,...
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:333
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:598
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
BlockT * getHeader() const
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:623
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
LLVM_ABI bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:64
Metadata node.
Definition Metadata.h:1087
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition Operator.h:113
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition Operator.h:107
iterator_range< const_block_iterator > blocks() const
op_range incoming_values()
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
PointerIntPair - This class implements a pair of a pointer and small integer.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
LLVM_ABI void addPredicate(const SCEVPredicate &Pred)
Adds a new predicate.
LLVM_ABI const SCEVPredicate & getPredicate() const
LLVM_ABI const SCEV * getPredicatedSCEV(const SCEV *Expr)
Returns the rewritten SCEV for Expr in the context of the current SCEV predicate.
LLVM_ABI bool areAddRecsEqualWithPreds(const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2, ArrayRef< const SCEVPredicate * > ExtraPreds={}) const
Check if AR1 and AR2 are equal, while taking into account Equal predicates in Preds and ExtraPreds.
LLVM_ABI const SCEVAddRecExpr * getAsAddRec(Value *V, SmallVectorImpl< const SCEVPredicate * > *WrapPredsAdded=nullptr)
Attempts to produce an AddRecExpr for V by adding additional SCEV predicates.
LLVM_ABI void print(raw_ostream &OS, unsigned Depth) const
Print the SCEV mappings done by the Predicated Scalar Evolution.
LLVM_ABI PredicatedScalarEvolution(ScalarEvolution &SE, Loop &L)
LLVM_ABI unsigned getSmallConstantMaxTripCount()
Returns the upper bound of the loop trip count as a normal unsigned value, or 0 if the trip count is ...
LLVM_ABI void addPredicates(ArrayRef< const SCEVPredicate * > Preds)
Adds all predicates in Preds.
LLVM_ABI const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSymbolicMaxBackedgeTakenCount()
Get the (predicated) symbolic max backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:276
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(SCEVFlags 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)
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
SCEVFlags getNoWrapFlags(SCEVFlags Mask=FlagsNoWrapMask) 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.
SCEVUse visitZeroExtendExpr(SCEVUseT< const SCEVZeroExtendExpr * > 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 SCEVFlags, but with slightly different semantics for FlagNUSW.
SCEVWrapPredicate(const FoldingSetNodeIDRef ID, const SCEVAddRecExpr *AR, IncrementWrapFlags Flags)
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Returns true if this predicate implies N.
static SCEVWrapPredicate::IncrementWrapFlags setFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OnFlags)
void print(raw_ostream &OS, unsigned Depth=0) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool isAlwaysTrue() const override
Returns true if the predicate is always true.
const SCEVAddRecExpr * getExpr() const
Implementation of the SCEVPredicate interface.
static SCEVWrapPredicate::IncrementWrapFlags clearFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OffFlags)
Convenient IncrementWrapFlags manipulation methods.
IncrementWrapFlags getFlags() const
Returns the set assumed no overflow flags.
This class represents a zero extension of a small integer value to a larger integer value.
This class represents an analyzed expression in the program.
unsigned short getExpressionSize() const
static constexpr auto FlagsNoWrapMask
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 * getCanonical() const
Return the canonical SCEV.
const SCEV * CanonicalSCEV
Pointer to the canonical version of the SCEV, i.e.
LLVM_ABI void dump() const
This method is used for debugging.
LLVM_ABI bool isAllOnesValue() const
Return true if the expression is a constant all-ones value.
LLVM_ABI bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
static constexpr auto FlagNSW
LLVM_ABI ArrayRef< SCEVUse > operands() const
Return operands of this SCEV expression.
Type * getType() const
Return the LLVM type of this SCEV expression.
static constexpr auto FlagNone
LLVM_ABI void print(raw_ostream &OS) const
Print out the internal representation of this scalar to the specified stream.
SCEVTypes getSCEVType() const
static constexpr auto FlagNW
Analysis pass that exposes the ScalarEvolution for a function.
LLVM_ABI ScalarEvolution run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void print(raw_ostream &OS, const Module *=nullptr) const override
print - Print out the internal state of the pass.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
static LoopGuards collectOnDemand(const Loop *L, ScalarEvolution &SE)
Return loop guards for loop L, which are collected on first use.
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.
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 ...
static bool hasFlags(SCEVFlags Flags, SCEVFlags TestFlags)
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 const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEVFlags Flags=SCEV::FlagNone)
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 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 const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI ExitLimit computeExitLimitFromCond(const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit, bool AllowPredicates=false)
Compute the number of times the backedge of the specified loop will execute if its exit condition wer...
LLVM_ABI const SCEV * getMinMaxExpr(SCEVTypes Kind, SmallVectorImpl< SCEVUse > &Operands)
LLVM_ABI const SCEVPredicate * getEqualPredicate(const SCEV *LHS, const SCEV *RHS)
LLVM_ABI unsigned getSmallConstantTripMultiple(const Loop *L, const SCEV *ExitCount)
Returns the largest constant divisor of the trip count as a normal unsigned value,...
LLVM_ABI SCEVUse getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
LLVM_ABI uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
LLVM_ABI void registerUser(const SCEV *User, ArrayRef< SCEVUse > Ops)
Notify this ScalarEvolution that User directly uses SCEVs in Ops.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getPredicatedBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getBackedgeTakenCount, except it will add a set of SCEV predicates to Predicates that are ...
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
ConstantRange getSignedRange(const SCEV *S)
Determine the signed range for a particular SCEV.
LLVM_ABI const SCEV * getNoopOrSignExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
static SCEVFlags setFlags(SCEVFlags Flags, SCEVFlags OnFlags)
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 SCEVUse getAddRecExpr(SCEVUse Start, SCEVUse Step, const Loop *L, SCEVFlagsPair Flags)
Get an add recurrence expression for the specified loop.
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.
static SCEVFlags clearFlags(SCEVFlags Flags, SCEVFlags OffFlags)
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.
static SCEVFlags maskFlags(SCEVFlags Flags, SCEVFlags Mask)
Convenient SCEVFlags manipulation.
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 SCEVUse getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI const SCEV * getZeroExtendExprImpl(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI Type * getEffectiveSCEVType(Type *Ty) const
Return a type with the same bitwidth as the given type and which represents how SCEV will treat the g...
LLVM_ABI const SCEVPredicate * getComparePredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
LLVM_ABI bool haveSameSign(const SCEV *S1, const SCEV *S2)
Return true if we know that S1 and S2 must have the same sign.
LLVM_ABI const SCEV * getNotSCEV(const SCEV *V)
Return the SCEV object corresponding to ~V.
LLVM_ABI bool instructionCouldExistWithOperands(const SCEV *A, const SCEV *B)
Return true if there exists a point in the program at which both A and B could be operands to the sam...
LLVM_ABI std::optional< SCEVFlags > getStrengthenedNoWrapFlagsFromBinOp(const OverflowingBinaryOperator *OBO)
Parse NSW/NUW flags from add/sub/mul IR binary operation Op into SCEV no-wrap flags,...
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.
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)
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.
LLVM_ABI bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count.
LLVM_ABI BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB)
Return the "disposition" of the given SCEV with respect to the given block.
LLVM_ABI const SCEV * getNoopOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
LLVM_ABI const SCEV * getUMinFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS, bool Sequential=false)
Promote the operands to the wider of the types using zero-extension, and then perform a umin operatio...
LLVM_ABI bool loopIsFiniteByAssumption(const Loop *L)
Return true if this loop is finite by assumption.
LLVM_ABI SCEVUse getSCEVAtExit(const SCEV *S, const Loop *L, const BasicBlock *ExitingBlock)
Return the SCEV expression at the specified loop exit.
LLVM_ABI const SCEV * getExistingSCEV(Value *V)
Return an existing SCEV for V if there is one, otherwise return nullptr.
LLVM_ABI APInt getConstantMultiple(const SCEV *S, const Instruction *CtxI=nullptr)
Returns the max constant multiple of S.
LoopDisposition
An enum describing the relationship between a SCEV and a loop.
@ LoopComputable
The SCEV varies predictably with the loop.
@ LoopVariant
The SCEV is loop-variant (unknown).
@ LoopInvariant
The SCEV is loop-invariant.
@ LoopUniform
The SCEV is loop-uniform.
LLVM_ABI bool isKnownToBeAPowerOfTwo(const SCEV *S, bool OrZero=false, bool OrNegative=false)
Test if the given expression is known to be a power of 2.
LLVM_ABI void forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V)
Forget LCSSA phi node V of loop L to which a new predecessor was added, such that it may no longer be...
LLVM_ABI bool containsUndefs(const SCEV *S) const
Return true if the SCEV expression contains an undef value.
LLVM_ABI std::optional< MonotonicPredicateType > getMonotonicPredicateType(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred)
If, for all loop invariant X, the predicate "LHS `Pred` X" is monotonically increasing or decreasing,...
LLVM_ABI const SCEV * getCouldNotCompute()
LLVM_ABI bool isAvailableAtLoopEntry(const SCEV *S, const Loop *L)
Determine if the SCEV can be evaluated at loop's entry.
LLVM_ABI uint32_t getMinTrailingZeros(const SCEV *S, const Instruction *CtxI=nullptr)
Determine the minimum number of zero bits that S is guaranteed to end in (at every loop iteration).
BlockDisposition
An enum describing the relationship between a SCEV and a basic block.
@ DominatesBlock
The SCEV dominates the block.
@ ProperlyDominatesBlock
The SCEV properly dominates the block.
@ DoesNotDominateBlock
The SCEV does not dominate the block.
LLVM_ABI const SCEV * getExitCount(const Loop *L, const BasicBlock *ExitingBlock, ExitCountKind Kind=Exact)
Return the number of times the backedge executes before the given exit would be taken; if not exactly...
LLVM_ABI void getPoisonGeneratingValues(SmallPtrSetImpl< const Value * > &Result, const SCEV *S)
Return the set of Values that, if poison, will definitively result in S being poison as well.
LLVM_ABI void setNoWrapFlags(SCEVAddRecExpr *AddRec, SCEVFlags Flags)
Update no-wrap flags of an AddRec.
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 SCEVUse getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
LLVM_ABI unsigned getSmallConstantTripCount(const Loop *L)
Returns the exact trip count of the loop if we can compute it, and the result is a small constant.
LLVM_ABI bool hasComputableLoopEvolution(const SCEV *S, const Loop *L)
Return true if the given SCEV changes value in a known way in the specified loop.
LLVM_ABI const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
LLVM_ABI void forgetAllLoops()
LLVM_ABI const SCEV * getSignExtendExprImpl(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool dominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV dominate the specified basic block.
APInt getUnsignedRangeMax(const SCEV *S)
Determine the max of the unsigned range for a particular SCEV.
ExitCountKind
The terms "backedge taken count" and "exit count" are used interchangeably to refer to the number of ...
@ SymbolicMaximum
An expression which provides an upper bound on the exact trip count.
@ ConstantMaximum
A constant which provides an upper bound on the exact trip count.
@ Exact
An expression exactly describing the number of times the backedge has executed when a loop is exited.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
LLVM_ABI const SCEV * getPtrToAddrExpr(const SCEV *Op)
LLVM_ABI const SCEVAddRecExpr * convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Preds)
Tries to convert the S expression to an AddRec expression, adding additional predicates to Preds as r...
LLVM_ABI const SCEV * getSMaxExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI const SCEV * getElementSize(Instruction *Inst)
Return the size of an element read or written by Inst.
LLVM_ABI bool isGuaranteedNotToCauseUB(const SCEV *Op)
Returns true if Op is guaranteed not to cause immediate UB.
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 * getNegativeSCEV(const SCEV *V, SCEVFlags Flags=SCEV::FlagNone)
Return the SCEV object corresponding to -V.
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:295
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)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:746
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:777
TypeSize getSizeInBits() const
Definition DataLayout.h:757
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:294
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:291
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
Use & Op()
Definition User.h:171
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition Value.h:545
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:183
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
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.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition APInt.h:2274
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition APInt.h:2279
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition APInt.h:2284
LLVM_ABI std::optional< APInt > SolveQuadraticEquationWrap(APInt A, APInt B, APInt C, unsigned RangeWidth)
Let q(n) = An^2 + Bn + C, and BW = bit width of the value range (e.g.
Definition APInt.cpp:2859
LLVM_ABI APInt GreatestCommonDivisor(APInt A, APInt B, bool IsSigned=false)
Compute GCD of two APInt values.
Definition APInt.cpp:826
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2289
constexpr bool any(E Val)
@ Entry
Definition COFF.h:862
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
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.
SCEVBinaryExpr_match< SCEVMinMaxExpr, Op0_t, Op1_t > m_scev_MinMax(const Op0_t &Op0, const Op1_t &Op1)
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)
SCEVBinaryExpr_match< SCEVAddExpr, Op0_t, Op1_t, SCEV::FlagNSW > m_scev_NSWAdd(const Op0_t &Op0, const Op1_t &Op1)
specificscev_ty m_scev_Specific(const SCEV *S)
Match if we have a specific specified SCEV.
SCEVAffineAddRec_match< Op0_t, Op1_t, match_isa< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
match_bind< const SCEVUnknown > m_SCEVUnknown(const SCEVUnknown *&V)
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t, SCEV::FlagNUW, true > m_scev_c_NUWMul(const Op0_t &Op0, const Op1_t &Op1)
SCEVBinaryExpr_match< SCEVUMaxExpr, Op0_t, Op1_t, SCEV::FlagNone, true > m_scev_UMax(const Op0_t &Op0, const Op1_t &Op1)
SCEVBinaryExpr_match< SCEVSMaxExpr, Op0_t, Op1_t, SCEV::FlagNone, true > m_scev_SMax(const Op0_t &Op0, const Op1_t &Op1)
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t, SCEV::FlagNone, true > m_scev_c_Mul(const Op0_t &Op0, const Op1_t &Op1)
match_bind< const SCEVAddExpr > m_scev_Add(const SCEVAddExpr *&V)
SCEVURem_match< Op0_t, Op1_t > m_scev_URem(Op0_t LHS, Op1_t RHS, ScalarEvolution &SE)
Match the mathematical pattern A - (A / B) * B, where A and B can be arbitrary expressions.
@ Valid
The data is already valid.
LocationClass< Ty > location(Ty &L)
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
Definition CoroShape.h:32
constexpr double e
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
void visitAll(const SCEV *Root, SV &Visitor)
Use SCEVTraversal to visit all nodes in the given expression tree.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
SaveAndRestore(T &) -> SaveAndRestore< T >
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
LLVM_ABI bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
LLVM_ABI bool mustTriggerUB(const Instruction *I, const SmallPtrSetImpl< const Value * > &KnownPoison)
Return true if the given instruction must trigger undefined behavior when I is executed with any oper...
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
@ Known
Known to have no common set bits.
@ Dead
Unused definition.
InterleavedRange< Range > interleaved(const Range &R, StringRef Separator=", ", StringRef Prefix="", StringRef Suffix="")
Output range R as a sequence of interleaved elements.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
auto successors(const MachineBasicBlock *BB)
scope_exit(Callable) -> scope_exit< Callable >
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
@ BinaryOp
One of the operands is a binary op.
constexpr from_range_t from_range
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
bool set_is_subset(const S1Ty &S1, const S2Ty &S2)
set_is_subset(A, B) - Return true iff A in B
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
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 void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=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...
void * PointerTy
LLVM_ABI bool VerifySCEV
auto uninitialized_copy(R &&Src, IterTy Dst)
Definition STLExtras.h:2127
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=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.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
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,...
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Function *CtxF=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
const AnalysisOptions & getAnalysisOptions(const LLVMContext &C)
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:2220
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI bool isMustProgress(const Loop *L)
Return true if this loop can be assumed to make progress.
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI bool isFinite(const Loop *L)
Return true if this loop can be assumed to run for a finite number of iterations.
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:373
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
LLVM_ABI bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ Mul
Product of integers.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ Add
Sum of integers.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
DWARFExpression::Operation Op
auto max_element(R &&Range)
Provide wrappers to std::max_element which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2104
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
SCEVFlags
SCEVFlags are bitfield indices into SCEV's SubclassData.
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2210
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:249
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
iterator_range< df_iterator< T > > depth_first(const T &G)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2162
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
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:879
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
#define NC
Definition regutils.h:42
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
An object of this class is returned by queries that could not be answered.
static LLVM_ABI bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
The no-wrap flags to apply when creating a SCEV expression, to the expression and use respectively.
SCEVFlags ExprFlags
Flags applied directly to a SCEV expression, must be valid wherever the expression is valid.
SCEVFlags UseFlags
Flags only applied to a SCEVUse.
static SCEVUseT getCommon(SCEVUseT A, SCEVUseT B)
bool isCanonical() const
Returns true if the SCEVUse is canonical, i.e.
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.