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: {
215 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
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,
1101 ICmpInst::Predicate *Pred,
1102 ScalarEvolution *SE) {
1103 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1104 if (SE->isKnownPositive(Step)) {
1105 *Pred = ICmpInst::ICMP_SLT;
1107 SE->getSignedRangeMax(Step));
1108 }
1109 if (SE->isKnownNegative(Step)) {
1110 *Pred = ICmpInst::ICMP_SGT;
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.
1121 ICmpInst::Predicate *Pred,
1122 ScalarEvolution *SE) {
1123 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1124 *Pred = ICmpInst::ICMP_ULT;
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
3609 // Keep track of the original operands, for verification when adding
3610 // use-specific flags.
3611 const SmallVector<SCEVUse, 4> OrigOperands(Operands.begin(), Operands.end());
3612#endif
3613
3614 if (Operands.back()->isZero()) {
3615 Operands.pop_back();
3616 return getAddRecExpr(Operands, L, SCEV::FlagNone); // {X,+,0} --> X
3617 }
3618
3619 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3620 // use that information to infer NUW and NSW flags. However, computing a
3621 // BE count requires calling getAddRecExpr, so we may not yet have a
3622 // meaningful BE count at this point (and if we don't, we'd be stuck
3623 // with a SCEVCouldNotCompute as the cached BE count).
3624
3625 ExprFlags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, ExprFlags);
3626
3627 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3628 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3629 const Loop *NestedLoop = NestedAR->getLoop();
3630 if (L->contains(NestedLoop)
3631 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3632 : (!NestedLoop->contains(L) &&
3633 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3634 SmallVector<SCEVUse, 4> NestedOperands(NestedAR->operands());
3635 Operands[0] = NestedAR->getStart();
3636 // AddRecs require their operands be loop-invariant with respect to their
3637 // loops. Don't perform this transformation if it would break this
3638 // requirement.
3639 bool AllInvariant = all_of(
3640 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3641
3642 if (AllInvariant) {
3643 // Create a recurrence for the outer loop with the same step size.
3644 //
3645 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3646 // inner recurrence has the same property.
3647 SCEVFlags OuterFlags =
3648 maskFlags(ExprFlags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3649
3650 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3651 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3652 return isLoopInvariant(Op, NestedLoop);
3653 });
3654
3655 if (AllInvariant) {
3656 // Ok, both add recurrences are valid after the transformation.
3657 //
3658 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3659 // the outer recurrence has the same property.
3660 SCEVFlags InnerFlags =
3661 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | ExprFlags);
3662 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3663 }
3664 }
3665 // Reset Operands to its original state.
3666 Operands[0] = NestedAR;
3667 }
3668 }
3669
3670 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3671 // already have one, otherwise create a new one.
3672 assert((UseFlags == SCEV::FlagNone || equal(OrigOperands, Operands)) &&
3673 "Tried to add SCEVUse flags after operands changed");
3674 return {getOrCreateAddRecExpr(Operands, L, ExprFlags), UseFlags};
3675}
3676
3678 ArrayRef<SCEVUse> IndexExprs) {
3679 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3680 // getSCEV(Base)->getType() has the same address space as Base->getType()
3681 // because SCEV::getType() preserves the address space.
3682 GEPNoWrapFlags BaseNW = GEP->getNoWrapFlags();
3683 GEPNoWrapFlags OffsetNW = GEP->getNoWrapFlags();
3684 if (BaseNW != GEPNoWrapFlags::none()) {
3685 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3686 // but to do that, we have to ensure that said flag is valid in the entire
3687 // defined scope of the SCEV.
3688 // TODO: non-instructions have global scope. We might be able to prove
3689 // some global scope cases
3690 auto *GEPI = dyn_cast<Instruction>(GEP);
3691 if (!GEPI || !isSCEVExprNeverPoison(GEPI)) {
3692 BaseNW = OffsetNW = GEPNoWrapFlags::none();
3693 } else if (any_of(IndexExprs, [&](const SCEVUse &IndexExpr) {
3694 const SCEV *Idx = IndexExpr;
3695 return !isa<SCEVConstant>(Idx) &&
3696 !isGuaranteedToTransferExecutionTo(
3697 getDefiningScopeBound({Idx}), GEPI);
3698 })) {
3699 // The offset flags should not take into account the base pointer
3700 // defining scope, as the offset only depends on the indices. Thus,
3701 // derive the scope bound for the offset flags from each index operand
3702 // individually.
3703 OffsetNW = GEPNoWrapFlags::none();
3704 }
3705 }
3706
3707 return getGEPExpr(BaseExpr, IndexExprs, GEP->getSourceElementType(), BaseNW,
3708 OffsetNW);
3709}
3710
3712 ArrayRef<SCEVUse> IndexExprs,
3713 Type *SrcElementTy,
3714 GEPNoWrapFlags BaseNW,
3715 GEPNoWrapFlags OffsetNW) {
3716 SCEVFlags OffsetWrap = SCEV::FlagNone;
3717 if (OffsetNW.hasNoUnsignedSignedWrap())
3718 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNSW);
3719 if (OffsetNW.hasNoUnsignedWrap())
3720 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNUW);
3721
3722 Type *CurTy = BaseExpr->getType();
3723 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3724 bool FirstIter = true;
3726 for (SCEVUse IndexExpr : IndexExprs) {
3727 // Compute the (potentially symbolic) offset in bytes for this index.
3728 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3729 // For a struct, add the member offset.
3730 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3731 unsigned FieldNo = Index->getZExtValue();
3732 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3733 Offsets.push_back(FieldOffset);
3734
3735 // Update CurTy to the type of the field at Index.
3736 CurTy = STy->getTypeAtIndex(Index);
3737 } else {
3738 // Update CurTy to its element type.
3739 if (FirstIter) {
3740 assert(isa<PointerType>(CurTy) &&
3741 "The first index of a GEP indexes a pointer");
3742 CurTy = SrcElementTy;
3743 FirstIter = false;
3744 } else {
3745 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3746 }
3747 // For an array, add the element offset, explicitly scaled.
3748 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3749 // Getelementptr indices are signed.
3750 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3751
3752 // Multiply the index by the element size to compute the element offset.
3753 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3754 Offsets.push_back(LocalOffset);
3755 }
3756 }
3757
3758 // Handle degenerate case of GEP without offsets.
3759 if (Offsets.empty())
3760 return BaseExpr;
3761
3762 // Add the offsets together, assuming nsw if inbounds.
3763 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3764 // Add the base address and the offset. We cannot use the nsw flag, as the
3765 // base address is unsigned. However, if we know that the offset is
3766 // non-negative, we can use nuw.
3767 bool NUW = BaseNW.hasNoUnsignedWrap() ||
3769 SCEVFlags BaseWrap = NUW ? SCEV::FlagNUW : SCEV::FlagNone;
3770 const SCEV *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3771 assert(BaseExpr->getType() == GEPExpr->getType() &&
3772 "GEP should not change type mid-flight.");
3773 return GEPExpr;
3774}
3775
3776SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3778 const Loop *L) {
3779 assert((SCEVType != scAddRecExpr || L) &&
3780 "L must be passed to find existing AddRecs");
3782 ID.AddInteger(SCEVType);
3783 for (SCEVUse Op : Ops)
3784 ID.AddPointer(Op.getOpaqueValue());
3785 if (L)
3786 ID.AddPointer(L);
3788 return UniqueSCEVs.lookup(ID, Token);
3789}
3790
3791const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3792 SCEVFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagNone;
3793 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3794}
3795
3798 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3799 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3800 if (Ops.size() == 1) return Ops[0];
3801#ifndef NDEBUG
3802 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3803 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3804 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3805 "Operand types don't match!");
3806 assert(Ops[0]->getType()->isPointerTy() ==
3807 Ops[i]->getType()->isPointerTy() &&
3808 "min/max should be consistently pointerish");
3809 }
3810#endif
3811
3812 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3813 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3814
3816 Opts, *this, LI, DT, Ops,
3817 [&](const APInt &C1, const APInt &C2) {
3818 switch (Kind) {
3819 case scSMaxExpr:
3820 return APIntOps::smax(C1, C2);
3821 case scSMinExpr:
3822 return APIntOps::smin(C1, C2);
3823 case scUMaxExpr:
3824 return APIntOps::umax(C1, C2);
3825 case scUMinExpr:
3826 return APIntOps::umin(C1, C2);
3827 default:
3828 llvm_unreachable("Unknown SCEV min/max opcode");
3829 }
3830 },
3831 [&](const APInt &C) {
3832 // identity
3833 if (IsMax)
3834 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3835 else
3836 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3837 },
3838 [&](const APInt &C) {
3839 // absorber
3840 if (IsMax)
3841 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3842 else
3843 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3844 });
3845 if (Folded)
3846 return Folded;
3847
3848 // Check if we have created the same expression before.
3849 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3850 return S;
3851 }
3852
3853 // Find the first operation of the same kind
3854 unsigned Idx = 0;
3855 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3856 ++Idx;
3857
3858 // Check to see if one of the operands is of the same kind. If so, expand its
3859 // operands onto our operand list, and recurse to simplify.
3860 if (Idx < Ops.size()) {
3861 bool DeletedAny = false;
3862 while (Ops[Idx]->getSCEVType() == Kind) {
3863 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3864 Ops.erase(Ops.begin()+Idx);
3865 append_range(Ops, SMME->operands());
3866 DeletedAny = true;
3867 }
3868
3869 if (DeletedAny)
3870 return getMinMaxExpr(Kind, Ops);
3871 }
3872
3873 // Okay, check to see if the same value occurs in the operand list twice. If
3874 // so, delete one. Since we sorted the list, these values are required to
3875 // be adjacent.
3880 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3881 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3882 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3883 if (SCEVUse Common = SCEVUse::getCommon(Ops[i], Ops[i + 1]))
3884 Ops[i] = Ops[i + 1] = Common;
3885 if (Ops[i] == Ops[i + 1] ||
3886 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3887 // X op Y op Y --> X op Y
3888 // X op Y --> X, if we know X, Y are ordered appropriately
3889 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3890 --i;
3891 --e;
3892 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3893 Ops[i + 1])) {
3894 // X op Y --> Y, if we know X, Y are ordered appropriately
3895 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3896 --i;
3897 --e;
3898 }
3899 }
3900
3901 if (Ops.size() == 1) return Ops[0];
3902
3903 assert(!Ops.empty() && "Reduced smax down to nothing!");
3904
3905 // Okay, it looks like we really DO need an expr. Check to see if we
3906 // already have one, otherwise create a new one.
3908 ID.AddInteger(Kind);
3909 for (SCEVUse Op : Ops)
3910 ID.AddPointer(Op.getOpaqueValue());
3912 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
3913 if (ExistingSCEV)
3914 return ExistingSCEV;
3915 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3917 SCEV *S = new (SCEVAllocator)
3918 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3919
3920 UniqueSCEVs.insert(S, Token);
3921 S->computeAndSetCanonical(*this);
3922 registerUser(S, Ops);
3923 return S;
3924}
3925
3926namespace {
3927
3928class SCEVSequentialMinMaxDeduplicatingVisitor final
3929 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
3930 std::optional<const SCEV *>> {
3931 using RetVal = std::optional<const SCEV *>;
3932
3933 ScalarEvolution &SE;
3934 const SCEVTypes RootKind; // Must be a sequential min/max expression.
3935 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
3937
3938 bool canRecurseInto(SCEVTypes Kind) const {
3939 // We can only recurse into the SCEV expression of the same effective type
3940 // as the type of our root SCEV expression.
3941 return RootKind == Kind || NonSequentialRootKind == Kind;
3942 };
3943
3944 RetVal visit(const SCEV *S) {
3945 // Has the whole operand been seen already?
3946 if (!SeenOps.insert(S).second)
3947 return std::nullopt;
3949 SCEVTypes Kind = S->getSCEVType();
3950
3951 if (!canRecurseInto(Kind))
3952 return S;
3953
3954 auto *NAry = cast<SCEVNAryExpr>(S);
3955 SmallVector<SCEVUse> NewOps;
3956 bool Changed = visit(Kind, NAry->operands(), NewOps);
3957
3958 if (!Changed)
3959 return S;
3960 if (NewOps.empty())
3961 return std::nullopt;
3962
3964 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
3965 : SE.getMinMaxExpr(Kind, NewOps);
3966 }
3967 return S;
3968 }
3969
3970public:
3971 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
3972 SCEVTypes RootKind)
3973 : SE(SE), RootKind(RootKind),
3974 NonSequentialRootKind(
3975 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
3976 RootKind)) {}
3977
3978 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<SCEVUse> OrigOps,
3979 SmallVectorImpl<SCEVUse> &NewOps) {
3980 bool Changed = false;
3982 Ops.reserve(OrigOps.size());
3983
3984 for (const SCEV *Op : OrigOps) {
3985 RetVal NewOp = visit(Op);
3986 if (NewOp != Op)
3987 Changed = true;
3988 if (NewOp)
3989 Ops.emplace_back(*NewOp);
3990 }
3991
3992 if (Changed)
3993 NewOps = std::move(Ops);
3994 return Changed;
3995 }
3996};
3997
3998} // namespace
3999
4001 switch (Kind) {
4002 case scConstant:
4003 case scVScale:
4004 case scTruncate:
4005 case scZeroExtend:
4006 case scSignExtend:
4007 case scPtrToAddr:
4008 case scAddExpr:
4009 case scMulExpr:
4010 case scUDivExpr:
4011 case scAddRecExpr:
4012 case scUMaxExpr:
4013 case scSMaxExpr:
4014 case scUMinExpr:
4015 case scSMinExpr:
4016 case scUnknown:
4017 // If any operand is poison, the whole expression is poison.
4018 return true;
4020 // FIXME: if the *first* operand is poison, the whole expression is poison.
4021 return false; // Pessimistically, say that it does not propagate poison.
4022 case scCouldNotCompute:
4023 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4024 }
4025 llvm_unreachable("Unknown SCEV kind!");
4026}
4027
4028namespace {
4029// The only way poison may be introduced in a SCEV expression is from a
4030// poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4031// not SCEVConstant). Notably, SCEVFlags on SCEV nodes can *not*
4032// introduce poison -- they encode guaranteed, non-speculated knowledge.
4033//
4034// Additionally, all SCEV nodes propagate poison from inputs to outputs,
4035// with the notable exception of umin_seq, where only poison from the first
4036// operand is (unconditionally) propagated.
4037struct SCEVPoisonCollector {
4038 bool LookThroughMaybePoisonBlocking;
4039 SmallPtrSet<const SCEVUnknown *, 4> MaybePoison;
4040 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4041 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4042
4043 bool follow(const SCEV *S) {
4044 if (!LookThroughMaybePoisonBlocking &&
4046 return false;
4047
4048 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4049 if (!isGuaranteedNotToBePoison(SU->getValue()))
4050 MaybePoison.insert(SU);
4051 }
4052 return true;
4053 }
4054 bool isDone() const { return false; }
4055};
4056} // namespace
4057
4058/// Return true if V is poison given that AssumedPoison is already poison.
4059static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4060 // First collect all SCEVs that might result in AssumedPoison to be poison.
4061 // We need to look through potentially poison-blocking operations here,
4062 // because we want to find all SCEVs that *might* result in poison, not only
4063 // those that are *required* to.
4064 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4065 visitAll(AssumedPoison, PC1);
4066
4067 // AssumedPoison is never poison. As the assumption is false, the implication
4068 // is true. Don't bother walking the other SCEV in this case.
4069 if (PC1.MaybePoison.empty())
4070 return true;
4071
4072 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4073 // as well. We cannot look through potentially poison-blocking operations
4074 // here, as their arguments only *may* make the result poison.
4075 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4076 visitAll(S, PC2);
4077
4078 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4079 // it will also make S poison by being part of PC2.MaybePoison.
4080 return llvm::set_is_subset(PC1.MaybePoison, PC2.MaybePoison);
4081}
4082
4084 SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4085 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4086 visitAll(S, PC);
4087 for (const SCEVUnknown *SU : PC.MaybePoison)
4088 Result.insert(SU->getValue());
4089}
4090
4092 const SCEV *S, Instruction *I,
4093 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
4094 // If the instruction cannot be poison, it's always safe to reuse.
4096 return true;
4097
4098 // Otherwise, it is possible that I is more poisonous that S. Collect the
4099 // poison-contributors of S, and then check whether I has any additional
4100 // poison-contributors. Poison that is contributed through poison-generating
4101 // flags is handled by dropping those flags instead.
4103 getPoisonGeneratingValues(PoisonVals, S);
4104
4105 SmallVector<Value *> Worklist;
4107 Worklist.push_back(I);
4108 unsigned NumVisitedInsts = 0;
4109 const unsigned InstLimit = std::max<unsigned>(16, S->getExpressionSize());
4110 while (!Worklist.empty()) {
4111 Value *V = Worklist.pop_back_val();
4112 if (!Visited.insert(V).second)
4113 continue;
4114
4115 // Either the value can't be poison, or the S would also be poison if it
4116 // is.
4117 if (PoisonVals.contains(V) || ::isGuaranteedNotToBePoison(V))
4118 continue;
4119
4120 // Avoid walking large instruction graphs.
4121 if (++NumVisitedInsts > InstLimit)
4122 return false;
4123
4124 auto *I = dyn_cast<Instruction>(V);
4125 if (!I)
4126 return false;
4127
4128 // Disjoint or instructions are interpreted as adds by SCEV. However, we
4129 // can't replace an arbitrary add with disjoint or, even if we drop the
4130 // flag. We would need to convert the or into an add.
4131 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
4132 if (PDI->isDisjoint())
4133 return false;
4134
4135 // FIXME: Ignore vscale, even though it technically could be poison. Do this
4136 // because SCEV currently assumes it can't be poison. Remove this special
4137 // case once we proper model when vscale can be poison.
4138 if (auto *II = dyn_cast<IntrinsicInst>(I);
4139 II && II->getIntrinsicID() == Intrinsic::vscale)
4140 continue;
4141
4142 if (canCreatePoison(cast<Operator>(I), /*ConsiderFlagsAndMetadata*/ false))
4143 return false;
4144
4145 // If the instruction can't create poison, we can recurse to its operands.
4146 if (I->hasPoisonGeneratingAnnotations())
4147 DropPoisonGeneratingInsts.push_back(I);
4148
4149 llvm::append_range(Worklist, I->operands());
4150 }
4151 return true;
4152}
4153
4154const SCEV *
4157 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4158 "Not a SCEVSequentialMinMaxExpr!");
4159 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4160 if (Ops.size() == 1)
4161 return Ops[0];
4162#ifndef NDEBUG
4163 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4164 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4165 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4166 "Operand types don't match!");
4167 assert(Ops[0]->getType()->isPointerTy() ==
4168 Ops[i]->getType()->isPointerTy() &&
4169 "min/max should be consistently pointerish");
4170 }
4171#endif
4172
4173 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4174 // so we can *NOT* do any kind of sorting of the expressions!
4175
4176 // Check if we have created the same expression before.
4177 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4178 return S;
4179
4180 // FIXME: there are *some* simplifications that we can do here.
4181
4182 // Keep only the first instance of an operand.
4183 {
4184 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4185 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4186 if (Changed)
4187 return getSequentialMinMaxExpr(Kind, Ops);
4188 }
4189
4190 // Check to see if one of the operands is of the same kind. If so, expand its
4191 // operands onto our operand list, and recurse to simplify.
4192 {
4193 unsigned Idx = 0;
4194 bool DeletedAny = false;
4195 while (Idx < Ops.size()) {
4196 if (Ops[Idx]->getSCEVType() != Kind) {
4197 ++Idx;
4198 continue;
4199 }
4200 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4201 Ops.erase(Ops.begin() + Idx);
4202 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4203 SMME->operands().end());
4204 DeletedAny = true;
4205 }
4206
4207 if (DeletedAny)
4208 return getSequentialMinMaxExpr(Kind, Ops);
4209 }
4210
4211 const SCEV *SaturationPoint;
4213 switch (Kind) {
4215 SaturationPoint = getZero(Ops[0]->getType());
4216 Pred = ICmpInst::ICMP_ULE;
4217 break;
4218 default:
4219 llvm_unreachable("Not a sequential min/max type.");
4220 }
4221
4222 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4224 continue;
4225 // We can replace %x umin_seq %y with %x umin %y if either:
4226 // * %y being poison implies %x is also poison.
4227 // * %x cannot be the saturating value (e.g. zero for umin).
4228 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4229 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4230 SaturationPoint)) {
4231 SmallVector<SCEVUse, 2> SeqOps = {Ops[i - 1], Ops[i]};
4232 Ops[i - 1] = getMinMaxExpr(
4234 SeqOps);
4235 Ops.erase(Ops.begin() + i);
4236 return getSequentialMinMaxExpr(Kind, Ops);
4237 }
4238 // Fold %x umin_seq %y to %x if %x ule %y.
4239 // TODO: We might be able to prove the predicate for a later operand.
4240 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4241 Ops.erase(Ops.begin() + i);
4242 return getSequentialMinMaxExpr(Kind, Ops);
4243 }
4244 }
4245
4246 // Okay, it looks like we really DO need an expr. Check to see if we
4247 // already have one, otherwise create a new one.
4249 ID.AddInteger(Kind);
4250 for (SCEVUse Op : Ops)
4251 ID.AddPointer(Op.getOpaqueValue());
4253 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
4254 if (ExistingSCEV)
4255 return ExistingSCEV;
4256
4257 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4259 SCEV *S = new (SCEVAllocator)
4260 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4261
4262 UniqueSCEVs.insert(S, Token);
4263 S->computeAndSetCanonical(*this);
4264 registerUser(S, Ops);
4265 return S;
4266}
4267
4272
4276
4281
4285
4290
4294
4296 bool Sequential) {
4297 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4298 return getUMinExpr(Ops, Sequential);
4299}
4300
4306
4307const SCEV *
4309 const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4310 if (Size.isScalable())
4311 Res = getMulExpr(Res, getVScale(IntTy));
4312 return Res;
4313}
4314
4316 return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4317}
4318
4320 return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4321}
4322
4324 StructType *STy,
4325 unsigned FieldNo) {
4326 // We can bypass creating a target-independent constant expression and then
4327 // folding it back into a ConstantInt. This is just a compile-time
4328 // optimization.
4329 const StructLayout *SL = getDataLayout().getStructLayout(STy);
4330 assert(!SL->getSizeInBits().isScalable() &&
4331 "Cannot get offset for structure containing scalable vector types");
4332 return getConstant(IntTy, SL->getElementOffset(FieldNo));
4333}
4334
4336 // Don't attempt to do anything other than create a SCEVUnknown object
4337 // here. createSCEV only calls getUnknown after checking for all other
4338 // interesting possibilities, and any other code that calls getUnknown
4339 // is doing so in order to hide a value from SCEV canonicalization.
4340
4343 ID.AddPointer(V);
4345 if (SCEV *S = UniqueSCEVs.lookup(ID, Token)) {
4346 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4347 "Stale SCEVUnknown in uniquing map!");
4348 return S;
4349 }
4350 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4351 FirstUnknown, NextUnknownOrderID++);
4352 FirstUnknown = cast<SCEVUnknown>(S);
4353 UniqueSCEVs.insert(S, Token);
4354 S->computeAndSetCanonical(*this);
4355 return S;
4356}
4357
4358//===----------------------------------------------------------------------===//
4359// Basic SCEV Analysis and PHI Idiom Recognition Code
4360//
4361
4362/// Test if values of the given type are analyzable within the SCEV
4363/// framework. This primarily includes integer types, and it can optionally
4364/// include pointer types if the ScalarEvolution class has access to
4365/// target-specific information.
4367 // Integers and pointers are always SCEVable.
4368 return Ty->isIntOrPtrTy();
4369}
4370
4371/// Return the size in bits of the specified type, for which isSCEVable must
4372/// return true.
4374 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4375 if (Ty->isPointerTy())
4377 return getDataLayout().getTypeSizeInBits(Ty);
4378}
4379
4380/// Return a type with the same bitwidth as the given type and which represents
4381/// how SCEV will treat the given type, for which isSCEVable must return
4382/// true. For pointer types, this is the pointer index sized integer type.
4384 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4385
4386 if (Ty->isIntegerTy())
4387 return Ty;
4388
4389 // The only other support type is pointer.
4390 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4391 return getDataLayout().getIndexType(Ty);
4392}
4393
4395 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4396}
4397
4399 const SCEV *B) {
4400 /// For a valid use point to exist, the defining scope of one operand
4401 /// must dominate the other.
4402 bool PreciseA, PreciseB;
4403 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4404 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4405 if (!PreciseA || !PreciseB)
4406 // Can't tell.
4407 return false;
4408 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4409 DT.dominates(ScopeB, ScopeA);
4410}
4411
4413 return CouldNotCompute.get();
4414}
4415
4416bool ScalarEvolution::checkValidity(const SCEV *S) const {
4417 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4418 auto *SU = dyn_cast<SCEVUnknown>(S);
4419 return SU && SU->getValue() == nullptr;
4420 });
4421
4422 return !ContainsNulls;
4423}
4424
4426 HasRecMapType::iterator I = HasRecMap.find(S);
4427 if (I != HasRecMap.end())
4428 return I->second;
4429
4430 bool FoundAddRec =
4431 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4432 HasRecMap.insert({S, FoundAddRec});
4433 return FoundAddRec;
4434}
4435
4436/// Return the ValueOffsetPair set for \p S. \p S can be represented
4437/// by the value and offset from any ValueOffsetPair in the set.
4438ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4439 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4440 if (SI == ExprValueMap.end())
4441 return {};
4442 return SI->second;
4443}
4444
4445/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4446/// cannot be used separately. eraseValueFromMap should be used to remove
4447/// V from ValueExprMap and ExprValueMap at the same time.
4448void ScalarEvolution::eraseValueFromMap(Value *V) {
4449 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4450 if (I != ValueExprMap.end()) {
4451 auto EVIt = ExprValueMap.find(I->second);
4452 assert(is_contained(EVIt->second, V) && "Value not in ExprValueMap?");
4453 llvm::erase(EVIt->second, V);
4454 ValueExprMap.erase(I);
4455 }
4456}
4457
4458void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4459 // A recursive query may have already computed the SCEV. It should be
4460 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4461 // inferred nowrap flags.
4462 if (ValueExprMap.insert({SCEVCallbackVH(V, this), S}).second)
4463 ExprValueMap[S].push_back(V);
4464}
4465
4466/// Return an existing SCEV if it exists, otherwise analyze the expression and
4467/// create a new one.
4469 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4470
4471 if (const SCEV *S = getExistingSCEV(V))
4472 return S;
4473 return createSCEVIter(V);
4474}
4475
4477 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4478
4479 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4480 if (I != ValueExprMap.end()) {
4481 const SCEV *S = I->second;
4482 assert(checkValidity(S) &&
4483 "existing SCEV has not been properly invalidated");
4484 return S;
4485 }
4486 return nullptr;
4487}
4488
4489/// Return a SCEV corresponding to -V = -1*V
4491 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4492 return getConstant(
4493 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4494
4495 Type *Ty = V->getType();
4496 Ty = getEffectiveSCEVType(Ty);
4497 return getMulExpr(V, getMinusOne(Ty), Flags);
4498}
4499
4500/// If Expr computes ~A, return A else return nullptr
4501static const SCEV *MatchNotExpr(const SCEV *Expr) {
4502 const SCEV *MulOp;
4503 if (match(Expr, m_scev_Add(m_scev_AllOnes(),
4504 m_scev_Mul(m_scev_AllOnes(), m_SCEV(MulOp)))))
4505 return MulOp;
4506 return nullptr;
4507}
4508
4509/// Return a SCEV corresponding to ~V = -1-V
4511 assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4512
4513 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4514 return getConstant(
4515 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4516
4517 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4518 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4519 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4520 SmallVector<SCEVUse, 2> MatchedOperands;
4521 for (const SCEV *Operand : MME->operands()) {
4522 const SCEV *Matched = MatchNotExpr(Operand);
4523 if (!Matched)
4524 return (const SCEV *)nullptr;
4525 MatchedOperands.push_back(Matched);
4526 }
4527 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4528 MatchedOperands);
4529 };
4530 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4531 return Replaced;
4532 }
4533
4534 Type *Ty = V->getType();
4535 Ty = getEffectiveSCEVType(Ty);
4536 return getMinusSCEV(getMinusOne(Ty), V);
4537}
4538
4540 assert(P->getType()->isPointerTy());
4541
4542 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4543 // The base of an AddRec is the first operand.
4544 SmallVector<SCEVUse> Ops{AddRec->operands()};
4545 Ops[0] = removePointerBase(Ops[0]);
4546 // Don't try to transfer nowrap flags for now. We could in some cases
4547 // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4548 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagNone);
4549 }
4550 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4551 // The base of an Add is the pointer operand.
4552 SmallVector<SCEVUse> Ops{Add->operands()};
4553 SCEVUse *PtrOp = nullptr;
4554 for (SCEVUse &AddOp : Ops) {
4555 if (AddOp->getType()->isPointerTy()) {
4556 assert(!PtrOp && "Cannot have multiple pointer ops");
4557 PtrOp = &AddOp;
4558 }
4559 }
4560 *PtrOp = removePointerBase(*PtrOp);
4561 // Don't try to transfer nowrap flags for now. We could in some cases
4562 // (for example, if the pointer operand of the Add is a SCEVUnknown).
4563 return getAddExpr(Ops);
4564 }
4565 // Any other expression must be a pointer base.
4566 return getZero(P->getType());
4567}
4568
4570 SCEVFlags Flags, unsigned Depth) {
4571 // Fast path: X - X --> 0.
4572 if (SCEVUse::getCommon(LHS, RHS))
4573 return getZero(LHS->getType());
4574
4575 // If we subtract two pointers with different pointer bases, bail.
4576 // Eventually, we're going to add an assertion to getMulExpr that we
4577 // can't multiply by a pointer.
4578 if (RHS->getType()->isPointerTy()) {
4579 if (!LHS->getType()->isPointerTy() ||
4580 getPointerBase(LHS) != getPointerBase(RHS))
4581 return getCouldNotCompute();
4582 LHS = removePointerBase(LHS);
4583 RHS = removePointerBase(RHS);
4584 }
4585
4586 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4587 // makes it so that we cannot make much use of NUW.
4588 auto AddFlags = SCEV::FlagNone;
4589 const bool RHSIsNotMinSigned =
4591 if (hasFlags(Flags, SCEV::FlagNSW)) {
4592 // Let M be the minimum representable signed value. Then (-1)*RHS
4593 // signed-wraps if and only if RHS is M. That can happen even for
4594 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4595 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4596 // (-1)*RHS, we need to prove that RHS != M.
4597 //
4598 // If LHS is non-negative and we know that LHS - RHS does not
4599 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4600 // either by proving that RHS > M or that LHS >= 0.
4601 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4602 AddFlags = SCEV::FlagNSW;
4603 }
4604 }
4605
4606 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4607 // RHS is NSW and LHS >= 0.
4608 //
4609 // The difficulty here is that the NSW flag may have been proven
4610 // relative to a loop that is to be found in a recurrence in LHS and
4611 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4612 // larger scope than intended.
4613 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagNone;
4614
4615 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4616}
4617
4619 unsigned Depth) {
4620 Type *SrcTy = V->getType();
4621 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4622 "Cannot truncate or zero extend with non-integer arguments!");
4623 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4624 return V; // No conversion
4625 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4626 return getTruncateExpr(V, Ty, Depth);
4627 return getZeroExtendExpr(V, Ty, Depth);
4628}
4629
4631 unsigned Depth) {
4632 Type *SrcTy = V->getType();
4633 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4634 "Cannot truncate or zero extend with non-integer arguments!");
4635 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4636 return V; // No conversion
4637 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4638 return getTruncateExpr(V, Ty, Depth);
4639 return getSignExtendExpr(V, Ty, Depth);
4640}
4641
4643 Type *SrcTy = V->getType();
4644 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4645 "Cannot noop or zero extend with non-integer arguments!");
4647 "getNoopOrZeroExtend cannot truncate!");
4648 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4649 return V; // No conversion
4650 return getZeroExtendExpr(V, Ty);
4651}
4652
4654 Type *SrcTy = V->getType();
4655 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4656 "Cannot noop or sign extend with non-integer arguments!");
4658 "getNoopOrSignExtend cannot truncate!");
4659 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4660 return V; // No conversion
4661 return getSignExtendExpr(V, Ty);
4662}
4663
4665 Type *SrcTy = V->getType();
4666 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4667 "Cannot noop or any extend with non-integer arguments!");
4669 "getNoopOrAnyExtend cannot truncate!");
4670 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4671 return V; // No conversion
4672 return getAnyExtendExpr(V, Ty);
4673}
4674
4676 Type *SrcTy = V->getType();
4677 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4678 "Cannot truncate or noop with non-integer arguments!");
4680 "getTruncateOrNoop cannot extend!");
4681 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4682 return V; // No conversion
4683 return getTruncateExpr(V, Ty);
4684}
4685
4687 const SCEV *RHS) {
4688 const SCEV *PromotedLHS = LHS;
4689 const SCEV *PromotedRHS = RHS;
4690
4691 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4692 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4693 else
4694 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4695
4696 return getUMaxExpr(PromotedLHS, PromotedRHS);
4697}
4698
4700 const SCEV *RHS,
4701 bool Sequential) {
4702 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4703 return getUMinFromMismatchedTypes(Ops, Sequential);
4704}
4705
4706const SCEV *
4708 bool Sequential) {
4709 assert(!Ops.empty() && "At least one operand must be!");
4710 // Trivial case.
4711 if (Ops.size() == 1)
4712 return Ops[0];
4713
4714 // Find the max type first.
4715 Type *MaxType = nullptr;
4716 for (SCEVUse S : Ops)
4717 if (MaxType)
4718 MaxType = getWiderType(MaxType, S->getType());
4719 else
4720 MaxType = S->getType();
4721 assert(MaxType && "Failed to find maximum type!");
4722
4723 // Extend all ops to max type.
4724 SmallVector<SCEVUse, 2> PromotedOps;
4725 for (SCEVUse S : Ops)
4726 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4727
4728 // Generate umin.
4729 return getUMinExpr(PromotedOps, Sequential);
4730}
4731
4733 // A pointer operand may evaluate to a nonpointer expression, such as null.
4734 if (!V->getType()->isPointerTy())
4735 return V;
4736
4737 while (true) {
4738 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4739 V = AddRec->getStart();
4740 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4741 const SCEV *PtrOp = nullptr;
4742 for (const SCEV *AddOp : Add->operands()) {
4743 if (AddOp->getType()->isPointerTy()) {
4744 assert(!PtrOp && "Cannot have multiple pointer ops");
4745 PtrOp = AddOp;
4746 }
4747 }
4748 assert(PtrOp && "Must have pointer op");
4749 V = PtrOp;
4750 } else // Not something we can look further into.
4751 return V;
4752 }
4753}
4754
4755/// Push users of the given Instruction onto the given Worklist.
4759 // Push the def-use children onto the Worklist stack.
4760 for (User *U : I->users()) {
4761 auto *UserInsn = cast<Instruction>(U);
4762 if (Visited.insert(UserInsn).second)
4763 Worklist.push_back(UserInsn);
4764 }
4765}
4766
4767namespace {
4768
4769/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4770/// expression in case its Loop is L. If it is not L then
4771/// if IgnoreOtherLoops is true then use AddRec itself
4772/// otherwise rewrite cannot be done.
4773/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4774class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4775public:
4776 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4777 bool IgnoreOtherLoops = true) {
4778 SCEVInitRewriter Rewriter(L, SE);
4779 const SCEV *Result = Rewriter.visit(S);
4780 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4781 return SE.getCouldNotCompute();
4782 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4783 ? SE.getCouldNotCompute()
4784 : Result;
4785 }
4786
4787 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4788 if (!SE.isLoopInvariant(Expr, L))
4789 SeenLoopVariantSCEVUnknown = true;
4790 return Expr;
4791 }
4792
4793 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4794 // Only re-write AddRecExprs for this loop.
4795 if (Expr->getLoop() == L)
4796 return Expr->getStart();
4797 SeenOtherLoops = true;
4798 return Expr;
4799 }
4800
4801 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4802
4803 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4804
4805private:
4806 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4807 : SCEVRewriteVisitor(SE), L(L) {}
4808
4809 const Loop *L;
4810 bool SeenLoopVariantSCEVUnknown = false;
4811 bool SeenOtherLoops = false;
4812};
4813
4814/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4815/// increment expression in case its Loop is L. If it is not L then
4816/// use AddRec itself.
4817/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4818class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4819public:
4820 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4821 SCEVPostIncRewriter Rewriter(L, SE);
4822 const SCEV *Result = Rewriter.visit(S);
4823 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4824 ? SE.getCouldNotCompute()
4825 : Result;
4826 }
4827
4828 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4829 if (!SE.isLoopInvariant(Expr, L))
4830 SeenLoopVariantSCEVUnknown = true;
4831 return Expr;
4832 }
4833
4834 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4835 // Only re-write AddRecExprs for this loop.
4836 if (Expr->getLoop() == L)
4837 return Expr->getPostIncExpr(SE);
4838 SeenOtherLoops = true;
4839 return Expr;
4840 }
4841
4842 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4843
4844 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4845
4846private:
4847 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4848 : SCEVRewriteVisitor(SE), L(L) {}
4849
4850 const Loop *L;
4851 bool SeenLoopVariantSCEVUnknown = false;
4852 bool SeenOtherLoops = false;
4853};
4854
4855/// This class evaluates the compare condition by matching it against the
4856/// condition of loop latch. If there is a match we assume a true value
4857/// for the condition while building SCEV nodes.
4858class SCEVBackedgeConditionFolder
4859 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4860public:
4861 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4862 ScalarEvolution &SE) {
4863 bool IsPosBECond = false;
4864 Value *BECond = nullptr;
4865 if (BasicBlock *Latch = L->getLoopLatch()) {
4866 if (CondBrInst *BI = dyn_cast<CondBrInst>(Latch->getTerminator())) {
4867 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4868 "Both outgoing branches should not target same header!");
4869 BECond = BI->getCondition();
4870 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4871 } else {
4872 return S;
4873 }
4874 }
4875 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4876 return Rewriter.visit(S);
4877 }
4878
4879 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4880 const SCEV *Result = Expr;
4881 bool InvariantF = SE.isLoopInvariant(Expr, L);
4882
4883 if (!InvariantF) {
4885 switch (I->getOpcode()) {
4886 case Instruction::Select: {
4887 SelectInst *SI = cast<SelectInst>(I);
4888 std::optional<const SCEV *> Res =
4889 compareWithBackedgeCondition(SI->getCondition());
4890 if (Res) {
4891 bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
4892 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4893 }
4894 break;
4895 }
4896 default: {
4897 std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4898 if (Res)
4899 Result = *Res;
4900 break;
4901 }
4902 }
4903 }
4904 return Result;
4905 }
4906
4907private:
4908 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4909 bool IsPosBECond, ScalarEvolution &SE)
4910 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4911 IsPositiveBECond(IsPosBECond) {}
4912
4913 std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4914
4915 const Loop *L;
4916 /// Loop back condition.
4917 Value *BackedgeCond = nullptr;
4918 /// Set to true if loop back is on positive branch condition.
4919 bool IsPositiveBECond;
4920};
4921
4922std::optional<const SCEV *>
4923SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4924
4925 // If value matches the backedge condition for loop latch,
4926 // then return a constant evolution node based on loopback
4927 // branch taken.
4928 if (BackedgeCond == IC)
4929 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4931 return std::nullopt;
4932}
4933
4934class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4935public:
4936 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4937 ScalarEvolution &SE) {
4938 SCEVShiftRewriter Rewriter(L, SE);
4939 const SCEV *Result = Rewriter.visit(S);
4940 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4941 }
4942
4943 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4944 // Only allow AddRecExprs for this loop.
4945 if (!SE.isLoopInvariant(Expr, L))
4946 Valid = false;
4947 return Expr;
4948 }
4949
4950 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4951 if (Expr->getLoop() == L && Expr->isAffine())
4952 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4953 Valid = false;
4954 return Expr;
4955 }
4956
4957 bool isValid() { return Valid; }
4958
4959private:
4960 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4961 : SCEVRewriteVisitor(SE), L(L) {}
4962
4963 const Loop *L;
4964 bool Valid = true;
4965};
4966
4967} // end anonymous namespace
4968
4969void ScalarEvolution::inferNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4970 if (!AR->isAffine())
4971 return;
4972
4973 // Force computation of ranges, which will also perform range-based flag
4974 // inference.
4975 if (!AR->hasNoSignedWrap())
4976 (void)getSignedRange(AR);
4977
4978 if (!AR->hasNoUnsignedWrap())
4979 (void)getUnsignedRange(AR);
4980
4981 if (!AR->hasNoSelfWrap()) {
4982 const SCEV *BECount = getConstantMaxBackedgeTakenCount(AR->getLoop());
4983 if (const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(BECount)) {
4984 ConstantRange StepCR = getSignedRange(AR->getStepRecurrence(*this));
4985 const APInt &BECountAP = BECountMax->getAPInt();
4986 unsigned NoOverflowBitWidth =
4987 BECountAP.getActiveBits() + StepCR.getMinSignedBits();
4988 if (NoOverflowBitWidth <= getTypeSizeInBits(AR->getType()))
4989 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
4990 }
4991 }
4992}
4993
4995ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4997
4998 if (AR->hasNoSignedWrap())
4999 return Result;
5000
5001 if (!AR->isAffine())
5002 return Result;
5003
5004 // This function can be expensive, only try to prove NSW once per AddRec.
5005 if (!SignedWrapViaInductionTried.insert(AR).second)
5006 return Result;
5007
5008 const SCEV *Step = AR->getStepRecurrence(*this);
5009 const Loop *L = AR->getLoop();
5010
5011 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5012 // Note that this serves two purposes: It filters out loops that are
5013 // simply not analyzable, and it covers the case where this code is
5014 // being called from within backedge-taken count analysis, such that
5015 // attempting to ask for the backedge-taken count would likely result
5016 // in infinite recursion. In the later case, the analysis code will
5017 // cope with a conservative value, and it will take care to purge
5018 // that value once it has finished.
5019 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5020
5021 // Normally, in the cases we can prove no-overflow via a
5022 // backedge guarding condition, we can also compute a backedge
5023 // taken count for the loop. The exceptions are assumptions and
5024 // guards present in the loop -- SCEV is not great at exploiting
5025 // these to compute max backedge taken counts, but can still use
5026 // these to prove lack of overflow. Use this fact to avoid
5027 // doing extra work that may not pay off.
5028
5029 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5030 AC.assumptions().empty())
5031 return Result;
5032
5033 // If the backedge is guarded by a comparison with the pre-inc value the
5034 // addrec is safe. Also, if the entry is guarded by a comparison with the
5035 // start value and the backedge is guarded by a comparison with the post-inc
5036 // value, the addrec is safe.
5038 const SCEV *OverflowLimit =
5039 getSignedOverflowLimitForStep(Step, &Pred, this);
5040 if (OverflowLimit &&
5041 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5042 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
5043 Result = setFlags(Result, SCEV::FlagNSW);
5044 }
5045 return Result;
5046}
5048ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5050
5051 if (AR->hasNoUnsignedWrap())
5052 return Result;
5053
5054 if (!AR->isAffine())
5055 return Result;
5056
5057 // This function can be expensive, only try to prove NUW once per AddRec.
5058 if (!UnsignedWrapViaInductionTried.insert(AR).second)
5059 return Result;
5060
5061 const SCEV *Step = AR->getStepRecurrence(*this);
5062 const Loop *L = AR->getLoop();
5063
5064 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5065 // Note that this serves two purposes: It filters out loops that are
5066 // simply not analyzable, and it covers the case where this code is
5067 // being called from within backedge-taken count analysis, such that
5068 // attempting to ask for the backedge-taken count would likely result
5069 // in infinite recursion. In the later case, the analysis code will
5070 // cope with a conservative value, and it will take care to purge
5071 // that value once it has finished.
5072 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5073
5074 // Normally, in the cases we can prove no-overflow via a
5075 // backedge guarding condition, we can also compute a backedge
5076 // taken count for the loop. The exceptions are assumptions and
5077 // guards present in the loop -- SCEV is not great at exploiting
5078 // these to compute max backedge taken counts, but can still use
5079 // these to prove lack of overflow. Use this fact to avoid
5080 // doing extra work that may not pay off.
5081
5082 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5083 AC.assumptions().empty())
5084 return Result;
5085
5086 // If the backedge is guarded by a comparison with the pre-inc value the
5087 // addrec is safe. Also, if the entry is guarded by a comparison with the
5088 // start value and the backedge is guarded by a comparison with the post-inc
5089 // value, the addrec is safe.
5090 if (isKnownPositive(Step)) {
5092 const SCEV *OverflowLimit =
5093 getUnsignedOverflowLimitForStep(Step, &Pred, this);
5094 if (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5095 isKnownOnEveryIteration(Pred, AR, OverflowLimit))
5096 Result = setFlags(Result, SCEV::FlagNUW);
5097 }
5098 return Result;
5099}
5100
5101namespace {
5102
5103/// Represents an abstract binary operation. This may exist as a
5104/// normal instruction or constant expression, or may have been
5105/// derived from an expression tree.
5106struct BinaryOp {
5107 unsigned Opcode;
5108 Value *LHS;
5109 Value *RHS;
5110 bool IsNSW = false;
5111 bool IsNUW = false;
5112
5113 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5114 /// constant expression.
5115 Operator *Op = nullptr;
5116
5117 explicit BinaryOp(Operator *Op)
5118 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5119 Op(Op) {
5120 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5121 IsNSW = OBO->hasNoSignedWrap();
5122 IsNUW = OBO->hasNoUnsignedWrap();
5123 }
5124 }
5125
5126 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5127 bool IsNUW = false)
5128 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5129};
5130
5131} // end anonymous namespace
5132
5133/// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
5134static std::optional<BinaryOp> MatchBinaryOp(Value *V,
5135 const DominatorTree &DT) {
5136 auto *Op = dyn_cast<Operator>(V);
5137 if (!Op)
5138 return std::nullopt;
5139
5140 // Implementation detail: all the cleverness here should happen without
5141 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5142 // SCEV expressions when possible, and we should not break that.
5143
5144 switch (Op->getOpcode()) {
5145 case Instruction::Add:
5146 case Instruction::Sub:
5147 case Instruction::Mul:
5148 case Instruction::UDiv:
5149 case Instruction::URem:
5150 case Instruction::And:
5151 case Instruction::AShr:
5152 case Instruction::Shl:
5153 return BinaryOp(Op);
5154
5155 case Instruction::Or: {
5156 // Convert or disjoint into add nuw nsw.
5157 if (cast<PossiblyDisjointInst>(Op)->isDisjoint()) {
5158 BinaryOp BinOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
5159 /*IsNSW=*/true, /*IsNUW=*/true);
5160 // Keep the reference to the original instruction so that we can later
5161 // check whether it can produce poison value or not.
5162 BinOp.Op = Op;
5163 return BinOp;
5164 }
5165 return BinaryOp(Op);
5166 }
5167
5168 case Instruction::Xor:
5169 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5170 // If the RHS of the xor is a signmask, then this is just an add.
5171 // Instcombine turns add of signmask into xor as a strength reduction step.
5172 if (RHSC->getValue().isSignMask())
5173 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5174 // Binary `xor` is a bit-wise `add`.
5175 if (V->getType()->isIntegerTy(1))
5176 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5177 return BinaryOp(Op);
5178
5179 case Instruction::LShr:
5180 // Turn logical shift right of a constant into a unsigned divide.
5181 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5182 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5183
5184 // If the shift count is not less than the bitwidth, the result of
5185 // the shift is undefined. Don't try to analyze it, because the
5186 // resolution chosen here may differ from the resolution chosen in
5187 // other parts of the compiler.
5188 if (SA->getValue().ult(BitWidth)) {
5189 Constant *X =
5190 ConstantInt::get(SA->getContext(),
5191 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5192 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5193 }
5194 }
5195 return BinaryOp(Op);
5196
5197 case Instruction::ExtractValue: {
5198 auto *EVI = cast<ExtractValueInst>(Op);
5199 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5200 break;
5201
5202 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5203 if (!WO)
5204 break;
5205
5206 Instruction::BinaryOps BinOp = WO->getBinaryOp();
5207 bool Signed = WO->isSigned();
5208 // TODO: Should add nuw/nsw flags for mul as well.
5209 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5210 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5211
5212 // Now that we know that all uses of the arithmetic-result component of
5213 // CI are guarded by the overflow check, we can go ahead and pretend
5214 // that the arithmetic is non-overflowing.
5215 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5216 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5217 }
5218
5219 default:
5220 break;
5221 }
5222
5223 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5224 // semantics as a Sub, return a binary sub expression.
5225 if (auto *II = dyn_cast<IntrinsicInst>(V))
5226 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5227 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5228
5229 return std::nullopt;
5230}
5231
5232/// Helper function to createAddRecFromPHIWithCasts. We have a phi
5233/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5234/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5235/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5236/// follows one of the following patterns:
5237/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5238/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5239/// If the SCEV expression of \p Op conforms with one of the expected patterns
5240/// we return the type of the truncation operation, and indicate whether the
5241/// truncated type should be treated as signed/unsigned by setting
5242/// \p Signed to true/false, respectively.
5243static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5244 bool &Signed, ScalarEvolution &SE) {
5245 // The case where Op == SymbolicPHI (that is, with no type conversions on
5246 // the way) is handled by the regular add recurrence creating logic and
5247 // would have already been triggered in createAddRecForPHI. Reaching it here
5248 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5249 // because one of the other operands of the SCEVAddExpr updating this PHI is
5250 // not invariant).
5251 //
5252 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5253 // this case predicates that allow us to prove that Op == SymbolicPHI will
5254 // be added.
5255 if (Op == SymbolicPHI)
5256 return nullptr;
5257
5258 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5259 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5260 if (SourceBits != NewBits)
5261 return nullptr;
5262
5263 if (match(Op, m_scev_SExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5264 Signed = true;
5265 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5266 }
5267 if (match(Op, m_scev_ZExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5268 Signed = false;
5269 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5270 }
5271 return nullptr;
5272}
5273
5274static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5275 if (!PN->getType()->isIntegerTy())
5276 return nullptr;
5277 const Loop *L = LI.getLoopFor(PN->getParent());
5278 if (!L || L->getHeader() != PN->getParent())
5279 return nullptr;
5280 return L;
5281}
5282
5283// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5284// computation that updates the phi follows the following pattern:
5285// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5286// which correspond to a phi->trunc->sext/zext->add->phi update chain.
5287// If so, try to see if it can be rewritten as an AddRecExpr under some
5288// Predicates. If successful, return them as a pair. Also cache the results
5289// of the analysis.
5290//
5291// Example usage scenario:
5292// Say the Rewriter is called for the following SCEV:
5293// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5294// where:
5295// %X = phi i64 (%Start, %BEValue)
5296// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5297// and call this function with %SymbolicPHI = %X.
5298//
5299// The analysis will find that the value coming around the backedge has
5300// the following SCEV:
5301// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5302// Upon concluding that this matches the desired pattern, the function
5303// will return the pair {NewAddRec, SmallPredsVec} where:
5304// NewAddRec = {%Start,+,%Step}
5305// SmallPredsVec = {P1, P2, P3} as follows:
5306// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5307// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5308// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5309// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5310// under the predicates {P1,P2,P3}.
5311// This predicated rewrite will be cached in PredicatedSCEVRewrites:
5312// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5313//
5314// TODO's:
5315//
5316// 1) Extend the Induction descriptor to also support inductions that involve
5317// casts: When needed (namely, when we are called in the context of the
5318// vectorizer induction analysis), a Set of cast instructions will be
5319// populated by this method, and provided back to isInductionPHI. This is
5320// needed to allow the vectorizer to properly record them to be ignored by
5321// the cost model and to avoid vectorizing them (otherwise these casts,
5322// which are redundant under the runtime overflow checks, will be
5323// vectorized, which can be costly).
5324//
5325// 2) Support additional induction/PHISCEV patterns: We also want to support
5326// inductions where the sext-trunc / zext-trunc operations (partly) occur
5327// after the induction update operation (the induction increment):
5328//
5329// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5330// which correspond to a phi->add->trunc->sext/zext->phi update chain.
5331//
5332// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5333// which correspond to a phi->trunc->add->sext/zext->phi update chain.
5334//
5335// 3) Outline common code with createAddRecFromPHI to avoid duplication.
5336std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5337ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5339
5340 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5341 // return an AddRec expression under some predicate.
5342
5343 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5344 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5345 assert(L && "Expecting an integer loop header phi");
5346
5347 // The loop may have multiple entrances or multiple exits; we can analyze
5348 // this phi as an addrec if it has a unique entry value and a unique
5349 // backedge value.
5350 Value *BEValueV = nullptr, *StartValueV = nullptr;
5351 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5352 Value *V = PN->getIncomingValue(i);
5353 if (L->contains(PN->getIncomingBlock(i))) {
5354 if (!BEValueV) {
5355 BEValueV = V;
5356 } else if (BEValueV != V) {
5357 BEValueV = nullptr;
5358 break;
5359 }
5360 } else if (!StartValueV) {
5361 StartValueV = V;
5362 } else if (StartValueV != V) {
5363 StartValueV = nullptr;
5364 break;
5365 }
5366 }
5367 if (!BEValueV || !StartValueV)
5368 return std::nullopt;
5369
5370 const SCEV *BEValue = getSCEV(BEValueV);
5371
5372 // If the value coming around the backedge is an add with the symbolic
5373 // value we just inserted, possibly with casts that we can ignore under
5374 // an appropriate runtime guard, then we found a simple induction variable!
5375 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5376 if (!Add)
5377 return std::nullopt;
5378
5379 // If there is a single occurrence of the symbolic value, possibly
5380 // casted, replace it with a recurrence.
5381 unsigned FoundIndex = Add->getNumOperands();
5382 Type *TruncTy = nullptr;
5383 bool Signed;
5384 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5385 if ((TruncTy =
5386 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5387 if (FoundIndex == e) {
5388 FoundIndex = i;
5389 break;
5390 }
5391
5392 if (FoundIndex == Add->getNumOperands())
5393 return std::nullopt;
5394
5395 // Create an add with everything but the specified operand.
5397 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5398 if (i != FoundIndex)
5399 Ops.push_back(Add->getOperand(i));
5400 const SCEV *Accum = getAddExpr(Ops);
5401
5402 // The runtime checks will not be valid if the step amount is
5403 // varying inside the loop.
5404 if (!isLoopInvariant(Accum, L))
5405 return std::nullopt;
5406
5407 // *** Part2: Create the predicates
5408
5409 // Analysis was successful: we have a phi-with-cast pattern for which we
5410 // can return an AddRec expression under the following predicates:
5411 //
5412 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5413 // fits within the truncated type (does not overflow) for i = 0 to n-1.
5414 // P2: An Equal predicate that guarantees that
5415 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5416 // P3: An Equal predicate that guarantees that
5417 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5418 //
5419 // As we next prove, the above predicates guarantee that:
5420 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5421 //
5422 //
5423 // More formally, we want to prove that:
5424 // Expr(i+1) = Start + (i+1) * Accum
5425 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5426 //
5427 // Given that:
5428 // 1) Expr(0) = Start
5429 // 2) Expr(1) = Start + Accum
5430 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5431 // 3) Induction hypothesis (step i):
5432 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5433 //
5434 // Proof:
5435 // Expr(i+1) =
5436 // = Start + (i+1)*Accum
5437 // = (Start + i*Accum) + Accum
5438 // = Expr(i) + Accum
5439 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5440 // :: from step i
5441 //
5442 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5443 //
5444 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5445 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
5446 // + Accum :: from P3
5447 //
5448 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5449 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5450 //
5451 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5452 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5453 //
5454 // By induction, the same applies to all iterations 1<=i<n:
5455 //
5456
5457 // Create a truncated addrec for which we will add a no overflow check (P1).
5458 const SCEV *StartVal = getSCEV(StartValueV);
5459 const SCEV *PHISCEV =
5460 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5461 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagNone);
5462
5463 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5464 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5465 // will be constant.
5466 //
5467 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5468 // add P1.
5469 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5473 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5474 Predicates.push_back(AddRecPred);
5475 }
5476
5477 // Create the Equal Predicates P2,P3:
5478
5479 // It is possible that the predicates P2 and/or P3 are computable at
5480 // compile time due to StartVal and/or Accum being constants.
5481 // If either one is, then we can check that now and escape if either P2
5482 // or P3 is false.
5483
5484 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5485 // for each of StartVal and Accum
5486 auto getExtendedExpr = [&](const SCEV *Expr,
5487 bool CreateSignExtend) -> const SCEV * {
5488 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5489 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5490 const SCEV *ExtendedExpr =
5491 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5492 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5493 return ExtendedExpr;
5494 };
5495
5496 // Given:
5497 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5498 // = getExtendedExpr(Expr)
5499 // Determine whether the predicate P: Expr == ExtendedExpr
5500 // is known to be false at compile time
5501 auto PredIsKnownFalse = [&](const SCEV *Expr,
5502 const SCEV *ExtendedExpr) -> bool {
5503 return Expr != ExtendedExpr &&
5504 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5505 };
5506
5507 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5508 if (PredIsKnownFalse(StartVal, StartExtended)) {
5509 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5510 return std::nullopt;
5511 }
5512
5513 // The Step is always Signed (because the overflow checks are either
5514 // NSSW or NUSW)
5515 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5516 if (PredIsKnownFalse(Accum, AccumExtended)) {
5517 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5518 return std::nullopt;
5519 }
5520
5521 auto AppendPredicate = [&](const SCEV *Expr,
5522 const SCEV *ExtendedExpr) -> void {
5523 if (Expr != ExtendedExpr &&
5524 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5525 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5526 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5527 Predicates.push_back(Pred);
5528 }
5529 };
5530
5531 AppendPredicate(StartVal, StartExtended);
5532 AppendPredicate(Accum, AccumExtended);
5533
5534 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5535 // which the casts had been folded away. The caller can rewrite SymbolicPHI
5536 // into NewAR if it will also add the runtime overflow checks specified in
5537 // Predicates.
5538 const SCEV *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagNone);
5539
5540 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5541 std::make_pair(NewAR, Predicates);
5542 // Remember the result of the analysis for this SCEV at this locayyytion.
5543 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5544 return PredRewrite;
5545}
5546
5547std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5549 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5550 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5551 if (!L)
5552 return std::nullopt;
5553
5554 // Check to see if we already analyzed this PHI.
5555 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5556 if (I != PredicatedSCEVRewrites.end()) {
5557 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5558 I->second;
5559 // Analysis was done before and failed to create an AddRec:
5560 if (Rewrite.first == SymbolicPHI)
5561 return std::nullopt;
5562 // Analysis was done before and succeeded to create an AddRec under
5563 // a predicate:
5564 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5565 assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5566 return Rewrite;
5567 }
5568
5569 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5570 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5571
5572 // Record in the cache that the analysis failed
5573 if (!Rewrite) {
5575 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5576 return std::nullopt;
5577 }
5578
5579 return Rewrite;
5580}
5581
5582// FIXME: This utility is currently required because the Rewriter currently
5583// does not rewrite this expression:
5584// {0, +, (sext ix (trunc iy to ix) to iy)}
5585// into {0, +, %step},
5586// even when the following Equal predicate exists:
5587// "%step == (sext ix (trunc iy to ix) to iy)".
5589 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2,
5590 ArrayRef<const SCEVPredicate *> NoWrapPreds) const {
5591 if (AR1 == AR2)
5592 return true;
5593
5594 SCEVUnionPredicate NoWrapUnionPred(NoWrapPreds, SE);
5595 SCEVUnionPredicate AllPreds = Preds->getUnionWith(&NoWrapUnionPred, SE);
5596 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5597 if (Expr1 != Expr2 &&
5598 !AllPreds.implies(SE.getEqualPredicate(Expr1, Expr2), SE) &&
5599 !AllPreds.implies(SE.getEqualPredicate(Expr2, Expr1), SE))
5600 return false;
5601 return true;
5602 };
5603
5604 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5605 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5606 return false;
5607 return true;
5608}
5609
5611 ScalarEvolution &SE) {
5612 SCEVFlags Flags = SCEV::FlagNone;
5613 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
5614 // If the increment has any nowrap flags, then we know the address
5615 // space cannot be wrapped around.
5616 if (NW != GEPNoWrapFlags::none())
5618 // If the GEP is nuw or nusw with non-negative offset, we know that
5619 // no unsigned wrap occurs. We cannot set the nsw flag as only the
5620 // offset is treated as signed, while the base is unsigned.
5621 if (NW.hasNoUnsignedWrap() ||
5622 (NW.hasNoUnsignedSignedWrap() && SE.isKnownNonNegative(Accum)))
5624
5625 return Flags;
5626}
5627
5628/// A helper function for createAddRecFromPHI to handle simple cases.
5629///
5630/// This function tries to find an AddRec expression for the simplest (yet most
5631/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5632/// If it fails, createAddRecFromPHI will use a more general, but slow,
5633/// technique for finding the AddRec expression.
5634const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5635 Value *BEValueV,
5636 Value *StartValueV) {
5637 const Loop *L = LI.getLoopFor(PN->getParent());
5638 assert(L && L->getHeader() == PN->getParent());
5639 assert(BEValueV && StartValueV);
5640
5641 const SCEV *Accum = nullptr;
5643 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5644 if (BO->Opcode != Instruction::Add)
5645 return nullptr;
5646
5647 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5648 Accum = getSCEV(BO->RHS);
5649 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5650 Accum = getSCEV(BO->LHS);
5651
5652 if (!Accum)
5653 return nullptr;
5654
5655 if (BO->IsNUW)
5656 Flags = setFlags(Flags, SCEV::FlagNUW);
5657 if (BO->IsNSW)
5658 Flags = setFlags(Flags, SCEV::FlagNSW);
5659 } else {
5660 // Handle pointer induction variable: PN = PHI(Start, gep PN,
5661 // LoopInvariant).
5662 auto *GEP = dyn_cast<GEPOperator>(BEValueV);
5663 if (!GEP || GEP->getPointerOperand() != PN || GEP->getNumIndices() != 1)
5664 return nullptr;
5665 Value *Idx = *GEP->idx_begin();
5666 if (!L->isLoopInvariant(Idx))
5667 return nullptr;
5668
5669 Type *IntIdxTy = getEffectiveSCEVType(GEP->getType());
5670 Accum = getMulExpr(getTruncateOrSignExtend(getSCEV(Idx), IntIdxTy),
5671 getSizeOfExpr(IntIdxTy, GEP->getSourceElementType()));
5672 Flags = getNoWrapFlagsForGEP(GEP, Accum, *this);
5673 }
5674
5675 const SCEV *StartVal = getSCEV(StartValueV);
5676 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5677 insertValueToMap(PN, PHISCEV);
5678
5679 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5680 inferNoWrapViaConstantRanges(AR);
5681
5682 // We can add Flags to the post-inc expression only if we
5683 // know that it is *undefined behavior* for BEValueV to
5684 // overflow.
5685 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5686 assert(isLoopInvariant(Accum, L) &&
5687 "Accum is defined outside L, but is not invariant?");
5688 if (isAddRecNeverPoison(BEInst, L))
5689 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5690 }
5691
5692 return PHISCEV;
5693}
5694
5695const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5696 const Loop *L = LI.getLoopFor(PN->getParent());
5697 if (!L || L->getHeader() != PN->getParent())
5698 return nullptr;
5699
5700 // The loop may have multiple entrances or multiple exits; we can analyze
5701 // this phi as an addrec if it has a unique entry value and a unique
5702 // backedge value.
5703 Value *BEValueV = nullptr, *StartValueV = nullptr;
5704 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5705 Value *V = PN->getIncomingValue(i);
5706 if (L->contains(PN->getIncomingBlock(i))) {
5707 if (!BEValueV) {
5708 BEValueV = V;
5709 } else if (BEValueV != V) {
5710 BEValueV = nullptr;
5711 break;
5712 }
5713 } else if (!StartValueV) {
5714 StartValueV = V;
5715 } else if (StartValueV != V) {
5716 StartValueV = nullptr;
5717 break;
5718 }
5719 }
5720 if (!BEValueV || !StartValueV)
5721 return nullptr;
5722
5723 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5724 "PHI node already processed?");
5725
5726 // First, try to find AddRec expression without creating a fictituos symbolic
5727 // value for PN.
5728 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5729 return S;
5730
5731 // Handle PHI node value symbolically.
5732 const SCEV *SymbolicName = getUnknown(PN);
5733 insertValueToMap(PN, SymbolicName);
5734
5735 // Using this symbolic name for the PHI, analyze the value coming around
5736 // the back-edge.
5737 const SCEV *BEValue = getSCEV(BEValueV);
5738
5739 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5740 // has a special value for the first iteration of the loop.
5741
5742 // If the value coming around the backedge is an add with the symbolic
5743 // value we just inserted, then we found a simple induction variable!
5744 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5745 // If there is a single occurrence of the symbolic value, replace it
5746 // with a recurrence.
5747 unsigned FoundIndex = Add->getNumOperands();
5748 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5749 if (Add->getOperand(i) == SymbolicName)
5750 if (FoundIndex == e) {
5751 FoundIndex = i;
5752 break;
5753 }
5754
5755 if (FoundIndex != Add->getNumOperands()) {
5756 // Create an add with everything but the specified operand.
5758 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5759 if (i != FoundIndex)
5760 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5761 L, *this));
5762 const SCEV *Accum = getAddExpr(Ops);
5763
5764 // This is not a valid addrec if the step amount is varying each
5765 // loop iteration, but is not itself an addrec in this loop.
5766 if (isLoopInvariant(Accum, L) ||
5767 (isa<SCEVAddRecExpr>(Accum) &&
5768 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5770
5771 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5772 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5773 if (BO->IsNUW)
5774 Flags = setFlags(Flags, SCEV::FlagNUW);
5775 if (BO->IsNSW)
5776 Flags = setFlags(Flags, SCEV::FlagNSW);
5777 }
5778 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5779 if (GEP->getOperand(0) == PN)
5780 Flags = getNoWrapFlagsForGEP(GEP, Accum, *this);
5781
5782 // We cannot transfer nuw and nsw flags from subtraction
5783 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5784 // for instance.
5785 }
5786
5787 const SCEV *StartVal = getSCEV(StartValueV);
5788 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5789
5790 // Okay, for the entire analysis of this edge we assumed the PHI
5791 // to be symbolic. We now need to go back and purge all of the
5792 // entries for the scalars that use the symbolic expression.
5793 forgetMemoizedResults({SymbolicName});
5794 insertValueToMap(PN, PHISCEV);
5795
5796 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5797 inferNoWrapViaConstantRanges(AR);
5798
5799 // We can add Flags to the post-inc expression only if we
5800 // know that it is *undefined behavior* for BEValueV to
5801 // overflow.
5802 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5803 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5804 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5805
5806 return PHISCEV;
5807 }
5808 }
5809 } else {
5810 // Otherwise, this could be a loop like this:
5811 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5812 // In this case, j = {1,+,1} and BEValue is j.
5813 // Because the other in-value of i (0) fits the evolution of BEValue
5814 // i really is an addrec evolution.
5815 //
5816 // We can generalize this saying that i is the shifted value of BEValue
5817 // by one iteration:
5818 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5819
5820 // Do not allow refinement in rewriting of BEValue.
5821 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5822 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5823 if (Shifted != getCouldNotCompute() && Start != getCouldNotCompute() &&
5824 isGuaranteedNotToCauseUB(Shifted) && ::impliesPoison(Shifted, Start)) {
5825 const SCEV *StartVal = getSCEV(StartValueV);
5826 if (Start == StartVal) {
5827 // Okay, for the entire analysis of this edge we assumed the PHI
5828 // to be symbolic. We now need to go back and purge all of the
5829 // entries for the scalars that use the symbolic expression.
5830 forgetMemoizedResults({SymbolicName});
5831 insertValueToMap(PN, Shifted);
5832 return Shifted;
5833 }
5834 }
5835 }
5836
5837 // Remove the temporary PHI node SCEV that has been inserted while intending
5838 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5839 // as it will prevent later (possibly simpler) SCEV expressions to be added
5840 // to the ValueExprMap.
5841 eraseValueFromMap(PN);
5842
5843 return nullptr;
5844}
5845
5846// Try to match a control flow sequence that branches out at BI and merges back
5847// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5848// match.
5850 Value *&C, Value *&LHS, Value *&RHS) {
5851 C = BI->getCondition();
5852
5853 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5854 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5855
5856 Use &LeftUse = Merge->getOperandUse(0);
5857 Use &RightUse = Merge->getOperandUse(1);
5858
5859 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5860 LHS = LeftUse;
5861 RHS = RightUse;
5862 return true;
5863 }
5864
5865 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5866 LHS = RightUse;
5867 RHS = LeftUse;
5868 return true;
5869 }
5870
5871 return false;
5872}
5873
5875 Value *&Cond, Value *&LHS,
5876 Value *&RHS) {
5877 auto IsReachable =
5878 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5879 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5880 // Try to match
5881 //
5882 // br %cond, label %left, label %right
5883 // left:
5884 // br label %merge
5885 // right:
5886 // br label %merge
5887 // merge:
5888 // V = phi [ %x, %left ], [ %y, %right ]
5889 //
5890 // as "select %cond, %x, %y"
5891
5892 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5893 assert(IDom && "At least the entry block should dominate PN");
5894
5895 auto *BI = dyn_cast<CondBrInst>(IDom->getTerminator());
5896 return BI && BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS);
5897 }
5898 return false;
5899}
5900
5901const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5902 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5903 if (getOperandsForSelectLikePHI(DT, PN, Cond, LHS, RHS) &&
5906 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5907
5908 return nullptr;
5909}
5910
5912 BinaryOperator *CommonInst = nullptr;
5913 // Check if instructions are identical.
5914 for (Value *Incoming : PN->incoming_values()) {
5915 auto *IncomingInst = dyn_cast<BinaryOperator>(Incoming);
5916 if (!IncomingInst)
5917 return nullptr;
5918 if (CommonInst) {
5919 if (!CommonInst->isIdenticalToWhenDefined(IncomingInst))
5920 return nullptr; // Not identical, give up
5921 } else {
5922 // Remember binary operator
5923 CommonInst = IncomingInst;
5924 }
5925 }
5926 return CommonInst;
5927}
5928
5929/// Returns SCEV for the first operand of a phi if all phi operands have
5930/// identical opcodes and operands
5931/// eg.
5932/// a: %add = %a + %b
5933/// br %c
5934/// b: %add1 = %a + %b
5935/// br %c
5936/// c: %phi = phi [%add, a], [%add1, b]
5937/// scev(%phi) => scev(%add)
5938const SCEV *
5939ScalarEvolution::createNodeForPHIWithIdenticalOperands(PHINode *PN) {
5940 BinaryOperator *CommonInst = getCommonInstForPHI(PN);
5941 if (!CommonInst)
5942 return nullptr;
5943
5944 // Check if SCEV exprs for instructions are identical.
5945 const SCEV *CommonSCEV = getSCEV(CommonInst);
5946 bool SCEVExprsIdentical =
5948 [this, CommonSCEV](Value *V) { return CommonSCEV == getSCEV(V); });
5949 return SCEVExprsIdentical ? CommonSCEV : nullptr;
5950}
5951
5952const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5953 if (const SCEV *S = createAddRecFromPHI(PN))
5954 return S;
5955
5956 // We do not allow simplifying phi (undef, X) to X here, to avoid reusing the
5957 // phi node for X.
5958 if (Value *V = simplifyInstruction(
5959 PN, {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
5960 /*UseInstrInfo=*/true, /*CanUseUndef=*/false}))
5961 return getSCEV(V);
5962
5963 if (const SCEV *S = createNodeForPHIWithIdenticalOperands(PN))
5964 return S;
5965
5966 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5967 return S;
5968
5969 // If it's not a loop phi, we can't handle it yet.
5970 return getUnknown(PN);
5971}
5972
5973bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
5974 SCEVTypes RootKind) {
5975 struct FindClosure {
5976 const SCEV *OperandToFind;
5977 const SCEVTypes RootKind; // Must be a sequential min/max expression.
5978 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
5979
5980 bool Found = false;
5981
5982 bool canRecurseInto(SCEVTypes Kind) const {
5983 // We can only recurse into the SCEV expression of the same effective type
5984 // as the type of our root SCEV expression, and into zero-extensions.
5985 return RootKind == Kind || NonSequentialRootKind == Kind ||
5986 scZeroExtend == Kind;
5987 };
5988
5989 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
5990 : OperandToFind(OperandToFind), RootKind(RootKind),
5991 NonSequentialRootKind(
5993 RootKind)) {}
5994
5995 bool follow(const SCEV *S) {
5996 Found = S == OperandToFind;
5997
5998 return !isDone() && canRecurseInto(S->getSCEVType());
5999 }
6000
6001 bool isDone() const { return Found; }
6002 };
6003
6004 FindClosure FC(OperandToFind, RootKind);
6005 visitAll(Root, FC);
6006 return FC.Found;
6007}
6008
6009std::optional<const SCEV *>
6010ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
6011 ICmpInst *Cond,
6012 Value *TrueVal,
6013 Value *FalseVal) {
6014 // Try to match some simple smax or umax patterns.
6015 auto *ICI = Cond;
6016
6017 Value *LHS = ICI->getOperand(0);
6018 Value *RHS = ICI->getOperand(1);
6019
6020 switch (ICI->getPredicate()) {
6021 case ICmpInst::ICMP_SLT:
6022 case ICmpInst::ICMP_SLE:
6023 case ICmpInst::ICMP_ULT:
6024 case ICmpInst::ICMP_ULE:
6025 std::swap(LHS, RHS);
6026 [[fallthrough]];
6027 case ICmpInst::ICMP_SGT:
6028 case ICmpInst::ICMP_SGE:
6029 case ICmpInst::ICMP_UGT:
6030 case ICmpInst::ICMP_UGE:
6031 // a > b ? a+x : b+x -> max(a, b)+x
6032 // a > b ? b+x : a+x -> min(a, b)+x
6034 bool Signed = ICI->isSigned();
6035 const SCEV *LA = getSCEV(TrueVal);
6036 const SCEV *RA = getSCEV(FalseVal);
6037 const SCEV *LS = getSCEV(LHS);
6038 const SCEV *RS = getSCEV(RHS);
6039 if (LA->getType()->isPointerTy()) {
6040 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6041 // Need to make sure we can't produce weird expressions involving
6042 // negated pointers.
6043 if (LA == LS && RA == RS)
6044 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6045 if (LA == RS && RA == LS)
6046 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6047 }
6048 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6049 if (Op->getType()->isPointerTy()) {
6052 return Op;
6053 }
6054 if (Signed)
6055 Op = getNoopOrSignExtend(Op, Ty);
6056 else
6057 Op = getNoopOrZeroExtend(Op, Ty);
6058 return Op;
6059 };
6060 LS = CoerceOperand(LS);
6061 RS = CoerceOperand(RS);
6063 break;
6064 const SCEV *LDiff = getMinusSCEV(LA, LS);
6065 const SCEV *RDiff = getMinusSCEV(RA, RS);
6066 if (LDiff == RDiff)
6067 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6068 LDiff);
6069 LDiff = getMinusSCEV(LA, RS);
6070 RDiff = getMinusSCEV(RA, LS);
6071 if (LDiff == RDiff)
6072 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6073 LDiff);
6074 }
6075 break;
6076 case ICmpInst::ICMP_NE:
6077 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
6078 std::swap(TrueVal, FalseVal);
6079 [[fallthrough]];
6080 case ICmpInst::ICMP_EQ:
6081 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
6084 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6085 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y
6086 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y
6087 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6088 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y
6089 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6090 return getAddExpr(getUMaxExpr(X, C), Y);
6091 }
6092 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
6093 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
6094 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
6095 // -> umin_seq(x, umin (..., umin_seq(...), ...))
6097 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6098 const SCEV *X = getSCEV(LHS);
6099 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6100 X = ZExt->getOperand();
6101 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6102 const SCEV *FalseValExpr = getSCEV(FalseVal);
6103 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6104 return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6105 /*Sequential=*/true);
6106 }
6107 }
6108 break;
6109 default:
6110 break;
6111 }
6112
6113 return std::nullopt;
6114}
6115
6116static std::optional<const SCEV *>
6118 const SCEV *TrueExpr, const SCEV *FalseExpr) {
6119 assert(CondExpr->getType()->isIntegerTy(1) &&
6120 TrueExpr->getType() == FalseExpr->getType() &&
6121 TrueExpr->getType()->isIntegerTy(1) &&
6122 "Unexpected operands of a select.");
6123
6124 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
6125 // --> C + (umin_seq cond, x - C)
6126 //
6127 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
6128 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6129 // --> C + (umin_seq ~cond, x - C)
6130
6131 // FIXME: while we can't legally model the case where both of the hands
6132 // are fully variable, we only require that the *difference* is constant.
6133 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6134 return std::nullopt;
6135
6136 const SCEV *X, *C;
6137 if (isa<SCEVConstant>(TrueExpr)) {
6138 CondExpr = SE->getNotSCEV(CondExpr);
6139 X = FalseExpr;
6140 C = TrueExpr;
6141 } else {
6142 X = TrueExpr;
6143 C = FalseExpr;
6144 }
6145 return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6146 /*Sequential=*/true));
6147}
6148
6149static std::optional<const SCEV *>
6151 Value *FalseVal) {
6152 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6153 return std::nullopt;
6154
6155 const auto *SECond = SE->getSCEV(Cond);
6156 const auto *SETrue = SE->getSCEV(TrueVal);
6157 const auto *SEFalse = SE->getSCEV(FalseVal);
6158 return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6159}
6160
6161const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6162 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6163 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6164 assert(TrueVal->getType() == FalseVal->getType() &&
6165 V->getType() == TrueVal->getType() &&
6166 "Types of select hands and of the result must match.");
6167
6168 // For now, only deal with i1-typed `select`s.
6169 if (!V->getType()->isIntegerTy(1))
6170 return getUnknown(V);
6171
6172 if (std::optional<const SCEV *> S =
6173 createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6174 return *S;
6175
6176 return getUnknown(V);
6177}
6178
6179const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6180 Value *TrueVal,
6181 Value *FalseVal) {
6182 // Handle "constant" branch or select. This can occur for instance when a
6183 // loop pass transforms an inner loop and moves on to process the outer loop.
6184 if (auto *CI = dyn_cast<ConstantInt>(Cond))
6185 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6186
6187 if (auto *I = dyn_cast<Instruction>(V)) {
6188 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6189 if (std::optional<const SCEV *> S =
6190 createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6191 TrueVal, FalseVal))
6192 return *S;
6193 }
6194 }
6195
6196 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6197}
6198
6199/// Expand GEP instructions into add and multiply operations. This allows them
6200/// to be analyzed by regular SCEV code.
6201const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6202 assert(GEP->getSourceElementType()->isSized() &&
6203 "GEP source element type must be sized");
6204
6205 SmallVector<SCEVUse, 4> IndexExprs;
6206 for (Value *Index : GEP->indices())
6207 IndexExprs.push_back(getSCEV(Index));
6208 return getGEPExpr(GEP, IndexExprs);
6209}
6210
6211APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S,
6212 const Instruction *CtxI) {
6214 auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6215 return TrailingZeros >= BitWidth
6217 : APInt::getOneBitSet(BitWidth, TrailingZeros);
6218 };
6219 auto GetGCDMultiple = [this, CtxI](const SCEVNAryExpr *N) {
6220 // The result is GCD of all operands results.
6221 APInt Res = getConstantMultiple(N->getOperand(0), CtxI);
6222 for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6224 Res, getConstantMultiple(N->getOperand(I), CtxI));
6225 return Res;
6226 };
6227
6228 switch (S->getSCEVType()) {
6229 case scConstant:
6230 return cast<SCEVConstant>(S)->getAPInt();
6231 case scPtrToAddr:
6232 return getConstantMultiple(cast<SCEVCastExpr>(S)->getOperand());
6233 case scUDivExpr:
6234 case scVScale:
6235 return APInt(BitWidth, 1);
6236 case scTruncate: {
6237 // Only multiples that are a power of 2 will hold after truncation.
6238 const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6239 uint32_t TZ = getMinTrailingZeros(T->getOperand(), CtxI);
6240 return GetShiftedByZeros(TZ);
6241 }
6242 case scZeroExtend: {
6243 const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(S);
6244 return getConstantMultiple(Z->getOperand(), CtxI).zext(BitWidth);
6245 }
6246 case scSignExtend: {
6247 // Only multiples that are a power of 2 will hold after sext.
6248 const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6249 uint32_t TZ = getMinTrailingZeros(E->getOperand(), CtxI);
6250 return GetShiftedByZeros(TZ);
6251 }
6252 case scMulExpr: {
6253 const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6254 if (M->hasNoUnsignedWrap()) {
6255 // The result is the product of all operand results.
6256 APInt Res = getConstantMultiple(M->getOperand(0), CtxI);
6257 for (const SCEV *Operand : M->operands().drop_front())
6258 Res = Res * getConstantMultiple(Operand, CtxI);
6259 return Res;
6260 }
6261
6262 // If there are no wrap guarentees, find the trailing zeros, which is the
6263 // sum of trailing zeros for all its operands.
6264 uint32_t TZ = 0;
6265 for (const SCEV *Operand : M->operands())
6266 TZ += getMinTrailingZeros(Operand, CtxI);
6267 return GetShiftedByZeros(TZ);
6268 }
6269 case scAddExpr:
6270 case scAddRecExpr: {
6271 const SCEVNAryExpr *N = cast<SCEVNAryExpr>(S);
6272 if (N->hasNoUnsignedWrap())
6273 return GetGCDMultiple(N);
6274 // Find the trailing bits, which is the minimum of its operands.
6275 uint32_t TZ = getMinTrailingZeros(N->getOperand(0), CtxI);
6276 for (const SCEV *Operand : N->operands().drop_front())
6277 TZ = std::min(TZ, getMinTrailingZeros(Operand, CtxI));
6278 return GetShiftedByZeros(TZ);
6279 }
6280 case scUMaxExpr:
6281 case scSMaxExpr:
6282 case scUMinExpr:
6283 case scSMinExpr:
6285 return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6286 case scUnknown: {
6287 // Ask ValueTracking for known bits. SCEVUnknown only become available at
6288 // the point their underlying IR instruction has been defined. If CtxI was
6289 // not provided, use:
6290 // * the first instruction in the entry block if it is an argument
6291 // * the instruction itself otherwise.
6292 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6293 if (!CtxI) {
6294 if (isa<Argument>(U->getValue()))
6295 CtxI = &*F.getEntryBlock().begin();
6296 else if (auto *I = dyn_cast<Instruction>(U->getValue()))
6297 CtxI = I;
6298 }
6299 unsigned Known =
6300 computeKnownBits(U->getValue(),
6301 SimplifyQuery(getDataLayout(), &DT, &AC, CtxI)
6302 .allowEphemerals(true))
6303 .countMinTrailingZeros();
6304 return GetShiftedByZeros(Known);
6305 }
6306 case scCouldNotCompute:
6307 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6308 }
6309 llvm_unreachable("Unknown SCEV kind!");
6310}
6311
6313 const Instruction *CtxI) {
6314 // Skip looking up and updating the cache if there is a context instruction,
6315 // as the result will only be valid in the specified context.
6316 if (CtxI)
6317 return getConstantMultipleImpl(S, CtxI);
6318
6319 auto I = ConstantMultipleCache.find(S);
6320 if (I != ConstantMultipleCache.end())
6321 return I->second;
6322
6323 APInt Result = getConstantMultipleImpl(S, CtxI);
6324 auto InsertPair = ConstantMultipleCache.insert({S, Result});
6325 assert(InsertPair.second && "Should insert a new key");
6326 return InsertPair.first->second;
6327}
6328
6330 APInt Multiple = getConstantMultiple(S);
6331 return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6332}
6333
6335 const Instruction *CtxI) {
6336 return std::min(getConstantMultiple(S, CtxI).countTrailingZeros(),
6337 (unsigned)getTypeSizeInBits(S->getType()));
6338}
6339
6340/// Helper method to assign a range to V from metadata present in the IR.
6341static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6343 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6344 return getConstantRangeFromMetadata(*MD);
6345 if (const auto *CB = dyn_cast<CallBase>(V))
6346 if (std::optional<ConstantRange> Range = CB->getRange())
6347 return Range;
6348 }
6349 if (auto *A = dyn_cast<Argument>(V))
6350 if (std::optional<ConstantRange> Range = A->getRange())
6351 return Range;
6352
6353 return std::nullopt;
6354}
6355
6357 SCEVFlags NWFlags = Flags & SCEV::FlagsNoWrapMask;
6358 if (AddRec->getNoWrapFlags(NWFlags) != NWFlags) {
6359 AddRec->setNoWrapFlags(NWFlags);
6360 UnsignedRanges.erase(AddRec);
6361 SignedRanges.erase(AddRec);
6362 ConstantMultipleCache.erase(AddRec);
6363 }
6364}
6365
6366ConstantRange ScalarEvolution::
6367getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6368 const DataLayout &DL = getDataLayout();
6369
6370 unsigned BitWidth = getTypeSizeInBits(U->getType());
6371 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6372
6373 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6374 // use information about the trip count to improve our available range. Note
6375 // that the trip count independent cases are already handled by known bits.
6376 // WARNING: The definition of recurrence used here is subtly different than
6377 // the one used by AddRec (and thus most of this file). Step is allowed to
6378 // be arbitrarily loop varying here, where AddRec allows only loop invariant
6379 // and other addrecs in the same loop (for non-affine addrecs). The code
6380 // below intentionally handles the case where step is not loop invariant.
6381 auto *P = dyn_cast<PHINode>(U->getValue());
6382 if (!P)
6383 return FullSet;
6384
6385 // Make sure that no Phi input comes from an unreachable block. Otherwise,
6386 // even the values that are not available in these blocks may come from them,
6387 // and this leads to false-positive recurrence test.
6388 for (auto *Pred : predecessors(P->getParent()))
6389 if (!DT.isReachableFromEntry(Pred))
6390 return FullSet;
6391
6392 BinaryOperator *BO;
6393 Value *Start, *Step;
6394 if (!matchSimpleRecurrence(P, BO, Start, Step))
6395 return FullSet;
6396
6397 // If we found a recurrence in reachable code, we must be in a loop. Note
6398 // that BO might be in some subloop of L, and that's completely okay.
6399 auto *L = LI.getLoopFor(P->getParent());
6400 assert(L && L->getHeader() == P->getParent());
6401 if (!L->contains(BO->getParent()))
6402 // NOTE: This bailout should be an assert instead. However, asserting
6403 // the condition here exposes a case where LoopFusion is querying SCEV
6404 // with malformed loop information during the midst of the transform.
6405 // There doesn't appear to be an obvious fix, so for the moment bailout
6406 // until the caller issue can be fixed. PR49566 tracks the bug.
6407 return FullSet;
6408
6409 // TODO: Extend to other opcodes such as mul, and div
6410 switch (BO->getOpcode()) {
6411 default:
6412 return FullSet;
6413 case Instruction::AShr:
6414 case Instruction::LShr:
6415 case Instruction::Shl:
6416 break;
6417 };
6418
6419 if (BO->getOperand(0) != P)
6420 // TODO: Handle the power function forms some day.
6421 return FullSet;
6422
6423 unsigned TC = getSmallConstantMaxTripCount(L);
6424 if (!TC || TC >= BitWidth)
6425 return FullSet;
6426
6427 auto KnownStart = computeKnownBits(Start, DL, &AC, nullptr, &DT);
6428 auto KnownStep = computeKnownBits(Step, DL, &AC, nullptr, &DT);
6429 assert(KnownStart.getBitWidth() == BitWidth &&
6430 KnownStep.getBitWidth() == BitWidth);
6431
6432 // Compute total shift amount, being careful of overflow and bitwidths.
6433 auto MaxShiftAmt = KnownStep.getMaxValue();
6434 APInt TCAP(BitWidth, TC-1);
6435 bool Overflow = false;
6436 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6437 if (Overflow)
6438 return FullSet;
6439
6440 switch (BO->getOpcode()) {
6441 default:
6442 llvm_unreachable("filtered out above");
6443 case Instruction::AShr: {
6444 // For each ashr, three cases:
6445 // shift = 0 => unchanged value
6446 // saturation => 0 or -1
6447 // other => a value closer to zero (of the same sign)
6448 // Thus, the end value is closer to zero than the start.
6449 auto KnownEnd = KnownBits::ashr(KnownStart,
6450 KnownBits::makeConstant(TotalShift));
6451 if (KnownStart.isNonNegative())
6452 // Analogous to lshr (simply not yet canonicalized)
6453 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6454 KnownStart.getMaxValue() + 1);
6455 if (KnownStart.isNegative())
6456 // End >=u Start && End <=s Start
6457 return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6458 KnownEnd.getMaxValue() + 1);
6459 break;
6460 }
6461 case Instruction::LShr: {
6462 // For each lshr, three cases:
6463 // shift = 0 => unchanged value
6464 // saturation => 0
6465 // other => a smaller positive number
6466 // Thus, the low end of the unsigned range is the last value produced.
6467 auto KnownEnd = KnownBits::lshr(KnownStart,
6468 KnownBits::makeConstant(TotalShift));
6469 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6470 KnownStart.getMaxValue() + 1);
6471 }
6472 case Instruction::Shl: {
6473 // Iff no bits are shifted out, value increases on every shift.
6474 auto KnownEnd = KnownBits::shl(KnownStart,
6475 KnownBits::makeConstant(TotalShift));
6476 if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6477 return ConstantRange(KnownStart.getMinValue(),
6478 KnownEnd.getMaxValue() + 1);
6479 break;
6480 }
6481 };
6482 return FullSet;
6483}
6484
6485// The goal of this function is to check if recursively visiting the operands
6486// of this PHI might lead to an infinite loop. If we do see such a loop,
6487// there's no good way to break it, so we avoid analyzing such cases.
6488//
6489// getRangeRef previously used a visited set to avoid infinite loops, but this
6490// caused other issues: the result was dependent on the order of getRangeRef
6491// calls, and the interaction with createSCEVIter could cause a stack overflow
6492// in some cases (see issue #148253).
6493//
6494// FIXME: The way this is implemented is overly conservative; this checks
6495// for a few obviously safe patterns, but anything that doesn't lead to
6496// recursion is fine.
6498 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6500 return true;
6501
6502 if (all_of(PHI->operands(),
6503 [&](Value *Operand) { return DT.dominates(Operand, PHI); }))
6504 return true;
6505
6506 return false;
6507}
6508
6509const ConstantRange &
6510ScalarEvolution::getRangeRefIter(const SCEV *S,
6511 ScalarEvolution::RangeSignHint SignHint) {
6512 DenseMap<const SCEV *, ConstantRange> &Cache =
6513 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6514 : SignedRanges;
6515 SmallVector<SCEVUse> WorkList;
6516 SmallPtrSet<const SCEV *, 8> Seen;
6517
6518 // Add Expr to the worklist, if Expr is either an N-ary expression or a
6519 // SCEVUnknown PHI node.
6520 auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6521 if (!Seen.insert(Expr).second)
6522 return;
6523 if (Cache.contains(Expr))
6524 return;
6525 switch (Expr->getSCEVType()) {
6526 case scUnknown:
6528 break;
6529 [[fallthrough]];
6530 case scConstant:
6531 case scVScale:
6532 case scTruncate:
6533 case scZeroExtend:
6534 case scSignExtend:
6535 case scPtrToAddr:
6536 case scAddExpr:
6537 case scMulExpr:
6538 case scUDivExpr:
6539 case scAddRecExpr:
6540 case scUMaxExpr:
6541 case scSMaxExpr:
6542 case scUMinExpr:
6543 case scSMinExpr:
6545 WorkList.push_back(Expr);
6546 break;
6547 case scCouldNotCompute:
6548 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6549 }
6550 };
6551 AddToWorklist(S);
6552
6553 // Build worklist by queuing operands of N-ary expressions and phi nodes.
6554 for (unsigned I = 0; I != WorkList.size(); ++I) {
6555 const SCEV *P = WorkList[I];
6556 auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6557 // If it is not a `SCEVUnknown`, just recurse into operands.
6558 if (!UnknownS) {
6559 for (const SCEV *Op : P->operands())
6560 AddToWorklist(Op);
6561 continue;
6562 }
6563 // `SCEVUnknown`'s require special treatment.
6564 if (PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6565 if (!RangeRefPHIAllowedOperands(DT, P))
6566 continue;
6567 for (auto &Op : reverse(P->operands()))
6568 AddToWorklist(getSCEV(Op));
6569 }
6570 }
6571
6572 if (!WorkList.empty()) {
6573 // Use getRangeRef to compute ranges for items in the worklist in reverse
6574 // order. This will force ranges for earlier operands to be computed before
6575 // their users in most cases.
6576 for (const SCEV *P : reverse(drop_begin(WorkList))) {
6577 getRangeRef(P, SignHint);
6578 }
6579 }
6580
6581 return getRangeRef(S, SignHint, 0);
6582}
6583
6584const APInt *ScalarEvolution::getConstantAPIntOrNull(const SCEV *S) {
6585 if (const auto *C = dyn_cast<SCEVConstant>(S))
6586 return &C->getAPInt();
6587 return nullptr;
6588}
6589
6590/// Determine the range for a particular SCEV. If SignHint is
6591/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6592/// with a "cleaner" unsigned (resp. signed) representation.
6593const ConstantRange &ScalarEvolution::getRangeRef(
6594 const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6595 DenseMap<const SCEV *, ConstantRange> &Cache =
6596 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6597 : SignedRanges;
6599 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6601
6602 // See if we've computed this range already.
6603 auto I = Cache.find(S);
6604 if (I != Cache.end())
6605 return I->second;
6606
6607 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6608 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6609
6610 // Switch to iteratively computing the range for S, if it is part of a deeply
6611 // nested expression.
6612 if (Depth > Opts.scev_range_iter_threshold)
6613 return getRangeRefIter(S, SignHint);
6614
6615 unsigned BitWidth = getTypeSizeInBits(S->getType());
6616 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6617 using OBO = OverflowingBinaryOperator;
6618
6619 // If the value has known zeros, the maximum value will have those known zeros
6620 // as well.
6621 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6622 APInt Multiple = getNonZeroConstantMultiple(S);
6623 APInt Remainder = APInt::getMaxValue(BitWidth).urem(Multiple);
6624 if (!Remainder.isZero())
6625 ConservativeResult =
6626 ConstantRange(APInt::getMinValue(BitWidth),
6627 APInt::getMaxValue(BitWidth) - Remainder + 1);
6628 }
6629 else {
6630 uint32_t TZ = getMinTrailingZeros(S);
6631 if (TZ != 0) {
6632 ConservativeResult = ConstantRange(
6634 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6635 }
6636 }
6637
6638 switch (S->getSCEVType()) {
6639 case scConstant:
6640 llvm_unreachable("Already handled above.");
6641 case scVScale:
6642 return setRange(S, SignHint, getVScaleRange(&F, BitWidth));
6643 case scTruncate: {
6644 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6645 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6646 return setRange(
6647 Trunc, SignHint,
6648 ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6649 }
6650 case scZeroExtend: {
6651 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6652 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6653 return setRange(
6654 ZExt, SignHint,
6655 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6656 }
6657 case scSignExtend: {
6658 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6659 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6660 return setRange(
6661 SExt, SignHint,
6662 ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6663 }
6664 case scPtrToAddr: {
6665 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6666 ConstantRange X = getRangeRef(Cast->getOperand(), SignHint, Depth + 1);
6667 return setRange(Cast, SignHint, X);
6668 }
6669 case scAddExpr: {
6670 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6671 // Check if this is a URem pattern: A - (A / B) * B, which is always < B.
6672 const SCEV *URemLHS = nullptr, *URemRHS = nullptr;
6673 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED &&
6674 match(S, m_scev_URem(m_SCEV(URemLHS), m_SCEV(URemRHS), *this))) {
6675 ConstantRange LHSRange = getRangeRef(URemLHS, SignHint, Depth + 1);
6676 ConstantRange RHSRange = getRangeRef(URemRHS, SignHint, Depth + 1);
6677 ConservativeResult =
6678 ConservativeResult.intersectWith(LHSRange.urem(RHSRange), RangeType);
6679 }
6680 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6681 unsigned WrapType = OBO::AnyWrap;
6682 if (Add->hasNoSignedWrap())
6683 WrapType |= OBO::NoSignedWrap;
6684 if (Add->hasNoUnsignedWrap())
6685 WrapType |= OBO::NoUnsignedWrap;
6686 for (const SCEV *Op : drop_begin(Add->operands()))
6687 X = X.addWithNoWrap(getRangeRef(Op, SignHint, Depth + 1), WrapType,
6688 RangeType);
6689 return setRange(Add, SignHint,
6690 ConservativeResult.intersectWith(X, RangeType));
6691 }
6692 case scMulExpr: {
6693 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6694 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6695 for (const SCEV *Op : drop_begin(Mul->operands()))
6696 X = X.multiply(getRangeRef(Op, SignHint, Depth + 1));
6697 return setRange(Mul, SignHint,
6698 ConservativeResult.intersectWith(X, RangeType));
6699 }
6700 case scUDivExpr: {
6701 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6702 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6703 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6704 return setRange(UDiv, SignHint,
6705 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6706 }
6707 case scAddRecExpr: {
6708 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6709 // If there's no unsigned wrap, the value will never be less than its
6710 // initial value.
6711 if (AddRec->hasNoUnsignedWrap()) {
6712 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6713 if (!UnsignedMinValue.isZero())
6714 ConservativeResult = ConservativeResult.intersectWith(
6715 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6716 }
6717
6718 // If there's no signed wrap, and all the operands except initial value have
6719 // the same sign or zero, the value won't ever be:
6720 // 1: smaller than initial value if operands are non negative,
6721 // 2: bigger than initial value if operands are non positive.
6722 // For both cases, value can not cross signed min/max boundary.
6723 if (AddRec->hasNoSignedWrap()) {
6724 bool AllNonNeg = true;
6725 bool AllNonPos = true;
6726 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6727 if (!isKnownNonNegative(AddRec->getOperand(i)))
6728 AllNonNeg = false;
6729 if (!isKnownNonPositive(AddRec->getOperand(i)))
6730 AllNonPos = false;
6731 }
6732 if (AllNonNeg)
6733 ConservativeResult = ConservativeResult.intersectWith(
6736 RangeType);
6737 else if (AllNonPos)
6738 ConservativeResult = ConservativeResult.intersectWith(
6740 getSignedRangeMax(AddRec->getStart()) +
6741 1),
6742 RangeType);
6743 }
6744
6745 // TODO: non-affine addrec
6746 if (AddRec->isAffine()) {
6747 const SCEV *MaxBEScev =
6749 if (!isa<SCEVCouldNotCompute>(MaxBEScev)) {
6750 APInt MaxBECount = cast<SCEVConstant>(MaxBEScev)->getAPInt();
6751
6752 // Adjust MaxBECount to the same bitwidth as AddRec. We can truncate if
6753 // MaxBECount's active bits are all <= AddRec's bit width.
6754 if (MaxBECount.getBitWidth() > BitWidth &&
6755 MaxBECount.getActiveBits() <= BitWidth)
6756 MaxBECount = MaxBECount.trunc(BitWidth);
6757 else if (MaxBECount.getBitWidth() < BitWidth)
6758 MaxBECount = MaxBECount.zext(BitWidth);
6759
6760 if (MaxBECount.getBitWidth() == BitWidth) {
6761 auto [RangeFromAffine, Flags] = getRangeForAffineAR(
6762 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6763 ConservativeResult =
6764 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6765 const_cast<SCEVAddRecExpr *>(AddRec)->setNoWrapFlags(Flags);
6766
6767 auto RangeFromFactoring = getRangeViaFactoring(
6768 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6769 ConservativeResult =
6770 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6771 }
6772 }
6773
6774 // Now try symbolic BE count and more powerful methods.
6775 if (Opts.scalar_evolution_use_expensive_range_sharpening) {
6776 const SCEV *SymbolicMaxBECount =
6778 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6779 getTypeSizeInBits(MaxBEScev->getType()) <= BitWidth &&
6780 AddRec->hasNoSelfWrap()) {
6781 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6782 AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6783 ConservativeResult =
6784 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6785 }
6786 }
6787 }
6788
6789 return setRange(AddRec, SignHint, std::move(ConservativeResult));
6790 }
6791 case scUMaxExpr:
6792 case scSMaxExpr:
6793 case scUMinExpr:
6794 case scSMinExpr:
6795 case scSequentialUMinExpr: {
6797 switch (S->getSCEVType()) {
6798 case scUMaxExpr:
6799 ID = Intrinsic::umax;
6800 break;
6801 case scSMaxExpr:
6802 ID = Intrinsic::smax;
6803 break;
6804 case scUMinExpr:
6806 ID = Intrinsic::umin;
6807 break;
6808 case scSMinExpr:
6809 ID = Intrinsic::smin;
6810 break;
6811 default:
6812 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6813 }
6814
6815 const auto *NAry = cast<SCEVNAryExpr>(S);
6816 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
6817 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6818 X = X.intrinsic(
6819 ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
6820 return setRange(S, SignHint,
6821 ConservativeResult.intersectWith(X, RangeType));
6822 }
6823 case scUnknown: {
6824 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6825 Value *V = U->getValue();
6826
6827 // Check if the IR explicitly contains !range metadata.
6828 std::optional<ConstantRange> MDRange = GetRangeFromMetadata(V);
6829 if (MDRange)
6830 ConservativeResult =
6831 ConservativeResult.intersectWith(*MDRange, RangeType);
6832
6833 // Use facts about recurrences in the underlying IR. Note that add
6834 // recurrences are AddRecExprs and thus don't hit this path. This
6835 // primarily handles shift recurrences.
6836 auto CR = getRangeForUnknownRecurrence(U);
6837 ConservativeResult = ConservativeResult.intersectWith(CR);
6838
6839 // See if ValueTracking can give us a useful range.
6840 const DataLayout &DL = getDataLayout();
6841 KnownBits Known = computeKnownBits(V, DL, &AC, nullptr, &DT);
6842 if (Known.getBitWidth() != BitWidth)
6843 Known = Known.zextOrTrunc(BitWidth);
6844
6845 // ValueTracking may be able to compute a tighter result for the number of
6846 // sign bits than for the value of those sign bits.
6847 unsigned NS = ComputeNumSignBits(V, DL, &AC, nullptr, &DT);
6848 if (U->getType()->isPointerTy()) {
6849 // NS counts the sign bits of the whole pointer; drop those above the
6850 // index bits.
6851 unsigned PtrIdxDiff =
6852 DL.getPointerTypeSizeInBits(U->getType()) - BitWidth;
6853 NS = NS > PtrIdxDiff ? NS - PtrIdxDiff : 1;
6854 }
6855
6856 if (NS > 1) {
6857 // If we know any of the sign bits, we know all of the sign bits.
6858 if (!Known.Zero.getHiBits(NS).isZero())
6859 Known.Zero.setHighBits(NS);
6860 if (!Known.One.getHiBits(NS).isZero())
6861 Known.One.setHighBits(NS);
6862 }
6863
6864 if (Known.getMinValue() != Known.getMaxValue() + 1)
6865 ConservativeResult = ConservativeResult.intersectWith(
6866 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6867 RangeType);
6868 if (NS > 1)
6869 ConservativeResult = ConservativeResult.intersectWith(
6870 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6871 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6872 RangeType);
6873
6874 if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
6875 // Strengthen the range if the underlying IR value is a
6876 // global/alloca/heap allocation using the size of the object.
6877 bool CanBeNull;
6878 uint64_t DerefBytes = V->getPointerDereferenceableBytes(
6879 DL, CanBeNull, /*CanBeFreed=*/nullptr);
6880 if (DerefBytes > 1 && isUIntN(BitWidth, DerefBytes)) {
6881 // The highest address the object can start is DerefBytes bytes before
6882 // the end (unsigned max value). If this value is not a multiple of the
6883 // alignment, the last possible start value is the next lowest multiple
6884 // of the alignment. Note: The computations below cannot overflow,
6885 // because if they would there's no possible start address for the
6886 // object.
6887 APInt MaxVal =
6888 APInt::getMaxValue(BitWidth) - APInt(BitWidth, DerefBytes);
6889 uint64_t Align = U->getValue()->getPointerAlignment(DL).value();
6890 uint64_t Rem = MaxVal.urem(Align);
6891 MaxVal -= APInt(BitWidth, Rem);
6892 APInt MinVal = APInt::getZero(BitWidth);
6893 if (llvm::isKnownNonZero(V, DL))
6894 MinVal = Align;
6895 ConservativeResult = ConservativeResult.intersectWith(
6896 ConstantRange::getNonEmpty(MinVal, MaxVal + 1), RangeType);
6897 }
6898 }
6899
6900 // A range of Phi is a subset of union of all ranges of its input.
6901 if (PHINode *Phi = dyn_cast<PHINode>(V)) {
6902 // SCEVExpander sometimes creates SCEVUnknowns that are secretly
6903 // AddRecs; return the range for the corresponding AddRec.
6904 if (auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V)))
6905 return getRangeRef(AR, SignHint, Depth + 1);
6906
6907 // Make sure that we do not run over cycled Phis.
6908 if (RangeRefPHIAllowedOperands(DT, Phi)) {
6909 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6910
6911 for (const auto &Op : Phi->operands()) {
6912 auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
6913 RangeFromOps = RangeFromOps.unionWith(OpRange);
6914 // No point to continue if we already have a full set.
6915 if (RangeFromOps.isFullSet())
6916 break;
6917 }
6918 ConservativeResult =
6919 ConservativeResult.intersectWith(RangeFromOps, RangeType);
6920 }
6921 }
6922
6923 // vscale can't be equal to zero
6924 if (const auto *II = dyn_cast<IntrinsicInst>(V))
6925 if (II->getIntrinsicID() == Intrinsic::vscale) {
6926 ConstantRange Disallowed = APInt::getZero(BitWidth);
6927 ConservativeResult = ConservativeResult.difference(Disallowed);
6928 }
6929
6930 return setRange(U, SignHint, std::move(ConservativeResult));
6931 }
6932 case scCouldNotCompute:
6933 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6934 }
6935
6936 return setRange(S, SignHint, std::move(ConservativeResult));
6937}
6938
6939// Given a StartRange, Step and MaxBECount for an expression compute a range of
6940// values that the expression can take. Initially, the expression has a value
6941// from StartRange and then is changed by Step up to MaxBECount times. Signed
6942// argument defines if we treat Step as signed or unsigned. The second return
6943// value indicates that no wrapping occurred.
6944static std::pair<ConstantRange, bool>
6946 const APInt &MaxBECount, bool Signed) {
6947 unsigned BitWidth = Step.getBitWidth();
6948 assert(BitWidth == StartRange.getBitWidth() &&
6949 BitWidth == MaxBECount.getBitWidth() && "mismatched bit widths");
6950 // If either Step or MaxBECount is 0, then the expression won't change, and we
6951 // just need to return the initial range.
6952 if (Step == 0 || MaxBECount == 0)
6953 return {StartRange, true};
6954
6955 // If we don't know anything about the initial value (i.e. StartRange is
6956 // FullRange), then we don't know anything about the final range either.
6957 // Return FullRange.
6958 if (StartRange.isFullSet())
6959 return {ConstantRange::getFull(BitWidth), false};
6960
6961 // If Step is signed and negative, then we use its absolute value, but we also
6962 // note that we're moving in the opposite direction.
6963 bool Descending = Signed && Step.isNegative();
6964
6965 if (Signed)
6966 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
6967 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
6968 // This equations hold true due to the well-defined wrap-around behavior of
6969 // APInt.
6970 Step = Step.abs();
6971
6972 // Check if Offset is more than full span of BitWidth. If it is, the
6973 // expression is guaranteed to overflow.
6974 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
6975 return {ConstantRange::getFull(BitWidth), false};
6976
6977 // Offset is by how much the expression can change. Checks above guarantee no
6978 // overflow here.
6979 APInt Offset = Step * MaxBECount;
6980
6981 // Minimum value of the final range will match the minimal value of StartRange
6982 // if the expression is increasing and will be decreased by Offset otherwise.
6983 // Maximum value of the final range will match the maximal value of StartRange
6984 // if the expression is decreasing and will be increased by Offset otherwise.
6985 APInt StartLower = StartRange.getLower();
6986 APInt StartUpper = StartRange.getUpper() - 1;
6987 bool Overflow;
6988 APInt MovedBoundary;
6989 if (Signed) {
6990 // This does not use sadd_ov, as we want to check overflow for a signed
6991 // start with an unsigned offset.
6992 if (Descending) {
6993 MovedBoundary = StartLower - std::move(Offset);
6994 Overflow = MovedBoundary.sgt(StartLower) || StartRange.isSignWrappedSet();
6995 } else {
6996 MovedBoundary = StartUpper + std::move(Offset);
6997 Overflow = MovedBoundary.slt(StartUpper) || StartRange.isSignWrappedSet();
6998 }
6999 } else {
7000 MovedBoundary = StartUpper.uadd_ov(std::move(Offset), Overflow);
7001 Overflow |= StartRange.isWrappedSet();
7002 }
7003
7004 // It's possible that the new minimum/maximum value will fall into the initial
7005 // range (due to wrap around). This means that the expression can take any
7006 // value in this bitwidth, and we have to return full range.
7007 if (StartRange.contains(MovedBoundary))
7008 return {ConstantRange::getFull(BitWidth), false};
7009
7010 APInt NewLower =
7011 Descending ? std::move(MovedBoundary) : std::move(StartLower);
7012 APInt NewUpper =
7013 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
7014 NewUpper += 1;
7015
7016 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
7017 return {ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)),
7018 !Overflow};
7019}
7020
7021std::pair<ConstantRange, SCEVFlags>
7022ScalarEvolution::getRangeForAffineAR(const SCEV *Start, const SCEV *Step,
7023 const APInt &MaxBECount) {
7024 assert(getTypeSizeInBits(Start->getType()) ==
7025 getTypeSizeInBits(Step->getType()) &&
7026 getTypeSizeInBits(Start->getType()) == MaxBECount.getBitWidth() &&
7027 "mismatched bit widths");
7028
7029 // First, consider step signed.
7030 ConstantRange StartSRange = getSignedRange(Start);
7031 ConstantRange StepSRange = getSignedRange(Step);
7032
7033 // If Step can be both positive and negative, we need to find ranges for the
7034 // maximum absolute step values in both directions and union them.
7035 auto [SR, NSW] = getRangeForAffineARHelper(
7036 StepSRange.getSignedMin(), StartSRange, MaxBECount, /*Signed=*/true);
7037 // A singleton step has identical signed bounds, so the second computation
7038 // would produce the same range and no-wrap result.
7039 if (!StepSRange.isSingleElement()) {
7040 auto [SRMax, NSWMax] = getRangeForAffineARHelper(
7041 StepSRange.getSignedMax(), StartSRange, MaxBECount, /*Signed=*/true);
7042 SR = SR.unionWith(SRMax);
7043 NSW &= NSWMax;
7044 }
7045
7046 // Next, consider step unsigned.
7047 auto [UR, NUW] = getRangeForAffineARHelper(
7048 getUnsignedRangeMax(Step), getUnsignedRange(Start), MaxBECount,
7049 /*Signed=*/false);
7050
7052 if (NUW)
7054 if (NSW)
7056
7057 // Finally, intersect signed and unsigned ranges.
7058 return {SR.intersectWith(UR, ConstantRange::Smallest), Flags};
7059}
7060
7061ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
7062 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
7063 ScalarEvolution::RangeSignHint SignHint) {
7064 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
7065 assert(AddRec->hasNoSelfWrap() &&
7066 "This only works for non-self-wrapping AddRecs!");
7067 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
7068 const SCEV *Step = AddRec->getStepRecurrence(*this);
7069 // Only deal with constant step to save compile time.
7070 if (!isa<SCEVConstant>(Step))
7071 return ConstantRange::getFull(BitWidth);
7072 // Let's make sure that we can prove that we do not self-wrap during
7073 // MaxBECount iterations. We need this because MaxBECount is a maximum
7074 // iteration count estimate, and we might infer nw from some exit for which we
7075 // do not know max exit count (or any other side reasoning).
7076 // TODO: Turn into assert at some point.
7077 if (getTypeSizeInBits(MaxBECount->getType()) >
7078 getTypeSizeInBits(AddRec->getType()))
7079 return ConstantRange::getFull(BitWidth);
7080 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
7081 const SCEV *RangeWidth = getMinusOne(AddRec->getType());
7082 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
7083 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
7084 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
7085 MaxItersWithoutWrap))
7086 return ConstantRange::getFull(BitWidth);
7087
7088 ICmpInst::Predicate LEPred =
7090 ICmpInst::Predicate GEPred =
7092 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7093
7094 // We know that there is no self-wrap. Let's take Start and End values and
7095 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7096 // the iteration. They either lie inside the range [Min(Start, End),
7097 // Max(Start, End)] or outside it:
7098 //
7099 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
7100 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
7101 //
7102 // No self wrap flag guarantees that the intermediate values cannot be BOTH
7103 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7104 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7105 // Start <= End and step is positive, or Start >= End and step is negative.
7106 const SCEV *Start = applyLoopGuards(AddRec->getStart(), AddRec->getLoop());
7107 ConstantRange StartRange = getRangeRef(Start, SignHint);
7108 ConstantRange EndRange = getRangeRef(End, SignHint);
7109 ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7110 // If they already cover full iteration space, we will know nothing useful
7111 // even if we prove what we want to prove.
7112 if (RangeBetween.isFullSet())
7113 return RangeBetween;
7114 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7115 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7116 : RangeBetween.isWrappedSet();
7117 if (IsWrappedSet)
7118 return ConstantRange::getFull(BitWidth);
7119
7120 if (isKnownPositive(Step) &&
7121 isKnownPredicateViaConstantRanges(LEPred, Start, End))
7122 return RangeBetween;
7123 if (isKnownNegative(Step) &&
7124 isKnownPredicateViaConstantRanges(GEPred, Start, End))
7125 return RangeBetween;
7126 return ConstantRange::getFull(BitWidth);
7127}
7128
7129ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7130 const SCEV *Step,
7131 const APInt &MaxBECount) {
7132 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7133 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7134
7135 unsigned BitWidth = MaxBECount.getBitWidth();
7136 assert(getTypeSizeInBits(Start->getType()) == BitWidth &&
7137 getTypeSizeInBits(Step->getType()) == BitWidth &&
7138 "mismatched bit widths");
7139
7140 struct SelectPattern {
7141 Value *Condition = nullptr;
7142 APInt TrueValue;
7143 APInt FalseValue;
7144
7145 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7146 const SCEV *S) {
7147 std::optional<unsigned> CastOp;
7148 APInt Offset(BitWidth, 0);
7149
7151 "Should be!");
7152
7153 // Peel off a constant offset. In the future we could consider being
7154 // smarter here and handle {Start+Step,+,Step} too.
7155 const APInt *Off;
7156 if (match(S, m_scev_Add(m_scev_APInt(Off), m_SCEV(S))))
7157 Offset = *Off;
7158
7159 // Peel off a cast operation
7160 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7161 CastOp = SCast->getSCEVType();
7162 S = SCast->getOperand();
7163 }
7164
7165 using namespace llvm::PatternMatch;
7166
7167 auto *SU = dyn_cast<SCEVUnknown>(S);
7168 const APInt *TrueVal, *FalseVal;
7169 if (!SU ||
7170 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7171 m_APInt(FalseVal)))) {
7172 Condition = nullptr;
7173 return;
7174 }
7175
7176 TrueValue = *TrueVal;
7177 FalseValue = *FalseVal;
7178
7179 // Re-apply the cast we peeled off earlier
7180 if (CastOp)
7181 switch (*CastOp) {
7182 default:
7183 llvm_unreachable("Unknown SCEV cast type!");
7184
7185 case scTruncate:
7186 TrueValue = TrueValue.trunc(BitWidth);
7187 FalseValue = FalseValue.trunc(BitWidth);
7188 break;
7189 case scZeroExtend:
7190 TrueValue = TrueValue.zext(BitWidth);
7191 FalseValue = FalseValue.zext(BitWidth);
7192 break;
7193 case scSignExtend:
7194 TrueValue = TrueValue.sext(BitWidth);
7195 FalseValue = FalseValue.sext(BitWidth);
7196 break;
7197 }
7198
7199 // Re-apply the constant offset we peeled off earlier
7200 TrueValue += Offset;
7201 FalseValue += Offset;
7202 }
7203
7204 bool isRecognized() { return Condition != nullptr; }
7205 };
7206
7207 SelectPattern StartPattern(*this, BitWidth, Start);
7208 if (!StartPattern.isRecognized())
7209 return ConstantRange::getFull(BitWidth);
7210
7211 SelectPattern StepPattern(*this, BitWidth, Step);
7212 if (!StepPattern.isRecognized())
7213 return ConstantRange::getFull(BitWidth);
7214
7215 if (StartPattern.Condition != StepPattern.Condition) {
7216 // We don't handle this case today; but we could, by considering four
7217 // possibilities below instead of two. I'm not sure if there are cases where
7218 // that will help over what getRange already does, though.
7219 return ConstantRange::getFull(BitWidth);
7220 }
7221
7222 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7223 // construct arbitrary general SCEV expressions here. This function is called
7224 // from deep in the call stack, and calling getSCEV (on a sext instruction,
7225 // say) can end up caching a suboptimal value.
7226
7227 // FIXME: without the explicit `this` receiver below, MSVC errors out with
7228 // C2352 and C2512 (otherwise it isn't needed).
7229
7230 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7231 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7232 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7233 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7234
7235 ConstantRange TrueRange =
7236 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount).first;
7237 ConstantRange FalseRange =
7238 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount).first;
7239
7240 return TrueRange.unionWith(FalseRange);
7241}
7242
7243SCEVFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7244 if (isa<ConstantExpr>(V))
7245 return SCEV::FlagNone;
7246 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7247
7248 // Return early if there are no flags to propagate to the SCEV.
7250 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(BinOp);
7251 PDI && PDI->isDisjoint()) {
7253 } else {
7254 if (BinOp->hasNoUnsignedWrap())
7256 if (BinOp->hasNoSignedWrap())
7258 }
7259 if (Flags == SCEV::FlagNone)
7260 return SCEV::FlagNone;
7261
7262 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagNone;
7263}
7264
7265const Instruction *
7266ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7267 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7268 return &*AddRec->getLoop()->getHeader()->begin();
7269 if (auto *U = dyn_cast<SCEVUnknown>(S))
7270 if (auto *I = dyn_cast<Instruction>(U->getValue()))
7271 return I;
7272 return nullptr;
7273}
7274
7275const Instruction *ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops,
7276 bool &Precise) {
7277 Precise = true;
7278 // Do a bounded search of the def relation of the requested SCEVs.
7279 SmallPtrSet<const SCEV *, 16> Visited;
7280 SmallVector<SCEVUse> Worklist;
7281 auto pushOp = [&](const SCEV *S) {
7282 if (!Visited.insert(S).second)
7283 return;
7284 // Threshold of 30 here is arbitrary.
7285 if (Visited.size() > 30) {
7286 Precise = false;
7287 return;
7288 }
7289 Worklist.push_back(S);
7290 };
7291
7292 for (SCEVUse S : Ops)
7293 pushOp(S);
7294
7295 const Instruction *Bound = nullptr;
7296 while (!Worklist.empty()) {
7297 SCEVUse S = Worklist.pop_back_val();
7298 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7299 if (!Bound || DT.dominates(Bound, DefI))
7300 Bound = DefI;
7301 } else {
7302 for (SCEVUse Op : S->operands())
7303 pushOp(Op);
7304 }
7305 }
7306 return Bound ? Bound : &*F.getEntryBlock().begin();
7307}
7308
7309const Instruction *
7310ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops) {
7311 bool Discard;
7312 return getDefiningScopeBound(Ops, Discard);
7313}
7314
7315bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7316 const Instruction *B) {
7317 if (A->getParent() == B->getParent() &&
7319 B->getIterator()))
7320 return true;
7321
7322 auto *BLoop = LI.getLoopFor(B->getParent());
7323 if (BLoop && BLoop->getHeader() == B->getParent() &&
7324 BLoop->getLoopPreheader() == A->getParent() &&
7326 A->getParent()->end()) &&
7327 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7328 B->getIterator()))
7329 return true;
7330 return false;
7331}
7332
7334 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ true);
7335 visitAll(Op, PC);
7336 return PC.MaybePoison.empty();
7337}
7338
7340 return !SCEVExprContains(Op, [this](const SCEV *S) {
7341 const SCEV *Op1;
7342 bool M = match(S, m_scev_UDiv(m_SCEV(), m_SCEV(Op1)));
7343 // The UDiv may be UB if the divisor is poison or zero. Unless the divisor
7344 // is a non-zero constant, we have to assume the UDiv may be UB.
7345 return M && (!isKnownNonZero(Op1) || !isGuaranteedNotToBePoison(Op1));
7346 });
7347}
7348
7349bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7350 // Only proceed if we can prove that I does not yield poison.
7352 return false;
7353
7354 // At this point we know that if I is executed, then it does not wrap
7355 // according to at least one of NSW or NUW. If I is not executed, then we do
7356 // not know if the calculation that I represents would wrap. Multiple
7357 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7358 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7359 // derived from other instructions that map to the same SCEV. We cannot make
7360 // that guarantee for cases where I is not executed. So we need to find a
7361 // upper bound on the defining scope for the SCEV, and prove that I is
7362 // executed every time we enter that scope. When the bounding scope is a
7363 // loop (the common case), this is equivalent to proving I executes on every
7364 // iteration of that loop.
7365 SmallVector<SCEVUse> SCEVOps;
7366 for (const Use &Op : I->operands()) {
7367 // I could be an extractvalue from a call to an overflow intrinsic.
7368 // TODO: We can do better here in some cases.
7369 if (isSCEVable(Op->getType()))
7370 SCEVOps.push_back(getSCEV(Op));
7371 }
7372 auto *DefI = getDefiningScopeBound(SCEVOps);
7373 return isGuaranteedToTransferExecutionTo(DefI, I);
7374}
7375
7376bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7377 // If we know that \c I can never be poison period, then that's enough.
7378 if (isSCEVExprNeverPoison(I))
7379 return true;
7380
7381 // If the loop only has one exit, then we know that, if the loop is entered,
7382 // any instruction dominating that exit will be executed. If any such
7383 // instruction would result in UB, the addrec cannot be poison.
7384 //
7385 // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7386 // also handles uses outside the loop header (they just need to dominate the
7387 // single exit).
7388
7389 auto *ExitingBB = L->getExitingBlock();
7390 if (!ExitingBB || !loopHasNoAbnormalExits(L))
7391 return false;
7392
7393 SmallPtrSet<const Value *, 16> KnownPoison;
7395
7396 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
7397 // things that are known to be poison under that assumption go on the
7398 // Worklist.
7399 KnownPoison.insert(I);
7400 Worklist.push_back(I);
7401
7402 while (!Worklist.empty()) {
7403 const Instruction *Poison = Worklist.pop_back_val();
7404
7405 for (const Use &U : Poison->uses()) {
7406 const Instruction *PoisonUser = cast<Instruction>(U.getUser());
7407 if (mustTriggerUB(PoisonUser, KnownPoison) &&
7408 DT.dominates(PoisonUser->getParent(), ExitingBB))
7409 return true;
7410
7411 if (propagatesPoison(U) && L->contains(PoisonUser))
7412 if (KnownPoison.insert(PoisonUser).second)
7413 Worklist.push_back(PoisonUser);
7414 }
7415 }
7416
7417 return false;
7418}
7419
7420ScalarEvolution::LoopProperties
7421ScalarEvolution::getLoopProperties(const Loop *L) {
7422 using LoopProperties = ScalarEvolution::LoopProperties;
7423
7424 auto Itr = LoopPropertiesCache.find(L);
7425 if (Itr == LoopPropertiesCache.end()) {
7426 auto HasSideEffects = [](Instruction *I) {
7427 if (auto *SI = dyn_cast<StoreInst>(I))
7428 return !SI->isSimple();
7429
7430 if (I->mayThrow())
7431 return true;
7432
7433 // Non-volatile memset / memcpy do not count as side-effect for forward
7434 // progress.
7435 if (isa<MemIntrinsic>(I) && !I->isVolatile())
7436 return false;
7437
7438 // Droppable intrinsics only model a memory write; they are not progress.
7439 if (I->isDroppable())
7440 return false;
7441
7442 return I->mayWriteToMemory();
7443 };
7444
7445 LoopProperties LP = {/* HasNoAbnormalExits */ true,
7446 /*HasNoSideEffects*/ true};
7447
7448 for (auto *BB : L->getBlocks())
7449 for (auto &I : *BB) {
7451 LP.HasNoAbnormalExits = false;
7452 if (HasSideEffects(&I))
7453 LP.HasNoSideEffects = false;
7454 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7455 break; // We're already as pessimistic as we can get.
7456 }
7457
7458 auto InsertPair = LoopPropertiesCache.insert({L, LP});
7459 assert(InsertPair.second && "We just checked!");
7460 Itr = InsertPair.first;
7461 }
7462
7463 return Itr->second;
7464}
7465
7467 // A mustprogress loop without side effects must be finite.
7468 // TODO: The check used here is very conservative. It's only *specific*
7469 // side effects which are well defined in infinite loops.
7470 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7471}
7472
7473const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7474 // Worklist item with a Value and a bool indicating whether all operands have
7475 // been visited already.
7478
7479 Stack.emplace_back(V, false);
7480 while (!Stack.empty()) {
7481 auto E = Stack.back();
7482 Value *CurV = E.getPointer();
7483
7484 if (getExistingSCEV(CurV)) {
7485 Stack.pop_back();
7486 continue;
7487 }
7488
7490 const SCEV *CreatedSCEV = nullptr;
7491 // If all operands have been visited already, create the SCEV.
7492 if (E.getInt()) {
7493 CreatedSCEV = createSCEV(CurV);
7494 } else {
7495 // Otherwise get the operands we need to create SCEV's for before creating
7496 // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7497 // just use it.
7498 CreatedSCEV = getOperandsToCreate(CurV, Ops);
7499 }
7500
7501 if (CreatedSCEV) {
7502 insertValueToMap(CurV, CreatedSCEV);
7503 Stack.pop_back();
7504 } else {
7505 Stack.back().setInt(true);
7506 // Queue its operands which need to be constructed.
7507 for (Value *Op : Ops)
7508 Stack.emplace_back(Op, false);
7509 }
7510 }
7511
7512 return getExistingSCEV(V);
7513}
7514
7515const SCEV *
7516ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7517 if (!isSCEVable(V->getType()))
7518 return getUnknown(V);
7519
7520 if (Instruction *I = dyn_cast<Instruction>(V)) {
7521 // Don't attempt to analyze instructions in blocks that aren't
7522 // reachable. Such instructions don't matter, and they aren't required
7523 // to obey basic rules for definitions dominating uses which this
7524 // analysis depends on.
7525 if (!DT.isReachableFromEntry(I->getParent()))
7526 return getUnknown(PoisonValue::get(V->getType()));
7527 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7528 return getConstant(CI);
7529 else if (isa<GlobalAlias>(V))
7530 return getUnknown(V);
7531 else if (!isa<ConstantExpr>(V))
7532 return getUnknown(V);
7533
7535 if (auto BO = MatchBinaryOp(U, DT)) {
7536 bool IsConstArg = isa<ConstantInt>(BO->RHS);
7537 switch (BO->Opcode) {
7538 case Instruction::Add:
7539 case Instruction::Mul: {
7540 // For additions and multiplications, traverse add/mul chains for which we
7541 // can potentially create a single SCEV, to reduce the number of
7542 // get{Add,Mul}Expr calls.
7543 do {
7544 if (BO->Op) {
7545 if (BO->Op != V && getExistingSCEV(BO->Op)) {
7546 Ops.push_back(BO->Op);
7547 break;
7548 }
7549 }
7550 Ops.push_back(BO->RHS);
7551 auto NewBO = MatchBinaryOp(BO->LHS, DT);
7552 if (!NewBO ||
7553 (BO->Opcode == Instruction::Add &&
7554 (NewBO->Opcode != Instruction::Add &&
7555 NewBO->Opcode != Instruction::Sub)) ||
7556 (BO->Opcode == Instruction::Mul &&
7557 NewBO->Opcode != Instruction::Mul)) {
7558 Ops.push_back(BO->LHS);
7559 break;
7560 }
7561 // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7562 // requires a SCEV for the LHS.
7563 if (BO->Op && (BO->IsNSW || BO->IsNUW)) {
7564 auto *I = dyn_cast<Instruction>(BO->Op);
7565 if (I && programUndefinedIfPoison(I)) {
7566 Ops.push_back(BO->LHS);
7567 break;
7568 }
7569 }
7570 BO = NewBO;
7571 } while (true);
7572 return nullptr;
7573 }
7574 case Instruction::Sub:
7575 case Instruction::UDiv:
7576 case Instruction::URem:
7577 break;
7578 case Instruction::AShr:
7579 case Instruction::Shl:
7580 case Instruction::Xor:
7581 if (!IsConstArg)
7582 return nullptr;
7583 break;
7584 case Instruction::And:
7585 case Instruction::Or:
7586 if (!IsConstArg && !BO->LHS->getType()->isIntegerTy(1))
7587 return nullptr;
7588 break;
7589 case Instruction::LShr:
7590 return getUnknown(V);
7591 default:
7592 llvm_unreachable("Unhandled binop");
7593 break;
7594 }
7595
7596 Ops.push_back(BO->LHS);
7597 Ops.push_back(BO->RHS);
7598 return nullptr;
7599 }
7600
7601 switch (U->getOpcode()) {
7602 case Instruction::Trunc:
7603 case Instruction::ZExt:
7604 case Instruction::SExt:
7605 case Instruction::PtrToAddr:
7606 case Instruction::PtrToInt:
7607 Ops.push_back(U->getOperand(0));
7608 return nullptr;
7609
7610 case Instruction::BitCast:
7611 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
7612 Ops.push_back(U->getOperand(0));
7613 return nullptr;
7614 }
7615 return getUnknown(V);
7616
7617 case Instruction::SDiv:
7618 case Instruction::SRem:
7619 Ops.push_back(U->getOperand(0));
7620 Ops.push_back(U->getOperand(1));
7621 return nullptr;
7622
7623 case Instruction::GetElementPtr:
7624 assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7625 "GEP source element type must be sized");
7626 llvm::append_range(Ops, U->operands());
7627 return nullptr;
7628
7629 case Instruction::IntToPtr:
7630 return getUnknown(V);
7631
7632 case Instruction::PHI:
7633 // getNodeForPHI has four ways to turn a PHI into a SCEV; retrieve the
7634 // relevant nodes for each of them.
7635 //
7636 // The first is just to call simplifyInstruction, and get something back
7637 // that isn't a PHI.
7638 if (Value *V = simplifyInstruction(
7639 cast<PHINode>(U),
7640 {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
7641 /*UseInstrInfo=*/true, /*CanUseUndef=*/false})) {
7642 assert(V);
7643 Ops.push_back(V);
7644 return nullptr;
7645 }
7646 // The second is createNodeForPHIWithIdenticalOperands: this looks for
7647 // operands which all perform the same operation, but haven't been
7648 // CSE'ed for whatever reason.
7649 if (BinaryOperator *BO = getCommonInstForPHI(cast<PHINode>(U))) {
7650 assert(BO);
7651 Ops.push_back(BO);
7652 return nullptr;
7653 }
7654 // The third is createNodeFromSelectLikePHI; this takes a PHI which
7655 // is equivalent to a select, and analyzes it like a select.
7656 {
7657 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
7659 assert(Cond);
7660 assert(LHS);
7661 assert(RHS);
7662 if (auto *CondICmp = dyn_cast<ICmpInst>(Cond)) {
7663 Ops.push_back(CondICmp->getOperand(0));
7664 Ops.push_back(CondICmp->getOperand(1));
7665 }
7666 Ops.push_back(Cond);
7667 Ops.push_back(LHS);
7668 Ops.push_back(RHS);
7669 return nullptr;
7670 }
7671 }
7672 // The fourth way is createAddRecFromPHI. It's complicated to handle here,
7673 // so just construct it recursively.
7674 //
7675 // In addition to getNodeForPHI, also construct nodes which might be needed
7676 // by getRangeRef.
7678 for (Value *V : cast<PHINode>(U)->operands())
7679 Ops.push_back(V);
7680 return nullptr;
7681 }
7682 return nullptr;
7683
7684 case Instruction::Select: {
7685 // Check if U is a select that can be simplified to a SCEVUnknown.
7686 auto CanSimplifyToUnknown = [this, U]() {
7687 if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
7688 return false;
7689
7690 auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
7691 if (!ICI)
7692 return false;
7693 Value *LHS = ICI->getOperand(0);
7694 Value *RHS = ICI->getOperand(1);
7695 if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7696 ICI->getPredicate() == CmpInst::ICMP_NE) {
7698 return true;
7699 } else if (getTypeSizeInBits(LHS->getType()) >
7700 getTypeSizeInBits(U->getType()))
7701 return true;
7702 return false;
7703 };
7704 if (CanSimplifyToUnknown())
7705 return getUnknown(U);
7706
7707 llvm::append_range(Ops, U->operands());
7708 return nullptr;
7709 break;
7710 }
7711 case Instruction::Call:
7712 case Instruction::Invoke:
7713 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7714 Ops.push_back(RV);
7715 return nullptr;
7716 }
7717
7718 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7719 switch (II->getIntrinsicID()) {
7720 case Intrinsic::abs:
7721 Ops.push_back(II->getArgOperand(0));
7722 return nullptr;
7723 case Intrinsic::umax:
7724 case Intrinsic::umin:
7725 case Intrinsic::smax:
7726 case Intrinsic::smin:
7727 case Intrinsic::usub_sat:
7728 case Intrinsic::uadd_sat:
7729 Ops.push_back(II->getArgOperand(0));
7730 Ops.push_back(II->getArgOperand(1));
7731 return nullptr;
7732 case Intrinsic::start_loop_iterations:
7733 case Intrinsic::annotation:
7734 case Intrinsic::ptr_annotation:
7735 Ops.push_back(II->getArgOperand(0));
7736 return nullptr;
7737 default:
7738 break;
7739 }
7740 }
7741 break;
7742 }
7743
7744 return nullptr;
7745}
7746
7747const SCEV *ScalarEvolution::createSCEV(Value *V) {
7748 if (!isSCEVable(V->getType()))
7749 return getUnknown(V);
7750
7751 if (Instruction *I = dyn_cast<Instruction>(V)) {
7752 // Don't attempt to analyze instructions in blocks that aren't
7753 // reachable. Such instructions don't matter, and they aren't required
7754 // to obey basic rules for definitions dominating uses which this
7755 // analysis depends on.
7756 if (!DT.isReachableFromEntry(I->getParent()))
7757 return getUnknown(PoisonValue::get(V->getType()));
7758 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7759 return getConstant(CI);
7760 else if (isa<GlobalAlias>(V))
7761 return getUnknown(V);
7762 else if (!isa<ConstantExpr>(V))
7763 return getUnknown(V);
7764
7765 const SCEV *LHS;
7766 const SCEV *RHS;
7767
7769 if (auto BO = MatchBinaryOp(U, DT)) {
7770 switch (BO->Opcode) {
7771 case Instruction::Add: {
7772 // The simple thing to do would be to just call getSCEV on both operands
7773 // and call getAddExpr with the result. However if we're looking at a
7774 // bunch of things all added together, this can be quite inefficient,
7775 // because it leads to N-1 getAddExpr calls for N ultimate operands.
7776 // Instead, gather up all the operands and make a single getAddExpr call.
7777 // LLVM IR canonical form means we need only traverse the left operands.
7779 do {
7780 if (BO->Op) {
7781 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7782 AddOps.push_back(OpSCEV);
7783 break;
7784 }
7785
7786 // If a NUW or NSW flag can be applied to the SCEV for this
7787 // addition, then compute the SCEV for this addition by itself
7788 // with a separate call to getAddExpr. We need to do that
7789 // instead of pushing the operands of the addition onto AddOps,
7790 // since the flags are only known to apply to this particular
7791 // addition - they may not apply to other additions that can be
7792 // formed with operands from AddOps.
7793 const SCEV *RHS = getSCEV(BO->RHS);
7794 SCEVFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7795 if (Flags != SCEV::FlagNone) {
7796 const SCEV *LHS = getSCEV(BO->LHS);
7797 if (BO->Opcode == Instruction::Sub)
7798 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7799 else
7800 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7801 break;
7802 }
7803 }
7804
7805 if (BO->Opcode == Instruction::Sub)
7806 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7807 else
7808 AddOps.push_back(getSCEV(BO->RHS));
7809
7810 auto NewBO = MatchBinaryOp(BO->LHS, DT);
7811 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7812 NewBO->Opcode != Instruction::Sub)) {
7813 AddOps.push_back(getSCEV(BO->LHS));
7814 break;
7815 }
7816 BO = NewBO;
7817 } while (true);
7818
7819 return getAddExpr(AddOps);
7820 }
7821
7822 case Instruction::Mul: {
7824 do {
7825 if (BO->Op) {
7826 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7827 MulOps.push_back(OpSCEV);
7828 break;
7829 }
7830
7831 SCEVFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7832 if (Flags != SCEV::FlagNone) {
7833 LHS = getSCEV(BO->LHS);
7834 RHS = getSCEV(BO->RHS);
7835 MulOps.push_back(getMulExpr(LHS, RHS, Flags));
7836 break;
7837 }
7838 }
7839
7840 MulOps.push_back(getSCEV(BO->RHS));
7841 auto NewBO = MatchBinaryOp(BO->LHS, DT);
7842 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7843 MulOps.push_back(getSCEV(BO->LHS));
7844 break;
7845 }
7846 BO = NewBO;
7847 } while (true);
7848
7849 return getMulExpr(MulOps);
7850 }
7851 case Instruction::UDiv:
7852 LHS = getSCEV(BO->LHS);
7853 RHS = getSCEV(BO->RHS);
7854 return getUDivExpr(LHS, RHS);
7855 case Instruction::URem:
7856 LHS = getSCEV(BO->LHS);
7857 RHS = getSCEV(BO->RHS);
7858 return getURemExpr(LHS, RHS);
7859 case Instruction::Sub: {
7861 if (BO->Op)
7862 Flags = getNoWrapFlagsFromUB(BO->Op);
7863
7864 // Try to use ptrtoaddr for subtracts with at least one ptrtoint
7865 // operand. While we don't model ptrtoint directly in SCEV, the
7866 // difference between two pointer addresses is well-defined.
7867 Value *PtrLHS = nullptr, *PtrRHS = nullptr;
7868 bool HasPtrLHS = match(BO->LHS, m_PtrToInt(m_Value(PtrLHS)));
7869 bool HasPtrRHS = match(BO->RHS, m_PtrToInt(m_Value(PtrRHS)));
7870 if (HasPtrLHS || HasPtrRHS) {
7871 // Convert a ptrtoint operand (OrigOp) to ptrtoaddr of its pointer
7872 // PtrOp. When only one side is ptrtoint (BothPtr is false), skip
7873 // SCEVUnknown pointers since wrapping them in ptrtoaddr adds no
7874 // useful structure.
7875 auto GetOp = [&](bool HasPtr, Value *PtrOp, Value *OrigOp,
7876 bool BothPtr) -> const SCEV * {
7877 if (!HasPtr)
7878 return getSCEV(OrigOp);
7879 const SCEV *PtrSCEV = getSCEV(PtrOp);
7880 if (BothPtr || !isa<SCEVUnknown>(PtrSCEV)) {
7881 const SCEV *Addr = getPtrToAddrExpr(PtrSCEV);
7882 if (!isa<SCEVCouldNotCompute>(Addr) &&
7883 getTypeSizeInBits(OrigOp->getType()) <=
7884 getTypeSizeInBits(Addr->getType()))
7885 return getTruncateOrNoop(Addr, OrigOp->getType());
7886 }
7887 return getSCEV(OrigOp);
7888 };
7889 const SCEV *L = GetOp(HasPtrLHS, PtrLHS, BO->LHS, HasPtrRHS);
7890 const SCEV *R = GetOp(HasPtrRHS, PtrRHS, BO->RHS, HasPtrLHS);
7891 return getMinusSCEV(L, R, Flags);
7892 }
7893
7894 LHS = getSCEV(BO->LHS);
7895 RHS = getSCEV(BO->RHS);
7896 return getMinusSCEV(LHS, RHS, Flags);
7897 }
7898 case Instruction::And:
7899 // For an expression like x&255 that merely masks off the high bits,
7900 // use zext(trunc(x)) as the SCEV expression.
7901 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7902 if (CI->isZero())
7903 return getSCEV(BO->RHS);
7904 if (CI->isMinusOne())
7905 return getSCEV(BO->LHS);
7906 const APInt &A = CI->getValue();
7907
7908 // Instcombine's ShrinkDemandedConstant may strip bits out of
7909 // constants, obscuring what would otherwise be a low-bits mask.
7910 // Use computeKnownBits to compute what ShrinkDemandedConstant
7911 // knew about to reconstruct a low-bits mask value.
7912 unsigned LZ = A.countl_zero();
7913 unsigned TZ = A.countr_zero();
7914 unsigned BitWidth = A.getBitWidth();
7915 KnownBits Known(BitWidth);
7916 computeKnownBits(BO->LHS, Known, getDataLayout(), &AC, nullptr, &DT);
7917
7918 APInt EffectiveMask =
7919 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
7920 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
7921 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
7922 const SCEV *LHS = getSCEV(BO->LHS);
7923 const SCEV *ShiftedLHS = nullptr;
7924 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
7925 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
7926 // For an expression like (x * 8) & 8, simplify the multiply.
7927 unsigned MulZeros = OpC->getAPInt().countr_zero();
7928 unsigned GCD = std::min(MulZeros, TZ);
7929 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
7931 MulOps.push_back(getConstant(OpC->getAPInt().ashr(GCD)));
7932 append_range(MulOps, LHSMul->operands().drop_front());
7933 const SCEV *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
7934 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
7935 }
7936 }
7937 if (!ShiftedLHS)
7938 ShiftedLHS = getUDivExpr(LHS, MulCount);
7939 return getMulExpr(
7941 getTruncateExpr(ShiftedLHS,
7942 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
7943 BO->LHS->getType()),
7944 MulCount);
7945 }
7946 }
7947 // Binary `and` is a bit-wise `umin`.
7948 if (BO->LHS->getType()->isIntegerTy(1)) {
7949 LHS = getSCEV(BO->LHS);
7950 RHS = getSCEV(BO->RHS);
7951 return getUMinExpr(LHS, RHS);
7952 }
7953 break;
7954
7955 case Instruction::Or:
7956 // Binary `or` is a bit-wise `umax`.
7957 if (BO->LHS->getType()->isIntegerTy(1)) {
7958 LHS = getSCEV(BO->LHS);
7959 RHS = getSCEV(BO->RHS);
7960 return getUMaxExpr(LHS, RHS);
7961 }
7962 break;
7963
7964 case Instruction::Xor:
7965 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7966 // If the RHS of xor is -1, then this is a not operation.
7967 if (CI->isMinusOne())
7968 return getNotSCEV(getSCEV(BO->LHS));
7969
7970 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
7971 // This is a variant of the check for xor with -1, and it handles
7972 // the case where instcombine has trimmed non-demanded bits out
7973 // of an xor with -1.
7974 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
7975 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
7976 if (LBO->getOpcode() == Instruction::And &&
7977 LCI->getValue() == CI->getValue())
7978 if (const SCEVZeroExtendExpr *Z =
7980 Type *UTy = BO->LHS->getType();
7981 const SCEV *Z0 = Z->getOperand();
7982 Type *Z0Ty = Z0->getType();
7983 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
7984
7985 // If C is a low-bits mask, the zero extend is serving to
7986 // mask off the high bits. Complement the operand and
7987 // re-apply the zext.
7988 if (CI->getValue().isMask(Z0TySize))
7989 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
7990
7991 // If C is a single bit, it may be in the sign-bit position
7992 // before the zero-extend. In this case, represent the xor
7993 // using an add, which is equivalent, and re-apply the zext.
7994 APInt Trunc = CI->getValue().trunc(Z0TySize);
7995 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
7996 Trunc.isSignMask())
7997 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
7998 UTy);
7999 }
8000 }
8001 break;
8002
8003 case Instruction::Shl:
8004 // Turn shift left of a constant amount into a multiply.
8005 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
8006 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
8007
8008 // If the shift count is not less than the bitwidth, the result of
8009 // the shift is undefined. Don't try to analyze it, because the
8010 // resolution chosen here may differ from the resolution chosen in
8011 // other parts of the compiler.
8012 if (SA->getValue().uge(BitWidth))
8013 break;
8014
8015 // We can safely preserve the nuw flag in all cases. It's also safe to
8016 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
8017 // requires special handling. It can be preserved as long as we're not
8018 // left shifting by bitwidth - 1.
8019 auto Flags = SCEV::FlagNone;
8020 if (BO->Op) {
8021 auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
8022 if (any(MulFlags & SCEV::FlagNSW) &&
8023 (any(MulFlags & SCEV::FlagNUW) ||
8024 SA->getValue().ult(BitWidth - 1)))
8026 if (any(MulFlags & SCEV::FlagNUW))
8028 }
8029
8030 ConstantInt *X = ConstantInt::get(
8031 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
8032 return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
8033 }
8034 break;
8035
8036 case Instruction::AShr:
8037 // AShr X, C, where C is a constant.
8038 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
8039 if (!CI)
8040 break;
8041
8042 Type *OuterTy = BO->LHS->getType();
8044 // If the shift count is not less than the bitwidth, the result of
8045 // the shift is undefined. Don't try to analyze it, because the
8046 // resolution chosen here may differ from the resolution chosen in
8047 // other parts of the compiler.
8048 if (CI->getValue().uge(BitWidth))
8049 break;
8050
8051 if (CI->isZero())
8052 return getSCEV(BO->LHS); // shift by zero --> noop
8053
8054 uint64_t AShrAmt = CI->getZExtValue();
8055 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
8056
8057 Operator *L = dyn_cast<Operator>(BO->LHS);
8058 const SCEV *AddTruncateExpr = nullptr;
8059 ConstantInt *ShlAmtCI = nullptr;
8060 const SCEV *AddConstant = nullptr;
8061
8062 if (L && L->getOpcode() == Instruction::Add) {
8063 // X = Shl A, n
8064 // Y = Add X, c
8065 // Z = AShr Y, m
8066 // n, c and m are constants.
8067
8068 Operator *LShift = dyn_cast<Operator>(L->getOperand(0));
8069 ConstantInt *AddOperandCI = dyn_cast<ConstantInt>(L->getOperand(1));
8070 if (LShift && LShift->getOpcode() == Instruction::Shl) {
8071 if (AddOperandCI) {
8072 const SCEV *ShlOp0SCEV = getSCEV(LShift->getOperand(0));
8073 ShlAmtCI = dyn_cast<ConstantInt>(LShift->getOperand(1));
8074 // since we truncate to TruncTy, the AddConstant should be of the
8075 // same type, so create a new Constant with type same as TruncTy.
8076 // Also, the Add constant should be shifted right by AShr amount.
8077 APInt AddOperand = AddOperandCI->getValue().ashr(AShrAmt);
8078 AddConstant = getConstant(AddOperand.trunc(BitWidth - AShrAmt));
8079 // we model the expression as sext(add(trunc(A), c << n)), since the
8080 // sext(trunc) part is already handled below, we create a
8081 // AddExpr(TruncExp) which will be used later.
8082 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8083 }
8084 }
8085 } else if (L && L->getOpcode() == Instruction::Shl) {
8086 // X = Shl A, n
8087 // Y = AShr X, m
8088 // Both n and m are constant.
8089
8090 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
8091 ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
8092 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8093 }
8094
8095 if (AddTruncateExpr && ShlAmtCI) {
8096 // We can merge the two given cases into a single SCEV statement,
8097 // incase n = m, the mul expression will be 2^0, so it gets resolved to
8098 // a simpler case. The following code handles the two cases:
8099 //
8100 // 1) For a two-shift sext-inreg, i.e. n = m,
8101 // use sext(trunc(x)) as the SCEV expression.
8102 //
8103 // 2) When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
8104 // expression. We already checked that ShlAmt < BitWidth, so
8105 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
8106 // ShlAmt - AShrAmt < Amt.
8107 const APInt &ShlAmt = ShlAmtCI->getValue();
8108 if (ShlAmt.ult(BitWidth) && ShlAmt.uge(AShrAmt)) {
8109 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
8110 ShlAmtCI->getZExtValue() - AShrAmt);
8111 const SCEV *CompositeExpr =
8112 getMulExpr(AddTruncateExpr, getConstant(Mul));
8113 if (L->getOpcode() != Instruction::Shl)
8114 CompositeExpr = getAddExpr(CompositeExpr, AddConstant);
8115
8116 return getSignExtendExpr(CompositeExpr, OuterTy);
8117 }
8118 }
8119 break;
8120 }
8121 }
8122
8123 switch (U->getOpcode()) {
8124 case Instruction::Trunc:
8125 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
8126
8127 case Instruction::ZExt:
8128 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8129
8130 case Instruction::SExt:
8131 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
8132 // The NSW flag of a subtract does not always survive the conversion to
8133 // A + (-1)*B. By pushing sign extension onto its operands we are much
8134 // more likely to preserve NSW and allow later AddRec optimisations.
8135 //
8136 // NOTE: This is effectively duplicating this logic from getSignExtend:
8137 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
8138 // but by that point the NSW information has potentially been lost.
8139 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
8140 Type *Ty = U->getType();
8141 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
8142 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
8143 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
8144 }
8145 }
8146 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8147
8148 case Instruction::BitCast:
8149 // BitCasts are no-op casts so we just eliminate the cast.
8150 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
8151 return getSCEV(U->getOperand(0));
8152 break;
8153
8154 case Instruction::PtrToAddr: {
8155 const SCEV *IntOp = getPtrToAddrExpr(getSCEV(U->getOperand(0)));
8156 if (isa<SCEVCouldNotCompute>(IntOp))
8157 return getUnknown(V);
8158 return IntOp;
8159 }
8160
8161 case Instruction::PtrToInt:
8162 // SCEV only models ptrtoaddr.
8163 return getUnknown(V);
8164
8165 case Instruction::IntToPtr:
8166 // Just don't deal with inttoptr casts.
8167 return getUnknown(V);
8168
8169 case Instruction::SDiv:
8170 // If both operands are non-negative, this is just an udiv.
8171 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8172 isKnownNonNegative(getSCEV(U->getOperand(1))))
8173 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8174 break;
8175
8176 case Instruction::SRem:
8177 // If both operands are non-negative, this is just an urem.
8178 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8179 isKnownNonNegative(getSCEV(U->getOperand(1))))
8180 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8181 break;
8182
8183 case Instruction::GetElementPtr:
8184 return createNodeForGEP(cast<GEPOperator>(U));
8185
8186 case Instruction::PHI:
8187 return createNodeForPHI(cast<PHINode>(U));
8188
8189 case Instruction::Select:
8190 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
8191 U->getOperand(2));
8192
8193 case Instruction::Call:
8194 case Instruction::Invoke:
8195 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
8196 return getSCEV(RV);
8197
8198 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
8199 switch (II->getIntrinsicID()) {
8200 case Intrinsic::abs:
8201 return getAbsExpr(
8202 getSCEV(II->getArgOperand(0)),
8203 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
8204 case Intrinsic::umax:
8205 LHS = getSCEV(II->getArgOperand(0));
8206 RHS = getSCEV(II->getArgOperand(1));
8207 return getUMaxExpr(LHS, RHS);
8208 case Intrinsic::umin:
8209 LHS = getSCEV(II->getArgOperand(0));
8210 RHS = getSCEV(II->getArgOperand(1));
8211 return getUMinExpr(LHS, RHS);
8212 case Intrinsic::smax:
8213 LHS = getSCEV(II->getArgOperand(0));
8214 RHS = getSCEV(II->getArgOperand(1));
8215 return getSMaxExpr(LHS, RHS);
8216 case Intrinsic::smin:
8217 LHS = getSCEV(II->getArgOperand(0));
8218 RHS = getSCEV(II->getArgOperand(1));
8219 return getSMinExpr(LHS, RHS);
8220 case Intrinsic::usub_sat: {
8221 const SCEV *X = getSCEV(II->getArgOperand(0));
8222 const SCEV *Y = getSCEV(II->getArgOperand(1));
8223 const SCEV *ClampedY = getUMinExpr(X, Y);
8224 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
8225 }
8226 case Intrinsic::uadd_sat: {
8227 const SCEV *X = getSCEV(II->getArgOperand(0));
8228 const SCEV *Y = getSCEV(II->getArgOperand(1));
8229 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
8230 return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
8231 }
8232 case Intrinsic::start_loop_iterations:
8233 case Intrinsic::annotation:
8234 case Intrinsic::ptr_annotation:
8235 // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8236 // just eqivalent to the first operand for SCEV purposes.
8237 return getSCEV(II->getArgOperand(0));
8238 case Intrinsic::vscale:
8239 return getVScale(II->getType());
8240 default:
8241 break;
8242 }
8243 }
8244 break;
8245 }
8246
8247 return getUnknown(V);
8248}
8249
8250//===----------------------------------------------------------------------===//
8251// Iteration Count Computation Code
8252//
8253
8255 if (isa<SCEVCouldNotCompute>(ExitCount))
8256 return getCouldNotCompute();
8257
8258 auto *ExitCountType = ExitCount->getType();
8259 assert(ExitCountType->isIntegerTy());
8260 auto *EvalTy = Type::getIntNTy(ExitCountType->getContext(),
8261 1 + ExitCountType->getScalarSizeInBits());
8262 return getTripCountFromExitCount(ExitCount, EvalTy, nullptr);
8263}
8264
8266 Type *EvalTy,
8267 const Loop *L) {
8268 if (isa<SCEVCouldNotCompute>(ExitCount))
8269 return getCouldNotCompute();
8270
8271 unsigned ExitCountSize = getTypeSizeInBits(ExitCount->getType());
8272 unsigned EvalSize = EvalTy->getPrimitiveSizeInBits();
8273
8274 auto CanAddOneWithoutOverflow = [&]() {
8275 ConstantRange ExitCountRange =
8276 getRangeRef(ExitCount, RangeSignHint::HINT_RANGE_UNSIGNED);
8277 if (!ExitCountRange.contains(APInt::getMaxValue(ExitCountSize)))
8278 return true;
8279
8280 return L && isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
8281 getMinusOne(ExitCount->getType()));
8282 };
8283
8284 // If we need to zero extend the backedge count, check if we can add one to
8285 // it prior to zero extending without overflow. Provided this is safe, it
8286 // allows better simplification of the +1.
8287 if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8288 return getZeroExtendExpr(
8289 getAddExpr(ExitCount, getOne(ExitCount->getType())), EvalTy);
8290
8291 // Get the total trip count from the count by adding 1. This may wrap.
8292 return getAddExpr(getTruncateOrZeroExtend(ExitCount, EvalTy), getOne(EvalTy));
8293}
8294
8295static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8296 if (!ExitCount)
8297 return 0;
8298
8299 ConstantInt *ExitConst = ExitCount->getValue();
8300
8301 // Guard against huge trip counts.
8302 if (ExitConst->getValue().getActiveBits() > 32)
8303 return 0;
8304
8305 // In case of integer overflow, this returns 0, which is correct.
8306 return ((unsigned)ExitConst->getZExtValue()) + 1;
8307}
8308
8310 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
8311 return getConstantTripCount(ExitCount);
8312}
8313
8314unsigned
8316 const BasicBlock *ExitingBlock) {
8317 assert(ExitingBlock && "Must pass a non-null exiting block!");
8318 assert(L->isLoopExiting(ExitingBlock) &&
8319 "Exiting block must actually branch out of the loop!");
8320 const SCEVConstant *ExitCount =
8321 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
8322 return getConstantTripCount(ExitCount);
8323}
8324
8326 const Loop *L, SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8327
8328 const auto *MaxExitCount =
8329 Predicates ? getPredicatedConstantMaxBackedgeTakenCount(L, *Predicates)
8331 return getConstantTripCount(dyn_cast<SCEVConstant>(MaxExitCount));
8332}
8333
8335 SmallVector<BasicBlock *, 8> ExitingBlocks;
8336 L->getExitingBlocks(ExitingBlocks);
8337
8338 // An exit with an uncomputable exit count makes the result 1.
8339 if (ExitingBlocks.empty() ||
8340 any_of(ExitingBlocks, [this, L](BasicBlock *ExitingBB) {
8341 return isa<SCEVCouldNotCompute>(getExitCount(L, ExitingBB));
8342 }))
8343 return 1;
8344
8345 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
8346 unsigned Res = 0;
8347 for (BasicBlock *ExitingBB : ExitingBlocks)
8348 Res = std::gcd(
8349 Res, getSmallConstantTripMultiple(getExitCount(L, ExitingBB), Guards));
8350 return Res;
8351}
8352
8353unsigned ScalarEvolution::getSmallConstantTripMultiple(const SCEV *ExitCount,
8354 LoopGuards &Guards) {
8355 assert(!isa<SCEVCouldNotCompute>(ExitCount) && "Must be computable!");
8356
8357 // Get the trip count
8358 const SCEV *TCExpr =
8359 getTripCountFromExitCount(applyLoopGuards(ExitCount, Guards));
8360
8361 APInt Multiple = getNonZeroConstantMultiple(TCExpr);
8362 // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8363 // the greatest power of 2 divisor less than 2^32.
8364 return Multiple.getActiveBits() > 32
8365 ? 1U << std::min(31U, Multiple.countTrailingZeros())
8366 : (unsigned)Multiple.getZExtValue();
8367}
8368
8370 const SCEV *ExitCount) {
8371 if (isa<SCEVCouldNotCompute>(ExitCount))
8372 return 1;
8373
8374 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
8375 return getSmallConstantTripMultiple(ExitCount, Guards);
8376}
8377
8378/// Returns the largest constant divisor of the trip count of this loop as a
8379/// normal unsigned value, if possible. This means that the actual trip count is
8380/// always a multiple of the returned value (don't forget the trip count could
8381/// very well be zero as well!).
8382///
8383/// Returns 1 if the trip count is unknown or not guaranteed to be the
8384/// multiple of a constant (which is also the case if the trip count is simply
8385/// constant, use getSmallConstantTripCount for that case), Will also return 1
8386/// if the trip count is very large (>= 2^32).
8387///
8388/// As explained in the comments for getSmallConstantTripCount, this assumes
8389/// that control exits the loop via ExitingBlock.
8390unsigned
8392 const BasicBlock *ExitingBlock) {
8393 assert(ExitingBlock && "Must pass a non-null exiting block!");
8394 assert(L->isLoopExiting(ExitingBlock) &&
8395 "Exiting block must actually branch out of the loop!");
8396 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8397 return getSmallConstantTripMultiple(L, ExitCount);
8398}
8399
8401 const BasicBlock *ExitingBlock,
8402 ExitCountKind Kind) {
8403 switch (Kind) {
8404 case Exact:
8405 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8406 case SymbolicMaximum:
8407 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8408 case ConstantMaximum:
8409 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8410 };
8411 llvm_unreachable("Invalid ExitCountKind!");
8412}
8413
8415 const Loop *L, const BasicBlock *ExitingBlock,
8417 switch (Kind) {
8418 case Exact:
8419 return getPredicatedBackedgeTakenInfo(L).getExact(ExitingBlock, this,
8420 Predicates);
8421 case SymbolicMaximum:
8422 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this,
8423 Predicates);
8424 case ConstantMaximum:
8425 return getPredicatedBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this,
8426 Predicates);
8427 };
8428 llvm_unreachable("Invalid ExitCountKind!");
8429}
8430
8433 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8434}
8435
8437 ExitCountKind Kind) {
8438 switch (Kind) {
8439 case Exact:
8440 return getBackedgeTakenInfo(L).getExact(L, this);
8441 case ConstantMaximum:
8442 return getBackedgeTakenInfo(L).getConstantMax(this);
8443 case SymbolicMaximum:
8444 return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8445 };
8446 llvm_unreachable("Invalid ExitCountKind!");
8447}
8448
8451 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(L, this, &Preds);
8452}
8453
8456 return getPredicatedBackedgeTakenInfo(L).getConstantMax(this, &Preds);
8457}
8458
8460 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8461}
8462
8463/// Push PHI nodes in the header of the given loop onto the given Worklist.
8464static void PushLoopPHIs(const Loop *L,
8467 BasicBlock *Header = L->getHeader();
8468
8469 // Push all Loop-header PHIs onto the Worklist stack.
8470 for (PHINode &PN : Header->phis())
8471 if (Visited.insert(&PN).second)
8472 Worklist.push_back(&PN);
8473}
8474
8475ScalarEvolution::BackedgeTakenInfo &
8476ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8477 auto &BTI = getBackedgeTakenInfo(L);
8478 if (BTI.hasFullInfo())
8479 return BTI;
8480
8481 auto Pair = PredicatedBackedgeTakenCounts.try_emplace(L);
8482
8483 if (!Pair.second)
8484 return Pair.first->second;
8485
8486 BackedgeTakenInfo Result =
8487 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8488
8489 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8490}
8491
8492ScalarEvolution::BackedgeTakenInfo &
8493ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8494 // Initially insert an invalid entry for this loop. If the insertion
8495 // succeeds, proceed to actually compute a backedge-taken count and
8496 // update the value. The temporary CouldNotCompute value tells SCEV
8497 // code elsewhere that it shouldn't attempt to request a new
8498 // backedge-taken count, which could result in infinite recursion.
8499 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8500 BackedgeTakenCounts.try_emplace(L);
8501 if (!Pair.second)
8502 return Pair.first->second;
8503
8504 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8505 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8506 // must be cleared in this scope.
8507 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8508
8509 // Now that we know more about the trip count for this loop, forget any
8510 // existing SCEV values for PHI nodes in this loop since they are only
8511 // conservative estimates made without the benefit of trip count
8512 // information. This invalidation is not necessary for correctness, and is
8513 // only done to produce more precise results.
8514 if (Result.hasAnyInfo()) {
8515 // Invalidate any expression using an addrec in this loop.
8516 SmallVector<SCEVUse, 8> ToForget;
8517 auto LoopUsersIt = LoopUsers.find(L);
8518 if (LoopUsersIt != LoopUsers.end())
8519 append_range(ToForget, LoopUsersIt->second);
8520 forgetMemoizedResults(ToForget);
8521
8522 // Invalidate constant-evolved loop header phis.
8523 for (PHINode &PN : L->getHeader()->phis())
8524 ConstantEvolutionLoopExitValue.erase(&PN);
8525 }
8526
8527 // Re-lookup the insert position, since the call to
8528 // computeBackedgeTakenCount above could result in a
8529 // recusive call to getBackedgeTakenInfo (on a different
8530 // loop), which would invalidate the iterator computed
8531 // earlier.
8532 return BackedgeTakenCounts.find(L)->second = std::move(Result);
8533}
8534
8536 // This method is intended to forget all info about loops. It should
8537 // invalidate caches as if the following happened:
8538 // - The trip counts of all loops have changed arbitrarily
8539 // - Every llvm::Value has been updated in place to produce a different
8540 // result.
8541 BackedgeTakenCounts.clear();
8542 PredicatedBackedgeTakenCounts.clear();
8543 BECountUsers.clear();
8544 LoopPropertiesCache.clear();
8545 ConstantEvolutionLoopExitValue.clear();
8546 ValueExprMap.clear();
8547 ValuesAtScopes.clear();
8548 ValuesAtScopesUsers.clear();
8549 LoopDispositions.clear();
8550 BlockDispositions.clear();
8551 UnsignedRanges.clear();
8552 SignedRanges.clear();
8553 ExprValueMap.clear();
8554 HasRecMap.clear();
8555 ConstantMultipleCache.clear();
8556 PredicatedSCEVRewrites.clear();
8557 FoldCache.clear();
8558 FoldCacheUser.clear();
8559}
8560void ScalarEvolution::visitAndClearUsers(
8563 SmallVectorImpl<SCEVUse> &ToForget) {
8564 // Nothing can be invalidated if no value has a SCEV yet.
8565 if (ValueExprMap.empty()) {
8566 Worklist.clear();
8567 return;
8568 }
8569 while (!Worklist.empty()) {
8570 Instruction *I = Worklist.pop_back_val();
8571 if (!isSCEVable(I->getType()) && !isa<WithOverflowInst>(I))
8572 continue;
8573
8575 ValueExprMap.find_as(static_cast<Value *>(I));
8576 if (It != ValueExprMap.end()) {
8577 ToForget.push_back(It->second);
8578 eraseValueFromMap(It->first);
8579 if (PHINode *PN = dyn_cast<PHINode>(I))
8580 ConstantEvolutionLoopExitValue.erase(PN);
8581 }
8582
8583 PushDefUseChildren(I, Worklist, Visited);
8584 }
8585}
8586
8588 SmallVector<const Loop *, 16> LoopWorklist(1, L);
8591 SmallVector<SCEVUse, 16> ToForget;
8592
8593 // Iterate over all the loops and sub-loops to drop SCEV information.
8594 while (!LoopWorklist.empty()) {
8595 auto *CurrL = LoopWorklist.pop_back_val();
8596
8597 // Drop any stored trip count value.
8598 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8599 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8600
8601 // Drop information about predicated SCEV rewrites for this loop.
8602 PredicatedSCEVRewrites.remove_if(
8603 [&](const auto &Entry) { return Entry.first.second == CurrL; });
8604
8605 auto LoopUsersItr = LoopUsers.find(CurrL);
8606 if (LoopUsersItr != LoopUsers.end())
8607 llvm::append_range(ToForget, LoopUsersItr->second);
8608
8609 // Drop information about expressions based on loop-header PHIs.
8610 PushLoopPHIs(CurrL, Worklist, Visited);
8611 visitAndClearUsers(Worklist, Visited, ToForget);
8612
8613 LoopPropertiesCache.erase(CurrL);
8614 // Forget all contained loops too, to avoid dangling entries in the
8615 // ValuesAtScopes map.
8616 LoopWorklist.append(CurrL->begin(), CurrL->end());
8617 }
8618 forgetMemoizedResults(ToForget);
8619}
8620
8622 forgetLoop(L->getOutermostLoop());
8623}
8624
8627 if (!I) return;
8628
8629 // Drop information about expressions based on loop-header PHIs.
8632 SmallVector<SCEVUse, 8> ToForget;
8633 Worklist.push_back(I);
8634 Visited.insert(I);
8635 visitAndClearUsers(Worklist, Visited, ToForget);
8636
8637 forgetMemoizedResults(ToForget);
8638}
8639
8643 SmallVector<SCEVUse, 8> ToForget;
8644 for (Value *V : Values)
8645 if (auto *I = dyn_cast<Instruction>(V))
8646 if (Visited.insert(I).second)
8647 Worklist.push_back(I);
8648 visitAndClearUsers(Worklist, Visited, ToForget);
8649
8650 forgetMemoizedResults(ToForget);
8651}
8652
8654 // If SCEV looked through a trivial LCSSA phi node, we might have SCEV's
8655 // directly using a SCEVUnknown/SCEVAddRec defined in the loop. After an
8656 // extra predecessor is added, this is no longer valid. Find all Unknowns and
8657 // AddRecs defined in the loop and invalidate any SCEV's making use of them.
8658 auto InvalidateValue = [&](Value *Val) {
8659 if (!isSCEVable(Val->getType()))
8660 return;
8661 if (const SCEV *S = getExistingSCEV(Val)) {
8662 struct InvalidationRootCollector {
8663 Loop *L;
8665
8666 InvalidationRootCollector(Loop *L) : L(L) {}
8667
8668 bool follow(const SCEV *S) {
8669 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
8670 if (auto *I = dyn_cast<Instruction>(SU->getValue()))
8671 if (L->contains(I))
8672 Roots.push_back(S);
8673 } else if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
8674 if (L->contains(AddRec->getLoop()))
8675 Roots.push_back(S);
8676 }
8677 return true;
8678 }
8679 bool isDone() const { return false; }
8680 };
8681
8682 InvalidationRootCollector C(L);
8683 visitAll(S, C);
8684 forgetMemoizedResults(C.Roots);
8685 }
8686 };
8687
8688 InvalidateValue(V);
8689
8690 // If V has a non-SCEV-able type (e.g. {i64, i1} from a with.overflow
8691 // intrinsic), its users (e.g. extractvalue) may have stale SCEV
8692 // expressions referencing loop-internal values.
8693 if (!isSCEVable(V->getType()) &&
8694 any_of(V->incoming_values(), IsaPred<WithOverflowInst>))
8695 for (User *U : V->users())
8696 InvalidateValue(U);
8697 // Also perform the normal invalidation.
8698 forgetValue(V);
8699}
8700
8701void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8702
8704 // Unless a specific value is passed to invalidation, completely clear both
8705 // caches.
8706 if (!V) {
8707 BlockDispositions.clear();
8708 LoopDispositions.clear();
8709 return;
8710 }
8711
8712 if (!isSCEVable(V->getType()))
8713 return;
8714
8715 const SCEV *S = getExistingSCEV(V);
8716 if (!S)
8717 return;
8718
8719 // Invalidate the block and loop dispositions cached for S. Dispositions of
8720 // S's users may change if S's disposition changes (i.e. a user may change to
8721 // loop-invariant, if S changes to loop invariant), so also invalidate
8722 // dispositions of S's users recursively.
8723 SmallVector<SCEVUse, 8> Worklist = {S};
8725 while (!Worklist.empty()) {
8726 const SCEV *Curr = Worklist.pop_back_val();
8727 bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8728 bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8729 if (!LoopDispoRemoved && !BlockDispoRemoved)
8730 continue;
8731 auto Users = SCEVUsers.find(Curr);
8732 if (Users != SCEVUsers.end())
8733 for (const auto *User : Users->second)
8734 if (Seen.insert(User).second)
8735 Worklist.push_back(User);
8736 }
8737}
8738
8739/// Get the exact loop backedge taken count considering all loop exits. A
8740/// computable result can only be returned for loops with all exiting blocks
8741/// dominating the latch. howFarToZero assumes that the limit of each loop test
8742/// is never skipped. This is a valid assumption as long as the loop exits via
8743/// that test. For precise results, it is the caller's responsibility to specify
8744/// the relevant loop exiting block using getExact(ExitingBlock, SE).
8745const SCEV *ScalarEvolution::BackedgeTakenInfo::getExact(
8746 const Loop *L, ScalarEvolution *SE,
8748 // If any exits were not computable, the loop is not computable.
8749 if (!isComplete() || ExitNotTaken.empty())
8750 return SE->getCouldNotCompute();
8751
8752 const BasicBlock *Latch = L->getLoopLatch();
8753 // All exiting blocks we have collected must dominate the only backedge.
8754 if (!Latch)
8755 return SE->getCouldNotCompute();
8756
8757 // All exiting blocks we have gathered dominate loop's latch, so exact trip
8758 // count is simply a minimum out of all these calculated exit counts.
8760 for (const auto &ENT : ExitNotTaken) {
8761 const SCEV *BECount = ENT.ExactNotTaken;
8762 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8763 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8764 "We should only have known counts for exiting blocks that dominate "
8765 "latch!");
8766
8767 Ops.push_back(BECount);
8768
8769 if (Preds)
8770 append_range(*Preds, ENT.Predicates);
8771
8772 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8773 "Predicate should be always true!");
8774 }
8775
8776 // If an earlier exit exits on the first iteration (exit count zero), then
8777 // a later poison exit count should not propagate into the result. This are
8778 // exactly the semantics provided by umin_seq.
8779 return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8780}
8781
8782const ScalarEvolution::ExitNotTakenInfo *
8783ScalarEvolution::BackedgeTakenInfo::getExitNotTaken(
8784 const BasicBlock *ExitingBlock,
8785 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8786 for (const auto &ENT : ExitNotTaken)
8787 if (ENT.ExitingBlock == ExitingBlock) {
8788 if (ENT.hasAlwaysTruePredicate())
8789 return &ENT;
8790 else if (Predicates) {
8791 append_range(*Predicates, ENT.Predicates);
8792 return &ENT;
8793 }
8794 }
8795
8796 return nullptr;
8797}
8798
8799/// getConstantMax - Get the constant max backedge taken count for the loop.
8800const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8801 ScalarEvolution *SE,
8802 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8803 if (!getConstantMax())
8804 return SE->getCouldNotCompute();
8805
8806 for (const auto &ENT : ExitNotTaken)
8807 if (!ENT.hasAlwaysTruePredicate()) {
8808 if (!Predicates)
8809 return SE->getCouldNotCompute();
8810 append_range(*Predicates, ENT.Predicates);
8811 }
8812
8813 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8814 isa<SCEVConstant>(getConstantMax())) &&
8815 "No point in having a non-constant max backedge taken count!");
8816 return getConstantMax();
8817}
8818
8819const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8820 const Loop *L, ScalarEvolution *SE,
8821 SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8822 if (!SymbolicMax) {
8823 // Form an expression for the maximum exit count possible for this loop. We
8824 // merge the max and exact information to approximate a version of
8825 // getConstantMaxBackedgeTakenCount which isn't restricted to just
8826 // constants.
8827 SmallVector<SCEVUse, 4> ExitCounts;
8828
8829 for (const auto &ENT : ExitNotTaken) {
8830 const SCEV *ExitCount = ENT.SymbolicMaxNotTaken;
8831 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
8832 assert(SE->DT.dominates(ENT.ExitingBlock, L->getLoopLatch()) &&
8833 "We should only have known counts for exiting blocks that "
8834 "dominate latch!");
8835 ExitCounts.push_back(ExitCount);
8836 if (Predicates)
8837 append_range(*Predicates, ENT.Predicates);
8838
8839 assert((Predicates || ENT.hasAlwaysTruePredicate()) &&
8840 "Predicate should be always true!");
8841 }
8842 }
8843 if (ExitCounts.empty())
8844 SymbolicMax = SE->getCouldNotCompute();
8845 else
8846 SymbolicMax =
8847 SE->getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
8848 }
8849 return SymbolicMax;
8850}
8851
8852bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8853 ScalarEvolution *SE) const {
8854 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8855 return !ENT.hasAlwaysTruePredicate();
8856 };
8857 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8858}
8859
8862
8864 const SCEV *E, const SCEV *ConstantMaxNotTaken,
8865 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8869 // If we prove the max count is zero, so is the symbolic bound. This happens
8870 // in practice due to differences in a) how context sensitive we've chosen
8871 // to be and b) how we reason about bounds implied by UB.
8872 if (ConstantMaxNotTaken->isZero()) {
8873 this->ExactNotTaken = E = ConstantMaxNotTaken;
8874 this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
8875 }
8876
8879 "Exact is not allowed to be less precise than Constant Max");
8882 "Exact is not allowed to be less precise than Symbolic Max");
8885 "Symbolic Max is not allowed to be less precise than Constant Max");
8888 "No point in having a non-constant max backedge taken count!");
8890 for (const auto PredList : PredLists)
8891 for (const auto *P : PredList) {
8892 if (SeenPreds.contains(P))
8893 continue;
8894 assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!");
8895 SeenPreds.insert(P);
8896 Predicates.push_back(P);
8897 }
8898 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8899 "Backedge count should be int");
8901 !ConstantMaxNotTaken->getType()->isPointerTy()) &&
8902 "Max backedge count should be int");
8903}
8904
8912
8913/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8914/// computable exit into a persistent ExitNotTakenInfo array.
8915ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8917 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
8918 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8919 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8920
8921 ExitNotTaken.reserve(ExitCounts.size());
8922 std::transform(ExitCounts.begin(), ExitCounts.end(),
8923 std::back_inserter(ExitNotTaken),
8924 [&](const EdgeExitInfo &EEI) {
8925 BasicBlock *ExitBB = EEI.first;
8926 const ExitLimit &EL = EEI.second;
8927 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
8928 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
8929 EL.Predicates);
8930 });
8931 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
8932 isa<SCEVConstant>(ConstantMax)) &&
8933 "No point in having a non-constant max backedge taken count!");
8934}
8935
8936/// Compute the number of times the backedge of the specified loop will execute.
8937ScalarEvolution::BackedgeTakenInfo
8938ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
8939 bool AllowPredicates) {
8940 SmallVector<BasicBlock *, 8> ExitingBlocks;
8941 L->getExitingBlocks(ExitingBlocks);
8942
8943 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8944
8946 bool CouldComputeBECount = true;
8947 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
8948 const SCEV *MustExitMaxBECount = nullptr;
8949 const SCEV *MayExitMaxBECount = nullptr;
8950 bool MustExitMaxOrZero = false;
8951 bool IsOnlyExit = ExitingBlocks.size() == 1;
8952
8953 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
8954 // and compute maxBECount.
8955 // Do a union of all the predicates here.
8956 for (BasicBlock *ExitBB : ExitingBlocks) {
8957 // We canonicalize untaken exits to br (constant), ignore them so that
8958 // proving an exit untaken doesn't negatively impact our ability to reason
8959 // about the loop as whole.
8960 if (auto *BI = dyn_cast<CondBrInst>(ExitBB->getTerminator()))
8961 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
8962 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8963 if (ExitIfTrue == CI->isZero())
8964 continue;
8965 }
8966
8967 ExitLimit EL = computeExitLimit(L, ExitBB, IsOnlyExit, AllowPredicates);
8968
8969 assert((AllowPredicates || EL.Predicates.empty()) &&
8970 "Predicated exit limit when predicates are not allowed!");
8971
8972 // 1. For each exit that can be computed, add an entry to ExitCounts.
8973 // CouldComputeBECount is true only if all exits can be computed.
8974 if (EL.ExactNotTaken != getCouldNotCompute())
8975 ++NumExitCountsComputed;
8976 else
8977 // We couldn't compute an exact value for this exit, so
8978 // we won't be able to compute an exact value for the loop.
8979 CouldComputeBECount = false;
8980 // Remember exit count if either exact or symbolic is known. Because
8981 // Exact always implies symbolic, only check symbolic.
8982 if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
8983 ExitCounts.emplace_back(ExitBB, EL);
8984 else {
8985 assert(EL.ExactNotTaken == getCouldNotCompute() &&
8986 "Exact is known but symbolic isn't?");
8987 ++NumExitCountsNotComputed;
8988 }
8989
8990 // 2. Derive the loop's MaxBECount from each exit's max number of
8991 // non-exiting iterations. Partition the loop exits into two kinds:
8992 // LoopMustExits and LoopMayExits.
8993 //
8994 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
8995 // is a LoopMayExit. If any computable LoopMustExit is found, then
8996 // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
8997 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
8998 // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
8999 // any
9000 // computable EL.ConstantMaxNotTaken.
9001 if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
9002 DT.dominates(ExitBB, Latch)) {
9003 if (!MustExitMaxBECount) {
9004 MustExitMaxBECount = EL.ConstantMaxNotTaken;
9005 MustExitMaxOrZero = EL.MaxOrZero;
9006 } else {
9007 MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
9008 EL.ConstantMaxNotTaken);
9009 }
9010 } else if (MayExitMaxBECount != getCouldNotCompute()) {
9011 if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
9012 MayExitMaxBECount = EL.ConstantMaxNotTaken;
9013 else {
9014 MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
9015 EL.ConstantMaxNotTaken);
9016 }
9017 }
9018 }
9019 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
9020 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
9021 // The loop backedge will be taken the maximum or zero times if there's
9022 // a single exit that must be taken the maximum or zero times.
9023 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
9024
9025 // Remember which SCEVs are used in exit limits for invalidation purposes.
9026 // We only care about non-constant SCEVs here, so we can ignore
9027 // EL.ConstantMaxNotTaken
9028 // and MaxBECount, which must be SCEVConstant.
9029 for (const auto &Pair : ExitCounts) {
9030 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
9031 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
9032 if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
9033 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
9034 {L, AllowPredicates});
9035 }
9036 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
9037 MaxBECount, MaxOrZero);
9038}
9039
9040ScalarEvolution::ExitLimit
9041ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
9042 bool IsOnlyExit, bool AllowPredicates) {
9043 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
9044 // If our exiting block does not dominate the latch, then its connection with
9045 // loop's exit limit may be far from trivial.
9046 const BasicBlock *Latch = L->getLoopLatch();
9047 if (!Latch || !DT.dominates(ExitingBlock, Latch))
9048 return getCouldNotCompute();
9049
9050 Instruction *Term = ExitingBlock->getTerminator();
9051 if (CondBrInst *BI = dyn_cast<CondBrInst>(Term)) {
9052 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9053 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
9054 "It should have one successor in loop and one exit block!");
9055 // Proceed to the next level to examine the exit condition expression.
9056 return computeExitLimitFromCond(L, BI->getCondition(), ExitIfTrue,
9057 /*ControlsOnlyExit=*/IsOnlyExit,
9058 AllowPredicates);
9059 }
9060
9061 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
9062 // For switch, make sure that there is a single exit from the loop.
9063 BasicBlock *Exit = nullptr;
9064 for (auto *SBB : successors(ExitingBlock))
9065 if (!L->contains(SBB)) {
9066 if (Exit) // Multiple exit successors.
9067 return getCouldNotCompute();
9068 Exit = SBB;
9069 }
9070 assert(Exit && "Exiting block must have at least one exit");
9071 return computeExitLimitFromSingleExitSwitch(
9072 L, SI, Exit, /*ControlsOnlyExit=*/IsOnlyExit);
9073 }
9074
9075 return getCouldNotCompute();
9076}
9077
9079 const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9080 bool AllowPredicates) {
9081 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
9082 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
9083 ControlsOnlyExit, AllowPredicates);
9084}
9085
9086std::optional<ScalarEvolution::ExitLimit>
9087ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
9088 bool ExitIfTrue, bool ControlsOnlyExit,
9089 bool AllowPredicates) {
9090 (void)this->L;
9091 (void)this->ExitIfTrue;
9092 (void)this->AllowPredicates;
9093
9094 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9095 this->AllowPredicates == AllowPredicates &&
9096 "Variance in assumed invariant key components!");
9097 auto Itr = TripCountMap.find({ExitCond, ControlsOnlyExit});
9098 if (Itr == TripCountMap.end())
9099 return std::nullopt;
9100 return Itr->second;
9101}
9102
9103void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
9104 bool ExitIfTrue,
9105 bool ControlsOnlyExit,
9106 bool AllowPredicates,
9107 const ExitLimit &EL) {
9108 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9109 this->AllowPredicates == AllowPredicates &&
9110 "Variance in assumed invariant key components!");
9111
9112 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsOnlyExit}, EL});
9113 assert(InsertResult.second && "Expected successful insertion!");
9114 (void)InsertResult;
9115 (void)ExitIfTrue;
9116}
9117
9118ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
9119 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9120 bool ControlsOnlyExit, bool AllowPredicates) {
9121
9122 if (auto MaybeEL = Cache.find(L, ExitCond, ExitIfTrue, ControlsOnlyExit,
9123 AllowPredicates))
9124 return *MaybeEL;
9125
9126 ExitLimit EL = computeExitLimitFromCondImpl(
9127 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates);
9128 Cache.insert(L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates, EL);
9129 return EL;
9130}
9131
9132ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
9133 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9134 bool ControlsOnlyExit, bool AllowPredicates) {
9135 // Handle BinOp conditions (And, Or).
9136 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
9137 Cache, L, ExitCond, ExitIfTrue, AllowPredicates))
9138 return *LimitFromBinOp;
9139
9140 // With an icmp, it may be feasible to compute an exact backedge-taken count.
9141 // Proceed to the next level to examine the icmp.
9142 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
9143 ExitLimit EL =
9144 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsOnlyExit);
9145 if (EL.hasFullInfo() || !AllowPredicates)
9146 return EL;
9147
9148 // Try again, but use SCEV predicates this time.
9149 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue,
9150 ControlsOnlyExit,
9151 /*AllowPredicates=*/true);
9152 }
9153
9154 // Check for a constant condition. These are normally stripped out by
9155 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
9156 // preserve the CFG and is temporarily leaving constant conditions
9157 // in place.
9158 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
9159 if (ExitIfTrue == !CI->getZExtValue())
9160 // The backedge is always taken.
9161 return getCouldNotCompute();
9162 // The backedge is never taken.
9163 return getZero(CI->getType());
9164 }
9165
9166 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
9167 // with a constant step, we can form an equivalent icmp predicate and figure
9168 // out how many iterations will be taken before we exit.
9169 const WithOverflowInst *WO;
9170 const APInt *C;
9171 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
9172 match(WO->getRHS(), m_APInt(C))) {
9173 ConstantRange NWR =
9175 WO->getNoWrapKind());
9176 CmpInst::Predicate Pred;
9177 APInt NewRHSC, Offset;
9178 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
9179 if (!ExitIfTrue)
9180 Pred = ICmpInst::getInversePredicate(Pred);
9181 auto *LHS = getSCEV(WO->getLHS());
9182 if (Offset != 0)
9184 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
9185 ControlsOnlyExit, AllowPredicates);
9186 if (EL.hasAnyInfo())
9187 return EL;
9188 }
9189
9190 // If it's not an integer or pointer comparison then compute it the hard way.
9191 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9192}
9193
9194std::optional<ScalarEvolution::ExitLimit>
9195ScalarEvolution::computeExitLimitFromCondFromBinOp(ExitLimitCacheTy &Cache,
9196 const Loop *L,
9197 Value *ExitCond,
9198 bool ExitIfTrue,
9199 bool AllowPredicates) {
9200 // Check if the controlling expression for this loop is an And or Or.
9201 Value *Op0, *Op1;
9202 bool IsAnd;
9203 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
9204 IsAnd = true;
9205 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
9206 IsAnd = false;
9207 else
9208 return std::nullopt;
9209
9210 // A sub-condition of a non-trivial binop never solely controls the exit,
9211 // whether we exit always depends on both conditions.
9212 ExitLimit EL0 = computeExitLimitFromCondCached(
9213 Cache, L, Op0, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9214 ExitLimit EL1 = computeExitLimitFromCondCached(
9215 Cache, L, Op1, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9216
9217 // EitherMayExit is true in these two cases:
9218 // br (and Op0 Op1), loop, exit
9219 // br (or Op0 Op1), exit, loop
9220 bool EitherMayExit = IsAnd ^ ExitIfTrue;
9221
9222 const SCEV *BECount = getCouldNotCompute();
9223 const SCEV *ConstantMaxBECount = getCouldNotCompute();
9224 const SCEV *SymbolicMaxBECount = getCouldNotCompute();
9225 if (EitherMayExit) {
9226 bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
9227 // Both conditions must be same for the loop to continue executing.
9228 // Choose the less conservative count.
9229 if (EL0.ExactNotTaken != getCouldNotCompute() &&
9230 EL1.ExactNotTaken != getCouldNotCompute()) {
9231 BECount = getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken,
9232 UseSequentialUMin);
9233 }
9234 if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
9235 ConstantMaxBECount = EL1.ConstantMaxNotTaken;
9236 else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
9237 ConstantMaxBECount = EL0.ConstantMaxNotTaken;
9238 else
9239 ConstantMaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
9240 EL1.ConstantMaxNotTaken);
9241 if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
9242 SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
9243 else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
9244 SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
9245 else
9246 SymbolicMaxBECount = getUMinFromMismatchedTypes(
9247 EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
9248 } else {
9249 // Both conditions must be same at the same time for the loop to exit.
9250 // For now, be conservative.
9251 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
9252 BECount = EL0.ExactNotTaken;
9253 }
9254
9255 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
9256 // to be more aggressive when computing BECount than when computing
9257 // ConstantMaxBECount. In these cases it is possible for EL0.ExactNotTaken
9258 // and
9259 // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
9260 // EL1.ConstantMaxNotTaken to not.
9261 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
9262 !isa<SCEVCouldNotCompute>(BECount))
9263 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
9264 if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
9265 SymbolicMaxBECount =
9266 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
9267 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
9268 {ArrayRef(EL0.Predicates), ArrayRef(EL1.Predicates)});
9269}
9270
9271ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9272 const Loop *L, ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9273 bool AllowPredicates) {
9274 // If the condition was exit on true, convert the condition to exit on false
9275 CmpPredicate Pred;
9276 if (!ExitIfTrue)
9277 Pred = ExitCond->getCmpPredicate();
9278 else
9279 Pred = ExitCond->getInverseCmpPredicate();
9280 const ICmpInst::Predicate OriginalPred = Pred;
9281
9282 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
9283 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
9284
9285 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsOnlyExit,
9286 AllowPredicates);
9287 if (EL.hasAnyInfo())
9288 return EL;
9289
9290 auto *ExhaustiveCount =
9291 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9292
9293 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
9294 return ExhaustiveCount;
9295
9296 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
9297 ExitCond->getOperand(1), L, OriginalPred);
9298}
9299ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9300 const Loop *L, CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS,
9301 bool ControlsOnlyExit, bool AllowPredicates) {
9302
9303 // Try to evaluate any dependencies out of the loop.
9304 LHS = getSCEVAtScope(LHS, L);
9305 RHS = getSCEVAtScope(RHS, L);
9306
9307 // At this point, we would like to compute how many iterations of the
9308 // loop the predicate will return true for these inputs.
9309 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
9310 // If there is a loop-invariant, force it into the RHS.
9311 std::swap(LHS, RHS);
9313 }
9314
9315 bool ControllingFiniteLoop = ControlsOnlyExit && loopHasNoAbnormalExits(L) &&
9317 // Simplify the operands before analyzing them.
9318 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0);
9319
9320 // If we have a comparison of a chrec against a constant, try to use value
9321 // ranges to answer this query.
9322 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
9323 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
9324 if (AddRec->getLoop() == L) {
9325 // Form the constant range.
9326 ConstantRange CompRange =
9327 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
9328
9329 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
9330 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
9331 }
9332
9333 // If this loop must exit based on this condition (or execute undefined
9334 // behaviour), see if we can improve wrap flags. This is essentially
9335 // a must execute style proof.
9336 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
9337 // If we can prove the test sequence produced must repeat the same values
9338 // on self-wrap of the IV, then we can infer that IV doesn't self wrap
9339 // because if it did, we'd have an infinite (undefined) loop.
9340 // TODO: We can peel off any functions which are invertible *in L*. Loop
9341 // invariant terms are effectively constants for our purposes here.
9342 SCEVUse InnerLHS = LHS;
9343 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
9344 InnerLHS = ZExt->getOperand();
9345 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS);
9346 AR && !AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
9347 isKnownToBeAPowerOfTwo(AR->getStepRecurrence(*this), /*OrZero=*/true,
9348 /*OrNegative=*/true)) {
9349 auto Flags = AR->getNoWrapFlags();
9350 Flags = setFlags(Flags, SCEV::FlagNW);
9353 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9354 }
9355
9356 // For a slt/ult condition with a positive step, can we prove nsw/nuw?
9357 // From no-self-wrap, this follows trivially from the fact that every
9358 // (un)signed-wrapped, but not self-wrapped value must be LT than the
9359 // last value before (un)signed wrap. Since we know that last value
9360 // didn't exit, nor will any smaller one.
9361 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT) {
9362 auto WrapType = Pred == ICmpInst::ICMP_SLT ? SCEV::FlagNSW : SCEV::FlagNUW;
9363 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9364 AR && AR->getLoop() == L && AR->isAffine() &&
9365 !AR->getNoWrapFlags(WrapType) && AR->hasNoSelfWrap() &&
9366 isKnownPositive(AR->getStepRecurrence(*this))) {
9367 auto Flags = AR->getNoWrapFlags();
9368 Flags = setFlags(Flags, WrapType);
9371 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9372 }
9373 }
9374 }
9375
9376 switch (Pred) {
9377 case ICmpInst::ICMP_NE: { // while (X != Y)
9378 // Convert to: while (X-Y != 0)
9379 if (LHS->getType()->isPointerTy()) {
9382 return LHS;
9383 }
9384 if (RHS->getType()->isPointerTy()) {
9387 return RHS;
9388 }
9389 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit,
9390 AllowPredicates);
9391 if (EL.hasAnyInfo())
9392 return EL;
9393 break;
9394 }
9395 case ICmpInst::ICMP_EQ: { // while (X == Y)
9396 // Convert to: while (X-Y == 0)
9397 if (LHS->getType()->isPointerTy()) {
9400 return LHS;
9401 }
9402 if (RHS->getType()->isPointerTy()) {
9405 return RHS;
9406 }
9407 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
9408 if (EL.hasAnyInfo()) return EL;
9409 break;
9410 }
9411 case ICmpInst::ICMP_SLE:
9412 case ICmpInst::ICMP_ULE:
9413 // Since the loop is finite, an invariant RHS cannot include the boundary
9414 // value, otherwise it would loop forever.
9415 if (!Opts.scalar_evolution_finite_loop || !ControllingFiniteLoop ||
9416 !isLoopInvariant(RHS, L)) {
9417 // Otherwise, perform the addition in a wider type, to avoid overflow.
9418 // If the LHS is an addrec with the appropriate nowrap flag, the
9419 // extension will be sunk into it and the exit count can be analyzed.
9420 auto *OldType = dyn_cast<IntegerType>(LHS->getType());
9421 if (!OldType)
9422 break;
9423 // Prefer doubling the bitwidth over adding a single bit to make it more
9424 // likely that we use a legal type.
9425 auto *NewType =
9426 Type::getIntNTy(OldType->getContext(), OldType->getBitWidth() * 2);
9427 if (ICmpInst::isSigned(Pred)) {
9428 LHS = getSignExtendExpr(LHS, NewType);
9429 RHS = getSignExtendExpr(RHS, NewType);
9430 } else {
9431 LHS = getZeroExtendExpr(LHS, NewType);
9432 RHS = getZeroExtendExpr(RHS, NewType);
9433 }
9434 }
9436 [[fallthrough]];
9437 case ICmpInst::ICMP_SLT:
9438 case ICmpInst::ICMP_ULT: { // while (X < Y)
9439 bool IsSigned = ICmpInst::isSigned(Pred);
9440 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, /*Invert=*/false,
9441 ControlsOnlyExit, AllowPredicates);
9442 if (EL.hasAnyInfo())
9443 return EL;
9444 break;
9445 }
9446 case ICmpInst::ICMP_SGE:
9447 case ICmpInst::ICMP_UGE:
9448 // Since the loop is finite, an invariant RHS cannot include the boundary
9449 // value, otherwise it would loop forever.
9450 if (!Opts.scalar_evolution_finite_loop || !ControllingFiniteLoop ||
9451 !isLoopInvariant(RHS, L))
9452 break;
9454 [[fallthrough]];
9455 case ICmpInst::ICMP_SGT:
9456 case ICmpInst::ICMP_UGT: { // while (X > Y)
9457 // "X > Y" is analyzed as the equivalent "~X < ~Y".
9458 bool IsSigned = ICmpInst::isSigned(Pred);
9459 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, /*Invert=*/true,
9460 ControlsOnlyExit, AllowPredicates);
9461 if (EL.hasAnyInfo())
9462 return EL;
9463 break;
9464 }
9465 default:
9466 break;
9467 }
9468
9469 return getCouldNotCompute();
9470}
9471
9472ScalarEvolution::ExitLimit
9473ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
9474 SwitchInst *Switch,
9475 BasicBlock *ExitingBlock,
9476 bool ControlsOnlyExit) {
9477 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
9478
9479 // Give up if the exit is the default dest of a switch.
9480 if (Switch->getDefaultDest() == ExitingBlock)
9481 return getCouldNotCompute();
9482
9483 assert(L->contains(Switch->getDefaultDest()) &&
9484 "Default case must not exit the loop!");
9485 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
9486 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
9487
9488 // while (X != Y) --> while (X-Y != 0)
9489 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit);
9490 if (EL.hasAnyInfo())
9491 return EL;
9492
9493 return getCouldNotCompute();
9494}
9495
9496static ConstantInt *
9498 ScalarEvolution &SE) {
9499 const SCEV *InVal = SE.getConstant(C);
9500 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
9502 "Evaluation of SCEV at constant didn't fold correctly?");
9503 return cast<SCEVConstant>(Val)->getValue();
9504}
9505
9506ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
9507 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
9508 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
9509 if (!RHS)
9510 return getCouldNotCompute();
9511
9512 const BasicBlock *Latch = L->getLoopLatch();
9513 if (!Latch)
9514 return getCouldNotCompute();
9515
9516 const BasicBlock *Predecessor = L->getLoopPredecessor();
9517 if (!Predecessor)
9518 return getCouldNotCompute();
9519
9520 // Return true if V is of the form "LHS `shift_op` <positive constant>".
9521 // Return LHS in OutLHS, shift_op in OutOpCode, and the shift amount in
9522 // OutShiftAmt.
9523 auto MatchPositiveShift = [](Value *V, Value *&OutLHS,
9524 Instruction::BinaryOps &OutOpCode,
9525 unsigned &OutShiftAmt) {
9526 using namespace PatternMatch;
9527
9528 ConstantInt *ShiftAmt;
9529 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9530 OutOpCode = Instruction::LShr;
9531 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9532 OutOpCode = Instruction::AShr;
9533 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9534 OutOpCode = Instruction::Shl;
9535 else
9536 return false;
9537
9538 uint64_t Amt = ShiftAmt->getValue().getLimitedValue();
9539 if (Amt == 0 || Amt >= OutLHS->getType()->getScalarSizeInBits())
9540 return false;
9541 OutShiftAmt = Amt;
9542 return true;
9543 };
9544
9545 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
9546 //
9547 // loop:
9548 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
9549 // %iv.shifted = lshr i32 %iv, <positive constant>
9550 //
9551 // Return true on a successful match. Return the corresponding PHI node (%iv
9552 // above) in PNOut, the opcode of the shift operation in OpCodeOut, and the
9553 // shift amount in ShiftAmtOut.
9554 auto MatchShiftRecurrence = [&](Value *V, PHINode *&PNOut,
9555 Instruction::BinaryOps &OpCodeOut,
9556 unsigned &ShiftAmtOut) {
9557 std::optional<Instruction::BinaryOps> PostShiftOpCode;
9558
9559 {
9561 Value *V;
9562 unsigned Amt;
9563
9564 // If we encounter a shift instruction, "peel off" the shift operation,
9565 // and remember that we did so. Later when we inspect %iv's backedge
9566 // value, we will make sure that the backedge value uses the same
9567 // operation.
9568 //
9569 // Note: the peeled shift operation does not have to be the same
9570 // instruction as the one feeding into the PHI's backedge value. We only
9571 // really care about it being the same *kind* of shift instruction --
9572 // that's all that is required for our later inferences to hold.
9573 if (MatchPositiveShift(LHS, V, OpC, Amt)) {
9574 PostShiftOpCode = OpC;
9575 LHS = V;
9576 }
9577 }
9578
9579 PNOut = dyn_cast<PHINode>(LHS);
9580 if (!PNOut || PNOut->getParent() != L->getHeader())
9581 return false;
9582
9583 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
9584 Value *OpLHS;
9585
9586 return
9587 // The backedge value for the PHI node must be a shift by a positive
9588 // amount
9589 MatchPositiveShift(BEValue, OpLHS, OpCodeOut, ShiftAmtOut) &&
9590
9591 // of the PHI node itself
9592 OpLHS == PNOut &&
9593
9594 // and the kind of shift should be match the kind of shift we peeled
9595 // off, if any.
9596 (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9597 };
9598
9599 PHINode *PN;
9601 unsigned ShiftAmt;
9602 if (!MatchShiftRecurrence(LHS, PN, OpCode, ShiftAmt))
9603 return getCouldNotCompute();
9604
9605 const DataLayout &DL = getDataLayout();
9606
9607 // The key rationale for this optimization is that for some kinds of shift
9608 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
9609 // within a finite number of iterations. If the condition guarding the
9610 // backedge (in the sense that the backedge is taken if the condition is true)
9611 // is false for the value the shift recurrence stabilizes to, then we know
9612 // that the backedge is taken only a finite number of times.
9613
9614 ConstantInt *StableValue = nullptr;
9615 switch (OpCode) {
9616 default:
9617 llvm_unreachable("Impossible case!");
9618
9619 case Instruction::AShr: {
9620 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
9621 // bitwidth(K) iterations.
9622 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
9623 KnownBits Known = computeKnownBits(FirstValue, DL, &AC,
9624 Predecessor->getTerminator(), &DT);
9625 auto *Ty = cast<IntegerType>(RHS->getType());
9626 if (Known.isNonNegative())
9627 StableValue = ConstantInt::get(Ty, 0);
9628 else if (Known.isNegative())
9629 StableValue = ConstantInt::get(Ty, -1, true);
9630 else
9631 return getCouldNotCompute();
9632
9633 break;
9634 }
9635 case Instruction::LShr:
9636 case Instruction::Shl:
9637 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
9638 // stabilize to 0 in at most bitwidth(K) iterations.
9639 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
9640 break;
9641 }
9642
9643 auto *Result =
9644 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
9645 assert(Result->getType()->isIntegerTy(1) &&
9646 "Otherwise cannot be an operand to a branch instruction");
9647
9648 if (Result->isNullValue()) {
9649 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9650 unsigned MaxBTC = BitWidth;
9651
9652 // For right-shift recurrences (lshr/ashr with non-negative start), we can
9653 // compute a tighter max backedge-taken count from the range of the start
9654 // value. After k shifts of ShiftAmt, value = start >> (k * ShiftAmt).
9655 // The value reaches 0 (the stable value) when k * ShiftAmt >=
9656 // activeBits(start), so max BTC = ceil(activeBits(maxStart) / ShiftAmt).
9657 if (OpCode == Instruction::LShr || OpCode == Instruction::AShr) {
9658 Value *StartValue = PN->getIncomingValueForBlock(Predecessor);
9659 const SCEV *StartSCEV = getSCEV(StartValue);
9660 APInt MaxStart = getUnsignedRangeMax(StartSCEV);
9661 if (MaxStart.isStrictlyPositive()) {
9662 unsigned ActiveBits = MaxStart.getActiveBits();
9663 unsigned RangeBTC = divideCeil(ActiveBits, ShiftAmt);
9664 MaxBTC = std::min(MaxBTC, RangeBTC);
9665 }
9666 }
9667
9668 const SCEV *UpperBound =
9670 return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
9671 }
9672
9673 return getCouldNotCompute();
9674}
9675
9676/// Return true if we can constant fold an instruction of the specified type,
9677/// assuming that all operands were constants.
9678static bool canConstantFold(const Instruction *I,
9679 const TargetLibraryInfo *TLI) {
9683 return true;
9684
9685 if (const CallInst *CI = dyn_cast<CallInst>(I))
9686 if (const Function *F = CI->getCalledFunction())
9687 return canConstantFoldCallTo(CI, F, TLI);
9688 return false;
9689}
9690
9691/// Determine whether this instruction can constant evolve within this loop
9692/// assuming its operands can all constant evolve.
9693static bool canConstantEvolve(Instruction *I, const Loop *L,
9694 const TargetLibraryInfo *TLI) {
9695 // An instruction outside of the loop can't be derived from a loop PHI.
9696 if (!L->contains(I)) return false;
9697
9698 if (isa<PHINode>(I)) {
9699 // We don't currently keep track of the control flow needed to evaluate
9700 // PHIs, so we cannot handle PHIs inside of loops.
9701 return L->getHeader() == I->getParent();
9702 }
9703
9704 // If we won't be able to constant fold this expression even if the operands
9705 // are constants, bail early.
9706 return canConstantFold(I, TLI);
9707}
9708
9709/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
9710/// recursing through each instruction operand until reaching a loop header phi.
9711static PHINode *
9712getConstantEvolvingPHIOperands(const AnalysisOptions &Opts,
9713 Instruction *UseInst, const Loop *L,
9715 const TargetLibraryInfo *TLI, unsigned Depth) {
9716 if (Depth > Opts.scalar_evolution_max_constant_evolving_depth)
9717 return nullptr;
9718
9719 // Otherwise, we can evaluate this instruction if all of its operands are
9720 // constant or derived from a PHI node themselves.
9721 PHINode *PHI = nullptr;
9722 for (Value *Op : UseInst->operands()) {
9723 if (isa<Constant>(Op)) continue;
9724
9726 if (!OpInst || !canConstantEvolve(OpInst, L, TLI))
9727 return nullptr;
9728
9729 PHINode *P = dyn_cast<PHINode>(OpInst);
9730 if (!P)
9731 // If this operand is already visited, reuse the prior result.
9732 // We may have P != PHI if this is the deepest point at which the
9733 // inconsistent paths meet.
9734 P = PHIMap.lookup(OpInst);
9735 if (!P) {
9736 // Recurse and memoize the results, whether a phi is found or not.
9737 // This recursive call invalidates pointers into PHIMap.
9738 P = getConstantEvolvingPHIOperands(Opts, OpInst, L, PHIMap, TLI,
9739 Depth + 1);
9740 PHIMap[OpInst] = P;
9741 }
9742 if (!P)
9743 return nullptr; // Not evolving from PHI
9744 if (PHI && PHI != P)
9745 return nullptr; // Evolving from multiple different PHIs.
9746 PHI = P;
9747 }
9748 // This is a expression evolving from a constant PHI!
9749 return PHI;
9750}
9751
9752/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9753/// in the loop that V is derived from. We allow arbitrary operations along the
9754/// way, but the operands of an operation must either be constants or a value
9755/// derived from a constant PHI. If this expression does not fit with these
9756/// constraints, return null.
9757static PHINode *getConstantEvolvingPHI(const AnalysisOptions &Opts, Value *V,
9758 const Loop *L,
9759 const TargetLibraryInfo *TLI) {
9761 if (!I || !canConstantEvolve(I, L, TLI))
9762 return nullptr;
9763
9764 if (PHINode *PN = dyn_cast<PHINode>(I))
9765 return PN;
9766
9767 // Record non-constant instructions contained by the loop.
9769 return getConstantEvolvingPHIOperands(Opts, I, L, PHIMap, TLI, 0);
9770}
9771
9772/// EvaluateExpression - Given an expression that passes the
9773/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9774/// in the loop has the value PHIVal. If we can't fold this expression for some
9775/// reason, return null.
9778 const DataLayout &DL,
9779 const TargetLibraryInfo *TLI) {
9780 // Convenient constant check, but redundant for recursive calls.
9781 if (Constant *C = dyn_cast<Constant>(V)) return C;
9783 if (!I) return nullptr;
9784
9785 if (Constant *C = Vals.lookup(I)) return C;
9786
9787 // An instruction inside the loop depends on a value outside the loop that we
9788 // weren't given a mapping for, or a value such as a call inside the loop.
9789 if (!canConstantEvolve(I, L, TLI))
9790 return nullptr;
9791
9792 // An unmapped PHI can be due to a branch or another loop inside this loop,
9793 // or due to this not being the initial iteration through a loop where we
9794 // couldn't compute the evolution of this particular PHI last time.
9795 if (isa<PHINode>(I)) return nullptr;
9796
9797 std::vector<Constant*> Operands(I->getNumOperands());
9798
9799 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9800 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9801 if (!Operand) {
9802 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9803 if (!Operands[i]) return nullptr;
9804 continue;
9805 }
9806 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9807 Vals[Operand] = C;
9808 if (!C) return nullptr;
9809 Operands[i] = C;
9810 }
9811
9812 return ConstantFoldInstOperands(I, Operands, DL, TLI,
9813 /*AllowNonDeterministic=*/false);
9814}
9815
9816
9817// If every incoming value to PN except the one for BB is a specific Constant,
9818// return that, else return nullptr.
9820 Constant *IncomingVal = nullptr;
9821
9822 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9823 if (PN->getIncomingBlock(i) == BB)
9824 continue;
9825
9826 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
9827 if (!CurrentVal)
9828 return nullptr;
9829
9830 if (IncomingVal != CurrentVal) {
9831 if (IncomingVal)
9832 return nullptr;
9833 IncomingVal = CurrentVal;
9834 }
9835 }
9836
9837 return IncomingVal;
9838}
9839
9840/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9841/// in the header of its containing loop, we know the loop executes a
9842/// constant number of times, and the PHI node is just a recurrence
9843/// involving constants, fold it.
9844Constant *
9845ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9846 const APInt &BEs,
9847 const Loop *L) {
9848 auto [I, Inserted] = ConstantEvolutionLoopExitValue.try_emplace(PN);
9849 if (!Inserted)
9850 return I->second;
9851
9852 if (BEs.ugt(Opts.scalar_evolution_max_iterations))
9853 return nullptr; // Not going to evaluate it.
9854
9855 Constant *&RetVal = I->second;
9856
9857 DenseMap<Instruction *, Constant *> CurrentIterVals;
9858 BasicBlock *Header = L->getHeader();
9859 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9860
9861 BasicBlock *Latch = L->getLoopLatch();
9862 if (!Latch)
9863 return nullptr;
9864
9865 for (PHINode &PHI : Header->phis()) {
9866 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9867 CurrentIterVals[&PHI] = StartCST;
9868 }
9869 if (!CurrentIterVals.count(PN))
9870 return RetVal = nullptr;
9871
9872 Value *BEValue = PN->getIncomingValueForBlock(Latch);
9873
9874 // Execute the loop symbolically to determine the exit value.
9875 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
9876 "BEs is <= -scalar-evolution-max-iterations which is an 'unsigned'!");
9877
9878 unsigned NumIterations = BEs.getZExtValue(); // must be in range
9879 unsigned IterationNum = 0;
9880 const DataLayout &DL = getDataLayout();
9881 for (; ; ++IterationNum) {
9882 if (IterationNum == NumIterations)
9883 return RetVal = CurrentIterVals[PN]; // Got exit value!
9884
9885 // Compute the value of the PHIs for the next iteration.
9886 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9887 DenseMap<Instruction *, Constant *> NextIterVals;
9888 Constant *NextPHI =
9889 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9890 if (!NextPHI)
9891 return nullptr; // Couldn't evaluate!
9892 NextIterVals[PN] = NextPHI;
9893
9894 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9895
9896 // Also evaluate the other PHI nodes. However, we don't get to stop if we
9897 // cease to be able to evaluate one of them or if they stop evolving,
9898 // because that doesn't necessarily prevent us from computing PN.
9900 for (const auto &I : CurrentIterVals) {
9901 PHINode *PHI = dyn_cast<PHINode>(I.first);
9902 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
9903 PHIsToCompute.emplace_back(PHI, I.second);
9904 }
9905 // We use two distinct loops because EvaluateExpression may invalidate any
9906 // iterators into CurrentIterVals.
9907 for (const auto &I : PHIsToCompute) {
9908 PHINode *PHI = I.first;
9909 Constant *&NextPHI = NextIterVals[PHI];
9910 if (!NextPHI) { // Not already computed.
9911 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9912 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9913 }
9914 if (NextPHI != I.second)
9915 StoppedEvolving = false;
9916 }
9917
9918 // If all entries in CurrentIterVals == NextIterVals then we can stop
9919 // iterating, the loop can't continue to change.
9920 if (StoppedEvolving)
9921 return RetVal = CurrentIterVals[PN];
9922
9923 CurrentIterVals.swap(NextIterVals);
9924 }
9925}
9926
9927const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
9928 Value *Cond,
9929 bool ExitWhen) {
9930 PHINode *PN = getConstantEvolvingPHI(Opts, Cond, L, &TLI);
9931 if (!PN) return getCouldNotCompute();
9932
9933 // If the loop is canonicalized, the PHI will have exactly two entries.
9934 // That's the only form we support here.
9935 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
9936
9937 DenseMap<Instruction *, Constant *> CurrentIterVals;
9938 BasicBlock *Header = L->getHeader();
9939 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9940
9941 BasicBlock *Latch = L->getLoopLatch();
9942 assert(Latch && "Should follow from NumIncomingValues == 2!");
9943
9944 for (PHINode &PHI : Header->phis()) {
9945 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9946 CurrentIterVals[&PHI] = StartCST;
9947 }
9948 if (!CurrentIterVals.count(PN))
9949 return getCouldNotCompute();
9950
9951 // Okay, we find a PHI node that defines the trip count of this loop. Execute
9952 // the loop symbolically to determine when the condition gets a value of
9953 // "ExitWhen".
9954 unsigned MaxIterations =
9955 Opts.scalar_evolution_max_iterations; // Limit analysis.
9956 const DataLayout &DL = getDataLayout();
9957 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
9958 auto *CondVal = dyn_cast_or_null<ConstantInt>(
9959 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
9960
9961 // Couldn't symbolically evaluate.
9962 if (!CondVal) return getCouldNotCompute();
9963
9964 if (CondVal->getValue() == uint64_t(ExitWhen)) {
9965 ++NumBruteForceTripCountsComputed;
9966 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
9967 }
9968
9969 // Update all the PHI nodes for the next iteration.
9970 DenseMap<Instruction *, Constant *> NextIterVals;
9971
9972 // Create a list of which PHIs we need to compute. We want to do this before
9973 // calling EvaluateExpression on them because that may invalidate iterators
9974 // into CurrentIterVals.
9975 SmallVector<PHINode *, 8> PHIsToCompute;
9976 for (const auto &I : CurrentIterVals) {
9977 PHINode *PHI = dyn_cast<PHINode>(I.first);
9978 if (!PHI || PHI->getParent() != Header) continue;
9979 PHIsToCompute.push_back(PHI);
9980 }
9981 for (PHINode *PHI : PHIsToCompute) {
9982 Constant *&NextPHI = NextIterVals[PHI];
9983 if (NextPHI) continue; // Already computed!
9984
9985 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9986 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9987 }
9988 CurrentIterVals.swap(NextIterVals);
9989 }
9990
9991 // Too many iterations were needed to evaluate.
9992 return getCouldNotCompute();
9993}
9994
9996 if (isa<SCEVConstant>(V))
9997 return V;
9998
9999 auto &Values = ValuesAtScopes[V];
10000 // Check to see if we've folded this expression at this loop before.
10001 for (auto &LS : Values)
10002 if (LS.first == L)
10003 return LS.second ? LS.second : SCEVUse(V);
10004
10005 Values.emplace_back(L, nullptr);
10006
10007 // Otherwise compute it.
10008 SCEVUse C = computeSCEVAtScope(V, L);
10009 for (auto &LS : reverse(ValuesAtScopes[V]))
10010 if (LS.first == L) {
10011 LS.second = C;
10012 // Record the dependency under the bare expression: invalidation walks
10013 // expressions, and any use flags on C do not change which expression
10014 // this is the value at scope of.
10015 if (!isa<SCEVConstant>(C))
10016 ValuesAtScopesUsers[C.getPointer()].push_back({L, V});
10017 break;
10018 }
10019 return C;
10020}
10021
10023 const BasicBlock *ExitingBlock) {
10024 SCEVUse ExitValue = getSCEVAtScope(V, L->getParentLoop());
10025 if (!isLoopInvariant(ExitValue, L)) {
10026 // If we failed to evaluate it in the outer scope, try to evaluate an
10027 // addrec for the specific exit.
10028 // TODO: Generalize this to other expressions.
10029 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
10030 if (!isa<SCEVCouldNotCompute>(ExitCount))
10031 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V))
10032 if (AddRec->getLoop() == L)
10033 ExitValue = AddRec->evaluateAtIteration(ExitCount, *this);
10034 }
10035 return ExitValue;
10036}
10037
10038/// This builds up a Constant using the ConstantExpr interface. That way, we
10039/// will return Constants for objects which aren't represented by a
10040/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
10041/// Returns NULL if the SCEV isn't representable as a Constant.
10043 switch (V->getSCEVType()) {
10044 case scCouldNotCompute:
10045 case scAddRecExpr:
10046 case scVScale:
10047 return nullptr;
10048 case scConstant:
10049 return cast<SCEVConstant>(V)->getValue();
10050 case scUnknown:
10052 case scPtrToAddr: {
10054 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
10055 return ConstantExpr::getPtrToAddr(CastOp, P2I->getType());
10056
10057 return nullptr;
10058 }
10059 case scTruncate: {
10061 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
10062 return ConstantExpr::getTrunc(CastOp, ST->getType());
10063 return nullptr;
10064 }
10065 case scAddExpr: {
10066 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
10067 Constant *C = nullptr;
10068 for (const SCEV *Op : SA->operands()) {
10070 if (!OpC)
10071 return nullptr;
10072 if (!C) {
10073 C = OpC;
10074 continue;
10075 }
10076 assert(!C->getType()->isPointerTy() &&
10077 "Can only have one pointer, and it must be last");
10078 if (OpC->getType()->isPointerTy()) {
10079 // The offsets have been converted to bytes. We can add bytes using
10080 // an i8 GEP.
10081 C = ConstantExpr::getPtrAdd(OpC, C);
10082 } else {
10083 C = ConstantExpr::getAdd(C, OpC);
10084 }
10085 }
10086 return C;
10087 }
10088 case scMulExpr:
10089 case scSignExtend:
10090 case scZeroExtend:
10091 case scUDivExpr:
10092 case scSMaxExpr:
10093 case scUMaxExpr:
10094 case scSMinExpr:
10095 case scUMinExpr:
10097 return nullptr;
10098 }
10099 llvm_unreachable("Unknown SCEV kind!");
10100}
10101
10102const SCEV *ScalarEvolution::getWithOperands(const SCEV *S,
10103 SmallVectorImpl<SCEVUse> &NewOps) {
10104 switch (S->getSCEVType()) {
10105 case scTruncate:
10106 case scZeroExtend:
10107 case scSignExtend:
10108 case scPtrToAddr:
10109 return getCastExpr(S->getSCEVType(), NewOps[0], S->getType());
10110 case scAddRecExpr: {
10111 auto *AddRec = cast<SCEVAddRecExpr>(S);
10112 return getAddRecExpr(NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags());
10113 }
10114 case scAddExpr:
10115 return getAddExpr(NewOps, cast<SCEVAddExpr>(S)->getNoWrapFlags());
10116 case scMulExpr:
10117 return getMulExpr(NewOps, cast<SCEVMulExpr>(S)->getNoWrapFlags());
10118 case scUDivExpr:
10119 return getUDivExpr(NewOps[0], NewOps[1]);
10120 case scUMaxExpr:
10121 case scSMaxExpr:
10122 case scUMinExpr:
10123 case scSMinExpr:
10124 return getMinMaxExpr(S->getSCEVType(), NewOps);
10126 return getSequentialMinMaxExpr(S->getSCEVType(), NewOps);
10127 case scConstant:
10128 case scVScale:
10129 case scUnknown:
10130 return S;
10131 case scCouldNotCompute:
10132 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10133 }
10134 llvm_unreachable("Unknown SCEV kind!");
10135}
10136
10137SCEVUse ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
10138 switch (V->getSCEVType()) {
10139 case scConstant:
10140 case scVScale:
10141 return V;
10142 case scAddRecExpr: {
10143 // If this is a loop recurrence for a loop that does not contain L, then we
10144 // are dealing with the final value computed by the loop.
10145 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(V);
10146 // First, attempt to evaluate each operand.
10147 // Avoid performing the look-up in the common case where the specified
10148 // expression has no loop-variant portions.
10149 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
10150 SCEVUse OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
10151 if (OpAtScope == AddRec->getOperand(i))
10152 continue;
10153
10154 // Okay, at least one of these operands is loop variant but might be
10155 // foldable. Build a new instance of the folded commutative expression.
10157 NewOps.reserve(AddRec->getNumOperands());
10158 append_range(NewOps, AddRec->operands().take_front(i));
10159 NewOps.push_back(OpAtScope);
10160 for (++i; i != e; ++i)
10161 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
10162
10163 const SCEV *FoldedRec = getAddRecExpr(
10164 NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags(SCEV::FlagNW));
10165 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
10166 // The addrec may be folded to a nonrecurrence, for example, if the
10167 // induction variable is multiplied by zero after constant folding. Go
10168 // ahead and return the folded value.
10169 if (!AddRec)
10170 return FoldedRec;
10171 break;
10172 }
10173
10174 // If the scope is outside the addrec's loop, evaluate it by using the
10175 // loop exit value of the addrec.
10176 if (!AddRec->getLoop()->contains(L)) {
10177 SCEVUse ExitValue = AddRec->getExitValue(*this);
10178 if (isa<SCEVCouldNotCompute>(ExitValue))
10179 return AddRec;
10180 return ExitValue;
10181 }
10182
10183 return AddRec;
10184 }
10185 case scTruncate:
10186 case scZeroExtend:
10187 case scSignExtend:
10188 case scPtrToAddr:
10189 case scAddExpr:
10190 case scMulExpr:
10191 case scUDivExpr:
10192 case scUMaxExpr:
10193 case scSMaxExpr:
10194 case scUMinExpr:
10195 case scSMinExpr:
10196 case scSequentialUMinExpr: {
10197 ArrayRef<SCEVUse> Ops = V->operands();
10198 // Avoid performing the look-up in the common case where the specified
10199 // expression has no loop-variant portions.
10200 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
10201 SCEVUse OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10202 if (OpAtScope != Ops[i].getPointer()) {
10203 // Okay, at least one of these operands is loop variant but might be
10204 // foldable. Build a new instance of the folded commutative expression.
10206 NewOps.reserve(Ops.size());
10207 append_range(NewOps, Ops.take_front(i));
10208 NewOps.push_back(OpAtScope);
10209
10210 for (++i; i != e; ++i) {
10211 OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10212 NewOps.push_back(OpAtScope);
10213 }
10214
10215 return getWithOperands(V, NewOps);
10216 }
10217 }
10218 // If we got here, all operands are loop invariant.
10219 return V;
10220 }
10221 case scUnknown: {
10222 // If this instruction is evolved from a constant-evolving PHI, compute the
10223 // exit value from the loop without using SCEVs.
10224 const SCEVUnknown *SU = cast<SCEVUnknown>(V);
10226 if (!I)
10227 return V; // This is some other type of SCEVUnknown, just return it.
10228
10229 if (PHINode *PN = dyn_cast<PHINode>(I)) {
10230 const Loop *CurrLoop = this->LI[I->getParent()];
10231 // Looking for loop exit value.
10232 if (CurrLoop && CurrLoop->getParentLoop() == L &&
10233 PN->getParent() == CurrLoop->getHeader()) {
10234 // Okay, there is no closed form solution for the PHI node. Check
10235 // to see if the loop that contains it has a known backedge-taken
10236 // count. If so, we may be able to force computation of the exit
10237 // value.
10238 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
10239 // This trivial case can show up in some degenerate cases where
10240 // the incoming IR has not yet been fully simplified.
10241 if (BackedgeTakenCount->isZero()) {
10242 Value *InitValue = nullptr;
10243 bool MultipleInitValues = false;
10244 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
10245 if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
10246 if (!InitValue)
10247 InitValue = PN->getIncomingValue(i);
10248 else if (InitValue != PN->getIncomingValue(i)) {
10249 MultipleInitValues = true;
10250 break;
10251 }
10252 }
10253 }
10254 if (!MultipleInitValues && InitValue)
10255 return getSCEV(InitValue);
10256 }
10257 // Do we have a loop invariant value flowing around the backedge
10258 // for a loop which must execute the backedge?
10259 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
10260 isKnownNonZero(BackedgeTakenCount) &&
10261 PN->getNumIncomingValues() == 2) {
10262
10263 unsigned InLoopPred =
10264 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
10265 Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
10266 if (CurrLoop->isLoopInvariant(BackedgeVal))
10267 return getSCEV(BackedgeVal);
10268 }
10269 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
10270 // Okay, we know how many times the containing loop executes. If
10271 // this is a constant evolving PHI node, get the final value at
10272 // the specified iteration number.
10273 Constant *RV =
10274 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
10275 if (RV)
10276 return getSCEV(RV);
10277 }
10278 }
10279 }
10280
10281 // Okay, this is an expression that we cannot symbolically evaluate
10282 // into a SCEV. Check to see if it's possible to symbolically evaluate
10283 // the arguments into constants, and if so, try to constant propagate the
10284 // result. This is particularly useful for computing loop exit values.
10285 if (!canConstantFold(I, &TLI))
10286 return V; // This is some other type of SCEVUnknown, just return it.
10287
10288 SmallVector<Constant *, 4> Operands;
10289 Operands.reserve(I->getNumOperands());
10290 bool MadeImprovement = false;
10291 for (Value *Op : I->operands()) {
10292 if (Constant *C = dyn_cast<Constant>(Op)) {
10293 Operands.push_back(C);
10294 continue;
10295 }
10296
10297 // If any of the operands is non-constant and if they are
10298 // non-integer and non-pointer, don't even try to analyze them
10299 // with scev techniques.
10300 if (!isSCEVable(Op->getType()))
10301 return V;
10302
10303 const SCEV *OrigV = getSCEV(Op);
10304 const SCEV *OpV = getSCEVAtScope(OrigV, L);
10305 MadeImprovement |= OrigV != OpV;
10306
10308 if (!C)
10309 return V;
10310 assert(C->getType() == Op->getType() && "Type mismatch");
10311 Operands.push_back(C);
10312 }
10313
10314 // Check to see if getSCEVAtScope actually made an improvement.
10315 if (!MadeImprovement)
10316 return V; // This is some other type of SCEVUnknown, just return it.
10317
10318 Constant *C = nullptr;
10319 const DataLayout &DL = getDataLayout();
10320 C = ConstantFoldInstOperands(I, Operands, DL, &TLI,
10321 /*AllowNonDeterministic=*/false);
10322 if (!C)
10323 return V;
10324 return getSCEV(C);
10325 }
10326 case scCouldNotCompute:
10327 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10328 }
10329 llvm_unreachable("Unknown SCEV type!");
10330}
10331
10333 return getSCEVAtScope(getSCEV(V), L);
10334}
10335
10336const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
10338 return stripInjectiveFunctions(ZExt->getOperand());
10340 return stripInjectiveFunctions(SExt->getOperand());
10341 return S;
10342}
10343
10344/// Finds the minimum unsigned root of the following equation:
10345///
10346/// A * X = B (mod N)
10347///
10348/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
10349/// A and B isn't important.
10350///
10351/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
10352static const SCEV *
10355 ScalarEvolution &SE, const Loop *L) {
10356 uint32_t BW = A.getBitWidth();
10357 assert(BW == SE.getTypeSizeInBits(B->getType()));
10358 assert(A != 0 && "A must be non-zero.");
10359
10360 // 1. D = gcd(A, N)
10361 //
10362 // The gcd of A and N may have only one prime factor: 2. The number of
10363 // trailing zeros in A is its multiplicity
10364 uint32_t Mult2 = A.countr_zero();
10365 // D = 2^Mult2
10366
10367 // 2. Check if B is divisible by D.
10368 //
10369 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
10370 // is not less than multiplicity of this prime factor for D.
10371 unsigned MinTZ = SE.getMinTrailingZeros(B);
10372 // Try again with the terminator of the loop predecessor for context-specific
10373 // result, if MinTZ s too small.
10374 if (MinTZ < Mult2 && L->getLoopPredecessor())
10375 MinTZ = SE.getMinTrailingZeros(B, L->getLoopPredecessor()->getTerminator());
10376 if (MinTZ < Mult2) {
10377 // Check if we can prove there's no remainder using URem.
10378 const SCEV *URem =
10379 SE.getURemExpr(B, SE.getConstant(APInt::getOneBitSet(BW, Mult2)));
10380 const SCEV *Zero = SE.getZero(B->getType());
10381 if (!SE.isKnownPredicate(CmpInst::ICMP_EQ, URem, Zero)) {
10382 // Try to add a predicate ensuring B is a multiple of 1 << Mult2.
10383 if (!Predicates)
10384 return SE.getCouldNotCompute();
10385
10386 // Avoid adding a predicate that is known to be false.
10387 if (SE.isKnownPredicate(CmpInst::ICMP_NE, URem, Zero))
10388 return SE.getCouldNotCompute();
10389 Predicates->push_back(SE.getEqualPredicate(URem, Zero));
10390 }
10391 }
10392
10393 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
10394 // modulo (N / D).
10395 //
10396 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
10397 // (N / D) in general. The inverse itself always fits into BW bits, though,
10398 // so we immediately truncate it.
10399 APInt AD = A.lshr(Mult2).trunc(BW - Mult2); // AD = A / D
10400 APInt I = AD.multiplicativeInverse().zext(BW);
10401
10402 // 4. Compute the minimum unsigned root of the equation:
10403 // I * (B / D) mod (N / D)
10404 // To simplify the computation, we factor out the divide by D:
10405 // (I * B mod N) / D
10406 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
10407 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
10408}
10409
10410/// For a given quadratic addrec, generate coefficients of the corresponding
10411/// quadratic equation, multiplied by a common value to ensure that they are
10412/// integers.
10413/// The returned value is a tuple { A, B, C, M, BitWidth }, where
10414/// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
10415/// were multiplied by, and BitWidth is the bit width of the original addrec
10416/// coefficients.
10417/// This function returns std::nullopt if the addrec coefficients are not
10418/// compile- time constants.
10419static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
10421 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
10422 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
10423 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
10424 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
10425 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
10426 << *AddRec << '\n');
10427
10428 // We currently can only solve this if the coefficients are constants.
10429 if (!LC || !MC || !NC) {
10430 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
10431 return std::nullopt;
10432 }
10433
10434 APInt L = LC->getAPInt();
10435 APInt M = MC->getAPInt();
10436 APInt N = NC->getAPInt();
10437 assert(!N.isZero() && "This is not a quadratic addrec");
10438
10439 unsigned BitWidth = LC->getAPInt().getBitWidth();
10440 unsigned NewWidth = BitWidth + 1;
10441 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
10442 << BitWidth << '\n');
10443 // The sign-extension (as opposed to a zero-extension) here matches the
10444 // extension used in SolveQuadraticEquationWrap (with the same motivation).
10445 N = N.sext(NewWidth);
10446 M = M.sext(NewWidth);
10447 L = L.sext(NewWidth);
10448
10449 // The increments are M, M+N, M+2N, ..., so the accumulated values are
10450 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
10451 // L+M, L+2M+N, L+3M+3N, ...
10452 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
10453 //
10454 // The equation Acc = 0 is then
10455 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
10456 // In a quadratic form it becomes:
10457 // N n^2 + (2M-N) n + 2L = 0.
10458
10459 APInt A = N;
10460 APInt B = 2 * M - A;
10461 APInt C = 2 * L;
10462 APInt T = APInt(NewWidth, 2);
10463 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
10464 << "x + " << C << ", coeff bw: " << NewWidth
10465 << ", multiplied by " << T << '\n');
10466 return std::make_tuple(A, B, C, T, BitWidth);
10467}
10468
10469/// Helper function to compare optional APInts:
10470/// (a) if X and Y both exist, return min(X, Y),
10471/// (b) if neither X nor Y exist, return std::nullopt,
10472/// (c) if exactly one of X and Y exists, return that value.
10473static std::optional<APInt> MinOptional(std::optional<APInt> X,
10474 std::optional<APInt> Y) {
10475 if (X && Y) {
10476 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
10477 APInt XW = X->sext(W);
10478 APInt YW = Y->sext(W);
10479 return XW.slt(YW) ? *X : *Y;
10480 }
10481 if (!X && !Y)
10482 return std::nullopt;
10483 return X ? *X : *Y;
10484}
10485
10486/// Helper function to truncate an optional APInt to a given BitWidth.
10487/// When solving addrec-related equations, it is preferable to return a value
10488/// that has the same bit width as the original addrec's coefficients. If the
10489/// solution fits in the original bit width, truncate it (except for i1).
10490/// Returning a value of a different bit width may inhibit some optimizations.
10491///
10492/// In general, a solution to a quadratic equation generated from an addrec
10493/// may require BW+1 bits, where BW is the bit width of the addrec's
10494/// coefficients. The reason is that the coefficients of the quadratic
10495/// equation are BW+1 bits wide (to avoid truncation when converting from
10496/// the addrec to the equation).
10497static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
10498 unsigned BitWidth) {
10499 if (!X)
10500 return std::nullopt;
10501 unsigned W = X->getBitWidth();
10503 return X->trunc(BitWidth);
10504 return X;
10505}
10506
10507/// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
10508/// iterations. The values L, M, N are assumed to be signed, and they
10509/// should all have the same bit widths.
10510/// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
10511/// where BW is the bit width of the addrec's coefficients.
10512/// If the calculated value is a BW-bit integer (for BW > 1), it will be
10513/// returned as such, otherwise the bit width of the returned value may
10514/// be greater than BW.
10515///
10516/// This function returns std::nullopt if
10517/// (a) the addrec coefficients are not constant, or
10518/// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
10519/// like x^2 = 5, no integer solutions exist, in other cases an integer
10520/// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
10521static std::optional<APInt>
10523 APInt A, B, C, M;
10524 unsigned BitWidth;
10525 auto T = GetQuadraticEquation(AddRec);
10526 if (!T)
10527 return std::nullopt;
10528
10529 std::tie(A, B, C, M, BitWidth) = *T;
10530 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
10531 std::optional<APInt> X =
10533 if (!X)
10534 return std::nullopt;
10535
10536 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
10537 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
10538 if (!V->isZero())
10539 return std::nullopt;
10540
10541 return TruncIfPossible(X, BitWidth);
10542}
10543
10544/// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
10545/// iterations. The values M, N are assumed to be signed, and they
10546/// should all have the same bit widths.
10547/// Find the least n such that c(n) does not belong to the given range,
10548/// while c(n-1) does.
10549///
10550/// This function returns std::nullopt if
10551/// (a) the addrec coefficients are not constant, or
10552/// (b) SolveQuadraticEquationWrap was unable to find a solution for the
10553/// bounds of the range.
10554static std::optional<APInt>
10556 const ConstantRange &Range, ScalarEvolution &SE) {
10557 assert(AddRec->getOperand(0)->isZero() &&
10558 "Starting value of addrec should be 0");
10559 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
10560 << Range << ", addrec " << *AddRec << '\n');
10561 // This case is handled in getNumIterationsInRange. Here we can assume that
10562 // we start in the range.
10563 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
10564 "Addrec's initial value should be in range");
10565
10566 APInt A, B, C, M;
10567 unsigned BitWidth;
10568 auto T = GetQuadraticEquation(AddRec);
10569 if (!T)
10570 return std::nullopt;
10571
10572 // Be careful about the return value: there can be two reasons for not
10573 // returning an actual number. First, if no solutions to the equations
10574 // were found, and second, if the solutions don't leave the given range.
10575 // The first case means that the actual solution is "unknown", the second
10576 // means that it's known, but not valid. If the solution is unknown, we
10577 // cannot make any conclusions.
10578 // Return a pair: the optional solution and a flag indicating if the
10579 // solution was found.
10580 auto SolveForBoundary =
10581 [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
10582 // Solve for signed overflow and unsigned overflow, pick the lower
10583 // solution.
10584 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
10585 << Bound << " (before multiplying by " << M << ")\n");
10586 Bound *= M; // The quadratic equation multiplier.
10587
10588 std::optional<APInt> SO;
10589 if (BitWidth > 1) {
10590 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10591 "signed overflow\n");
10593 }
10594 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10595 "unsigned overflow\n");
10596 std::optional<APInt> UO =
10598
10599 auto LeavesRange = [&] (const APInt &X) {
10600 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
10602 if (Range.contains(V0->getValue()))
10603 return false;
10604 // X should be at least 1, so X-1 is non-negative.
10605 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
10607 if (Range.contains(V1->getValue()))
10608 return true;
10609 return false;
10610 };
10611
10612 // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
10613 // can be a solution, but the function failed to find it. We cannot treat it
10614 // as "no solution".
10615 if (!SO || !UO)
10616 return {std::nullopt, false};
10617
10618 // Check the smaller value first to see if it leaves the range.
10619 // At this point, both SO and UO must have values.
10620 std::optional<APInt> Min = MinOptional(SO, UO);
10621 if (LeavesRange(*Min))
10622 return { Min, true };
10623 std::optional<APInt> Max = Min == SO ? UO : SO;
10624 if (LeavesRange(*Max))
10625 return { Max, true };
10626
10627 // Solutions were found, but were eliminated, hence the "true".
10628 return {std::nullopt, true};
10629 };
10630
10631 std::tie(A, B, C, M, BitWidth) = *T;
10632 // Lower bound is inclusive, subtract 1 to represent the exiting value.
10633 APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
10634 APInt Upper = Range.getUpper().sext(A.getBitWidth());
10635 auto SL = SolveForBoundary(Lower);
10636 auto SU = SolveForBoundary(Upper);
10637 // If any of the solutions was unknown, no meaninigful conclusions can
10638 // be made.
10639 if (!SL.second || !SU.second)
10640 return std::nullopt;
10641
10642 // Claim: The correct solution is not some value between Min and Max.
10643 //
10644 // Justification: Assuming that Min and Max are different values, one of
10645 // them is when the first signed overflow happens, the other is when the
10646 // first unsigned overflow happens. Crossing the range boundary is only
10647 // possible via an overflow (treating 0 as a special case of it, modeling
10648 // an overflow as crossing k*2^W for some k).
10649 //
10650 // The interesting case here is when Min was eliminated as an invalid
10651 // solution, but Max was not. The argument is that if there was another
10652 // overflow between Min and Max, it would also have been eliminated if
10653 // it was considered.
10654 //
10655 // For a given boundary, it is possible to have two overflows of the same
10656 // type (signed/unsigned) without having the other type in between: this
10657 // can happen when the vertex of the parabola is between the iterations
10658 // corresponding to the overflows. This is only possible when the two
10659 // overflows cross k*2^W for the same k. In such case, if the second one
10660 // left the range (and was the first one to do so), the first overflow
10661 // would have to enter the range, which would mean that either we had left
10662 // the range before or that we started outside of it. Both of these cases
10663 // are contradictions.
10664 //
10665 // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
10666 // solution is not some value between the Max for this boundary and the
10667 // Min of the other boundary.
10668 //
10669 // Justification: Assume that we had such Max_A and Min_B corresponding
10670 // to range boundaries A and B and such that Max_A < Min_B. If there was
10671 // a solution between Max_A and Min_B, it would have to be caused by an
10672 // overflow corresponding to either A or B. It cannot correspond to B,
10673 // since Min_B is the first occurrence of such an overflow. If it
10674 // corresponded to A, it would have to be either a signed or an unsigned
10675 // overflow that is larger than both eliminated overflows for A. But
10676 // between the eliminated overflows and this overflow, the values would
10677 // cover the entire value space, thus crossing the other boundary, which
10678 // is a contradiction.
10679
10680 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
10681}
10682
10683ScalarEvolution::ExitLimit ScalarEvolution::howFarToZero(const SCEV *V,
10684 const Loop *L,
10685 bool ControlsOnlyExit,
10686 bool AllowPredicates) {
10687
10688 // This is only used for loops with a "x != y" exit test. The exit condition
10689 // is now expressed as a single expression, V = x-y. So the exit test is
10690 // effectively V != 0. We know and take advantage of the fact that this
10691 // expression only being used in a comparison by zero context.
10692
10694 // If the value is a constant
10695 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10696 // If the value is already zero, the branch will execute zero times.
10697 if (C->getValue()->isZero()) return C;
10698 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10699 }
10700
10701 const SCEVAddRecExpr *AddRec =
10702 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
10703
10704 if (!AddRec && AllowPredicates)
10705 // Try to make this an AddRec using runtime tests, in the first X
10706 // iterations of this loop, where X is the SCEV expression found by the
10707 // algorithm below.
10708 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
10709
10710 if (!AddRec || AddRec->getLoop() != L)
10711 return getCouldNotCompute();
10712
10713 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
10714 // the quadratic equation to solve it.
10715 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
10716 // We can only use this value if the chrec ends up with an exact zero
10717 // value at this index. When solving for "X*X != 5", for example, we
10718 // should not accept a root of 2.
10719 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
10720 const auto *R = cast<SCEVConstant>(getConstant(*S));
10721 return ExitLimit(R, R, R, false, Predicates);
10722 }
10723 return getCouldNotCompute();
10724 }
10725
10726 // Otherwise we can only handle this if it is affine.
10727 if (!AddRec->isAffine())
10728 return getCouldNotCompute();
10729
10730 // If this is an affine expression, the execution count of this branch is
10731 // the minimum unsigned root of the following equation:
10732 //
10733 // Start + Step*N = 0 (mod 2^BW)
10734 //
10735 // equivalent to:
10736 //
10737 // Step*N = -Start (mod 2^BW)
10738 //
10739 // where BW is the common bit width of Start and Step.
10740
10741 // Get the initial value for the loop.
10742 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
10743 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
10744
10745 if (!isLoopInvariant(Step, L))
10746 return getCouldNotCompute();
10747
10748 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
10749 // Specialize step for this loop so we get context sensitive facts below.
10750 const SCEV *StepWLG = applyLoopGuards(Step, Guards);
10751
10752 // For positive steps (counting up until unsigned overflow):
10753 // N = -Start/Step (as unsigned)
10754 // For negative steps (counting down to zero):
10755 // N = Start/-Step
10756 // First compute the unsigned distance from zero in the direction of Step.
10757 bool CountDown = isKnownNegative(StepWLG);
10758 if (!CountDown && !isKnownNonNegative(StepWLG))
10759 return getCouldNotCompute();
10760
10761 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
10762 // Handle unitary steps, which cannot wraparound.
10763 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10764 // N = Distance (as unsigned)
10765
10766 if (match(Step, m_CombineOr(m_scev_One(), m_scev_AllOnes()))) {
10767 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, Guards));
10768 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
10769
10770 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10771 // we end up with a loop whose backedge-taken count is n - 1. Detect this
10772 // case, and see if we can improve the bound.
10773 //
10774 // Explicitly handling this here is necessary because getUnsignedRange
10775 // isn't context-sensitive; it doesn't know that we only care about the
10776 // range inside the loop.
10777 const SCEV *Zero = getZero(Distance->getType());
10778 const SCEV *One = getOne(Distance->getType());
10779 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
10780 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
10781 // If Distance + 1 doesn't overflow, we can compute the maximum distance
10782 // as "unsigned_max(Distance + 1) - 1". Also apply the loop guards to
10783 // Distance + 1; the range of Distance itself may be a wrapped set even
10784 // when the guards bound Distance + 1 tightly.
10785 APInt Max = APIntOps::umin(
10786 getUnsignedRangeMax(applyLoopGuards(DistancePlusOne, Guards)),
10787 getUnsignedRangeMax(DistancePlusOne));
10788 MaxBECount = APIntOps::umin(MaxBECount, Max - 1);
10789 }
10790 return ExitLimit(Distance, getConstant(MaxBECount), Distance, false,
10791 Predicates);
10792 }
10793
10794 // If the condition controls loop exit (the loop exits only if the expression
10795 // is true) and the addition is no-wrap we can use unsigned divide to
10796 // compute the backedge count. In this case, the step may not divide the
10797 // distance, but we don't care because if the condition is "missed" the loop
10798 // will have undefined behavior due to wrapping.
10799 if (ControlsOnlyExit && AddRec->hasNoSelfWrap() &&
10800 loopHasNoAbnormalExits(AddRec->getLoop())) {
10801
10802 // If the stride is zero and the start is non-zero, the loop must be
10803 // infinite. In C++, most loops are finite by assumption, in which case the
10804 // step being zero implies UB must execute if the loop is entered.
10805 if (!(loopIsFiniteByAssumption(L) && isKnownNonZero(Start)) &&
10806 !isKnownNonZero(StepWLG))
10807 return getCouldNotCompute();
10808
10809 const SCEV *Exact =
10810 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10811 const SCEV *ConstantMax = getCouldNotCompute();
10812 if (Exact != getCouldNotCompute()) {
10813 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, Guards));
10814 ConstantMax =
10816 }
10817 const SCEV *SymbolicMax =
10818 isa<SCEVCouldNotCompute>(Exact) ? ConstantMax : Exact;
10819 return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
10820 }
10821
10822 // Solve the general equation.
10823 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
10824 if (!StepC || StepC->getValue()->isZero())
10825 return getCouldNotCompute();
10826 const SCEV *E = SolveLinEquationWithOverflow(
10827 StepC->getAPInt(), getNegativeSCEV(Start),
10828 AllowPredicates ? &Predicates : nullptr, *this, L);
10829
10830 const SCEV *M = E;
10831 if (E != getCouldNotCompute()) {
10832 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, Guards));
10833 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
10834 }
10835 auto *S = isa<SCEVCouldNotCompute>(E) ? M : E;
10836 return ExitLimit(E, M, S, false, Predicates);
10837}
10838
10839ScalarEvolution::ExitLimit
10840ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10841 // Loops that look like: while (X == 0) are very strange indeed. We don't
10842 // handle them yet except for the trivial case. This could be expanded in the
10843 // future as needed.
10844
10845 // If the value is a constant, check to see if it is known to be non-zero
10846 // already. If so, the backedge will execute zero times.
10847 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10848 if (!C->getValue()->isZero())
10849 return getZero(C->getType());
10850 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10851 }
10852
10853 // We could implement others, but I really doubt anyone writes loops like
10854 // this, and if they did, they would already be constant folded.
10855 return getCouldNotCompute();
10856}
10857
10858std::pair<const BasicBlock *, const BasicBlock *>
10859ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10860 const {
10861 // If the block has a unique predecessor, then there is no path from the
10862 // predecessor to the block that does not go through the direct edge
10863 // from the predecessor to the block.
10864 if (const BasicBlock *Pred = BB->getSinglePredecessor())
10865 return {Pred, BB};
10866
10867 // A loop's header is defined to be a block that dominates the loop.
10868 // If the header has a unique predecessor outside the loop, it must be
10869 // a block that has exactly one successor that can reach the loop.
10870 if (const Loop *L = LI.getLoopFor(BB))
10871 return {L->getLoopPredecessor(), L->getHeader()};
10872
10873 return {nullptr, BB};
10874}
10875
10876/// SCEV structural equivalence is usually sufficient for testing whether two
10877/// expressions are equal, however for the purposes of looking for a condition
10878/// guarding a loop, it can be useful to be a little more general, since a
10879/// front-end may have replicated the controlling expression.
10880static bool HasSameValue(const SCEV *A, const SCEV *B) {
10881 // Quick check to see if they are the same SCEV.
10882 if (A == B) return true;
10883
10884 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10885 // Not all instructions that are "identical" compute the same value. For
10886 // instance, two distinct alloca instructions allocating the same type are
10887 // identical and do not read memory; but compute distinct values.
10888 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
10889 };
10890
10891 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10892 // two different instructions with the same value. Check for this case.
10893 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
10894 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
10895 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
10896 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
10897 if (ComputesEqualValues(AI, BI))
10898 return true;
10899
10900 // Otherwise assume they may have a different value.
10901 return false;
10902}
10903
10904static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS) {
10905 const SCEV *Op0, *Op1;
10906 if (!match(S, m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))))
10907 return false;
10908 if (match(Op0, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10909 LHS = Op1;
10910 return true;
10911 }
10912 if (match(Op1, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10913 LHS = Op0;
10914 return true;
10915 }
10916 return false;
10917}
10918
10920 SCEVUse &RHS, unsigned Depth) {
10921 bool Changed = false;
10922 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
10923 // '0 != 0'.
10924 auto TrivialCase = [&](bool TriviallyTrue) {
10926 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
10927 return true;
10928 };
10929 // If we hit the max recursion limit bail out.
10930 if (Depth >= 3)
10931 return false;
10932
10933 const SCEV *NewLHS, *NewRHS;
10934 if (match(LHS, m_scev_c_Mul(m_SCEV(NewLHS), m_SCEVVScale())) &&
10935 match(RHS, m_scev_c_Mul(m_SCEV(NewRHS), m_SCEVVScale()))) {
10936 const SCEVMulExpr *LMul = cast<SCEVMulExpr>(LHS);
10937 const SCEVMulExpr *RMul = cast<SCEVMulExpr>(RHS);
10938
10939 // (X * vscale) pred (Y * vscale) ==> X pred Y
10940 // when both multiples are NSW.
10941 // (X * vscale) uicmp/eq/ne (Y * vscale) ==> X uicmp/eq/ne Y
10942 // when both multiples are NUW.
10943 if ((LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap()) ||
10944 (LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap() &&
10945 !ICmpInst::isSigned(Pred))) {
10946 LHS = NewLHS;
10947 RHS = NewRHS;
10948 Changed = true;
10949 }
10950 }
10951
10952 // Canonicalize a constant to the right side.
10953 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
10954 // Check for both operands constant.
10955 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
10956 if (!ICmpInst::compare(LHSC->getAPInt(), RHSC->getAPInt(), Pred))
10957 return TrivialCase(false);
10958 return TrivialCase(true);
10959 }
10960 // Otherwise swap the operands to put the constant on the right.
10961 std::swap(LHS, RHS);
10963 Changed = true;
10964 }
10965
10966 // (K + A) pred (K + B) --> A pred B
10967 // For equality, no flags are needed.
10968 // For signed, both adds must be NSW. For unsigned, both must be NUW.
10969 {
10970 const SCEVConstant *C = nullptr;
10971 if (match(LHS, m_scev_Add(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
10972 match(RHS, m_scev_Add(m_scev_Specific(C), m_SCEV(NewRHS)))) {
10973 const auto *LAdd = cast<SCEVAddExpr>(LHS);
10974 const auto *RAdd = cast<SCEVAddExpr>(RHS);
10975 if (ICmpInst::isEquality(Pred) ||
10976 (ICmpInst::isSigned(Pred) && LAdd->hasNoSignedWrap() &&
10977 RAdd->hasNoSignedWrap()) ||
10978 (ICmpInst::isUnsigned(Pred) && LAdd->hasNoUnsignedWrap() &&
10979 RAdd->hasNoUnsignedWrap())) {
10980 LHS = NewLHS;
10981 RHS = NewRHS;
10982 Changed = true;
10983 }
10984 }
10985 }
10986
10987 // (C * A) pred (C * B) --> A pred B
10988 // For equality predicates, both muls must be NUW or both must be NSW
10989 // (either suffices to make multiplication by C injective; C == 0 is
10990 // impossible because SCEV folds 0 * X to 0).
10991 // For signed ordering, C must be positive and both muls must be NSW.
10992 // For unsigned ordering, both muls must be NUW.
10993 {
10994 const SCEVConstant *C = nullptr;
10995 if (match(LHS, m_scev_Mul(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
10996 match(RHS, m_scev_Mul(m_scev_Specific(C), m_SCEV(NewRHS)))) {
10997 const auto *LMul = cast<SCEVMulExpr>(LHS);
10998 const auto *RMul = cast<SCEVMulExpr>(RHS);
10999 bool BothNUW = LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap();
11000 bool BothNSW = LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap();
11001 if ((ICmpInst::isEquality(Pred) && (BothNUW || BothNSW)) ||
11002 (ICmpInst::isSigned(Pred) && BothNSW &&
11003 C->getAPInt().isStrictlyPositive()) ||
11004 (ICmpInst::isUnsigned(Pred) && BothNUW)) {
11005 LHS = NewLHS;
11006 RHS = NewRHS;
11007 Changed = true;
11008 }
11009 }
11010 }
11011
11012 // If we're comparing an addrec with a value which is loop-invariant in the
11013 // addrec's loop, put the addrec on the left. Also make a dominance check,
11014 // as both operands could be addrecs loop-invariant in each other's loop.
11015 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
11016 const Loop *L = AR->getLoop();
11017 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
11018 std::swap(LHS, RHS);
11020 Changed = true;
11021 }
11022 }
11023
11024 // If there's a constant operand, canonicalize comparisons with boundary
11025 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
11026 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
11027 const APInt &RA = RC->getAPInt();
11028
11029 bool SimplifiedByConstantRange = false;
11030
11031 if (!ICmpInst::isEquality(Pred)) {
11033 if (ExactCR.isFullSet())
11034 return TrivialCase(true);
11035 if (ExactCR.isEmptySet())
11036 return TrivialCase(false);
11037
11038 APInt NewRHS;
11039 CmpInst::Predicate NewPred;
11040 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
11041 ICmpInst::isEquality(NewPred)) {
11042 // We were able to convert an inequality to an equality.
11043 Pred = NewPred;
11044 RHS = getConstant(NewRHS);
11045 Changed = SimplifiedByConstantRange = true;
11046 }
11047 }
11048
11049 if (!SimplifiedByConstantRange) {
11050 switch (Pred) {
11051 default:
11052 break;
11053 case ICmpInst::ICMP_EQ:
11054 case ICmpInst::ICMP_NE:
11055 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
11056 if (RA.isZero() && MatchBinarySub(LHS, LHS, RHS))
11057 Changed = true;
11058 break;
11059
11060 // The "Should have been caught earlier!" messages refer to the fact
11061 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
11062 // should have fired on the corresponding cases, and canonicalized the
11063 // check to trivial case.
11064
11065 case ICmpInst::ICMP_UGE:
11066 assert(!RA.isMinValue() && "Should have been caught earlier!");
11067 Pred = ICmpInst::ICMP_UGT;
11068 RHS = getConstant(RA - 1);
11069 Changed = true;
11070 break;
11071 case ICmpInst::ICMP_ULE:
11072 assert(!RA.isMaxValue() && "Should have been caught earlier!");
11073 Pred = ICmpInst::ICMP_ULT;
11074 RHS = getConstant(RA + 1);
11075 Changed = true;
11076 break;
11077 case ICmpInst::ICMP_SGE:
11078 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
11079 Pred = ICmpInst::ICMP_SGT;
11080 RHS = getConstant(RA - 1);
11081 Changed = true;
11082 break;
11083 case ICmpInst::ICMP_SLE:
11084 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
11085 Pred = ICmpInst::ICMP_SLT;
11086 RHS = getConstant(RA + 1);
11087 Changed = true;
11088 break;
11089 }
11090 }
11091 }
11092
11093 // a /u b == 0 => a < b
11094 // a /u b != 0 => a >= b
11095 if (ICmpInst::isEquality(Pred) && RHS->isZero() &&
11096 match(LHS, m_scev_UDiv(m_SCEV(LHS), m_SCEV(RHS)))) {
11098 Changed = true;
11099 }
11100
11101 // Check for obvious equality.
11102 if (HasSameValue(LHS, RHS)) {
11103 if (ICmpInst::isTrueWhenEqual(Pred))
11104 return TrivialCase(true);
11106 return TrivialCase(false);
11107 }
11108
11109 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
11110 // adding or subtracting 1 from one of the operands.
11111 switch (Pred) {
11112 case ICmpInst::ICMP_SLE:
11113 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
11114 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11116 Pred = ICmpInst::ICMP_SLT;
11117 Changed = true;
11118 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
11119 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
11121 Pred = ICmpInst::ICMP_SLT;
11122 Changed = true;
11123 }
11124 break;
11125 case ICmpInst::ICMP_SGE:
11126 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
11127 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
11129 Pred = ICmpInst::ICMP_SGT;
11130 Changed = true;
11131 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
11132 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11134 Pred = ICmpInst::ICMP_SGT;
11135 Changed = true;
11136 }
11137 break;
11138 case ICmpInst::ICMP_ULE:
11139 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
11140 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11142 Pred = ICmpInst::ICMP_ULT;
11143 Changed = true;
11144 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
11145 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
11146 Pred = ICmpInst::ICMP_ULT;
11147 Changed = true;
11148 }
11149 break;
11150 case ICmpInst::ICMP_UGE:
11151 // If RHS is an op we can fold the -1, try that first.
11152 // Otherwise prefer LHS to preserve the nuw flag.
11153 if ((isa<SCEVConstant>(RHS) ||
11155 isa<SCEVConstant>(cast<SCEVNAryExpr>(RHS)->getOperand(0)))) &&
11156 !getUnsignedRangeMin(RHS).isMinValue()) {
11157 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11158 Pred = ICmpInst::ICMP_UGT;
11159 Changed = true;
11160 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
11161 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11163 Pred = ICmpInst::ICMP_UGT;
11164 Changed = true;
11165 } else if (!getUnsignedRangeMin(RHS).isMinValue()) {
11166 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11167 Pred = ICmpInst::ICMP_UGT;
11168 Changed = true;
11169 }
11170 break;
11171 default:
11172 break;
11173 }
11174
11175 // TODO: More simplifications are possible here.
11176
11177 // Recursively simplify until we either hit a recursion limit or nothing
11178 // changes.
11179 if (Changed)
11180 (void)SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1);
11181
11182 return Changed;
11183}
11184
11186 return getSignedRangeMax(S).isNegative();
11187}
11188
11192
11194 return !getSignedRangeMin(S).isNegative();
11195}
11196
11200
11202 // Query push down for cases where the unsigned range is
11203 // less than sufficient.
11204 if (const auto *SExt = dyn_cast<SCEVSignExtendExpr>(S))
11205 return isKnownNonZero(SExt->getOperand(0));
11206 return getUnsignedRangeMin(S) != 0;
11207}
11208
11210 bool OrNegative) {
11211 auto NonRecursive = [OrNegative](const SCEV *S) {
11212 if (auto *C = dyn_cast<SCEVConstant>(S))
11213 return C->getAPInt().isPowerOf2() ||
11214 (OrNegative && C->getAPInt().isNegatedPowerOf2());
11215
11216 // vscale is a power-of-two.
11217 return isa<SCEVVScale>(S);
11218 };
11219
11220 if (NonRecursive(S))
11221 return true;
11222
11223 auto *Mul = dyn_cast<SCEVMulExpr>(S);
11224 if (!Mul)
11225 return false;
11226 return all_of(Mul->operands(), NonRecursive) && (OrZero || isKnownNonZero(S));
11227}
11228
11230 const SCEV *S, uint64_t M,
11232 if (M == 0)
11233 return false;
11234 if (M == 1)
11235 return true;
11236
11237 // For a constant, check that "S % M == 0".
11238 if (auto *Cst = dyn_cast<SCEVConstant>(S)) {
11239 APInt C = Cst->getAPInt();
11240 return C.urem(M) == 0;
11241 }
11242
11243 // Basic tests have failed.
11244 // Check "S % M == 0" at compile time and record runtime Assumptions.
11245 auto *STy = dyn_cast<IntegerType>(S->getType());
11246 const SCEV *SmodM =
11247 getURemExpr(S, getConstant(ConstantInt::get(STy, M, false)));
11248 const SCEV *Zero = getZero(STy);
11249
11250 // Check whether "S % M == 0" is known at compile time.
11251 if (isKnownPredicate(ICmpInst::ICMP_EQ, SmodM, Zero))
11252 return true;
11253
11254 // Check whether "S % M != 0" is known at compile time.
11255 if (isKnownPredicate(ICmpInst::ICMP_NE, SmodM, Zero))
11256 return false;
11257
11258 if (!Predicates)
11259 return false;
11260
11261 // Look through Add and AddRec expressions with nuw to improve the
11262 // precision of added predicates. S is a multiple of M if S starts with a
11263 // multiple of M and at every iteration step S only adds multiples of M.
11266 all_of(S->operands(),
11267 [&](SCEVUse Op) { return isKnownMultipleOf(Op, M, Predicates); }))
11268 return true;
11269
11270 // Similarly, look through Mul with nuw, where any operand being a
11271 // known-multiple is sufficient.
11272 if (auto *Mul = dyn_cast<SCEVMulExpr>(S))
11273 if (Mul->hasNoUnsignedWrap() && any_of(S->operands(), [&](SCEVUse Op) {
11274 return isKnownMultipleOf(Op, M, Predicates);
11275 }))
11276 return true;
11277
11278 // Similarly, look through MinMax, with no wrapping arithmetic to consider.
11279 if (isa<SCEVMinMaxExpr>(S) && all_of(S->operands(), [&](SCEVUse Op) {
11280 return isKnownMultipleOf(Op, M, Predicates);
11281 }))
11282 return true;
11283
11285
11286 // Detect redundant predicates.
11287 for (auto *A : *Predicates)
11288 if (A->implies(P, *this))
11289 return true;
11290
11291 // Only record non-redundant predicates.
11292 Predicates->push_back(P);
11293 return true;
11294}
11295
11297 return ((isKnownNonNegative(S1) && isKnownNonNegative(S2)) ||
11299}
11300
11301std::pair<const SCEV *, const SCEV *>
11303 // Compute SCEV on entry of loop L.
11304 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
11305 if (Start == getCouldNotCompute())
11306 return { Start, Start };
11307 // Compute post increment SCEV for loop L.
11308 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
11309 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
11310 return { Start, PostInc };
11311}
11312
11314 SCEVUse RHS) {
11315 // First collect all loops.
11317 getUsedLoops(LHS, LoopsUsed);
11318 getUsedLoops(RHS, LoopsUsed);
11319
11320 if (LoopsUsed.empty())
11321 return false;
11322
11323 // Domination relationship must be a linear order on collected loops.
11324#ifndef NDEBUG
11325 for (const auto *L1 : LoopsUsed)
11326 for (const auto *L2 : LoopsUsed)
11327 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
11328 DT.dominates(L2->getHeader(), L1->getHeader())) &&
11329 "Domination relationship is not a linear order");
11330#endif
11331
11332 const Loop *MDL =
11333 *llvm::max_element(LoopsUsed, [&](const Loop *L1, const Loop *L2) {
11334 return DT.properlyDominates(L1->getHeader(), L2->getHeader());
11335 });
11336
11337 // Get init and post increment value for LHS.
11338 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
11339 // if LHS contains unknown non-invariant SCEV then bail out.
11340 if (SplitLHS.first == getCouldNotCompute())
11341 return false;
11342 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
11343 // Get init and post increment value for RHS.
11344 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
11345 // if RHS contains unknown non-invariant SCEV then bail out.
11346 if (SplitRHS.first == getCouldNotCompute())
11347 return false;
11348 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
11349 // It is possible that init SCEV contains an invariant load but it does
11350 // not dominate MDL and is not available at MDL loop entry, so we should
11351 // check it here.
11352 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
11353 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
11354 return false;
11355
11356 // It seems backedge guard check is faster than entry one so in some cases
11357 // it can speed up whole estimation by short circuit
11358 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
11359 SplitRHS.second) &&
11360 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
11361}
11362
11364 SCEVUse RHS) {
11365 // Canonicalize the inputs first.
11366 (void)SimplifyICmpOperands(Pred, LHS, RHS);
11367
11368 return isKnownViaInduction(Pred, LHS, RHS) ||
11369 isKnownPredicateViaSplitting(Pred, LHS, RHS) ||
11370 isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
11371}
11372
11374 const SCEV *LHS,
11375 const SCEV *RHS) {
11376 if (isKnownPredicate(Pred, LHS, RHS))
11377 return true;
11379 return false;
11380 return std::nullopt;
11381}
11382
11384 const SCEV *RHS,
11385 const Instruction *CtxI) {
11386 // TODO: Analyze guards and assumes from Context's block.
11387 return isKnownPredicate(Pred, LHS, RHS) ||
11388 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
11389}
11390
11391std::optional<bool>
11393 const SCEV *RHS, const Instruction *CtxI) {
11394 std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
11395 if (KnownWithoutContext)
11396 return KnownWithoutContext;
11397
11398 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
11399 return true;
11401 CtxI->getParent(), ICmpInst::getInverseCmpPredicate(Pred), LHS, RHS))
11402 return false;
11403 return std::nullopt;
11404}
11405
11407 const SCEVAddRecExpr *LHS,
11408 const SCEV *RHS) {
11409 const Loop *L = LHS->getLoop();
11410 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
11411 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
11412}
11413
11414std::optional<ScalarEvolution::MonotonicPredicateType>
11416 ICmpInst::Predicate Pred) {
11417 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
11418
11419#ifndef NDEBUG
11420 // Verify an invariant: inverting the predicate should turn a monotonically
11421 // increasing change to a monotonically decreasing one, and vice versa.
11422 if (Result) {
11423 auto ResultSwapped =
11424 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
11425
11426 assert(*ResultSwapped != *Result &&
11427 "monotonicity should flip as we flip the predicate");
11428 }
11429#endif
11430
11431 return Result;
11432}
11433
11434std::optional<ScalarEvolution::MonotonicPredicateType>
11435ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
11436 ICmpInst::Predicate Pred) {
11437 // A zero step value for LHS means the induction variable is essentially a
11438 // loop invariant value. We don't really depend on the predicate actually
11439 // flipping from false to true (for increasing predicates, and the other way
11440 // around for decreasing predicates), all we care about is that *if* the
11441 // predicate changes then it only changes from false to true.
11442 //
11443 // A zero step value in itself is not very useful, but there may be places
11444 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
11445 // as general as possible.
11446
11447 // Only handle LE/LT/GE/GT predicates.
11448 if (!ICmpInst::isRelational(Pred))
11449 return std::nullopt;
11450
11451 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
11452 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
11453 "Should be greater or less!");
11454
11455 // Check that AR does not wrap.
11456 if (ICmpInst::isUnsigned(Pred)) {
11457 if (!LHS->hasNoUnsignedWrap())
11458 return std::nullopt;
11460 }
11461 assert(ICmpInst::isSigned(Pred) &&
11462 "Relational predicate is either signed or unsigned!");
11463 if (!LHS->hasNoSignedWrap())
11464 return std::nullopt;
11465
11466 const SCEV *Step = LHS->getStepRecurrence(*this);
11467
11468 if (isKnownNonNegative(Step))
11470
11471 if (isKnownNonPositive(Step))
11473
11474 return std::nullopt;
11475}
11476
11477std::optional<ScalarEvolution::LoopInvariantPredicate>
11479 const SCEV *RHS, const Loop *L,
11480 const Instruction *CtxI) {
11481 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11482 if (!isLoopInvariant(RHS, L)) {
11483 if (!isLoopInvariant(LHS, L))
11484 return std::nullopt;
11485
11486 std::swap(LHS, RHS);
11488 }
11489
11490 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11491 if (!ArLHS || ArLHS->getLoop() != L)
11492 return std::nullopt;
11493
11494 // Even if both are valid, we need to consistently choose the unsigned or the
11495 // signed predicate for the monotonicity and backedge checks below, not
11496 // mixtures of both. For now, prefer the unsigned predicate.
11497 Pred = Pred.dropSameSign();
11498 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
11499 if (!MonotonicType)
11500 return std::nullopt;
11501 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
11502 // true as the loop iterates, and the backedge is control dependent on
11503 // "ArLHS `Pred` RHS" == true then we can reason as follows:
11504 //
11505 // * if the predicate was false in the first iteration then the predicate
11506 // is never evaluated again, since the loop exits without taking the
11507 // backedge.
11508 // * if the predicate was true in the first iteration then it will
11509 // continue to be true for all future iterations since it is
11510 // monotonically increasing.
11511 //
11512 // For both the above possibilities, we can replace the loop varying
11513 // predicate with its value on the first iteration of the loop (which is
11514 // loop invariant).
11515 //
11516 // A similar reasoning applies for a monotonically decreasing predicate, by
11517 // replacing true with false and false with true in the above two bullets.
11519 auto P = Increasing ? Pred : ICmpInst::getInverseCmpPredicate(Pred);
11520
11521 if (isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
11523 RHS);
11524
11525 if (!CtxI)
11526 return std::nullopt;
11527 // Try to prove via context.
11528 // TODO: Support other cases.
11529 switch (Pred) {
11530 default:
11531 break;
11532 case ICmpInst::ICMP_ULE:
11533 case ICmpInst::ICMP_ULT: {
11534 assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!");
11535 // Given preconditions
11536 // (1) ArLHS does not cross the border of positive and negative parts of
11537 // range because of:
11538 // - Positive step; (TODO: lift this limitation)
11539 // - nuw - does not cross zero boundary;
11540 // - nsw - does not cross SINT_MAX boundary;
11541 // (2) ArLHS <s RHS
11542 // (3) RHS >=s 0
11543 // we can replace the loop variant ArLHS <u RHS condition with loop
11544 // invariant Start(ArLHS) <u RHS.
11545 //
11546 // Because of (1) there are two options:
11547 // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
11548 // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
11549 // It means that ArLHS <s RHS <=> ArLHS <u RHS.
11550 // Because of (2) ArLHS <u RHS is trivially true.
11551 // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
11552 // We can strengthen this to Start(ArLHS) <u RHS.
11553 auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
11554 if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
11555 isKnownPositive(ArLHS->getStepRecurrence(*this)) &&
11556 isKnownNonNegative(RHS) &&
11557 isKnownPredicateAt(SignFlippedPred, ArLHS, RHS, CtxI))
11559 RHS);
11560 }
11561 }
11562
11563 return std::nullopt;
11564}
11565
11566std::optional<ScalarEvolution::LoopInvariantPredicate>
11568 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11569 const Instruction *CtxI, const SCEV *MaxIter) {
11571 Pred, LHS, RHS, L, CtxI, MaxIter))
11572 return LIP;
11573 if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
11574 // Number of iterations expressed as UMIN isn't always great for expressing
11575 // the value on the last iteration. If the straightforward approach didn't
11576 // work, try the following trick: if the a predicate is invariant for X, it
11577 // is also invariant for umin(X, ...). So try to find something that works
11578 // among subexpressions of MaxIter expressed as umin.
11579 for (SCEVUse Op : UMin->operands())
11581 Pred, LHS, RHS, L, CtxI, Op))
11582 return LIP;
11583 return std::nullopt;
11584}
11585
11586std::optional<ScalarEvolution::LoopInvariantPredicate>
11588 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11589 const Instruction *CtxI, const SCEV *MaxIter) {
11590 // Try to prove the following set of facts:
11591 // - The predicate is monotonic in the iteration space.
11592 // - If the check does not fail on the 1st iteration:
11593 // - No overflow will happen during first MaxIter iterations;
11594 // - It will not fail on the MaxIter'th iteration.
11595 // If the check does fail on the 1st iteration, we leave the loop and no
11596 // other checks matter.
11597
11598 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11599 if (!isLoopInvariant(RHS, L)) {
11600 if (!isLoopInvariant(LHS, L))
11601 return std::nullopt;
11602
11603 std::swap(LHS, RHS);
11605 }
11606
11607 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
11608 if (!AR || AR->getLoop() != L)
11609 return std::nullopt;
11610
11611 // Even if both are valid, we need to consistently chose the unsigned or the
11612 // signed predicate below, not mixtures of both. For now, prefer the unsigned
11613 // predicate.
11614 Pred = Pred.dropSameSign();
11615
11616 // The predicate must be relational (i.e. <, <=, >=, >).
11617 if (!ICmpInst::isRelational(Pred))
11618 return std::nullopt;
11619
11620 // TODO: Support steps other than +/- 1.
11621 const SCEV *Step = AR->getStepRecurrence(*this);
11622 auto *One = getOne(Step->getType());
11623 auto *MinusOne = getNegativeSCEV(One);
11624 if (Step != One && Step != MinusOne)
11625 return std::nullopt;
11626
11627 // Type mismatch here means that MaxIter is potentially larger than max
11628 // unsigned value in start type, which mean we cannot prove no wrap for the
11629 // indvar.
11630 if (AR->getType() != MaxIter->getType())
11631 return std::nullopt;
11632
11633 // Value of IV on suggested last iteration.
11634 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
11635 // Does it still meet the requirement?
11636 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
11637 return std::nullopt;
11638 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
11639 // not exceed max unsigned value of this type), this effectively proves
11640 // that there is no wrap during the iteration. To prove that there is no
11641 // signed/unsigned wrap, we need to check that
11642 // Start <= Last for step = 1 or Start >= Last for step = -1.
11643 ICmpInst::Predicate NoOverflowPred =
11645 if (Step == MinusOne)
11646 NoOverflowPred = ICmpInst::getSwappedPredicate(NoOverflowPred);
11647 const SCEV *Start = AR->getStart();
11648 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
11649 return std::nullopt;
11650
11651 // Everything is fine.
11652 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
11653}
11654
11655bool ScalarEvolution::isKnownPredicateViaConstantRanges(CmpPredicate Pred,
11656 SCEVUse LHS,
11657 SCEVUse RHS) {
11658 if (HasSameValue(LHS, RHS))
11659 return ICmpInst::isTrueWhenEqual(Pred);
11660
11661 auto CheckRange = [&](bool IsSigned) {
11662 auto RangeLHS = IsSigned ? getSignedRange(LHS) : getUnsignedRange(LHS);
11663 auto RangeRHS = IsSigned ? getSignedRange(RHS) : getUnsignedRange(RHS);
11664 return RangeLHS.icmp(Pred, RangeRHS);
11665 };
11666
11667 // The check at the top of the function catches the case where the values are
11668 // known to be equal.
11669 if (Pred == CmpInst::ICMP_EQ)
11670 return false;
11671
11672 if (Pred == CmpInst::ICMP_NE) {
11673 if (CheckRange(true) || CheckRange(false))
11674 return true;
11675 auto *Diff = getMinusSCEV(LHS, RHS);
11676 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
11677 }
11678
11679 return CheckRange(CmpInst::isSigned(Pred));
11680}
11681
11682bool ScalarEvolution::isKnownPredicateViaNoOverflow(CmpPredicate Pred,
11684 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
11685 // C1 and C2 are constant integers. If either X or Y are not add expressions,
11686 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
11687 // OutC1 and OutC2.
11688 auto MatchBinaryAddToConst = [this](SCEVUse X, SCEVUse Y, APInt &OutC1,
11689 APInt &OutC2, SCEVFlags ExpectedFlags) {
11690 SCEVUse XNonConstOp, XConstOp;
11691 SCEVUse YNonConstOp, YConstOp;
11692 SCEVFlags XFlagsPresent;
11693 SCEVFlags YFlagsPresent;
11694
11695 // Use nullptr for 0, to avoid creating a zero SCEV.
11696 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
11697 XConstOp = nullptr;
11698 XNonConstOp = X;
11699 XFlagsPresent = ExpectedFlags;
11700 }
11701 if (XConstOp && !isa<SCEVConstant>(XConstOp))
11702 return false;
11703
11704 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
11705 YConstOp = nullptr;
11706 YNonConstOp = Y;
11707 YFlagsPresent = ExpectedFlags;
11708 }
11709
11710 if (YNonConstOp != XNonConstOp)
11711 return false;
11712
11713 if (YConstOp && !isa<SCEVConstant>(YConstOp))
11714 return false;
11715
11716 // When matching ADDs with NUW flags (and unsigned predicates), only the
11717 // second ADD (with the larger constant) requires NUW.
11718 if ((YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11719 return false;
11721 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) {
11722 return false;
11723 }
11724
11725 OutC1 = XConstOp ? cast<SCEVConstant>(XConstOp)->getAPInt()
11726 : APInt::getZero(getTypeSizeInBits(X->getType()));
11727 OutC2 = YConstOp ? cast<SCEVConstant>(YConstOp)->getAPInt()
11728 : APInt::getZero(getTypeSizeInBits(Y->getType()));
11729
11730 return true;
11731 };
11732
11733 APInt C1;
11734 APInt C2;
11735
11736 switch (Pred) {
11737 default:
11738 break;
11739
11740 case ICmpInst::ICMP_SGE:
11741 std::swap(LHS, RHS);
11742 [[fallthrough]];
11743 case ICmpInst::ICMP_SLE:
11744 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
11745 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
11746 return true;
11747
11748 break;
11749
11750 case ICmpInst::ICMP_SGT:
11751 std::swap(LHS, RHS);
11752 [[fallthrough]];
11753 case ICmpInst::ICMP_SLT:
11754 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
11755 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
11756 return true;
11757
11758 break;
11759
11760 case ICmpInst::ICMP_UGE:
11761 std::swap(LHS, RHS);
11762 [[fallthrough]];
11763 case ICmpInst::ICMP_ULE:
11764 // (X + C1) u<= (X + C2)<nuw> for C1 u<= C2.
11765 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ule(C2))
11766 return true;
11767
11768 break;
11769
11770 case ICmpInst::ICMP_UGT:
11771 std::swap(LHS, RHS);
11772 [[fallthrough]];
11773 case ICmpInst::ICMP_ULT:
11774 // (X + C1) u< (X + C2)<nuw> if C1 u< C2.
11775 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ult(C2))
11776 return true;
11777 break;
11778 }
11779
11780 return false;
11781}
11782
11783bool ScalarEvolution::isKnownPredicateViaSplitting(CmpPredicate Pred,
11785 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
11786 return false;
11787
11788 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
11789 // the stack can result in exponential time complexity.
11790 SaveAndRestore Restore(ProvingSplitPredicate, true);
11791
11792 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
11793 //
11794 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
11795 // isKnownPredicate. isKnownPredicate is more powerful, but also more
11796 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
11797 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
11798 // use isKnownPredicate later if needed.
11799 return isKnownNonNegative(RHS) &&
11802}
11803
11804bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, CmpPredicate Pred,
11805 const SCEV *LHS, const SCEV *RHS) {
11806 // No need to even try if we know the module has no guards.
11807 if (!HasGuards)
11808 return false;
11809
11810 return any_of(*BB, [&](const Instruction &I) {
11811 using namespace llvm::PatternMatch;
11812
11813 Value *Condition;
11815 m_Value(Condition))) &&
11816 isImpliedCond(Pred, LHS, RHS, Condition, false);
11817 });
11818}
11819
11820/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
11821/// protected by a conditional between LHS and RHS. This is used to
11822/// to eliminate casts.
11824 CmpPredicate Pred,
11825 const SCEV *LHS,
11826 const SCEV *RHS) {
11827 // Interpret a null as meaning no loop, where there is obviously no guard
11828 // (interprocedural conditions notwithstanding). Do not bother about
11829 // unreachable loops.
11830 if (!L || !DT.isReachableFromEntry(L->getHeader()))
11831 return true;
11832
11833 if (Opts.scev_verify_ir)
11834 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
11835 "This cannot be done on broken IR!");
11836
11837
11838 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11839 return true;
11840
11841 BasicBlock *Latch = L->getLoopLatch();
11842 if (!Latch)
11843 return false;
11844
11845 CondBrInst *LoopContinuePredicate =
11847 if (LoopContinuePredicate &&
11848 isImpliedCond(Pred, LHS, RHS, LoopContinuePredicate->getCondition(),
11849 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
11850 return true;
11851
11852 // We don't want more than one activation of the following loops on the stack
11853 // -- that can lead to O(n!) time complexity.
11854 if (WalkingBEDominatingConds)
11855 return false;
11856
11857 SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
11858
11859 // See if we can exploit a trip count to prove the predicate.
11860 const auto &BETakenInfo = getBackedgeTakenInfo(L);
11861 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
11862 if (LatchBECount != getCouldNotCompute()) {
11863 // We know that Latch branches back to the loop header exactly
11864 // LatchBECount times. This means the backdege condition at Latch is
11865 // equivalent to "{0,+,1} u< LatchBECount".
11866 Type *Ty = LatchBECount->getType();
11867 auto NoWrapFlags = SCEVFlags(SCEV::FlagNUW | SCEV::FlagNW);
11868 const SCEV *LoopCounter =
11869 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
11870 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
11871 LatchBECount))
11872 return true;
11873 }
11874
11875 // Check conditions due to any @llvm.assume intrinsics.
11876 for (auto &AssumeVH : AC.assumptions()) {
11877 if (!AssumeVH)
11878 continue;
11879 auto *CI = cast<CallInst>(AssumeVH);
11880 if (!DT.dominates(CI, Latch->getTerminator()))
11881 continue;
11882
11883 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
11884 return true;
11885 }
11886
11887 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
11888 return true;
11889
11890 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
11891 DTN != HeaderDTN; DTN = DTN->getIDom()) {
11892 assert(DTN && "should reach the loop header before reaching the root!");
11893
11894 BasicBlock *BB = DTN->getBlock();
11895 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
11896 return true;
11897
11898 BasicBlock *PBB = BB->getSinglePredecessor();
11899 if (!PBB)
11900 continue;
11901
11903 if (!ContBr || ContBr->getSuccessor(0) == ContBr->getSuccessor(1))
11904 continue;
11905
11906 // If we have an edge `E` within the loop body that dominates the only
11907 // latch, the condition guarding `E` also guards the backedge. This
11908 // reasoning works only for loops with a single latch.
11909 // We're constructively (and conservatively) enumerating edges within the
11910 // loop body that dominate the latch. The dominator tree better agree
11911 // with us on this:
11912 assert(DT.dominates(BasicBlockEdge(PBB, BB), Latch) && "should be!");
11913 if (isImpliedCond(Pred, LHS, RHS, ContBr->getCondition(),
11914 BB != ContBr->getSuccessor(0)))
11915 return true;
11916 }
11917
11918 return false;
11919}
11920
11922 CmpPredicate Pred,
11923 const SCEV *LHS,
11924 const SCEV *RHS) {
11925 // Do not bother proving facts for unreachable code.
11926 if (!DT.isReachableFromEntry(BB))
11927 return true;
11928 if (Opts.scev_verify_ir)
11929 assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
11930 "This cannot be done on broken IR!");
11931
11932 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
11933 // the facts (a >= b && a != b) separately. A typical situation is when the
11934 // non-strict comparison is known from ranges and non-equality is known from
11935 // dominating predicates. If we are proving strict comparison, we always try
11936 // to prove non-equality and non-strict comparison separately.
11937 CmpPredicate NonStrictPredicate = ICmpInst::getNonStrictCmpPredicate(Pred);
11938 const bool ProvingStrictComparison =
11939 Pred != NonStrictPredicate.dropSameSign();
11940 bool ProvedNonStrictComparison = false;
11941 bool ProvedNonEquality = false;
11942
11943 auto SplitAndProve = [&](std::function<bool(CmpPredicate)> Fn) -> bool {
11944 if (!ProvedNonStrictComparison)
11945 ProvedNonStrictComparison = Fn(NonStrictPredicate);
11946 if (!ProvedNonEquality)
11947 ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
11948 if (ProvedNonStrictComparison && ProvedNonEquality)
11949 return true;
11950 return false;
11951 };
11952
11953 if (ProvingStrictComparison) {
11954 auto ProofFn = [&](CmpPredicate P) {
11955 return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
11956 };
11957 if (SplitAndProve(ProofFn))
11958 return true;
11959 }
11960
11961 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
11962 auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
11963 const Instruction *CtxI = &BB->front();
11964 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
11965 return true;
11966 if (ProvingStrictComparison) {
11967 auto ProofFn = [&](CmpPredicate P) {
11968 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
11969 };
11970 if (SplitAndProve(ProofFn))
11971 return true;
11972 }
11973 return false;
11974 };
11975
11976 // Starting at the block's predecessor, climb up the predecessor chain, as long
11977 // as there are predecessors that can be found that have unique successors
11978 // leading to the original block.
11979 const Loop *ContainingLoop = LI.getLoopFor(BB);
11980 const BasicBlock *PredBB;
11981 if (ContainingLoop && ContainingLoop->getHeader() == BB)
11982 PredBB = ContainingLoop->getLoopPredecessor();
11983 else
11984 PredBB = BB->getSinglePredecessor();
11985 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
11986 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
11987 const CondBrInst *BlockEntryPredicate =
11988 dyn_cast<CondBrInst>(Pair.first->getTerminator());
11989 if (!BlockEntryPredicate)
11990 continue;
11991
11992 if (ProveViaCond(BlockEntryPredicate->getCondition(),
11993 BlockEntryPredicate->getSuccessor(0) != Pair.second))
11994 return true;
11995 }
11996
11997 // Check conditions due to any @llvm.assume intrinsics.
11998 for (auto &AssumeVH : AC.assumptions()) {
11999 if (!AssumeVH)
12000 continue;
12001 auto *CI = cast<CallInst>(AssumeVH);
12002 if (!DT.dominates(CI, BB))
12003 continue;
12004
12005 if (ProveViaCond(CI->getArgOperand(0), false))
12006 return true;
12007 }
12008
12009 // Check conditions due to any @llvm.experimental.guard intrinsics.
12010 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
12011 F.getParent(), Intrinsic::experimental_guard);
12012 if (GuardDecl)
12013 for (const auto *GU : GuardDecl->users())
12014 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
12015 if (Guard->getFunction() == BB->getParent() && DT.dominates(Guard, BB))
12016 if (ProveViaCond(Guard->getArgOperand(0), false))
12017 return true;
12018 return false;
12019}
12020
12022 const SCEV *LHS,
12023 const SCEV *RHS) {
12024 // Interpret a null as meaning no loop, where there is obviously no guard
12025 // (interprocedural conditions notwithstanding).
12026 if (!L)
12027 return false;
12028
12029 // Both LHS and RHS must be available at loop entry.
12031 "LHS is not available at Loop Entry");
12033 "RHS is not available at Loop Entry");
12034
12035 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
12036 return true;
12037
12038 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
12039}
12040
12041bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12042 const SCEV *RHS,
12043 const Value *FoundCondValue, bool Inverse,
12044 const Instruction *CtxI) {
12045 // False conditions implies anything. Do not bother analyzing it further.
12046 if (FoundCondValue ==
12047 ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
12048 return true;
12049
12050 if (!PendingLoopPredicates.insert(FoundCondValue).second)
12051 return false;
12052
12053 llvm::scope_exit ClearOnExit(
12054 [&]() { PendingLoopPredicates.erase(FoundCondValue); });
12055
12056 // Recursively handle And and Or conditions.
12057 const Value *Op0, *Op1;
12058 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
12059 if (!Inverse)
12060 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12061 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12062 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
12063 if (Inverse)
12064 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12065 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12066 }
12067
12068 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
12069 if (!ICI) return false;
12070
12071 // Now that we found a conditional branch that dominates the loop or controls
12072 // the loop latch. Check to see if it is the comparison we are looking for.
12073 CmpPredicate FoundPred;
12074 if (Inverse)
12075 FoundPred = ICI->getInverseCmpPredicate();
12076 else
12077 FoundPred = ICI->getCmpPredicate();
12078
12079 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
12080 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
12081
12082 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
12083}
12084
12085bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12086 const SCEV *RHS, CmpPredicate FoundPred,
12087 const SCEV *FoundLHS, const SCEV *FoundRHS,
12088 const Instruction *CtxI) {
12089 // Balance the types.
12090 if (getTypeSizeInBits(LHS->getType()) <
12091 getTypeSizeInBits(FoundLHS->getType())) {
12092 // For unsigned and equality predicates, try to prove that both found
12093 // operands fit into narrow unsigned range. If so, try to prove facts in
12094 // narrow types.
12095 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
12096 !FoundRHS->getType()->isPointerTy()) {
12097 auto *NarrowType = LHS->getType();
12098 auto *WideType = FoundLHS->getType();
12099 auto BitWidth = getTypeSizeInBits(NarrowType);
12100 const SCEV *MaxValue = getZeroExtendExpr(
12102 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
12103 MaxValue) &&
12104 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
12105 MaxValue)) {
12106 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
12107 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
12108 // We cannot preserve samesign after truncation.
12109 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred.dropSameSign(),
12110 TruncFoundLHS, TruncFoundRHS, CtxI))
12111 return true;
12112 }
12113 }
12114
12115 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
12116 return false;
12117 if (CmpInst::isSigned(Pred)) {
12118 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
12119 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
12120 } else {
12121 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
12122 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
12123 }
12124 } else if (getTypeSizeInBits(LHS->getType()) >
12125 getTypeSizeInBits(FoundLHS->getType())) {
12126 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
12127 return false;
12128 if (CmpInst::isSigned(FoundPred)) {
12129 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
12130 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
12131 } else {
12132 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
12133 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
12134 }
12135 }
12136 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
12137 FoundRHS, CtxI);
12138}
12139
12140bool ScalarEvolution::isImpliedCondBalancedTypes(
12141 CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, CmpPredicate FoundPred,
12142 SCEVUse FoundLHS, SCEVUse FoundRHS, const Instruction *CtxI) {
12144 getTypeSizeInBits(FoundLHS->getType()) &&
12145 "Types should be balanced!");
12146 // Canonicalize the query to match the way instcombine will have
12147 // canonicalized the comparison.
12148 if (SimplifyICmpOperands(Pred, LHS, RHS))
12149 if (LHS == RHS)
12150 return CmpInst::isTrueWhenEqual(Pred);
12151 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
12152 if (FoundLHS == FoundRHS)
12153 return CmpInst::isFalseWhenEqual(FoundPred);
12154
12155 // Check to see if we can make the LHS or RHS match.
12156 if (LHS == FoundRHS || RHS == FoundLHS) {
12157 if (isa<SCEVConstant>(RHS)) {
12158 std::swap(FoundLHS, FoundRHS);
12159 FoundPred = ICmpInst::getSwappedCmpPredicate(FoundPred);
12160 } else {
12161 std::swap(LHS, RHS);
12163 }
12164 }
12165
12166 // Check whether the found predicate is the same as the desired predicate.
12167 if (auto P = CmpPredicate::getMatching(FoundPred, Pred))
12168 return isImpliedCondOperands(*P, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12169
12170 // Check whether swapping the found predicate makes it the same as the
12171 // desired predicate.
12172 if (auto P = CmpPredicate::getMatching(
12173 ICmpInst::getSwappedCmpPredicate(FoundPred), Pred)) {
12174 // We can write the implication
12175 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS
12176 // using one of the following ways:
12177 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS
12178 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS
12179 // Both require swapping the operands of one condition. Don't do this if it
12180 // would break canonical constant/addrec ordering.
12182 return isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P), RHS,
12183 LHS, FoundLHS, FoundRHS, CtxI);
12184 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
12185 return isImpliedCondOperands(*P, LHS, RHS, FoundRHS, FoundLHS, CtxI);
12186
12187 return false;
12188 }
12189
12190 // Try the query as is and with its operands swapped. E.g. "x >s -1" is
12191 // tried as "-1 <s x" too, to match the found condition "x <u y".
12192 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
12194 return CmpInst::isRelational(P2) &&
12196 };
12197 if (IsSignFlippedPredicate(Pred, FoundPred) &&
12198 isImpliedCondViaSignFlippedPred(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12199 return true;
12200 CmpPredicate SwappedPred = ICmpInst::getSwappedCmpPredicate(Pred);
12201 if (IsSignFlippedPredicate(SwappedPred, FoundPred) &&
12202 isImpliedCondViaSignFlippedPred(SwappedPred, RHS, LHS, FoundLHS, FoundRHS,
12203 CtxI))
12204 return true;
12205
12206 // Check if we can make progress by sharpening ranges.
12207 if (FoundPred == ICmpInst::ICMP_NE &&
12208 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
12209
12210 const SCEVConstant *C = nullptr;
12211 const SCEV *V = nullptr;
12212
12213 if (isa<SCEVConstant>(FoundLHS)) {
12214 C = cast<SCEVConstant>(FoundLHS);
12215 V = FoundRHS;
12216 } else {
12217 C = cast<SCEVConstant>(FoundRHS);
12218 V = FoundLHS;
12219 }
12220
12221 // The guarding predicate tells us that C != V. If the known range
12222 // of V is [C, t), we can sharpen the range to [C + 1, t). The
12223 // range we consider has to correspond to same signedness as the
12224 // predicate we're interested in folding.
12225
12226 APInt Min = ICmpInst::isSigned(Pred) ?
12228
12229 if (Min == C->getAPInt()) {
12230 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
12231 // This is true even if (Min + 1) wraps around -- in case of
12232 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
12233
12234 APInt SharperMin = Min + 1;
12235
12236 switch (Pred) {
12237 case ICmpInst::ICMP_SGE:
12238 case ICmpInst::ICMP_UGE:
12239 // We know V `Pred` SharperMin. If this implies LHS `Pred`
12240 // RHS, we're done.
12241 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
12242 CtxI))
12243 return true;
12244 [[fallthrough]];
12245
12246 case ICmpInst::ICMP_SGT:
12247 case ICmpInst::ICMP_UGT:
12248 // We know from the range information that (V `Pred` Min ||
12249 // V == Min). We know from the guarding condition that !(V
12250 // == Min). This gives us
12251 //
12252 // V `Pred` Min || V == Min && !(V == Min)
12253 // => V `Pred` Min
12254 //
12255 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
12256
12257 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
12258 return true;
12259 break;
12260
12261 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
12262 case ICmpInst::ICMP_SLE:
12263 case ICmpInst::ICMP_ULE:
12264 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12265 LHS, V, getConstant(SharperMin), CtxI))
12266 return true;
12267 [[fallthrough]];
12268
12269 case ICmpInst::ICMP_SLT:
12270 case ICmpInst::ICMP_ULT:
12271 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12272 LHS, V, getConstant(Min), CtxI))
12273 return true;
12274 break;
12275
12276 default:
12277 // No change
12278 break;
12279 }
12280 }
12281 }
12282
12283 // Check whether the actual condition is beyond sufficient.
12284 if (FoundPred == ICmpInst::ICMP_EQ)
12285 if (ICmpInst::isTrueWhenEqual(Pred))
12286 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12287 return true;
12288 if (Pred == ICmpInst::ICMP_NE)
12289 if (!ICmpInst::isTrueWhenEqual(FoundPred))
12290 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12291 return true;
12292
12293 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS))
12294 return true;
12295
12296 // Otherwise assume the worst.
12297 return false;
12298}
12299
12300bool ScalarEvolution::isImpliedCondViaSignFlippedPred(
12301 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12302 const SCEV *FoundRHS, const Instruction *CtxI) {
12303 CmpPredicate FoundPred = ICmpInst::getFlippedSignednessPredicate(Pred);
12304 // Unsigned comparison is the same as signed comparison when both the
12305 // operands are non-negative or negative.
12306 if (haveSameSign(FoundLHS, FoundRHS) &&
12307 isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12308 return true;
12309 // Canonicalize both conditions to "le/lt".
12310 if (ICmpInst::isGT(Pred) || ICmpInst::isGE(Pred)) {
12312 FoundPred = ICmpInst::getSwappedCmpPredicate(FoundPred);
12313 std::swap(LHS, RHS);
12314 std::swap(FoundLHS, FoundRHS);
12315 }
12316 assert((ICmpInst::isLT(Pred) || ICmpInst::isLE(Pred)) && "Must be!");
12317 assert((ICmpInst::isLT(FoundPred) || ICmpInst::isLE(FoundPred)) &&
12318 "Must be!");
12319 if (ICmpInst::isSigned(Pred)) {
12320 // Use implication:
12321 // x <u y && y <=u 2^(n-1) --> x >=s 0,
12322 // x <=u y && y <u 2^(n-1) --> x >=s 0,
12323 // where n is the bit width of x and y.
12324 // In both cases x <u 2^(n-1), so x >=s 0.
12325 // y <=u 2^(n-1) means y >=s 0 or y == INT_MIN.
12326 // If the implication's left part holds, try proving the query from x >=s
12327 // 0.
12328 Type *Ty = FoundLHS->getType();
12329 unsigned BitWidth = getTypeSizeInBits(Ty);
12330 const SCEV *SignedMin = getConstant(APInt::getSignedMinValue(BitWidth));
12331 CmpPredicate BoundPred =
12333 if (isKnownViaNonRecursiveReasoning(BoundPred, FoundRHS, SignedMin)) {
12334 // x >=s 0, written as 0 <=s x, or as -1 <s x to match a strict query.
12335 const SCEV *Bound = ICmpInst::isLE(Pred) ? getZero(Ty) : getMinusOne(Ty);
12336 if (isImpliedCondOperands(Pred, LHS, RHS, Bound, FoundLHS, CtxI))
12337 return true;
12338 }
12339 }
12341 // Use implication:
12342 // x <u y && y >=s 0 --> x <s y.
12343 // If we can prove the left part, the right part is also proven.
12344 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
12345 return true;
12346 }
12348 // Use implication:
12349 // x <s y && y <s 0 --> x <u y.
12350 // If we can prove the left part, the right part is also proven.
12351 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
12352 return true;
12353 }
12354 return false;
12355}
12356
12357bool ScalarEvolution::splitBinaryAdd(SCEVUse Expr, SCEVUse &L, SCEVUse &R,
12358 SCEVFlags &Flags) {
12359 if (!match(Expr, m_scev_Add(m_SCEV(L), m_SCEV(R))))
12360 return false;
12361
12362 Flags = cast<SCEVAddExpr>(Expr)->getNoWrapFlags();
12363 return true;
12364}
12365
12366std::optional<APInt>
12368 // We avoid subtracting expressions here because this function is usually
12369 // fairly deep in the call stack (i.e. is called many times).
12370
12371 unsigned BW = getTypeSizeInBits(More->getType());
12372 APInt Diff(BW, 0);
12373 APInt DiffMul(BW, 1);
12374 // Try various simplifications to reduce the difference to a constant. Limit
12375 // the number of allowed simplifications to keep compile-time low.
12376 for (unsigned I = 0; I < 8; ++I) {
12377 if (More == Less)
12378 return Diff;
12379
12380 // Reduce addrecs with identical steps to their start value.
12382 const auto *LAR = cast<SCEVAddRecExpr>(Less);
12383 const auto *MAR = cast<SCEVAddRecExpr>(More);
12384
12385 if (LAR->getLoop() != MAR->getLoop())
12386 return std::nullopt;
12387
12388 // We look at affine expressions only; not for correctness but to keep
12389 // getStepRecurrence cheap.
12390 if (!LAR->isAffine() || !MAR->isAffine())
12391 return std::nullopt;
12392
12393 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
12394 return std::nullopt;
12395
12396 Less = LAR->getStart();
12397 More = MAR->getStart();
12398 continue;
12399 }
12400
12401 // Try to match a common constant multiply.
12402 auto MatchConstMul =
12403 [](const SCEV *S) -> std::optional<std::pair<const SCEV *, APInt>> {
12404 const APInt *C;
12405 const SCEV *Op;
12406 if (match(S, m_scev_Mul(m_scev_APInt(C), m_SCEV(Op))))
12407 return {{Op, *C}};
12408 return std::nullopt;
12409 };
12410 if (auto MatchedMore = MatchConstMul(More)) {
12411 if (auto MatchedLess = MatchConstMul(Less)) {
12412 if (MatchedMore->second == MatchedLess->second) {
12413 More = MatchedMore->first;
12414 Less = MatchedLess->first;
12415 DiffMul *= MatchedMore->second;
12416 continue;
12417 }
12418 }
12419 }
12420
12421 // Try to cancel out common factors in two add expressions.
12423 auto Add = [&](const SCEV *S, int Mul) {
12424 if (auto *C = dyn_cast<SCEVConstant>(S)) {
12425 if (Mul == 1) {
12426 Diff += C->getAPInt() * DiffMul;
12427 } else {
12428 assert(Mul == -1);
12429 Diff -= C->getAPInt() * DiffMul;
12430 }
12431 } else
12432 Multiplicity[S] += Mul;
12433 };
12434 auto Decompose = [&](const SCEV *S, int Mul) {
12435 if (isa<SCEVAddExpr>(S)) {
12436 for (const SCEV *Op : S->operands())
12437 Add(Op, Mul);
12438 } else
12439 Add(S, Mul);
12440 };
12441 Decompose(More, 1);
12442 Decompose(Less, -1);
12443
12444 // Check whether all the non-constants cancel out, or reduce to new
12445 // More/Less values.
12446 const SCEV *NewMore = nullptr, *NewLess = nullptr;
12447 for (const auto &[S, Mul] : Multiplicity) {
12448 if (Mul == 0)
12449 continue;
12450 if (Mul == 1) {
12451 if (NewMore)
12452 return std::nullopt;
12453 NewMore = S;
12454 } else if (Mul == -1) {
12455 if (NewLess)
12456 return std::nullopt;
12457 NewLess = S;
12458 } else
12459 return std::nullopt;
12460 }
12461
12462 // Values stayed the same, no point in trying further.
12463 if (NewMore == More || NewLess == Less)
12464 return std::nullopt;
12465
12466 More = NewMore;
12467 Less = NewLess;
12468
12469 // Reduced to constant.
12470 if (!More && !Less)
12471 return Diff;
12472
12473 // Left with variable on only one side, bail out.
12474 if (!More || !Less)
12475 return std::nullopt;
12476 }
12477
12478 // Did not reduce to constant.
12479 return std::nullopt;
12480}
12481
12482bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
12483 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12484 const SCEV *FoundRHS, const Instruction *CtxI) {
12485 // Try to recognize the following pattern:
12486 //
12487 // FoundRHS = ...
12488 // ...
12489 // loop:
12490 // FoundLHS = {Start,+,W}
12491 // context_bb: // Basic block from the same loop
12492 // known(Pred, FoundLHS, FoundRHS)
12493 //
12494 // If some predicate is known in the context of a loop, it is also known on
12495 // each iteration of this loop, including the first iteration. Therefore, in
12496 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
12497 // prove the original pred using this fact.
12498 if (!CtxI)
12499 return false;
12500 const BasicBlock *ContextBB = CtxI->getParent();
12501 // Make sure AR varies in the context block.
12502 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
12503 const Loop *L = AR->getLoop();
12504 const auto *Latch = L->getLoopLatch();
12505 // Make sure that context belongs to the loop and executes on 1st iteration
12506 // (if it ever executes at all).
12507 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12508 return false;
12509 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
12510 return false;
12511 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
12512 }
12513
12514 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
12515 const Loop *L = AR->getLoop();
12516 const auto *Latch = L->getLoopLatch();
12517 // Make sure that context belongs to the loop and executes on 1st iteration
12518 // (if it ever executes at all).
12519 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12520 return false;
12521 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
12522 return false;
12523 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
12524 }
12525
12526 return false;
12527}
12528
12529bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(CmpPredicate Pred,
12530 const SCEV *LHS,
12531 const SCEV *RHS,
12532 const SCEV *FoundLHS,
12533 const SCEV *FoundRHS) {
12534 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
12535 return false;
12536
12537 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
12538 if (!AddRecLHS)
12539 return false;
12540
12541 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12542 if (!AddRecFoundLHS)
12543 return false;
12544
12545 // We'd like to let SCEV reason about control dependencies, so we constrain
12546 // both the inequalities to be about add recurrences on the same loop. This
12547 // way we can use isLoopEntryGuardedByCond later.
12548
12549 const Loop *L = AddRecFoundLHS->getLoop();
12550 if (L != AddRecLHS->getLoop())
12551 return false;
12552
12553 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
12554 //
12555 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
12556 // ... (2)
12557 //
12558 // Informal proof for (2), assuming (1) [*]:
12559 //
12560 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
12561 //
12562 // Then
12563 //
12564 // FoundLHS s< FoundRHS s< INT_MIN - C
12565 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
12566 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
12567 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
12568 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
12569 // <=> FoundLHS + C s< FoundRHS + C
12570 //
12571 // [*]: (1) can be proved by ruling out overflow.
12572 //
12573 // [**]: This can be proved by analyzing all the four possibilities:
12574 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
12575 // (A s>= 0, B s>= 0).
12576 //
12577 // Note:
12578 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
12579 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
12580 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
12581 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
12582 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
12583 // C)".
12584
12585 std::optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
12586 if (!LDiff)
12587 return false;
12588 std::optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
12589 if (!RDiff || *LDiff != *RDiff)
12590 return false;
12591
12592 if (LDiff->isMinValue())
12593 return true;
12594
12595 APInt FoundRHSLimit;
12596
12597 if (Pred == CmpInst::ICMP_ULT) {
12598 FoundRHSLimit = -(*RDiff);
12599 } else {
12600 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
12601 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
12602 }
12603
12604 // Try to prove (1) or (2), as needed.
12605 return isAvailableAtLoopEntry(FoundRHS, L) &&
12606 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
12607 getConstant(FoundRHSLimit));
12608}
12609
12610bool ScalarEvolution::isImpliedViaMerge(CmpPredicate Pred, const SCEV *LHS,
12611 const SCEV *RHS, const SCEV *FoundLHS,
12612 const SCEV *FoundRHS, unsigned Depth) {
12613 const PHINode *LPhi = nullptr, *RPhi = nullptr;
12614
12615 llvm::scope_exit ClearOnExit([&]() {
12616 if (LPhi) {
12617 bool Erased = PendingMerges.erase(LPhi);
12618 assert(Erased && "Failed to erase LPhi!");
12619 (void)Erased;
12620 }
12621 if (RPhi) {
12622 bool Erased = PendingMerges.erase(RPhi);
12623 assert(Erased && "Failed to erase RPhi!");
12624 (void)Erased;
12625 }
12626 });
12627
12628 // Find respective Phis and check that they are not being pending.
12629 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
12630 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
12631 if (!PendingMerges.insert(Phi).second)
12632 return false;
12633 LPhi = Phi;
12634 }
12635 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
12636 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
12637 // If we detect a loop of Phi nodes being processed by this method, for
12638 // example:
12639 //
12640 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
12641 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
12642 //
12643 // we don't want to deal with a case that complex, so return conservative
12644 // answer false.
12645 if (!PendingMerges.insert(Phi).second)
12646 return false;
12647 RPhi = Phi;
12648 }
12649
12650 // If none of LHS, RHS is a Phi, nothing to do here.
12651 if (!LPhi && !RPhi)
12652 return false;
12653
12654 // If there is a SCEVUnknown Phi we are interested in, make it left.
12655 if (!LPhi) {
12656 std::swap(LHS, RHS);
12657 std::swap(FoundLHS, FoundRHS);
12658 std::swap(LPhi, RPhi);
12660 }
12661
12662 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
12663 const BasicBlock *LBB = LPhi->getParent();
12664 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12665
12666 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
12667 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
12668 isImpliedCondOperandsViaRanges(Pred, S1, S2, Pred, FoundLHS, FoundRHS) ||
12669 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
12670 };
12671
12672 if (RPhi && RPhi->getParent() == LBB) {
12673 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
12674 // If we compare two Phis from the same block, and for each entry block
12675 // the predicate is true for incoming values from this block, then the
12676 // predicate is also true for the Phis.
12677 for (const BasicBlock *IncBB : predecessors(LBB)) {
12678 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12679 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
12680 if (!ProvedEasily(L, R))
12681 return false;
12682 }
12683 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
12684 // Case two: RHS is also a Phi from the same basic block, and it is an
12685 // AddRec. It means that there is a loop which has both AddRec and Unknown
12686 // PHIs, for it we can compare incoming values of AddRec from above the loop
12687 // and latch with their respective incoming values of LPhi.
12688 // TODO: Generalize to handle loops with many inputs in a header.
12689 if (LPhi->getNumIncomingValues() != 2) return false;
12690
12691 auto *RLoop = RAR->getLoop();
12692 auto *Predecessor = RLoop->getLoopPredecessor();
12693 assert(Predecessor && "Loop with AddRec with no predecessor?");
12694 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
12695 if (!ProvedEasily(L1, RAR->getStart()))
12696 return false;
12697 auto *Latch = RLoop->getLoopLatch();
12698 assert(Latch && "Loop with AddRec with no latch?");
12699 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
12700 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
12701 return false;
12702 } else {
12703 // In all other cases go over inputs of LHS and compare each of them to RHS,
12704 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
12705 // At this point RHS is either a non-Phi, or it is a Phi from some block
12706 // different from LBB.
12707 for (const BasicBlock *IncBB : predecessors(LBB)) {
12708 // Check that RHS is available in this block.
12709 if (!dominates(RHS, IncBB))
12710 return false;
12711 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12712 // Make sure L does not refer to a value from a potentially previous
12713 // iteration of a loop.
12714 if (!properlyDominates(L, LBB))
12715 return false;
12716 // Addrecs are considered to properly dominate their loop, so are missed
12717 // by the previous check. Discard any values that have computable
12718 // evolution in this loop.
12719 if (auto *Loop = LI.getLoopFor(LBB))
12721 return false;
12722 if (!ProvedEasily(L, RHS))
12723 return false;
12724 }
12725 }
12726 return true;
12727}
12728
12729bool ScalarEvolution::isImpliedCondOperandsViaShift(CmpPredicate Pred,
12730 const SCEV *LHS,
12731 const SCEV *RHS,
12732 const SCEV *FoundLHS,
12733 const SCEV *FoundRHS) {
12734 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make
12735 // sure that we are dealing with same LHS.
12736 if (RHS == FoundRHS) {
12737 std::swap(LHS, RHS);
12738 std::swap(FoundLHS, FoundRHS);
12740 }
12741 if (LHS != FoundLHS)
12742 return false;
12743
12744 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
12745 if (!SUFoundRHS)
12746 return false;
12747
12748 Value *Shiftee, *ShiftValue;
12749
12750 using namespace PatternMatch;
12751 if (match(SUFoundRHS->getValue(),
12752 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
12753 auto *ShifteeS = getSCEV(Shiftee);
12754 // Prove one of the following:
12755 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
12756 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
12757 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12758 // ---> LHS <s RHS
12759 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12760 // ---> LHS <=s RHS
12761 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
12762 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
12763 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
12764 if (isKnownNonNegative(ShifteeS))
12765 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
12766 }
12767
12768 return false;
12769}
12770
12771bool ScalarEvolution::isImpliedCondOperandsViaMatchingDiff(
12772 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12773 const SCEV *FoundRHS) {
12774 // Only valid for equality predicates: (A == B) implies (C == D) when
12775 // the SCEV difference A - B equals C - D (they check the same
12776 // underlying relationship at every iteration).
12777 if (!ICmpInst::isEquality(Pred))
12778 return false;
12779
12780 // Restrict to cases involving loop recurrences - that's where this
12781 // pattern arises (correlated IV comparisons). This avoids calling
12782 // getMinusSCEV on arbitrary non-loop expressions.
12784 (!isa<SCEVAddRecExpr>(FoundLHS) && !isa<SCEVAddRecExpr>(FoundRHS)))
12785 return false;
12786
12787 // AddRecs from different loops can never produce matching differences.
12788 const SCEVAddRecExpr *QueryAddRec = dyn_cast<SCEVAddRecExpr>(LHS);
12789 if (!QueryAddRec)
12790 QueryAddRec = cast<SCEVAddRecExpr>(RHS);
12791 const SCEVAddRecExpr *FoundAddRec = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12792 if (!FoundAddRec)
12793 FoundAddRec = cast<SCEVAddRecExpr>(FoundRHS);
12794 if (QueryAddRec->getLoop() != FoundAddRec->getLoop())
12795 return false;
12796
12797 // If the strides differ, the differences can never match.
12798 if (QueryAddRec->getStepRecurrence(*this) !=
12799 FoundAddRec->getStepRecurrence(*this))
12800 return false;
12801
12802 // Compute differences. For pointer-typed operands sharing the same base,
12803 // getMinusSCEV strips the common base and returns an integer SCEV.
12804 // For example, {base,+,8} - (base+8*n) = {-8n,+,8}
12805 const SCEV *FoundDiff = getMinusSCEV(FoundLHS, FoundRHS);
12806 if (isa<SCEVCouldNotCompute>(FoundDiff))
12807 return false;
12808
12809 const SCEV *Diff = getMinusSCEV(LHS, RHS);
12810 if (isa<SCEVCouldNotCompute>(Diff))
12811 return false;
12812
12813 return Diff == FoundDiff;
12814}
12815
12816bool ScalarEvolution::isImpliedCondOperands(CmpPredicate Pred, const SCEV *LHS,
12817 const SCEV *RHS,
12818 const SCEV *FoundLHS,
12819 const SCEV *FoundRHS,
12820 const Instruction *CtxI) {
12821 return isImpliedCondOperandsViaRanges(Pred, LHS, RHS, Pred, FoundLHS,
12822 FoundRHS) ||
12823 isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS,
12824 FoundRHS) ||
12825 isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS) ||
12826 isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12827 CtxI) ||
12828 isImpliedCondOperandsViaMatchingDiff(Pred, LHS, RHS, FoundLHS,
12829 FoundRHS) ||
12830 isImpliedCondOperandsHelper(Pred, LHS, RHS, FoundLHS, FoundRHS);
12831}
12832
12833/// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
12834template <typename MinMaxExprType>
12835static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
12836 const SCEV *Candidate) {
12837 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12838 if (!MinMaxExpr)
12839 return false;
12840
12841 return is_contained(MinMaxExpr->operands(), Candidate);
12842}
12843
12845 CmpPredicate Pred, const SCEV *LHS,
12846 const SCEV *RHS) {
12847 // If both sides are affine addrecs for the same loop, with equal
12848 // steps, and we know the recurrences don't wrap, then we only
12849 // need to check the predicate on the starting values.
12850
12851 if (!ICmpInst::isRelational(Pred))
12852 return false;
12853
12854 const SCEV *LStart, *RStart, *Step;
12855 const Loop *L;
12856 if (!match(LHS,
12857 m_scev_AffineAddRec(m_SCEV(LStart), m_SCEV(Step), m_Loop(L))) ||
12859 m_SpecificLoop(L))))
12860 return false;
12864 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
12865 return false;
12866
12867 return SE.isKnownPredicate(Pred, LStart, RStart);
12868}
12869
12870/// Is LHS `Pred` RHS true because one of them is an AddRec that is known not to
12871/// go below its own start value?
12873 CmpPredicate Pred,
12874 const SCEV *LHS,
12875 const SCEV *RHS) {
12876 // Normalize to (AddRec Pred Start).
12879 std::swap(LHS, RHS);
12880 }
12881
12882 // The recurrence is equal to Start in the first iteration, so only the
12883 // non-strict predicate holds.
12884 if (Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE)
12885 return false;
12886
12887 const auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
12888 if (!AR || AR->getStart() != RHS)
12889 return false;
12890
12891 return SE.getMonotonicPredicateType(AR, Pred) ==
12893}
12894
12895/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
12896/// expression?
12898 const SCEV *LHS, const SCEV *RHS) {
12899 switch (Pred) {
12900 default:
12901 return false;
12902
12903 case ICmpInst::ICMP_SGE:
12904 std::swap(LHS, RHS);
12905 [[fallthrough]];
12906 case ICmpInst::ICMP_SLE:
12907 return
12908 // min(A, ...) <= A
12910 // A <= max(A, ...)
12912
12913 case ICmpInst::ICMP_UGE:
12914 std::swap(LHS, RHS);
12915 [[fallthrough]];
12916 case ICmpInst::ICMP_ULE:
12917 return
12918 // min(A, ...) <= A
12919 // FIXME: what about umin_seq?
12921 // A <= max(A, ...)
12923
12924 case ICmpInst::ICMP_UGT:
12925 std::swap(LHS, RHS);
12926 [[fallthrough]];
12927 case ICmpInst::ICMP_ULT:
12928 // umin(Ops) u<= each Op, so proving Op u< RHS for any Op proves
12929 // umin(Ops) u< RHS.
12930 //
12931 // Use computeConstantDifference instead of the more powerful
12932 // isKnownPredicate to keep this check cheap: isKnownPredicateViaMinOrMax
12933 // is called from isKnownViaNonRecursiveReasoning, so recursing into
12934 // the full predicate prover would be expensive.
12935 if (const auto *Min = dyn_cast<SCEVUMinExpr>(LHS)) {
12936 for (SCEVUse Op : Min->operands()) {
12937 std::optional<APInt> Diff = SE.computeConstantDifference(RHS, Op);
12938 // When Op and RHS share a common base differing by a
12939 // constant offset D (RHS - Op = D), Op u< RHS holds iff D != 0 and
12940 // RHS >= D (unsigned), i.e. the subtraction doesn't underflow.
12941 if (Diff && !Diff->isZero() && SE.getUnsignedRangeMin(RHS).uge(*Diff))
12942 return true;
12943 }
12944 }
12945 return false;
12946 }
12947
12948 llvm_unreachable("covered switch fell through?!");
12949}
12950
12951bool ScalarEvolution::isImpliedViaOperations(CmpPredicate Pred, const SCEV *LHS,
12952 const SCEV *RHS,
12953 const SCEV *FoundLHS,
12954 const SCEV *FoundRHS,
12955 unsigned Depth) {
12958 "LHS and RHS have different sizes?");
12959 assert(getTypeSizeInBits(FoundLHS->getType()) ==
12960 getTypeSizeInBits(FoundRHS->getType()) &&
12961 "FoundLHS and FoundRHS have different sizes?");
12962 // We want to avoid hurting the compile time with analysis of too big trees.
12963 if (Depth > Opts.scalar_evolution_max_scev_operations_implication_depth)
12964 return false;
12965
12966 // We only want to work with GT comparison so far.
12967 if (ICmpInst::isLT(Pred)) {
12969 std::swap(LHS, RHS);
12970 std::swap(FoundLHS, FoundRHS);
12971 }
12972
12974
12975 // For unsigned, try to reduce it to corresponding signed comparison.
12976 if (P == ICmpInst::ICMP_UGT)
12977 // We can replace unsigned predicate with its signed counterpart if all
12978 // involved values are non-negative.
12979 // TODO: We could have better support for unsigned.
12980 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
12981 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
12982 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
12983 // use this fact to prove that LHS and RHS are non-negative.
12984 const SCEV *MinusOne = getMinusOne(LHS->getType());
12985 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
12986 FoundRHS) &&
12987 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
12988 FoundRHS))
12990 }
12991
12992 if (P != ICmpInst::ICMP_SGT)
12993 return false;
12994
12995 auto GetOpFromSExt = [&](const SCEV *S) -> const SCEV * {
12996 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
12997 return Ext->getOperand();
12998 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
12999 // the constant in some cases.
13000 return S;
13001 };
13002
13003 // Acquire values from extensions.
13004 auto *OrigLHS = LHS;
13005 auto *OrigFoundLHS = FoundLHS;
13006 LHS = GetOpFromSExt(LHS);
13007 FoundLHS = GetOpFromSExt(FoundLHS);
13008
13009 // Is the SGT predicate can be proved trivially or using the found context.
13010 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
13011 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
13012 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
13013 FoundRHS, Depth + 1);
13014 };
13015
13016 SCEVUse LL;
13017 SCEVUse LR;
13018 if (match(LHS, m_scev_NSWAdd(m_SCEV(LL), m_SCEV(LR)))) {
13019 // We want to avoid creation of any new non-constant SCEV. Since we are
13020 // going to compare the operands to RHS, we should be certain that we don't
13021 // need any size extensions for this. So let's decline all cases when the
13022 // sizes of types of LHS and RHS do not match.
13023 // TODO: Maybe try to get RHS from sext to catch more cases?
13025 return false;
13026
13027 auto *MinusOne = getMinusOne(RHS->getType());
13028
13029 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
13030 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
13031 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
13032 };
13033 // Try to prove the following rule:
13034 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
13035 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
13036 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
13037 return true;
13038 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
13039 Value *LL, *LR;
13040 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
13041
13042 using namespace llvm::PatternMatch;
13043
13044 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
13045 // Rules for division.
13046 // We are going to perform some comparisons with Denominator and its
13047 // derivative expressions. In general case, creating a SCEV for it may
13048 // lead to a complex analysis of the entire graph, and in particular it
13049 // can request trip count recalculation for the same loop. This would
13050 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
13051 // this, we only want to create SCEVs that are constants in this section.
13052 // So we bail if Denominator is not a constant.
13053 if (!isa<ConstantInt>(LR))
13054 return false;
13055
13056 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
13057
13058 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
13059 // then a SCEV for the numerator already exists and matches with FoundLHS.
13060 auto *Numerator = getExistingSCEV(LL);
13061 if (!Numerator || Numerator->getType() != FoundLHS->getType())
13062 return false;
13063
13064 // Make sure that the numerator matches with FoundLHS and the denominator
13065 // is positive.
13066 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
13067 return false;
13068
13069 auto *DTy = Denominator->getType();
13070 auto *FRHSTy = FoundRHS->getType();
13071 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
13072 // One of types is a pointer and another one is not. We cannot extend
13073 // them properly to a wider type, so let us just reject this case.
13074 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
13075 // to avoid this check.
13076 return false;
13077
13078 // Given that:
13079 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
13080 auto *WTy = getWiderType(DTy, FRHSTy);
13081 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
13082 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
13083
13084 // Try to prove the following rule:
13085 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
13086 // For example, given that FoundLHS > 2. It means that FoundLHS is at
13087 // least 3. If we divide it by Denominator < 4, we will have at least 1.
13088 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
13089 if (isKnownNonPositive(RHS) &&
13090 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
13091 return true;
13092
13093 // Try to prove the following rule:
13094 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
13095 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
13096 // If we divide it by Denominator > 2, then:
13097 // 1. If FoundLHS is negative, then the result is 0.
13098 // 2. If FoundLHS is non-negative, then the result is non-negative.
13099 // Anyways, the result is non-negative.
13100 auto *MinusOne = getMinusOne(WTy);
13101 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
13102 if (isKnownNegative(RHS) &&
13103 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
13104 return true;
13105 }
13106 }
13107
13108 // If our expression contained SCEVUnknown Phis, and we split it down and now
13109 // need to prove something for them, try to prove the predicate for every
13110 // possible incoming values of those Phis.
13111 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
13112 return true;
13113
13114 return false;
13115}
13116
13118 const SCEV *RHS) {
13119 // zext x u<= sext x, sext x s<= zext x
13120 const SCEV *Op;
13121 switch (Pred) {
13122 case ICmpInst::ICMP_SGE:
13123 std::swap(LHS, RHS);
13124 [[fallthrough]];
13125 case ICmpInst::ICMP_SLE: {
13126 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt.
13127 return match(LHS, m_scev_SExt(m_SCEV(Op))) &&
13129 }
13130 case ICmpInst::ICMP_UGE:
13131 std::swap(LHS, RHS);
13132 [[fallthrough]];
13133 case ICmpInst::ICMP_ULE: {
13134 // If operand >=u 0 then ZExt == SExt. If operand <u 0 then ZExt <u SExt.
13135 return match(LHS, m_scev_ZExt(m_SCEV(Op))) &&
13137 }
13138 default:
13139 return false;
13140 };
13141 llvm_unreachable("unhandled case");
13142}
13143
13144bool ScalarEvolution::isKnownViaNonRecursiveReasoning(CmpPredicate Pred,
13145 SCEVUse LHS,
13146 SCEVUse RHS) {
13147 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
13148 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
13149 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
13150 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
13152 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
13153}
13154
13155bool ScalarEvolution::isImpliedCondOperandsHelper(CmpPredicate Pred,
13156 const SCEV *LHS,
13157 const SCEV *RHS,
13158 const SCEV *FoundLHS,
13159 const SCEV *FoundRHS) {
13160 if (ICmpInst::isEquality(Pred)) {
13161 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
13162 return true;
13163 } else {
13165 if (isKnownViaNonRecursiveReasoning(NonStrictPred, LHS, FoundLHS) &&
13166 isKnownViaNonRecursiveReasoning(
13167 ICmpInst::getSwappedPredicate(NonStrictPred), RHS, FoundRHS))
13168 return true;
13169 }
13170
13171 // Maybe it can be proved via operations?
13172 return isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS);
13173}
13174
13175bool ScalarEvolution::isImpliedCondOperandsViaRanges(
13176 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, CmpPredicate FoundPred,
13177 const SCEV *FoundLHS, const SCEV *FoundRHS) {
13178 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
13179 // The restriction on `FoundRHS` be lifted easily -- it exists only to
13180 // reduce the compile time impact of this optimization.
13181 return false;
13182
13183 std::optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
13184 if (!Addend)
13185 return false;
13186
13187 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
13188
13189 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
13190 // antecedent "`FoundLHS` `FoundPred` `FoundRHS`".
13191 ConstantRange FoundLHSRange =
13192 ConstantRange::makeExactICmpRegion(FoundPred, ConstFoundRHS);
13193
13194 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
13195 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
13196
13197 // We can also compute the range of values for `LHS` that satisfy the
13198 // consequent, "`LHS` `Pred` `RHS`":
13199 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
13200 // The antecedent implies the consequent if every value of `LHS` that
13201 // satisfies the antecedent also satisfies the consequent.
13202 return LHSRange.icmp(Pred, ConstRHS);
13203}
13204
13205bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
13206 bool IsSigned, bool Invert) {
13207 assert(isKnownPositive(Stride) && "Positive stride expected!");
13208
13209 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13210 const SCEV *One = getOne(Stride->getType());
13211
13212 if (IsSigned) {
13213 APInt MaxRHS = getRangeMax(RHS, /*IsSigned=*/true, Invert);
13214 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
13215 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13216
13217 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
13218 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
13219 }
13220
13221 APInt MaxRHS = getRangeMax(RHS, /*IsSigned=*/false, Invert);
13222 APInt MaxValue = APInt::getMaxValue(BitWidth);
13223 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13224
13225 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
13226 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
13227}
13228
13230 // umin(N, 1) + floor((N - umin(N, 1)) / D)
13231 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
13232 // expression fixes the case of N=0.
13233 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
13234 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
13235 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
13236}
13237
13238const SCEV *
13239ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, const SCEV *Stride,
13240 const SCEV *End, unsigned BitWidth,
13241 bool IsSigned, bool Invert) {
13242 // The logic in this function assumes we can represent a positive stride.
13243 // If we can't, the backedge-taken count must be zero.
13244 if (IsSigned && BitWidth == 1)
13245 return getZero(Stride->getType());
13246
13247 // This code below only been closely audited for negative strides in the
13248 // unsigned comparison case, it may be correct for signed comparison, but
13249 // that needs to be established.
13250 if (IsSigned && isKnownNegative(Stride))
13251 return getCouldNotCompute();
13252
13253 // Calculate the maximum backedge count based on the range of values
13254 // permitted by Start, End, and Stride. If Invert is true, both Start and End
13255 // need inverting. Stride was already negated by the caller.
13256 APInt MinStart = getRangeMin(Start, IsSigned, Invert);
13257
13258 APInt MinStride =
13259 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
13260
13261 // We assume either the stride is positive, or the backedge-taken count
13262 // is zero. So force StrideForMaxBECount to be at least one.
13263 APInt One(BitWidth, 1);
13264 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
13265 : APIntOps::umax(One, MinStride);
13266
13267 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
13268 : APInt::getMaxValue(BitWidth);
13269 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
13270
13271 // Although End can be a MAX expression we estimate MaxEnd considering only
13272 // the case End = RHS of the loop termination condition. This is safe because
13273 // in the other case (End - Start) is zero, leading to a zero maximum backedge
13274 // taken count.
13275 APInt MaxEnd = getRangeMax(End, IsSigned, Invert);
13276 MaxEnd =
13277 IsSigned ? APIntOps::smin(MaxEnd, Limit) : APIntOps::umin(MaxEnd, Limit);
13278
13279 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
13280 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
13281 : APIntOps::umax(MaxEnd, MinStart);
13282
13283 APInt Delta = MaxEnd - MinStart;
13284
13285 // Try to refine Delta in case End - Start (or Start - End if Invert) gives a
13286 // tighter bound after folding.
13287 const SCEV *DeltaExpr =
13288 Invert ? getMinusSCEV(Start, End) : getMinusSCEV(End, Start);
13289 Delta = APIntOps::umin(Delta, getUnsignedRangeMax(DeltaExpr));
13290
13291 return getUDivCeilSCEV(getConstant(Delta), getConstant(StrideForMaxBECount));
13292}
13293
13295ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
13296 const Loop *L, bool IsSigned, bool Invert,
13297 bool ControlsOnlyExit, bool AllowPredicates) {
13299
13300 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
13301
13302 // FIXME: Extend the non-invariant RHS analysis to greater-than comparisons.
13303 if (Invert && !isLoopInvariant(RHS, L))
13304 return getCouldNotCompute();
13305
13307 bool PredicatedIV = false;
13308 // FIXME: Generalize the NUW inference below to decreasing IVs.
13309 if (!IV && !Invert) {
13310 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
13311 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
13312 if (AR && AR->getLoop() == L && AR->isAffine()) {
13313 auto canProveNUW = [&]() {
13314 // We can use the comparison to infer no-wrap flags only if it fully
13315 // controls the loop exit.
13316 if (!ControlsOnlyExit)
13317 return false;
13318
13319 if (!isLoopInvariant(RHS, L))
13320 return false;
13321
13322 if (!isKnownNonZero(AR->getStepRecurrence(*this)))
13323 // We need the sequence defined by AR to strictly increase in the
13324 // unsigned integer domain for the logic below to hold.
13325 return false;
13326
13327 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
13328 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
13329 // If RHS <=u Limit, then there must exist a value V in the sequence
13330 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
13331 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned
13332 // overflow occurs. This limit also implies that a signed comparison
13333 // (in the wide bitwidth) is equivalent to an unsigned comparison as
13334 // the high bits on both sides must be zero.
13335 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
13336 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
13337 Limit = Limit.zext(OuterBitWidth);
13338 return getUnsignedRangeMax(applyLoopGuards(RHS, Guards)).ule(Limit);
13339 };
13340 auto Flags = AR->getNoWrapFlags();
13341 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
13342 Flags = setFlags(Flags, SCEV::FlagNUW);
13343
13344 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
13345 if (AR->hasNoUnsignedWrap()) {
13346 // Emulate what getZeroExtendExpr would have done during construction
13347 // if we'd been able to infer the fact just above at that time.
13348 const SCEV *Step = AR->getStepRecurrence(*this);
13349 Type *Ty = ZExt->getType();
13350 const SCEV *S = getAddRecExpr(
13352 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
13354 }
13355 }
13356 }
13357 }
13358
13359 if (!IV && AllowPredicates) {
13360 // Try to make this an AddRec using runtime tests, in the first X
13361 // iterations of this loop, where X is the SCEV expression found by the
13362 // algorithm below.
13363 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13364 PredicatedIV = true;
13365 }
13366
13367 // Avoid weird loops
13368 if (!IV || IV->getLoop() != L || !IV->isAffine())
13369 return getCouldNotCompute();
13370
13371 // A precondition of this method is that the condition being analyzed
13372 // reaches an exiting branch which dominates the latch. Given that, we can
13373 // assume that an increment which violates the nowrap specification and
13374 // produces poison must cause undefined behavior when the resulting poison
13375 // value is branched upon and thus we can conclude that the backedge is
13376 // taken no more often than would be required to produce that poison value.
13377 // Note that a well defined loop can exit on the iteration which violates
13378 // the nowrap specification if there is another exit (either explicit or
13379 // implicit/exceptional) which causes the loop to execute before the
13380 // exiting instruction we're analyzing would trigger UB.
13381 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13382 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13383 // Reverse the ordering for greater-than comparisons.
13385 if (Invert)
13387
13388 // The step of ~IV is the negated step of IV.
13389 const SCEV *Stride = IV->getStepRecurrence(*this);
13390 if (Invert)
13391 Stride = getNegativeSCEV(Stride);
13392 const SCEV *GuardedStride = Stride;
13393
13394 // Whether the IV may reach the maximum (or minimum if inverted) value
13395 // before the exit is taken.
13396 bool IVMayOverflow = true;
13397
13398 bool PositiveStride = isKnownPositive(Stride);
13399 // A dominating guard may prove the stride positive.
13400 if (!PositiveStride) {
13401 const SCEV *LoopGuardedStride = applyLoopGuards(Stride, Guards);
13402 if (isKnownPositive(LoopGuardedStride)) {
13403 GuardedStride = LoopGuardedStride;
13404 PositiveStride = true;
13405 // Encode the context-sensitive stride > 0 fact into the expression
13406 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13407 }
13408 }
13409
13410 // Avoid negative or zero stride values.
13411 if (!PositiveStride) {
13412 // FIXME: Generalize the unknown-stride analysis to decreasing IVs.
13413 if (Invert)
13414 return getCouldNotCompute();
13415
13416 // We can compute the correct backedge taken count for loops with unknown
13417 // strides if we can prove that the loop is not an infinite loop with side
13418 // effects. Here's the loop structure we are trying to handle -
13419 //
13420 // i = start
13421 // do {
13422 // A[i] = i;
13423 // i += s;
13424 // } while (i < end);
13425 //
13426 // The backedge taken count for such loops is evaluated as -
13427 // (max(end, start + stride) - start - 1) /u stride
13428 //
13429 // The additional preconditions that we need to check to prove correctness
13430 // of the above formula is as follows -
13431 //
13432 // a) IV is either nuw or nsw depending upon signedness (indicated by the
13433 // NoWrap flag).
13434 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13435 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13436 // no side effects within the loop) or a predicate is added to ensure
13437 // stride is positive.
13438 // c) loop has a single static exit (with no abnormal exits)
13439 //
13440 // Precondition a) implies that if the stride is negative, this is a single
13441 // trip loop. The backedge taken count formula reduces to zero in this case.
13442 //
13443 // Precondition b) and c) combine to imply that if rhs is invariant in L,
13444 // then a zero stride means the backedge can't be taken without executing
13445 // undefined behavior.
13446 //
13447 // The positive stride case is the same as isKnownPositive(Stride) returning
13448 // true (original behavior of the function).
13449 //
13450 if (PredicatedIV || !NoWrap || !loopHasNoAbnormalExits(L))
13451 return getCouldNotCompute();
13452
13453 if (!loopIsFiniteByAssumption(L)) {
13454 // If the loop may be infinite, add a predicate ensuring Stride is
13455 // positive, to guarantee forward progress.
13456 if (!AllowPredicates || !isLoopInvariant(Stride, L))
13457 return getCouldNotCompute();
13458
13459 const SCEV *Zero = getZero(Stride->getType());
13460 const SCEVPredicate *P =
13462 Predicates.push_back(P);
13463 // When the predicate holds (Stride > 0), umax(Stride, 1) == Stride,
13464 // so the result is unchanged. To prevent div by zero.
13465 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13466 } else if (!isKnownNonZero(Stride)) {
13467 // If we have a step of zero, and RHS isn't invariant in L, we don't know
13468 // if it might eventually be greater than start and if so, on which
13469 // iteration. We can't even produce a useful upper bound.
13470 if (!isLoopInvariant(RHS, L))
13471 return getCouldNotCompute();
13472
13473 // We allow a potentially zero stride, but we need to divide by stride
13474 // below. Since the loop can't be infinite and this check must control
13475 // the sole exit, we can infer the exit must be taken on the first
13476 // iteration (e.g. backedge count = 0) if the stride is zero. Given that,
13477 // we know the numerator in the divides below must be zero, so we can
13478 // pick an arbitrary non-zero value for the denominator (e.g. stride)
13479 // and produce the right result.
13480 // FIXME: Handle the case where Stride is poison?
13481 auto wouldZeroStrideBeUB = [&]() {
13482 // Proof by contradiction. Suppose the stride were zero. If we can
13483 // prove that the backedge *is* taken on the first iteration, then since
13484 // we know this condition controls the sole exit, we must have an
13485 // infinite loop. We can't have a (well defined) infinite loop per
13486 // check just above.
13487 // Note: The (Start - Stride) term is used to get the start' term from
13488 // (start' + stride,+,stride). Remember that we only care about the
13489 // result of this expression when stride == 0 at runtime.
13490 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
13491 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
13492 };
13493 if (!wouldZeroStrideBeUB()) {
13494 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13495 }
13496 }
13497 } else {
13498 // Avoid proven overflow cases: this will ensure that the backedge taken
13499 // count will not generate any unsigned overflow.
13500 IVMayOverflow = canIVOverflowOnLT(RHS, GuardedStride, IsSigned, Invert) &&
13501 canIVOverflowOnLT(applyLoopGuards(RHS, Guards),
13502 GuardedStride, IsSigned, Invert);
13503 if (IVMayOverflow && !NoWrap)
13504 return getCouldNotCompute();
13505 }
13506
13507 // On all paths just preceeding, we established the following invariant:
13508 // IV can be assumed not to overflow up to and including the exiting
13509 // iteration. We proved this in one of two ways:
13510 // 1) We can show overflow doesn't occur before the exiting iteration
13511 // 1a) canIVOverflowOnLT, and b) step of one
13512 // 2) We can show that if overflow occurs, the loop must execute UB
13513 // before any possible exit.
13514 // Note that we have not yet proved RHS invariant (in general).
13515
13516 const SCEV *Start = IV->getStart();
13517
13518 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
13519 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
13520 // Use integer-typed versions for actual computation; we can't subtract
13521 // pointers in general.
13522 const SCEV *OrigStart = Start;
13523 const SCEV *OrigRHS = RHS;
13524 if (Start->getType()->isPointerTy()) {
13525 Start = getPtrToAddrExpr(Start);
13526 if (isa<SCEVCouldNotCompute>(Start))
13527 return Start;
13528 }
13529 if (RHS->getType()->isPointerTy()) {
13532 return RHS;
13533 }
13534
13535 const SCEV *End = nullptr, *BECount = getCouldNotCompute(),
13536 *BECountIfBackedgeTaken = getCouldNotCompute();
13537 if (!isLoopInvariant(RHS, L)) {
13538 assert(!Invert && "RHS must be loop-invariant for Invert");
13539 const auto *RHSAddRec = dyn_cast<SCEVAddRecExpr>(RHS);
13540 if (PositiveStride && RHSAddRec != nullptr && RHSAddRec->getLoop() == L &&
13541 any(RHSAddRec->getNoWrapFlags())) {
13542 // The structure of loop we are trying to calculate backedge count of:
13543 //
13544 // left = left_start
13545 // right = right_start
13546 //
13547 // while(left < right){
13548 // ... do something here ...
13549 // left += s1; // stride of left is s1 (s1 > 0)
13550 // right += s2; // stride of right is s2 (s2 < 0)
13551 // }
13552 //
13553
13554 const SCEV *RHSStart = RHSAddRec->getStart();
13555 const SCEV *RHSStride = RHSAddRec->getStepRecurrence(*this);
13556
13557 // If Stride - RHSStride is positive and does not overflow, we can write
13558 // backedge count as ->
13559 // ceil((End - Start) /u (Stride - RHSStride))
13560 // Where, End = max(RHSStart, Start)
13561
13562 // Check if RHSStride < 0 and Stride - RHSStride will not overflow.
13563 if (isKnownNegative(RHSStride) &&
13564 willNotOverflow(Instruction::Sub, /*Signed=*/true, Stride,
13565 RHSStride)) {
13566
13567 const SCEV *Denominator = getMinusSCEV(Stride, RHSStride);
13568 if (isKnownPositive(Denominator)) {
13569 End = IsSigned ? getSMaxExpr(RHSStart, Start)
13570 : getUMaxExpr(RHSStart, Start);
13571
13572 // We can do this because End >= Start, as End = max(RHSStart, Start)
13573 const SCEV *Delta = getMinusSCEV(End, Start);
13574
13575 BECount = getUDivCeilSCEV(Delta, Denominator);
13576 BECountIfBackedgeTaken =
13577 getUDivCeilSCEV(getMinusSCEV(RHSStart, Start), Denominator);
13578 }
13579 }
13580 }
13581 } else {
13582 // Let End = max(RHS,Start). We use the expression (End-Start)/Stride to
13583 // describe the backedge count: if the backedge is taken at least once then
13584 // End is RHS, and if not End is Start so we get a backedge count of zero.
13585 // Inverted, End is min(RHS, Start).
13586 //
13587 // AddingStrideMinusOneMayOverflow has the following preconditions:
13588 //
13589 // 1. Start <= End, signed if IsSigned (inverted: End <= Start)
13590 // 2. The index variable doesn't overflow.
13591 //
13592 // Therefore, we know N exists such that
13593 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
13594 // doesn't overflow.
13595 //
13596 // Using this information, try to prove whether the addition in
13597 // "(End - Start) + (Stride - 1)" has unsigned overflow.
13598 //
13599 // If the IV cannot overflow, RHS is at least Stride - 1 below the maximum
13600 // value, so the distance End - Start is at most UMAX - (Stride - 1) and
13601 // the (Stride - 1) addition below cannot overflow.
13602 const SCEV *One = getOne(Stride->getType());
13603 bool AddingStrideMinusOneMayOverflow = IVMayOverflow && [&] {
13604 if (isKnownToBeAPowerOfTwo(Stride)) {
13605 // Suppose Stride is a power of two, and Start/End are unsigned
13606 // integers. Let UMAX be the largest representable unsigned
13607 // integer.
13608 //
13609 // By the preconditions of this function, we know
13610 // "(Start + Stride * N) >= End", and this doesn't overflow.
13611 // As a formula:
13612 //
13613 // End <= (Start + Stride * N) <= UMAX
13614 //
13615 // Subtracting Start from all the terms:
13616 //
13617 // End - Start <= Stride * N <= UMAX - Start
13618 //
13619 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore:
13620 //
13621 // End - Start <= Stride * N <= UMAX
13622 //
13623 // Stride * N is a multiple of Stride. Therefore,
13624 //
13625 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
13626 //
13627 // Since Stride is a power of two, UMAX + 1 is divisible by
13628 // Stride. Therefore, UMAX mod Stride == Stride - 1. So we can
13629 // write:
13630 //
13631 // End - Start <= Stride * N <= UMAX - Stride - 1
13632 //
13633 // Dropping the middle term:
13634 //
13635 // End - Start <= UMAX - Stride - 1
13636 //
13637 // Adding Stride - 1 to both sides:
13638 //
13639 // (End - Start) + (Stride - 1) <= UMAX
13640 //
13641 // In other words, the addition doesn't have unsigned overflow.
13642 //
13643 // A similar proof works if we treat Start/End as signed values.
13644 // Just rewrite steps before "End - Start <= Stride * N <= UMAX"
13645 // to use signed max instead of unsigned max. Note that we're
13646 // trying to prove a lack of unsigned overflow in either case.
13647 // Inverted: "Start - End <= Stride * N <= Start - MIN <= UMAX", same.
13648 return false;
13649 }
13650 if (!Invert && (Start == Stride || Start == getMinusSCEV(Stride, One))) {
13651 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End
13652 // - 1. If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1
13653 // <u End. If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End -
13654 // 1 <s End.
13655 //
13656 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 ==
13657 // End.
13658 //
13659 // Both need Start to be the smaller value, so neither applies inverted.
13660 return false;
13661 }
13662 return true;
13663 }();
13664
13665 // If inverted, the analyzed values are complements: "~V - Offset" is "~(V +
13666 // Offset)" and "~To - ~From" is "From - To".
13667 auto StepBack = [&](const SCEV *V, const SCEV *Offset) -> const SCEV * {
13668 if (Invert)
13669 return getAddExpr(V, Offset);
13670 return getMinusSCEV(V, Offset);
13671 };
13672 auto Distance = [&](const SCEV *From, const SCEV *To) {
13673 return Invert ? getMinusSCEV(From, To) : getMinusSCEV(To, From);
13674 };
13675
13676 const SCEV *OrigPrevStart = StepBack(OrigStart, Stride);
13677 assert(isAvailableAtLoopEntry(OrigPrevStart, L) && "Must be!");
13678 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
13679 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
13680 // Can we prove Start - Stride < RHS, and either Start - Stride < Start or
13681 // (via !AddingStrideMinusOneMayOverflow) that (RHS - Start) + (Stride - 1)
13682 // does not overflow?
13683 if ((!AddingStrideMinusOneMayOverflow ||
13684 isLoopEntryGuardedByCond(L, Cond, OrigPrevStart, OrigStart)) &&
13685 isLoopEntryGuardedByCond(L, Cond, OrigPrevStart, OrigRHS)) {
13686 // In this case, we can use a refined formula for computing backedge
13687 // taken count. The general formula remains:
13688 // "End-Start /uceiling Stride"
13689 // We want to use the alternate formula:
13690 // "((RHS - 1) - (Start - Stride)) /u Stride"
13691 // Let's do a quick case analysis to show these are equivalent under
13692 // our preconditions. When inverted, the proof uses complemented Start,
13693 // RHS and End; Stride remains positive.
13694 // * For RHS <= Start (End is Start), the backedge-taken count must be
13695 // zero. Together with the precondition "Start - Stride < RHS", we have
13696 // "Start - Stride < RHS <= Start". Subtracting Start - Stride from
13697 // all sides we get "0 < RHS - (Start - Stride) <= Stride".
13698 // Subtracting 1 we get "0 <= (RHS - 1) - (Start - Stride) < Stride".
13699 // So dividing that by Stride gives zero.
13700 //
13701 // * For RHS > Start (End is RHS), the backedge count must be
13702 // "RHS-Start /uceil Stride", so it is sufficient to show that the
13703 // numerator "((RHS - 1) - (Start - Stride))" does not overflow.
13704 //
13705 // If "Start - Stride < Start" holds, we have
13706 // "RHS > Start > Start - Stride". As such
13707 // "RHS - (Start - Stride) - 1" does not overflow, which is the
13708 // reassociated numerator.
13709 //
13710 // Otherwise !AddingStrideMinusOneMayOverflow guarantees that
13711 // "(End - Start) + (Stride - 1)" does not overflow unsigned. Here
13712 // "End" is "RHS", as "RHS > Start", so this is the reassociated
13713 // numerator. Neither sub-term wraps unsigned: "RHS - Start"
13714 // due to "RHS > Start", and "Stride - 1", as Stride is non-zero.
13715 const SCEV *Numerator =
13716 getMinusSCEV(Distance(StepBack(Start, Stride), RHS), One);
13717 BECount = getUDivExpr(Numerator, Stride);
13718 }
13719
13720 if (isa<SCEVCouldNotCompute>(BECount)) {
13721 auto canProveRHSIsAtOrBeyondStart = [&]() {
13722 // Inverted, the claim is "Start >= RHS". Reverse the comparisons below
13723 // by swapping their operands rather than their predicates:
13724 // isLoopEntryGuardedByCond is sensitive to operand order and loses the
13725 // proof if the IV bound moves to the other side.
13726 auto SwapIfInverted = [&](const SCEV *A, const SCEV *B) {
13727 return Invert ? std::pair(B, A) : std::pair(A, B);
13728 };
13729
13730 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
13731 const SCEV *GuardedRHS = applyLoopGuards(OrigRHS, Guards);
13732 const SCEV *GuardedStart = applyLoopGuards(OrigStart, Guards);
13733 if (Invert)
13734 std::swap(GuardedRHS, GuardedStart);
13735
13736 auto [GELHS, GERHS] = SwapIfInverted(OrigRHS, OrigStart);
13737 if (isLoopEntryGuardedByCond(L, CondGE, GELHS, GERHS) ||
13738 isKnownPredicate(CondGE, GuardedRHS, GuardedStart))
13739 return true;
13740
13741 if ((GuardedRHS != GELHS || GuardedStart != GERHS) &&
13742 isKnownPredicate(CondGE, GELHS, GERHS))
13743 return true;
13744
13745 // (RHS > Start - 1) implies RHS >= Start.
13746 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
13747 // "Start - 1" doesn't overflow.
13748 // * For signed comparison, if Start - 1 does overflow, it's equal
13749 // to INT_MAX, and "RHS >s INT_MAX" is trivially false.
13750 // * For unsigned comparison, if Start - 1 does overflow, it's equal
13751 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
13752 //
13753 // FIXME: Should isLoopEntryGuardedByCond do this for us?
13754 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13755 auto [GTLHS, GTRHS] = SwapIfInverted(OrigRHS, StepBack(OrigStart, One));
13756 return isLoopEntryGuardedByCond(L, CondGT, GTLHS, GTRHS);
13757 };
13758
13759 // If we know that RHS >= Start in the context of loop, then we know
13760 // that max(RHS, Start) = RHS at this point.
13761 if (canProveRHSIsAtOrBeyondStart()) {
13762 End = RHS;
13763 } else {
13764 // If RHS < Start, the backedge will be taken zero times. So in
13765 // general, we can write the backedge-taken count as:
13766 //
13767 // RHS >= Start ? ceil(RHS - Start) / Stride : 0
13768 //
13769 // We convert it to the following to make it more convenient for SCEV:
13770 //
13771 // ceil(max(RHS, Start) - Start) / Stride
13772 //
13773 // Inverted, this is ceil(Start - min(RHS, Start)) / Stride.
13774 if (Invert)
13775 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
13776 else
13777 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
13778
13779 // See what would happen if we assume the backedge is taken. This is
13780 // used to compute MaxBECount.
13781 BECountIfBackedgeTaken = getUDivCeilSCEV(Distance(Start, RHS), Stride);
13782 }
13783
13784 const SCEV *Delta = Distance(Start, End);
13785 if (!AddingStrideMinusOneMayOverflow) {
13786 // floor((D + (S - 1)) / S)
13787 // We prefer this formulation if it's legal because it's fewer
13788 // operations.
13789 BECount =
13790 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13791 } else {
13792 BECount = getUDivCeilSCEV(Delta, Stride);
13793 }
13794 }
13795 }
13796
13797 const SCEV *ConstantMaxBECount;
13798 bool MaxOrZero = false;
13799 if (isa<SCEVConstant>(BECount)) {
13800 ConstantMaxBECount = BECount;
13801 } else {
13802 ConstantMaxBECount = computeMaxBECountForLT(
13803 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned,
13804 Invert);
13805 // If we know exactly how many times the backedge will be taken if it's
13806 // taken at least once, then the backedge count will either be that or
13807 // zero. If that count exceeds the range-based bound, the backedge can
13808 // never be taken.
13809 const APInt *IfTaken, *RangeMax;
13810 if (match(BECountIfBackedgeTaken, m_scev_APInt(IfTaken))) {
13811 if (match(ConstantMaxBECount, m_scev_APInt(RangeMax)) &&
13812 IfTaken->ugt(*RangeMax)) {
13813 ConstantMaxBECount = getZero(BECountIfBackedgeTaken->getType());
13814 } else {
13815 ConstantMaxBECount = BECountIfBackedgeTaken;
13816 MaxOrZero = true;
13817 }
13818 }
13819 }
13820
13821 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
13822 !isa<SCEVCouldNotCompute>(BECount))
13823 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
13824
13825 const SCEV *SymbolicMaxBECount =
13826 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13827 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
13828 Predicates);
13829}
13830
13832 ScalarEvolution &SE) const {
13833 if (Range.isFullSet()) // Infinite loop.
13834 return SE.getCouldNotCompute();
13835
13836 // If the start is a non-zero constant, shift the range to simplify things.
13837 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
13838 if (!SC->getValue()->isZero()) {
13840 Operands[0] = SE.getZero(SC->getType());
13841 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
13843 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
13844 return ShiftedAddRec->getNumIterationsInRange(
13845 Range.subtract(SC->getAPInt()), SE);
13846 // This is strange and shouldn't happen.
13847 return SE.getCouldNotCompute();
13848 }
13849
13850 // The only time we can solve this is when we have all constant indices.
13851 // Otherwise, we cannot determine the overflow conditions.
13853 return SE.getCouldNotCompute();
13854
13855 // Okay at this point we know that all elements of the chrec are constants and
13856 // that the start element is zero.
13857
13858 // First check to see if the range contains zero. If not, the first
13859 // iteration exits.
13860 unsigned BitWidth = SE.getTypeSizeInBits(getType());
13861 if (!Range.contains(APInt(BitWidth, 0)))
13862 return SE.getZero(getType());
13863
13864 if (isAffine()) {
13865 // If this is an affine expression then we have this situation:
13866 // Solve {0,+,A} in Range === Ax in Range
13867
13868 // We know that zero is in the range. If A is positive then we know that
13869 // the upper value of the range must be the first possible exit value.
13870 // If A is negative then the lower of the range is the last possible loop
13871 // value. Also note that we already checked for a full range.
13872 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
13873 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
13874
13875 // The exit value should be (End+A)/A.
13876 APInt ExitVal = (End + A).udiv(A);
13877 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
13878
13879 // Evaluate at the exit value. If we really did fall out of the valid
13880 // range, then we computed our trip count, otherwise wrap around or other
13881 // things must have happened.
13882 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
13883 if (Range.contains(Val->getValue()))
13884 return SE.getCouldNotCompute(); // Something strange happened
13885
13886 // Ensure that the previous value is in the range.
13887 assert(Range.contains(
13889 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
13890 "Linear scev computation is off in a bad way!");
13891 return SE.getConstant(ExitValue);
13892 }
13893
13894 if (isQuadratic()) {
13895 if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
13896 return SE.getConstant(*S);
13897 }
13898
13899 return SE.getCouldNotCompute();
13900}
13901
13902const SCEVAddRecExpr *
13904 assert(getNumOperands() > 1 && "AddRec with zero step?");
13905 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
13906 // but in this case we cannot guarantee that the value returned will be an
13907 // AddRec because SCEV does not have a fixed point where it stops
13908 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
13909 // may happen if we reach arithmetic depth limit while simplifying. So we
13910 // construct the returned value explicitly.
13912 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
13913 // (this + Step) is {A+B,+,B+C,+...,+,N}.
13914 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
13915 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
13916 // We know that the last operand is not a constant zero (otherwise it would
13917 // have been popped out earlier). This guarantees us that if the result has
13918 // the same last operand, then it will also not be popped out, meaning that
13919 // the returned value will be an AddRec.
13920 const SCEV *Last = getOperand(getNumOperands() - 1);
13921 assert(!Last->isZero() && "Recurrency with zero step?");
13922 Ops.push_back(Last);
13924}
13925
13926// Return true when S contains at least an undef value.
13928 return SCEVExprContains(
13929 S, [](const SCEV *S) { return match(S, m_scev_UndefOrPoison()); });
13930}
13931
13932// Return true when S contains a value that is a nullptr.
13934 return SCEVExprContains(S, [](const SCEV *S) {
13935 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
13936 return SU->getValue() == nullptr;
13937 return false;
13938 });
13939}
13940
13941/// Return the size of an element read or written by Inst.
13943 if (!isa<LoadInst, StoreInst>(Inst))
13944 return nullptr;
13946 return getSizeOfExpr(ETy, getLoadStoreType(Inst));
13947}
13948
13949//===----------------------------------------------------------------------===//
13950// SCEVCallbackVH Class Implementation
13951//===----------------------------------------------------------------------===//
13952
13954 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
13955 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
13956 SE->ConstantEvolutionLoopExitValue.erase(PN);
13957 SE->eraseValueFromMap(getValPtr());
13958 // this now dangles!
13959}
13960
13961void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
13962 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
13963
13964 // Forget all the expressions associated with users of the old value,
13965 // so that future queries will recompute the expressions using the new
13966 // value.
13967 SE->forgetValue(getValPtr());
13968 // this now dangles!
13969}
13970
13971ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
13972 : CallbackVH(V), SE(se) {}
13973
13974//===----------------------------------------------------------------------===//
13975// ScalarEvolution Class Implementation
13976//===----------------------------------------------------------------------===//
13977
13980 LoopInfo &LI)
13981 : Opts(getAnalysisOptions(F)), F(F), DL(F.getDataLayout()), TLI(TLI),
13982 AC(AC), DT(DT), LI(LI), CouldNotCompute(new SCEVCouldNotCompute()),
13983 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64) {
13984 // To use guards for proving predicates, we need to scan every instruction in
13985 // relevant basic blocks, and not just terminators. Doing this is a waste of
13986 // time if the IR does not actually contain any calls to
13987 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
13988 //
13989 // This pessimizes the case where a pass that preserves ScalarEvolution wants
13990 // to _add_ guards to the module when there weren't any before, and wants
13991 // ScalarEvolution to optimize based on those guards. For now we prefer to be
13992 // efficient in lieu of being smart in that rather obscure case.
13993
13994 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
13995 F.getParent(), Intrinsic::experimental_guard);
13996 HasGuards = GuardDecl && !GuardDecl->use_empty();
13997}
13998
14000 : Opts(Arg.Opts), F(Arg.F), DL(Arg.DL), HasGuards(Arg.HasGuards),
14001 TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), LI(Arg.LI),
14002 CouldNotCompute(std::move(Arg.CouldNotCompute)),
14003 ValueExprMap(std::move(Arg.ValueExprMap)),
14004 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
14005 PendingMerges(std::move(Arg.PendingMerges)),
14006 ConstantMultipleCache(std::move(Arg.ConstantMultipleCache)),
14007 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
14008 PredicatedBackedgeTakenCounts(
14009 std::move(Arg.PredicatedBackedgeTakenCounts)),
14010 BECountUsers(std::move(Arg.BECountUsers)),
14011 ConstantEvolutionLoopExitValue(
14012 std::move(Arg.ConstantEvolutionLoopExitValue)),
14013 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
14014 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
14015 LoopDispositions(std::move(Arg.LoopDispositions)),
14016 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
14017 BlockDispositions(std::move(Arg.BlockDispositions)),
14018 SCEVUsers(std::move(Arg.SCEVUsers)),
14019 UnsignedRanges(std::move(Arg.UnsignedRanges)),
14020 SignedRanges(std::move(Arg.SignedRanges)),
14021 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
14022 UniquePreds(std::move(Arg.UniquePreds)),
14023 SCEVAllocator(std::move(Arg.SCEVAllocator)),
14024 ConstantSCEVs(std::move(Arg.ConstantSCEVs)),
14025 LoopUsers(std::move(Arg.LoopUsers)),
14026 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
14027 FirstUnknown(Arg.FirstUnknown),
14028 NextUnknownOrderID(Arg.NextUnknownOrderID) {
14029 Arg.FirstUnknown = nullptr;
14030}
14031
14033 // Iterate through all the SCEVUnknown instances and call their
14034 // destructors, so that they release their references to their values.
14035 for (SCEVUnknown *U = FirstUnknown; U;) {
14036 SCEVUnknown *Tmp = U;
14037 U = U->Next;
14038 Tmp->~SCEVUnknown();
14039 }
14040 FirstUnknown = nullptr;
14041
14042 ExprValueMap.clear();
14043 ValueExprMap.clear();
14044 HasRecMap.clear();
14045 BackedgeTakenCounts.clear();
14046 PredicatedBackedgeTakenCounts.clear();
14047
14048 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
14049 assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
14050 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
14051 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
14052}
14053
14057
14058/// When printing a top-level SCEV for trip counts, it's helpful to include
14059/// a type for constants which are otherwise hard to disambiguate.
14060static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV* S) {
14061 if (isa<SCEVConstant>(S))
14062 OS << *S->getType() << " ";
14063 OS << *S;
14064}
14065
14067 const Loop *L) {
14068 // Print all inner loops first
14069 for (Loop *I : *L)
14070 PrintLoopInfo(OS, SE, I);
14071
14072 OS << "Loop ";
14073 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14074 OS << ": ";
14075
14076 SmallVector<BasicBlock *, 8> ExitingBlocks;
14077 L->getExitingBlocks(ExitingBlocks);
14078 if (ExitingBlocks.size() != 1)
14079 OS << "<multiple exits> ";
14080
14081 auto *BTC = SE->getBackedgeTakenCount(L);
14082 if (!isa<SCEVCouldNotCompute>(BTC)) {
14083 OS << "backedge-taken count is ";
14084 PrintSCEVWithTypeHint(OS, BTC);
14085 } else
14086 OS << "Unpredictable backedge-taken count.";
14087 OS << "\n";
14088
14089 if (ExitingBlocks.size() > 1)
14090 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14091 OS << " exit count for " << ExitingBlock->getName() << ": ";
14092 const SCEV *EC = SE->getExitCount(L, ExitingBlock);
14093 PrintSCEVWithTypeHint(OS, EC);
14094 if (isa<SCEVCouldNotCompute>(EC)) {
14095 // Retry with predicates.
14097 EC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates);
14098 if (!isa<SCEVCouldNotCompute>(EC)) {
14099 OS << "\n predicated exit count for " << ExitingBlock->getName()
14100 << ": ";
14101 PrintSCEVWithTypeHint(OS, EC);
14102 OS << "\n Predicates:\n";
14103 for (const auto *P : Predicates)
14104 P->print(OS, 4);
14105 }
14106 }
14107 OS << "\n";
14108 }
14109
14110 OS << "Loop ";
14111 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14112 OS << ": ";
14113
14114 auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
14115 if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
14116 OS << "constant max backedge-taken count is ";
14117 PrintSCEVWithTypeHint(OS, ConstantBTC);
14119 OS << ", actual taken count either this or zero.";
14120 } else {
14121 OS << "Unpredictable constant max backedge-taken count. ";
14122 }
14123
14124 OS << "\n"
14125 "Loop ";
14126 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14127 OS << ": ";
14128
14129 auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
14130 if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
14131 OS << "symbolic max backedge-taken count is ";
14132 PrintSCEVWithTypeHint(OS, SymbolicBTC);
14134 OS << ", actual taken count either this or zero.";
14135 } else {
14136 OS << "Unpredictable symbolic max backedge-taken count. ";
14137 }
14138 OS << "\n";
14139
14140 if (ExitingBlocks.size() > 1)
14141 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14142 OS << " symbolic max exit count for " << ExitingBlock->getName() << ": ";
14143 auto *ExitBTC = SE->getExitCount(L, ExitingBlock,
14145 PrintSCEVWithTypeHint(OS, ExitBTC);
14146 if (isa<SCEVCouldNotCompute>(ExitBTC)) {
14147 // Retry with predicates.
14149 ExitBTC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates,
14151 if (!isa<SCEVCouldNotCompute>(ExitBTC)) {
14152 OS << "\n predicated symbolic max exit count for "
14153 << ExitingBlock->getName() << ": ";
14154 PrintSCEVWithTypeHint(OS, ExitBTC);
14155 OS << "\n Predicates:\n";
14156 for (const auto *P : Predicates)
14157 P->print(OS, 4);
14158 }
14159 }
14160 OS << "\n";
14161 }
14162
14164 auto *PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
14165 if (PBT != BTC) {
14166 OS << "Loop ";
14167 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14168 OS << ": ";
14169 if (!isa<SCEVCouldNotCompute>(PBT)) {
14170 OS << "Predicated backedge-taken count is ";
14171 PrintSCEVWithTypeHint(OS, PBT);
14172 } else
14173 OS << "Unpredictable predicated backedge-taken count.";
14174 OS << "\n";
14175 OS << " Predicates:\n";
14176 for (const auto *P : Preds)
14177 P->print(OS, 4);
14178 }
14179 Preds.clear();
14180
14181 auto *PredConstantMax =
14183 if (PredConstantMax != ConstantBTC) {
14184 OS << "Loop ";
14185 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14186 OS << ": ";
14187 if (!isa<SCEVCouldNotCompute>(PredConstantMax)) {
14188 OS << "Predicated constant max backedge-taken count is ";
14189 PrintSCEVWithTypeHint(OS, PredConstantMax);
14190 } else
14191 OS << "Unpredictable predicated constant max backedge-taken count.";
14192 OS << "\n";
14193 OS << " Predicates:\n";
14194 for (const auto *P : Preds)
14195 P->print(OS, 4);
14196 }
14197 Preds.clear();
14198
14199 auto *PredSymbolicMax =
14201 if (SymbolicBTC != PredSymbolicMax) {
14202 OS << "Loop ";
14203 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14204 OS << ": ";
14205 if (!isa<SCEVCouldNotCompute>(PredSymbolicMax)) {
14206 OS << "Predicated symbolic max backedge-taken count is ";
14207 PrintSCEVWithTypeHint(OS, PredSymbolicMax);
14208 } else
14209 OS << "Unpredictable predicated symbolic max backedge-taken count.";
14210 OS << "\n";
14211 OS << " Predicates:\n";
14212 for (const auto *P : Preds)
14213 P->print(OS, 4);
14214 }
14215
14217 OS << "Loop ";
14218 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14219 OS << ": ";
14220 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
14221 }
14222}
14223
14224namespace llvm {
14225// Note: these overloaded operators need to be in the llvm namespace for them
14226// to be resolved correctly. If we put them outside the llvm namespace, the
14227//
14228// OS << ": " << SE.getLoopDisposition(SV, InnerL);
14229//
14230// code below "breaks" and start printing raw enum values as opposed to the
14231// string values.
14234 switch (LD) {
14236 OS << "Variant";
14237 break;
14239 OS << "Invariant";
14240 break;
14242 OS << "Uniform";
14243 break;
14245 OS << "Computable";
14246 break;
14247 }
14248 return OS;
14249}
14250
14253 switch (BD) {
14255 OS << "DoesNotDominate";
14256 break;
14258 OS << "Dominates";
14259 break;
14261 OS << "ProperlyDominates";
14262 break;
14263 }
14264 return OS;
14265}
14266} // namespace llvm
14267
14269 // ScalarEvolution's implementation of the print method is to print
14270 // out SCEV values of all instructions that are interesting. Doing
14271 // this potentially causes it to create new SCEV objects though,
14272 // which technically conflicts with the const qualifier. This isn't
14273 // observable from outside the class though, so casting away the
14274 // const isn't dangerous.
14275 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14276
14277 if (Opts.scalar_evolution_classify_expressions) {
14278 OS << "Classifying expressions for: ";
14279 F.printAsOperand(OS, /*PrintType=*/false);
14280 OS << "\n";
14281 for (Instruction &I : instructions(F))
14282 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
14283 OS << I << '\n';
14284 OS << " --> ";
14285 const SCEV *SV = SE.getSCEV(&I);
14286 SV->print(OS);
14287 if (!isa<SCEVCouldNotCompute>(SV)) {
14288 OS << " U: ";
14289 SE.getUnsignedRange(SV).print(OS);
14290 OS << " S: ";
14291 SE.getSignedRange(SV).print(OS);
14292 }
14293
14294 const Loop *L = LI.getLoopFor(I.getParent());
14295
14296 SCEVUse AtUse = SE.getSCEVAtScope(SV, L);
14297 if (AtUse != SV) {
14298 OS << " --> ";
14299 OS << AtUse;
14300 if (!isa<SCEVCouldNotCompute>(AtUse)) {
14301 OS << " U: ";
14302 SE.getUnsignedRange(AtUse).print(OS);
14303 OS << " S: ";
14304 SE.getSignedRange(AtUse).print(OS);
14305 }
14306 }
14307
14308 if (L) {
14309 OS << "\t\t" "Exits: ";
14310 SCEVUse ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
14311 if (!SE.isLoopInvariant(ExitValue, L)) {
14312 OS << "<<Unknown>>";
14313 } else {
14314 OS << ExitValue;
14315 }
14316
14317 ListSeparator LS(", ", "\t\tLoopDispositions: { ");
14318 for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
14319 OS << LS;
14320 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14321 OS << ": " << SE.getLoopDisposition(SV, Iter);
14322 }
14323
14324 for (const auto *InnerL : depth_first(L)) {
14325 if (InnerL == L)
14326 continue;
14327 OS << LS;
14328 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14329 OS << ": " << SE.getLoopDisposition(SV, InnerL);
14330 }
14331
14332 OS << " }";
14333 }
14334
14335 OS << "\n";
14336 }
14337 }
14338
14339 OS << "Determining loop execution counts for: ";
14340 F.printAsOperand(OS, /*PrintType=*/false);
14341 OS << "\n";
14342 for (Loop *I : LI)
14343 PrintLoopInfo(OS, &SE, I);
14344}
14345
14348 if (isa<SCEVConstant>(S))
14349 return LoopInvariant;
14350
14351 auto &Values = LoopDispositions[S];
14352 for (auto &V : Values) {
14353 if (V.getPointer() == L)
14354 return V.getInt();
14355 }
14356 Values.emplace_back(L, LoopVariant);
14357 LoopDisposition D = computeLoopDisposition(S, L);
14358 auto &Values2 = LoopDispositions[S];
14359 for (auto &V : llvm::reverse(Values2)) {
14360 if (V.getPointer() == L) {
14361 V.setInt(D);
14362 break;
14363 }
14364 }
14365 return D;
14366}
14367
14369ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
14370 switch (S->getSCEVType()) {
14371 case scConstant:
14372 case scVScale:
14373 return LoopInvariant;
14374 case scAddRecExpr: {
14375 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14376
14377 // If L is the addrec's loop, it's computable.
14378 if (AR->getLoop() == L)
14379 return LoopComputable;
14380
14381 // Add recurrences are never invariant in the function-body (null loop).
14382 if (!L)
14383 return LoopVariant;
14384
14385 // Everything that is not defined at loop entry is variant.
14386 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) {
14387 if (L->contains(AR->getLoop()) &&
14388 llvm::all_of(AR->operands(),
14389 [&](const SCEV *Op) { return isLoopUniform(Op, L); }))
14390 return LoopUniform;
14391
14392 return LoopVariant;
14393 }
14394 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
14395 " dominate the contained loop's header?");
14396
14397 // This recurrence is invariant w.r.t. L if AR's loop contains L.
14398 if (AR->getLoop()->contains(L))
14399 return LoopInvariant;
14400
14401 // This recurrence is variant w.r.t. L if any of its operands
14402 // are variant.
14403 for (SCEVUse Op : AR->operands())
14404 if (!isLoopInvariant(Op, L))
14405 return LoopVariant;
14406
14407 // Otherwise it's loop-invariant.
14408 return LoopInvariant;
14409 }
14410 case scTruncate:
14411 case scZeroExtend:
14412 case scSignExtend:
14413 case scPtrToAddr:
14414 case scAddExpr:
14415 case scMulExpr:
14416 case scUDivExpr:
14417 case scUMaxExpr:
14418 case scSMaxExpr:
14419 case scUMinExpr:
14420 case scSMinExpr:
14421 case scSequentialUMinExpr: {
14422 bool HasVarying = false;
14423 bool HasUniform = false;
14424 for (SCEVUse Op : S->operands()) {
14426 if (D == LoopVariant)
14427 return LoopVariant;
14428 if (D == LoopComputable)
14429 HasVarying = true;
14430 if (D == LoopUniform)
14431 HasUniform = true;
14432 }
14433 return HasVarying ? (HasUniform ? LoopVariant : LoopComputable)
14434 : (HasUniform ? LoopUniform : LoopInvariant);
14435 }
14436 case scUnknown:
14437 // All non-instruction values are loop invariant. All instructions are loop
14438 // invariant if they are not contained in the specified loop.
14439 // Instructions are never considered invariant in the function body
14440 // (null loop) because they are defined within the "loop".
14442 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
14443 return LoopInvariant;
14444 case scCouldNotCompute:
14445 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14446 }
14447 llvm_unreachable("Unknown SCEV kind!");
14448}
14449
14450bool ScalarEvolution::isLoopUniform(const SCEV *S, const Loop *L) {
14452 return D == LoopUniform || D == LoopInvariant;
14453}
14454
14456 return getLoopDisposition(S, L) == LoopInvariant;
14457}
14458
14460 return getLoopDisposition(S, L) == LoopComputable;
14461}
14462
14465 if (isa<SCEVConstant>(S))
14467
14468 auto &Values = BlockDispositions[S];
14469 for (auto &V : Values) {
14470 if (V.getPointer() == BB)
14471 return V.getInt();
14472 }
14473 Values.emplace_back(BB, DoesNotDominateBlock);
14474 BlockDisposition D = computeBlockDisposition(S, BB);
14475 auto &Values2 = BlockDispositions[S];
14476 for (auto &V : llvm::reverse(Values2)) {
14477 if (V.getPointer() == BB) {
14478 V.setInt(D);
14479 break;
14480 }
14481 }
14482 return D;
14483}
14484
14486ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
14487 switch (S->getSCEVType()) {
14488 case scConstant:
14489 case scVScale:
14491 case scAddRecExpr: {
14492 // This uses a "dominates" query instead of "properly dominates" query
14493 // to test for proper dominance too, because the instruction which
14494 // produces the addrec's value is a PHI, and a PHI effectively properly
14495 // dominates its entire containing block.
14496 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14497 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
14498 return DoesNotDominateBlock;
14499
14500 // Fall through into SCEVNAryExpr handling.
14501 [[fallthrough]];
14502 }
14503 case scTruncate:
14504 case scZeroExtend:
14505 case scSignExtend:
14506 case scPtrToAddr:
14507 case scAddExpr:
14508 case scMulExpr:
14509 case scUDivExpr:
14510 case scUMaxExpr:
14511 case scSMaxExpr:
14512 case scUMinExpr:
14513 case scSMinExpr:
14514 case scSequentialUMinExpr: {
14515 bool Proper = true;
14516 for (const SCEV *NAryOp : S->operands()) {
14518 if (D == DoesNotDominateBlock)
14519 return DoesNotDominateBlock;
14520 if (D == DominatesBlock)
14521 Proper = false;
14522 }
14523 return Proper ? ProperlyDominatesBlock : DominatesBlock;
14524 }
14525 case scUnknown:
14526 if (Instruction *I =
14528 if (I->getParent() == BB)
14529 return DominatesBlock;
14530 if (DT.properlyDominates(I->getParent(), BB))
14532 return DoesNotDominateBlock;
14533 }
14535 case scCouldNotCompute:
14536 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14537 }
14538 llvm_unreachable("Unknown SCEV kind!");
14539}
14540
14541bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
14542 return getBlockDisposition(S, BB) >= DominatesBlock;
14543}
14544
14547}
14548
14549void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
14550 bool Predicated) {
14551 auto &BECounts =
14552 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14553 auto It = BECounts.find(L);
14554 if (It != BECounts.end()) {
14555 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
14556 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14557 if (!isa<SCEVConstant>(S)) {
14558 auto UserIt = BECountUsers.find(S);
14559 assert(UserIt != BECountUsers.end());
14560 UserIt->second.erase({L, Predicated});
14561 }
14562 }
14563 }
14564 BECounts.erase(It);
14565 }
14566}
14567
14568void ScalarEvolution::forgetMemoizedResults(ArrayRef<SCEVUse> SCEVs) {
14569 SmallPtrSet<const SCEV *, 8> ToForget(llvm::from_range, SCEVs);
14570 SmallVector<SCEVUse, 8> Worklist(ToForget.begin(), ToForget.end());
14571
14572 while (!Worklist.empty()) {
14573 const SCEV *Curr = Worklist.pop_back_val();
14574 auto Users = SCEVUsers.find(Curr);
14575 if (Users != SCEVUsers.end())
14576 for (const auto *User : Users->second)
14577 if (ToForget.insert(User).second)
14578 Worklist.push_back(User);
14579 }
14580
14581 for (const auto *S : ToForget)
14582 forgetMemoizedResultsImpl(S);
14583
14584 PredicatedSCEVRewrites.remove_if(
14585 [&](const auto &Entry) { return ToForget.count(Entry.first.first); });
14586}
14587
14588void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
14589 LoopDispositions.erase(S);
14590 BlockDispositions.erase(S);
14591 UnsignedRanges.erase(S);
14592 SignedRanges.erase(S);
14593 HasRecMap.erase(S);
14594 ConstantMultipleCache.erase(S);
14595
14596 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
14597 UnsignedWrapViaInductionTried.erase(AR);
14598 SignedWrapViaInductionTried.erase(AR);
14599 }
14600
14601 auto ExprIt = ExprValueMap.find(S);
14602 if (ExprIt != ExprValueMap.end()) {
14603 for (Value *V : ExprIt->second) {
14604 auto ValueIt = ValueExprMap.find_as(V);
14605 if (ValueIt != ValueExprMap.end())
14606 ValueExprMap.erase(ValueIt);
14607 }
14608 ExprValueMap.erase(ExprIt);
14609 }
14610
14611 auto ScopeIt = ValuesAtScopes.find(S);
14612 if (ScopeIt != ValuesAtScopes.end()) {
14613 for (const auto &Pair : ScopeIt->second)
14614 if (!isa_and_nonnull<SCEVConstant>(Pair.second))
14615 llvm::erase(ValuesAtScopesUsers[Pair.second.getPointer()],
14616 std::make_pair(Pair.first, S));
14617 ValuesAtScopes.erase(ScopeIt);
14618 }
14619
14620 auto ScopeUserIt = ValuesAtScopesUsers.find(S);
14621 if (ScopeUserIt != ValuesAtScopesUsers.end()) {
14622 for (const auto &Pair : ScopeUserIt->second)
14623 // The recorded value at scope is a use of S, which may carry no-wrap
14624 // flags that are not part of this key.
14625 llvm::erase_if(ValuesAtScopes[Pair.second], [&](const auto &LS) {
14626 return LS.first == Pair.first && LS.second.getPointer() == S;
14627 });
14628 ValuesAtScopesUsers.erase(ScopeUserIt);
14629 }
14630
14631 auto BEUsersIt = BECountUsers.find(S);
14632 if (BEUsersIt != BECountUsers.end()) {
14633 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
14634 auto Copy = BEUsersIt->second;
14635 for (const auto &Pair : Copy)
14636 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
14637 BECountUsers.erase(BEUsersIt);
14638 }
14639
14640 auto FoldUser = FoldCacheUser.find(S);
14641 if (FoldUser != FoldCacheUser.end())
14642 for (auto &KV : FoldUser->second)
14643 FoldCache.erase(KV);
14644 FoldCacheUser.erase(S);
14645}
14646
14647void
14648ScalarEvolution::getUsedLoops(const SCEV *S,
14649 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
14650 struct FindUsedLoops {
14651 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
14652 : LoopsUsed(LoopsUsed) {}
14653 SmallPtrSetImpl<const Loop *> &LoopsUsed;
14654 bool follow(const SCEV *S) {
14655 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
14656 LoopsUsed.insert(AR->getLoop());
14657 return true;
14658 }
14659
14660 bool isDone() const { return false; }
14661 };
14662
14663 FindUsedLoops F(LoopsUsed);
14664 SCEVTraversal<FindUsedLoops>(F).visitAll(S);
14665}
14666
14667void ScalarEvolution::getReachableBlocks(
14670 Worklist.push_back(&F.getEntryBlock());
14671 while (!Worklist.empty()) {
14672 BasicBlock *BB = Worklist.pop_back_val();
14673 if (!Reachable.insert(BB).second)
14674 continue;
14675
14676 Value *Cond;
14677 BasicBlock *TrueBB, *FalseBB;
14678 if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
14679 m_BasicBlock(FalseBB)))) {
14680 if (auto *C = dyn_cast<ConstantInt>(Cond)) {
14681 Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
14682 continue;
14683 }
14684
14685 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14686 const SCEV *L = getSCEV(Cmp->getOperand(0));
14687 const SCEV *R = getSCEV(Cmp->getOperand(1));
14688 if (isKnownPredicateViaConstantRanges(Cmp->getCmpPredicate(), L, R)) {
14689 Worklist.push_back(TrueBB);
14690 continue;
14691 }
14692 if (isKnownPredicateViaConstantRanges(Cmp->getInverseCmpPredicate(), L,
14693 R)) {
14694 Worklist.push_back(FalseBB);
14695 continue;
14696 }
14697 }
14698 }
14699
14700 append_range(Worklist, successors(BB));
14701 }
14702}
14703
14705 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14706 ScalarEvolution SE2(F, TLI, AC, DT, LI);
14707
14708 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
14709
14710 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
14711 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
14712 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
14713
14714 const SCEV *visitConstant(const SCEVConstant *Constant) {
14715 return SE.getConstant(Constant->getAPInt());
14716 }
14717
14718 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14719 return SE.getUnknown(Expr->getValue());
14720 }
14721
14722 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
14723 return SE.getCouldNotCompute();
14724 }
14725 };
14726
14727 SCEVMapper SCM(SE2);
14728 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
14729 SE2.getReachableBlocks(ReachableBlocks, F);
14730
14731 auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
14732 if (containsUndefs(Old) || containsUndefs(New)) {
14733 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
14734 // not propagate undef aggressively). This means we can (and do) fail
14735 // verification in cases where a transform makes a value go from "undef"
14736 // to "undef+1" (say). The transform is fine, since in both cases the
14737 // result is "undef", but SCEV thinks the value increased by 1.
14738 return nullptr;
14739 }
14740
14741 // Unless -verify-scev-strict is set, we only compare constant deltas.
14742 const SCEV *Delta = SE2.getMinusSCEV(Old, New);
14743 if (!Opts.verify_scev_strict && !isa<SCEVConstant>(Delta))
14744 return nullptr;
14745
14746 return Delta;
14747 };
14748
14749 while (!LoopStack.empty()) {
14750 auto *L = LoopStack.pop_back_val();
14751 llvm::append_range(LoopStack, *L);
14752
14753 // Only verify BECounts in reachable loops. For an unreachable loop,
14754 // any BECount is legal.
14755 if (!ReachableBlocks.contains(L->getHeader()))
14756 continue;
14757
14758 // Only verify cached BECounts. Computing new BECounts may change the
14759 // results of subsequent SCEV uses.
14760 auto It = BackedgeTakenCounts.find(L);
14761 if (It == BackedgeTakenCounts.end())
14762 continue;
14763
14764 auto *CurBECount =
14765 SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
14766 auto *NewBECount = SE2.getBackedgeTakenCount(L);
14767
14768 if (CurBECount == SE2.getCouldNotCompute() ||
14769 NewBECount == SE2.getCouldNotCompute()) {
14770 // NB! This situation is legal, but is very suspicious -- whatever pass
14771 // change the loop to make a trip count go from could not compute to
14772 // computable or vice-versa *should have* invalidated SCEV. However, we
14773 // choose not to assert here (for now) since we don't want false
14774 // positives.
14775 continue;
14776 }
14777
14778 if (SE.getTypeSizeInBits(CurBECount->getType()) >
14779 SE.getTypeSizeInBits(NewBECount->getType()))
14780 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
14781 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
14782 SE.getTypeSizeInBits(NewBECount->getType()))
14783 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
14784
14785 const SCEV *Delta = GetDelta(CurBECount, NewBECount);
14786 if (Delta && !Delta->isZero()) {
14787 dbgs() << "Trip Count for " << *L << " Changed!\n";
14788 dbgs() << "Old: " << *CurBECount << "\n";
14789 dbgs() << "New: " << *NewBECount << "\n";
14790 dbgs() << "Delta: " << *Delta << "\n";
14791 std::abort();
14792 }
14793 }
14794
14795 // Collect all valid loops currently in LoopInfo.
14796 SmallPtrSet<Loop *, 32> ValidLoops;
14797 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
14798 while (!Worklist.empty()) {
14799 Loop *L = Worklist.pop_back_val();
14800 if (ValidLoops.insert(L).second)
14801 Worklist.append(L->begin(), L->end());
14802 }
14803 for (const auto &KV : ValueExprMap) {
14804#ifndef NDEBUG
14805 // Check for SCEV expressions referencing invalid/deleted loops.
14806 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14807 assert(ValidLoops.contains(AR->getLoop()) &&
14808 "AddRec references invalid loop");
14809 }
14810#endif
14811
14812 // Check that the value is also part of the reverse map.
14813 auto It = ExprValueMap.find(KV.second);
14814 if (It == ExprValueMap.end() || !is_contained(It->second, KV.first)) {
14815 dbgs() << "Value " << *KV.first
14816 << " is in ValueExprMap but not in ExprValueMap\n";
14817 std::abort();
14818 }
14819
14820 if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
14821 if (!ReachableBlocks.contains(I->getParent()))
14822 continue;
14823 const SCEV *OldSCEV = SCM.visit(KV.second);
14824 const SCEV *NewSCEV = SE2.getSCEV(I);
14825 const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14826 if (Delta && !Delta->isZero()) {
14827 dbgs() << "SCEV for value " << *I << " changed!\n"
14828 << "Old: " << *OldSCEV << "\n"
14829 << "New: " << *NewSCEV << "\n"
14830 << "Delta: " << *Delta << "\n";
14831 std::abort();
14832 }
14833 }
14834 }
14835
14836 for (const auto &KV : ExprValueMap) {
14837 for (Value *V : KV.second) {
14838 const SCEV *S = ValueExprMap.lookup(V);
14839 if (!S) {
14840 dbgs() << "Value " << *V
14841 << " is in ExprValueMap but not in ValueExprMap\n";
14842 std::abort();
14843 }
14844 if (S != KV.first) {
14845 dbgs() << "Value " << *V << " mapped to " << *S << " rather than "
14846 << *KV.first << "\n";
14847 std::abort();
14848 }
14849 }
14850 }
14851
14852 // Verify integrity of SCEV users.
14853 for (const auto &S : UniqueSCEVs) {
14854 for (SCEVUse Op : S.operands()) {
14855 // We do not store dependencies of constants.
14856 if (isa<SCEVConstant>(Op))
14857 continue;
14858 auto It = SCEVUsers.find(Op);
14859 if (It != SCEVUsers.end() && It->second.count(&S))
14860 continue;
14861 dbgs() << "Use of operand " << *Op << " by user " << S
14862 << " is not being tracked!\n";
14863 std::abort();
14864 }
14865 }
14866
14867 // Verify integrity of ValuesAtScopes users.
14868 for (const auto &ValueAndVec : ValuesAtScopes) {
14869 const SCEV *Value = ValueAndVec.first;
14870 for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
14871 const Loop *L = LoopAndValueAtScope.first;
14872 SCEVUse ValueAtScope = LoopAndValueAtScope.second;
14873 if (!isa<SCEVConstant>(ValueAtScope)) {
14874 auto It = ValuesAtScopesUsers.find(ValueAtScope.getPointer());
14875 if (It != ValuesAtScopesUsers.end() &&
14876 is_contained(It->second, std::make_pair(L, Value)))
14877 continue;
14878 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14879 << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
14880 std::abort();
14881 }
14882 }
14883 }
14884
14885 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
14886 const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
14887 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
14888 const Loop *L = LoopAndValue.first;
14889 const SCEV *Value = LoopAndValue.second;
14891 auto It = ValuesAtScopes.find(Value);
14892 // The recorded value at scope may carry no-wrap flags that are not part
14893 // of the key it is recorded under.
14894 if (It != ValuesAtScopes.end() && any_of(It->second, [&](const auto &LS) {
14895 return LS.first == L && LS.second.getPointer() == ValueAtScope;
14896 }))
14897 continue;
14898 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14899 << *ValueAtScope << " missing in ValuesAtScopes\n";
14900 std::abort();
14901 }
14902 }
14903
14904 // Verify integrity of BECountUsers.
14905 auto VerifyBECountUsers = [&](bool Predicated) {
14906 auto &BECounts =
14907 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14908 for (const auto &LoopAndBEInfo : BECounts) {
14909 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
14910 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14911 if (!isa<SCEVConstant>(S)) {
14912 auto UserIt = BECountUsers.find(S);
14913 if (UserIt != BECountUsers.end() &&
14914 UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
14915 continue;
14916 dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
14917 << " missing from BECountUsers\n";
14918 std::abort();
14919 }
14920 }
14921 }
14922 }
14923 };
14924 VerifyBECountUsers(/* Predicated */ false);
14925 VerifyBECountUsers(/* Predicated */ true);
14926
14927 // Verify intergity of loop disposition cache.
14928 for (auto &[S, Values] : LoopDispositions) {
14929 for (auto [Loop, CachedDisposition] : Values) {
14930 const auto RecomputedDisposition = SE2.getLoopDisposition(S, Loop);
14931 if (CachedDisposition != RecomputedDisposition) {
14932 dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
14933 << " is incorrect: cached " << CachedDisposition << ", actual "
14934 << RecomputedDisposition << "\n";
14935 std::abort();
14936 }
14937 }
14938 }
14939
14940 // Verify integrity of the block disposition cache.
14941 for (auto &[S, Values] : BlockDispositions) {
14942 for (auto [BB, CachedDisposition] : Values) {
14943 const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
14944 if (CachedDisposition != RecomputedDisposition) {
14945 dbgs() << "Cached disposition of " << *S << " for block %"
14946 << BB->getName() << " is incorrect: cached " << CachedDisposition
14947 << ", actual " << RecomputedDisposition << "\n";
14948 std::abort();
14949 }
14950 }
14951 }
14952
14953 // Verify FoldCache/FoldCacheUser caches.
14954 for (auto [FoldID, Expr] : FoldCache) {
14955 auto I = FoldCacheUser.find(Expr);
14956 if (I == FoldCacheUser.end()) {
14957 dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
14958 << "!\n";
14959 std::abort();
14960 }
14961 if (!is_contained(I->second, FoldID)) {
14962 dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
14963 std::abort();
14964 }
14965 }
14966 for (auto [Expr, IDs] : FoldCacheUser) {
14967 for (auto &FoldID : IDs) {
14968 const SCEV *S = FoldCache.lookup(FoldID);
14969 if (!S) {
14970 dbgs() << "Missing entry in FoldCache for expression " << *Expr
14971 << "!\n";
14972 std::abort();
14973 }
14974 if (S != Expr) {
14975 dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: " << *S
14976 << " != " << *Expr << "!\n";
14977 std::abort();
14978 }
14979 }
14980 }
14981
14982 // Verify that ConstantMultipleCache computations are correct. We check that
14983 // cached multiples and recomputed multiples are multiples of each other to
14984 // verify correctness. It is possible that a recomputed multiple is different
14985 // from the cached multiple due to strengthened no wrap flags or changes in
14986 // KnownBits computations.
14987 for (auto [S, Multiple] : ConstantMultipleCache) {
14988 APInt RecomputedMultiple = SE2.getConstantMultiple(S);
14989 if ((Multiple != 0 && RecomputedMultiple != 0 &&
14990 Multiple.urem(RecomputedMultiple) != 0 &&
14991 RecomputedMultiple.urem(Multiple) != 0)) {
14992 dbgs() << "Incorrect cached computation in ConstantMultipleCache for "
14993 << *S << " : Computed " << RecomputedMultiple
14994 << " but cache contains " << Multiple << "!\n";
14995 std::abort();
14996 }
14997 }
14998}
14999
15001 Function &F, const PreservedAnalyses &PA,
15002 FunctionAnalysisManager::Invalidator &Inv) {
15003 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
15004 // of its dependencies is invalidated.
15005 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
15006 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
15007 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
15008 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
15009 Inv.invalidate<LoopAnalysis>(F, PA);
15010}
15011
15012AnalysisKey ScalarEvolutionAnalysis::Key;
15013
15016 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
15017 auto &AC = AM.getResult<AssumptionAnalysis>(F);
15018 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
15019 auto &LI = AM.getResult<LoopAnalysis>(F);
15020 return ScalarEvolution(F, TLI, AC, DT, LI);
15021}
15022
15028
15031 // For compatibility with opt's -analyze feature under legacy pass manager
15032 // which was not ported to NPM. This keeps tests using
15033 // update_analyze_test_checks.py working.
15034 OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
15035 << F.getName() << "':\n";
15037 return PreservedAnalyses::all();
15038}
15039
15041 "Scalar Evolution Analysis", false, true)
15047 "Scalar Evolution Analysis", false, true)
15048
15049char ScalarEvolutionWrapperPass::ID = 0;
15050
15052
15054 SE.reset(new ScalarEvolution(
15056 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
15058 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
15059 return false;
15060}
15061
15063
15065 SE->print(OS);
15066}
15067
15069 if (!VerifySCEV)
15070 return;
15071
15072 SE->verify();
15073}
15074
15082
15084 const SCEV *RHS) {
15085 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
15086}
15087
15088const SCEVPredicate *
15090 const SCEV *LHS, const SCEV *RHS) {
15092 assert(LHS->getType() == RHS->getType() &&
15093 "Type mismatch between LHS and RHS");
15094 // Unique this node based on the arguments
15095 ID.AddInteger(SCEVPredicate::P_Compare);
15096 ID.AddInteger(Pred);
15097 ID.AddPointer(LHS);
15098 ID.AddPointer(RHS);
15100 if (const auto *S = UniquePreds.lookup(ID, Token))
15101 return S;
15102 SCEVComparePredicate *Eq = new (SCEVAllocator)
15103 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
15104 UniquePreds.insert(Eq, Token);
15105 return Eq;
15106}
15107
15109 const SCEVAddRecExpr *AR,
15112 // Unique this node based on the arguments
15114 ID.AddPointer(AR);
15115 ID.AddInteger(AddedFlags);
15117 if (const auto *S = UniquePreds.lookup(ID, Token))
15118 return S;
15119 auto *OF = new (SCEVAllocator)
15120 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
15121 UniquePreds.insert(OF, Token);
15122 return OF;
15123}
15124
15125namespace {
15126
15127class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
15128public:
15129
15130 /// Rewrites \p S in the context of a loop L and the SCEV predication
15131 /// infrastructure.
15132 ///
15133 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
15134 /// equivalences present in \p Pred.
15135 ///
15136 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
15137 /// \p NewPreds such that the result will be an AddRecExpr.
15138 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
15140 const SCEVPredicate *Pred) {
15141 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
15142 return Rewriter.visit(S);
15143 }
15144
15145 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
15146 if (Pred) {
15147 if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
15148 for (const auto *Pred : U->getPredicates())
15149 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
15150 if (IPred->getLHS() == Expr &&
15151 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15152 return IPred->getRHS();
15153 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
15154 if (IPred->getLHS() == Expr &&
15155 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15156 return IPred->getRHS();
15157 }
15158 }
15159 return convertToAddRecWithPreds(Expr);
15160 }
15161
15162 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
15163 const SCEV *Operand = visit(Expr->getOperand());
15164 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15165 if (AR && AR->getLoop() == L && AR->isAffine()) {
15166 // This couldn't be folded because the operand didn't have the nuw
15167 // flag. Add the nusw flag as an assumption that we could make.
15168 const SCEV *Step = AR->getStepRecurrence(SE);
15169 Type *Ty = Expr->getType();
15170 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
15171 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
15172 SE.getSignExtendExpr(Step, Ty), L,
15173 AR->getNoWrapFlags());
15174 }
15175 return SE.getZeroExtendExpr(Operand, Expr->getType());
15176 }
15177
15178 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
15179 const SCEV *Operand = visit(Expr->getOperand());
15180 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15181 if (AR && AR->getLoop() == L && AR->isAffine()) {
15182 // This couldn't be folded because the operand didn't have the nsw
15183 // flag. Add the nssw flag as an assumption that we could make.
15184 const SCEV *Step = AR->getStepRecurrence(SE);
15185 Type *Ty = Expr->getType();
15186 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
15187 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
15188 SE.getSignExtendExpr(Step, Ty), L,
15189 AR->getNoWrapFlags());
15190 }
15191 return SE.getSignExtendExpr(Operand, Expr->getType());
15192 }
15193
15194private:
15195 explicit SCEVPredicateRewriter(
15196 const Loop *L, ScalarEvolution &SE,
15197 SmallVectorImpl<const SCEVPredicate *> *NewPreds,
15198 const SCEVPredicate *Pred)
15199 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
15200
15201 bool addOverflowAssumption(const SCEVPredicate *P) {
15202 if (!NewPreds) {
15203 // Check if we've already made this assumption.
15204 return Pred && Pred->implies(P, SE);
15205 }
15206 NewPreds->push_back(P);
15207 return true;
15208 }
15209
15210 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
15212 auto *A = SE.getWrapPredicate(AR, AddedFlags);
15213 return addOverflowAssumption(A);
15214 }
15215
15216 // If \p Expr represents a PHINode, we try to see if it can be represented
15217 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
15218 // to add this predicate as a runtime overflow check, we return the AddRec.
15219 // If \p Expr does not meet these conditions (is not a PHI node, or we
15220 // couldn't create an AddRec for it, or couldn't add the predicate), we just
15221 // return \p Expr.
15222 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
15223 if (!isa<PHINode>(Expr->getValue()))
15224 return Expr;
15225 std::optional<
15226 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
15227 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
15228 if (!PredicatedRewrite)
15229 return Expr;
15230 for (const auto *P : PredicatedRewrite->second){
15231 // Wrap predicates from outer loops are not supported.
15232 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
15233 if (L != WP->getExpr()->getLoop())
15234 return Expr;
15235 }
15236 if (!addOverflowAssumption(P))
15237 return Expr;
15238 }
15239 return PredicatedRewrite->first;
15240 }
15241
15242 SmallVectorImpl<const SCEVPredicate *> *NewPreds;
15243 const SCEVPredicate *Pred;
15244 const Loop *L;
15245};
15246
15247} // end anonymous namespace
15248
15249const SCEV *
15251 const SCEVPredicate &Preds) {
15252 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
15253}
15254
15256 const SCEV *S, const Loop *L,
15259 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
15260 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
15261
15262 if (!AddRec)
15263 return nullptr;
15264
15265 // Check if any of the transformed predicates is known to be false. In that
15266 // case, it doesn't make sense to convert to a predicated AddRec, as the
15267 // versioned loop will never execute.
15268 for (const SCEVPredicate *Pred : TransformPreds) {
15269 auto *WrapPred = dyn_cast<SCEVWrapPredicate>(Pred);
15270 if (!WrapPred || WrapPred->getFlags() != SCEVWrapPredicate::IncrementNSSW)
15271 continue;
15272
15273 const SCEVAddRecExpr *AddRecToCheck = WrapPred->getExpr();
15274 const SCEV *ExitCount = getBackedgeTakenCount(AddRecToCheck->getLoop());
15275 if (isa<SCEVCouldNotCompute>(ExitCount))
15276 continue;
15277
15278 const SCEV *Step = AddRecToCheck->getStepRecurrence(*this);
15279 if (!Step->isOne())
15280 continue;
15281
15282 ExitCount = getTruncateOrSignExtend(ExitCount, Step->getType());
15283 const SCEV *Add = getAddExpr(AddRecToCheck->getStart(), ExitCount);
15284 if (isKnownPredicate(CmpInst::ICMP_SLT, Add, AddRecToCheck->getStart()))
15285 return nullptr;
15286 }
15287
15288 // Since the transformation was successful, we can now transfer the SCEV
15289 // predicates.
15290 Preds.append(TransformPreds.begin(), TransformPreds.end());
15291
15292 return AddRec;
15293}
15294
15295/// SCEV predicates
15299
15301 const ICmpInst::Predicate Pred,
15302 const SCEV *LHS, const SCEV *RHS)
15303 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
15304 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
15305 assert(LHS != RHS && "LHS and RHS are the same SCEV");
15306}
15307
15309 ScalarEvolution &SE) const {
15310 const auto *Op = dyn_cast<SCEVComparePredicate>(N);
15311
15312 if (!Op)
15313 return false;
15314
15315 if (Pred != ICmpInst::ICMP_EQ)
15316 return false;
15317
15318 return Op->LHS == LHS && Op->RHS == RHS;
15319}
15320
15321bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
15322
15324 if (Pred == ICmpInst::ICMP_EQ)
15325 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
15326 else
15327 OS.indent(Depth) << "Compare predicate: " << *LHS << " " << Pred << ") "
15328 << *RHS << "\n";
15329
15330}
15331
15333 const SCEVAddRecExpr *AR,
15334 IncrementWrapFlags Flags)
15335 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
15336
15337const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
15338
15340 ScalarEvolution &SE) const {
15341 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
15342 if (!Op || setFlags(Flags, Op->Flags) != Flags)
15343 return false;
15344
15345 if (Op->AR == AR)
15346 return true;
15347
15348 if (Flags != SCEVWrapPredicate::IncrementNSSW &&
15350 return false;
15351
15352 const SCEV *Start = AR->getStart();
15353 const SCEV *OpStart = Op->AR->getStart();
15354 if (Start->getType()->isPointerTy() != OpStart->getType()->isPointerTy())
15355 return false;
15356
15357 // Reject pointers to different address spaces.
15358 if (Start->getType()->isPointerTy() && Start->getType() != OpStart->getType())
15359 return false;
15360
15361 // NUSW/NSSW on a wider-type AddRec does not imply the same on a
15362 // narrower-type AddRec.
15363 if (SE.getTypeSizeInBits(AR->getType()) >
15364 SE.getTypeSizeInBits(Op->AR->getType()))
15365 return false;
15366
15367 const SCEV *Step = AR->getStepRecurrence(SE);
15368 const SCEV *OpStep = Op->AR->getStepRecurrence(SE);
15369 if (!SE.isKnownPositive(Step) || !SE.isKnownPositive(OpStep))
15370 return false;
15371
15372 // If both steps are positive, this implies N, if N's start and step are
15373 // ULE/SLE (for NSUW/NSSW) than this'.
15374 Type *WiderTy = SE.getWiderType(Step->getType(), OpStep->getType());
15375 Step = SE.getNoopOrZeroExtend(Step, WiderTy);
15376 OpStep = SE.getNoopOrZeroExtend(OpStep, WiderTy);
15377
15378 bool IsNUW = Flags == SCEVWrapPredicate::IncrementNUSW;
15379 OpStart = IsNUW ? SE.getNoopOrZeroExtend(OpStart, WiderTy)
15380 : SE.getNoopOrSignExtend(OpStart, WiderTy);
15381 Start = IsNUW ? SE.getNoopOrZeroExtend(Start, WiderTy)
15382 : SE.getNoopOrSignExtend(Start, WiderTy);
15384 return SE.isKnownPredicate(Pred, OpStep, Step) &&
15385 SE.isKnownPredicate(Pred, OpStart, Start);
15386}
15387
15389 SCEVFlags ScevFlags = AR->getNoWrapFlags();
15390 IncrementWrapFlags IFlags = Flags;
15391
15392 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
15393 IFlags = clearFlags(IFlags, IncrementNSSW);
15394
15395 return IFlags == IncrementAnyWrap;
15396}
15397
15398void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
15399 OS.indent(Depth) << *getExpr() << " Added Flags: ";
15401 OS << "<nusw>";
15403 OS << "<nssw>";
15404 OS << "\n";
15405}
15406
15407/// Union predicates don't get cached so create a dummy set ID for it.
15409 ScalarEvolution &SE)
15411 for (const auto *P : Preds)
15412 add(P, SE);
15413}
15414
15416 return all_of(Preds,
15417 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
15418}
15419
15421 ScalarEvolution &SE) const {
15422 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
15423 return all_of(Set->Preds, [this, &SE](const SCEVPredicate *I) {
15424 return this->implies(I, SE);
15425 });
15426
15427 if (any_of(Preds,
15428 [N, &SE](const SCEVPredicate *I) { return I->implies(N, SE); }))
15429 return true;
15430
15431 // A wrap predicate may be implied by a wrap predicate in Preds after applying
15432 // equal predicates.
15433 const auto *NWrap = dyn_cast<SCEVWrapPredicate>(N);
15434 if (!NWrap)
15435 return false;
15436 const Loop *L = NWrap->getExpr()->getLoop();
15437 return any_of(Preds, [&](const SCEVPredicate *I) {
15438 const auto *IWrap = dyn_cast<SCEVWrapPredicate>(I);
15439 if (!IWrap)
15440 return false;
15441 const auto *RewrittenAR = dyn_cast<SCEVAddRecExpr>(
15442 SE.rewriteUsingPredicate(IWrap->getExpr(), L, *this));
15443 return RewrittenAR &&
15444 SE.getWrapPredicate(RewrittenAR, IWrap->getFlags())->implies(N, SE);
15445 });
15446}
15447
15449 for (const auto *Pred : Preds)
15450 Pred->print(OS, Depth);
15451}
15452
15453void SCEVUnionPredicate::add(const SCEVPredicate *N, ScalarEvolution &SE) {
15454 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
15455 for (const auto *Pred : Set->Preds)
15456 add(Pred, SE);
15457 return;
15458 }
15459
15460 // Implication checks are quadratic in the number of predicates. Stop doing
15461 // them if there are many predicates, as they should be too expensive to use
15462 // anyway at that point.
15463 bool CheckImplies = Preds.size() < 16;
15464
15465 // Only add predicate if it is not already implied by this union predicate.
15466 if (CheckImplies && implies(N, SE))
15467 return;
15468
15469 // Build a new vector containing the current predicates, except the ones that
15470 // are implied by the new predicate N.
15472 for (auto *P : Preds) {
15473 if (CheckImplies && N->implies(P, SE))
15474 continue;
15475 PrunedPreds.push_back(P);
15476 }
15477 Preds = std::move(PrunedPreds);
15478 Preds.push_back(N);
15479}
15480
15482 Loop &L)
15483 : SE(SE), L(L) {
15485 Preds = std::make_unique<SCEVUnionPredicate>(Empty, SE);
15486}
15487
15489 for (const SCEV *Op : Ops)
15490 // We do not expect that forgetting cached data for SCEVConstants will ever
15491 // open any prospects for sharpening or introduce any correctness issues,
15492 // so we don't bother storing their dependencies.
15493 if (!isa<SCEVConstant>(Op))
15494 SCEVUsers[Op].insert(User);
15495}
15496
15498 const SCEV *Expr = SE.getSCEV(V);
15499 return getPredicatedSCEV(Expr);
15500}
15501
15503 RewriteEntry &Entry = RewriteMap[Expr];
15504
15505 // If we already have an entry and the version matches, return it.
15506 if (Entry.second && Generation == Entry.first)
15507 return Entry.second;
15508
15509 // We found an entry but it's stale. Rewrite the stale entry
15510 // according to the current predicate.
15511 if (Entry.second)
15512 Expr = Entry.second;
15513
15514 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
15515 Entry = {Generation, NewSCEV};
15516
15517 return NewSCEV;
15518}
15519
15521 if (!BackedgeCount) {
15523 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
15524 for (const auto *P : Preds)
15525 addPredicate(*P);
15526 }
15527 return BackedgeCount;
15528}
15529
15531 if (!SymbolicMaxBackedgeCount) {
15533 SymbolicMaxBackedgeCount =
15534 SE.getPredicatedSymbolicMaxBackedgeTakenCount(&L, Preds);
15535 for (const auto *P : Preds)
15536 addPredicate(*P);
15537 }
15538 return SymbolicMaxBackedgeCount;
15539}
15540
15542 if (!SmallConstantMaxTripCount) {
15544 SmallConstantMaxTripCount = SE.getSmallConstantMaxTripCount(&L, &Preds);
15545 for (const auto *P : Preds)
15546 addPredicate(*P);
15547 }
15548 return *SmallConstantMaxTripCount;
15549}
15550
15552 if (Preds->implies(&Pred, SE))
15553 return;
15554
15555 Preds = std::make_unique<SCEVUnionPredicate>(Preds->getUnionWith(&Pred, SE));
15556 updateGeneration();
15557}
15558
15561 for (const SCEVPredicate *P : Preds)
15562 addPredicate(*P);
15563}
15564
15566 return *Preds;
15567}
15568
15569void PredicatedScalarEvolution::updateGeneration() {
15570 // If the generation number wrapped recompute everything.
15571 if (++Generation == 0) {
15572 for (auto &II : RewriteMap) {
15573 const SCEV *Rewritten = II.second.second;
15574 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
15575 }
15576 }
15577}
15578
15581 const SCEV *Expr = this->getSCEV(V);
15583 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
15584
15585 if (!New)
15586 return nullptr;
15587
15588 if (ExtraPreds) {
15589 ExtraPreds->append(NewPreds);
15590 return New;
15591 }
15592
15593 addPredicates(NewPreds);
15594
15595 RewriteMap[SE.getSCEV(V)] = {Generation, New};
15596 return New;
15597}
15598
15601 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
15602 Preds(std::make_unique<SCEVUnionPredicate>(*Init.Preds)),
15603 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {}
15604
15606 // For each block.
15607 for (auto *BB : L.getBlocks())
15608 for (auto &I : *BB) {
15609 if (!SE.isSCEVable(I.getType()))
15610 continue;
15611
15612 auto *Expr = SE.getSCEV(&I);
15613 auto II = RewriteMap.find(Expr);
15614
15615 if (II == RewriteMap.end())
15616 continue;
15617
15618 // Don't print things that are not interesting.
15619 if (II->second.second == Expr)
15620 continue;
15621
15622 OS.indent(Depth) << "[PSE]" << I << ":\n";
15623 OS.indent(Depth + 2) << *Expr << "\n";
15624 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
15625 }
15626}
15627
15628void ScalarEvolution::LoopGuards::collectPending() {
15629 const Loop *L = PendingLoop;
15630 if (!L)
15631 return;
15632 PendingLoop = nullptr;
15633 BasicBlock *Pred = L->getLoopPredecessor();
15634 if (!Pred)
15635 return;
15637 collectFromBlock(SE, *this, L->getHeader(), Pred, VisitedBlocks);
15638}
15639
15640void ScalarEvolution::LoopGuards::collectFromPHI(
15644 unsigned Depth) {
15645 if (!SE.isSCEVable(Phi.getType()))
15646 return;
15647
15648 using MinMaxPattern = std::pair<const SCEVConstant *, SCEVTypes>;
15649 auto GetMinMaxConst = [&](unsigned IncomingIdx) -> MinMaxPattern {
15650 const BasicBlock *InBlock = Phi.getIncomingBlock(IncomingIdx);
15651 if (!VisitedBlocks.insert(InBlock).second)
15652 return {nullptr, scCouldNotCompute};
15653
15654 // Avoid analyzing unreachable blocks so that we don't get trapped
15655 // traversing cycles with ill-formed dominance or infinite cycles
15656 if (!SE.DT.isReachableFromEntry(InBlock))
15657 return {nullptr, scCouldNotCompute};
15658
15659 auto [G, Inserted] = IncomingGuards.try_emplace(InBlock, LoopGuards(SE));
15660 if (Inserted)
15661 collectFromBlock(SE, G->second, Phi.getParent(), InBlock, VisitedBlocks,
15662 Depth + 1);
15663 auto &RewriteMap = G->second.RewriteMap;
15664 if (RewriteMap.empty())
15665 return {nullptr, scCouldNotCompute};
15666 auto S = RewriteMap.find(SE.getSCEV(Phi.getIncomingValue(IncomingIdx)));
15667 if (S == RewriteMap.end())
15668 return {nullptr, scCouldNotCompute};
15669 auto *SM = dyn_cast_if_present<SCEVMinMaxExpr>(S->second);
15670 if (!SM)
15671 return {nullptr, scCouldNotCompute};
15672 if (const SCEVConstant *C0 = dyn_cast<SCEVConstant>(SM->getOperand(0)))
15673 return {C0, SM->getSCEVType()};
15674 return {nullptr, scCouldNotCompute};
15675 };
15676 auto MergeMinMaxConst = [](MinMaxPattern P1,
15677 MinMaxPattern P2) -> MinMaxPattern {
15678 auto [C1, T1] = P1;
15679 auto [C2, T2] = P2;
15680 if (!C1 || !C2 || T1 != T2)
15681 return {nullptr, scCouldNotCompute};
15682 switch (T1) {
15683 case scUMaxExpr:
15684 return {C1->getAPInt().ult(C2->getAPInt()) ? C1 : C2, T1};
15685 case scSMaxExpr:
15686 return {C1->getAPInt().slt(C2->getAPInt()) ? C1 : C2, T1};
15687 case scUMinExpr:
15688 return {C1->getAPInt().ugt(C2->getAPInt()) ? C1 : C2, T1};
15689 case scSMinExpr:
15690 return {C1->getAPInt().sgt(C2->getAPInt()) ? C1 : C2, T1};
15691 default:
15692 llvm_unreachable("Trying to merge non-MinMaxExpr SCEVs.");
15693 }
15694 };
15695 auto P = GetMinMaxConst(0);
15696 for (unsigned int In = 1; In < Phi.getNumIncomingValues(); In++) {
15697 if (!P.first)
15698 break;
15699 P = MergeMinMaxConst(P, GetMinMaxConst(In));
15700 }
15701 if (P.first) {
15702 const SCEV *LHS = SE.getSCEV(const_cast<PHINode *>(&Phi));
15703 SmallVector<SCEVUse, 2> Ops({P.first, LHS});
15704 const SCEV *RHS = SE.getMinMaxExpr(P.second, Ops);
15705 Guards.RewriteMap.insert({LHS, RHS});
15706 }
15707}
15708
15709// Return a new SCEV that modifies \p Expr to the closest number divides by
15710// \p Divisor and less or equal than Expr. For now, only handle constant
15711// Expr.
15713 const APInt &DivisorVal,
15714 ScalarEvolution &SE) {
15715 const APInt *ExprVal;
15716 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15717 DivisorVal.isNonPositive())
15718 return Expr;
15719 APInt Rem = ExprVal->urem(DivisorVal);
15720 // return the SCEV: Expr - Expr % Divisor
15721 return SE.getConstant(*ExprVal - Rem);
15722}
15723
15724// Return a new SCEV that modifies \p Expr to the closest number divides by
15725// \p Divisor and greater or equal than Expr. For now, only handle constant
15726// Expr.
15727static const SCEV *getNextSCEVDivisibleByDivisor(const SCEV *Expr,
15728 const APInt &DivisorVal,
15729 ScalarEvolution &SE) {
15730 const APInt *ExprVal;
15731 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15732 DivisorVal.isNonPositive())
15733 return Expr;
15734 APInt Rem = ExprVal->urem(DivisorVal);
15735 if (Rem.isZero())
15736 return Expr;
15737 // return the SCEV: Expr + Divisor - Expr % Divisor
15738 return SE.getConstant(*ExprVal + DivisorVal - Rem);
15739}
15740
15742 ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS,
15745 // If we have LHS == 0, check if LHS is computing a property of some unknown
15746 // SCEV %v which we can rewrite %v to express explicitly.
15748 return false;
15749 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
15750 // explicitly express that.
15751 const SCEVUnknown *URemLHS = nullptr;
15752 const SCEV *URemRHS = nullptr;
15753 if (!match(LHS, m_scev_URem(m_SCEVUnknown(URemLHS), m_SCEV(URemRHS), SE)))
15754 return false;
15755
15756 const SCEV *Multiple =
15757 SE.getMulExpr(SE.getUDivExpr(URemLHS, URemRHS), URemRHS);
15758 DivInfo[URemLHS] = Multiple;
15759 if (auto *C = dyn_cast<SCEVConstant>(URemRHS))
15760 Multiples[URemLHS] = C->getAPInt();
15761 return true;
15762}
15763
15764// Check if the condition is a divisibility guard (A % B == 0).
15765static bool isDivisibilityGuard(const SCEV *LHS, const SCEV *RHS,
15766 ScalarEvolution &SE) {
15767 const SCEV *X, *Y;
15768 return match(LHS, m_scev_URem(m_SCEV(X), m_SCEV(Y), SE)) && RHS->isZero();
15769}
15770
15771// Apply divisibility by \p Divisor on MinMaxExpr with constant values,
15772// recursively. This is done by aligning up/down the constant value to the
15773// Divisor.
15774static const SCEV *applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr,
15775 APInt Divisor,
15776 ScalarEvolution &SE) {
15777 // Return true if \p Expr is a MinMax SCEV expression with a non-negative
15778 // constant operand. If so, return in \p SCTy the SCEV type and in \p RHS
15779 // the non-constant operand and in \p LHS the constant operand.
15780 auto IsMinMaxSCEVWithNonNegativeConstant =
15781 [&](const SCEV *Expr, SCEVTypes &SCTy, const SCEV *&LHS,
15782 const SCEV *&RHS) {
15783 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr)) {
15784 if (MinMax->getNumOperands() != 2)
15785 return false;
15786 if (auto *C = dyn_cast<SCEVConstant>(MinMax->getOperand(0))) {
15787 if (C->getAPInt().isNegative())
15788 return false;
15789 SCTy = MinMax->getSCEVType();
15790 LHS = MinMax->getOperand(0);
15791 RHS = MinMax->getOperand(1);
15792 return true;
15793 }
15794 }
15795 return false;
15796 };
15797
15798 const SCEV *MinMaxLHS = nullptr, *MinMaxRHS = nullptr;
15799 SCEVTypes SCTy;
15800 if (!IsMinMaxSCEVWithNonNegativeConstant(MinMaxExpr, SCTy, MinMaxLHS,
15801 MinMaxRHS))
15802 return MinMaxExpr;
15803 auto IsMin = isa<SCEVSMinExpr>(MinMaxExpr) || isa<SCEVUMinExpr>(MinMaxExpr);
15804 assert(SE.isKnownNonNegative(MinMaxLHS) && "Expected non-negative operand!");
15805 auto *DivisibleExpr =
15806 IsMin ? getPreviousSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE)
15807 : getNextSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE);
15809 applyDivisibilityOnMinMaxExpr(MinMaxRHS, Divisor, SE), DivisibleExpr};
15810 return SE.getMinMaxExpr(SCTy, Ops);
15811}
15812
15813void ScalarEvolution::LoopGuards::collectFromBlock(
15814 ScalarEvolution &SE, ScalarEvolution::LoopGuards &Guards,
15815 const BasicBlock *Block, const BasicBlock *Pred,
15816 SmallPtrSetImpl<const BasicBlock *> &VisitedBlocks, unsigned Depth) {
15817
15819
15820 SmallVector<SCEVUse> ExprsToRewrite;
15821 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
15822 const SCEV *RHS,
15823 DenseMap<const SCEV *, const SCEV *> &RewriteMap,
15824 const LoopGuards &DivGuards) {
15825 // WARNING: It is generally unsound to apply any wrap flags to the proposed
15826 // replacement SCEV which isn't directly implied by the structure of that
15827 // SCEV. In particular, using contextual facts to imply flags is *NOT*
15828 // legal. See the scoping rules for flags in the header to understand why.
15829
15830 // Puts rewrite rule \p From -> \p To into the rewrite map. Also if \p From
15831 // and \p FromRewritten are the same (i.e. there has been no rewrite
15832 // registered for \p From), then puts this value in the list of rewritten
15833 // expressions.
15834 auto AddRewrite = [&](const SCEV *From, const SCEV *FromRewritten,
15835 const SCEV *To) {
15836 if (From == FromRewritten)
15837 ExprsToRewrite.push_back(From);
15838 RewriteMap[From] = To;
15839 };
15840
15841 // Checks whether \p S has already been rewritten. In that case returns the
15842 // existing rewrite because we want to chain further rewrites onto the
15843 // already rewritten value. Otherwise returns \p S.
15844 auto GetMaybeRewritten = [&](const SCEV *S) {
15845 return RewriteMap.lookup_or(S, S);
15846 };
15847
15848 // Check for a condition of the form (-C1 + X < C2). InstCombine will
15849 // create this form when combining two checks of the form (X u< C2 + C1) and
15850 // (X >=u C1).
15851 auto MatchRangeCheckIdiom = [&](ICmpInst::Predicate Pred,
15852 const SCEV *MatchLHS,
15853 const SCEV *MatchRHS) {
15854 const SCEVConstant *C1;
15855 const SCEVUnknown *LHSUnknown;
15856 auto *C2 = dyn_cast<SCEVConstant>(MatchRHS);
15857 if (!match(MatchLHS,
15858 m_scev_Add(m_SCEVConstant(C1), m_SCEVUnknown(LHSUnknown))) ||
15859 !C2)
15860 return false;
15861
15862 auto ExactRegion =
15863 ConstantRange::makeExactICmpRegion(Pred, C2->getAPInt())
15864 .sub(C1->getAPInt());
15865
15866 // Tighten the raw range with what we already know about LHSUnknown
15867 // from prior guards recorded in RewriteMap, or from SCEV's own range
15868 // analysis.
15869 const SCEV *RewrittenLHS = GetMaybeRewritten(LHSUnknown);
15870 ExactRegion = ExactRegion.intersectWith(SE.getUnsignedRange(RewrittenLHS),
15872
15873 // Bail if the guard is inconsistent with prior facts, or if the range
15874 // is still not a monotonic non-wrapping interval after tightening.
15875 if (ExactRegion.isEmptySet() || ExactRegion.isWrappedSet() ||
15876 ExactRegion.isFullSet())
15877 return false;
15878
15879 const SCEV *RegionMin = SE.getConstant(ExactRegion.getUnsignedMin());
15880 const SCEV *RegionMax = SE.getConstant(ExactRegion.getUnsignedMax());
15881 const SCEV *ClampedLHS =
15882 SE.getUMaxExpr(RegionMin, SE.getUMinExpr(RewrittenLHS, RegionMax));
15883 AddRewrite(LHSUnknown, RewrittenLHS, ClampedLHS);
15884 return true;
15885 };
15886 if (MatchRangeCheckIdiom(Predicate, LHS, RHS))
15887 return;
15888
15889 // Do not apply information for constants or if RHS contains an AddRec.
15891 return;
15892
15893 // If RHS is SCEVUnknown, make sure the information is applied to it.
15895 std::swap(LHS, RHS);
15897 }
15898
15899 const SCEV *RewrittenLHS = GetMaybeRewritten(LHS);
15900 // Apply divisibility information when computing the constant multiple.
15901 const APInt &DividesBy =
15902 SE.getConstantMultiple(DivGuards.rewrite(RewrittenLHS));
15903
15904 // Collect rewrites for LHS and its transitive operands based on the
15905 // condition.
15906 // For min/max expressions, also apply the guard to its operands:
15907 // 'min(a, b) >= c' -> '(a >= c) and (b >= c)',
15908 // 'min(a, b) > c' -> '(a > c) and (b > c)',
15909 // 'max(a, b) <= c' -> '(a <= c) and (b <= c)',
15910 // 'max(a, b) < c' -> '(a < c) and (b < c)'.
15911
15912 // We cannot express strict predicates in SCEV, so instead we replace them
15913 // with non-strict ones against plus or minus one of RHS depending on the
15914 // predicate.
15915 const SCEV *One = SE.getOne(RHS->getType());
15916 switch (Predicate) {
15917 case CmpInst::ICMP_ULT:
15918 if (RHS->getType()->isPointerTy())
15919 return;
15920 RHS = SE.getUMaxExpr(RHS, One);
15921 [[fallthrough]];
15922 case CmpInst::ICMP_SLT: {
15923 RHS = SE.getMinusSCEV(RHS, One);
15924 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
15925 break;
15926 }
15927 case CmpInst::ICMP_UGT:
15928 case CmpInst::ICMP_SGT:
15929 RHS = SE.getAddExpr(RHS, One);
15930 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
15931 break;
15932 case CmpInst::ICMP_ULE:
15933 case CmpInst::ICMP_SLE:
15934 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
15935 break;
15936 case CmpInst::ICMP_UGE:
15937 case CmpInst::ICMP_SGE:
15938 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
15939 break;
15940 default:
15941 break;
15942 }
15943
15944 SmallVector<SCEVUse, 16> Worklist(1, LHS);
15945 SmallPtrSet<const SCEV *, 16> Visited;
15946
15947 auto EnqueueOperands = [&Worklist](const SCEVNAryExpr *S) {
15948 append_range(Worklist, S->operands());
15949 };
15950
15951 while (!Worklist.empty()) {
15952 const SCEV *From = Worklist.pop_back_val();
15953 if (isa<SCEVConstant>(From))
15954 continue;
15955 if (!Visited.insert(From).second)
15956 continue;
15957 const SCEV *FromRewritten = GetMaybeRewritten(From);
15958 const SCEV *To = nullptr;
15959
15960 switch (Predicate) {
15961 case CmpInst::ICMP_ULT:
15962 case CmpInst::ICMP_ULE:
15963 To = SE.getUMinExpr(FromRewritten, RHS);
15964 if (auto *UMax = dyn_cast<SCEVUMaxExpr>(FromRewritten))
15965 EnqueueOperands(UMax);
15966 break;
15967 case CmpInst::ICMP_SLT:
15968 case CmpInst::ICMP_SLE:
15969 To = SE.getSMinExpr(FromRewritten, RHS);
15970 if (auto *SMax = dyn_cast<SCEVSMaxExpr>(FromRewritten))
15971 EnqueueOperands(SMax);
15972 break;
15973 case CmpInst::ICMP_UGT:
15974 case CmpInst::ICMP_UGE:
15975 To = SE.getUMaxExpr(FromRewritten, RHS);
15976 if (auto *UMin = dyn_cast<SCEVUMinExpr>(FromRewritten))
15977 EnqueueOperands(UMin);
15978 break;
15979 case CmpInst::ICMP_SGT:
15980 case CmpInst::ICMP_SGE:
15981 To = SE.getSMaxExpr(FromRewritten, RHS);
15982 if (auto *SMin = dyn_cast<SCEVSMinExpr>(FromRewritten))
15983 EnqueueOperands(SMin);
15984 break;
15985 case CmpInst::ICMP_EQ:
15987 To = RHS;
15988 break;
15989 case CmpInst::ICMP_NE:
15990 if (match(RHS, m_scev_Zero())) {
15991 const SCEV *OneAlignedUp =
15992 getNextSCEVDivisibleByDivisor(One, DividesBy, SE);
15993 To = SE.getUMaxExpr(FromRewritten, OneAlignedUp);
15994 } else {
15995 // LHS != RHS can be rewritten as (LHS - RHS) = UMax(1, LHS - RHS),
15996 // but creating the subtraction eagerly is expensive. Track the
15997 // inequalities in a separate map, and materialize the rewrite lazily
15998 // when encountering a suitable subtraction while re-writing.
15999 if (LHS->getType()->isPointerTy()) {
16000 LHS = SE.getPtrToAddrExpr(LHS);
16001 RHS = SE.getPtrToAddrExpr(RHS);
16003 break;
16004 }
16005 const SCEVConstant *C;
16006 const SCEV *A, *B;
16009 RHS = A;
16010 LHS = B;
16011 }
16012 if (LHS > RHS)
16013 std::swap(LHS, RHS);
16014 Guards.NotEqual.insert({LHS, RHS});
16015 continue;
16016 }
16017 break;
16018 default:
16019 break;
16020 }
16021
16022 if (To)
16023 AddRewrite(From, FromRewritten, To);
16024 }
16025 };
16026
16028 // First, collect information from assumptions dominating the loop.
16029 for (auto &AssumeVH : SE.AC.assumptions()) {
16030 if (!AssumeVH)
16031 continue;
16032 auto *AssumeI = cast<CallInst>(AssumeVH);
16033 if (!SE.DT.dominates(AssumeI, Block))
16034 continue;
16035 Terms.emplace_back(AssumeI->getOperand(0), true);
16036 }
16037
16038 // Second, collect information from llvm.experimental.guards dominating the loop.
16039 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
16040 SE.F.getParent(), Intrinsic::experimental_guard);
16041 if (GuardDecl)
16042 for (const auto *GU : GuardDecl->users())
16043 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
16044 if (Guard->getFunction() == Block->getParent() &&
16045 SE.DT.dominates(Guard, Block))
16046 Terms.emplace_back(Guard->getArgOperand(0), true);
16047
16048 // Third, collect conditions from dominating branches. Starting at the loop
16049 // predecessor, climb up the predecessor chain, as long as there are
16050 // predecessors that can be found that have unique successors leading to the
16051 // original header. If there is no such predecessor, continue at the
16052 // immediate dominator.
16053 // TODO: share this logic with isLoopEntryGuardedByCond.
16054 unsigned NumCollectedConditions = 0;
16055 unsigned NumDomTreeSteps = 0;
16057 std::pair<const BasicBlock *, const BasicBlock *> Pair(Pred, Block);
16058 for (;; Pair = SE.getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
16059 if (!Pair.first) {
16060 // At the first block without a unique predecessor, try to build
16061 // conditions for its phis by merging those of their incoming blocks.
16062 if (!NumDomTreeSteps &&
16063 Depth < SE.Opts.scalar_evolution_max_loop_guard_collection_depth) {
16064 SmallDenseMap<const BasicBlock *, LoopGuards> IncomingGuards;
16065 for (auto &Phi : Pair.second->phis())
16066 collectFromPHI(SE, Guards, Phi, VisitedBlocks, IncomingGuards, Depth);
16067 }
16068 const DomTreeNode *IDom = SE.DT.getNode(Pair.second)->getIDom();
16069 if (!IDom ||
16070 ++NumDomTreeSteps > SE.Opts.scalar_evolution_max_guard_dom_tree_steps)
16071 break;
16072 Pair.first = IDom->getBlock();
16073 continue;
16074 }
16075 VisitedBlocks.insert(Pair.second);
16076 const CondBrInst *LoopEntryPredicate =
16077 dyn_cast<CondBrInst>(Pair.first->getTerminator());
16078 if (!LoopEntryPredicate)
16079 continue;
16080
16081 Terms.emplace_back(LoopEntryPredicate->getCondition(),
16082 LoopEntryPredicate->getSuccessor(0) == Pair.second);
16083 NumCollectedConditions++;
16084
16085 // If we are recursively collecting guards stop after 2
16086 // conditions to limit compile-time impact for now.
16087 if (Depth > 0 && NumCollectedConditions == 2)
16088 break;
16089 }
16090
16091 // Now apply the information from the collected conditions to
16092 // Guards.RewriteMap. Conditions are processed in reverse order, so the
16093 // earliest conditions is processed first, except guards with divisibility
16094 // information, which are moved to the back. This ensures the SCEVs with the
16095 // shortest dependency chains are constructed first.
16097 GuardsToProcess;
16098 for (auto [Term, EnterIfTrue] : reverse(Terms)) {
16099 SmallVector<Value *, 8> Worklist;
16100 SmallPtrSet<Value *, 8> Visited;
16101 Worklist.push_back(Term);
16102 while (!Worklist.empty()) {
16103 Value *Cond = Worklist.pop_back_val();
16104 if (!Visited.insert(Cond).second)
16105 continue;
16106
16107 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
16108 auto Predicate =
16109 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
16110 const auto *LHS = SE.getSCEV(Cmp->getOperand(0));
16111 const auto *RHS = SE.getSCEV(Cmp->getOperand(1));
16112 // If LHS is a constant, apply information to the other expression.
16113 // TODO: If LHS is not a constant, check if using compareSCEVComplexity
16114 // can improve results.
16115 if (isa<SCEVConstant>(LHS)) {
16116 std::swap(LHS, RHS);
16118 }
16119 GuardsToProcess.emplace_back(Predicate, LHS, RHS);
16120 continue;
16121 }
16122
16123 Value *L, *R;
16124 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
16125 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
16126 Worklist.push_back(L);
16127 Worklist.push_back(R);
16128 }
16129 }
16130 }
16131
16132 // Process divisibility guards in reverse order to populate DivGuards early.
16133 DenseMap<const SCEV *, APInt> Multiples;
16134 LoopGuards DivGuards(SE);
16135 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess) {
16136 if (!isDivisibilityGuard(LHS, RHS, SE))
16137 continue;
16138 collectDivisibilityInformation(Predicate, LHS, RHS, DivGuards.RewriteMap,
16139 Multiples, SE);
16140 }
16141
16142 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess)
16143 CollectCondition(Predicate, LHS, RHS, Guards.RewriteMap, DivGuards);
16144
16145 // Apply divisibility information last. This ensures it is applied to the
16146 // outermost expression after other rewrites for the given value.
16147 for (const auto &[K, Divisor] : Multiples) {
16148 const SCEV *DivisorSCEV = SE.getConstant(Divisor);
16149 Guards.RewriteMap[K] =
16151 Guards.rewrite(K), Divisor, SE),
16152 DivisorSCEV),
16153 DivisorSCEV);
16154 ExprsToRewrite.push_back(K);
16155 }
16156
16157 // Let the rewriter preserve NUW/NSW flags if the unsigned/signed ranges of
16158 // the replacement expressions are contained in the ranges of the replaced
16159 // expressions.
16160 Guards.PreserveNUW = true;
16161 Guards.PreserveNSW = true;
16162 for (const SCEV *Expr : ExprsToRewrite) {
16163 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16164 Guards.PreserveNUW &=
16165 SE.getUnsignedRange(Expr).contains(SE.getUnsignedRange(RewriteTo));
16166 Guards.PreserveNSW &=
16167 SE.getSignedRange(Expr).contains(SE.getSignedRange(RewriteTo));
16168 }
16169
16170 // Now that all rewrite information is collect, rewrite the collected
16171 // expressions with the information in the map. This applies information to
16172 // sub-expressions.
16173 if (ExprsToRewrite.size() > 1) {
16174 for (const SCEV *Expr : ExprsToRewrite) {
16175 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16176 Guards.RewriteMap.erase(Expr);
16177 Guards.RewriteMap.insert({Expr, Guards.rewrite(RewriteTo)});
16178 }
16179 }
16180}
16181
16183 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
16184 /// in the map. It skips AddRecExpr because we cannot guarantee that the
16185 /// replacement is loop invariant in the loop of the AddRec.
16186 class SCEVLoopGuardRewriter
16187 : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
16190
16191 SCEVFlags FlagMask = SCEV::FlagNone;
16192
16193 public:
16194 SCEVLoopGuardRewriter(ScalarEvolution &SE,
16195 const ScalarEvolution::LoopGuards &Guards)
16196 : SCEVRewriteVisitor(SE), Map(Guards.RewriteMap),
16197 NotEqual(Guards.NotEqual) {
16198 if (Guards.PreserveNUW)
16199 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNUW);
16200 if (Guards.PreserveNSW)
16201 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNSW);
16202 }
16203
16204 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
16205
16206 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
16207 return Map.lookup_or(Expr, Expr);
16208 }
16209
16210 const SCEV *visitPtrToAddrExpr(const SCEVPtrToAddrExpr *Expr) {
16211 if (const SCEV *S = Map.lookup(Expr))
16212 return S;
16214 Expr);
16215 }
16216
16217 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
16218 if (const SCEV *S = Map.lookup(Expr))
16219 return S;
16220
16221 // If we didn't find the extact ZExt expr in the map, check if there's
16222 // an entry for a smaller ZExt we can use instead.
16223 Type *Ty = Expr->getType();
16224 const SCEV *Op = Expr->getOperand(0);
16225 unsigned Bitwidth = Ty->getScalarSizeInBits() / 2;
16226 while (Bitwidth % 8 == 0 && Bitwidth >= 8 &&
16227 Bitwidth > Op->getType()->getScalarSizeInBits()) {
16228 Type *NarrowTy = IntegerType::get(SE.getContext(), Bitwidth);
16229 auto *NarrowExt = SE.getZeroExtendExpr(Op, NarrowTy);
16230 if (const SCEV *S = Map.lookup(NarrowExt))
16231 return SE.getZeroExtendExpr(S, Ty);
16232 Bitwidth = Bitwidth / 2;
16233 }
16234
16236 Expr);
16237 }
16238
16239 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
16240 if (const SCEV *S = Map.lookup(Expr))
16241 return S;
16243 Expr);
16244 }
16245
16246 const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
16247 if (const SCEV *S = Map.lookup(Expr))
16248 return S;
16250 }
16251
16252 const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
16253 if (const SCEV *S = Map.lookup(Expr))
16254 return S;
16256 }
16257
16258 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
16259 if (const SCEV *S = Map.lookup(Expr))
16260 return S;
16261
16262 // Helper to check if S is a subtraction (A - B) where A != B, and if so,
16263 // return UMax(S, 1).
16264 auto RewriteSubtraction = [&](const SCEV *S) -> const SCEV * {
16265 SCEVUse LHS, RHS;
16266 if (MatchBinarySub(S, LHS, RHS)) {
16267 if (LHS > RHS)
16268 std::swap(LHS, RHS);
16269 if (NotEqual.contains({LHS, RHS})) {
16270 const SCEV *OneAlignedUp = getNextSCEVDivisibleByDivisor(
16271 SE.getOne(S->getType()), SE.getConstantMultiple(S), SE);
16272 return SE.getUMaxExpr(OneAlignedUp, S);
16273 }
16274 }
16275 return nullptr;
16276 };
16277
16278 // Check if Expr itself is a subtraction pattern with guard info.
16279 if (const SCEV *Rewritten = RewriteSubtraction(Expr))
16280 return Rewritten;
16281
16282 // Trip count expressions sometimes consist of adding 3 operands, i.e.
16283 // (Const + A + B). There may be guard info for A + B, and if so, apply
16284 // it.
16285 // TODO: Could more generally apply guards to Add sub-expressions.
16286 if (isa<SCEVConstant>(Expr->getOperand(0))) {
16287 if (Expr->getNumOperands() == 3) {
16288 const SCEV *Add =
16289 SE.getAddExpr(Expr->getOperand(1), Expr->getOperand(2));
16290 if (const SCEV *Rewritten = RewriteSubtraction(Add))
16291 return SE.getAddExpr(
16292 Expr->getOperand(0), Rewritten,
16293 ScalarEvolution::maskFlags(Expr->getNoWrapFlags(), FlagMask));
16294 if (const SCEV *S = Map.lookup(Add))
16295 return SE.getAddExpr(Expr->getOperand(0), S);
16296 }
16297
16298 // For expressions of the form (Const + A), check if we have guard info
16299 // for (Const + 1 + A), and rewrite to ((Const + 1 + A) - 1). This makes
16300 // sure we don't lose information when rewriting expressions based on
16301 // back-edge taken counts in some cases.
16302 if (Expr->getNumOperands() == 2) {
16303 const SCEV *S = nullptr;
16304 // Handle (-1 + 1 + A) without constructing SCEVs.
16305 if (match(Expr->getOperand(0), m_scev_AllOnes())) {
16306 S = Map.lookup(Expr->getOperand(1));
16307 } else {
16308 const SCEV *NewC =
16309 SE.getAddExpr(Expr->getOperand(0), SE.getOne(Expr->getType()));
16310 S = Map.lookup(SE.getAddExpr(NewC, Expr->getOperand(1)));
16311 }
16312 if (S)
16313 return SE.getAddExpr(S, SE.getMinusOne(Expr->getType()));
16314 }
16315 }
16317 bool Changed = false;
16318 for (SCEVUse Op : Expr->operands()) {
16319 Operands.push_back(
16321 Changed |= Op != Operands.back();
16322 }
16323 // We are only replacing operands with equivalent values, so transfer the
16324 // flags from the original expression.
16325 return !Changed ? Expr
16326 : SE.getAddExpr(Operands,
16328 Expr->getNoWrapFlags(), FlagMask));
16329 }
16330
16331 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
16333 bool Changed = false;
16334 for (SCEVUse Op : Expr->operands()) {
16335 Operands.push_back(
16337 Changed |= Op != Operands.back();
16338 }
16339 // We are only replacing operands with equivalent values, so transfer the
16340 // flags from the original expression.
16341 return !Changed ? Expr
16342 : SE.getMulExpr(Operands,
16344 Expr->getNoWrapFlags(), FlagMask));
16345 }
16346 };
16347
16348 if (RewriteMap.empty() && NotEqual.empty())
16349 return Expr;
16350
16351 SCEVLoopGuardRewriter Rewriter(SE, *this);
16352 return Rewriter.visit(Expr);
16353}
16354
16355const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
16356 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
16357 return applyLoopGuards(Expr, Guards);
16358}
16359
16361 LoopGuards &Guards) {
16362 // Loop guards never rewrite constants and AddRecs, so there is no need to
16363 // collect pending guards for them.
16365 return Expr;
16366 if (Guards.PendingLoop)
16367 Guards.collectPending();
16368 return Guards.rewrite(Expr);
16369}
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
#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:690
This file contains the declarations for the subclasses of Constant, which represent the different fla...
SmallPtrSet< const BasicBlock *, 8 > VisitedBlocks
This file defines the DenseMap class.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
static bool isSigned(unsigned Opcode)
This file defines a hash set that can be used to remove duplication of nodes in a graph.
#define op(i)
Hexagon Common GEP
Value * getPointer(Value *Ptr)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This defines the Use class.
iv Induction Variable Users
Definition IVUsers.cpp:48
static bool hasNoUnsignedWrap(BinaryOperator &I)
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:540
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define T
#define T1
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
ppc ctr loops verify
PowerPC Reduce CR logical Operation
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
R600 Clause Merge
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 * 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 const SCEV * applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr, APInt Divisor, ScalarEvolution &SE)
static cl::opt< bool, true > VerifySCEVOpt("verify-scev", cl::Hidden, cl::location(VerifySCEV), cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"))
static const SCEV * getSignedOverflowLimitForStep(const SCEV *Step, ICmpInst::Predicate *Pred, ScalarEvolution *SE)
static 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
Value * RHS
Value * LHS
BinaryOperator * Mul
static const uint32_t IV[8]
Definition blake3_impl.h:83
SCEVCastSinkingRewriter(ScalarEvolution &SE, Type *TargetTy, ConversionFn CreatePtrCast)
static const SCEV * rewrite(const SCEV *Scev, ScalarEvolution &SE, Type *TargetTy, ConversionFn CreatePtrCast)
const SCEV * visitUnknown(const SCEVUnknown *Expr)
const SCEV * visitAddExpr(const SCEVAddExpr *Expr)
const SCEV * visit(const SCEV *S)
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2009
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
APInt abs() const
Get the absolute value.
Definition APInt.h:1815
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition APInt.h:462
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:212
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1973
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
bool isNonPositive() const
Determine if this APInt Value is non-positive (<= 0).
Definition APInt.h:357
unsigned countTrailingZeros() const
Definition APInt.h:1667
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:352
unsigned logBase2() const
Definition APInt.h:1781
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:471
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1303
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
bool isSignBitSet() const
Determine if sign bit of this APInt is set.
Definition APInt.h:337
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1134
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition APInt.h:428
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
AnalysisUsage & addRequiredTransitive()
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
MutableArrayRef< WeakVH > assumptions()
Access the list of assumption handles currently tracked for this function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h: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...
LLVM_ABI CmpInst::Predicate getPreferredSignedPredicate() const
Attempts to return a signed CmpInst::Predicate from the CmpPredicate.
CmpInst::Predicate dropSameSign() const
Drops samesign information.
Conditional Branch instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static LLVM_ABI Constant * getNot(Constant *C)
static Constant * getPtrAdd(Constant *Ptr, Constant *Offset, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReduced=nullptr)
Create a getelementptr i8, ptr, offset constant expression.
Definition Constants.h: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:791
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.
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
static bool isLE(Predicate P)
Return true if the predicate is SLE or ULE.
This instruction inserts a single (scalar) element into a VectorType value.
This instruction inserts a struct field of array element value into an aggregate value.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI bool isIdenticalToWhenDefined(const Instruction *I, bool IntersectAttrs=false) const LLVM_READONLY
This is like isIdenticalTo, except that it ignores the SubclassOptionalData flags,...
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
A helper class to return the specified delimiter string after the first invocation of operator String...
An instruction for reading from memory.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
BlockT * getHeader() const
unsigned getLoopDepth() const
Return the nesting level of this loop.
BlockT * getLoopPredecessor() const
If the given loop's header has exactly one unique predecessor outside the loop, return it.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
unsigned getLoopDepth(const BlockT *BB) const
Return the loop nesting level of the specified block.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:619
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:68
Metadata node.
Definition Metadata.h:1081
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition Operator.h:113
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition Operator.h:107
iterator_range< const_block_iterator > blocks() const
op_range incoming_values()
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
PointerIntPair - This class implements a pair of a pointer and small integer.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
LLVM_ABI void addPredicate(const SCEVPredicate &Pred)
Adds a new predicate.
LLVM_ABI const SCEVPredicate & getPredicate() const
LLVM_ABI const SCEV * getPredicatedSCEV(const SCEV *Expr)
Returns the rewritten SCEV for Expr in the context of the current SCEV predicate.
LLVM_ABI bool areAddRecsEqualWithPreds(const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2, ArrayRef< const SCEVPredicate * > ExtraPreds={}) const
Check if AR1 and AR2 are equal, while taking into account Equal predicates in Preds and ExtraPreds.
LLVM_ABI const SCEVAddRecExpr * getAsAddRec(Value *V, SmallVectorImpl< const SCEVPredicate * > *WrapPredsAdded=nullptr)
Attempts to produce an AddRecExpr for V by adding additional SCEV predicates.
LLVM_ABI void print(raw_ostream &OS, unsigned Depth) const
Print the SCEV mappings done by the Predicated Scalar Evolution.
LLVM_ABI PredicatedScalarEvolution(ScalarEvolution &SE, Loop &L)
LLVM_ABI unsigned getSmallConstantMaxTripCount()
Returns the upper bound of the loop trip count as a normal unsigned value, or 0 if the trip count is ...
LLVM_ABI void addPredicates(ArrayRef< const SCEVPredicate * > Preds)
Adds all predicates in Preds.
LLVM_ABI const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSymbolicMaxBackedgeTakenCount()
Get the (predicated) symbolic max backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
constexpr bool isValid() const
Definition Register.h:112
This node represents an addition of some number of SCEVs.
This node represents a polynomial recurrence on the trip count of the specified loop.
LLVM_ABI SCEVUse getExitValue(ScalarEvolution &SE) const
Return the value of this recurrences when its loop exits, i.e.
LLVM_ABI const SCEV * evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const
Return the value of this chain of recurrences at the specified iteration number.
void setNoWrapFlags(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.
const SCEV * visitPtrToAddrExpr(const SCEVPtrToAddrExpr *Expr)
const SCEV * visitSignExtendExpr(const SCEVSignExtendExpr *Expr)
const SCEV * visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr)
const SCEV * visitSMinExpr(const SCEVSMinExpr *Expr)
const SCEV * visitUMinExpr(const SCEVUMinExpr *Expr)
This class represents a signed minimum selection.
This node is the base class for sequential/in-order min/max selections.
static SCEVTypes getEquivalentNonSequentialSCEVType(SCEVTypes Ty)
This class represents a sign extension of a small integer value to a larger integer value.
Visit all nodes in the expression tree using worklist traversal.
This class represents a truncation of an integer value to a smaller integer value.
This class represents a binary unsigned division operation.
This class represents an unsigned minimum selection.
This class represents a composition of other SCEV predicates, and is the class that most clients will...
void print(raw_ostream &OS, unsigned Depth) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Returns true if this predicate implies N.
SCEVUnionPredicate(ArrayRef< const SCEVPredicate * > Preds, ScalarEvolution &SE)
Union predicates don't get cached so create a dummy set ID for it.
bool isAlwaysTrue() const override
Implementation of the SCEVPredicate interface.
SCEVUnionPredicate getUnionWith(const SCEVPredicate *N, ScalarEvolution &SE) const
Returns a new SCEVUnionPredicate that is the union of this predicate and the given predicate N.
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
This class represents the value of vscale, as used when defining the length of a scalable vector or r...
This class represents an assumption made on an AddRec expression.
IncrementWrapFlags
Similar to 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.
LLVM_ABI const SCEV * rewrite(const SCEV *Expr) const
Try to apply the collected loop guards to Expr.
The main scalar evolution driver.
LLVM_ABI const SCEV * getUDivExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
const SCEV * getConstantMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
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:293
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:743
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
TypeSize getSizeInBits() const
Definition DataLayout.h:754
Class to represent struct types.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
Use & Op()
Definition User.h:171
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition Value.h:545
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
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:2850
LLVM_ABI APInt GreatestCommonDivisor(APInt A, APInt B, bool IsSigned=false)
Compute GCD of two APInt values.
Definition APInt.cpp:826
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2289
constexpr bool any(E Val)
@ Entry
Definition COFF.h:862
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h: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.
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< 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:2224
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
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:2216
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI bool isMustProgress(const Loop *L)
Return true if this loop can be assumed to make progress.
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
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:376
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:2208
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:249
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
iterator_range< df_iterator< T > > depth_first(const T &G)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2162
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:267
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
SCEVUseT< const SCEV * > SCEVUse
bool SCEVExprContains(const SCEV *Root, PredTy Pred)
Return true if any node in Root satisfies the predicate Pred.
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
#define NC
Definition regutils.h:42
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
An object of this class is returned by queries that could not be answered.
static LLVM_ABI bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
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)
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.