LLVM 24.0.0git
ScalarEvolution.cpp
Go to the documentation of this file.
1//===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the implementation of the scalar evolution analysis
10// engine, which is used primarily to analyze expressions involving induction
11// variables in loops.
12//
13// There are several aspects to this library. First is the representation of
14// scalar expressions, which are represented as subclasses of the SCEV class.
15// These classes are used to represent certain types of subexpressions that we
16// can handle. We only create one SCEV of a particular shape, so
17// pointer-comparisons for equality are legal.
18//
19// One important aspect of the SCEV objects is that they are never cyclic, even
20// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
21// the PHI node is one of the idioms that we can represent (e.g., a polynomial
22// recurrence) then we represent it directly as a recurrence node, otherwise we
23// represent it as a SCEVUnknown node.
24//
25// In addition to being able to represent expressions of various types, we also
26// have folders that are used to build the *canonical* representation for a
27// particular expression. These folders are capable of using a variety of
28// rewrite rules to simplify the expressions.
29//
30// Once the folders are defined, we can implement the more interesting
31// higher-level code, such as the code that recognizes PHI nodes of various
32// types, computes the execution count of a loop, etc.
33//
34// TODO: We should use these routines and value representations to implement
35// dependence analysis!
36//
37//===----------------------------------------------------------------------===//
38//
39// There are several good references for the techniques used in this analysis.
40//
41// Chains of recurrences -- a method to expedite the evaluation
42// of closed-form functions
43// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
44//
45// On computational properties of chains of recurrences
46// Eugene V. Zima
47//
48// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
49// Robert A. van Engelen
50//
51// Efficient Symbolic Analysis for Optimizing Compilers
52// Robert A. van Engelen
53//
54// Using the chains of recurrences algebra for data dependence testing and
55// induction variable substitution
56// MS Thesis, Johnie Birch
57//
58//===----------------------------------------------------------------------===//
59
61#include "AnalysisOptions.h"
62#include "llvm/ADT/APInt.h"
63#include "llvm/ADT/ArrayRef.h"
64#include "llvm/ADT/DenseMap.h"
66#include "llvm/ADT/FoldingSet.h"
67#include "llvm/ADT/STLExtras.h"
68#include "llvm/ADT/ScopeExit.h"
69#include "llvm/ADT/Sequence.h"
72#include "llvm/ADT/Statistic.h"
74#include "llvm/ADT/StringRef.h"
84#include "llvm/Config/llvm-config.h"
85#include "llvm/IR/Argument.h"
86#include "llvm/IR/BasicBlock.h"
87#include "llvm/IR/CFG.h"
88#include "llvm/IR/Constant.h"
90#include "llvm/IR/Constants.h"
91#include "llvm/IR/DataLayout.h"
93#include "llvm/IR/Dominators.h"
94#include "llvm/IR/Function.h"
95#include "llvm/IR/GlobalAlias.h"
96#include "llvm/IR/GlobalValue.h"
98#include "llvm/IR/InstrTypes.h"
99#include "llvm/IR/Instruction.h"
100#include "llvm/IR/Instructions.h"
102#include "llvm/IR/Intrinsics.h"
103#include "llvm/IR/LLVMContext.h"
104#include "llvm/IR/Operator.h"
105#include "llvm/IR/PatternMatch.h"
106#include "llvm/IR/Type.h"
107#include "llvm/IR/Use.h"
108#include "llvm/IR/User.h"
109#include "llvm/IR/Value.h"
110#include "llvm/IR/Verifier.h"
112#include "llvm/Pass.h"
113#include "llvm/Support/Casting.h"
116#include "llvm/Support/Debug.h"
122#include <algorithm>
123#include <cassert>
124#include <climits>
125#include <cstdint>
126#include <cstdlib>
127#include <map>
128#include <memory>
129#include <numeric>
130#include <optional>
131#include <tuple>
132#include <utility>
133#include <vector>
134
135using namespace llvm;
136using namespace PatternMatch;
137using namespace SCEVPatternMatch;
138
139#define DEBUG_TYPE "scalar-evolution"
140
141STATISTIC(NumExitCountsComputed,
142 "Number of loop exits with predictable exit counts");
143STATISTIC(NumExitCountsNotComputed,
144 "Number of loop exits without predictable exit counts");
145STATISTIC(NumBruteForceTripCountsComputed,
146 "Number of loops with trip counts computed by force");
147
148#ifdef EXPENSIVE_CHECKS
149bool llvm::VerifySCEV = true;
150#else
151bool llvm::VerifySCEV = false;
152#endif
153
155 "verify-scev", cl::Hidden, cl::location(VerifySCEV),
156 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
157
158//===----------------------------------------------------------------------===//
159// SCEV class definitions
160//===----------------------------------------------------------------------===//
161
163 // Leaf nodes are always their own canonical.
164 switch (getSCEVType()) {
165 case scConstant:
166 case scVScale:
167 case scUnknown:
168 CanonicalSCEV = this;
169 return;
170 default:
171 break;
172 }
173
174 // For all other expressions, check whether any immediate operand has a
175 // different canonical. Since operands are always created before their parent,
176 // their canonical pointers are already set — no recursion needed.
177 if (all_of(operands(), [](SCEVUse Op) { return Op.isCanonical(); })) {
178 CanonicalSCEV = this;
179 return;
180 }
181
183 map_range(operands(), [](SCEVUse Op) { return Op.getCanonical(); }));
184 // Rebuild the expression from the canonical operands, stripping use flags.
185 CanonicalSCEV = SE.getWithOperands(this, CanonOps);
186}
187
188//===----------------------------------------------------------------------===//
189// Implementation of the SCEV class.
190//
191
192#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
194 print(dbgs());
195 dbgs() << '\n';
196}
197#endif
198
199void SCEV::print(raw_ostream &OS) const {
200 switch (getSCEVType()) {
201 case scConstant:
202 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
203 return;
204 case scVScale:
205 OS << "vscale";
206 return;
207 case scPtrToAddr: {
208 const SCEVCastExpr *PtrCast = cast<SCEVCastExpr>(this);
209 SCEVUse Op = PtrCast->getOperand();
210 OS << "(ptrtoaddr " << *Op->getType() << " " << Op << " to "
211 << *PtrCast->getType() << ")";
212 return;
213 }
214 case scTruncate: {
216 SCEVUse Op = Trunc->getOperand();
217 OS << "(trunc " << *Op->getType() << " " << Op << " to "
218 << *Trunc->getType() << ")";
219 return;
220 }
221 case scZeroExtend: {
223 SCEVUse Op = ZExt->getOperand();
224 OS << "(zext " << *Op->getType() << " " << Op << " to " << *ZExt->getType()
225 << ")";
226 return;
227 }
228 case scSignExtend: {
230 SCEVUse Op = SExt->getOperand();
231 OS << "(sext " << *Op->getType() << " " << Op << " to " << *SExt->getType()
232 << ")";
233 return;
234 }
235 case scAddRecExpr: {
236 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
237 OS << "{" << AR->getOperand(0);
238 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
239 OS << ",+," << AR->getOperand(i);
240 OS << "}<";
241 if (AR->hasNoUnsignedWrap())
242 OS << "nuw><";
243 if (AR->hasNoSignedWrap())
244 OS << "nsw><";
245 if (AR->hasNoSelfWrap() && !AR->hasNoUnsignedWrap() &&
246 !AR->hasNoSignedWrap())
247 OS << "nw><";
248 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
249 OS << ">";
250 return;
251 }
252 case scAddExpr:
253 case scMulExpr:
254 case scUMaxExpr:
255 case scSMaxExpr:
256 case scUMinExpr:
257 case scSMinExpr:
259 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
260 const char *OpStr = nullptr;
261 switch (NAry->getSCEVType()) {
262 case scAddExpr: OpStr = " + "; break;
263 case scMulExpr: OpStr = " * "; break;
264 case scUMaxExpr: OpStr = " umax "; break;
265 case scSMaxExpr: OpStr = " smax "; break;
266 case scUMinExpr:
267 OpStr = " umin ";
268 break;
269 case scSMinExpr:
270 OpStr = " smin ";
271 break;
273 OpStr = " umin_seq ";
274 break;
275 default:
276 llvm_unreachable("There are no other nary expression types.");
277 }
278 OS << "(" << llvm::interleaved(NAry->operands(), OpStr) << ")";
279 switch (NAry->getSCEVType()) {
280 case scAddExpr:
281 case scMulExpr:
282 if (NAry->hasNoUnsignedWrap())
283 OS << "<nuw>";
284 if (NAry->hasNoSignedWrap())
285 OS << "<nsw>";
286 break;
287 default:
288 // Nothing to print for other nary expressions.
289 break;
290 }
291 return;
292 }
293 case scUDivExpr: {
294 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
295 OS << "(" << UDiv->getLHS() << " /u " << UDiv->getRHS() << ")";
296 return;
297 }
298 case scUnknown:
299 cast<SCEVUnknown>(this)->getValue()->printAsOperand(OS, false);
300 return;
302 OS << "***COULDNOTCOMPUTE***";
303 return;
304 }
305 llvm_unreachable("Unknown SCEV kind!");
306}
307
309 switch (getSCEVType()) {
310 case scConstant:
311 case scVScale:
312 case scUnknown:
313 return {};
314 case scPtrToAddr:
315 case scTruncate:
316 case scZeroExtend:
317 case scSignExtend:
318 return cast<SCEVCastExpr>(this)->operands();
319 case scAddRecExpr:
320 case scAddExpr:
321 case scMulExpr:
322 case scUMaxExpr:
323 case scSMaxExpr:
324 case scUMinExpr:
325 case scSMinExpr:
327 return cast<SCEVNAryExpr>(this)->operands();
328 case scUDivExpr:
329 return cast<SCEVUDivExpr>(this)->operands();
331 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
332 }
333 llvm_unreachable("Unknown SCEV kind!");
334}
335
336bool SCEV::isZero() const { return match(this, m_scev_Zero()); }
337
338bool SCEV::isOne() const { return match(this, m_scev_One()); }
339
340bool SCEV::isAllOnesValue() const { return match(this, m_scev_AllOnes()); }
341
344 if (!Mul) return false;
345
346 // If there is a constant factor, it will be first.
347 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
348 if (!SC) return false;
349
350 // Return true if the value is negative, this matches things like (-42 * V).
351 return SC->getAPInt().isNegative();
352}
353
356
358 return S->getSCEVType() == scCouldNotCompute;
359}
360
362 auto &Entry = ConstantSCEVs[V];
363 if (Entry)
364 return Entry;
365
368 ID.AddPointer(V);
370 if (SCEVConstant *S =
371 static_cast<SCEVConstant *>(UniqueSCEVs.lookup(ID, Token)))
372 return Entry = S;
373 SCEVConstant *S =
374 new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
375 UniqueSCEVs.insert(S, Token);
376 S->computeAndSetCanonical(*this);
377 return Entry = S;
378}
379
381 return getConstant(ConstantInt::get(getContext(), Val));
382}
383
384const SCEV *
387 // TODO: Avoid implicit trunc?
388 // See https://github.com/llvm/llvm-project/issues/112510.
389 return getConstant(
390 ConstantInt::get(ITy, V, isSigned, /*ImplicitTrunc=*/true));
391}
392
396 ID.AddPointer(Ty);
398 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
399 return S;
400 SCEV *S = new (SCEVAllocator) SCEVVScale(ID.Intern(SCEVAllocator), Ty);
401 UniqueSCEVs.insert(S, Token);
402 S->computeAndSetCanonical(*this);
403 return S;
404}
405
407 SCEVFlags Flags) {
408 const SCEV *Res = getConstant(Ty, EC.getKnownMinValue());
409 if (EC.isScalable())
410 Res = getMulExpr(Res, getVScale(Ty), Flags);
411 return Res;
412}
413
415 SCEVUse op, Type *ty)
416 : SCEV(ID, SCEVTy, computeExpressionSize(op), ty), Op(op) {}
417
418SCEVPtrToAddrExpr::SCEVPtrToAddrExpr(const FoldingSetNodeIDRef ID,
419 const SCEV *Op, Type *ITy)
420 : SCEVCastExpr(ID, scPtrToAddr, Op, ITy) {
421 assert(getOperand()->getType()->isPointerTy() && getType()->isIntegerTy() &&
422 "Must be a non-bit-width-changing pointer-to-integer cast!");
423}
424
429
430SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
431 Type *ty)
433 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
434 "Cannot truncate non-integer value!");
435}
436
437SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
438 Type *ty)
440 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
441 "Cannot zero extend non-integer value!");
442}
443
444SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
445 Type *ty)
447 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
448 "Cannot sign extend non-integer value!");
449}
450
452 // Clear this SCEVUnknown from various maps.
453 SE->forgetMemoizedResults({this});
454
455 // Remove this SCEVUnknown from the uniquing map.
456 SE->UniqueSCEVs.erase(this);
457
458 // Release the value.
459 setValPtr(nullptr);
460}
461
462void SCEVUnknown::allUsesReplacedWith(Value *New) {
463 // Clear this SCEVUnknown from various maps.
464 SE->forgetMemoizedResults({this});
465
466 // Remove this SCEVUnknown from the uniquing map.
467 SE->UniqueSCEVs.erase(this);
468
469 // Replace the value pointer in case someone is still using this SCEVUnknown.
470 setValPtr(New);
471}
472
473//===----------------------------------------------------------------------===//
474// SCEV Utilities
475//===----------------------------------------------------------------------===//
476
477/// Compare the two values \p LV and \p RV in terms of their "complexity" where
478/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
479/// operands in SCEV expressions.
480static int compareValueComplexity(const AnalysisOptions &Opts,
481 const LoopInfo *const LI, Value *LV,
482 Value *RV, unsigned Depth) {
483 if (Depth > Opts.scalar_evolution_max_value_compare_depth)
484 return 0;
485
486 // Order pointer values after integer values. This helps SCEVExpander form
487 // GEPs.
488 bool LIsPointer = LV->getType()->isPointerTy(),
489 RIsPointer = RV->getType()->isPointerTy();
490 if (LIsPointer != RIsPointer)
491 return (int)LIsPointer - (int)RIsPointer;
492
493 // Compare getValueID values.
494 unsigned LID = LV->getValueID(), RID = RV->getValueID();
495 if (LID != RID)
496 return (int)LID - (int)RID;
497
498 // Sort arguments by their position.
499 if (const auto *LA = dyn_cast<Argument>(LV)) {
500 const auto *RA = cast<Argument>(RV);
501 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
502 return (int)LArgNo - (int)RArgNo;
503 }
504
505 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
506 const auto *RGV = cast<GlobalValue>(RV);
507
508 if (auto L = LGV->getLinkage() - RGV->getLinkage())
509 return L;
510
511 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
512 auto LT = GV->getLinkage();
513 return !(GlobalValue::isPrivateLinkage(LT) ||
515 };
516
517 // Use the names to distinguish the two values, but only if the
518 // names are semantically important.
519 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
520 return LGV->getName().compare(RGV->getName());
521 }
522
523 // For instructions, compare their loop depth, and their operand count. This
524 // is pretty loose.
525 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
526 const auto *RInst = cast<Instruction>(RV);
527
528 // Compare loop depths.
529 const BasicBlock *LParent = LInst->getParent(),
530 *RParent = RInst->getParent();
531 if (LParent != RParent) {
532 unsigned LDepth = LI->getLoopDepth(LParent),
533 RDepth = LI->getLoopDepth(RParent);
534 if (LDepth != RDepth)
535 return (int)LDepth - (int)RDepth;
536 }
537
538 // Compare the number of operands.
539 unsigned LNumOps = LInst->getNumOperands(),
540 RNumOps = RInst->getNumOperands();
541 if (LNumOps != RNumOps)
542 return (int)LNumOps - (int)RNumOps;
543
544 for (unsigned Idx : seq(LNumOps)) {
545 int Result = compareValueComplexity(Opts, LI, LInst->getOperand(Idx),
546 RInst->getOperand(Idx), Depth + 1);
547 if (Result != 0)
548 return Result;
549 }
550 }
551
552 return 0;
553}
554
555// Return negative, zero, or positive, if LHS is less than, equal to, or greater
556// than RHS, respectively. A three-way result allows recursive comparisons to be
557// more efficient. The result is a total order.
558static int compareSCEVComplexity(const AnalysisOptions &Opts,
559 const LoopInfo *const LI, SCEVUse LHS,
561 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
562 if (LHS == RHS)
563 return 0;
564
565 if (LHS.getPointer() == RHS.getPointer())
566 return (int)LHS.getUseNoWrapFlags() - (int)RHS.getUseNoWrapFlags();
567
568 // Primarily, sort the SCEVs by their getSCEVType().
569 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
570 if (LType != RType)
571 return (int)LType - (int)RType;
572
573 // Aside from the getSCEVType() ordering, the particular ordering
574 // isn't very important except that it's beneficial to be consistent,
575 // so that (a + b) and (b + a) don't end up as different expressions.
576 switch (LType) {
577 case scUnknown: {
578 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
579 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
580
581 if (int X = compareValueComplexity(Opts, LI, LU->getValue(), RU->getValue(),
582 /*Depth=*/0))
583 return X;
584 return LU->getOrderID() < RU->getOrderID() ? -1 : 1;
585 }
586
587 case scConstant: {
590
591 // Compare constant values.
592 const APInt &LA = LC->getAPInt();
593 const APInt &RA = RC->getAPInt();
594 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
595 if (LBitWidth != RBitWidth)
596 return (int)LBitWidth - (int)RBitWidth;
597 return LA.ult(RA) ? -1 : 1;
598 }
599
600 case scVScale: {
601 const auto *LTy = cast<IntegerType>(cast<SCEVVScale>(LHS)->getType());
602 const auto *RTy = cast<IntegerType>(cast<SCEVVScale>(RHS)->getType());
603 return LTy->getBitWidth() - RTy->getBitWidth();
604 }
605
606 case scAddRecExpr: {
609
610 // There is always a dominance between two recs that are used by one SCEV,
611 // so we can safely sort recs by loop header dominance. We require such
612 // order in getAddExpr.
613 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
614 if (LLoop != RLoop) {
615 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
616 assert(LHead != RHead && "Two loops share the same header?");
617 if (DT.dominates(LHead, RHead))
618 return 1;
619 assert(DT.dominates(RHead, LHead) &&
620 "No dominance between recurrences used by one SCEV?");
621 return -1;
622 }
623
624 [[fallthrough]];
625 }
626
627 case scTruncate:
628 case scZeroExtend:
629 case scSignExtend:
630 case scPtrToAddr:
631 case scAddExpr:
632 case scMulExpr:
633 case scUDivExpr:
634 case scSMaxExpr:
635 case scUMaxExpr:
636 case scSMinExpr:
637 case scUMinExpr:
639 ArrayRef<SCEVUse> LOps = LHS->operands();
640 ArrayRef<SCEVUse> ROps = RHS->operands();
641
642 // Lexicographically compare n-ary-like expressions.
643 unsigned LNumOps = LOps.size(), RNumOps = ROps.size();
644 if (LNumOps != RNumOps)
645 return (int)LNumOps - (int)RNumOps;
646
647 for (unsigned i = 0; i != LNumOps; ++i) {
648 auto X = compareSCEVComplexity(Opts, LI, LOps[i], ROps[i], DT);
649 if (X != 0)
650 return X;
651 }
652
653 assert(isa<SCEVCastExpr>(LHS) && "distinct SCEVs compare equal");
654 unsigned LBitWidth = cast<IntegerType>(LHS->getType())->getBitWidth();
655 unsigned RBitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
656 assert(LBitWidth != RBitWidth && "distinct SCEVs compare equal");
657 return (int)LBitWidth - (int)RBitWidth;
658 }
659
661 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
662 }
663 llvm_unreachable("Unknown SCEV kind!");
664}
665
666/// Given a list of SCEV objects, order them by their complexity, and group
667/// objects of the same complexity together by value. When this routine is
668/// finished, we know that any duplicates in the vector are consecutive and that
669/// complexity is monotonically increasing.
670///
671/// Note that we go take special precautions to ensure that we get deterministic
672/// results from this routine. In other words, we don't want the results of
673/// this to depend on where the addresses of various SCEV objects happened to
674/// land in memory.
675static void groupByComplexity(const AnalysisOptions &Opts,
677 DominatorTree &DT) {
678 if (Ops.size() < 2) return; // Noop
679
680 // Whether LHS has provably less complexity than RHS.
681 auto IsLessComplex = [&](SCEVUse LHS, SCEVUse RHS) {
682 return compareSCEVComplexity(Opts, LI, LHS, RHS, DT) < 0;
683 };
684 if (Ops.size() == 2) {
685 // This is the common case, which also happens to be trivially simple.
686 // Special case it.
687 SCEVUse &LHS = Ops[0], &RHS = Ops[1];
688 if (IsLessComplex(RHS, LHS))
689 std::swap(LHS, RHS);
690 return;
691 }
692
693 llvm::sort(Ops, IsLessComplex);
694}
695
696/// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
697/// least -scalar-evolution-huge-expr-threshold nodes).
698static bool hasHugeExpression(const AnalysisOptions &Opts,
700 return any_of(Ops, [&](const SCEV *S) {
701 return S->getExpressionSize() >= Opts.scalar_evolution_huge_expr_threshold;
702 });
703}
704
705/// Performs a number of common optimizations on the passed \p Ops. If the
706/// whole expression reduces down to a single operand, it will be returned.
707///
708/// The following optimizations are performed:
709/// * Fold constants using the \p Fold function.
710/// * Remove identity constants satisfying \p IsIdentity.
711/// * If a constant satisfies \p IsAbsorber, return it.
712/// * Sort operands by complexity.
713template <typename FoldT, typename IsIdentityT, typename IsAbsorberT>
714static const SCEV *
715constantFoldAndGroupOps(const AnalysisOptions &Opts, ScalarEvolution &SE,
716 LoopInfo &LI, DominatorTree &DT,
717 SmallVectorImpl<SCEVUse> &Ops, FoldT Fold,
718 IsIdentityT IsIdentity, IsAbsorberT IsAbsorber) {
719 const SCEVConstant *Folded = nullptr;
720 for (unsigned Idx = 0; Idx < Ops.size();) {
721 const SCEV *Op = Ops[Idx];
722 if (const auto *C = dyn_cast<SCEVConstant>(Op)) {
723 if (!Folded)
724 Folded = C;
725 else
727 SE.getConstant(Fold(Folded->getAPInt(), C->getAPInt())));
728 Ops.erase(Ops.begin() + Idx);
729 continue;
730 }
731 ++Idx;
732 }
733
734 if (Ops.empty()) {
735 assert(Folded && "Must have folded value");
736 return Folded;
737 }
738
739 if (Folded && IsAbsorber(Folded->getAPInt()))
740 return Folded;
741
742 groupByComplexity(Opts, Ops, &LI, DT);
743 if (Folded && !IsIdentity(Folded->getAPInt()))
744 Ops.insert(Ops.begin(), Folded);
745
746 return Ops.size() == 1 ? Ops[0] : nullptr;
747}
748
749//===----------------------------------------------------------------------===//
750// Simple SCEV method implementations
751//===----------------------------------------------------------------------===//
752
753/// Compute BC(It, K). The result has width W. Assume, K > 0.
754static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
755 ScalarEvolution &SE,
756 Type *ResultTy) {
757 // Handle the simplest case efficiently.
758 if (K == 1)
759 return SE.getTruncateOrZeroExtend(It, ResultTy);
760
761 // We are using the following formula for BC(It, K):
762 //
763 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
764 //
765 // Suppose, W is the bitwidth of the return value. We must be prepared for
766 // overflow. Hence, we must assure that the result of our computation is
767 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
768 // safe in modular arithmetic.
769 //
770 // However, this code doesn't use exactly that formula; the formula it uses
771 // is something like the following, where T is the number of factors of 2 in
772 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
773 // exponentiation:
774 //
775 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
776 //
777 // This formula is trivially equivalent to the previous formula. However,
778 // this formula can be implemented much more efficiently. The trick is that
779 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
780 // arithmetic. To do exact division in modular arithmetic, all we have
781 // to do is multiply by the inverse. Therefore, this step can be done at
782 // width W.
783 //
784 // The next issue is how to safely do the division by 2^T. The way this
785 // is done is by doing the multiplication step at a width of at least W + T
786 // bits. This way, the bottom W+T bits of the product are accurate. Then,
787 // when we perform the division by 2^T (which is equivalent to a right shift
788 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
789 // truncated out after the division by 2^T.
790 //
791 // In comparison to just directly using the first formula, this technique
792 // is much more efficient; using the first formula requires W * K bits,
793 // but this formula less than W + K bits. Also, the first formula requires
794 // a division step, whereas this formula only requires multiplies and shifts.
795 //
796 // It doesn't matter whether the subtraction step is done in the calculation
797 // width or the input iteration count's width; if the subtraction overflows,
798 // the result must be zero anyway. We prefer here to do it in the width of
799 // the induction variable because it helps a lot for certain cases; CodeGen
800 // isn't smart enough to ignore the overflow, which leads to much less
801 // efficient code if the width of the subtraction is wider than the native
802 // register width.
803 //
804 // (It's possible to not widen at all by pulling out factors of 2 before
805 // the multiplication; for example, K=2 can be calculated as
806 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
807 // extra arithmetic, so it's not an obvious win, and it gets
808 // much more complicated for K > 3.)
809
810 // Protection from insane SCEVs; this bound is conservative,
811 // but it probably doesn't matter.
812 if (K > 1000)
813 return SE.getCouldNotCompute();
814
815 unsigned W = SE.getTypeSizeInBits(ResultTy);
816
817 // Calculate K! / 2^T and T; we divide out the factors of two before
818 // multiplying for calculating K! / 2^T to avoid overflow.
819 // Other overflow doesn't matter because we only care about the bottom
820 // W bits of the result.
821 APInt OddFactorial(W, 1);
822 unsigned T = 1;
823 for (unsigned i = 3; i <= K; ++i) {
824 unsigned TwoFactors = countr_zero(i);
825 T += TwoFactors;
826 OddFactorial *= (i >> TwoFactors);
827 }
828
829 // We need at least W + T bits for the multiplication step
830 unsigned CalculationBits = W + T;
831
832 // Calculate 2^T, at width T+W.
833 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
834
835 // Calculate the multiplicative inverse of K! / 2^T;
836 // this multiplication factor will perform the exact division by
837 // K! / 2^T.
838 APInt MultiplyFactor = OddFactorial.multiplicativeInverse();
839
840 // Calculate the product, at width T+W
841 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
842 CalculationBits);
843 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
844 for (unsigned i = 1; i != K; ++i) {
845 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
846 Dividend = SE.getMulExpr(Dividend,
847 SE.getTruncateOrZeroExtend(S, CalculationTy));
848 }
849
850 // Divide by 2^T
851 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
852
853 // Truncate the result, and divide by K! / 2^T.
854
855 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
856 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
857}
858
859/// Return the value of this chain of recurrences at the specified iteration
860/// number. We can evaluate this recurrence by multiplying each element in the
861/// chain by the binomial coefficient corresponding to it. In other words, we
862/// can evaluate {A,+,B,+,C,+,D} as:
863///
864/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
865///
866/// where BC(It, k) stands for binomial coefficient.
868 ScalarEvolution &SE) const {
869 return evaluateAtIteration(operands(), It, SE);
870}
871
873 const SCEV *It, ScalarEvolution &SE,
874 SCEVFlags UseFlags) {
875 assert(Operands.size() > 0);
876 assert((Operands.size() == 2 || UseFlags == SCEV::FlagNone) &&
877 "use-specific flags only supported for affine AddRecs");
878 SCEVUse Result = Operands[0].getPointer();
879 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
880 // The computation is correct in the face of overflow provided that the
881 // multiplication is performed _after_ the evaluation of the binomial
882 // coefficient.
883 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
884 if (isa<SCEVCouldNotCompute>(Coeff))
885 return Coeff;
886
887 SCEVUse Mul = SE.getMulExpr(Operands[i].getPointer(), Coeff,
888 {SCEV::FlagNone, UseFlags});
889 Result = SE.getAddExpr(Result, Mul, {SCEV::FlagNone, UseFlags});
890 }
891 return Result;
892}
893
895 const SCEV *BTC = SE.getBackedgeTakenCount(getLoop());
897 return BTC;
898 // The loop reaches iteration BTC, so the value this recurrence computes there
899 // is the value it had, and that did not wrap.
900 return evaluateAtIteration(operands(), BTC, SE,
903}
904
905//===----------------------------------------------------------------------===//
906// SCEV Expression folder implementations
907//===----------------------------------------------------------------------===//
908
909/// The SCEVCastSinkingRewriter takes a scalar evolution expression,
910/// which computes a pointer-typed value, and rewrites the whole expression
911/// tree so that *all* the computations are done on integers, and the only
912/// pointer-typed operands in the expression are SCEVUnknown.
913/// The CreatePtrCast callback is invoked to create the actual conversion
914/// (ptrtoint or ptrtoaddr) at the SCEVUnknown leaves.
916 : public SCEVRewriteVisitor<SCEVCastSinkingRewriter> {
918 using ConversionFn = function_ref<const SCEV *(const SCEVUnknown *)>;
919 Type *TargetTy;
920 ConversionFn CreatePtrCast;
921
922public:
924 ConversionFn CreatePtrCast)
925 : Base(SE), TargetTy(TargetTy), CreatePtrCast(std::move(CreatePtrCast)) {}
926
927 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
928 Type *TargetTy, ConversionFn CreatePtrCast) {
929 SCEVCastSinkingRewriter Rewriter(SE, TargetTy, std::move(CreatePtrCast));
930 return Rewriter.visit(Scev);
931 }
932
933 const SCEV *visit(const SCEV *S) {
934 Type *STy = S->getType();
935 // If the expression is not pointer-typed, just keep it as-is.
936 if (!STy->isPointerTy())
937 return S;
938 // Else, recursively sink the cast down into it.
939 return Base::visit(S);
940 }
941
942 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
943 // Preserve wrap flags on rewritten SCEVAddExpr, which the default
944 // implementation drops.
946 bool Changed = false;
947 for (SCEVUse Op : Expr->operands()) {
948 Operands.push_back(visit(Op.getPointer()));
949 Changed |= Op.getPointer() != Operands.back();
950 }
951 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
952 }
953
954 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
955 assert(Expr->getType()->isPointerTy() &&
956 "Should only reach pointer-typed SCEVUnknown's.");
957 // Perform some basic constant folding. If the operand of the cast is a
958 // null pointer, don't create a cast SCEV expression (that will be left
959 // as-is), but produce a zero constant.
961 return SE.getZero(TargetTy);
962 return CreatePtrCast(Expr);
963 }
964};
965
967 assert(Op->getType()->isPointerTy() && "Op must be a pointer");
968
969 // Treat pointers with unstable representation conservatively, since the
970 // address bits may change.
971 if (DL.hasUnstableRepresentation(Op->getType()))
972 return getCouldNotCompute();
973
974 Type *Ty = DL.getAddressType(Op->getType());
975
976 // Use the rewriter to sink the cast down to SCEVUnknown leaves.
977 // The rewriter handles null pointer constant folding.
979 Op, *this, Ty, [this, Ty](const SCEVUnknown *U) {
982 ID.AddPointer(U);
983 ID.AddPointer(Ty);
985 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
986 return S;
987 SCEV *S = new (SCEVAllocator)
988 SCEVPtrToAddrExpr(ID.Intern(SCEVAllocator), U, Ty);
989 UniqueSCEVs.insert(S, Token);
990 S->computeAndSetCanonical(*this);
991 registerUser(S, {U});
992 return static_cast<const SCEV *>(S);
993 });
994 assert(IntOp->getType()->isIntegerTy() &&
995 "We must have succeeded in sinking the cast, "
996 "and ending up with an integer-typed expression!");
997 return IntOp;
998}
999
1001 unsigned Depth) {
1002 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1003 "This is not a truncating conversion!");
1004 assert(isSCEVable(Ty) &&
1005 "This is not a conversion to a SCEVable type!");
1006 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1007 Ty = getEffectiveSCEVType(Ty);
1008
1011 ID.AddPointer(Op.getOpaqueValue());
1012 ID.AddPointer(Ty);
1014 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1015 return S;
1016
1017 // Fold if the operand is constant.
1018 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1019 return getConstant(
1020 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1021
1022 // trunc(trunc(x)) --> trunc(x)
1024 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1025
1026 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1028 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1029
1030 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1032 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1033
1034 if (Depth > Opts.scalar_evolution_max_cast_depth) {
1035 SCEV *S =
1036 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1037 UniqueSCEVs.insert(S, Token);
1038 S->computeAndSetCanonical(*this);
1039 registerUser(S, Op);
1040 return S;
1041 }
1042
1043 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1044 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1045 // if after transforming we have at most one truncate, not counting truncates
1046 // that replace other casts.
1048 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1050 unsigned numTruncs = 0;
1051 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1052 ++i) {
1053 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1054 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1056 numTruncs++;
1057 Operands.push_back(S);
1058 }
1059 if (numTruncs < 2) {
1060 if (isa<SCEVAddExpr>(Op))
1061 return getAddExpr(Operands);
1062 if (isa<SCEVMulExpr>(Op))
1063 return getMulExpr(Operands);
1064 llvm_unreachable("Unexpected SCEV type for Op.");
1065 }
1066 // Although we checked in the beginning that ID is not in the cache, it is
1067 // possible that during recursion and different modification ID was inserted
1068 // into the cache. So if we find it, just return it.
1069 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1070 return S;
1071 }
1072
1073 // If the input value is a chrec scev, truncate the chrec's operands.
1074 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1076 for (const SCEV *Op : AddRec->operands())
1077 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1078 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagNone);
1079 }
1080
1081 // Return zero if truncating to known zeros.
1082 uint32_t MinTrailingZeros = getMinTrailingZeros(Op);
1083 if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1084 return getZero(Ty);
1085
1086 // The cast wasn't folded; create an explicit cast node. We can reuse
1087 // the existing insert position since if we get here, we won't have
1088 // made any changes which would invalidate it.
1089 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1090 Op, Ty);
1091 UniqueSCEVs.insert(S, Token);
1092 S->computeAndSetCanonical(*this);
1093 registerUser(S, Op);
1094 return S;
1095}
1096
1097// Get the limit of a recurrence such that incrementing by Step cannot cause
1098// signed overflow as long as the value of the recurrence within the
1099// loop does not exceed this limit before incrementing.
1100static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1102 ScalarEvolution *SE) {
1103 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1104 if (SE->isKnownPositive(Step)) {
1107 SE->getSignedRangeMax(Step));
1108 }
1109 if (SE->isKnownNegative(Step)) {
1112 SE->getSignedRangeMin(Step));
1113 }
1114 return nullptr;
1115}
1116
1117// Get the limit of a recurrence such that incrementing by Step cannot cause
1118// unsigned overflow as long as the value of the recurrence within the loop does
1119// not exceed this limit before incrementing.
1122 ScalarEvolution *SE) {
1123 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1125
1127 SE->getUnsignedRangeMax(Step));
1128}
1129
1130namespace {
1131
1132struct ExtendOpTraitsBase {
1133 typedef SCEVUse (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
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 (any(Op.getNoWrapFlags(SCEVFlags::FlagNUW))) {
1452 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1453 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1454 return getAddRecExpr(Start, Step, L,
1455 Op.getFlagsToPropagate(SCEVFlags::FlagNUW));
1456 }
1457 }
1458
1459 // Before doing any expensive analysis, check to see if we've already
1460 // computed a SCEV for this Op and Ty.
1463 ID.AddPointer(Op.getOpaqueValue());
1464 ID.AddPointer(Ty);
1466 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1467 return S;
1468 if (Depth > Opts.scalar_evolution_max_cast_depth) {
1469 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1470 Op, Ty);
1471 UniqueSCEVs.insert(S, Token);
1472 S->computeAndSetCanonical(*this);
1473 registerUser(S, Op);
1474 return S;
1475 }
1476
1477 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1479 // It's possible the bits taken off by the truncate were all zero bits. If
1480 // so, we should be able to simplify this further.
1481 const SCEV *X = ST->getOperand();
1483 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1484 unsigned NewBits = getTypeSizeInBits(Ty);
1485 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1486 CR.zextOrTrunc(NewBits)))
1487 return getTruncateOrZeroExtend(X, Ty, Depth);
1488 }
1489
1490 // If the input value is a chrec scev, and we can prove that the value
1491 // did not overflow the old, smaller, value, we can zero extend all of the
1492 // operands (often constants). This allows analysis of something like
1493 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1494 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1495 const auto *AR = cast<SCEVAddRecExpr>(Op);
1496 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1497
1498 // The no-unsigned-wrap case is handled before the uniquing lookup above.
1499
1500 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1501 // Note that this serves two purposes: It filters out loops that are
1502 // simply not analyzable, and it covers the case where this code is
1503 // being called from within backedge-taken count analysis, such that
1504 // attempting to ask for the backedge-taken count would likely result
1505 // in infinite recursion. In the later case, the analysis code will
1506 // cope with a conservative value, and it will take care to purge
1507 // that value once it has finished.
1508 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1509 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1510 // Manually compute the final value for AR, checking for overflow.
1511
1512 // Check whether the backedge-taken count can be losslessly casted to
1513 // the addrec's type. The count is always unsigned.
1514 const SCEV *CastedMaxBECount =
1515 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1516 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1517 CastedMaxBECount, MaxBECount->getType(), Depth);
1518 if (MaxBECount == RecastedMaxBECount) {
1519 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1520 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1521 const SCEV *ZMul =
1522 getMulExpr(CastedMaxBECount, Step, SCEV::FlagNone, Depth + 1);
1523 const SCEV *ZAdd = getZeroExtendExpr(
1524 getAddExpr(Start, ZMul, SCEV::FlagNone, Depth + 1), WideTy,
1525 Depth + 1);
1526 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1527 const SCEV *WideMaxBECount =
1528 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1529 const SCEV *OperandExtendedAdd =
1530 getAddExpr(WideStart,
1531 getMulExpr(WideMaxBECount,
1532 getZeroExtendExpr(Step, WideTy, Depth + 1),
1533 SCEV::FlagNone, Depth + 1),
1534 SCEV::FlagNone, Depth + 1);
1535 if (ZAdd == OperandExtendedAdd) {
1536 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1537 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1538 // Return the expression with the addrec on the outside.
1539 Start =
1541 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1542 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1543 }
1544 // Similar to above, only this time treat the step value as signed.
1545 // This covers loops that count down.
1546 OperandExtendedAdd =
1547 getAddExpr(WideStart,
1548 getMulExpr(WideMaxBECount,
1549 getSignExtendExpr(Step, WideTy, Depth + 1),
1550 SCEV::FlagNone, Depth + 1),
1551 SCEV::FlagNone, Depth + 1);
1552 if (ZAdd == OperandExtendedAdd) {
1553 // Cache knowledge of AR NW, which is propagated to this AddRec.
1554 // Negative step causes unsigned wrap, but it still can't self-wrap.
1555 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1556 // Return the expression with the addrec on the outside.
1557 Start =
1559 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1560 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1561 }
1562 }
1563 }
1564
1565 // Normally, in the cases we can prove no-overflow via a
1566 // backedge guarding condition, we can also compute a backedge
1567 // taken count for the loop. The exceptions are assumptions and
1568 // guards present in the loop -- SCEV is not great at exploiting
1569 // these to compute max backedge taken counts, but can still use
1570 // these to prove lack of overflow. Use this fact to avoid
1571 // doing extra work that may not pay off.
1572 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1573 !AC.assumptions().empty()) {
1574
1575 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1576 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1577 if (AR->hasNoUnsignedWrap()) {
1578 // Same as nuw case above - duplicated here to avoid a compile time
1579 // issue. It's not clear that the order of checks does matter, but
1580 // it's one of two issue possible causes for a change which was
1581 // reverted. Be conservative for the moment.
1582 Start =
1584 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1585 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1586 }
1587
1588 // For a negative step, we can extend the operands iff doing so only
1589 // traverses values in the range zext([0,UINT_MAX]).
1590 if (isKnownNegative(Step)) {
1591 const SCEV *N =
1595 // Cache knowledge of AR NW, which is propagated to this
1596 // AddRec. Negative step causes unsigned wrap, but it
1597 // still can't self-wrap.
1598 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1599 // Return the expression with the addrec on the outside.
1600 Start =
1602 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1603 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1604 }
1605 }
1606 }
1607
1608 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1609 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1610 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1611 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1612 const APInt &C = SC->getAPInt();
1613 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1614 if (D != 0) {
1615 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1616 const SCEV *SResidual =
1617 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1618 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1619 return getAddExpr(SZExtD, SZExtR, SCEV::FlagNSW | SCEV::FlagNUW,
1620 Depth + 1);
1621 }
1622 }
1623
1624 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1625 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1626 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1627 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1628 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1629 }
1630 }
1631
1632 // zext(A % B) --> zext(A) % zext(B)
1633 {
1634 const SCEV *LHS;
1635 const SCEV *RHS;
1636 if (match(Op, m_scev_URem(m_SCEV(LHS), m_SCEV(RHS), *this)))
1637 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1638 getZeroExtendExpr(RHS, Ty, Depth + 1));
1639 }
1640
1641 // zext(A / B) --> zext(A) / zext(B).
1642 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1643 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1644 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1645
1646 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1647 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1648 if (SA->hasNoUnsignedWrap()) {
1649 // If the addition does not unsign overflow then we can, by definition,
1650 // commute the zero extension with the addition operation.
1652 for (SCEVUse Op : SA->operands())
1653 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1654 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1655 }
1656
1657 const APInt *C, *C2;
1658 // zext (C + A)<nsw> -> (sext(C) + sext(A))<nsw> if zext (C + A)<nsw> >=s 0.
1659 // Currently the non-negative check is done manually, as isKnownNonNegative
1660 // is too expensive.
1661 if (SA->hasNoSignedWrap() &&
1663 m_scev_SMax(m_scev_APInt(C2), m_SCEV()))) &&
1664 C->isNegative() && !C->isMinSignedValue() && C2->sge(C->abs())) {
1665 assert(isKnownNonNegative(SA) && "incorrectly determined non-negative");
1666 return getAddExpr(getSignExtendExpr(SA->getOperand(0), Ty, Depth + 1),
1667 getSignExtendExpr(SA->getOperand(1), Ty, Depth + 1),
1668 SCEV::FlagNSW, Depth + 1);
1669 }
1670
1671 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1672 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1673 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1674 //
1675 // Often address arithmetics contain expressions like
1676 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1677 // This transformation is useful while proving that such expressions are
1678 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1679 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1680 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1681 if (D != 0) {
1682 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1683 const SCEV *SResidual =
1685 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1686 return getAddExpr(SZExtD, SZExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1687 Depth + 1);
1688 }
1689 }
1690 }
1691
1692 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1693 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1694 if (SM->hasNoUnsignedWrap()) {
1695 // If the multiply does not unsign overflow then we can, by definition,
1696 // commute the zero extension with the multiply operation.
1698 for (SCEVUse Op : SM->operands())
1699 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1700 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1701 }
1702
1703 // zext(2^K * (trunc X to iN)) to iM ->
1704 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1705 //
1706 // Proof:
1707 //
1708 // zext(2^K * (trunc X to iN)) to iM
1709 // = zext((trunc X to iN) << K) to iM
1710 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1711 // (because shl removes the top K bits)
1712 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1713 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1714 //
1715 const APInt *C;
1716 const SCEV *TruncRHS;
1717 if (match(SM,
1718 m_scev_Mul(m_scev_APInt(C), m_scev_Trunc(m_SCEV(TruncRHS)))) &&
1719 C->isPowerOf2()) {
1720 int NewTruncBits =
1721 getTypeSizeInBits(SM->getOperand(1)->getType()) - C->logBase2();
1722 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1723 return getMulExpr(
1724 getZeroExtendExpr(SM->getOperand(0), Ty),
1725 getZeroExtendExpr(getTruncateExpr(TruncRHS, NewTruncTy), Ty),
1726 SCEV::FlagNUW, Depth + 1);
1727 }
1728 }
1729
1730 // zext(umin(x, y)) -> umin(zext(x), zext(y))
1731 // zext(umax(x, y)) -> umax(zext(x), zext(y))
1735 for (SCEVUse Operand : MinMax->operands())
1736 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1738 return getUMinExpr(Operands);
1739 return getUMaxExpr(Operands);
1740 }
1741
1742 // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
1744 assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!");
1746 for (SCEVUse Operand : MinMax->operands())
1747 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1748 return getUMinExpr(Operands, /*Sequential*/ true);
1749 }
1750
1751 // The cast wasn't folded; create an explicit cast node.
1752 // Recompute the insert position, as it may have been invalidated.
1753 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1754 return S;
1755 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1756 Op, Ty);
1757 UniqueSCEVs.insert(S, Token);
1758 S->computeAndSetCanonical(*this);
1759 registerUser(S, Op);
1760 return S;
1761}
1762
1764 unsigned Depth) {
1765 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1766 "This is not an extending conversion!");
1767 assert(isSCEVable(Ty) &&
1768 "This is not a conversion to a SCEVable type!");
1769 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1770 Ty = getEffectiveSCEVType(Ty);
1771
1772 FoldID ID(scSignExtend, Op, Ty);
1773 if (const SCEV *S = FoldCache.lookup(ID))
1774 return S;
1775
1778 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1779 return S;
1780}
1781
1783 unsigned Depth) {
1784 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1785 "This is not an extending conversion!");
1786 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1787 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1788 Ty = getEffectiveSCEVType(Ty);
1789
1790 // Fold if the operand is constant.
1791 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1792 return getConstant(SC->getAPInt().sext(getTypeSizeInBits(Ty)));
1793
1794 // sext(sext(x)) --> sext(x)
1796 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1797
1798 // sext(zext(x)) --> zext(x)
1800 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1801
1802 // If the operand is an affine AddRec with the no-signed-wrap flag, the
1803 // sign-extension distributes over the recurrence.
1804 const SCEV *Start, *Step;
1805 const Loop *L;
1806 if (Depth <= Opts.scalar_evolution_max_cast_depth &&
1807 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1808 const auto *AR = cast<SCEVAddRecExpr>(Op);
1809 if (any(Op.getNoWrapFlags(SCEVFlags::FlagNSW))) {
1810 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
1811 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1812 return getAddRecExpr(Start, Step, L,
1813 Op.getFlagsToPropagate(SCEVFlags::FlagNSW));
1814 }
1815 }
1816
1817 // Before doing any expensive analysis, check to see if we've already
1818 // computed a SCEV for this Op and Ty.
1821 ID.AddPointer(Op.getOpaqueValue());
1822 ID.AddPointer(Ty);
1824 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1825 return S;
1826 // Limit recursion depth.
1827 if (Depth > Opts.scalar_evolution_max_cast_depth) {
1828 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1829 Op, Ty);
1830 UniqueSCEVs.insert(S, Token);
1831 S->computeAndSetCanonical(*this);
1832 registerUser(S, Op);
1833 return S;
1834 }
1835
1836 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1838 // It's possible the bits taken off by the truncate were all sign bits. If
1839 // so, we should be able to simplify this further.
1840 const SCEV *X = ST->getOperand();
1842 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1843 unsigned NewBits = getTypeSizeInBits(Ty);
1844 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1845 CR.sextOrTrunc(NewBits)))
1846 return getTruncateOrSignExtend(X, Ty, Depth);
1847 }
1848
1849 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1850 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1851 if (SA->hasNoSignedWrap()) {
1852 // If the addition does not sign overflow then we can, by definition,
1853 // commute the sign extension with the addition operation.
1855 for (SCEVUse Op : SA->operands())
1856 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1857 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1858 }
1859
1860 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1861 // if D + (C - D + x + y + ...) could be proven to not signed wrap
1862 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1863 //
1864 // For instance, this will bring two seemingly different expressions:
1865 // 1 + sext(5 + 20 * %x + 24 * %y) and
1866 // sext(6 + 20 * %x + 24 * %y)
1867 // to the same form:
1868 // 2 + sext(4 + 20 * %x + 24 * %y)
1869 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1870 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1871 if (D != 0) {
1872 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1873 const SCEV *SResidual =
1875 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1876 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1877 Depth + 1);
1878 }
1879 }
1880 }
1881 // If the input value is a chrec scev, and we can prove that the value
1882 // did not overflow the old, smaller, value, we can sign extend all of the
1883 // operands (often constants). This allows analysis of something like
1884 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1885 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1886 const auto *AR = cast<SCEVAddRecExpr>(Op);
1887 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1888
1889 // The no-signed-wrap case is handled before the uniquing lookup above.
1890
1891 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1892 // Note that this serves two purposes: It filters out loops that are
1893 // simply not analyzable, and it covers the case where this code is
1894 // being called from within backedge-taken count analysis, such that
1895 // attempting to ask for the backedge-taken count would likely result
1896 // in infinite recursion. In the later case, the analysis code will
1897 // cope with a conservative value, and it will take care to purge
1898 // that value once it has finished.
1899 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1900 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1901 // Manually compute the final value for AR, checking for
1902 // overflow.
1903
1904 // Check whether the backedge-taken count can be losslessly casted to
1905 // the addrec's type. The count is always unsigned.
1906 const SCEV *CastedMaxBECount =
1907 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1908 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1909 CastedMaxBECount, MaxBECount->getType(), Depth);
1910 if (MaxBECount == RecastedMaxBECount) {
1911 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1912 // Check whether Start+Step*MaxBECount has no signed overflow.
1913 const SCEV *SMul =
1914 getMulExpr(CastedMaxBECount, Step, SCEV::FlagNone, Depth + 1);
1915 const SCEV *SAdd = getSignExtendExpr(
1916 getAddExpr(Start, SMul, SCEV::FlagNone, Depth + 1), WideTy,
1917 Depth + 1);
1918 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
1919 const SCEV *WideMaxBECount =
1920 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1921 const SCEV *OperandExtendedAdd =
1922 getAddExpr(WideStart,
1923 getMulExpr(WideMaxBECount,
1924 getSignExtendExpr(Step, WideTy, Depth + 1),
1925 SCEV::FlagNone, Depth + 1),
1926 SCEV::FlagNone, Depth + 1);
1927 if (SAdd == OperandExtendedAdd) {
1928 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1929 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
1930 // Return the expression with the addrec on the outside.
1931 Start =
1933 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1934 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1935 }
1936 // Similar to above, only this time treat the step value as unsigned.
1937 // This covers loops that count up with an unsigned step.
1938 OperandExtendedAdd =
1939 getAddExpr(WideStart,
1940 getMulExpr(WideMaxBECount,
1941 getZeroExtendExpr(Step, WideTy, Depth + 1),
1942 SCEV::FlagNone, Depth + 1),
1943 SCEV::FlagNone, Depth + 1);
1944 if (SAdd == OperandExtendedAdd) {
1945 // If AR wraps around then
1946 //
1947 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
1948 // => SAdd != OperandExtendedAdd
1949 //
1950 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1951 // (SAdd == OperandExtendedAdd => AR is NW)
1952
1953 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1954
1955 // Return the expression with the addrec on the outside.
1956 Start =
1958 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1959 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1960 }
1961 }
1962 }
1963
1964 auto NewFlags = proveNoSignedWrapViaInduction(AR);
1965 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1966 if (AR->hasNoSignedWrap()) {
1967 // Same as nsw case above - duplicated here to avoid a compile time
1968 // issue. It's not clear that the order of checks does matter, but
1969 // it's one of two issue possible causes for a change which was
1970 // reverted. Be conservative for the moment.
1971 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
1972 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1973 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1974 }
1975
1976 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
1977 // if D + (C - D + Step * n) could be proven to not signed wrap
1978 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1979 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1980 const APInt &C = SC->getAPInt();
1981 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1982 if (D != 0) {
1983 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1984 const SCEV *SResidual =
1985 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1986 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1987 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1988 Depth + 1);
1989 }
1990 }
1991
1992 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1993 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
1994 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
1995 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1996 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1997 }
1998 }
1999
2000 // If the input value is provably positive and we could not simplify
2001 // away the sext build a zext instead.
2003 return getZeroExtendExpr(Op, Ty, Depth + 1);
2004
2005 // sext(smin(x, y)) -> smin(sext(x), sext(y))
2006 // sext(smax(x, y)) -> smax(sext(x), sext(y))
2010 for (SCEVUse Operand : MinMax->operands())
2011 Operands.push_back(getSignExtendExpr(Operand, Ty));
2013 return getSMinExpr(Operands);
2014 return getSMaxExpr(Operands);
2015 }
2016
2017 // The cast wasn't folded; create an explicit cast node.
2018 // Recompute the insert position, as it may have been invalidated.
2019 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
2020 return S;
2021 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2022 Op, Ty);
2023 UniqueSCEVs.insert(S, Token);
2024 S->computeAndSetCanonical(*this);
2025 registerUser(S, Op);
2026 return S;
2027}
2028
2030 switch (Kind) {
2031 case scTruncate:
2032 return getTruncateExpr(Op, Ty);
2033 case scZeroExtend:
2034 return getZeroExtendExpr(Op, Ty);
2035 case scSignExtend:
2036 return getSignExtendExpr(Op, Ty);
2037 case scPtrToAddr: {
2038 const SCEV *Expr = getPtrToAddrExpr(Op);
2039 assert(Expr->getType() == Ty && "requested type must match");
2040 return Expr;
2041 }
2042 default:
2043 llvm_unreachable("Not a SCEV cast expression!");
2044 }
2045}
2046
2047/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2048/// unspecified bits out to the given type.
2050 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2051 "This is not an extending conversion!");
2052 assert(isSCEVable(Ty) &&
2053 "This is not a conversion to a SCEVable type!");
2054 Ty = getEffectiveSCEVType(Ty);
2055
2056 // Sign-extend negative constants.
2057 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2058 if (SC->getAPInt().isNegative())
2059 return getSignExtendExpr(Op, Ty);
2060
2061 // Peel off a truncate cast.
2063 const SCEV *NewOp = T->getOperand();
2064 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2065 return getAnyExtendExpr(NewOp, Ty);
2066 return getTruncateOrNoop(NewOp, Ty);
2067 }
2068
2069 // Next try a zext cast. If the cast is folded, use it.
2070 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2071 if (!isa<SCEVZeroExtendExpr>(ZExt))
2072 return ZExt;
2073
2074 // Next try a sext cast. If the cast is folded, use it.
2075 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2076 if (!isa<SCEVSignExtendExpr>(SExt))
2077 return SExt;
2078
2079 // Force the cast to be folded into the operands of an addrec.
2080 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2082 for (const SCEV *Op : AR->operands())
2083 Ops.push_back(getAnyExtendExpr(Op, Ty));
2084 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2085 }
2086
2087 // If the expression is obviously signed, use the sext cast value.
2088 if (isa<SCEVSMaxExpr>(Op))
2089 return SExt;
2090
2091 // Absent any other information, use the zext cast value.
2092 return ZExt;
2093}
2094
2095/// Process the given Ops list, which is a list of operands to be added under
2096/// the given scale, update the given map. This is a helper function for
2097/// getAddRecExpr. As an example of what it does, given a sequence of operands
2098/// that would form an add expression like this:
2099///
2100/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2101///
2102/// where A and B are constants, update the map with these values:
2103///
2104/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2105///
2106/// and add 13 + A*B*29 to AccumulatedConstant.
2107/// This will allow getAddRecExpr to produce this:
2108///
2109/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2110///
2111/// This form often exposes folding opportunities that are hidden in
2112/// the original operand list.
2113///
2114/// Return true iff it appears that any interesting folding opportunities
2115/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2116/// the common case where no interesting opportunities are present, and
2117/// is also used as a check to avoid infinite recursion.
2118static bool
2121 APInt &AccumulatedConstant, ArrayRef<SCEVUse> Ops,
2122 const APInt &Scale, ScalarEvolution &SE) {
2123 bool Interesting = false;
2124
2125 // Iterate over the add operands. They are sorted, with constants first.
2126 unsigned i = 0;
2127 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2128 ++i;
2129 // Pull a buried constant out to the outside.
2130 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2131 Interesting = true;
2132 AccumulatedConstant += Scale * C->getAPInt();
2133 }
2134
2135 // Next comes everything else. We're especially interested in multiplies
2136 // here, but they're in the middle, so just visit the rest with one loop.
2137 for (; i != Ops.size(); ++i) {
2139 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2140 APInt NewScale =
2141 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2142 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2143 // A multiplication of a constant with another add; recurse.
2144 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2145 Interesting |= CollectAddOperandsWithScales(
2146 M, NewOps, AccumulatedConstant, Add->operands(), NewScale, SE);
2147 } else {
2148 // A multiplication of a constant with some other value. Update
2149 // the map.
2150 SmallVector<SCEVUse, 4> MulOps(drop_begin(Mul->operands()));
2151 const SCEV *Key = SE.getMulExpr(MulOps)->getCanonical();
2152 auto Pair = M.insert({Key, NewScale});
2153 if (Pair.second) {
2154 NewOps.push_back(Pair.first->first);
2155 } else {
2156 Pair.first->second += NewScale;
2157 // The map already had an entry for this value, which may indicate
2158 // a folding opportunity.
2159 Interesting = true;
2160 }
2161 }
2162 } else {
2163 // An ordinary operand. Update the map.
2164 auto Pair = M.insert({Ops[i]->getCanonical(), Scale});
2165 if (Pair.second) {
2166 NewOps.push_back(Pair.first->first);
2167 } else {
2168 Pair.first->second += Scale;
2169 // The map already had an entry for this value, which may indicate
2170 // a folding opportunity.
2171 Interesting = true;
2172 }
2173 }
2174 }
2175
2176 return Interesting;
2177}
2178
2180 const SCEV *LHS, const SCEV *RHS,
2181 const Instruction *CtxI) {
2182 auto Operation = [this, BinOp](SCEVUse L, SCEVUse R) -> const SCEV * {
2183 switch (BinOp) {
2184 default:
2185 llvm_unreachable("Unsupported binary op");
2186 case Instruction::Add:
2187 return getAddExpr(L, R);
2188 case Instruction::Sub:
2189 return getMinusSCEV(L, R);
2190 case Instruction::Mul:
2191 return getMulExpr(L, R);
2192 }
2193 };
2194
2195 SCEVUse (ScalarEvolution::*Extension)(SCEVUse, Type *, unsigned) =
2198
2199 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2200 auto *NarrowTy = cast<IntegerType>(LHS->getType());
2201 auto *WideTy =
2202 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2203
2204 const SCEV *A = (this->*Extension)(Operation(LHS, RHS), WideTy, 0);
2205 const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2206 const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2207 const SCEV *B = Operation(LHSB, RHSB);
2208 if (A == B)
2209 return true;
2210 // Can we use context to prove the fact we need?
2211 if (!CtxI)
2212 return false;
2213 // TODO: Support mul.
2214 if (BinOp == Instruction::Mul)
2215 return false;
2216 auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2217 // TODO: Lift this limitation.
2218 if (!RHSC)
2219 return false;
2220 APInt C = RHSC->getAPInt();
2221 unsigned NumBits = C.getBitWidth();
2222 bool IsSub = (BinOp == Instruction::Sub);
2223 bool IsNegativeConst = (Signed && C.isNegative());
2224 // Compute the direction and magnitude by which we need to check overflow.
2225 bool OverflowDown = IsSub ^ IsNegativeConst;
2226 APInt Magnitude = C;
2227 if (IsNegativeConst) {
2228 if (C == APInt::getSignedMinValue(NumBits))
2229 // TODO: SINT_MIN on inversion gives the same negative value, we don't
2230 // want to deal with that.
2231 return false;
2232 Magnitude = -C;
2233 }
2234
2236 if (OverflowDown) {
2237 // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2238 APInt Min = Signed ? APInt::getSignedMinValue(NumBits)
2239 : APInt::getMinValue(NumBits);
2240 APInt Limit = Min + Magnitude;
2241 return isKnownPredicateAt(Pred, getConstant(Limit), LHS, CtxI);
2242 } else {
2243 // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2244 APInt Max = Signed ? APInt::getSignedMaxValue(NumBits)
2245 : APInt::getMaxValue(NumBits);
2246 APInt Limit = Max - Magnitude;
2247 return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2248 }
2249}
2250
2252 const OverflowingBinaryOperator *OBO) {
2253 // It cannot be done any better.
2254 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2255 return std::nullopt;
2256
2258
2259 if (OBO->hasNoUnsignedWrap())
2261 if (OBO->hasNoSignedWrap())
2263
2264 bool Deduced = false;
2265
2267 const SCEV *LHS = getSCEV(OBO->getOperand(0));
2268 const SCEV *RHS = getSCEV(OBO->getOperand(1));
2269
2270 bool CanUseNSW = true;
2271 const APInt *ShiftAmt;
2272 // Treat `shl %a, C` as `mul %a, 1 << C`.
2273 if (match(OBO, m_Shl(m_Value(), m_APInt(ShiftAmt)))) {
2274 unsigned BitWidth = ShiftAmt->getBitWidth();
2275 if (ShiftAmt->uge(BitWidth))
2276 return std::nullopt;
2277 // NSW only transfers if the shift amount is < BitWidth - 1, as INT_MIN * -1
2278 // overflows.
2279 CanUseNSW = ShiftAmt->ult(BitWidth - 1);
2280 Opcode = Instruction::Mul;
2282 } else if (Opcode != Instruction::Add && Opcode != Instruction::Sub &&
2283 Opcode != Instruction::Mul) {
2284 return std::nullopt;
2285 }
2286
2287 const Instruction *CtxI =
2288 Opts.scalar_evolution_use_context_for_no_wrap_flag_strenghening
2290 : nullptr;
2291 if (!OBO->hasNoUnsignedWrap() &&
2292 willNotOverflow(Opcode, /* Signed */ false, LHS, RHS, CtxI)) {
2294 Deduced = true;
2295 }
2296
2297 if (CanUseNSW && !OBO->hasNoSignedWrap() &&
2298 willNotOverflow(Opcode, /* Signed */ true, LHS, RHS, CtxI)) {
2300 Deduced = true;
2301 }
2302
2303 if (Deduced)
2304 return Flags;
2305 return std::nullopt;
2306}
2307
2308// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2309// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2310// can't-overflow flags for the operation if possible.
2313 using namespace std::placeholders;
2314
2315 using OBO = OverflowingBinaryOperator;
2316
2317 bool CanAnalyze =
2319 (void)CanAnalyze;
2320 assert(CanAnalyze && "don't call from other places!");
2321
2322 SCEVFlags SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2323 SCEVFlags SignOrUnsignWrap =
2324 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2325
2326 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2327 auto IsKnownNonNegative = [&](SCEVUse U) {
2328 return SE->isKnownNonNegative(U);
2329 };
2330
2331 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2332 Flags = ScalarEvolution::setFlags(Flags, SignOrUnsignMask);
2333
2334 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2335
2336 if (SignOrUnsignWrap != SignOrUnsignMask &&
2337 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2338 isa<SCEVConstant>(Ops[0])) {
2339
2340 auto Opcode = [&] {
2341 switch (Type) {
2342 case scAddExpr:
2343 return Instruction::Add;
2344 case scMulExpr:
2345 return Instruction::Mul;
2346 default:
2347 llvm_unreachable("Unexpected SCEV op.");
2348 }
2349 }();
2350
2351 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2352
2353 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2354 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2355 auto NSWRegion =
2356 ConstantRange::makeExactNoWrapRegion(Opcode, C, OBO::NoSignedWrap);
2357 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2359 }
2360
2361 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2362 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2363 auto NUWRegion =
2364 ConstantRange::makeExactNoWrapRegion(Opcode, C, OBO::NoUnsignedWrap);
2365 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2367 }
2368 }
2369
2370 // <0,+,nonnegative><nw> is also nuw
2371 // TODO: Add corresponding nsw case
2373 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2374 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2376
2377 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2379 Ops.size() == 2) {
2380 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2381 if (UDiv->getOperand(1) == Ops[1])
2383 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2384 if (UDiv->getOperand(1) == Ops[0])
2386 }
2387
2388 return Flags;
2389}
2390
2392 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2393}
2394
2395/// Get a canonical add expression, or something simpler if possible.
2397 SCEVFlagsPair Flags, unsigned Depth) {
2398 SCEVFlags ExprFlags = Flags.ExprFlags;
2399 SCEVFlags UseFlags = Flags.UseFlags;
2400 assert(!(ExprFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2401 "only nuw or nsw allowed");
2402 assert(!(UseFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2403 "only nuw or nsw allowed");
2404 assert(!Ops.empty() && "Cannot get empty add!");
2405 if (Ops.size() == 1) return Ops[0];
2406#ifndef NDEBUG
2407 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2408 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2409 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2410 "SCEVAddExpr operand types don't match!");
2411 unsigned NumPtrs = count_if(
2412 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2413 assert(NumPtrs <= 1 && "add has at most one pointer operand");
2414#endif
2415
2417 Opts, *this, LI, DT, Ops,
2418 [](const APInt &C1, const APInt &C2) { return C1 + C2; },
2419 [](const APInt &C) { return C.isZero(); }, // identity
2420 [](const APInt &C) { return false; }); // absorber
2421 if (Folded)
2422 return Folded;
2423
2424#ifndef NDEBUG
2425 // Keep track of operands after constant folding, for verification when adding
2426 // use-specific flags.
2427 const SmallVector<SCEVUse, 8> OrigOps(Ops.begin(), Ops.end());
2428#endif
2429
2430 unsigned Idx = isa<SCEVConstant>(Ops[0]) ? 1 : 0;
2431
2432 // Delay expensive flag strengthening until necessary.
2433 auto ComputeFlags = [this, ExprFlags](ArrayRef<SCEVUse> Ops) {
2434 return StrengthenNoWrapFlags(this, scAddExpr, Ops, ExprFlags);
2435 };
2436
2437 // Limit recursion calls depth.
2438 if (Depth > Opts.scalar_evolution_max_arith_depth ||
2439 hasHugeExpression(Opts, Ops))
2440 return {getOrCreateAddExpr(Ops, ComputeFlags(Ops)), UseFlags};
2441
2442 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2443 // Don't strengthen flags if we have no new information.
2444 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2445 if (Add->getNoWrapFlags(ExprFlags) != ExprFlags)
2446 Add->setNoWrapFlags(ComputeFlags(Ops));
2447 return {S, UseFlags};
2448 }
2449
2450 // Okay, check to see if the same value occurs in the operand list more than
2451 // once. If so, merge them together into an multiply expression. Since we
2452 // sorted the list, these values are required to be adjacent.
2453 Type *Ty = Ops[0]->getType();
2454 bool FoundMatch = false;
2455 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2456 if (SCEVUse Op = SCEVUse::getCommon(Ops[i], Ops[i + 1])) {
2457 // X + Y + Y --> X + Y*2
2458 // Scan ahead to count how many equal operands there are.
2459 unsigned Count = 2;
2460 for (; i + Count != e; ++Count) {
2461 SCEVUse Common = SCEVUse::getCommon(Op, Ops[i + Count]);
2462 if (!Common)
2463 break;
2464 Op = Common;
2465 }
2466 // Merge the values into a multiply.
2467 SCEVUse Scale = getConstant(Ty, Count);
2468 SCEVUse Mul = getMulExpr(Scale, Op, SCEV::FlagNone, Depth + 1);
2469 if (Ops.size() == Count)
2470 return Mul;
2471 Ops[i] = Mul;
2472 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2473 --i; e -= Count - 1;
2474 FoundMatch = true;
2475 }
2476 if (FoundMatch)
2477 return getAddExpr(Ops, ExprFlags, Depth + 1);
2478
2479 // Check for truncates. If all the operands are truncated from the same
2480 // type, see if factoring out the truncate would permit the result to be
2481 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2482 // if the contents of the resulting outer trunc fold to something simple.
2483 auto FindTruncSrcType = [&]() -> Type * {
2484 // We're ultimately looking to fold an addrec of truncs and muls of only
2485 // constants and truncs, so if we find any other types of SCEV
2486 // as operands of the addrec then we bail and return nullptr here.
2487 // Otherwise, we return the type of the operand of a trunc that we find.
2488 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2489 return T->getOperand()->getType();
2490 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2491 SCEVUse LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2492 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2493 return T->getOperand()->getType();
2494 }
2495 return nullptr;
2496 };
2497 if (auto *SrcType = FindTruncSrcType()) {
2498 SmallVector<SCEVUse, 8> LargeOps;
2499 bool Ok = true;
2500 // Check all the operands to see if they can be represented in the
2501 // source type of the truncate.
2502 for (const SCEV *Op : Ops) {
2504 if (T->getOperand()->getType() != SrcType) {
2505 Ok = false;
2506 break;
2507 }
2508 LargeOps.push_back(T->getOperand());
2509 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Op)) {
2510 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2511 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Op)) {
2512 SmallVector<SCEVUse, 8> LargeMulOps;
2513 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2514 if (const SCEVTruncateExpr *T =
2515 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2516 if (T->getOperand()->getType() != SrcType) {
2517 Ok = false;
2518 break;
2519 }
2520 LargeMulOps.push_back(T->getOperand());
2521 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2522 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2523 } else {
2524 Ok = false;
2525 break;
2526 }
2527 }
2528 if (Ok)
2529 LargeOps.push_back(
2530 getMulExpr(LargeMulOps, SCEV::FlagNone, Depth + 1));
2531 } else {
2532 Ok = false;
2533 break;
2534 }
2535 }
2536 if (Ok) {
2537 // Evaluate the expression in the larger type.
2538 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagNone, Depth + 1);
2539 // If it folds to something simple, use it. Otherwise, don't.
2540 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2541 return getTruncateExpr(Fold, Ty);
2542 }
2543 }
2544
2545 if (Ops.size() == 2) {
2546 // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2547 // C2 can be folded in a way that allows retaining wrapping flags of (X +
2548 // C1).
2549 const SCEV *A = Ops[0];
2550 const SCEV *B = Ops[1];
2551 auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2552 auto *C = dyn_cast<SCEVConstant>(A);
2553 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2554 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2555 auto C2 = C->getAPInt();
2556 SCEVFlags PreservedFlags = SCEV::FlagNone;
2557
2558 APInt ConstAdd = C1 + C2;
2559 auto AddFlags = AddExpr->getNoWrapFlags();
2560 // Adding a smaller constant is NUW if the original AddExpr was NUW.
2562 ConstAdd.ule(C1)) {
2563 PreservedFlags =
2565 }
2566
2567 // Adding a constant with the same sign and small magnitude is NSW, if the
2568 // original AddExpr was NSW.
2570 C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2571 ConstAdd.abs().ule(C1.abs())) {
2572 PreservedFlags =
2574 }
2575
2576 if (PreservedFlags != SCEV::FlagNone) {
2577 SmallVector<SCEVUse, 4> NewOps(AddExpr->operands());
2578 NewOps[0] = getConstant(ConstAdd);
2579 return getAddExpr(NewOps, PreservedFlags);
2580 }
2581 }
2582
2583 // Try to push the constant operand into a ZExt: A + zext (-A + B) -> zext
2584 // (B), if trunc (A) + -A + B does not unsigned-wrap.
2585 const SCEVAddExpr *InnerAdd;
2586 if (match(B, m_scev_ZExt(m_scev_Add(InnerAdd)))) {
2587 const SCEV *NarrowA = getTruncateExpr(A, InnerAdd->getType());
2588 if (NarrowA == getNegativeSCEV(InnerAdd->getOperand(0)) &&
2589 getZeroExtendExpr(NarrowA, B->getType()) == A &&
2590 hasFlags(StrengthenNoWrapFlags(this, scAddExpr, {NarrowA, InnerAdd},
2592 SCEV::FlagNUW)) {
2593 return getZeroExtendExpr(getAddExpr(NarrowA, InnerAdd), B->getType());
2594 }
2595 }
2596 }
2597
2598 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2599 const SCEV *Y;
2600 if (Ops.size() == 2 &&
2601 match(Ops[0],
2603 m_scev_URem(m_scev_Specific(Ops[1]), m_SCEV(Y), *this))))
2604 return getMulExpr(Y, getUDivExpr(Ops[1], Y));
2605
2606 // Skip past any other cast SCEVs.
2607 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2608 ++Idx;
2609
2610 // If there are add operands they would be next.
2611 if (Idx < Ops.size()) {
2612 bool DeletedAdd = false;
2613 // If the original flags and all inlined SCEVAddExprs are NUW, use the
2614 // common NUW flag for expression after inlining. Other flags cannot be
2615 // preserved, because they may depend on the original order of operations.
2616 SCEVFlags CommonFlags = maskFlags(ExprFlags, SCEV::FlagNUW);
2617 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2618 if (Ops.size() > Opts.scev_addops_inline_threshold ||
2619 Add->getNumOperands() > Opts.scev_addops_inline_threshold)
2620 break;
2621 // If we have an add, expand the add operands onto the end of the operands
2622 // list.
2623 Ops.erase(Ops.begin()+Idx);
2624 append_range(Ops, Add->operands());
2625 DeletedAdd = true;
2626 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2627 }
2628
2629 // If we deleted at least one add, we added operands to the end of the list,
2630 // and they are not necessarily sorted. Recurse to resort and resimplify
2631 // any operands we just acquired.
2632 if (DeletedAdd)
2633 return getAddExpr(Ops, CommonFlags, Depth + 1);
2634 }
2635
2636 // Skip over the add expression until we get to a multiply.
2637 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2638 ++Idx;
2639
2640 // Check to see if there are any folding opportunities present with
2641 // operands multiplied by constant values.
2642 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2643 uint64_t BitWidth = getTypeSizeInBits(Ty);
2646 APInt AccumulatedConstant(BitWidth, 0);
2647 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2648 Ops, APInt(BitWidth, 1), *this)) {
2649 struct APIntCompare {
2650 bool operator()(const APInt &LHS, const APInt &RHS) const {
2651 return LHS.ult(RHS);
2652 }
2653 };
2654
2655 // Some interesting folding opportunity is present, so its worthwhile to
2656 // re-generate the operands list. Group the operands by constant scale,
2657 // to avoid multiplying by the same constant scale multiple times.
2658 std::map<APInt, SmallVector<SCEVUse, 4>, APIntCompare> MulOpLists;
2659 for (SCEVUse NewOp : NewOps)
2660 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2661 // Re-generate the operands list.
2662 Ops.clear();
2663 if (AccumulatedConstant != 0)
2664 Ops.push_back(getConstant(AccumulatedConstant));
2665 for (auto &MulOp : MulOpLists) {
2666 if (MulOp.first == 1) {
2667 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagNone, Depth + 1));
2668 } else if (MulOp.first != 0) {
2669 Ops.push_back(
2670 getMulExpr(getConstant(MulOp.first),
2671 getAddExpr(MulOp.second, SCEV::FlagNone, Depth + 1),
2672 SCEV::FlagNone, Depth + 1));
2673 }
2674 }
2675 if (Ops.empty())
2676 return getZero(Ty);
2677 if (Ops.size() == 1)
2678 return Ops[0];
2679 return getAddExpr(Ops, SCEV::FlagNone, Depth + 1);
2680 }
2681 }
2682
2683 // Given a SCEVMulExpr and an operand index, return the product of all
2684 // operands except the one at OpIdx.
2685 auto StripFactor = [&](const SCEVMulExpr *M, unsigned OpIdx) -> SCEVUse {
2686 if (M->getNumOperands() == 2)
2687 return M->getOperand(OpIdx == 0);
2688 SmallVector<SCEVUse, 4> Remaining(M->operands().take_front(OpIdx));
2689 append_range(Remaining, M->operands().drop_front(OpIdx + 1));
2690 return getMulExpr(Remaining, SCEV::FlagNone, Depth + 1);
2691 };
2692
2693 // If we are adding something to a multiply expression, make sure the
2694 // something is not already an operand of the multiply. If so, merge it into
2695 // the multiply.
2696 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2697 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2698 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2699 // Scan all terms to find every occurrence of common factor MulOpSCEV
2700 // and fold them in one shot:
2701 // A1*X + A2*X + ... + An*X --> X * (A1 + A2 + ... + An)
2702 SCEVUse MulOpSCEV = Mul->getOperand(MulOp);
2703 if (isa<SCEVConstant>(MulOpSCEV))
2704 continue;
2705
2706 // Cofactors: 1 for bare addends matching MulOpSCEV, or the
2707 // remaining product for multiply terms containing MulOpSCEV.
2708 SmallVector<SCEVUse, 4> Cofactors;
2709 SmallVector<unsigned, 4> DeadIndices;
2710 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) {
2711 if (SCEVUse Common = SCEVUse::getCommon(MulOpSCEV, Ops[AddOp])) {
2712 // W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2713 MulOpSCEV = Common;
2714 Cofactors.push_back(getOne(Ty));
2715 DeadIndices.push_back(AddOp);
2716 continue;
2717 }
2718
2719 if (AddOp <= Idx || !isa<SCEVMulExpr>(Ops[AddOp]))
2720 continue;
2721
2722 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[AddOp]);
2723 for (unsigned OMulOp = 0, OE = OtherMul->getNumOperands(); OMulOp != OE;
2724 ++OMulOp) {
2725 if (SCEVUse Common =
2726 SCEVUse::getCommon(MulOpSCEV, OtherMul->getOperand(OMulOp))) {
2727 // (A*B*C) + (A*D*E) --> A * (B*C + D*E)
2728 MulOpSCEV = Common;
2729 Cofactors.push_back(StripFactor(OtherMul, OMulOp));
2730 DeadIndices.push_back(AddOp);
2731 break;
2732 }
2733 }
2734 }
2735
2736 // Fold all collected cofactors with the anchor multiply's cofactor:
2737 // MulOpSCEV * (Cofactor_1 + ... + Cofactor_n + AnchorCofactor)
2738 if (!Cofactors.empty()) {
2739 Cofactors.push_back(StripFactor(Mul, MulOp));
2740
2741 SCEVUse InnerSum = getAddExpr(Cofactors, SCEV::FlagNone, Depth + 1);
2742 SCEVUse OuterMul =
2743 getMulExpr(MulOpSCEV, InnerSum, SCEV::FlagNone, Depth + 1);
2744
2745 // DeadIndices does not include Idx (the anchor), hence +1.
2746 if (Ops.size() == DeadIndices.size() + 1)
2747 return OuterMul;
2748
2749 // Erase Ops[Idx] first, then erase DeadIndices in reverse order.
2750 // The -1 adjustment accounts for the shift from removing Idx;
2751 // reverse order means each erasure only shifts later positions,
2752 // which have already been processed.
2753 Ops.erase(Ops.begin() + Idx);
2754 for (unsigned Dead : reverse(DeadIndices))
2755 Ops.erase(Ops.begin() + (Dead > Idx ? Dead - 1 : Dead));
2756
2757 Ops.push_back(OuterMul);
2758 return getAddExpr(Ops, SCEV::FlagNone, Depth + 1);
2759 }
2760 }
2761 }
2762
2763 // If there are any add recurrences in the operands list, see if any other
2764 // added values are loop invariant. If so, we can fold them into the
2765 // recurrence.
2766 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2767 ++Idx;
2768
2769 // Scan over all recurrences, trying to fold loop invariants into them.
2770 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2771 // Scan all of the other operands to this add and add them to the vector if
2772 // they are loop invariant w.r.t. the recurrence.
2774 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2775 const Loop *AddRecLoop = AddRec->getLoop();
2776 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2777 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2778 LIOps.push_back(Ops[i]);
2779 Ops.erase(Ops.begin()+i);
2780 --i; --e;
2781 }
2782
2783 // If we found some loop invariants, fold them into the recurrence.
2784 if (!LIOps.empty()) {
2785 // Compute nowrap flags for the addition of the loop-invariant ops and
2786 // the addrec. Temporarily push it as an operand for that purpose. These
2787 // flags are valid in the scope of the addrec only.
2788 LIOps.push_back(AddRec);
2789 SCEVFlags Flags = ComputeFlags(LIOps);
2790 LIOps.pop_back();
2791
2792 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2793 LIOps.push_back(AddRec->getStart());
2794
2795 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2796
2797 // It is not in general safe to propagate flags valid on an add within
2798 // the addrec scope to one outside it. We must prove that the inner
2799 // scope is guaranteed to execute if the outer one does to be able to
2800 // safely propagate. We know the program is undefined if poison is
2801 // produced on the inner scoped addrec. We also know that *for this use*
2802 // the outer scoped add can't overflow (because of the flags we just
2803 // computed for the inner scoped add) without the program being undefined.
2804 // Proving that entry to the outer scope neccesitates entry to the inner
2805 // scope, thus proves the program undefined if the flags would be violated
2806 // in the outer scope.
2807 SCEVFlags AddFlags = Flags;
2808 if (AddFlags != SCEV::FlagNone) {
2809 auto *DefI = getDefiningScopeBound(LIOps);
2810 auto *ReachI = &*AddRecLoop->getHeader()->begin();
2811 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2812 AddFlags = SCEV::FlagNone;
2813 }
2814 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2815
2816 // Build the new addrec. Propagate the NUW and NSW flags if both the
2817 // outer add and the inner addrec are guaranteed to have no overflow.
2818 // Always propagate NW.
2819 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2820 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2821
2822 // If all of the other operands were loop invariant, we are done.
2823 if (Ops.size() == 1) return NewRec;
2824
2825 // Otherwise, add the folded AddRec by the non-invariant parts.
2826 for (unsigned i = 0;; ++i)
2827 if (Ops[i] == AddRec) {
2828 Ops[i] = NewRec;
2829 break;
2830 }
2831 return getAddExpr(Ops, SCEV::FlagNone, Depth + 1);
2832 }
2833
2834 // Okay, if there weren't any loop invariants to be folded, check to see if
2835 // there are multiple AddRec's with the same loop induction variable being
2836 // added together. If so, we can fold them.
2837 for (unsigned OtherIdx = Idx+1;
2838 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2839 ++OtherIdx) {
2840 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2841 // so that the 1st found AddRecExpr is dominated by all others.
2842 assert(DT.dominates(
2843 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2844 AddRec->getLoop()->getHeader()) &&
2845 "AddRecExprs are not sorted in reverse dominance order?");
2846 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2847 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2848 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2849 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2850 ++OtherIdx) {
2851 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2852 if (OtherAddRec->getLoop() == AddRecLoop) {
2853 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2854 i != e; ++i) {
2855 if (i >= AddRecOps.size()) {
2856 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
2857 break;
2858 }
2859 AddRecOps[i] =
2860 getAddExpr(AddRecOps[i], OtherAddRec->getOperand(i),
2861 SCEV::FlagNone, Depth + 1);
2862 }
2863 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2864 }
2865 }
2866 // Step size has changed, so we cannot guarantee no self-wraparound.
2867 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagNone);
2868 return getAddExpr(Ops, SCEV::FlagNone, Depth + 1);
2869 }
2870 }
2871
2872 // Otherwise couldn't fold anything into this recurrence. Move onto the
2873 // next one.
2874 }
2875
2876 // Okay, it looks like we really DO need an add expr. Check to see if we
2877 // already have one, otherwise create a new one.
2878 assert((UseFlags == SCEV::FlagNone || equal(OrigOps, Ops)) &&
2879 "Tried to add SCEVUse flags after operands changed");
2880 return {getOrCreateAddExpr(Ops, ComputeFlags(Ops)), UseFlags};
2881}
2882
2883const SCEV *ScalarEvolution::getOrCreateAddExpr(ArrayRef<SCEVUse> Ops,
2884 SCEVFlags Flags) {
2887 for (SCEVUse Op : Ops)
2888 ID.AddPointer(Op.getOpaqueValue());
2890 SCEVAddExpr *S = static_cast<SCEVAddExpr *>(UniqueSCEVs.lookup(ID, Token));
2891 if (!S) {
2892 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
2894 S = new (SCEVAllocator)
2895 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2896 UniqueSCEVs.insert(S, Token);
2897 S->computeAndSetCanonical(*this);
2898 registerUser(S, Ops);
2899 }
2900 S->setNoWrapFlags(Flags);
2901 return S;
2902}
2903
2904const SCEV *ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<SCEVUse> Ops,
2905 const Loop *L,
2906 SCEVFlags Flags) {
2907 FoldingSetNodeID ID;
2908 ID.AddInteger(scAddRecExpr);
2909 for (SCEVUse Op : Ops)
2910 ID.AddPointer(Op.getOpaqueValue());
2911 ID.AddPointer(L);
2912 FoldingSetInsertToken Token;
2913 SCEVAddRecExpr *S =
2914 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.lookup(ID, Token));
2915 if (!S) {
2916 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
2918 S = new (SCEVAllocator)
2919 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2920 UniqueSCEVs.insert(S, Token);
2921 S->computeAndSetCanonical(*this);
2922 LoopUsers[L].push_back(S);
2923 registerUser(S, Ops);
2924 }
2925 setNoWrapFlags(S, Flags);
2926 return S;
2927}
2928
2929const SCEV *ScalarEvolution::getOrCreateMulExpr(ArrayRef<SCEVUse> Ops,
2930 SCEVFlags Flags) {
2931 FoldingSetNodeID ID;
2932 ID.AddInteger(scMulExpr);
2933 for (SCEVUse Op : Ops)
2934 ID.AddPointer(Op.getOpaqueValue());
2935 FoldingSetInsertToken Token;
2936 SCEVMulExpr *S = static_cast<SCEVMulExpr *>(UniqueSCEVs.lookup(ID, Token));
2937 if (!S) {
2938 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
2940 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2941 O, Ops.size());
2942 UniqueSCEVs.insert(S, Token);
2943 S->computeAndSetCanonical(*this);
2944 registerUser(S, Ops);
2945 }
2946 S->setNoWrapFlags(Flags);
2947 return S;
2948}
2949
2950const SCEV *ScalarEvolution::getOrCreateUDivExpr(SCEVUse LHS, SCEVUse RHS) {
2951 FoldingSetNodeID ID;
2952 ID.AddInteger(scUDivExpr);
2953 ID.AddPointer(LHS.getOpaqueValue());
2954 ID.AddPointer(RHS.getOpaqueValue());
2955 FoldingSetInsertToken Token;
2956 SCEV *S = UniqueSCEVs.lookup(ID, Token);
2957 if (!S) {
2958 S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), LHS, RHS);
2959 UniqueSCEVs.insert(S, Token);
2960 S->computeAndSetCanonical(*this);
2961 registerUser(S, {LHS, RHS});
2962 }
2963 return S;
2964}
2965
2966static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2967 uint64_t k = i*j;
2968 if (j > 1 && k / j != i) Overflow = true;
2969 return k;
2970}
2971
2972/// Compute the result of "n choose k", the binomial coefficient. If an
2973/// intermediate computation overflows, Overflow will be set and the return will
2974/// be garbage. Overflow is not cleared on absence of overflow.
2975static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2976 // We use the multiplicative formula:
2977 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2978 // At each iteration, we take the n-th term of the numeral and divide by the
2979 // (k-n)th term of the denominator. This division will always produce an
2980 // integral result, and helps reduce the chance of overflow in the
2981 // intermediate computations. However, we can still overflow even when the
2982 // final result would fit.
2983
2984 if (n == 0 || n == k) return 1;
2985 if (k > n) return 0;
2986
2987 if (k > n/2)
2988 k = n-k;
2989
2990 uint64_t r = 1;
2991 for (uint64_t i = 1; i <= k; ++i) {
2992 r = umul_ov(r, n-(i-1), Overflow);
2993 r /= i;
2994 }
2995 return r;
2996}
2997
2998/// Determine if any of the operands in this SCEV are a constant or if
2999/// any of the add or multiply expressions in this SCEV contain a constant.
3000static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3001 struct FindConstantInAddMulChain {
3002 bool FoundConstant = false;
3003
3004 bool follow(const SCEV *S) {
3005 FoundConstant |= isa<SCEVConstant>(S);
3006 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3007 }
3008
3009 bool isDone() const {
3010 return FoundConstant;
3011 }
3012 };
3013
3014 FindConstantInAddMulChain F;
3016 ST.visitAll(StartExpr);
3017 return F.FoundConstant;
3018}
3019
3020/// Get a canonical multiply expression, or something simpler if possible.
3022 SCEVFlagsPair Flags, unsigned Depth) {
3023 SCEVFlags ExprFlags = Flags.ExprFlags;
3024 SCEVFlags UseFlags = Flags.UseFlags;
3025 assert(ExprFlags == maskFlags(ExprFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3026 "only nuw or nsw allowed");
3027 assert(UseFlags == maskFlags(UseFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3028 "only nuw or nsw allowed");
3029 assert(!Ops.empty() && "Cannot get empty mul!");
3030 if (Ops.size() == 1) return Ops[0];
3031#ifndef NDEBUG
3032 Type *ETy = Ops[0]->getType();
3033 assert(!ETy->isPointerTy());
3034 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3035 assert(Ops[i]->getType() == ETy &&
3036 "SCEVMulExpr operand types don't match!");
3037#endif
3038
3040 Opts, *this, LI, DT, Ops,
3041 [](const APInt &C1, const APInt &C2) { return C1 * C2; },
3042 [](const APInt &C) { return C.isOne(); }, // identity
3043 [](const APInt &C) { return C.isZero(); }); // absorber
3044 if (Folded)
3045 return Folded;
3046
3047#ifndef NDEBUG
3048 // Keep track of operands after constant folding, for verification when adding
3049 // use-specific flags.
3050 const SmallVector<SCEVUse, 8> OrigOps(Ops.begin(), Ops.end());
3051#endif
3052
3053 // Delay expensive flag strengthening until necessary.
3054 auto ComputeFlags = [this, ExprFlags](const ArrayRef<SCEVUse> Ops) {
3055 return StrengthenNoWrapFlags(this, scMulExpr, Ops, ExprFlags);
3056 };
3057
3058 // Limit recursion calls depth.
3059 if (Depth > Opts.scalar_evolution_max_arith_depth ||
3060 hasHugeExpression(Opts, Ops))
3061 return {getOrCreateMulExpr(Ops, ComputeFlags(Ops)), UseFlags};
3062
3063 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3064 // Don't strengthen flags if we have no new information.
3065 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3066 if (Mul->getNoWrapFlags(ExprFlags) != ExprFlags)
3067 Mul->setNoWrapFlags(ComputeFlags(Ops));
3068 return {S, UseFlags};
3069 }
3070
3071 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3072 if (Ops.size() == 2) {
3073 // C1*(C2+V) -> C1*C2 + C1*V
3074 // If any of Add's ops are Adds or Muls with a constant, apply this
3075 // transformation as well.
3076 //
3077 // TODO: There are some cases where this transformation is not
3078 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
3079 // this transformation should be narrowed down.
3080 const SCEV *Op0, *Op1;
3081 if (match(Ops[1], m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))) &&
3083 const SCEV *LHS = getMulExpr(LHSC, Op0, SCEV::FlagNone, Depth + 1);
3084 const SCEV *RHS = getMulExpr(LHSC, Op1, SCEV::FlagNone, Depth + 1);
3085 return getAddExpr(LHS, RHS, SCEV::FlagNone, Depth + 1);
3086 }
3087
3088 if (Ops[0]->isAllOnesValue()) {
3089 // If we have a mul by -1 of an add, try distributing the -1 among the
3090 // add operands.
3091 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3093 bool AnyFolded = false;
3094 for (const SCEV *AddOp : Add->operands()) {
3095 const SCEV *Mul =
3096 getMulExpr(Ops[0], SCEVUse(AddOp), SCEV::FlagNone, Depth + 1);
3097 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3098 NewOps.push_back(Mul);
3099 }
3100 if (AnyFolded)
3101 return getAddExpr(NewOps, SCEV::FlagNone, Depth + 1);
3102 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3103 // Negation preserves a recurrence's no self-wrap property.
3105 for (const SCEV *AddRecOp : AddRec->operands())
3106 Operands.push_back(getMulExpr(Ops[0], SCEVUse(AddRecOp),
3107 SCEV::FlagNone, Depth + 1));
3108 // Let M be the minimum representable signed value. AddRec with nsw
3109 // multiplied by -1 can have signed overflow if and only if it takes a
3110 // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3111 // maximum signed value. In all other cases signed overflow is
3112 // impossible.
3113 auto FlagsMask = SCEV::FlagNW;
3114 if (AddRec->hasNoSignedWrap()) {
3115 auto MinInt =
3116 APInt::getSignedMinValue(getTypeSizeInBits(AddRec->getType()));
3117 if (getSignedRangeMin(AddRec) != MinInt)
3119 }
3120 return getAddRecExpr(Operands, AddRec->getLoop(),
3121 AddRec->getNoWrapFlags(FlagsMask));
3122 }
3123 }
3124
3125 // Try to push the constant operand into a ZExt: C * zext (A + B) ->
3126 // zext (C*A + C*B) if trunc (C) * (A + B) does not unsigned-wrap.
3127 const SCEVAddExpr *InnerAdd;
3128 if (match(Ops[1], m_scev_ZExt(m_scev_Add(InnerAdd)))) {
3129 const SCEV *NarrowC = getTruncateExpr(LHSC, InnerAdd->getType());
3130 if (isa<SCEVConstant>(InnerAdd->getOperand(0)) &&
3131 getZeroExtendExpr(NarrowC, Ops[1]->getType()) == LHSC &&
3132 hasFlags(StrengthenNoWrapFlags(this, scMulExpr, {NarrowC, InnerAdd},
3134 SCEV::FlagNUW)) {
3135 const SCEV *Res =
3136 getMulExpr(NarrowC, InnerAdd, SCEV::FlagNUW, Depth + 1);
3137 return getZeroExtendExpr(Res, Ops[1]->getType(), Depth + 1);
3138 };
3139 }
3140
3141 // Try to fold (C1 * D /u C2) -> C1/C2 * D, if C1 and C2 are powers-of-2,
3142 // D is a multiple of C2, and C1 is a multiple of C2. If C2 is a multiple
3143 // of C1, fold to (D /u (C2 /u C1)).
3144 const SCEV *D;
3145 APInt C1V = LHSC->getAPInt();
3146 // (C1 * D /u C2) == -1 * -C1 * D /u C2 when C1 != INT_MIN. Don't treat -1
3147 // as -1 * 1, as it won't enable additional folds.
3148 if (C1V.isNegative() && !C1V.isMinSignedValue() && !C1V.isAllOnes())
3149 C1V = C1V.abs();
3150 const SCEVConstant *C2;
3151 if (C1V.isPowerOf2() &&
3153 C2->getAPInt().isPowerOf2() &&
3154 C1V.logBase2() <= getMinTrailingZeros(D)) {
3155 const SCEV *NewMul = nullptr;
3156 if (C1V.uge(C2->getAPInt())) {
3157 NewMul = getMulExpr(getUDivExpr(getConstant(C1V), C2), D);
3158 } else if (C2->getAPInt().logBase2() <= getMinTrailingZeros(D)) {
3159 assert(C1V.ugt(1) && "C1 <= 1 should have been folded earlier");
3160 NewMul = getUDivExpr(D, getUDivExpr(C2, getConstant(C1V)));
3161 }
3162 if (NewMul)
3163 return C1V == LHSC->getAPInt() ? NewMul : getNegativeSCEV(NewMul);
3164 }
3165 }
3166 }
3167
3168 // Skip over the add expression until we get to a multiply.
3169 unsigned Idx = 0;
3170 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3171 ++Idx;
3172
3173 // If there are mul operands inline them all into this expression.
3174 if (Idx < Ops.size()) {
3175 bool DeletedMul = false;
3176 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3177 if (Ops.size() > Opts.scev_mulops_inline_threshold)
3178 break;
3179 // If we have an mul, expand the mul operands onto the end of the
3180 // operands list.
3181 Ops.erase(Ops.begin()+Idx);
3182 append_range(Ops, Mul->operands());
3183 DeletedMul = true;
3184 }
3185
3186 // If we deleted at least one mul, we added operands to the end of the
3187 // list, and they are not necessarily sorted. Recurse to resort and
3188 // resimplify any operands we just acquired.
3189 if (DeletedMul)
3190 return getMulExpr(Ops, SCEV::FlagNone, Depth + 1);
3191 }
3192
3193 // If there are any add recurrences in the operands list, see if any other
3194 // added values are loop invariant. If so, we can fold them into the
3195 // recurrence.
3196 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3197 ++Idx;
3198
3199 // Scan over all recurrences, trying to fold loop invariants into them.
3200 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3201 // Scan all of the other operands to this mul and add them to the vector
3202 // if they are loop invariant w.r.t. the recurrence.
3204 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3205 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3206 if (isAvailableAtLoopEntry(Ops[i], AddRec->getLoop())) {
3207 LIOps.push_back(Ops[i]);
3208 Ops.erase(Ops.begin()+i);
3209 --i; --e;
3210 }
3211
3212 // If we found some loop invariants, fold them into the recurrence.
3213 if (!LIOps.empty()) {
3214 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3216 NewOps.reserve(AddRec->getNumOperands());
3217 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagNone, Depth + 1);
3218
3219 // If both the mul and addrec are nuw, we can preserve nuw.
3220 // If both the mul and addrec are nsw, we can only preserve nsw if either
3221 // a) they are also nuw, or
3222 // b) all multiplications of addrec operands with scale are nsw.
3223 SCEVFlags Flags = AddRec->getNoWrapFlags(ComputeFlags({Scale, AddRec}));
3224
3225 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3226 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3227 SCEV::FlagNone, Depth + 1));
3228
3229 if (hasFlags(Flags, SCEV::FlagNSW) && !hasFlags(Flags, SCEV::FlagNUW)) {
3231 Instruction::Mul, getSignedRange(Scale),
3233 if (!NSWRegion.contains(getSignedRange(AddRec->getOperand(i))))
3234 Flags = clearFlags(Flags, SCEV::FlagNSW);
3235 }
3236 }
3237
3238 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(), Flags);
3239
3240 // If all of the other operands were loop invariant, we are done.
3241 if (Ops.size() == 1) return NewRec;
3242
3243 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3244 for (unsigned i = 0;; ++i)
3245 if (Ops[i] == AddRec) {
3246 Ops[i] = NewRec;
3247 break;
3248 }
3249 return getMulExpr(Ops, SCEV::FlagNone, Depth + 1);
3250 }
3251
3252 // Okay, if there weren't any loop invariants to be folded, check to see
3253 // if there are multiple AddRec's with the same loop induction variable
3254 // being multiplied together. If so, we can fold them.
3255
3256 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3257 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3258 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3259 // ]]],+,...up to x=2n}.
3260 // Note that the arguments to choose() are always integers with values
3261 // known at compile time, never SCEV objects.
3262 //
3263 // The implementation avoids pointless extra computations when the two
3264 // addrec's are of different length (mathematically, it's equivalent to
3265 // an infinite stream of zeros on the right).
3266 bool OpsModified = false;
3267 for (unsigned OtherIdx = Idx+1;
3268 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3269 ++OtherIdx) {
3270 const SCEVAddRecExpr *OtherAddRec =
3271 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3272 if (!OtherAddRec || OtherAddRec->getLoop() != AddRec->getLoop())
3273 continue;
3274
3275 // Limit max number of arguments to avoid creation of unreasonably big
3276 // SCEVAddRecs with very complex operands.
3277 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3278 Opts.scalar_evolution_max_add_rec_size ||
3279 hasHugeExpression(Opts, {AddRec, OtherAddRec}))
3280 continue;
3281
3282 bool Overflow = false;
3283 Type *Ty = AddRec->getType();
3284 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3285 SmallVector<SCEVUse, 7> AddRecOps;
3286 for (int x = 0, xe = AddRec->getNumOperands() +
3287 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3289 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3290 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3291 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3292 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3293 z < ze && !Overflow; ++z) {
3294 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3295 uint64_t Coeff;
3296 if (LargerThan64Bits)
3297 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3298 else
3299 Coeff = Coeff1*Coeff2;
3300 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3301 const SCEV *Term1 = AddRec->getOperand(y-z);
3302 const SCEV *Term2 = OtherAddRec->getOperand(z);
3303 SumOps.push_back(
3304 getMulExpr(CoeffTerm, Term1, Term2, SCEV::FlagNone, Depth + 1));
3305 }
3306 }
3307 if (SumOps.empty())
3308 SumOps.push_back(getZero(Ty));
3309 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagNone, Depth + 1));
3310 }
3311 if (!Overflow) {
3312 const SCEV *NewAddRec =
3313 getAddRecExpr(AddRecOps, AddRec->getLoop(), SCEV::FlagNone);
3314 if (Ops.size() == 2) return NewAddRec;
3315 Ops[Idx] = NewAddRec;
3316 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3317 OpsModified = true;
3318 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3319 if (!AddRec)
3320 break;
3321 }
3322 }
3323 if (OpsModified)
3324 return getMulExpr(Ops, SCEV::FlagNone, Depth + 1);
3325
3326 // Otherwise couldn't fold anything into this recurrence. Move onto the
3327 // next one.
3328 }
3329
3330 // Okay, it looks like we really DO need an mul expr. Check to see if we
3331 // already have one, otherwise create a new one.
3332 assert((UseFlags == SCEV::FlagNone || equal(OrigOps, Ops)) &&
3333 "Tried to add SCEVUse flags after operands changed");
3334 return {getOrCreateMulExpr(Ops, ComputeFlags(Ops)), UseFlags};
3335}
3336
3337/// Represents an unsigned remainder expression based on unsigned division.
3339 assert(getEffectiveSCEVType(LHS->getType()) ==
3340 getEffectiveSCEVType(RHS->getType()) &&
3341 "SCEVURemExpr operand types don't match!");
3342
3343 // Short-circuit easy cases
3344 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3345 // If constant is one, the result is trivial
3346 if (RHSC->getValue()->isOne())
3347 return getZero(LHS->getType()); // X urem 1 --> 0
3348
3349 // If constant is a power of two, fold into a zext(trunc(LHS)).
3350 if (RHSC->getAPInt().isPowerOf2()) {
3351 Type *FullTy = LHS->getType();
3352 Type *TruncTy =
3353 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3354 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3355 }
3356 }
3357
3358 // Fold LHS urem X and LHS urem (C * X) to 0 if X is a power of 2 and LHS is
3359 // a multiple of C * max(X).
3360 const APInt *C = nullptr;
3361 const SCEV *X = RHS;
3364 APInt MaxX = getUnsignedRangeMax(X);
3365 bool Overflow = false;
3366 APInt MaxRHS = C ? C->umul_ov(MaxX, Overflow) : MaxX;
3367 if (MaxX.isPowerOf2() && !Overflow &&
3368 getConstantMultiple(LHS).urem(MaxRHS) == 0)
3369 return getZero(LHS->getType());
3370 }
3371
3372 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3373 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3374 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3375 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3376}
3377
3378/// Get a canonical unsigned division expression, or something simpler if
3379/// possible.
3381 assert(!LHS->getType()->isPointerTy() &&
3382 "SCEVUDivExpr operand can't be pointer!");
3383 assert(LHS->getType() == RHS->getType() &&
3384 "SCEVUDivExpr operand types don't match!");
3385
3386 if (SCEV *S = findExistingSCEVInCache(scUDivExpr, {LHS, RHS}))
3387 return S;
3388
3389 // 0 udiv Y == 0
3390 if (match(LHS, m_scev_Zero()))
3391 return LHS;
3392
3393 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3394 if (RHSC->getValue()->isOne())
3395 return LHS; // X udiv 1 --> x
3396 // If the denominator is zero, the result of the udiv is undefined. Don't
3397 // try to analyze it, because the resolution chosen here may differ from
3398 // the resolution chosen in other parts of the compiler.
3399 if (!RHSC->getValue()->isZero()) {
3400 // Determine if the division can be folded into the operands of
3401 // its operands.
3402 // TODO: Generalize this to non-constants by using known-bits information.
3403 Type *Ty = LHS->getType();
3404 unsigned LZ = RHSC->getAPInt().countl_zero();
3405 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3406 // For non-power-of-two values, effectively round the value up to the
3407 // nearest power of two.
3408 if (!RHSC->getAPInt().isPowerOf2())
3409 ++MaxShiftAmt;
3410 IntegerType *ExtTy =
3411 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3412 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3413 if (const SCEVConstant *Step =
3414 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3415 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3416 const APInt &StepInt = Step->getAPInt();
3417 const APInt &DivInt = RHSC->getAPInt();
3418 if (!StepInt.urem(DivInt) &&
3419 getZeroExtendExpr(AR, ExtTy) ==
3420 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3421 getZeroExtendExpr(Step, ExtTy), AR->getLoop(),
3422 SCEV::FlagNone)) {
3424 for (const SCEV *Op : AR->operands())
3425 Operands.push_back(getUDivExpr(Op, RHS));
3426 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3427 }
3428 /// Get a canonical UDivExpr for a recurrence.
3429 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3430 const APInt *StartRem;
3431 if (!DivInt.urem(StepInt) && match(getURemExpr(AR->getStart(), Step),
3432 m_scev_APInt(StartRem))) {
3433 bool NoWrap =
3434 getZeroExtendExpr(AR, ExtTy) ==
3435 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3436 getZeroExtendExpr(Step, ExtTy), AR->getLoop(),
3438
3439 // With N <= C and both N, C as powers-of-2, the transformation
3440 // {X,+,N}/C => {(X - X%N),+,N}/C preserves division results even
3441 // if wrapping occurs, as the division results remain equivalent for
3442 // all offsets in [[(X - X%N), X).
3443 bool CanFoldWithWrap = StepInt.ule(DivInt) && // N <= C
3444 StepInt.isPowerOf2() && DivInt.isPowerOf2();
3445 // Only fold if the subtraction can be folded in the start
3446 // expression.
3447 const SCEV *NewStart =
3448 getMinusSCEV(AR->getStart(), getConstant(*StartRem));
3449 if (*StartRem != 0 && (NoWrap || CanFoldWithWrap) &&
3450 !isa<SCEVAddExpr>(NewStart)) {
3451 const SCEV *NewLHS =
3452 getAddRecExpr(NewStart, Step, AR->getLoop(),
3453 NoWrap ? SCEV::FlagNW : SCEV::FlagNone);
3454 if (LHS != NewLHS)
3455 return getUDivExpr(NewLHS, RHS);
3456 }
3457 }
3458 }
3459 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3460 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3461 if (M->hasNoUnsignedWrap()) {
3462 // Find an operand that's safely divisible.
3463 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3464 const SCEV *Op = M->getOperand(i);
3465 const SCEV *Div = getUDivExpr(Op, RHSC);
3466 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3467 SmallVector<SCEVUse, 4> Operands(M->operands());
3468 Operands[i] = Div;
3469 return getMulExpr(Operands);
3470 }
3471 }
3472
3473 // Even if it's not divisible, try to remove a common factor.
3474 if (const auto *LHSC = dyn_cast<SCEVConstant>(M->getOperand(0))) {
3475 APInt Factor = APIntOps::GreatestCommonDivisor(LHSC->getAPInt(),
3476 RHSC->getAPInt());
3477 if (!Factor.isIntN(1)) {
3478 SmallVector<SCEVUse, 2> NewOperands;
3479 NewOperands.push_back(getConstant(LHSC->getAPInt().udiv(Factor)));
3480 append_range(NewOperands, M->operands().drop_front());
3481 const SCEV *NewMul = getMulExpr(NewOperands);
3482 return getUDivExpr(NewMul,
3483 getConstant(RHSC->getAPInt().udiv(Factor)));
3484 }
3485 }
3486 }
3487 }
3488
3489 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3490 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3491 if (auto *DivisorConstant =
3492 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3493 bool Overflow = false;
3494 APInt NewRHS =
3495 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3496 if (Overflow) {
3497 return getConstant(RHSC->getType(), 0, false);
3498 }
3499 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3500 }
3501 }
3502
3503 // (A+B)/C --> (A/C + B/C) if the add does not unsigned wrap and A/C and
3504 // B/C can be folded.
3505 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3506 if (A->hasNoUnsignedWrap()) {
3508 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3509 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3510 if (isa<SCEVUDivExpr>(Op) ||
3511 getMulExpr(Op, RHS) != A->getOperand(i))
3512 break;
3513 Operands.push_back(Op);
3514 }
3515 if (Operands.size() == A->getNumOperands())
3516 return getAddExpr(Operands);
3517 }
3518 }
3519
3520 // ((N - M) + (M * A)) / N --> ((N - 1) + (M * A)) / N
3521 // This is an idiom for rounding A up to the next multiple of N, where A
3522 // is aready known to be a multiple of M. In this case, instcombine can
3523 // see that some low bits of the added constant are unused, so can clear
3524 // them, but we want to canonicalise to set the low bits. This makes the
3525 // pattern easier to match, without needing to check for known bits in
3526 // A*M.
3527 const APInt &N = RHSC->getAPInt();
3528 const APInt *NMinusM, *M;
3529 const SCEV *A;
3530 if (match(LHS, m_scev_Add(m_scev_APInt(NMinusM),
3531 m_scev_Mul(m_scev_APInt(M), m_SCEV(A))))) {
3532 if (N.isPowerOf2() && M->isPowerOf2() && M->ult(N) &&
3533 *NMinusM == N - *M) {
3534 return getUDivExpr(
3536 RHS);
3537 }
3538 }
3539
3540 // Fold if both operands are constant.
3541 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3542 return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3543 }
3544 }
3545
3546 // ((-C + (C smax %x)) /u %x) evaluates to zero, for any positive constant C.
3547 const APInt *NegC, *C;
3548 if (match(LHS,
3551 NegC->isNegative() && !NegC->isMinSignedValue() && *C == -*NegC)
3552 return getZero(LHS->getType());
3553
3554 // (%a * %b)<nuw> / %b -> %a
3555 const auto *Mul = dyn_cast<SCEVMulExpr>(LHS);
3556 if (Mul && Mul->hasNoUnsignedWrap()) {
3557 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3558 if (Mul->getOperand(i) == RHS) {
3560 append_range(Operands, Mul->operands().take_front(i));
3561 append_range(Operands, Mul->operands().drop_front(i + 1));
3562 return getMulExpr(Operands);
3563 }
3564 }
3565 }
3566
3567 // TODO: Generalize to handle any common factors.
3568 // udiv (mul nuw a, vscale), (mul nuw b, vscale) --> udiv a, b
3569 const SCEV *NewLHS, *NewRHS;
3570 if (match(LHS, m_scev_c_NUWMul(m_SCEV(NewLHS), m_SCEVVScale())) &&
3571 match(RHS, m_scev_c_NUWMul(m_SCEV(NewRHS), m_SCEVVScale())))
3572 return getUDivExpr(NewLHS, NewRHS);
3573
3574 return getOrCreateUDivExpr(LHS, RHS);
3575}
3576
3577/// Get a canonical unsigned division expression, or something simpler if
3578/// possible. There is no representation for an exact udiv in SCEV IR, but we
3579/// can attempt to optimize it prior to construction.
3581 // Currently there is no exact specific logic.
3582
3583 return getUDivExpr(LHS, RHS);
3584}
3585
3586/// Get an add recurrence expression for the specified loop. Simplify the
3587/// expression as much as possible.
3589 const Loop *L, SCEVFlagsPair Flags) {
3591 Operands.push_back(Start);
3592 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3593 if (StepChrec->getLoop() == L) {
3594 append_range(Operands, StepChrec->operands());
3595 // The use flags describe the two-operand recurrence, not the flattened
3596 // one built here, so drop them just like the expression's NUW/NSW.
3597 return getAddRecExpr(Operands, L,
3598 maskFlags(Flags.ExprFlags, SCEV::FlagNW));
3599 }
3600
3601 Operands.push_back(Step);
3602 return getAddRecExpr(Operands, L, Flags);
3603}
3604
3605/// Get an add recurrence expression for the specified loop. Simplify the
3606/// expression as much as possible.
3608 const Loop *L, SCEVFlagsPair NWFlags) {
3609 SCEVFlags ExprFlags = NWFlags.ExprFlags;
3610 SCEVFlags UseFlags = NWFlags.UseFlags;
3611 assert(!(UseFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
3612 "only nuw or nsw allowed");
3613 if (Operands.size() == 1) return Operands[0];
3614#ifndef NDEBUG
3616 for (const SCEV *Op : llvm::drop_begin(Operands)) {
3617 assert(getEffectiveSCEVType(Op->getType()) == ETy &&
3618 "SCEVAddRecExpr operand types don't match!");
3619 assert(!Op->getType()->isPointerTy() && "Step must be integer");
3620 }
3621 for (const SCEV *Op : Operands)
3623 "SCEVAddRecExpr operand is not available at loop entry!");
3624#endif
3625
3626 if (Operands.back()->isZero()) {
3627 Operands.pop_back();
3628 return getAddRecExpr(Operands, L, SCEV::FlagNone); // {X,+,0} --> X
3629 }
3630
3631 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3632 // use that information to infer NUW and NSW flags. However, computing a
3633 // BE count requires calling getAddRecExpr, so we may not yet have a
3634 // meaningful BE count at this point (and if we don't, we'd be stuck
3635 // with a SCEVCouldNotCompute as the cached BE count).
3636
3637 ExprFlags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, ExprFlags);
3638
3639 return {getOrCreateAddRecExpr(Operands, L, ExprFlags), UseFlags};
3640}
3641
3643 ArrayRef<SCEVUse> IndexExprs) {
3644 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3645 // getSCEV(Base)->getType() has the same address space as Base->getType()
3646 // because SCEV::getType() preserves the address space.
3647 GEPNoWrapFlags BaseNW = GEP->getNoWrapFlags();
3648 GEPNoWrapFlags OffsetNW = GEP->getNoWrapFlags();
3649 if (BaseNW != GEPNoWrapFlags::none()) {
3650 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3651 // but to do that, we have to ensure that said flag is valid in the entire
3652 // defined scope of the SCEV.
3653 // TODO: non-instructions have global scope. We might be able to prove
3654 // some global scope cases
3655 auto *GEPI = dyn_cast<Instruction>(GEP);
3656 if (!GEPI || !isSCEVExprNeverPoison(GEPI)) {
3657 BaseNW = OffsetNW = GEPNoWrapFlags::none();
3658 } else if (any_of(IndexExprs, [&](const SCEVUse &IndexExpr) {
3659 const SCEV *Idx = IndexExpr;
3660 return !isa<SCEVConstant>(Idx) &&
3661 !isGuaranteedToTransferExecutionTo(
3662 getDefiningScopeBound({Idx}), GEPI);
3663 })) {
3664 // The offset flags should not take into account the base pointer
3665 // defining scope, as the offset only depends on the indices. Thus,
3666 // derive the scope bound for the offset flags from each index operand
3667 // individually.
3668 OffsetNW = GEPNoWrapFlags::none();
3669 }
3670 }
3671
3672 return getGEPExpr(BaseExpr, IndexExprs, GEP->getSourceElementType(), BaseNW,
3673 OffsetNW);
3674}
3675
3677 ArrayRef<SCEVUse> IndexExprs,
3678 Type *SrcElementTy,
3679 GEPNoWrapFlags BaseNW,
3680 GEPNoWrapFlags OffsetNW) {
3681 SCEVFlags OffsetWrap = SCEV::FlagNone;
3682 if (OffsetNW.hasNoUnsignedSignedWrap())
3683 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNSW);
3684 if (OffsetNW.hasNoUnsignedWrap())
3685 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNUW);
3686
3687 Type *CurTy = BaseExpr->getType();
3688 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3689 bool FirstIter = true;
3691 for (SCEVUse IndexExpr : IndexExprs) {
3692 // Compute the (potentially symbolic) offset in bytes for this index.
3693 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3694 // For a struct, add the member offset.
3695 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3696 unsigned FieldNo = Index->getZExtValue();
3697 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3698 Offsets.push_back(FieldOffset);
3699
3700 // Update CurTy to the type of the field at Index.
3701 CurTy = STy->getTypeAtIndex(Index);
3702 } else {
3703 // Update CurTy to its element type.
3704 if (FirstIter) {
3705 assert(isa<PointerType>(CurTy) &&
3706 "The first index of a GEP indexes a pointer");
3707 CurTy = SrcElementTy;
3708 FirstIter = false;
3709 } else {
3710 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3711 }
3712 // For an array, add the element offset, explicitly scaled.
3713 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3714 // Getelementptr indices are signed.
3715 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3716
3717 // Multiply the index by the element size to compute the element offset.
3718 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3719 Offsets.push_back(LocalOffset);
3720 }
3721 }
3722
3723 // Handle degenerate case of GEP without offsets.
3724 if (Offsets.empty())
3725 return BaseExpr;
3726
3727 // Add the offsets successively, as the flags only hold for that order.
3728 const SCEV *Offset = Offsets[0];
3729 for (SCEVUse O : drop_begin(Offsets))
3730 Offset = getAddExpr(Offset, O, OffsetWrap);
3731 // Add the base address and the offset. We cannot use the nsw flag, as the
3732 // base address is unsigned. However, if we know that the offset is
3733 // non-negative, we can use nuw.
3734 bool NUW = BaseNW.hasNoUnsignedWrap() ||
3736 SCEVFlags BaseWrap = NUW ? SCEV::FlagNUW : SCEV::FlagNone;
3737 const SCEV *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3738 assert(BaseExpr->getType() == GEPExpr->getType() &&
3739 "GEP should not change type mid-flight.");
3740 return GEPExpr;
3741}
3742
3743SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3745 const Loop *L) {
3746 assert((SCEVType != scAddRecExpr || L) &&
3747 "L must be passed to find existing AddRecs");
3749 ID.AddInteger(SCEVType);
3750 for (SCEVUse Op : Ops)
3751 ID.AddPointer(Op.getOpaqueValue());
3752 if (L)
3753 ID.AddPointer(L);
3755 return UniqueSCEVs.lookup(ID, Token);
3756}
3757
3758const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3759 SCEVFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagNone;
3760 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3761}
3762
3765 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3766 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3767 if (Ops.size() == 1) return Ops[0];
3768#ifndef NDEBUG
3769 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3770 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3771 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3772 "Operand types don't match!");
3773 assert(Ops[0]->getType()->isPointerTy() ==
3774 Ops[i]->getType()->isPointerTy() &&
3775 "min/max should be consistently pointerish");
3776 }
3777#endif
3778
3779 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3780 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3781
3783 Opts, *this, LI, DT, Ops,
3784 [&](const APInt &C1, const APInt &C2) {
3785 switch (Kind) {
3786 case scSMaxExpr:
3787 return APIntOps::smax(C1, C2);
3788 case scSMinExpr:
3789 return APIntOps::smin(C1, C2);
3790 case scUMaxExpr:
3791 return APIntOps::umax(C1, C2);
3792 case scUMinExpr:
3793 return APIntOps::umin(C1, C2);
3794 default:
3795 llvm_unreachable("Unknown SCEV min/max opcode");
3796 }
3797 },
3798 [&](const APInt &C) {
3799 // identity
3800 if (IsMax)
3801 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3802 else
3803 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3804 },
3805 [&](const APInt &C) {
3806 // absorber
3807 if (IsMax)
3808 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3809 else
3810 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3811 });
3812 if (Folded)
3813 return Folded;
3814
3815 // Check if we have created the same expression before.
3816 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3817 return S;
3818 }
3819
3820 // Find the first operation of the same kind
3821 unsigned Idx = 0;
3822 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3823 ++Idx;
3824
3825 // Check to see if one of the operands is of the same kind. If so, expand its
3826 // operands onto our operand list, and recurse to simplify.
3827 if (Idx < Ops.size()) {
3828 bool DeletedAny = false;
3829 while (Ops[Idx]->getSCEVType() == Kind) {
3830 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3831 Ops.erase(Ops.begin()+Idx);
3832 append_range(Ops, SMME->operands());
3833 DeletedAny = true;
3834 }
3835
3836 if (DeletedAny)
3837 return getMinMaxExpr(Kind, Ops);
3838 }
3839
3840 // Okay, check to see if the same value occurs in the operand list twice. If
3841 // so, delete one. Since we sorted the list, these values are required to
3842 // be adjacent.
3847 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3848 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3849 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3850 if (SCEVUse Common = SCEVUse::getCommon(Ops[i], Ops[i + 1]))
3851 Ops[i] = Ops[i + 1] = Common;
3852 if (Ops[i] == Ops[i + 1] ||
3853 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3854 // X op Y op Y --> X op Y
3855 // X op Y --> X, if we know X, Y are ordered appropriately
3856 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3857 --i;
3858 --e;
3859 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3860 Ops[i + 1])) {
3861 // X op Y --> Y, if we know X, Y are ordered appropriately
3862 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3863 --i;
3864 --e;
3865 }
3866 }
3867
3868 if (Ops.size() == 1) return Ops[0];
3869
3870 assert(!Ops.empty() && "Reduced smax down to nothing!");
3871
3872 // Okay, it looks like we really DO need an expr. Check to see if we
3873 // already have one, otherwise create a new one.
3875 ID.AddInteger(Kind);
3876 for (SCEVUse Op : Ops)
3877 ID.AddPointer(Op.getOpaqueValue());
3879 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
3880 if (ExistingSCEV)
3881 return ExistingSCEV;
3882 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3884 SCEV *S = new (SCEVAllocator)
3885 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3886
3887 UniqueSCEVs.insert(S, Token);
3888 S->computeAndSetCanonical(*this);
3889 registerUser(S, Ops);
3890 return S;
3891}
3892
3893namespace {
3894
3895class SCEVSequentialMinMaxDeduplicatingVisitor final
3896 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
3897 std::optional<const SCEV *>> {
3898 using RetVal = std::optional<const SCEV *>;
3899
3900 ScalarEvolution &SE;
3901 const SCEVTypes RootKind; // Must be a sequential min/max expression.
3902 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
3904
3905 bool canRecurseInto(SCEVTypes Kind) const {
3906 // We can only recurse into the SCEV expression of the same effective type
3907 // as the type of our root SCEV expression.
3908 return RootKind == Kind || NonSequentialRootKind == Kind;
3909 };
3910
3911 RetVal visit(const SCEV *S) {
3912 // Has the whole operand been seen already?
3913 if (!SeenOps.insert(S).second)
3914 return std::nullopt;
3916 SCEVTypes Kind = S->getSCEVType();
3917
3918 if (!canRecurseInto(Kind))
3919 return S;
3920
3921 auto *NAry = cast<SCEVNAryExpr>(S);
3922 SmallVector<SCEVUse> NewOps;
3923 bool Changed = visit(Kind, NAry->operands(), NewOps);
3924
3925 if (!Changed)
3926 return S;
3927 if (NewOps.empty())
3928 return std::nullopt;
3929
3931 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
3932 : SE.getMinMaxExpr(Kind, NewOps);
3933 }
3934 return S;
3935 }
3936
3937public:
3938 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
3939 SCEVTypes RootKind)
3940 : SE(SE), RootKind(RootKind),
3941 NonSequentialRootKind(
3942 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
3943 RootKind)) {}
3944
3945 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<SCEVUse> OrigOps,
3946 SmallVectorImpl<SCEVUse> &NewOps) {
3947 bool Changed = false;
3949 Ops.reserve(OrigOps.size());
3950
3951 for (const SCEV *Op : OrigOps) {
3952 RetVal NewOp = visit(Op);
3953 if (NewOp != Op)
3954 Changed = true;
3955 if (NewOp)
3956 Ops.emplace_back(*NewOp);
3957 }
3958
3959 if (Changed)
3960 NewOps = std::move(Ops);
3961 return Changed;
3962 }
3963};
3964
3965} // namespace
3966
3968 switch (Kind) {
3969 case scConstant:
3970 case scVScale:
3971 case scTruncate:
3972 case scZeroExtend:
3973 case scSignExtend:
3974 case scPtrToAddr:
3975 case scAddExpr:
3976 case scMulExpr:
3977 case scUDivExpr:
3978 case scAddRecExpr:
3979 case scUMaxExpr:
3980 case scSMaxExpr:
3981 case scUMinExpr:
3982 case scSMinExpr:
3983 case scUnknown:
3984 // If any operand is poison, the whole expression is poison.
3985 return true;
3987 // FIXME: if the *first* operand is poison, the whole expression is poison.
3988 return false; // Pessimistically, say that it does not propagate poison.
3989 case scCouldNotCompute:
3990 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
3991 }
3992 llvm_unreachable("Unknown SCEV kind!");
3993}
3994
3995namespace {
3996// The only way poison may be introduced in a SCEV expression is from a
3997// poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
3998// not SCEVConstant). Notably, SCEVFlags on SCEV nodes can *not*
3999// introduce poison -- they encode guaranteed, non-speculated knowledge. The
4000// flags of a SCEVUse can, as they only hold where it is used.
4001//
4002// Additionally, all SCEV nodes propagate poison from inputs to outputs,
4003// with the notable exception of umin_seq, where only poison from the first
4004// operand is (unconditionally) propagated.
4005struct SCEVPoisonCollector {
4006 bool LookThroughMaybePoisonBlocking;
4007 SmallPtrSet<const SCEVUnknown *, 4> MaybePoison;
4008 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4009 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4010
4011 bool follow(const SCEV *S) {
4012 if (!LookThroughMaybePoisonBlocking &&
4014 return false;
4015
4016 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4017 if (!isGuaranteedNotToBePoison(SU->getValue()))
4018 MaybePoison.insert(SU);
4019 }
4020 return true;
4021 }
4022 bool isDone() const { return false; }
4023};
4024} // namespace
4025
4026/// Return true if S is poison given that AssumedPoison is already poison.
4027static bool impliesPoison(SCEVUse AssumedPoison, const SCEV *S) {
4028 // AssumedPoison may be poison due to its use flags alone.
4029 if (!AssumedPoison.isCanonical())
4030 return false;
4031
4032 // First collect all SCEVs that might result in AssumedPoison to be poison.
4033 // We need to look through potentially poison-blocking operations here,
4034 // because we want to find all SCEVs that *might* result in poison, not only
4035 // those that are *required* to.
4036 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4037 visitAll(AssumedPoison, PC1);
4038
4039 // AssumedPoison is never poison. As the assumption is false, the implication
4040 // is true. Don't bother walking the other SCEV in this case.
4041 if (PC1.MaybePoison.empty())
4042 return true;
4043
4044 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4045 // as well. We cannot look through potentially poison-blocking operations
4046 // here, as their arguments only *may* make the result poison.
4047 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4048 visitAll(S, PC2);
4049
4050 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4051 // it will also make S poison by being part of PC2.MaybePoison.
4052 return llvm::set_is_subset(PC1.MaybePoison, PC2.MaybePoison);
4053}
4054
4056 SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4057 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4058 visitAll(S, PC);
4059 for (const SCEVUnknown *SU : PC.MaybePoison)
4060 Result.insert(SU->getValue());
4061}
4062
4064 const SCEV *S, Instruction *I,
4065 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
4066 // If the instruction cannot be poison, it's always safe to reuse.
4068 return true;
4069
4070 // Otherwise, it is possible that I is more poisonous that S. Collect the
4071 // poison-contributors of S, and then check whether I has any additional
4072 // poison-contributors. Poison that is contributed through poison-generating
4073 // flags is handled by dropping those flags instead.
4075 getPoisonGeneratingValues(PoisonVals, S);
4076
4077 SmallVector<Value *> Worklist;
4079 Worklist.push_back(I);
4080 unsigned NumVisitedInsts = 0;
4081 const unsigned InstLimit = std::max<unsigned>(16, S->getExpressionSize());
4082 while (!Worklist.empty()) {
4083 Value *V = Worklist.pop_back_val();
4084 if (!Visited.insert(V).second)
4085 continue;
4086
4087 // Either the value can't be poison, or the S would also be poison if it
4088 // is.
4089 if (PoisonVals.contains(V) || ::isGuaranteedNotToBePoison(V))
4090 continue;
4091
4092 // Avoid walking large instruction graphs.
4093 if (++NumVisitedInsts > InstLimit)
4094 return false;
4095
4096 auto *I = dyn_cast<Instruction>(V);
4097 if (!I)
4098 return false;
4099
4100 // Disjoint or instructions are interpreted as adds by SCEV. However, we
4101 // can't replace an arbitrary add with disjoint or, even if we drop the
4102 // flag. We would need to convert the or into an add.
4103 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
4104 if (PDI->isDisjoint())
4105 return false;
4106
4107 // FIXME: Ignore vscale, even though it technically could be poison. Do this
4108 // because SCEV currently assumes it can't be poison. Remove this special
4109 // case once we proper model when vscale can be poison.
4110 if (auto *II = dyn_cast<IntrinsicInst>(I);
4111 II && II->getIntrinsicID() == Intrinsic::vscale)
4112 continue;
4113
4114 if (canCreatePoison(cast<Operator>(I), /*ConsiderFlagsAndMetadata*/ false))
4115 return false;
4116
4117 // If the instruction can't create poison, we can recurse to its operands.
4118 if (I->hasPoisonGeneratingAnnotations())
4119 DropPoisonGeneratingInsts.push_back(I);
4120
4121 llvm::append_range(Worklist, I->operands());
4122 }
4123 return true;
4124}
4125
4126const SCEV *
4129 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4130 "Not a SCEVSequentialMinMaxExpr!");
4131 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4132 if (Ops.size() == 1)
4133 return Ops[0];
4134#ifndef NDEBUG
4135 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4136 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4137 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4138 "Operand types don't match!");
4139 assert(Ops[0]->getType()->isPointerTy() ==
4140 Ops[i]->getType()->isPointerTy() &&
4141 "min/max should be consistently pointerish");
4142 }
4143#endif
4144
4145 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4146 // so we can *NOT* do any kind of sorting of the expressions!
4147
4148 // Check if we have created the same expression before.
4149 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4150 return S;
4151
4152 // FIXME: there are *some* simplifications that we can do here.
4153
4154 // Keep only the first instance of an operand.
4155 {
4156 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4157 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4158 if (Changed)
4159 return getSequentialMinMaxExpr(Kind, Ops);
4160 }
4161
4162 // Check to see if one of the operands is of the same kind. If so, expand its
4163 // operands onto our operand list, and recurse to simplify.
4164 {
4165 unsigned Idx = 0;
4166 bool DeletedAny = false;
4167 while (Idx < Ops.size()) {
4168 if (Ops[Idx]->getSCEVType() != Kind) {
4169 ++Idx;
4170 continue;
4171 }
4172 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4173 Ops.erase(Ops.begin() + Idx);
4174 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4175 SMME->operands().end());
4176 DeletedAny = true;
4177 }
4178
4179 if (DeletedAny)
4180 return getSequentialMinMaxExpr(Kind, Ops);
4181 }
4182
4183 const SCEV *SaturationPoint;
4185 switch (Kind) {
4187 SaturationPoint = getZero(Ops[0]->getType());
4188 Pred = ICmpInst::ICMP_ULE;
4189 break;
4190 default:
4191 llvm_unreachable("Not a sequential min/max type.");
4192 }
4193
4194 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4196 continue;
4197 // We can replace %x umin_seq %y with %x umin %y if either:
4198 // * %y being poison implies %x is also poison.
4199 // * %x cannot be the saturating value (e.g. zero for umin).
4200 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4201 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4202 SaturationPoint)) {
4203 SmallVector<SCEVUse, 2> SeqOps = {Ops[i - 1], Ops[i]};
4204 Ops[i - 1] = getMinMaxExpr(
4206 SeqOps);
4207 Ops.erase(Ops.begin() + i);
4208 return getSequentialMinMaxExpr(Kind, Ops);
4209 }
4210 // Fold %x umin_seq %y to %x if %x ule %y.
4211 // TODO: We might be able to prove the predicate for a later operand.
4212 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4213 Ops.erase(Ops.begin() + i);
4214 return getSequentialMinMaxExpr(Kind, Ops);
4215 }
4216 }
4217
4218 // Okay, it looks like we really DO need an expr. Check to see if we
4219 // already have one, otherwise create a new one.
4221 ID.AddInteger(Kind);
4222 for (SCEVUse Op : Ops)
4223 ID.AddPointer(Op.getOpaqueValue());
4225 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
4226 if (ExistingSCEV)
4227 return ExistingSCEV;
4228
4229 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4231 SCEV *S = new (SCEVAllocator)
4232 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4233
4234 UniqueSCEVs.insert(S, Token);
4235 S->computeAndSetCanonical(*this);
4236 registerUser(S, Ops);
4237 return S;
4238}
4239
4244
4248
4253
4257
4262
4266
4268 bool Sequential) {
4269 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4270 return getUMinExpr(Ops, Sequential);
4271}
4272
4278
4279const SCEV *
4281 const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4282 if (Size.isScalable())
4283 Res = getMulExpr(Res, getVScale(IntTy));
4284 return Res;
4285}
4286
4288 return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4289}
4290
4292 return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4293}
4294
4296 StructType *STy,
4297 unsigned FieldNo) {
4298 // We can bypass creating a target-independent constant expression and then
4299 // folding it back into a ConstantInt. This is just a compile-time
4300 // optimization.
4301 const StructLayout *SL = getDataLayout().getStructLayout(STy);
4302 assert(!SL->getSizeInBits().isScalable() &&
4303 "Cannot get offset for structure containing scalable vector types");
4304 return getConstant(IntTy, SL->getElementOffset(FieldNo));
4305}
4306
4308 // Don't attempt to do anything other than create a SCEVUnknown object
4309 // here. createSCEV only calls getUnknown after checking for all other
4310 // interesting possibilities, and any other code that calls getUnknown
4311 // is doing so in order to hide a value from SCEV canonicalization.
4312
4315 ID.AddPointer(V);
4317 if (SCEV *S = UniqueSCEVs.lookup(ID, Token)) {
4318 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4319 "Stale SCEVUnknown in uniquing map!");
4320 return S;
4321 }
4322 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4323 FirstUnknown, NextUnknownOrderID++);
4324 FirstUnknown = cast<SCEVUnknown>(S);
4325 UniqueSCEVs.insert(S, Token);
4326 S->computeAndSetCanonical(*this);
4327 return S;
4328}
4329
4330//===----------------------------------------------------------------------===//
4331// Basic SCEV Analysis and PHI Idiom Recognition Code
4332//
4333
4334/// Test if values of the given type are analyzable within the SCEV
4335/// framework. This primarily includes integer types, and it can optionally
4336/// include pointer types if the ScalarEvolution class has access to
4337/// target-specific information.
4339 // Integers and pointers are always SCEVable.
4340 return Ty->isIntOrPtrTy();
4341}
4342
4343/// Return the size in bits of the specified type, for which isSCEVable must
4344/// return true.
4346 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4347 if (Ty->isPointerTy())
4349 return getDataLayout().getTypeSizeInBits(Ty);
4350}
4351
4352/// Return a type with the same bitwidth as the given type and which represents
4353/// how SCEV will treat the given type, for which isSCEVable must return
4354/// true. For pointer types, this is the pointer index sized integer type.
4356 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4357
4358 if (Ty->isIntegerTy())
4359 return Ty;
4360
4361 // The only other support type is pointer.
4362 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4363 return getDataLayout().getIndexType(Ty);
4364}
4365
4367 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4368}
4369
4371 const SCEV *B) {
4372 /// For a valid use point to exist, the defining scope of one operand
4373 /// must dominate the other.
4374 bool PreciseA, PreciseB;
4375 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4376 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4377 if (!PreciseA || !PreciseB)
4378 // Can't tell.
4379 return false;
4380 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4381 DT.dominates(ScopeB, ScopeA);
4382}
4383
4385 return CouldNotCompute.get();
4386}
4387
4388bool ScalarEvolution::checkValidity(const SCEV *S) const {
4389 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4390 auto *SU = dyn_cast<SCEVUnknown>(S);
4391 return SU && SU->getValue() == nullptr;
4392 });
4393
4394 return !ContainsNulls;
4395}
4396
4398 auto [I, Inserted] = HasRecMap.try_emplace(S);
4399 if (Inserted)
4400 I->second = SCEVExprContains(
4401 S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4402 return I->second;
4403}
4404
4405/// Return the ValueOffsetPair set for \p S. \p S can be represented
4406/// by the value and offset from any ValueOffsetPair in the set.
4407ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4408 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4409 if (SI == ExprValueMap.end())
4410 return {};
4411 return SI->second;
4412}
4413
4414/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4415/// cannot be used separately. eraseValueFromMap should be used to remove
4416/// V from ValueExprMap and ExprValueMap at the same time.
4417void ScalarEvolution::eraseValueFromMap(Value *V) {
4418 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4419 if (I != ValueExprMap.end()) {
4420 auto EVIt = ExprValueMap.find(I->second);
4421 assert(is_contained(EVIt->second, V) && "Value not in ExprValueMap?");
4422 llvm::erase(EVIt->second, V);
4423 ValueExprMap.erase(I);
4424 }
4425}
4426
4427void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4428 // A recursive query may have already computed the SCEV. It should be
4429 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4430 // inferred nowrap flags.
4431 if (ValueExprMap.insert({SCEVCallbackVH(V, this), S}).second)
4432 ExprValueMap[S].push_back(V);
4433}
4434
4435/// Return an existing SCEV if it exists, otherwise analyze the expression and
4436/// create a new one.
4438 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4439
4440 if (const SCEV *S = getExistingSCEV(V))
4441 return S;
4442 return createSCEVIter(V);
4443}
4444
4446 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4447
4448 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4449 if (I != ValueExprMap.end()) {
4450 const SCEV *S = I->second;
4451 assert(checkValidity(S) &&
4452 "existing SCEV has not been properly invalidated");
4453 return S;
4454 }
4455 return nullptr;
4456}
4457
4458/// Return a SCEV corresponding to -V = -1*V
4460 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4461 return getConstant(
4462 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4463
4464 Type *Ty = V->getType();
4465 Ty = getEffectiveSCEVType(Ty);
4466 return getMulExpr(V, getMinusOne(Ty), Flags);
4467}
4468
4469/// If Expr computes ~A, return A else return nullptr
4470static const SCEV *MatchNotExpr(const SCEV *Expr) {
4471 const SCEV *MulOp;
4472 if (match(Expr, m_scev_Add(m_scev_AllOnes(),
4473 m_scev_Mul(m_scev_AllOnes(), m_SCEV(MulOp)))))
4474 return MulOp;
4475 return nullptr;
4476}
4477
4478/// Return a SCEV corresponding to ~V = -1-V
4480 assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4481
4482 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4483 return getConstant(
4484 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4485
4486 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4487 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4488 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4489 SmallVector<SCEVUse, 2> MatchedOperands;
4490 for (const SCEV *Operand : MME->operands()) {
4491 const SCEV *Matched = MatchNotExpr(Operand);
4492 if (!Matched)
4493 return (const SCEV *)nullptr;
4494 MatchedOperands.push_back(Matched);
4495 }
4496 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4497 MatchedOperands);
4498 };
4499 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4500 return Replaced;
4501 }
4502
4503 Type *Ty = V->getType();
4504 Ty = getEffectiveSCEVType(Ty);
4505 return getMinusSCEV(getMinusOne(Ty), V);
4506}
4507
4509 assert(P->getType()->isPointerTy());
4510
4511 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4512 // The base of an AddRec is the first operand.
4513 SmallVector<SCEVUse> Ops{AddRec->operands()};
4514 Ops[0] = removePointerBase(Ops[0]);
4515 // Don't try to transfer nowrap flags for now. We could in some cases
4516 // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4517 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagNone);
4518 }
4519 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4520 // The base of an Add is the pointer operand.
4521 SmallVector<SCEVUse> Ops{Add->operands()};
4522 SCEVUse *PtrOp = nullptr;
4523 for (SCEVUse &AddOp : Ops) {
4524 if (AddOp->getType()->isPointerTy()) {
4525 assert(!PtrOp && "Cannot have multiple pointer ops");
4526 PtrOp = &AddOp;
4527 }
4528 }
4529 *PtrOp = removePointerBase(*PtrOp);
4530 // Don't try to transfer nowrap flags for now. We could in some cases
4531 // (for example, if the pointer operand of the Add is a SCEVUnknown).
4532 return getAddExpr(Ops);
4533 }
4534 // Any other expression must be a pointer base.
4535 return getZero(P->getType());
4536}
4537
4539 SCEVFlags Flags, unsigned Depth) {
4540 // Fast path: X - X --> 0.
4541 if (SCEVUse::getCommon(LHS, RHS))
4542 return getZero(LHS->getType());
4543
4544 // If we subtract two pointers with different pointer bases, bail.
4545 // Eventually, we're going to add an assertion to getMulExpr that we
4546 // can't multiply by a pointer.
4547 if (RHS->getType()->isPointerTy()) {
4548 if (!LHS->getType()->isPointerTy() ||
4549 getPointerBase(LHS) != getPointerBase(RHS))
4550 return getCouldNotCompute();
4551 LHS = removePointerBase(LHS);
4552 RHS = removePointerBase(RHS);
4553 }
4554
4555 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4556 // makes it so that we cannot make much use of NUW.
4557 auto AddFlags = SCEV::FlagNone;
4558 const bool RHSIsNotMinSigned =
4560 if (hasFlags(Flags, SCEV::FlagNSW)) {
4561 // Let M be the minimum representable signed value. Then (-1)*RHS
4562 // signed-wraps if and only if RHS is M. That can happen even for
4563 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4564 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4565 // (-1)*RHS, we need to prove that RHS != M.
4566 //
4567 // If LHS is non-negative and we know that LHS - RHS does not
4568 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4569 // either by proving that RHS > M or that LHS >= 0.
4570 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4571 AddFlags = SCEV::FlagNSW;
4572 }
4573 }
4574
4575 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4576 // RHS is NSW and LHS >= 0.
4577 //
4578 // The difficulty here is that the NSW flag may have been proven
4579 // relative to a loop that is to be found in a recurrence in LHS and
4580 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4581 // larger scope than intended.
4582 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagNone;
4583
4584 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4585}
4586
4588 unsigned Depth) {
4589 Type *SrcTy = V->getType();
4590 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4591 "Cannot truncate or zero extend with non-integer arguments!");
4592 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4593 return V; // No conversion
4594 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4595 return getTruncateExpr(V, Ty, Depth);
4596 return getZeroExtendExpr(V, Ty, Depth);
4597}
4598
4600 unsigned Depth) {
4601 Type *SrcTy = V->getType();
4602 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4603 "Cannot truncate or zero extend with non-integer arguments!");
4604 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4605 return V; // No conversion
4606 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4607 return getTruncateExpr(V, Ty, Depth);
4608 return getSignExtendExpr(V, Ty, Depth);
4609}
4610
4612 Type *SrcTy = V->getType();
4613 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4614 "Cannot noop or zero extend with non-integer arguments!");
4616 "getNoopOrZeroExtend cannot truncate!");
4617 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4618 return V; // No conversion
4619 return getZeroExtendExpr(V, Ty);
4620}
4621
4623 Type *SrcTy = V->getType();
4624 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4625 "Cannot noop or sign extend with non-integer arguments!");
4627 "getNoopOrSignExtend cannot truncate!");
4628 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4629 return V; // No conversion
4630 return getSignExtendExpr(V, Ty);
4631}
4632
4634 Type *SrcTy = V->getType();
4635 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4636 "Cannot noop or any extend with non-integer arguments!");
4638 "getNoopOrAnyExtend cannot truncate!");
4639 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4640 return V; // No conversion
4641 return getAnyExtendExpr(V, Ty);
4642}
4643
4645 Type *SrcTy = V->getType();
4646 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4647 "Cannot truncate or noop with non-integer arguments!");
4649 "getTruncateOrNoop cannot extend!");
4650 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4651 return V; // No conversion
4652 return getTruncateExpr(V, Ty);
4653}
4654
4656 const SCEV *RHS) {
4657 const SCEV *PromotedLHS = LHS;
4658 const SCEV *PromotedRHS = RHS;
4659
4660 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4661 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4662 else
4663 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4664
4665 return getUMaxExpr(PromotedLHS, PromotedRHS);
4666}
4667
4669 const SCEV *RHS,
4670 bool Sequential) {
4671 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4672 return getUMinFromMismatchedTypes(Ops, Sequential);
4673}
4674
4675const SCEV *
4677 bool Sequential) {
4678 assert(!Ops.empty() && "At least one operand must be!");
4679 // Trivial case.
4680 if (Ops.size() == 1)
4681 return Ops[0];
4682
4683 // Find the max type first.
4684 Type *MaxType = nullptr;
4685 for (SCEVUse S : Ops)
4686 if (MaxType)
4687 MaxType = getWiderType(MaxType, S->getType());
4688 else
4689 MaxType = S->getType();
4690 assert(MaxType && "Failed to find maximum type!");
4691
4692 // Extend all ops to max type.
4693 SmallVector<SCEVUse, 2> PromotedOps;
4694 for (SCEVUse S : Ops)
4695 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4696
4697 // Generate umin.
4698 return getUMinExpr(PromotedOps, Sequential);
4699}
4700
4702 // A pointer operand may evaluate to a nonpointer expression, such as null.
4703 if (!V->getType()->isPointerTy())
4704 return V;
4705
4706 while (true) {
4707 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4708 V = AddRec->getStart();
4709 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4710 const SCEV *PtrOp = nullptr;
4711 for (const SCEV *AddOp : Add->operands()) {
4712 if (AddOp->getType()->isPointerTy()) {
4713 assert(!PtrOp && "Cannot have multiple pointer ops");
4714 PtrOp = AddOp;
4715 }
4716 }
4717 assert(PtrOp && "Must have pointer op");
4718 V = PtrOp;
4719 } else // Not something we can look further into.
4720 return V;
4721 }
4722}
4723
4724/// Push users of the given Instruction onto the given Worklist.
4728 // Push the def-use children onto the Worklist stack.
4729 for (Instruction *UserInsn : I->users()) {
4730 if (Visited.insert(UserInsn).second)
4731 Worklist.push_back(UserInsn);
4732 }
4733}
4734
4735namespace {
4736
4737/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4738/// expression in case its Loop is L. If it is not L then
4739/// if IgnoreOtherLoops is true then use AddRec itself
4740/// otherwise rewrite cannot be done.
4741/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4742class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4743public:
4744 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4745 bool IgnoreOtherLoops = true) {
4746 SCEVInitRewriter Rewriter(L, SE);
4747 const SCEV *Result = Rewriter.visit(S);
4748 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4749 return SE.getCouldNotCompute();
4750 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4751 ? SE.getCouldNotCompute()
4752 : Result;
4753 }
4754
4755 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4756 if (!SE.isLoopInvariant(Expr, L))
4757 SeenLoopVariantSCEVUnknown = true;
4758 return Expr;
4759 }
4760
4761 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4762 // Only re-write AddRecExprs for this loop.
4763 if (Expr->getLoop() == L)
4764 return Expr->getStart();
4765 SeenOtherLoops = true;
4766 return Expr;
4767 }
4768
4769 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4770
4771 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4772
4773private:
4774 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4775 : SCEVRewriteVisitor(SE), L(L) {}
4776
4777 const Loop *L;
4778 bool SeenLoopVariantSCEVUnknown = false;
4779 bool SeenOtherLoops = false;
4780};
4781
4782/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4783/// increment expression in case its Loop is L. If it is not L then
4784/// use AddRec itself.
4785/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4786class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4787public:
4788 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4789 SCEVPostIncRewriter Rewriter(L, SE);
4790 const SCEV *Result = Rewriter.visit(S);
4791 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4792 ? SE.getCouldNotCompute()
4793 : Result;
4794 }
4795
4796 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4797 if (!SE.isLoopInvariant(Expr, L))
4798 SeenLoopVariantSCEVUnknown = true;
4799 return Expr;
4800 }
4801
4802 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4803 // Only re-write AddRecExprs for this loop.
4804 if (Expr->getLoop() == L)
4805 return Expr->getPostIncExpr(SE);
4806 SeenOtherLoops = true;
4807 return Expr;
4808 }
4809
4810 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4811
4812 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4813
4814private:
4815 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4816 : SCEVRewriteVisitor(SE), L(L) {}
4817
4818 const Loop *L;
4819 bool SeenLoopVariantSCEVUnknown = false;
4820 bool SeenOtherLoops = false;
4821};
4822
4823/// This class evaluates the compare condition by matching it against the
4824/// condition of loop latch. If there is a match we assume a true value
4825/// for the condition while building SCEV nodes.
4826class SCEVBackedgeConditionFolder
4827 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4828public:
4829 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4830 ScalarEvolution &SE) {
4831 bool IsPosBECond = false;
4832 Value *BECond = nullptr;
4833 if (BasicBlock *Latch = L->getLoopLatch()) {
4834 if (CondBrInst *BI = dyn_cast<CondBrInst>(Latch->getTerminator())) {
4835 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4836 "Both outgoing branches should not target same header!");
4837 BECond = BI->getCondition();
4838 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4839 } else {
4840 return S;
4841 }
4842 }
4843 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4844 return Rewriter.visit(S);
4845 }
4846
4847 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4848 const SCEV *Result = Expr;
4849 bool InvariantF = SE.isLoopInvariant(Expr, L);
4850
4851 if (!InvariantF) {
4853 switch (I->getOpcode()) {
4854 case Instruction::Select: {
4855 SelectInst *SI = cast<SelectInst>(I);
4856 std::optional<const SCEV *> Res =
4857 compareWithBackedgeCondition(SI->getCondition());
4858 if (Res) {
4859 bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
4860 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4861 }
4862 break;
4863 }
4864 default: {
4865 std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4866 if (Res)
4867 Result = *Res;
4868 break;
4869 }
4870 }
4871 }
4872 return Result;
4873 }
4874
4875private:
4876 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4877 bool IsPosBECond, ScalarEvolution &SE)
4878 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4879 IsPositiveBECond(IsPosBECond) {}
4880
4881 std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4882
4883 const Loop *L;
4884 /// Loop back condition.
4885 Value *BackedgeCond = nullptr;
4886 /// Set to true if loop back is on positive branch condition.
4887 bool IsPositiveBECond;
4888};
4889
4890std::optional<const SCEV *>
4891SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4892
4893 // If value matches the backedge condition for loop latch,
4894 // then return a constant evolution node based on loopback
4895 // branch taken.
4896 if (BackedgeCond == IC)
4897 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4899 return std::nullopt;
4900}
4901
4902class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4903public:
4904 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4905 ScalarEvolution &SE) {
4906 SCEVShiftRewriter Rewriter(L, SE);
4907 const SCEV *Result = Rewriter.visit(S);
4908 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4909 }
4910
4911 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4912 // Only allow AddRecExprs for this loop.
4913 if (!SE.isLoopInvariant(Expr, L))
4914 Valid = false;
4915 return Expr;
4916 }
4917
4918 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4919 if (Expr->getLoop() == L && Expr->isAffine())
4920 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4921 Valid = false;
4922 return Expr;
4923 }
4924
4925 bool isValid() { return Valid; }
4926
4927private:
4928 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4929 : SCEVRewriteVisitor(SE), L(L) {}
4930
4931 const Loop *L;
4932 bool Valid = true;
4933};
4934
4935} // end anonymous namespace
4936
4937void ScalarEvolution::inferNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4938 if (!AR->isAffine())
4939 return;
4940
4941 // Force computation of ranges, which will also perform range-based flag
4942 // inference.
4943 if (!AR->hasNoSignedWrap())
4944 (void)getSignedRange(AR);
4945
4946 if (!AR->hasNoUnsignedWrap())
4947 (void)getUnsignedRange(AR);
4948
4949 if (!AR->hasNoSelfWrap()) {
4950 const SCEV *BECount = getConstantMaxBackedgeTakenCount(AR->getLoop());
4951 if (const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(BECount)) {
4952 ConstantRange StepCR = getSignedRange(AR->getStepRecurrence(*this));
4953 const APInt &BECountAP = BECountMax->getAPInt();
4954 unsigned NoOverflowBitWidth =
4955 BECountAP.getActiveBits() + StepCR.getMinSignedBits();
4956 if (NoOverflowBitWidth <= getTypeSizeInBits(AR->getType()))
4957 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
4958 }
4959 }
4960}
4961
4963ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4965
4966 if (AR->hasNoSignedWrap())
4967 return Result;
4968
4969 if (!AR->isAffine())
4970 return Result;
4971
4972 // This function can be expensive, only try to prove NSW once per AddRec.
4973 if (!SignedWrapViaInductionTried.insert(AR).second)
4974 return Result;
4975
4976 const SCEV *Step = AR->getStepRecurrence(*this);
4977 const Loop *L = AR->getLoop();
4978
4979 // Check whether the backedge-taken count is SCEVCouldNotCompute.
4980 // Note that this serves two purposes: It filters out loops that are
4981 // simply not analyzable, and it covers the case where this code is
4982 // being called from within backedge-taken count analysis, such that
4983 // attempting to ask for the backedge-taken count would likely result
4984 // in infinite recursion. In the later case, the analysis code will
4985 // cope with a conservative value, and it will take care to purge
4986 // that value once it has finished.
4987 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4988
4989 // Normally, in the cases we can prove no-overflow via a
4990 // backedge guarding condition, we can also compute a backedge
4991 // taken count for the loop. The exceptions are assumptions and
4992 // guards present in the loop -- SCEV is not great at exploiting
4993 // these to compute max backedge taken counts, but can still use
4994 // these to prove lack of overflow. Use this fact to avoid
4995 // doing extra work that may not pay off.
4996
4997 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4998 AC.assumptions().empty())
4999 return Result;
5000
5001 // If the backedge is guarded by a comparison with the pre-inc value the
5002 // addrec is safe. Also, if the entry is guarded by a comparison with the
5003 // start value and the backedge is guarded by a comparison with the post-inc
5004 // value, the addrec is safe.
5006 const SCEV *OverflowLimit =
5007 getSignedOverflowLimitForStep(Step, &Pred, this);
5008 if (OverflowLimit &&
5009 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5010 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
5011 Result = setFlags(Result, SCEV::FlagNSW);
5012 }
5013 return Result;
5014}
5016ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5018
5019 if (AR->hasNoUnsignedWrap())
5020 return Result;
5021
5022 if (!AR->isAffine())
5023 return Result;
5024
5025 // This function can be expensive, only try to prove NUW once per AddRec.
5026 if (!UnsignedWrapViaInductionTried.insert(AR).second)
5027 return Result;
5028
5029 const SCEV *Step = AR->getStepRecurrence(*this);
5030 const Loop *L = AR->getLoop();
5031
5032 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5033 // Note that this serves two purposes: It filters out loops that are
5034 // simply not analyzable, and it covers the case where this code is
5035 // being called from within backedge-taken count analysis, such that
5036 // attempting to ask for the backedge-taken count would likely result
5037 // in infinite recursion. In the later case, the analysis code will
5038 // cope with a conservative value, and it will take care to purge
5039 // that value once it has finished.
5040 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5041
5042 // Normally, in the cases we can prove no-overflow via a
5043 // backedge guarding condition, we can also compute a backedge
5044 // taken count for the loop. The exceptions are assumptions and
5045 // guards present in the loop -- SCEV is not great at exploiting
5046 // these to compute max backedge taken counts, but can still use
5047 // these to prove lack of overflow. Use this fact to avoid
5048 // doing extra work that may not pay off.
5049
5050 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5051 AC.assumptions().empty())
5052 return Result;
5053
5054 // If the backedge is guarded by a comparison with the pre-inc value the
5055 // addrec is safe. Also, if the entry is guarded by a comparison with the
5056 // start value and the backedge is guarded by a comparison with the post-inc
5057 // value, the addrec is safe.
5058 if (isKnownPositive(Step)) {
5060 const SCEV *OverflowLimit =
5062 if (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5063 isKnownOnEveryIteration(Pred, AR, OverflowLimit))
5064 Result = setFlags(Result, SCEV::FlagNUW);
5065 }
5066 return Result;
5067}
5068
5069namespace {
5070
5071/// Represents an abstract binary operation. This may exist as a
5072/// normal instruction or constant expression, or may have been
5073/// derived from an expression tree.
5074struct BinaryOp {
5075 unsigned Opcode;
5076 Value *LHS;
5077 Value *RHS;
5078 bool IsNSW = false;
5079 bool IsNUW = false;
5080
5081 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5082 /// constant expression.
5083 Operator *Op = nullptr;
5084
5085 explicit BinaryOp(Operator *Op)
5086 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5087 Op(Op) {
5088 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5089 IsNSW = OBO->hasNoSignedWrap();
5090 IsNUW = OBO->hasNoUnsignedWrap();
5091 }
5092 }
5093
5094 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5095 bool IsNUW = false)
5096 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5097};
5098
5099} // end anonymous namespace
5100
5101/// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
5102static std::optional<BinaryOp> MatchBinaryOp(Value *V,
5103 const DominatorTree &DT) {
5104 auto *Op = dyn_cast<Operator>(V);
5105 if (!Op)
5106 return std::nullopt;
5107
5108 // Implementation detail: all the cleverness here should happen without
5109 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5110 // SCEV expressions when possible, and we should not break that.
5111
5112 switch (Op->getOpcode()) {
5113 case Instruction::Add:
5114 case Instruction::Sub:
5115 case Instruction::Mul:
5116 case Instruction::UDiv:
5117 case Instruction::URem:
5118 case Instruction::And:
5119 case Instruction::AShr:
5120 case Instruction::Shl:
5121 return BinaryOp(Op);
5122
5123 case Instruction::Or: {
5124 // Convert or disjoint into add nuw nsw.
5125 if (cast<PossiblyDisjointInst>(Op)->isDisjoint()) {
5126 BinaryOp BinOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
5127 /*IsNSW=*/true, /*IsNUW=*/true);
5128 // Keep the reference to the original instruction so that we can later
5129 // check whether it can produce poison value or not.
5130 BinOp.Op = Op;
5131 return BinOp;
5132 }
5133 return BinaryOp(Op);
5134 }
5135
5136 case Instruction::Xor:
5137 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5138 // If the RHS of the xor is a signmask, then this is just an add.
5139 // Instcombine turns add of signmask into xor as a strength reduction step.
5140 if (RHSC->getValue().isSignMask())
5141 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5142 // Binary `xor` is a bit-wise `add`.
5143 if (V->getType()->isIntegerTy(1))
5144 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5145 return BinaryOp(Op);
5146
5147 case Instruction::LShr:
5148 // Turn logical shift right of a constant into a unsigned divide.
5149 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5150 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5151
5152 // If the shift count is not less than the bitwidth, the result of
5153 // the shift is undefined. Don't try to analyze it, because the
5154 // resolution chosen here may differ from the resolution chosen in
5155 // other parts of the compiler.
5156 if (SA->getValue().ult(BitWidth)) {
5157 Constant *X =
5158 ConstantInt::get(SA->getContext(),
5159 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5160 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5161 }
5162 }
5163 return BinaryOp(Op);
5164
5165 case Instruction::ExtractValue: {
5166 auto *EVI = cast<ExtractValueInst>(Op);
5167 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5168 break;
5169
5170 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5171 if (!WO)
5172 break;
5173
5174 Instruction::BinaryOps BinOp = WO->getBinaryOp();
5175 bool Signed = WO->isSigned();
5176 // TODO: Should add nuw/nsw flags for mul as well.
5177 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5178 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5179
5180 // Now that we know that all uses of the arithmetic-result component of
5181 // CI are guarded by the overflow check, we can go ahead and pretend
5182 // that the arithmetic is non-overflowing.
5183 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5184 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5185 }
5186
5187 default:
5188 break;
5189 }
5190
5191 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5192 // semantics as a Sub, return a binary sub expression.
5193 if (auto *II = dyn_cast<IntrinsicInst>(V))
5194 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5195 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5196
5197 return std::nullopt;
5198}
5199
5200/// Helper function to createAddRecFromPHIWithCasts. We have a phi
5201/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5202/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5203/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5204/// follows one of the following patterns:
5205/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5206/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5207/// If the SCEV expression of \p Op conforms with one of the expected patterns
5208/// we return the type of the truncation operation, and indicate whether the
5209/// truncated type should be treated as signed/unsigned by setting
5210/// \p Signed to true/false, respectively.
5211static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5212 bool &Signed, ScalarEvolution &SE) {
5213 // The case where Op == SymbolicPHI (that is, with no type conversions on
5214 // the way) is handled by the regular add recurrence creating logic and
5215 // would have already been triggered in createAddRecForPHI. Reaching it here
5216 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5217 // because one of the other operands of the SCEVAddExpr updating this PHI is
5218 // not invariant).
5219 //
5220 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5221 // this case predicates that allow us to prove that Op == SymbolicPHI will
5222 // be added.
5223 if (Op == SymbolicPHI)
5224 return nullptr;
5225
5226 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5227 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5228 if (SourceBits != NewBits)
5229 return nullptr;
5230
5231 if (match(Op, m_scev_SExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5232 Signed = true;
5233 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5234 }
5235 if (match(Op, m_scev_ZExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5236 Signed = false;
5237 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5238 }
5239 return nullptr;
5240}
5241
5242static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5243 if (!PN->getType()->isIntegerTy())
5244 return nullptr;
5245 const Loop *L = LI.getLoopFor(PN->getParent());
5246 if (!L || L->getHeader() != PN->getParent())
5247 return nullptr;
5248 return L;
5249}
5250
5251// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5252// computation that updates the phi follows the following pattern:
5253// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5254// which correspond to a phi->trunc->sext/zext->add->phi update chain.
5255// If so, try to see if it can be rewritten as an AddRecExpr under some
5256// Predicates. If successful, return them as a pair. Also cache the results
5257// of the analysis.
5258//
5259// Example usage scenario:
5260// Say the Rewriter is called for the following SCEV:
5261// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5262// where:
5263// %X = phi i64 (%Start, %BEValue)
5264// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5265// and call this function with %SymbolicPHI = %X.
5266//
5267// The analysis will find that the value coming around the backedge has
5268// the following SCEV:
5269// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5270// Upon concluding that this matches the desired pattern, the function
5271// will return the pair {NewAddRec, SmallPredsVec} where:
5272// NewAddRec = {%Start,+,%Step}
5273// SmallPredsVec = {P1, P2, P3} as follows:
5274// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5275// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5276// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5277// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5278// under the predicates {P1,P2,P3}.
5279// This predicated rewrite will be cached in PredicatedSCEVRewrites:
5280// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5281//
5282// TODO's:
5283//
5284// 1) Extend the Induction descriptor to also support inductions that involve
5285// casts: When needed (namely, when we are called in the context of the
5286// vectorizer induction analysis), a Set of cast instructions will be
5287// populated by this method, and provided back to isInductionPHI. This is
5288// needed to allow the vectorizer to properly record them to be ignored by
5289// the cost model and to avoid vectorizing them (otherwise these casts,
5290// which are redundant under the runtime overflow checks, will be
5291// vectorized, which can be costly).
5292//
5293// 2) Support additional induction/PHISCEV patterns: We also want to support
5294// inductions where the sext-trunc / zext-trunc operations (partly) occur
5295// after the induction update operation (the induction increment):
5296//
5297// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5298// which correspond to a phi->add->trunc->sext/zext->phi update chain.
5299//
5300// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5301// which correspond to a phi->trunc->add->sext/zext->phi update chain.
5302//
5303// 3) Outline common code with createAddRecFromPHI to avoid duplication.
5304std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5305ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5307
5308 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5309 // return an AddRec expression under some predicate.
5310
5311 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5312 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5313 assert(L && "Expecting an integer loop header phi");
5314
5315 // The loop may have multiple entrances or multiple exits; we can analyze
5316 // this phi as an addrec if it has a unique entry value and a unique
5317 // backedge value.
5318 Value *BEValueV = nullptr, *StartValueV = nullptr;
5319 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5320 Value *V = PN->getIncomingValue(i);
5321 if (L->contains(PN->getIncomingBlock(i))) {
5322 if (!BEValueV) {
5323 BEValueV = V;
5324 } else if (BEValueV != V) {
5325 BEValueV = nullptr;
5326 break;
5327 }
5328 } else if (!StartValueV) {
5329 StartValueV = V;
5330 } else if (StartValueV != V) {
5331 StartValueV = nullptr;
5332 break;
5333 }
5334 }
5335 if (!BEValueV || !StartValueV)
5336 return std::nullopt;
5337
5338 const SCEV *BEValue = getSCEV(BEValueV);
5339
5340 // If the value coming around the backedge is an add with the symbolic
5341 // value we just inserted, possibly with casts that we can ignore under
5342 // an appropriate runtime guard, then we found a simple induction variable!
5343 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5344 if (!Add)
5345 return std::nullopt;
5346
5347 // If there is a single occurrence of the symbolic value, possibly
5348 // casted, replace it with a recurrence.
5349 unsigned FoundIndex = Add->getNumOperands();
5350 Type *TruncTy = nullptr;
5351 bool Signed;
5352 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5353 if ((TruncTy =
5354 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5355 if (FoundIndex == e) {
5356 FoundIndex = i;
5357 break;
5358 }
5359
5360 if (FoundIndex == Add->getNumOperands())
5361 return std::nullopt;
5362
5363 // Create an add with everything but the specified operand.
5365 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5366 if (i != FoundIndex)
5367 Ops.push_back(Add->getOperand(i));
5368 const SCEV *Accum = getAddExpr(Ops);
5369
5370 // The runtime checks will not be valid if the step amount is
5371 // varying inside the loop.
5372 if (!isLoopInvariant(Accum, L))
5373 return std::nullopt;
5374
5375 // *** Part2: Create the predicates
5376
5377 // Analysis was successful: we have a phi-with-cast pattern for which we
5378 // can return an AddRec expression under the following predicates:
5379 //
5380 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5381 // fits within the truncated type (does not overflow) for i = 0 to n-1.
5382 // P2: An Equal predicate that guarantees that
5383 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5384 // P3: An Equal predicate that guarantees that
5385 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5386 //
5387 // As we next prove, the above predicates guarantee that:
5388 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5389 //
5390 //
5391 // More formally, we want to prove that:
5392 // Expr(i+1) = Start + (i+1) * Accum
5393 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5394 //
5395 // Given that:
5396 // 1) Expr(0) = Start
5397 // 2) Expr(1) = Start + Accum
5398 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5399 // 3) Induction hypothesis (step i):
5400 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5401 //
5402 // Proof:
5403 // Expr(i+1) =
5404 // = Start + (i+1)*Accum
5405 // = (Start + i*Accum) + Accum
5406 // = Expr(i) + Accum
5407 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5408 // :: from step i
5409 //
5410 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5411 //
5412 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5413 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
5414 // + Accum :: from P3
5415 //
5416 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5417 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5418 //
5419 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5420 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5421 //
5422 // By induction, the same applies to all iterations 1<=i<n:
5423 //
5424
5425 // Create a truncated addrec for which we will add a no overflow check (P1).
5426 const SCEV *StartVal = getSCEV(StartValueV);
5427 const SCEV *PHISCEV =
5428 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5429 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagNone);
5430
5431 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5432 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5433 // will be constant.
5434 //
5435 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5436 // add P1.
5437 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5441 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5442 Predicates.push_back(AddRecPred);
5443 }
5444
5445 // Create the Equal Predicates P2,P3:
5446
5447 // It is possible that the predicates P2 and/or P3 are computable at
5448 // compile time due to StartVal and/or Accum being constants.
5449 // If either one is, then we can check that now and escape if either P2
5450 // or P3 is false.
5451
5452 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5453 // for each of StartVal and Accum
5454 auto getExtendedExpr = [&](const SCEV *Expr,
5455 bool CreateSignExtend) -> const SCEV * {
5456 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5457 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5458 const SCEV *ExtendedExpr =
5459 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5460 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5461 return ExtendedExpr;
5462 };
5463
5464 // Given:
5465 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5466 // = getExtendedExpr(Expr)
5467 // Determine whether the predicate P: Expr == ExtendedExpr
5468 // is known to be false at compile time
5469 auto PredIsKnownFalse = [&](const SCEV *Expr,
5470 const SCEV *ExtendedExpr) -> bool {
5471 return Expr != ExtendedExpr &&
5472 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5473 };
5474
5475 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5476 if (PredIsKnownFalse(StartVal, StartExtended)) {
5477 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5478 return std::nullopt;
5479 }
5480
5481 // The Step is always Signed (because the overflow checks are either
5482 // NSSW or NUSW)
5483 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5484 if (PredIsKnownFalse(Accum, AccumExtended)) {
5485 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5486 return std::nullopt;
5487 }
5488
5489 auto AppendPredicate = [&](const SCEV *Expr,
5490 const SCEV *ExtendedExpr) -> void {
5491 if (Expr != ExtendedExpr &&
5492 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5493 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5494 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5495 Predicates.push_back(Pred);
5496 }
5497 };
5498
5499 AppendPredicate(StartVal, StartExtended);
5500 AppendPredicate(Accum, AccumExtended);
5501
5502 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5503 // which the casts had been folded away. The caller can rewrite SymbolicPHI
5504 // into NewAR if it will also add the runtime overflow checks specified in
5505 // Predicates.
5506 const SCEV *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagNone);
5507
5508 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5509 std::make_pair(NewAR, Predicates);
5510 // Remember the result of the analysis for this SCEV at this locayyytion.
5511 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5512 return PredRewrite;
5513}
5514
5515std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5517 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5518 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5519 if (!L)
5520 return std::nullopt;
5521
5522 // Check to see if we already analyzed this PHI.
5523 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5524 if (I != PredicatedSCEVRewrites.end()) {
5525 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5526 I->second;
5527 // Analysis was done before and failed to create an AddRec:
5528 if (Rewrite.first == SymbolicPHI)
5529 return std::nullopt;
5530 // Analysis was done before and succeeded to create an AddRec under
5531 // a predicate:
5532 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5533 assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5534 return Rewrite;
5535 }
5536
5537 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5538 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5539
5540 // Record in the cache that the analysis failed
5541 if (!Rewrite) {
5543 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5544 return std::nullopt;
5545 }
5546
5547 return Rewrite;
5548}
5549
5550// FIXME: This utility is currently required because the Rewriter currently
5551// does not rewrite this expression:
5552// {0, +, (sext ix (trunc iy to ix) to iy)}
5553// into {0, +, %step},
5554// even when the following Equal predicate exists:
5555// "%step == (sext ix (trunc iy to ix) to iy)".
5557 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2,
5558 ArrayRef<const SCEVPredicate *> NoWrapPreds) const {
5559 if (AR1 == AR2)
5560 return true;
5561
5562 SCEVUnionPredicate NoWrapUnionPred(NoWrapPreds, SE);
5563 SCEVUnionPredicate AllPreds = Preds->getUnionWith(&NoWrapUnionPred, SE);
5564 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5565 if (Expr1 != Expr2 &&
5566 !AllPreds.implies(SE.getEqualPredicate(Expr1, Expr2), SE) &&
5567 !AllPreds.implies(SE.getEqualPredicate(Expr2, Expr1), SE))
5568 return false;
5569 return true;
5570 };
5571
5572 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5573 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5574 return false;
5575 return true;
5576}
5577
5579 ScalarEvolution &SE) {
5580 SCEVFlags Flags = SCEV::FlagNone;
5581 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
5582 // If the increment has any nowrap flags, then we know the address
5583 // space cannot be wrapped around.
5584 if (NW != GEPNoWrapFlags::none())
5586 // If the GEP is nuw or nusw with non-negative offset, we know that
5587 // no unsigned wrap occurs. We cannot set the nsw flag as only the
5588 // offset is treated as signed, while the base is unsigned.
5589 if (NW.hasNoUnsignedWrap() ||
5590 (NW.hasNoUnsignedSignedWrap() && SE.isKnownNonNegative(Accum)))
5592
5593 return Flags;
5594}
5595
5596/// A helper function for createAddRecFromPHI to handle simple cases.
5597///
5598/// This function tries to find an AddRec expression for the simplest (yet most
5599/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5600/// If it fails, createAddRecFromPHI will use a more general, but slow,
5601/// technique for finding the AddRec expression.
5602const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5603 Value *BEValueV,
5604 Value *StartValueV) {
5605 const Loop *L = LI.getLoopFor(PN->getParent());
5606 assert(L && L->getHeader() == PN->getParent());
5607 assert(BEValueV && StartValueV);
5608
5609 const SCEV *Accum = nullptr;
5611 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5612 if (BO->Opcode != Instruction::Add)
5613 return nullptr;
5614
5615 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5616 Accum = getSCEV(BO->RHS);
5617 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5618 Accum = getSCEV(BO->LHS);
5619
5620 if (!Accum)
5621 return nullptr;
5622
5623 if (BO->IsNUW)
5624 Flags = setFlags(Flags, SCEV::FlagNUW);
5625 if (BO->IsNSW)
5626 Flags = setFlags(Flags, SCEV::FlagNSW);
5627 } else {
5628 // Handle pointer induction variable: PN = PHI(Start, gep PN,
5629 // LoopInvariant).
5630 auto *GEP = dyn_cast<GEPOperator>(BEValueV);
5631 if (!GEP || GEP->getPointerOperand() != PN || GEP->getNumIndices() != 1)
5632 return nullptr;
5633 Value *Idx = *GEP->idx_begin();
5634 if (!L->isLoopInvariant(Idx))
5635 return nullptr;
5636
5637 Type *IntIdxTy = getEffectiveSCEVType(GEP->getType());
5638 Accum = getMulExpr(getTruncateOrSignExtend(getSCEV(Idx), IntIdxTy),
5639 getSizeOfExpr(IntIdxTy, GEP->getSourceElementType()));
5640 Flags = getNoWrapFlagsForGEP(GEP, Accum, *this);
5641 }
5642
5643 const SCEV *StartVal = getSCEV(StartValueV);
5644 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5645 insertValueToMap(PN, PHISCEV);
5646
5647 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5648 inferNoWrapViaConstantRanges(AR);
5649
5650 // We can add Flags to the post-inc expression only if we
5651 // know that it is *undefined behavior* for BEValueV to
5652 // overflow.
5653 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5654 assert(isLoopInvariant(Accum, L) &&
5655 "Accum is defined outside L, but is not invariant?");
5656 if (isAddRecNeverPoison(BEInst, L))
5657 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5658 }
5659
5660 return PHISCEV;
5661}
5662
5663const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5664 const Loop *L = LI.getLoopFor(PN->getParent());
5665 if (!L || L->getHeader() != PN->getParent())
5666 return nullptr;
5667
5668 // The loop may have multiple entrances or multiple exits; we can analyze
5669 // this phi as an addrec if it has a unique entry value and a unique
5670 // backedge value.
5671 Value *BEValueV = nullptr, *StartValueV = nullptr;
5672 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5673 Value *V = PN->getIncomingValue(i);
5674 if (L->contains(PN->getIncomingBlock(i))) {
5675 if (!BEValueV) {
5676 BEValueV = V;
5677 } else if (BEValueV != V) {
5678 BEValueV = nullptr;
5679 break;
5680 }
5681 } else if (!StartValueV) {
5682 StartValueV = V;
5683 } else if (StartValueV != V) {
5684 StartValueV = nullptr;
5685 break;
5686 }
5687 }
5688 if (!BEValueV || !StartValueV)
5689 return nullptr;
5690
5691 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5692 "PHI node already processed?");
5693
5694 // First, try to find AddRec expression without creating a fictituos symbolic
5695 // value for PN.
5696 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5697 return S;
5698
5699 // Handle PHI node value symbolically.
5700 const SCEV *SymbolicName = getUnknown(PN);
5701 insertValueToMap(PN, SymbolicName);
5702
5703 // Using this symbolic name for the PHI, analyze the value coming around
5704 // the back-edge.
5705 const SCEV *BEValue = getSCEV(BEValueV);
5706
5707 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5708 // has a special value for the first iteration of the loop.
5709
5710 // If the value coming around the backedge is an add with the symbolic
5711 // value we just inserted, then we found a simple induction variable!
5712 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5713 // If there is a single occurrence of the symbolic value, replace it
5714 // with a recurrence.
5715 unsigned FoundIndex = Add->getNumOperands();
5716 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5717 if (Add->getOperand(i) == SymbolicName)
5718 if (FoundIndex == e) {
5719 FoundIndex = i;
5720 break;
5721 }
5722
5723 if (FoundIndex != Add->getNumOperands()) {
5724 // Create an add with everything but the specified operand.
5726 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5727 if (i != FoundIndex)
5728 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5729 L, *this));
5730 const SCEV *Accum = getAddExpr(Ops);
5731
5732 // This is not a valid addrec if the step amount is varying each
5733 // loop iteration, but is not itself an addrec in this loop.
5734 if (isLoopInvariant(Accum, L) ||
5735 (isa<SCEVAddRecExpr>(Accum) &&
5736 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5738
5739 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5740 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5741 if (BO->IsNUW)
5742 Flags = setFlags(Flags, SCEV::FlagNUW);
5743 if (BO->IsNSW)
5744 Flags = setFlags(Flags, SCEV::FlagNSW);
5745 }
5746 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5747 if (GEP->getOperand(0) == PN)
5748 Flags = getNoWrapFlagsForGEP(GEP, Accum, *this);
5749
5750 // We cannot transfer nuw and nsw flags from subtraction
5751 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5752 // for instance.
5753 }
5754
5755 const SCEV *StartVal = getSCEV(StartValueV);
5756 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5757
5758 // Okay, for the entire analysis of this edge we assumed the PHI
5759 // to be symbolic. We now need to go back and purge all of the
5760 // entries for the scalars that use the symbolic expression.
5761 forgetMemoizedResults({SymbolicName});
5762 insertValueToMap(PN, PHISCEV);
5763
5764 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5765 inferNoWrapViaConstantRanges(AR);
5766
5767 // We can add Flags to the post-inc expression only if we
5768 // know that it is *undefined behavior* for BEValueV to
5769 // overflow.
5770 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5771 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5772 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5773
5774 return PHISCEV;
5775 }
5776 }
5777 } else {
5778 // Otherwise, this could be a loop like this:
5779 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5780 // In this case, j = {1,+,1} and BEValue is j.
5781 // Because the other in-value of i (0) fits the evolution of BEValue
5782 // i really is an addrec evolution.
5783 //
5784 // We can generalize this saying that i is the shifted value of BEValue
5785 // by one iteration:
5786 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5787
5788 // Do not allow refinement in rewriting of BEValue.
5789 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5790 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5791 if (Shifted != getCouldNotCompute() && Start != getCouldNotCompute() &&
5792 isGuaranteedNotToCauseUB(Shifted) && ::impliesPoison(Shifted, Start)) {
5793 const SCEV *StartVal = getSCEV(StartValueV);
5794 if (Start == StartVal) {
5795 // Okay, for the entire analysis of this edge we assumed the PHI
5796 // to be symbolic. We now need to go back and purge all of the
5797 // entries for the scalars that use the symbolic expression.
5798 forgetMemoizedResults({SymbolicName});
5799 insertValueToMap(PN, Shifted);
5800 return Shifted;
5801 }
5802 }
5803 }
5804
5805 // Remove the temporary PHI node SCEV that has been inserted while intending
5806 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5807 // as it will prevent later (possibly simpler) SCEV expressions to be added
5808 // to the ValueExprMap.
5809 eraseValueFromMap(PN);
5810
5811 return nullptr;
5812}
5813
5814// Try to match a control flow sequence that branches out at BI and merges back
5815// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5816// match.
5818 Value *&C, Value *&LHS, Value *&RHS) {
5819 C = BI->getCondition();
5820
5821 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5822 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5823
5824 Use &LeftUse = Merge->getOperandUse(0);
5825 Use &RightUse = Merge->getOperandUse(1);
5826
5827 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5828 LHS = LeftUse;
5829 RHS = RightUse;
5830 return true;
5831 }
5832
5833 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5834 LHS = RightUse;
5835 RHS = LeftUse;
5836 return true;
5837 }
5838
5839 return false;
5840}
5841
5843 Value *&Cond, Value *&LHS,
5844 Value *&RHS) {
5845 auto IsReachable =
5846 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5847 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5848 // Try to match
5849 //
5850 // br %cond, label %left, label %right
5851 // left:
5852 // br label %merge
5853 // right:
5854 // br label %merge
5855 // merge:
5856 // V = phi [ %x, %left ], [ %y, %right ]
5857 //
5858 // as "select %cond, %x, %y"
5859
5860 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5861 assert(IDom && "At least the entry block should dominate PN");
5862
5863 auto *BI = dyn_cast<CondBrInst>(IDom->getTerminator());
5864 return BI && BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS);
5865 }
5866 return false;
5867}
5868
5869const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5870 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5871 if (getOperandsForSelectLikePHI(DT, PN, Cond, LHS, RHS) &&
5874 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5875
5876 return nullptr;
5877}
5878
5880 BinaryOperator *CommonInst = nullptr;
5881 // Check if instructions are identical.
5882 for (Value *Incoming : PN->incoming_values()) {
5883 auto *IncomingInst = dyn_cast<BinaryOperator>(Incoming);
5884 if (!IncomingInst)
5885 return nullptr;
5886 if (CommonInst) {
5887 if (!CommonInst->isIdenticalToWhenDefined(IncomingInst))
5888 return nullptr; // Not identical, give up
5889 } else {
5890 // Remember binary operator
5891 CommonInst = IncomingInst;
5892 }
5893 }
5894 return CommonInst;
5895}
5896
5897/// Returns SCEV for the first operand of a phi if all phi operands have
5898/// identical opcodes and operands
5899/// eg.
5900/// a: %add = %a + %b
5901/// br %c
5902/// b: %add1 = %a + %b
5903/// br %c
5904/// c: %phi = phi [%add, a], [%add1, b]
5905/// scev(%phi) => scev(%add)
5906const SCEV *
5907ScalarEvolution::createNodeForPHIWithIdenticalOperands(PHINode *PN) {
5908 BinaryOperator *CommonInst = getCommonInstForPHI(PN);
5909 if (!CommonInst)
5910 return nullptr;
5911
5912 // Check if SCEV exprs for instructions are identical.
5913 const SCEV *CommonSCEV = getSCEV(CommonInst);
5914 bool SCEVExprsIdentical =
5916 [this, CommonSCEV](Value *V) { return CommonSCEV == getSCEV(V); });
5917 return SCEVExprsIdentical ? CommonSCEV : nullptr;
5918}
5919
5920const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5921 if (const SCEV *S = createAddRecFromPHI(PN))
5922 return S;
5923
5924 // We do not allow simplifying phi (undef, X) to X here, to avoid reusing the
5925 // phi node for X.
5927 PN, {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
5928 /*UseInstrInfo=*/true, /*CanUseUndef=*/false}))
5929 return getSCEV(V);
5930
5931 if (const SCEV *S = createNodeForPHIWithIdenticalOperands(PN))
5932 return S;
5933
5934 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5935 return S;
5936
5937 // If it's not a loop phi, we can't handle it yet.
5938 return getUnknown(PN);
5939}
5940
5941bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
5942 SCEVTypes RootKind) {
5943 struct FindClosure {
5944 const SCEV *OperandToFind;
5945 const SCEVTypes RootKind; // Must be a sequential min/max expression.
5946 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
5947
5948 bool Found = false;
5949
5950 bool canRecurseInto(SCEVTypes Kind) const {
5951 // We can only recurse into the SCEV expression of the same effective type
5952 // as the type of our root SCEV expression, and into zero-extensions.
5953 return RootKind == Kind || NonSequentialRootKind == Kind ||
5954 scZeroExtend == Kind;
5955 };
5956
5957 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
5958 : OperandToFind(OperandToFind), RootKind(RootKind),
5959 NonSequentialRootKind(
5961 RootKind)) {}
5962
5963 bool follow(const SCEV *S) {
5964 Found = S == OperandToFind;
5965
5966 return !isDone() && canRecurseInto(S->getSCEVType());
5967 }
5968
5969 bool isDone() const { return Found; }
5970 };
5971
5972 FindClosure FC(OperandToFind, RootKind);
5973 visitAll(Root, FC);
5974 return FC.Found;
5975}
5976
5977std::optional<const SCEV *>
5978ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
5979 ICmpInst *Cond,
5980 Value *TrueVal,
5981 Value *FalseVal) {
5982 // Try to match some simple smax or umax patterns.
5983 auto *ICI = Cond;
5984
5985 Value *LHS = ICI->getOperand(0);
5986 Value *RHS = ICI->getOperand(1);
5987
5988 switch (ICI->getPredicate()) {
5989 case ICmpInst::ICMP_SLT:
5990 case ICmpInst::ICMP_SLE:
5991 case ICmpInst::ICMP_ULT:
5992 case ICmpInst::ICMP_ULE:
5993 std::swap(LHS, RHS);
5994 [[fallthrough]];
5995 case ICmpInst::ICMP_SGT:
5996 case ICmpInst::ICMP_SGE:
5997 case ICmpInst::ICMP_UGT:
5998 case ICmpInst::ICMP_UGE:
5999 // a > b ? a+x : b+x -> max(a, b)+x
6000 // a > b ? b+x : a+x -> min(a, b)+x
6002 bool Signed = ICI->isSigned();
6003 const SCEV *LA = getSCEV(TrueVal);
6004 const SCEV *RA = getSCEV(FalseVal);
6005 const SCEV *LS = getSCEV(LHS);
6006 const SCEV *RS = getSCEV(RHS);
6007 if (LA->getType()->isPointerTy()) {
6008 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6009 // Need to make sure we can't produce weird expressions involving
6010 // negated pointers.
6011 if (LA == LS && RA == RS)
6012 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6013 if (LA == RS && RA == LS)
6014 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6015 }
6016 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6017 if (Op->getType()->isPointerTy()) {
6020 return Op;
6021 }
6022 if (Signed)
6023 Op = getNoopOrSignExtend(Op, Ty);
6024 else
6025 Op = getNoopOrZeroExtend(Op, Ty);
6026 return Op;
6027 };
6028 LS = CoerceOperand(LS);
6029 RS = CoerceOperand(RS);
6031 break;
6032 const SCEV *LDiff = getMinusSCEV(LA, LS);
6033 const SCEV *RDiff = getMinusSCEV(RA, RS);
6034 if (LDiff == RDiff)
6035 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6036 LDiff);
6037 LDiff = getMinusSCEV(LA, RS);
6038 RDiff = getMinusSCEV(RA, LS);
6039 if (LDiff == RDiff)
6040 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6041 LDiff);
6042 }
6043 break;
6044 case ICmpInst::ICMP_NE:
6045 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
6046 std::swap(TrueVal, FalseVal);
6047 [[fallthrough]];
6048 case ICmpInst::ICMP_EQ:
6049 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
6052 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6053 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y
6054 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y
6055 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6056 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y
6057 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6058 return getAddExpr(getUMaxExpr(X, C), Y);
6059 }
6060 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
6061 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
6062 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
6063 // -> umin_seq(x, umin (..., umin_seq(...), ...))
6065 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6066 const SCEV *X = getSCEV(LHS);
6067 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6068 X = ZExt->getOperand();
6069 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6070 const SCEV *FalseValExpr = getSCEV(FalseVal);
6071 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6072 return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6073 /*Sequential=*/true);
6074 }
6075 }
6076 break;
6077 default:
6078 break;
6079 }
6080
6081 return std::nullopt;
6082}
6083
6084static std::optional<const SCEV *>
6086 const SCEV *TrueExpr, const SCEV *FalseExpr) {
6087 assert(CondExpr->getType()->isIntegerTy(1) &&
6088 TrueExpr->getType() == FalseExpr->getType() &&
6089 TrueExpr->getType()->isIntegerTy(1) &&
6090 "Unexpected operands of a select.");
6091
6092 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
6093 // --> C + (umin_seq cond, x - C)
6094 //
6095 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
6096 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6097 // --> C + (umin_seq ~cond, x - C)
6098
6099 // FIXME: while we can't legally model the case where both of the hands
6100 // are fully variable, we only require that the *difference* is constant.
6101 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6102 return std::nullopt;
6103
6104 const SCEV *X, *C;
6105 if (isa<SCEVConstant>(TrueExpr)) {
6106 CondExpr = SE->getNotSCEV(CondExpr);
6107 X = FalseExpr;
6108 C = TrueExpr;
6109 } else {
6110 X = TrueExpr;
6111 C = FalseExpr;
6112 }
6113 return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6114 /*Sequential=*/true));
6115}
6116
6117static std::optional<const SCEV *>
6119 Value *FalseVal) {
6120 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6121 return std::nullopt;
6122
6123 const auto *SECond = SE->getSCEV(Cond);
6124 const auto *SETrue = SE->getSCEV(TrueVal);
6125 const auto *SEFalse = SE->getSCEV(FalseVal);
6126 return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6127}
6128
6129const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6130 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6131 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6132 assert(TrueVal->getType() == FalseVal->getType() &&
6133 V->getType() == TrueVal->getType() &&
6134 "Types of select hands and of the result must match.");
6135
6136 // For now, only deal with i1-typed `select`s.
6137 if (!V->getType()->isIntegerTy(1))
6138 return getUnknown(V);
6139
6140 if (std::optional<const SCEV *> S =
6141 createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6142 return *S;
6143
6144 return getUnknown(V);
6145}
6146
6147const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6148 Value *TrueVal,
6149 Value *FalseVal) {
6150 // Handle "constant" branch or select. This can occur for instance when a
6151 // loop pass transforms an inner loop and moves on to process the outer loop.
6152 if (auto *CI = dyn_cast<ConstantInt>(Cond))
6153 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6154
6155 if (auto *I = dyn_cast<Instruction>(V)) {
6156 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6157 if (std::optional<const SCEV *> S =
6158 createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6159 TrueVal, FalseVal))
6160 return *S;
6161 }
6162 }
6163
6164 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6165}
6166
6167/// Expand GEP instructions into add and multiply operations. This allows them
6168/// to be analyzed by regular SCEV code.
6169const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6170 assert(GEP->getSourceElementType()->isSized() &&
6171 "GEP source element type must be sized");
6172
6173 SmallVector<SCEVUse, 4> IndexExprs;
6174 for (Value *Index : GEP->indices())
6175 IndexExprs.push_back(getSCEV(Index));
6176 return getGEPExpr(GEP, IndexExprs);
6177}
6178
6179APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S,
6180 const Instruction *CtxI) {
6182 auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6183 return TrailingZeros >= BitWidth
6185 : APInt::getOneBitSet(BitWidth, TrailingZeros);
6186 };
6187 auto GetGCDMultiple = [this, CtxI](const SCEVNAryExpr *N) {
6188 // The result is GCD of all operands results.
6189 APInt Res = getConstantMultiple(N->getOperand(0), CtxI);
6190 for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6192 Res, getConstantMultiple(N->getOperand(I), CtxI));
6193 return Res;
6194 };
6195
6196 switch (S->getSCEVType()) {
6197 case scConstant:
6198 return cast<SCEVConstant>(S)->getAPInt();
6199 case scPtrToAddr:
6200 return getConstantMultiple(cast<SCEVCastExpr>(S)->getOperand());
6201 case scUDivExpr:
6202 case scVScale:
6203 return APInt(BitWidth, 1);
6204 case scTruncate: {
6205 // Only multiples that are a power of 2 will hold after truncation.
6206 const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6207 uint32_t TZ = getMinTrailingZeros(T->getOperand(), CtxI);
6208 return GetShiftedByZeros(TZ);
6209 }
6210 case scZeroExtend: {
6211 const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(S);
6212 return getConstantMultiple(Z->getOperand(), CtxI).zext(BitWidth);
6213 }
6214 case scSignExtend: {
6215 // Only multiples that are a power of 2 will hold after sext.
6216 const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6217 uint32_t TZ = getMinTrailingZeros(E->getOperand(), CtxI);
6218 return GetShiftedByZeros(TZ);
6219 }
6220 case scMulExpr: {
6221 const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6222 if (M->hasNoUnsignedWrap()) {
6223 // The result is the product of all operand results.
6224 APInt Res = getConstantMultiple(M->getOperand(0), CtxI);
6225 for (const SCEV *Operand : M->operands().drop_front())
6226 Res = Res * getConstantMultiple(Operand, CtxI);
6227 return Res;
6228 }
6229
6230 // If there are no wrap guarentees, find the trailing zeros, which is the
6231 // sum of trailing zeros for all its operands.
6232 uint32_t TZ = 0;
6233 for (const SCEV *Operand : M->operands())
6234 TZ += getMinTrailingZeros(Operand, CtxI);
6235 return GetShiftedByZeros(TZ);
6236 }
6237 case scAddExpr:
6238 case scAddRecExpr: {
6239 const SCEVNAryExpr *N = cast<SCEVNAryExpr>(S);
6240 if (N->hasNoUnsignedWrap())
6241 return GetGCDMultiple(N);
6242 // Find the trailing bits, which is the minimum of its operands.
6243 uint32_t TZ = getMinTrailingZeros(N->getOperand(0), CtxI);
6244 for (const SCEV *Operand : N->operands().drop_front())
6245 TZ = std::min(TZ, getMinTrailingZeros(Operand, CtxI));
6246 return GetShiftedByZeros(TZ);
6247 }
6248 case scUMaxExpr:
6249 case scSMaxExpr:
6250 case scUMinExpr:
6251 case scSMinExpr:
6253 return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6254 case scUnknown: {
6255 // Ask ValueTracking for known bits. SCEVUnknown only become available at
6256 // the point their underlying IR instruction has been defined. If CtxI was
6257 // not provided, use:
6258 // * the first instruction in the entry block if it is an argument
6259 // * the instruction itself otherwise.
6260 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6261 if (!CtxI) {
6262 if (isa<Argument>(U->getValue()))
6263 CtxI = &*F.getEntryBlock().begin();
6264 else if (auto *I = dyn_cast<Instruction>(U->getValue()))
6265 CtxI = I;
6266 }
6267 unsigned Known =
6268 computeKnownBits(U->getValue(),
6269 SimplifyQuery(getDataLayout(), &DT, &AC, CtxI)
6270 .allowEphemerals(true))
6271 .countMinTrailingZeros();
6272 return GetShiftedByZeros(Known);
6273 }
6274 case scCouldNotCompute:
6275 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6276 }
6277 llvm_unreachable("Unknown SCEV kind!");
6278}
6279
6281 const Instruction *CtxI) {
6282 // Skip looking up and updating the cache if there is a context instruction,
6283 // as the result will only be valid in the specified context.
6284 if (CtxI)
6285 return getConstantMultipleImpl(S, CtxI);
6286
6287 auto I = ConstantMultipleCache.find(S);
6288 if (I != ConstantMultipleCache.end())
6289 return I->second;
6290
6291 APInt Result = getConstantMultipleImpl(S, CtxI);
6292 auto InsertPair = ConstantMultipleCache.insert({S, Result});
6293 assert(InsertPair.second && "Should insert a new key");
6294 return InsertPair.first->second;
6295}
6296
6298 APInt Multiple = getConstantMultiple(S);
6299 return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6300}
6301
6303 const Instruction *CtxI) {
6304 return std::min(getConstantMultiple(S, CtxI).countTrailingZeros(),
6305 (unsigned)getTypeSizeInBits(S->getType()));
6306}
6307
6308/// Helper method to assign a range to V from metadata present in the IR.
6309static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6311 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6312 return getConstantRangeFromMetadata(*MD);
6313 if (const auto *CB = dyn_cast<CallBase>(V))
6314 if (std::optional<ConstantRange> Range = CB->getRange())
6315 return Range;
6316 }
6317 if (auto *A = dyn_cast<Argument>(V))
6318 if (std::optional<ConstantRange> Range = A->getRange())
6319 return Range;
6320
6321 return std::nullopt;
6322}
6323
6325 SCEVFlags NWFlags = Flags & SCEV::FlagsNoWrapMask;
6326 if (AddRec->getNoWrapFlags(NWFlags) != NWFlags) {
6327 AddRec->setNoWrapFlags(NWFlags);
6328 UnsignedRanges.erase(AddRec);
6329 SignedRanges.erase(AddRec);
6330 ConstantMultipleCache.erase(AddRec);
6331 }
6332}
6333
6334ConstantRange ScalarEvolution::
6335getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6336 const DataLayout &DL = getDataLayout();
6337
6338 unsigned BitWidth = getTypeSizeInBits(U->getType());
6339 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6340
6341 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6342 // use information about the trip count to improve our available range. Note
6343 // that the trip count independent cases are already handled by known bits.
6344 // WARNING: The definition of recurrence used here is subtly different than
6345 // the one used by AddRec (and thus most of this file). Step is allowed to
6346 // be arbitrarily loop varying here, where AddRec allows only loop invariant
6347 // and other addrecs in the same loop (for non-affine addrecs). The code
6348 // below intentionally handles the case where step is not loop invariant.
6349 auto *P = dyn_cast<PHINode>(U->getValue());
6350 if (!P)
6351 return FullSet;
6352
6353 // Make sure that no Phi input comes from an unreachable block. Otherwise,
6354 // even the values that are not available in these blocks may come from them,
6355 // and this leads to false-positive recurrence test.
6356 for (auto *Pred : predecessors(P->getParent()))
6357 if (!DT.isReachableFromEntry(Pred))
6358 return FullSet;
6359
6360 BinaryOperator *BO;
6361 Value *Start, *Step;
6362 if (!matchSimpleRecurrence(P, BO, Start, Step))
6363 return FullSet;
6364
6365 // If we found a recurrence in reachable code, we must be in a loop. Note
6366 // that BO might be in some subloop of L, and that's completely okay.
6367 auto *L = LI.getLoopFor(P->getParent());
6368 assert(L && L->getHeader() == P->getParent());
6369 if (!L->contains(BO->getParent()))
6370 // NOTE: This bailout should be an assert instead. However, asserting
6371 // the condition here exposes a case where LoopFusion is querying SCEV
6372 // with malformed loop information during the midst of the transform.
6373 // There doesn't appear to be an obvious fix, so for the moment bailout
6374 // until the caller issue can be fixed. PR49566 tracks the bug.
6375 return FullSet;
6376
6377 // TODO: Extend to other opcodes such as mul, and div
6378 switch (BO->getOpcode()) {
6379 default:
6380 return FullSet;
6381 case Instruction::AShr:
6382 case Instruction::LShr:
6383 case Instruction::Shl:
6384 break;
6385 };
6386
6387 if (BO->getOperand(0) != P)
6388 // TODO: Handle the power function forms some day.
6389 return FullSet;
6390
6391 unsigned TC = getSmallConstantMaxTripCount(L);
6392 if (!TC || TC >= BitWidth)
6393 return FullSet;
6394
6395 auto KnownStart = computeKnownBits(Start, DL, &AC, nullptr, &DT);
6396 auto KnownStep = computeKnownBits(Step, DL, &AC, nullptr, &DT);
6397 assert(KnownStart.getBitWidth() == BitWidth &&
6398 KnownStep.getBitWidth() == BitWidth);
6399
6400 // Compute total shift amount, being careful of overflow and bitwidths.
6401 auto MaxShiftAmt = KnownStep.getMaxValue();
6402 APInt TCAP(BitWidth, TC-1);
6403 bool Overflow = false;
6404 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6405 if (Overflow)
6406 return FullSet;
6407
6408 switch (BO->getOpcode()) {
6409 default:
6410 llvm_unreachable("filtered out above");
6411 case Instruction::AShr: {
6412 // For each ashr, three cases:
6413 // shift = 0 => unchanged value
6414 // saturation => 0 or -1
6415 // other => a value closer to zero (of the same sign)
6416 // Thus, the end value is closer to zero than the start.
6417 auto KnownEnd = KnownBits::ashr(KnownStart,
6418 KnownBits::makeConstant(TotalShift));
6419 if (KnownStart.isNonNegative())
6420 // Analogous to lshr (simply not yet canonicalized)
6421 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6422 KnownStart.getMaxValue() + 1);
6423 if (KnownStart.isNegative())
6424 // End >=u Start && End <=s Start
6425 return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6426 KnownEnd.getMaxValue() + 1);
6427 break;
6428 }
6429 case Instruction::LShr: {
6430 // For each lshr, three cases:
6431 // shift = 0 => unchanged value
6432 // saturation => 0
6433 // other => a smaller positive number
6434 // Thus, the low end of the unsigned range is the last value produced.
6435 auto KnownEnd = KnownBits::lshr(KnownStart,
6436 KnownBits::makeConstant(TotalShift));
6437 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6438 KnownStart.getMaxValue() + 1);
6439 }
6440 case Instruction::Shl: {
6441 // Iff no bits are shifted out, value increases on every shift.
6442 auto KnownEnd = KnownBits::shl(KnownStart,
6443 KnownBits::makeConstant(TotalShift));
6444 if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6445 return ConstantRange(KnownStart.getMinValue(),
6446 KnownEnd.getMaxValue() + 1);
6447 break;
6448 }
6449 };
6450 return FullSet;
6451}
6452
6453// The goal of this function is to check if recursively visiting the operands
6454// of this PHI might lead to an infinite loop. If we do see such a loop,
6455// there's no good way to break it, so we avoid analyzing such cases.
6456//
6457// getRangeRef previously used a visited set to avoid infinite loops, but this
6458// caused other issues: the result was dependent on the order of getRangeRef
6459// calls, and the interaction with createSCEVIter could cause a stack overflow
6460// in some cases (see issue #148253).
6461//
6462// FIXME: The way this is implemented is overly conservative; this checks
6463// for a few obviously safe patterns, but anything that doesn't lead to
6464// recursion is fine.
6466 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6468 return true;
6469
6470 if (all_of(PHI->operands(),
6471 [&](Value *Operand) { return DT.dominates(Operand, PHI); }))
6472 return true;
6473
6474 return false;
6475}
6476
6477const ConstantRange &
6478ScalarEvolution::getRangeRefIter(const SCEV *S,
6479 ScalarEvolution::RangeSignHint SignHint) {
6480 DenseMap<const SCEV *, ConstantRange> &Cache =
6481 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6482 : SignedRanges;
6483 SmallVector<SCEVUse> WorkList;
6484 SmallPtrSet<const SCEV *, 8> Seen;
6485
6486 // Add Expr to the worklist, if Expr is either an N-ary expression or a
6487 // SCEVUnknown PHI node.
6488 auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6489 if (!Seen.insert(Expr).second)
6490 return;
6491 if (Cache.contains(Expr))
6492 return;
6493 switch (Expr->getSCEVType()) {
6494 case scUnknown:
6496 break;
6497 [[fallthrough]];
6498 case scConstant:
6499 case scVScale:
6500 case scTruncate:
6501 case scZeroExtend:
6502 case scSignExtend:
6503 case scPtrToAddr:
6504 case scAddExpr:
6505 case scMulExpr:
6506 case scUDivExpr:
6507 case scAddRecExpr:
6508 case scUMaxExpr:
6509 case scSMaxExpr:
6510 case scUMinExpr:
6511 case scSMinExpr:
6513 WorkList.push_back(Expr);
6514 break;
6515 case scCouldNotCompute:
6516 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6517 }
6518 };
6519 AddToWorklist(S);
6520
6521 // Build worklist by queuing operands of N-ary expressions and phi nodes.
6522 for (unsigned I = 0; I != WorkList.size(); ++I) {
6523 const SCEV *P = WorkList[I];
6524 auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6525 // If it is not a `SCEVUnknown`, just recurse into operands.
6526 if (!UnknownS) {
6527 for (const SCEV *Op : P->operands())
6528 AddToWorklist(Op);
6529 continue;
6530 }
6531 // `SCEVUnknown`'s require special treatment.
6532 if (PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6533 if (!RangeRefPHIAllowedOperands(DT, P))
6534 continue;
6535 for (auto &Op : reverse(P->operands()))
6536 AddToWorklist(getSCEV(Op));
6537 }
6538 }
6539
6540 if (!WorkList.empty()) {
6541 // Use getRangeRef to compute ranges for items in the worklist in reverse
6542 // order. This will force ranges for earlier operands to be computed before
6543 // their users in most cases.
6544 for (const SCEV *P : reverse(drop_begin(WorkList))) {
6545 getRangeRef(P, SignHint);
6546 }
6547 }
6548
6549 return getRangeRef(S, SignHint, 0);
6550}
6551
6552const APInt *ScalarEvolution::getConstantAPIntOrNull(const SCEV *S) {
6553 if (const auto *C = dyn_cast<SCEVConstant>(S))
6554 return &C->getAPInt();
6555 return nullptr;
6556}
6557
6558/// Determine the range for a particular SCEV. If SignHint is
6559/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6560/// with a "cleaner" unsigned (resp. signed) representation.
6561const ConstantRange &ScalarEvolution::getRangeRef(
6562 const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6563 DenseMap<const SCEV *, ConstantRange> &Cache =
6564 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6565 : SignedRanges;
6567 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6569
6570 // See if we've computed this range already.
6571 auto I = Cache.find(S);
6572 if (I != Cache.end())
6573 return I->second;
6574
6575 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6576 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6577
6578 // Switch to iteratively computing the range for S, if it is part of a deeply
6579 // nested expression.
6580 if (Depth > Opts.scev_range_iter_threshold)
6581 return getRangeRefIter(S, SignHint);
6582
6583 unsigned BitWidth = getTypeSizeInBits(S->getType());
6584 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6585 using OBO = OverflowingBinaryOperator;
6586
6587 // If the value has known zeros, the maximum value will have those known zeros
6588 // as well.
6589 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6590 APInt Multiple = getNonZeroConstantMultiple(S);
6591 APInt Remainder = APInt::getMaxValue(BitWidth).urem(Multiple);
6592 if (!Remainder.isZero())
6593 ConservativeResult =
6594 ConstantRange(APInt::getMinValue(BitWidth),
6595 APInt::getMaxValue(BitWidth) - Remainder + 1);
6596 }
6597 else {
6598 uint32_t TZ = getMinTrailingZeros(S);
6599 if (TZ != 0) {
6600 ConservativeResult = ConstantRange(
6602 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6603 }
6604 }
6605
6606 switch (S->getSCEVType()) {
6607 case scConstant:
6608 llvm_unreachable("Already handled above.");
6609 case scVScale:
6610 return setRange(S, SignHint, getVScaleRange(&F, BitWidth));
6611 case scTruncate: {
6612 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6613 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6614 return setRange(
6615 Trunc, SignHint,
6616 ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6617 }
6618 case scZeroExtend: {
6619 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6620 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6621 return setRange(
6622 ZExt, SignHint,
6623 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6624 }
6625 case scSignExtend: {
6626 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6627 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6628 return setRange(
6629 SExt, SignHint,
6630 ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6631 }
6632 case scPtrToAddr: {
6633 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6634 ConstantRange X = getRangeRef(Cast->getOperand(), SignHint, Depth + 1);
6635 return setRange(Cast, SignHint, X);
6636 }
6637 case scAddExpr: {
6638 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6639 // Check if this is a URem pattern: A - (A / B) * B, which is always < B.
6640 const SCEV *URemLHS = nullptr, *URemRHS = nullptr;
6641 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED &&
6642 match(S, m_scev_URem(m_SCEV(URemLHS), m_SCEV(URemRHS), *this))) {
6643 ConstantRange LHSRange = getRangeRef(URemLHS, SignHint, Depth + 1);
6644 ConstantRange RHSRange = getRangeRef(URemRHS, SignHint, Depth + 1);
6645 ConservativeResult =
6646 ConservativeResult.intersectWith(LHSRange.urem(RHSRange), RangeType);
6647 }
6648 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6649 unsigned WrapType = OBO::AnyWrap;
6650 if (Add->hasNoSignedWrap())
6651 WrapType |= OBO::NoSignedWrap;
6652 if (Add->hasNoUnsignedWrap())
6653 WrapType |= OBO::NoUnsignedWrap;
6654 for (const SCEV *Op : drop_begin(Add->operands()))
6655 X = X.addWithNoWrap(getRangeRef(Op, SignHint, Depth + 1), WrapType,
6656 RangeType);
6657 return setRange(Add, SignHint,
6658 ConservativeResult.intersectWith(X, RangeType));
6659 }
6660 case scMulExpr: {
6661 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6662 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6663 for (const SCEV *Op : drop_begin(Mul->operands()))
6664 X = X.multiply(getRangeRef(Op, SignHint, Depth + 1));
6665 return setRange(Mul, SignHint,
6666 ConservativeResult.intersectWith(X, RangeType));
6667 }
6668 case scUDivExpr: {
6669 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6670 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6671 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6672 return setRange(UDiv, SignHint,
6673 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6674 }
6675 case scAddRecExpr: {
6676 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6677 // If there's no unsigned wrap, the value will never be less than its
6678 // initial value.
6679 if (AddRec->hasNoUnsignedWrap()) {
6680 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6681 if (!UnsignedMinValue.isZero())
6682 ConservativeResult = ConservativeResult.intersectWith(
6683 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6684 }
6685
6686 // If there's no signed wrap, and all the operands except initial value have
6687 // the same sign or zero, the value won't ever be:
6688 // 1: smaller than initial value if operands are non negative,
6689 // 2: bigger than initial value if operands are non positive.
6690 // For both cases, value can not cross signed min/max boundary.
6691 if (AddRec->hasNoSignedWrap()) {
6692 bool AllNonNeg = true;
6693 bool AllNonPos = true;
6694 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6695 if (!isKnownNonNegative(AddRec->getOperand(i)))
6696 AllNonNeg = false;
6697 if (!isKnownNonPositive(AddRec->getOperand(i)))
6698 AllNonPos = false;
6699 }
6700 if (AllNonNeg)
6701 ConservativeResult = ConservativeResult.intersectWith(
6704 RangeType);
6705 else if (AllNonPos)
6706 ConservativeResult = ConservativeResult.intersectWith(
6708 getSignedRangeMax(AddRec->getStart()) +
6709 1),
6710 RangeType);
6711 }
6712
6713 // TODO: non-affine addrec
6714 if (AddRec->isAffine()) {
6715 const SCEV *MaxBEScev =
6717 if (!isa<SCEVCouldNotCompute>(MaxBEScev)) {
6718 APInt MaxBECount = cast<SCEVConstant>(MaxBEScev)->getAPInt();
6719
6720 // Adjust MaxBECount to the same bitwidth as AddRec. We can truncate if
6721 // MaxBECount's active bits are all <= AddRec's bit width.
6722 if (MaxBECount.getBitWidth() > BitWidth &&
6723 MaxBECount.getActiveBits() <= BitWidth)
6724 MaxBECount = MaxBECount.trunc(BitWidth);
6725 else if (MaxBECount.getBitWidth() < BitWidth)
6726 MaxBECount = MaxBECount.zext(BitWidth);
6727
6728 if (MaxBECount.getBitWidth() == BitWidth) {
6729 auto [RangeFromAffine, Flags] = getRangeForAffineAR(
6730 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6731 ConservativeResult =
6732 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6733 const_cast<SCEVAddRecExpr *>(AddRec)->setNoWrapFlags(Flags);
6734
6735 auto RangeFromFactoring = getRangeViaFactoring(
6736 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6737 ConservativeResult =
6738 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6739 }
6740 }
6741
6742 // Now try symbolic BE count and more powerful methods.
6743 if (Opts.scalar_evolution_use_expensive_range_sharpening) {
6744 const SCEV *SymbolicMaxBECount =
6746 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6747 getTypeSizeInBits(MaxBEScev->getType()) <= BitWidth &&
6748 AddRec->hasNoSelfWrap()) {
6749 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6750 AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6751 ConservativeResult =
6752 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6753 }
6754 }
6755 }
6756
6757 return setRange(AddRec, SignHint, std::move(ConservativeResult));
6758 }
6759 case scUMaxExpr:
6760 case scSMaxExpr:
6761 case scUMinExpr:
6762 case scSMinExpr:
6763 case scSequentialUMinExpr: {
6765 switch (S->getSCEVType()) {
6766 case scUMaxExpr:
6767 ID = Intrinsic::umax;
6768 break;
6769 case scSMaxExpr:
6770 ID = Intrinsic::smax;
6771 break;
6772 case scUMinExpr:
6774 ID = Intrinsic::umin;
6775 break;
6776 case scSMinExpr:
6777 ID = Intrinsic::smin;
6778 break;
6779 default:
6780 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6781 }
6782
6783 const auto *NAry = cast<SCEVNAryExpr>(S);
6784 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
6785 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6786 X = X.intrinsic(
6787 ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
6788 return setRange(S, SignHint,
6789 ConservativeResult.intersectWith(X, RangeType));
6790 }
6791 case scUnknown: {
6792 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6793 Value *V = U->getValue();
6794
6795 // Check if the IR explicitly contains !range metadata.
6796 std::optional<ConstantRange> MDRange = GetRangeFromMetadata(V);
6797 if (MDRange)
6798 ConservativeResult =
6799 ConservativeResult.intersectWith(*MDRange, RangeType);
6800
6801 // Use facts about recurrences in the underlying IR. Note that add
6802 // recurrences are AddRecExprs and thus don't hit this path. This
6803 // primarily handles shift recurrences.
6804 auto CR = getRangeForUnknownRecurrence(U);
6805 ConservativeResult = ConservativeResult.intersectWith(CR);
6806
6807 // See if ValueTracking can give us a useful range.
6808 const DataLayout &DL = getDataLayout();
6809 KnownBits Known = computeKnownBits(V, DL, &AC, nullptr, &DT);
6810 if (Known.getBitWidth() != BitWidth)
6811 Known = Known.zextOrTrunc(BitWidth);
6812
6813 // ValueTracking may be able to compute a tighter result for the number of
6814 // sign bits than for the value of those sign bits.
6815 unsigned NS = computeNumSignBits(V, DL, &AC, nullptr, &DT);
6816 if (U->getType()->isPointerTy()) {
6817 // NS counts the sign bits of the whole pointer; drop those above the
6818 // index bits.
6819 unsigned PtrIdxDiff =
6820 DL.getPointerTypeSizeInBits(U->getType()) - BitWidth;
6821 NS = NS > PtrIdxDiff ? NS - PtrIdxDiff : 1;
6822 }
6823
6824 if (NS > 1) {
6825 // If we know any of the sign bits, we know all of the sign bits.
6826 if (!Known.Zero.getHiBits(NS).isZero())
6827 Known.Zero.setHighBits(NS);
6828 if (!Known.One.getHiBits(NS).isZero())
6829 Known.One.setHighBits(NS);
6830 }
6831
6832 if (Known.getMinValue() != Known.getMaxValue() + 1)
6833 ConservativeResult = ConservativeResult.intersectWith(
6834 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6835 RangeType);
6836 if (NS > 1)
6837 ConservativeResult = ConservativeResult.intersectWith(
6838 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6839 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6840 RangeType);
6841
6842 if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
6843 // Strengthen the range if the underlying IR value is a
6844 // global/alloca/heap allocation using the size of the object.
6845 bool CanBeNull;
6846 uint64_t DerefBytes = V->getPointerDereferenceableBytes(
6847 DL, CanBeNull, /*CanBeFreed=*/nullptr);
6848 if (DerefBytes > 1 && isUIntN(BitWidth, DerefBytes)) {
6849 // The highest address the object can start is DerefBytes bytes before
6850 // the end (unsigned max value). If this value is not a multiple of the
6851 // alignment, the last possible start value is the next lowest multiple
6852 // of the alignment. Note: The computations below cannot overflow,
6853 // because if they would there's no possible start address for the
6854 // object.
6855 APInt MaxVal =
6856 APInt::getMaxValue(BitWidth) - APInt(BitWidth, DerefBytes);
6857 uint64_t Align = U->getValue()->getPointerAlignment(DL).value();
6858 uint64_t Rem = MaxVal.urem(Align);
6859 MaxVal -= APInt(BitWidth, Rem);
6860 APInt MinVal = APInt::getZero(BitWidth);
6861 if (llvm::isKnownNonZero(V, DL))
6862 MinVal = Align;
6863 ConservativeResult = ConservativeResult.intersectWith(
6864 ConstantRange::getNonEmpty(MinVal, MaxVal + 1), RangeType);
6865 }
6866 }
6867
6868 // A range of Phi is a subset of union of all ranges of its input.
6869 if (PHINode *Phi = dyn_cast<PHINode>(V)) {
6870 // SCEVExpander sometimes creates SCEVUnknowns that are secretly
6871 // AddRecs; return the range for the corresponding AddRec.
6872 if (auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V)))
6873 return getRangeRef(AR, SignHint, Depth + 1);
6874
6875 // Make sure that we do not run over cycled Phis.
6876 if (RangeRefPHIAllowedOperands(DT, Phi)) {
6877 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6878
6879 for (const auto &Op : Phi->operands()) {
6880 auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
6881 RangeFromOps = RangeFromOps.unionWith(OpRange, RangeType);
6882 // No point to continue if we already have a full set.
6883 if (RangeFromOps.isFullSet())
6884 break;
6885 }
6886 ConservativeResult =
6887 ConservativeResult.intersectWith(RangeFromOps, RangeType);
6888 }
6889 }
6890
6891 const APInt *TrueC, *FalseC;
6892 if (match(V, m_Select(m_Value(), m_APInt(TrueC), m_APInt(FalseC))))
6893 ConservativeResult = ConservativeResult.intersectWith(
6894 ConstantRange(*TrueC).unionWith(*FalseC, RangeType), RangeType);
6895
6896 // vscale can't be equal to zero
6897 if (const auto *II = dyn_cast<IntrinsicInst>(V))
6898 if (II->getIntrinsicID() == Intrinsic::vscale) {
6899 ConstantRange Disallowed = APInt::getZero(BitWidth);
6900 ConservativeResult = ConservativeResult.difference(Disallowed);
6901 }
6902
6903 return setRange(U, SignHint, std::move(ConservativeResult));
6904 }
6905 case scCouldNotCompute:
6906 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6907 }
6908
6909 return setRange(S, SignHint, std::move(ConservativeResult));
6910}
6911
6912// Given a StartRange, Step and MaxBECount for an expression compute a range of
6913// values that the expression can take. Initially, the expression has a value
6914// from StartRange and then is changed by Step up to MaxBECount times. Signed
6915// argument defines if we treat Step as signed or unsigned. The second return
6916// value indicates that no wrapping occurred.
6917static std::pair<ConstantRange, bool>
6919 const APInt &MaxBECount, bool Signed) {
6920 unsigned BitWidth = Step.getBitWidth();
6921 assert(BitWidth == StartRange.getBitWidth() &&
6922 BitWidth == MaxBECount.getBitWidth() && "mismatched bit widths");
6923 // If either Step or MaxBECount is 0, then the expression won't change, and we
6924 // just need to return the initial range.
6925 if (Step == 0 || MaxBECount == 0)
6926 return {StartRange, true};
6927
6928 // If we don't know anything about the initial value (i.e. StartRange is
6929 // FullRange), then we don't know anything about the final range either.
6930 // Return FullRange.
6931 if (StartRange.isFullSet())
6932 return {ConstantRange::getFull(BitWidth), false};
6933
6934 // If Step is signed and negative, then we use its absolute value, but we also
6935 // note that we're moving in the opposite direction.
6936 bool Descending = Signed && Step.isNegative();
6937
6938 if (Signed)
6939 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
6940 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
6941 // This equations hold true due to the well-defined wrap-around behavior of
6942 // APInt.
6943 Step = Step.abs();
6944
6945 // Check if Offset is more than full span of BitWidth. If it is, the
6946 // expression is guaranteed to overflow.
6947 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
6948 return {ConstantRange::getFull(BitWidth), false};
6949
6950 // Offset is by how much the expression can change. Checks above guarantee no
6951 // overflow here.
6952 APInt Offset = Step * MaxBECount;
6953
6954 // Minimum value of the final range will match the minimal value of StartRange
6955 // if the expression is increasing and will be decreased by Offset otherwise.
6956 // Maximum value of the final range will match the maximal value of StartRange
6957 // if the expression is decreasing and will be increased by Offset otherwise.
6958 APInt StartLower = StartRange.getLower();
6959 APInt StartUpper = StartRange.getUpper() - 1;
6960 bool Overflow;
6961 APInt MovedBoundary;
6962 if (Signed) {
6963 // This does not use sadd_ov, as we want to check overflow for a signed
6964 // start with an unsigned offset.
6965 if (Descending) {
6966 MovedBoundary = StartLower - std::move(Offset);
6967 Overflow = MovedBoundary.sgt(StartLower) || StartRange.isSignWrappedSet();
6968 } else {
6969 MovedBoundary = StartUpper + std::move(Offset);
6970 Overflow = MovedBoundary.slt(StartUpper) || StartRange.isSignWrappedSet();
6971 }
6972 } else {
6973 MovedBoundary = StartUpper.uadd_ov(std::move(Offset), Overflow);
6974 Overflow |= StartRange.isWrappedSet();
6975 }
6976
6977 // It's possible that the new minimum/maximum value will fall into the initial
6978 // range (due to wrap around). This means that the expression can take any
6979 // value in this bitwidth, and we have to return full range.
6980 if (StartRange.contains(MovedBoundary))
6981 return {ConstantRange::getFull(BitWidth), false};
6982
6983 APInt NewLower =
6984 Descending ? std::move(MovedBoundary) : std::move(StartLower);
6985 APInt NewUpper =
6986 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
6987 NewUpper += 1;
6988
6989 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
6990 return {ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)),
6991 !Overflow};
6992}
6993
6994std::pair<ConstantRange, SCEVFlags>
6995ScalarEvolution::getRangeForAffineAR(const SCEV *Start, const SCEV *Step,
6996 const APInt &MaxBECount) {
6997 assert(getTypeSizeInBits(Start->getType()) ==
6998 getTypeSizeInBits(Step->getType()) &&
6999 getTypeSizeInBits(Start->getType()) == MaxBECount.getBitWidth() &&
7000 "mismatched bit widths");
7001
7002 // First, consider step signed.
7003 ConstantRange StartSRange = getSignedRange(Start);
7004 ConstantRange StepSRange = getSignedRange(Step);
7005
7006 // If Step can be both positive and negative, we need to find ranges for the
7007 // maximum absolute step values in both directions and union them.
7008 auto [SR, NSW] = getRangeForAffineARHelper(
7009 StepSRange.getSignedMin(), StartSRange, MaxBECount, /*Signed=*/true);
7010 // A singleton step has identical signed bounds, so the second computation
7011 // would produce the same range and no-wrap result.
7012 if (!StepSRange.isSingleElement()) {
7013 auto [SRMax, NSWMax] = getRangeForAffineARHelper(
7014 StepSRange.getSignedMax(), StartSRange, MaxBECount, /*Signed=*/true);
7015 SR = SR.unionWith(SRMax);
7016 NSW &= NSWMax;
7017 }
7018
7019 // Next, consider step unsigned.
7020 auto [UR, NUW] = getRangeForAffineARHelper(
7021 getUnsignedRangeMax(Step), getUnsignedRange(Start), MaxBECount,
7022 /*Signed=*/false);
7023
7025 if (NUW)
7027 if (NSW)
7029
7030 // Finally, intersect signed and unsigned ranges.
7031 return {SR.intersectWith(UR, ConstantRange::Smallest), Flags};
7032}
7033
7034ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
7035 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
7036 ScalarEvolution::RangeSignHint SignHint) {
7037 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
7038 assert(AddRec->hasNoSelfWrap() &&
7039 "This only works for non-self-wrapping AddRecs!");
7040 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
7041 const SCEV *Step = AddRec->getStepRecurrence(*this);
7042 // Only deal with constant step to save compile time.
7043 if (!isa<SCEVConstant>(Step))
7044 return ConstantRange::getFull(BitWidth);
7045 // Let's make sure that we can prove that we do not self-wrap during
7046 // MaxBECount iterations. We need this because MaxBECount is a maximum
7047 // iteration count estimate, and we might infer nw from some exit for which we
7048 // do not know max exit count (or any other side reasoning).
7049 // TODO: Turn into assert at some point.
7050 if (getTypeSizeInBits(MaxBECount->getType()) >
7051 getTypeSizeInBits(AddRec->getType()))
7052 return ConstantRange::getFull(BitWidth);
7053 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
7054 const SCEV *RangeWidth = getMinusOne(AddRec->getType());
7055 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
7056 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
7057 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
7058 MaxItersWithoutWrap))
7059 return ConstantRange::getFull(BitWidth);
7060
7061 ICmpInst::Predicate LEPred =
7063 ICmpInst::Predicate GEPred =
7065 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7066
7067 // We know that there is no self-wrap. Let's take Start and End values and
7068 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7069 // the iteration. They either lie inside the range [Min(Start, End),
7070 // Max(Start, End)] or outside it:
7071 //
7072 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
7073 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
7074 //
7075 // No self wrap flag guarantees that the intermediate values cannot be BOTH
7076 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7077 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7078 // Start <= End and step is positive, or Start >= End and step is negative.
7079 const SCEV *Start = applyLoopGuards(AddRec->getStart(), AddRec->getLoop());
7080 ConstantRange StartRange = getRangeRef(Start, SignHint);
7081 ConstantRange EndRange = getRangeRef(End, SignHint);
7082 ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7083 // If they already cover full iteration space, we will know nothing useful
7084 // even if we prove what we want to prove.
7085 if (RangeBetween.isFullSet())
7086 return RangeBetween;
7087 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7088 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7089 : RangeBetween.isWrappedSet();
7090 if (IsWrappedSet)
7091 return ConstantRange::getFull(BitWidth);
7092
7093 if (isKnownPositive(Step) &&
7094 isKnownPredicateViaConstantRanges(LEPred, Start, End))
7095 return RangeBetween;
7096 if (isKnownNegative(Step) &&
7097 isKnownPredicateViaConstantRanges(GEPred, Start, End))
7098 return RangeBetween;
7099 return ConstantRange::getFull(BitWidth);
7100}
7101
7102ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7103 const SCEV *Step,
7104 const APInt &MaxBECount) {
7105 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7106 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7107
7108 unsigned BitWidth = MaxBECount.getBitWidth();
7109 assert(getTypeSizeInBits(Start->getType()) == BitWidth &&
7110 getTypeSizeInBits(Step->getType()) == BitWidth &&
7111 "mismatched bit widths");
7112
7113 struct SelectPattern {
7114 Value *Condition = nullptr;
7115 APInt TrueValue;
7116 APInt FalseValue;
7117
7118 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7119 const SCEV *S) {
7120 std::optional<unsigned> CastOp;
7121 APInt Offset(BitWidth, 0);
7122
7124 "Should be!");
7125
7126 // Peel off a constant offset. In the future we could consider being
7127 // smarter here and handle {Start+Step,+,Step} too.
7128 const APInt *Off;
7129 if (match(S, m_scev_Add(m_scev_APInt(Off), m_SCEV(S))))
7130 Offset = *Off;
7131
7132 // Peel off a cast operation
7133 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7134 CastOp = SCast->getSCEVType();
7135 S = SCast->getOperand();
7136 }
7137
7138 using namespace llvm::PatternMatch;
7139
7140 auto *SU = dyn_cast<SCEVUnknown>(S);
7141 const APInt *TrueVal, *FalseVal;
7142 if (!SU ||
7143 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7144 m_APInt(FalseVal)))) {
7145 Condition = nullptr;
7146 return;
7147 }
7148
7149 TrueValue = *TrueVal;
7150 FalseValue = *FalseVal;
7151
7152 // Re-apply the cast we peeled off earlier
7153 if (CastOp)
7154 switch (*CastOp) {
7155 default:
7156 llvm_unreachable("Unknown SCEV cast type!");
7157
7158 case scTruncate:
7159 TrueValue = TrueValue.trunc(BitWidth);
7160 FalseValue = FalseValue.trunc(BitWidth);
7161 break;
7162 case scZeroExtend:
7163 TrueValue = TrueValue.zext(BitWidth);
7164 FalseValue = FalseValue.zext(BitWidth);
7165 break;
7166 case scSignExtend:
7167 TrueValue = TrueValue.sext(BitWidth);
7168 FalseValue = FalseValue.sext(BitWidth);
7169 break;
7170 }
7171
7172 // Re-apply the constant offset we peeled off earlier
7173 TrueValue += Offset;
7174 FalseValue += Offset;
7175 }
7176
7177 bool isRecognized() { return Condition != nullptr; }
7178 };
7179
7180 SelectPattern StartPattern(*this, BitWidth, Start);
7181 if (!StartPattern.isRecognized())
7182 return ConstantRange::getFull(BitWidth);
7183
7184 SelectPattern StepPattern(*this, BitWidth, Step);
7185 if (!StepPattern.isRecognized())
7186 return ConstantRange::getFull(BitWidth);
7187
7188 if (StartPattern.Condition != StepPattern.Condition) {
7189 // We don't handle this case today; but we could, by considering four
7190 // possibilities below instead of two. I'm not sure if there are cases where
7191 // that will help over what getRange already does, though.
7192 return ConstantRange::getFull(BitWidth);
7193 }
7194
7195 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7196 // construct arbitrary general SCEV expressions here. This function is called
7197 // from deep in the call stack, and calling getSCEV (on a sext instruction,
7198 // say) can end up caching a suboptimal value.
7199
7200 // FIXME: without the explicit `this` receiver below, MSVC errors out with
7201 // C2352 and C2512 (otherwise it isn't needed).
7202
7203 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7204 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7205 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7206 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7207
7208 ConstantRange TrueRange =
7209 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount).first;
7210 ConstantRange FalseRange =
7211 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount).first;
7212
7213 return TrueRange.unionWith(FalseRange);
7214}
7215
7216SCEVFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7217 if (isa<ConstantExpr>(V))
7218 return SCEV::FlagNone;
7219 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7220
7221 // Return early if there are no flags to propagate to the SCEV.
7223 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(BinOp);
7224 PDI && PDI->isDisjoint()) {
7226 } else {
7227 if (BinOp->hasNoUnsignedWrap())
7229 if (BinOp->hasNoSignedWrap())
7231 }
7232 if (Flags == SCEV::FlagNone)
7233 return SCEV::FlagNone;
7234
7235 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagNone;
7236}
7237
7238const Instruction *
7239ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7240 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7241 return &*AddRec->getLoop()->getHeader()->begin();
7242 if (auto *U = dyn_cast<SCEVUnknown>(S))
7243 if (auto *I = dyn_cast<Instruction>(U->getValue()))
7244 return I;
7245 return nullptr;
7246}
7247
7248const Instruction *ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops,
7249 bool &Precise) {
7250 Precise = true;
7251 // Do a bounded search of the def relation of the requested SCEVs.
7252 SmallPtrSet<const SCEV *, 16> Visited;
7253 SmallVector<SCEVUse> Worklist;
7254 auto pushOp = [&](const SCEV *S) {
7255 if (!Visited.insert(S).second)
7256 return;
7257 // Threshold of 30 here is arbitrary.
7258 if (Visited.size() > 30) {
7259 Precise = false;
7260 return;
7261 }
7262 Worklist.push_back(S);
7263 };
7264
7265 for (SCEVUse S : Ops)
7266 pushOp(S);
7267
7268 const Instruction *Bound = nullptr;
7269 while (!Worklist.empty()) {
7270 SCEVUse S = Worklist.pop_back_val();
7271 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7272 if (!Bound || DT.dominates(Bound, DefI))
7273 Bound = DefI;
7274 } else {
7275 for (SCEVUse Op : S->operands())
7276 pushOp(Op);
7277 }
7278 }
7279 return Bound ? Bound : &*F.getEntryBlock().begin();
7280}
7281
7282const Instruction *
7283ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops) {
7284 bool Discard;
7285 return getDefiningScopeBound(Ops, Discard);
7286}
7287
7288bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7289 const Instruction *B) {
7290 if (A->getParent() == B->getParent() &&
7292 B->getIterator()))
7293 return true;
7294
7295 auto *BLoop = LI.getLoopFor(B->getParent());
7296 if (BLoop && BLoop->getHeader() == B->getParent() &&
7297 BLoop->getLoopPreheader() == A->getParent() &&
7299 A->getParent()->end()) &&
7300 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7301 B->getIterator()))
7302 return true;
7303 return false;
7304}
7305
7307 // Use flags only hold where the expression is used, so Op may be poison
7308 // elsewhere if it or any of its operands carries them.
7309 if (Op->getCanonical() != Op)
7310 return false;
7311 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ true);
7312 visitAll(Op, PC);
7313 return PC.MaybePoison.empty();
7314}
7315
7317 return !SCEVExprContains(Op, [this](const SCEV *S) {
7318 const SCEV *Op1;
7319 bool M = match(S, m_scev_UDiv(m_SCEV(), m_SCEV(Op1)));
7320 // The UDiv may be UB if the divisor is poison or zero. Unless the divisor
7321 // is a non-zero constant, we have to assume the UDiv may be UB.
7322 return M && (!isKnownNonZero(Op1) || !isGuaranteedNotToBePoison(Op1));
7323 });
7324}
7325
7326bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7327 // Only proceed if we can prove that I does not yield poison.
7329 return false;
7330
7331 // At this point we know that if I is executed, then it does not wrap
7332 // according to at least one of NSW or NUW. If I is not executed, then we do
7333 // not know if the calculation that I represents would wrap. Multiple
7334 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7335 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7336 // derived from other instructions that map to the same SCEV. We cannot make
7337 // that guarantee for cases where I is not executed. So we need to find a
7338 // upper bound on the defining scope for the SCEV, and prove that I is
7339 // executed every time we enter that scope. When the bounding scope is a
7340 // loop (the common case), this is equivalent to proving I executes on every
7341 // iteration of that loop.
7342 SmallVector<SCEVUse> SCEVOps;
7343 for (const Use &Op : I->operands()) {
7344 // I could be an extractvalue from a call to an overflow intrinsic.
7345 // TODO: We can do better here in some cases.
7346 if (isSCEVable(Op->getType()))
7347 SCEVOps.push_back(getSCEV(Op));
7348 }
7349 auto *DefI = getDefiningScopeBound(SCEVOps);
7350 return isGuaranteedToTransferExecutionTo(DefI, I);
7351}
7352
7353bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7354 // If we know that \c I can never be poison period, then that's enough.
7355 if (isSCEVExprNeverPoison(I))
7356 return true;
7357
7358 // If the loop only has one exit, then we know that, if the loop is entered,
7359 // any instruction dominating that exit will be executed. If any such
7360 // instruction would result in UB, the addrec cannot be poison.
7361 //
7362 // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7363 // also handles uses outside the loop header (they just need to dominate the
7364 // single exit).
7365
7366 auto *ExitingBB = L->getExitingBlock();
7367 if (!ExitingBB || !loopHasNoAbnormalExits(L))
7368 return false;
7369
7370 SmallPtrSet<const Value *, 16> KnownPoison;
7372
7373 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
7374 // things that are known to be poison under that assumption go on the
7375 // Worklist.
7376 KnownPoison.insert(I);
7377 Worklist.push_back(I);
7378
7379 while (!Worklist.empty()) {
7380 const Instruction *Poison = Worklist.pop_back_val();
7381
7382 for (const Use &U : Poison->uses()) {
7383 const Instruction *PoisonUser = cast<Instruction>(U.getUser());
7384 if (mustTriggerUB(PoisonUser, KnownPoison) &&
7385 DT.dominates(PoisonUser->getParent(), ExitingBB))
7386 return true;
7387
7388 if (propagatesPoison(U) && L->contains(PoisonUser))
7389 if (KnownPoison.insert(PoisonUser).second)
7390 Worklist.push_back(PoisonUser);
7391 }
7392 }
7393
7394 return false;
7395}
7396
7397ScalarEvolution::LoopProperties
7398ScalarEvolution::getLoopProperties(const Loop *L) {
7399 using LoopProperties = ScalarEvolution::LoopProperties;
7400
7401 auto Itr = LoopPropertiesCache.find(L);
7402 if (Itr == LoopPropertiesCache.end()) {
7403 auto HasSideEffects = [](Instruction *I) {
7404 if (auto *SI = dyn_cast<StoreInst>(I))
7405 return !SI->isSimple();
7406
7407 if (I->mayThrow())
7408 return true;
7409
7410 // Non-volatile memset / memcpy do not count as side-effect for forward
7411 // progress.
7412 if (auto *MI = dyn_cast<MemIntrinsic>(I))
7413 if (!MI->isVolatile())
7414 return false;
7415
7416 // Droppable intrinsics only model a memory write; they are not progress.
7417 if (I->isDroppable())
7418 return false;
7419
7420 return I->mayWriteToMemory();
7421 };
7422
7423 LoopProperties LP = {/* HasNoAbnormalExits */ true,
7424 /*HasNoSideEffects*/ true};
7425
7426 for (auto *BB : L->getBlocks())
7427 for (auto &I : *BB) {
7429 LP.HasNoAbnormalExits = false;
7430 if (HasSideEffects(&I))
7431 LP.HasNoSideEffects = false;
7432 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7433 break; // We're already as pessimistic as we can get.
7434 }
7435
7436 auto InsertPair = LoopPropertiesCache.insert({L, LP});
7437 assert(InsertPair.second && "We just checked!");
7438 Itr = InsertPair.first;
7439 }
7440
7441 return Itr->second;
7442}
7443
7445 // A mustprogress loop without side effects must be finite.
7446 // TODO: The check used here is very conservative. It's only *specific*
7447 // side effects which are well defined in infinite loops.
7448 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7449}
7450
7451const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7452 // Worklist item with a Value and a bool indicating whether all operands have
7453 // been visited already.
7456
7457 Stack.emplace_back(V, false);
7458 while (!Stack.empty()) {
7459 auto E = Stack.back();
7460 Value *CurV = E.getPointer();
7461
7462 if (getExistingSCEV(CurV)) {
7463 Stack.pop_back();
7464 continue;
7465 }
7466
7468 const SCEV *CreatedSCEV = nullptr;
7469 // If all operands have been visited already, create the SCEV.
7470 if (E.getInt()) {
7471 CreatedSCEV = createSCEV(CurV);
7472 } else {
7473 // Otherwise get the operands we need to create SCEV's for before creating
7474 // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7475 // just use it.
7476 CreatedSCEV = getOperandsToCreate(CurV, Ops);
7477 }
7478
7479 if (CreatedSCEV) {
7480 insertValueToMap(CurV, CreatedSCEV);
7481 Stack.pop_back();
7482 } else {
7483 Stack.back().setInt(true);
7484 // Queue its operands which need to be constructed.
7485 for (Value *Op : Ops)
7486 Stack.emplace_back(Op, false);
7487 }
7488 }
7489
7490 return getExistingSCEV(V);
7491}
7492
7493const SCEV *
7494ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7495 if (!isSCEVable(V->getType()))
7496 return getUnknown(V);
7497
7498 if (Instruction *I = dyn_cast<Instruction>(V)) {
7499 // Don't attempt to analyze instructions in blocks that aren't
7500 // reachable. Such instructions don't matter, and they aren't required
7501 // to obey basic rules for definitions dominating uses which this
7502 // analysis depends on.
7503 if (!DT.isReachableFromEntry(I->getParent()))
7504 return getUnknown(PoisonValue::get(V->getType()));
7505 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7506 return getConstant(CI);
7507 else if (isa<GlobalAlias>(V))
7508 return getUnknown(V);
7509 else if (!isa<ConstantExpr>(V))
7510 return getUnknown(V);
7511
7513 if (auto BO = MatchBinaryOp(U, DT)) {
7514 bool IsConstArg = isa<ConstantInt>(BO->RHS);
7515 switch (BO->Opcode) {
7516 case Instruction::Add:
7517 case Instruction::Mul: {
7518 // For additions and multiplications, traverse add/mul chains for which we
7519 // can potentially create a single SCEV, to reduce the number of
7520 // get{Add,Mul}Expr calls.
7521 do {
7522 if (BO->Op) {
7523 if (BO->Op != V && getExistingSCEV(BO->Op)) {
7524 Ops.push_back(BO->Op);
7525 break;
7526 }
7527 }
7528 Ops.push_back(BO->RHS);
7529 auto NewBO = MatchBinaryOp(BO->LHS, DT);
7530 if (!NewBO ||
7531 (BO->Opcode == Instruction::Add &&
7532 (NewBO->Opcode != Instruction::Add &&
7533 NewBO->Opcode != Instruction::Sub)) ||
7534 (BO->Opcode == Instruction::Mul &&
7535 NewBO->Opcode != Instruction::Mul)) {
7536 Ops.push_back(BO->LHS);
7537 break;
7538 }
7539 // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7540 // requires a SCEV for the LHS.
7541 if (BO->Op && (BO->IsNSW || BO->IsNUW)) {
7542 auto *I = dyn_cast<Instruction>(BO->Op);
7543 if (I && programUndefinedIfPoison(I)) {
7544 Ops.push_back(BO->LHS);
7545 break;
7546 }
7547 }
7548 BO = NewBO;
7549 } while (true);
7550 return nullptr;
7551 }
7552 case Instruction::Sub:
7553 case Instruction::UDiv:
7554 case Instruction::URem:
7555 break;
7556 case Instruction::AShr:
7557 case Instruction::Shl:
7558 case Instruction::Xor:
7559 if (!IsConstArg)
7560 return nullptr;
7561 break;
7562 case Instruction::And:
7563 case Instruction::Or:
7564 if (!IsConstArg && !BO->LHS->getType()->isIntegerTy(1))
7565 return nullptr;
7566 break;
7567 case Instruction::LShr:
7568 return getUnknown(V);
7569 default:
7570 llvm_unreachable("Unhandled binop");
7571 break;
7572 }
7573
7574 Ops.push_back(BO->LHS);
7575 Ops.push_back(BO->RHS);
7576 return nullptr;
7577 }
7578
7579 switch (U->getOpcode()) {
7580 case Instruction::Trunc:
7581 case Instruction::ZExt:
7582 case Instruction::SExt:
7583 case Instruction::PtrToAddr:
7584 case Instruction::PtrToInt:
7585 Ops.push_back(U->getOperand(0));
7586 return nullptr;
7587
7588 case Instruction::BitCast:
7589 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
7590 Ops.push_back(U->getOperand(0));
7591 return nullptr;
7592 }
7593 return getUnknown(V);
7594
7595 case Instruction::SDiv:
7596 case Instruction::SRem:
7597 Ops.push_back(U->getOperand(0));
7598 Ops.push_back(U->getOperand(1));
7599 return nullptr;
7600
7601 case Instruction::GetElementPtr:
7602 assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7603 "GEP source element type must be sized");
7604 llvm::append_range(Ops, U->operands());
7605 return nullptr;
7606
7607 case Instruction::IntToPtr:
7608 return getUnknown(V);
7609
7610 case Instruction::PHI:
7611 // getNodeForPHI has four ways to turn a PHI into a SCEV; retrieve the
7612 // relevant nodes for each of them.
7613 //
7614 // The first is just to call simplifyInstruction, and get something back
7615 // that isn't a PHI.
7617 cast<PHINode>(U),
7618 {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
7619 /*UseInstrInfo=*/true, /*CanUseUndef=*/false})) {
7620 assert(V);
7621 Ops.push_back(V);
7622 return nullptr;
7623 }
7624 // The second is createNodeForPHIWithIdenticalOperands: this looks for
7625 // operands which all perform the same operation, but haven't been
7626 // CSE'ed for whatever reason.
7627 if (BinaryOperator *BO = getCommonInstForPHI(cast<PHINode>(U))) {
7628 assert(BO);
7629 Ops.push_back(BO);
7630 return nullptr;
7631 }
7632 // The third is createNodeFromSelectLikePHI; this takes a PHI which
7633 // is equivalent to a select, and analyzes it like a select.
7634 {
7635 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
7637 assert(Cond);
7638 assert(LHS);
7639 assert(RHS);
7640 if (auto *CondICmp = dyn_cast<ICmpInst>(Cond)) {
7641 Ops.push_back(CondICmp->getOperand(0));
7642 Ops.push_back(CondICmp->getOperand(1));
7643 }
7644 Ops.push_back(Cond);
7645 Ops.push_back(LHS);
7646 Ops.push_back(RHS);
7647 return nullptr;
7648 }
7649 }
7650 // The fourth way is createAddRecFromPHI. It's complicated to handle here,
7651 // so just construct it recursively.
7652 //
7653 // In addition to getNodeForPHI, also construct nodes which might be needed
7654 // by getRangeRef.
7656 for (Value *V : cast<PHINode>(U)->operands())
7657 Ops.push_back(V);
7658 return nullptr;
7659 }
7660 return nullptr;
7661
7662 case Instruction::Select: {
7663 // Check if U is a select that can be simplified to a SCEVUnknown.
7664 auto CanSimplifyToUnknown = [this, U]() {
7665 if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
7666 return false;
7667
7668 auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
7669 if (!ICI)
7670 return false;
7671 Value *LHS = ICI->getOperand(0);
7672 Value *RHS = ICI->getOperand(1);
7673 if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7674 ICI->getPredicate() == CmpInst::ICMP_NE) {
7676 return true;
7677 } else if (getTypeSizeInBits(LHS->getType()) >
7678 getTypeSizeInBits(U->getType()))
7679 return true;
7680 return false;
7681 };
7682 if (CanSimplifyToUnknown())
7683 return getUnknown(U);
7684
7685 llvm::append_range(Ops, U->operands());
7686 return nullptr;
7687 break;
7688 }
7689 case Instruction::Call:
7690 case Instruction::Invoke:
7691 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7692 Ops.push_back(RV);
7693 return nullptr;
7694 }
7695
7696 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7697 switch (II->getIntrinsicID()) {
7698 case Intrinsic::abs:
7699 Ops.push_back(II->getArgOperand(0));
7700 return nullptr;
7701 case Intrinsic::umax:
7702 case Intrinsic::umin:
7703 case Intrinsic::smax:
7704 case Intrinsic::smin:
7705 case Intrinsic::usub_sat:
7706 case Intrinsic::uadd_sat:
7707 Ops.push_back(II->getArgOperand(0));
7708 Ops.push_back(II->getArgOperand(1));
7709 return nullptr;
7710 case Intrinsic::start_loop_iterations:
7711 case Intrinsic::annotation:
7712 case Intrinsic::ptr_annotation:
7713 Ops.push_back(II->getArgOperand(0));
7714 return nullptr;
7715 default:
7716 break;
7717 }
7718 }
7719 break;
7720 }
7721
7722 return nullptr;
7723}
7724
7725const SCEV *ScalarEvolution::createSCEV(Value *V) {
7726 if (!isSCEVable(V->getType()))
7727 return getUnknown(V);
7728
7729 if (Instruction *I = dyn_cast<Instruction>(V)) {
7730 // Don't attempt to analyze instructions in blocks that aren't
7731 // reachable. Such instructions don't matter, and they aren't required
7732 // to obey basic rules for definitions dominating uses which this
7733 // analysis depends on.
7734 if (!DT.isReachableFromEntry(I->getParent()))
7735 return getUnknown(PoisonValue::get(V->getType()));
7736 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7737 return getConstant(CI);
7738 else if (isa<GlobalAlias>(V))
7739 return getUnknown(V);
7740 else if (!isa<ConstantExpr>(V))
7741 return getUnknown(V);
7742
7743 const SCEV *LHS;
7744 const SCEV *RHS;
7745
7747 if (auto BO = MatchBinaryOp(U, DT)) {
7748 switch (BO->Opcode) {
7749 case Instruction::Add: {
7750 // The simple thing to do would be to just call getSCEV on both operands
7751 // and call getAddExpr with the result. However if we're looking at a
7752 // bunch of things all added together, this can be quite inefficient,
7753 // because it leads to N-1 getAddExpr calls for N ultimate operands.
7754 // Instead, gather up all the operands and make a single getAddExpr call.
7755 // LLVM IR canonical form means we need only traverse the left operands.
7757 do {
7758 if (BO->Op) {
7759 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7760 AddOps.push_back(OpSCEV);
7761 break;
7762 }
7763
7764 // If a NUW or NSW flag can be applied to the SCEV for this
7765 // addition, then compute the SCEV for this addition by itself
7766 // with a separate call to getAddExpr. We need to do that
7767 // instead of pushing the operands of the addition onto AddOps,
7768 // since the flags are only known to apply to this particular
7769 // addition - they may not apply to other additions that can be
7770 // formed with operands from AddOps.
7771 const SCEV *RHS = getSCEV(BO->RHS);
7772 SCEVFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7773 if (Flags != SCEV::FlagNone) {
7774 const SCEV *LHS = getSCEV(BO->LHS);
7775 if (BO->Opcode == Instruction::Sub)
7776 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7777 else
7778 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7779 break;
7780 }
7781 }
7782
7783 if (BO->Opcode == Instruction::Sub)
7784 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7785 else
7786 AddOps.push_back(getSCEV(BO->RHS));
7787
7788 auto NewBO = MatchBinaryOp(BO->LHS, DT);
7789 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7790 NewBO->Opcode != Instruction::Sub)) {
7791 AddOps.push_back(getSCEV(BO->LHS));
7792 break;
7793 }
7794 BO = NewBO;
7795 } while (true);
7796
7797 return getAddExpr(AddOps);
7798 }
7799
7800 case Instruction::Mul: {
7802 do {
7803 if (BO->Op) {
7804 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7805 MulOps.push_back(OpSCEV);
7806 break;
7807 }
7808
7809 SCEVFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7810 if (Flags != SCEV::FlagNone) {
7811 LHS = getSCEV(BO->LHS);
7812 RHS = getSCEV(BO->RHS);
7813 MulOps.push_back(getMulExpr(LHS, RHS, Flags));
7814 break;
7815 }
7816 }
7817
7818 MulOps.push_back(getSCEV(BO->RHS));
7819 auto NewBO = MatchBinaryOp(BO->LHS, DT);
7820 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7821 MulOps.push_back(getSCEV(BO->LHS));
7822 break;
7823 }
7824 BO = NewBO;
7825 } while (true);
7826
7827 return getMulExpr(MulOps);
7828 }
7829 case Instruction::UDiv:
7830 LHS = getSCEV(BO->LHS);
7831 RHS = getSCEV(BO->RHS);
7832 return getUDivExpr(LHS, RHS);
7833 case Instruction::URem:
7834 LHS = getSCEV(BO->LHS);
7835 RHS = getSCEV(BO->RHS);
7836 return getURemExpr(LHS, RHS);
7837 case Instruction::Sub: {
7839 if (BO->Op)
7840 Flags = getNoWrapFlagsFromUB(BO->Op);
7841
7842 // Try to use ptrtoaddr for subtracts with at least one ptrtoint
7843 // operand. While we don't model ptrtoint directly in SCEV, the
7844 // difference between two pointer addresses is well-defined.
7845 Value *PtrLHS = nullptr, *PtrRHS = nullptr;
7846 bool HasPtrLHS = match(BO->LHS, m_PtrToInt(m_Value(PtrLHS)));
7847 bool HasPtrRHS = match(BO->RHS, m_PtrToInt(m_Value(PtrRHS)));
7848 if (HasPtrLHS || HasPtrRHS) {
7849 // Convert a ptrtoint operand (OrigOp) to ptrtoaddr of its pointer
7850 // PtrOp. When only one side is ptrtoint (BothPtr is false), skip
7851 // SCEVUnknown pointers since wrapping them in ptrtoaddr adds no
7852 // useful structure.
7853 auto GetOp = [&](bool HasPtr, Value *PtrOp, Value *OrigOp,
7854 bool BothPtr) -> const SCEV * {
7855 if (!HasPtr)
7856 return getSCEV(OrigOp);
7857 const SCEV *PtrSCEV = getSCEV(PtrOp);
7858 if (BothPtr || !isa<SCEVUnknown>(PtrSCEV)) {
7859 const SCEV *Addr = getPtrToAddrExpr(PtrSCEV);
7860 if (!isa<SCEVCouldNotCompute>(Addr) &&
7861 getTypeSizeInBits(OrigOp->getType()) <=
7862 getTypeSizeInBits(Addr->getType()))
7863 return getTruncateOrNoop(Addr, OrigOp->getType());
7864 }
7865 return getSCEV(OrigOp);
7866 };
7867 const SCEV *L = GetOp(HasPtrLHS, PtrLHS, BO->LHS, HasPtrRHS);
7868 const SCEV *R = GetOp(HasPtrRHS, PtrRHS, BO->RHS, HasPtrLHS);
7869 return getMinusSCEV(L, R, Flags);
7870 }
7871
7872 LHS = getSCEV(BO->LHS);
7873 RHS = getSCEV(BO->RHS);
7874 return getMinusSCEV(LHS, RHS, Flags);
7875 }
7876 case Instruction::And:
7877 // For an expression like x&255 that merely masks off the high bits,
7878 // use zext(trunc(x)) as the SCEV expression.
7879 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7880 if (CI->isZero())
7881 return getSCEV(BO->RHS);
7882 if (CI->isMinusOne())
7883 return getSCEV(BO->LHS);
7884 const APInt &A = CI->getValue();
7885
7886 // Instcombine's ShrinkDemandedConstant may strip bits out of
7887 // constants, obscuring what would otherwise be a low-bits mask.
7888 // Use computeKnownBits to compute what ShrinkDemandedConstant
7889 // knew about to reconstruct a low-bits mask value.
7890 unsigned LZ = A.countl_zero();
7891 unsigned TZ = A.countr_zero();
7892 unsigned BitWidth = A.getBitWidth();
7893 KnownBits Known(BitWidth);
7894 computeKnownBits(BO->LHS, Known, getDataLayout(), &AC, nullptr, &DT);
7895
7896 APInt EffectiveMask =
7897 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
7898 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
7899 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
7900 const SCEV *LHS = getSCEV(BO->LHS);
7901 const SCEV *ShiftedLHS = nullptr;
7902 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
7903 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
7904 // For an expression like (x * 8) & 8, simplify the multiply.
7905 unsigned MulZeros = OpC->getAPInt().countr_zero();
7906 unsigned GCD = std::min(MulZeros, TZ);
7907 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
7909 MulOps.push_back(getConstant(OpC->getAPInt().ashr(GCD)));
7910 append_range(MulOps, LHSMul->operands().drop_front());
7911 const SCEV *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
7912 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
7913 }
7914 }
7915 if (!ShiftedLHS)
7916 ShiftedLHS = getUDivExpr(LHS, MulCount);
7917 return getMulExpr(
7919 getTruncateExpr(ShiftedLHS,
7920 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
7921 BO->LHS->getType()),
7922 MulCount);
7923 }
7924 }
7925 // Binary `and` is a bit-wise `umin`.
7926 if (BO->LHS->getType()->isIntegerTy(1)) {
7927 LHS = getSCEV(BO->LHS);
7928 RHS = getSCEV(BO->RHS);
7929 return getUMinExpr(LHS, RHS);
7930 }
7931 break;
7932
7933 case Instruction::Or:
7934 // Binary `or` is a bit-wise `umax`.
7935 if (BO->LHS->getType()->isIntegerTy(1)) {
7936 LHS = getSCEV(BO->LHS);
7937 RHS = getSCEV(BO->RHS);
7938 return getUMaxExpr(LHS, RHS);
7939 }
7940 break;
7941
7942 case Instruction::Xor:
7943 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7944 // If the RHS of xor is -1, then this is a not operation.
7945 if (CI->isMinusOne())
7946 return getNotSCEV(getSCEV(BO->LHS));
7947
7948 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
7949 // This is a variant of the check for xor with -1, and it handles
7950 // the case where instcombine has trimmed non-demanded bits out
7951 // of an xor with -1.
7952 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
7953 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
7954 if (LBO->getOpcode() == Instruction::And &&
7955 LCI->getValue() == CI->getValue())
7956 if (const SCEVZeroExtendExpr *Z =
7958 Type *UTy = BO->LHS->getType();
7959 const SCEV *Z0 = Z->getOperand();
7960 Type *Z0Ty = Z0->getType();
7961 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
7962
7963 // If C is a low-bits mask, the zero extend is serving to
7964 // mask off the high bits. Complement the operand and
7965 // re-apply the zext.
7966 if (CI->getValue().isMask(Z0TySize))
7967 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
7968
7969 // If C is a single bit, it may be in the sign-bit position
7970 // before the zero-extend. In this case, represent the xor
7971 // using an add, which is equivalent, and re-apply the zext.
7972 APInt Trunc = CI->getValue().trunc(Z0TySize);
7973 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
7974 Trunc.isSignMask())
7976 UTy);
7977 }
7978 }
7979 break;
7980
7981 case Instruction::Shl:
7982 // Turn shift left of a constant amount into a multiply.
7983 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
7984 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
7985
7986 // If the shift count is not less than the bitwidth, the result of
7987 // the shift is undefined. Don't try to analyze it, because the
7988 // resolution chosen here may differ from the resolution chosen in
7989 // other parts of the compiler.
7990 if (SA->getValue().uge(BitWidth))
7991 break;
7992
7993 // We can safely preserve the nuw flag in all cases. It's also safe to
7994 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
7995 // requires special handling. It can be preserved as long as we're not
7996 // left shifting by bitwidth - 1.
7997 auto Flags = SCEV::FlagNone;
7998 if (BO->Op) {
7999 auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
8000 if (any(MulFlags & SCEV::FlagNSW) &&
8001 (any(MulFlags & SCEV::FlagNUW) ||
8002 SA->getValue().ult(BitWidth - 1)))
8004 if (any(MulFlags & SCEV::FlagNUW))
8006 }
8007
8008 ConstantInt *X = ConstantInt::get(
8009 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
8010 return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
8011 }
8012 break;
8013
8014 case Instruction::AShr:
8015 // AShr X, C, where C is a constant.
8016 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
8017 if (!CI)
8018 break;
8019
8020 Type *OuterTy = BO->LHS->getType();
8022 // If the shift count is not less than the bitwidth, the result of
8023 // the shift is undefined. Don't try to analyze it, because the
8024 // resolution chosen here may differ from the resolution chosen in
8025 // other parts of the compiler.
8026 if (CI->getValue().uge(BitWidth))
8027 break;
8028
8029 if (CI->isZero())
8030 return getSCEV(BO->LHS); // shift by zero --> noop
8031
8032 uint64_t AShrAmt = CI->getZExtValue();
8033 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
8034
8035 Operator *L = dyn_cast<Operator>(BO->LHS);
8036 const SCEV *AddTruncateExpr = nullptr;
8037 ConstantInt *ShlAmtCI = nullptr;
8038 const SCEV *AddConstant = nullptr;
8039
8040 if (L && L->getOpcode() == Instruction::Add) {
8041 // X = Shl A, n
8042 // Y = Add X, c
8043 // Z = AShr Y, m
8044 // n, c and m are constants.
8045
8046 Operator *LShift = dyn_cast<Operator>(L->getOperand(0));
8047 ConstantInt *AddOperandCI = dyn_cast<ConstantInt>(L->getOperand(1));
8048 if (LShift && LShift->getOpcode() == Instruction::Shl) {
8049 if (AddOperandCI) {
8050 const SCEV *ShlOp0SCEV = getSCEV(LShift->getOperand(0));
8051 ShlAmtCI = dyn_cast<ConstantInt>(LShift->getOperand(1));
8052 // since we truncate to TruncTy, the AddConstant should be of the
8053 // same type, so create a new Constant with type same as TruncTy.
8054 // Also, the Add constant should be shifted right by AShr amount.
8055 APInt AddOperand = AddOperandCI->getValue().ashr(AShrAmt);
8056 AddConstant = getConstant(AddOperand.trunc(BitWidth - AShrAmt));
8057 // we model the expression as sext(add(trunc(A), c << n)), since the
8058 // sext(trunc) part is already handled below, we create a
8059 // AddExpr(TruncExp) which will be used later.
8060 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8061 }
8062 }
8063 } else if (L && L->getOpcode() == Instruction::Shl) {
8064 // X = Shl A, n
8065 // Y = AShr X, m
8066 // Both n and m are constant.
8067
8068 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
8069 ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
8070 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8071 }
8072
8073 if (AddTruncateExpr && ShlAmtCI) {
8074 // We can merge the two given cases into a single SCEV statement,
8075 // incase n = m, the mul expression will be 2^0, so it gets resolved to
8076 // a simpler case. The following code handles the two cases:
8077 //
8078 // 1) For a two-shift sext-inreg, i.e. n = m,
8079 // use sext(trunc(x)) as the SCEV expression.
8080 //
8081 // 2) When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
8082 // expression. We already checked that ShlAmt < BitWidth, so
8083 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
8084 // ShlAmt - AShrAmt < Amt.
8085 const APInt &ShlAmt = ShlAmtCI->getValue();
8086 if (ShlAmt.ult(BitWidth) && ShlAmt.uge(AShrAmt)) {
8087 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
8088 ShlAmtCI->getZExtValue() - AShrAmt);
8089 const SCEV *CompositeExpr =
8090 getMulExpr(AddTruncateExpr, getConstant(Mul));
8091 if (L->getOpcode() != Instruction::Shl)
8092 CompositeExpr = getAddExpr(CompositeExpr, AddConstant);
8093
8094 return getSignExtendExpr(CompositeExpr, OuterTy);
8095 }
8096 }
8097 break;
8098 }
8099 }
8100
8101 switch (U->getOpcode()) {
8102 case Instruction::Trunc:
8103 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
8104
8105 case Instruction::ZExt:
8106 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8107
8108 case Instruction::SExt:
8109 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
8110 // The NSW flag of a subtract does not always survive the conversion to
8111 // A + (-1)*B. By pushing sign extension onto its operands we are much
8112 // more likely to preserve NSW and allow later AddRec optimisations.
8113 //
8114 // NOTE: This is effectively duplicating this logic from getSignExtend:
8115 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
8116 // but by that point the NSW information has potentially been lost.
8117 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
8118 Type *Ty = U->getType();
8119 SCEVUse V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
8120 SCEVUse V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
8121 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
8122 }
8123 }
8124 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8125
8126 case Instruction::BitCast:
8127 // BitCasts are no-op casts so we just eliminate the cast.
8128 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
8129 return getSCEV(U->getOperand(0));
8130 break;
8131
8132 case Instruction::PtrToAddr: {
8133 const SCEV *IntOp = getPtrToAddrExpr(getSCEV(U->getOperand(0)));
8134 if (isa<SCEVCouldNotCompute>(IntOp))
8135 return getUnknown(V);
8136 return IntOp;
8137 }
8138
8139 case Instruction::PtrToInt:
8140 // SCEV only models ptrtoaddr.
8141 return getUnknown(V);
8142
8143 case Instruction::IntToPtr:
8144 // Just don't deal with inttoptr casts.
8145 return getUnknown(V);
8146
8147 case Instruction::SDiv:
8148 // If both operands are non-negative, this is just an udiv.
8149 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8150 isKnownNonNegative(getSCEV(U->getOperand(1))))
8151 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8152 break;
8153
8154 case Instruction::SRem:
8155 // If both operands are non-negative, this is just an urem.
8156 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8157 isKnownNonNegative(getSCEV(U->getOperand(1))))
8158 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8159 break;
8160
8161 case Instruction::GetElementPtr:
8162 return createNodeForGEP(cast<GEPOperator>(U));
8163
8164 case Instruction::PHI:
8165 return createNodeForPHI(cast<PHINode>(U));
8166
8167 case Instruction::Select:
8168 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
8169 U->getOperand(2));
8170
8171 case Instruction::Call:
8172 case Instruction::Invoke:
8173 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
8174 return getSCEV(RV);
8175
8176 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
8177 switch (II->getIntrinsicID()) {
8178 case Intrinsic::abs:
8179 return getAbsExpr(
8180 getSCEV(II->getArgOperand(0)),
8181 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
8182 case Intrinsic::umax:
8183 LHS = getSCEV(II->getArgOperand(0));
8184 RHS = getSCEV(II->getArgOperand(1));
8185 return getUMaxExpr(LHS, RHS);
8186 case Intrinsic::umin:
8187 LHS = getSCEV(II->getArgOperand(0));
8188 RHS = getSCEV(II->getArgOperand(1));
8189 return getUMinExpr(LHS, RHS);
8190 case Intrinsic::smax:
8191 LHS = getSCEV(II->getArgOperand(0));
8192 RHS = getSCEV(II->getArgOperand(1));
8193 return getSMaxExpr(LHS, RHS);
8194 case Intrinsic::smin:
8195 LHS = getSCEV(II->getArgOperand(0));
8196 RHS = getSCEV(II->getArgOperand(1));
8197 return getSMinExpr(LHS, RHS);
8198 case Intrinsic::usub_sat: {
8199 const SCEV *X = getSCEV(II->getArgOperand(0));
8200 const SCEV *Y = getSCEV(II->getArgOperand(1));
8201 const SCEV *ClampedY = getUMinExpr(X, Y);
8202 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
8203 }
8204 case Intrinsic::uadd_sat: {
8205 const SCEV *X = getSCEV(II->getArgOperand(0));
8206 const SCEV *Y = getSCEV(II->getArgOperand(1));
8207 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
8208 return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
8209 }
8210 case Intrinsic::start_loop_iterations:
8211 case Intrinsic::annotation:
8212 case Intrinsic::ptr_annotation:
8213 // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8214 // just eqivalent to the first operand for SCEV purposes.
8215 return getSCEV(II->getArgOperand(0));
8216 case Intrinsic::vscale:
8217 return getVScale(II->getType());
8218 default:
8219 break;
8220 }
8221 }
8222 break;
8223 }
8224
8225 return getUnknown(V);
8226}
8227
8228//===----------------------------------------------------------------------===//
8229// Iteration Count Computation Code
8230//
8231
8233 if (isa<SCEVCouldNotCompute>(ExitCount))
8234 return getCouldNotCompute();
8235
8236 auto *ExitCountType = ExitCount->getType();
8237 assert(ExitCountType->isIntegerTy());
8238 auto *EvalTy = Type::getIntNTy(ExitCountType->getContext(),
8239 1 + ExitCountType->getScalarSizeInBits());
8240 return getTripCountFromExitCount(ExitCount, EvalTy, nullptr);
8241}
8242
8244 Type *EvalTy,
8245 const Loop *L) {
8246 if (isa<SCEVCouldNotCompute>(ExitCount))
8247 return getCouldNotCompute();
8248
8249 unsigned ExitCountSize = getTypeSizeInBits(ExitCount->getType());
8250 unsigned EvalSize = EvalTy->getPrimitiveSizeInBits();
8251
8252 auto CanAddOneWithoutOverflow = [&]() {
8253 ConstantRange ExitCountRange =
8254 getRangeRef(ExitCount, RangeSignHint::HINT_RANGE_UNSIGNED);
8255 if (!ExitCountRange.contains(APInt::getMaxValue(ExitCountSize)))
8256 return true;
8257
8258 return L && isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
8259 getMinusOne(ExitCount->getType()));
8260 };
8261
8262 // If we need to zero extend the backedge count, check if we can add one to
8263 // it prior to zero extending without overflow. Provided this is safe, it
8264 // allows better simplification of the +1.
8265 if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8266 return getZeroExtendExpr(
8267 getAddExpr(ExitCount, getOne(ExitCount->getType())), EvalTy);
8268
8269 // Get the total trip count from the count by adding 1. This may wrap.
8270 return getAddExpr(getTruncateOrZeroExtend(ExitCount, EvalTy), getOne(EvalTy));
8271}
8272
8273static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8274 if (!ExitCount)
8275 return 0;
8276
8277 ConstantInt *ExitConst = ExitCount->getValue();
8278
8279 // Guard against huge trip counts.
8280 if (ExitConst->getValue().getActiveBits() > 32)
8281 return 0;
8282
8283 // In case of integer overflow, this returns 0, which is correct.
8284 return ((unsigned)ExitConst->getZExtValue()) + 1;
8285}
8286
8288 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
8289 return getConstantTripCount(ExitCount);
8290}
8291
8292unsigned
8294 const BasicBlock *ExitingBlock) {
8295 assert(ExitingBlock && "Must pass a non-null exiting block!");
8296 assert(L->isLoopExiting(ExitingBlock) &&
8297 "Exiting block must actually branch out of the loop!");
8298 const SCEVConstant *ExitCount =
8299 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
8300 return getConstantTripCount(ExitCount);
8301}
8302
8304 const Loop *L, SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8305
8306 const auto *MaxExitCount =
8307 Predicates ? getPredicatedConstantMaxBackedgeTakenCount(L, *Predicates)
8309 return getConstantTripCount(dyn_cast<SCEVConstant>(MaxExitCount));
8310}
8311
8313 SmallVector<BasicBlock *, 8> ExitingBlocks;
8314 L->getExitingBlocks(ExitingBlocks);
8315
8316 // An exit with an uncomputable exit count makes the result 1.
8317 if (ExitingBlocks.empty() ||
8318 any_of(ExitingBlocks, [this, L](BasicBlock *ExitingBB) {
8319 return isa<SCEVCouldNotCompute>(getExitCount(L, ExitingBB));
8320 }))
8321 return 1;
8322
8323 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
8324 unsigned Res = 0;
8325 for (BasicBlock *ExitingBB : ExitingBlocks)
8326 Res = std::gcd(
8327 Res, getSmallConstantTripMultiple(getExitCount(L, ExitingBB), Guards));
8328 return Res;
8329}
8330
8331unsigned ScalarEvolution::getSmallConstantTripMultiple(const SCEV *ExitCount,
8332 LoopGuards &Guards) {
8333 assert(!isa<SCEVCouldNotCompute>(ExitCount) && "Must be computable!");
8334
8335 // Get the trip count
8336 const SCEV *TCExpr =
8337 getTripCountFromExitCount(applyLoopGuards(ExitCount, Guards));
8338
8339 APInt Multiple = getNonZeroConstantMultiple(TCExpr);
8340 // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8341 // the greatest power of 2 divisor less than 2^32.
8342 return Multiple.getActiveBits() > 32
8343 ? 1U << std::min(31U, Multiple.countTrailingZeros())
8344 : (unsigned)Multiple.getZExtValue();
8345}
8346
8348 const SCEV *ExitCount) {
8349 if (isa<SCEVCouldNotCompute>(ExitCount))
8350 return 1;
8351
8352 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
8353 return getSmallConstantTripMultiple(ExitCount, Guards);
8354}
8355
8356/// Returns the largest constant divisor of the trip count of this loop as a
8357/// normal unsigned value, if possible. This means that the actual trip count is
8358/// always a multiple of the returned value (don't forget the trip count could
8359/// very well be zero as well!).
8360///
8361/// Returns 1 if the trip count is unknown or not guaranteed to be the
8362/// multiple of a constant (which is also the case if the trip count is simply
8363/// constant, use getSmallConstantTripCount for that case), Will also return 1
8364/// if the trip count is very large (>= 2^32).
8365///
8366/// As explained in the comments for getSmallConstantTripCount, this assumes
8367/// that control exits the loop via ExitingBlock.
8368unsigned
8370 const BasicBlock *ExitingBlock) {
8371 assert(ExitingBlock && "Must pass a non-null exiting block!");
8372 assert(L->isLoopExiting(ExitingBlock) &&
8373 "Exiting block must actually branch out of the loop!");
8374 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8375 return getSmallConstantTripMultiple(L, ExitCount);
8376}
8377
8379 const BasicBlock *ExitingBlock,
8380 ExitCountKind Kind) {
8381 switch (Kind) {
8382 case Exact:
8383 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8384 case SymbolicMaximum:
8385 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8386 case ConstantMaximum:
8387 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8388 };
8389 llvm_unreachable("Invalid ExitCountKind!");
8390}
8391
8393 const Loop *L, const BasicBlock *ExitingBlock,
8395 switch (Kind) {
8396 case Exact:
8397 return getPredicatedBackedgeTakenInfo(L).getExact(ExitingBlock, this,
8398 Predicates);
8399 case SymbolicMaximum:
8400 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this,
8401 Predicates);
8402 case ConstantMaximum:
8403 return getPredicatedBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this,
8404 Predicates);
8405 };
8406 llvm_unreachable("Invalid ExitCountKind!");
8407}
8408
8411 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8412}
8413
8415 ExitCountKind Kind) {
8416 switch (Kind) {
8417 case Exact:
8418 return getBackedgeTakenInfo(L).getExact(L, this);
8419 case ConstantMaximum:
8420 return getBackedgeTakenInfo(L).getConstantMax(this);
8421 case SymbolicMaximum:
8422 return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8423 };
8424 llvm_unreachable("Invalid ExitCountKind!");
8425}
8426
8429 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(L, this, &Preds);
8430}
8431
8434 return getPredicatedBackedgeTakenInfo(L).getConstantMax(this, &Preds);
8435}
8436
8438 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8439}
8440
8441/// Push PHI nodes in the header of the given loop onto the given Worklist.
8442static void PushLoopPHIs(const Loop *L,
8445 BasicBlock *Header = L->getHeader();
8446
8447 // Push all Loop-header PHIs onto the Worklist stack.
8448 for (PHINode &PN : Header->phis())
8449 if (Visited.insert(&PN).second)
8450 Worklist.push_back(&PN);
8451}
8452
8453ScalarEvolution::BackedgeTakenInfo &
8454ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8455 auto &BTI = getBackedgeTakenInfo(L);
8456 if (BTI.hasFullInfo())
8457 return BTI;
8458
8459 auto Pair = PredicatedBackedgeTakenCounts.try_emplace(L);
8460
8461 if (!Pair.second)
8462 return Pair.first->second;
8463
8464 BackedgeTakenInfo Result =
8465 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8466
8467 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8468}
8469
8470ScalarEvolution::BackedgeTakenInfo &
8471ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8472 // Initially insert an invalid entry for this loop. If the insertion
8473 // succeeds, proceed to actually compute a backedge-taken count and
8474 // update the value. The temporary CouldNotCompute value tells SCEV
8475 // code elsewhere that it shouldn't attempt to request a new
8476 // backedge-taken count, which could result in infinite recursion.
8477 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8478 BackedgeTakenCounts.try_emplace(L);
8479 if (!Pair.second)
8480 return Pair.first->second;
8481
8482 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8483 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8484 // must be cleared in this scope.
8485 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8486
8487 // Now that we know more about the trip count for this loop, forget any
8488 // existing SCEV values for PHI nodes in this loop since they are only
8489 // conservative estimates made without the benefit of trip count
8490 // information. This invalidation is not necessary for correctness, and is
8491 // only done to produce more precise results.
8492 if (Result.hasAnyInfo()) {
8493 // Invalidate any expression using an addrec in this loop.
8494 SmallVector<SCEVUse, 8> ToForget;
8495 auto LoopUsersIt = LoopUsers.find(L);
8496 if (LoopUsersIt != LoopUsers.end())
8497 append_range(ToForget, LoopUsersIt->second);
8498 forgetMemoizedResults(ToForget);
8499
8500 // Invalidate constant-evolved loop header phis.
8501 for (PHINode &PN : L->getHeader()->phis())
8502 ConstantEvolutionLoopExitValue.erase(&PN);
8503 }
8504
8505 // Re-lookup the insert position, since the call to
8506 // computeBackedgeTakenCount above could result in a
8507 // recusive call to getBackedgeTakenInfo (on a different
8508 // loop), which would invalidate the iterator computed
8509 // earlier.
8510 return BackedgeTakenCounts.find(L)->second = std::move(Result);
8511}
8512
8514 // This method is intended to forget all info about loops. It should
8515 // invalidate caches as if the following happened:
8516 // - The trip counts of all loops have changed arbitrarily
8517 // - Every llvm::Value has been updated in place to produce a different
8518 // result.
8519 BackedgeTakenCounts.clear();
8520 PredicatedBackedgeTakenCounts.clear();
8521 BECountUsers.clear();
8522 LoopPropertiesCache.clear();
8523 ConstantEvolutionLoopExitValue.clear();
8524 ValueExprMap.clear();
8525 ValuesAtScopes.clear();
8526 ValuesAtScopesUsers.clear();
8527 LoopDispositions.clear();
8528 BlockDispositions.clear();
8529 UnsignedRanges.clear();
8530 SignedRanges.clear();
8531 ExprValueMap.clear();
8532 HasRecMap.clear();
8533 ConstantMultipleCache.clear();
8534 PredicatedSCEVRewrites.clear();
8535 FoldCache.clear();
8536 FoldCacheUser.clear();
8537}
8538void ScalarEvolution::visitAndClearUsers(
8541 SmallVectorImpl<SCEVUse> &ToForget) {
8542 // Nothing can be invalidated if no value has a SCEV yet.
8543 if (ValueExprMap.empty()) {
8544 Worklist.clear();
8545 return;
8546 }
8547 while (!Worklist.empty()) {
8548 Instruction *I = Worklist.pop_back_val();
8549 if (!isSCEVable(I->getType()) && !isa<WithOverflowInst>(I))
8550 continue;
8551
8553 ValueExprMap.find_as(static_cast<Value *>(I));
8554 if (It != ValueExprMap.end()) {
8555 ToForget.push_back(It->second);
8556 eraseValueFromMap(It->first);
8557 if (PHINode *PN = dyn_cast<PHINode>(I))
8558 ConstantEvolutionLoopExitValue.erase(PN);
8559 }
8560
8561 PushDefUseChildren(I, Worklist, Visited);
8562 }
8563}
8564
8566 SmallVector<const Loop *, 16> LoopWorklist(1, L);
8569 SmallVector<SCEVUse, 16> ToForget;
8570
8571 // Iterate over all the loops and sub-loops to drop SCEV information.
8572 while (!LoopWorklist.empty()) {
8573 auto *CurrL = LoopWorklist.pop_back_val();
8574
8575 // Drop any stored trip count value.
8576 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8577 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8578
8579 // Drop information about predicated SCEV rewrites for this loop.
8580 PredicatedSCEVRewrites.remove_if(
8581 [&](const auto &Entry) { return Entry.first.second == CurrL; });
8582
8583 auto LoopUsersItr = LoopUsers.find(CurrL);
8584 if (LoopUsersItr != LoopUsers.end())
8585 llvm::append_range(ToForget, LoopUsersItr->second);
8586
8587 // Drop information about expressions based on loop-header PHIs.
8588 PushLoopPHIs(CurrL, Worklist, Visited);
8589 visitAndClearUsers(Worklist, Visited, ToForget);
8590
8591 LoopPropertiesCache.erase(CurrL);
8592 // Forget all contained loops too, to avoid dangling entries in the
8593 // ValuesAtScopes map.
8594 LoopWorklist.append(CurrL->begin(), CurrL->end());
8595 }
8596 forgetMemoizedResults(ToForget);
8597}
8598
8600 forgetLoop(L->getOutermostLoop());
8601}
8602
8605 if (!I) return;
8606
8607 // Drop information about expressions based on loop-header PHIs.
8610 SmallVector<SCEVUse, 8> ToForget;
8611 Worklist.push_back(I);
8612 Visited.insert(I);
8613 visitAndClearUsers(Worklist, Visited, ToForget);
8614
8615 forgetMemoizedResults(ToForget);
8616}
8617
8621 SmallVector<SCEVUse, 8> ToForget;
8622 for (Value *V : Values)
8623 if (auto *I = dyn_cast<Instruction>(V))
8624 if (Visited.insert(I).second)
8625 Worklist.push_back(I);
8626 visitAndClearUsers(Worklist, Visited, ToForget);
8627
8628 forgetMemoizedResults(ToForget);
8629}
8630
8632 // If SCEV looked through a trivial LCSSA phi node, we might have SCEV's
8633 // directly using a SCEVUnknown/SCEVAddRec defined in the loop. After an
8634 // extra predecessor is added, this is no longer valid. Find all Unknowns and
8635 // AddRecs defined in the loop and invalidate any SCEV's making use of them.
8636 auto InvalidateValue = [&](Value *Val) {
8637 if (!isSCEVable(Val->getType()))
8638 return;
8639 if (const SCEV *S = getExistingSCEV(Val)) {
8640 struct InvalidationRootCollector {
8641 Loop *L;
8643
8644 InvalidationRootCollector(Loop *L) : L(L) {}
8645
8646 bool follow(const SCEV *S) {
8647 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
8648 if (auto *I = dyn_cast<Instruction>(SU->getValue()))
8649 if (L->contains(I))
8650 Roots.push_back(S);
8651 } else if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
8652 if (L->contains(AddRec->getLoop()))
8653 Roots.push_back(S);
8654 }
8655 return true;
8656 }
8657 bool isDone() const { return false; }
8658 };
8659
8660 InvalidationRootCollector C(L);
8661 visitAll(S, C);
8662 forgetMemoizedResults(C.Roots);
8663 }
8664 };
8665
8666 InvalidateValue(V);
8667
8668 // If V has a non-SCEV-able type (e.g. {i64, i1} from a with.overflow
8669 // intrinsic), its users (e.g. extractvalue) may have stale SCEV
8670 // expressions referencing loop-internal values.
8671 if (!isSCEVable(V->getType()) &&
8672 any_of(V->incoming_values(), IsaPred<WithOverflowInst>))
8673 for (User *U : V->users())
8674 InvalidateValue(U);
8675 // Also perform the normal invalidation.
8676 forgetValue(V);
8677}
8678
8679void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8680
8682 // Unless a specific value is passed to invalidation, completely clear both
8683 // caches.
8684 if (!V) {
8685 BlockDispositions.clear();
8686 LoopDispositions.clear();
8687 return;
8688 }
8689
8690 if (!isSCEVable(V->getType()))
8691 return;
8692
8693 const SCEV *S = getExistingSCEV(V);
8694 if (!S)
8695 return;
8696
8697 // Invalidate the block and loop dispositions cached for S. Dispositions of
8698 // S's users may change if S's disposition changes (i.e. a user may change to
8699 // loop-invariant, if S changes to loop invariant), so also invalidate
8700 // dispositions of S's users recursively.
8701 SmallVector<SCEVUse, 8> Worklist = {S};
8703 while (!Worklist.empty()) {
8704 const SCEV *Curr = Worklist.pop_back_val();
8705 bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8706 bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8707 if (!LoopDispoRemoved && !BlockDispoRemoved)
8708 continue;
8709 auto Users = SCEVUsers.find(Curr);
8710 if (Users != SCEVUsers.end())
8711 for (const auto *User : Users->second)
8712 if (Seen.insert(User).second)
8713 Worklist.push_back(User);
8714 }
8715}
8716
8717/// Get the exact loop backedge taken count considering all loop exits. A
8718/// computable result can only be returned for loops with all exiting blocks
8719/// dominating the latch. howFarToZero assumes that the limit of each loop test
8720/// is never skipped. This is a valid assumption as long as the loop exits via
8721/// that test. For precise results, it is the caller's responsibility to specify
8722/// the relevant loop exiting block using getExact(ExitingBlock, SE).
8723const SCEV *ScalarEvolution::BackedgeTakenInfo::getExact(
8724 const Loop *L, ScalarEvolution *SE,
8726 // If any exits were not computable, the loop is not computable.
8727 if (!isComplete() || ExitNotTaken.empty())
8728 return SE->getCouldNotCompute();
8729
8730 const BasicBlock *Latch = L->getLoopLatch();
8731 // All exiting blocks we have collected must dominate the only backedge.
8732 if (!Latch)
8733 return SE->getCouldNotCompute();
8734
8735 // All exiting blocks we have gathered dominate loop's latch, so exact trip
8736 // count is simply a minimum out of all these calculated exit counts.
8738 for (const auto &ENT : ExitNotTaken) {
8739 const SCEV *BECount = ENT.ExactNotTaken;
8740 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8741 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8742 "We should only have known counts for exiting blocks that dominate "
8743 "latch!");
8744
8745 Ops.push_back(BECount);
8746
8747 if (Preds)
8748 append_range(*Preds, ENT.Predicates);
8749
8750 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8751 "Predicate should be always true!");
8752 }
8753
8754 // If an earlier exit exits on the first iteration (exit count zero), then
8755 // a later poison exit count should not propagate into the result. This are
8756 // exactly the semantics provided by umin_seq.
8757 return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8758}
8759
8760const ScalarEvolution::ExitNotTakenInfo *
8761ScalarEvolution::BackedgeTakenInfo::getExitNotTaken(
8762 const BasicBlock *ExitingBlock,
8763 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8764 for (const auto &ENT : ExitNotTaken)
8765 if (ENT.ExitingBlock == ExitingBlock) {
8766 if (ENT.hasAlwaysTruePredicate())
8767 return &ENT;
8768 else if (Predicates) {
8769 append_range(*Predicates, ENT.Predicates);
8770 return &ENT;
8771 }
8772 }
8773
8774 return nullptr;
8775}
8776
8777/// getConstantMax - Get the constant max backedge taken count for the loop.
8778const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8779 ScalarEvolution *SE,
8780 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8781 if (!getConstantMax())
8782 return SE->getCouldNotCompute();
8783
8784 for (const auto &ENT : ExitNotTaken)
8785 if (!ENT.hasAlwaysTruePredicate()) {
8786 if (!Predicates)
8787 return SE->getCouldNotCompute();
8788 append_range(*Predicates, ENT.Predicates);
8789 }
8790
8791 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8792 isa<SCEVConstant>(getConstantMax())) &&
8793 "No point in having a non-constant max backedge taken count!");
8794 return getConstantMax();
8795}
8796
8797const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8798 const Loop *L, ScalarEvolution *SE,
8799 SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8800 if (!SymbolicMax) {
8801 // Form an expression for the maximum exit count possible for this loop. We
8802 // merge the max and exact information to approximate a version of
8803 // getConstantMaxBackedgeTakenCount which isn't restricted to just
8804 // constants.
8805 SmallVector<SCEVUse, 4> ExitCounts;
8806
8807 for (const auto &ENT : ExitNotTaken) {
8808 const SCEV *ExitCount = ENT.SymbolicMaxNotTaken;
8809 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
8810 assert(SE->DT.dominates(ENT.ExitingBlock, L->getLoopLatch()) &&
8811 "We should only have known counts for exiting blocks that "
8812 "dominate latch!");
8813 ExitCounts.push_back(ExitCount);
8814 if (Predicates)
8815 append_range(*Predicates, ENT.Predicates);
8816
8817 assert((Predicates || ENT.hasAlwaysTruePredicate()) &&
8818 "Predicate should be always true!");
8819 }
8820 }
8821 if (ExitCounts.empty())
8822 SymbolicMax = SE->getCouldNotCompute();
8823 else
8824 SymbolicMax =
8825 SE->getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
8826 }
8827 return SymbolicMax;
8828}
8829
8830bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8831 ScalarEvolution *SE) const {
8832 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8833 return !ENT.hasAlwaysTruePredicate();
8834 };
8835 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8836}
8837
8840
8842 const SCEV *E, const SCEV *ConstantMaxNotTaken,
8843 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8847 // If we prove the max count is zero, so is the symbolic bound. This happens
8848 // in practice due to differences in a) how context sensitive we've chosen
8849 // to be and b) how we reason about bounds implied by UB.
8850 if (ConstantMaxNotTaken->isZero()) {
8851 this->ExactNotTaken = E = ConstantMaxNotTaken;
8852 this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
8853 }
8854
8857 "Exact is not allowed to be less precise than Constant Max");
8860 "Exact is not allowed to be less precise than Symbolic Max");
8863 "Symbolic Max is not allowed to be less precise than Constant Max");
8866 "No point in having a non-constant max backedge taken count!");
8868 for (const auto PredList : PredLists)
8869 for (const auto *P : PredList) {
8870 if (SeenPreds.contains(P))
8871 continue;
8872 assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!");
8873 SeenPreds.insert(P);
8874 Predicates.push_back(P);
8875 }
8876 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8877 "Backedge count should be int");
8879 !ConstantMaxNotTaken->getType()->isPointerTy()) &&
8880 "Max backedge count should be int");
8881}
8882
8890
8891/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8892/// computable exit into a persistent ExitNotTakenInfo array.
8893ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8895 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
8896 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8897 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8898
8899 ExitNotTaken.reserve(ExitCounts.size());
8900 std::transform(ExitCounts.begin(), ExitCounts.end(),
8901 std::back_inserter(ExitNotTaken),
8902 [&](const EdgeExitInfo &EEI) {
8903 BasicBlock *ExitBB = EEI.first;
8904 const ExitLimit &EL = EEI.second;
8905 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
8906 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
8907 EL.Predicates);
8908 });
8909 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
8910 isa<SCEVConstant>(ConstantMax)) &&
8911 "No point in having a non-constant max backedge taken count!");
8912}
8913
8914/// Compute the number of times the backedge of the specified loop will execute.
8915ScalarEvolution::BackedgeTakenInfo
8916ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
8917 bool AllowPredicates) {
8918 SmallVector<BasicBlock *, 8> ExitingBlocks;
8919 L->getExitingBlocks(ExitingBlocks);
8920
8921 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8922
8924 bool CouldComputeBECount = true;
8925 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
8926 const SCEV *MustExitMaxBECount = nullptr;
8927 const SCEV *MayExitMaxBECount = nullptr;
8928 bool MustExitMaxOrZero = false;
8929 bool IsOnlyExit = ExitingBlocks.size() == 1;
8930
8931 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
8932 // and compute maxBECount.
8933 // Do a union of all the predicates here.
8934 for (BasicBlock *ExitBB : ExitingBlocks) {
8935 // We canonicalize untaken exits to br (constant), ignore them so that
8936 // proving an exit untaken doesn't negatively impact our ability to reason
8937 // about the loop as whole.
8938 if (auto *BI = dyn_cast<CondBrInst>(ExitBB->getTerminator()))
8939 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
8940 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8941 if (ExitIfTrue == CI->isZero())
8942 continue;
8943 }
8944
8945 ExitLimit EL = computeExitLimit(L, ExitBB, IsOnlyExit, AllowPredicates);
8946
8947 assert((AllowPredicates || EL.Predicates.empty()) &&
8948 "Predicated exit limit when predicates are not allowed!");
8949
8950 // 1. For each exit that can be computed, add an entry to ExitCounts.
8951 // CouldComputeBECount is true only if all exits can be computed.
8952 if (EL.ExactNotTaken != getCouldNotCompute())
8953 ++NumExitCountsComputed;
8954 else
8955 // We couldn't compute an exact value for this exit, so
8956 // we won't be able to compute an exact value for the loop.
8957 CouldComputeBECount = false;
8958 // Remember exit count if either exact or symbolic is known. Because
8959 // Exact always implies symbolic, only check symbolic.
8960 if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
8961 ExitCounts.emplace_back(ExitBB, EL);
8962 else {
8963 assert(EL.ExactNotTaken == getCouldNotCompute() &&
8964 "Exact is known but symbolic isn't?");
8965 ++NumExitCountsNotComputed;
8966 }
8967
8968 // 2. Derive the loop's MaxBECount from each exit's max number of
8969 // non-exiting iterations. Partition the loop exits into two kinds:
8970 // LoopMustExits and LoopMayExits.
8971 //
8972 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
8973 // is a LoopMayExit. If any computable LoopMustExit is found, then
8974 // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
8975 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
8976 // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
8977 // any
8978 // computable EL.ConstantMaxNotTaken.
8979 if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
8980 DT.dominates(ExitBB, Latch)) {
8981 if (!MustExitMaxBECount) {
8982 MustExitMaxBECount = EL.ConstantMaxNotTaken;
8983 MustExitMaxOrZero = EL.MaxOrZero;
8984 } else {
8985 MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
8986 EL.ConstantMaxNotTaken);
8987 }
8988 } else if (MayExitMaxBECount != getCouldNotCompute()) {
8989 if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
8990 MayExitMaxBECount = EL.ConstantMaxNotTaken;
8991 else {
8992 MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
8993 EL.ConstantMaxNotTaken);
8994 }
8995 }
8996 }
8997 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
8998 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
8999 // The loop backedge will be taken the maximum or zero times if there's
9000 // a single exit that must be taken the maximum or zero times.
9001 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
9002
9003 // Remember which SCEVs are used in exit limits for invalidation purposes.
9004 // We only care about non-constant SCEVs here, so we can ignore
9005 // EL.ConstantMaxNotTaken
9006 // and MaxBECount, which must be SCEVConstant.
9007 for (const auto &Pair : ExitCounts) {
9008 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
9009 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
9010 if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
9011 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
9012 {L, AllowPredicates});
9013 }
9014 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
9015 MaxBECount, MaxOrZero);
9016}
9017
9018ScalarEvolution::ExitLimit
9019ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
9020 bool IsOnlyExit, bool AllowPredicates) {
9021 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
9022 // If our exiting block does not dominate the latch, then its connection with
9023 // loop's exit limit may be far from trivial.
9024 const BasicBlock *Latch = L->getLoopLatch();
9025 if (!Latch || !DT.dominates(ExitingBlock, Latch))
9026 return getCouldNotCompute();
9027
9028 Instruction *Term = ExitingBlock->getTerminator();
9029 if (CondBrInst *BI = dyn_cast<CondBrInst>(Term)) {
9030 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9031 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
9032 "It should have one successor in loop and one exit block!");
9033 // Proceed to the next level to examine the exit condition expression.
9034 return computeExitLimitFromCond(L, BI->getCondition(), ExitIfTrue,
9035 /*ControlsOnlyExit=*/IsOnlyExit,
9036 AllowPredicates);
9037 }
9038
9039 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
9040 // For switch, make sure that there is a single exit from the loop.
9041 BasicBlock *Exit = nullptr;
9042 for (auto *SBB : successors(ExitingBlock))
9043 if (!L->contains(SBB)) {
9044 if (Exit) // Multiple exit successors.
9045 return getCouldNotCompute();
9046 Exit = SBB;
9047 }
9048 assert(Exit && "Exiting block must have at least one exit");
9049 return computeExitLimitFromSingleExitSwitch(
9050 L, SI, Exit, /*ControlsOnlyExit=*/IsOnlyExit);
9051 }
9052
9053 return getCouldNotCompute();
9054}
9055
9057 const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9058 bool AllowPredicates) {
9059 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
9060 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
9061 ControlsOnlyExit, AllowPredicates);
9062}
9063
9064std::optional<ScalarEvolution::ExitLimit>
9065ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
9066 bool ExitIfTrue, bool ControlsOnlyExit,
9067 bool AllowPredicates) {
9068 (void)this->L;
9069 (void)this->ExitIfTrue;
9070 (void)this->AllowPredicates;
9071
9072 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9073 this->AllowPredicates == AllowPredicates &&
9074 "Variance in assumed invariant key components!");
9075 auto Itr = TripCountMap.find({ExitCond, ControlsOnlyExit});
9076 if (Itr == TripCountMap.end())
9077 return std::nullopt;
9078 return Itr->second;
9079}
9080
9081void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
9082 bool ExitIfTrue,
9083 bool ControlsOnlyExit,
9084 bool AllowPredicates,
9085 const ExitLimit &EL) {
9086 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9087 this->AllowPredicates == AllowPredicates &&
9088 "Variance in assumed invariant key components!");
9089
9090 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsOnlyExit}, EL});
9091 assert(InsertResult.second && "Expected successful insertion!");
9092 (void)InsertResult;
9093 (void)ExitIfTrue;
9094}
9095
9096ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
9097 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9098 bool ControlsOnlyExit, bool AllowPredicates) {
9099
9100 if (auto MaybeEL = Cache.find(L, ExitCond, ExitIfTrue, ControlsOnlyExit,
9101 AllowPredicates))
9102 return *MaybeEL;
9103
9104 ExitLimit EL = computeExitLimitFromCondImpl(
9105 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates);
9106 Cache.insert(L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates, EL);
9107 return EL;
9108}
9109
9110ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
9111 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9112 bool ControlsOnlyExit, bool AllowPredicates) {
9113 // Handle BinOp conditions (And, Or).
9114 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
9115 Cache, L, ExitCond, ExitIfTrue, AllowPredicates))
9116 return *LimitFromBinOp;
9117
9118 // With an icmp, it may be feasible to compute an exact backedge-taken count.
9119 // Proceed to the next level to examine the icmp.
9120 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
9121 ExitLimit EL =
9122 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsOnlyExit);
9123 if (EL.hasFullInfo() || !AllowPredicates)
9124 return EL;
9125
9126 // Try again, but use SCEV predicates this time.
9127 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue,
9128 ControlsOnlyExit,
9129 /*AllowPredicates=*/true);
9130 }
9131
9132 // Check for a constant condition. These are normally stripped out by
9133 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
9134 // preserve the CFG and is temporarily leaving constant conditions
9135 // in place.
9136 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
9137 if (ExitIfTrue == !CI->getZExtValue())
9138 // The backedge is always taken.
9139 return getCouldNotCompute();
9140 // The backedge is never taken.
9141 return getZero(CI->getType());
9142 }
9143
9144 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
9145 // with a constant step, we can form an equivalent icmp predicate and figure
9146 // out how many iterations will be taken before we exit.
9147 const WithOverflowInst *WO;
9148 const APInt *C;
9149 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
9150 match(WO->getRHS(), m_APInt(C))) {
9151 ConstantRange NWR =
9153 WO->getNoWrapKind());
9155 APInt NewRHSC, Offset;
9156 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
9157 if (!ExitIfTrue)
9159 auto *LHS = getSCEV(WO->getLHS());
9160 if (Offset != 0)
9162 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
9163 ControlsOnlyExit, AllowPredicates);
9164 if (EL.hasAnyInfo())
9165 return EL;
9166 }
9167
9168 // If it's not an integer or pointer comparison then compute it the hard way.
9169 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9170}
9171
9172std::optional<ScalarEvolution::ExitLimit>
9173ScalarEvolution::computeExitLimitFromCondFromBinOp(ExitLimitCacheTy &Cache,
9174 const Loop *L,
9175 Value *ExitCond,
9176 bool ExitIfTrue,
9177 bool AllowPredicates) {
9178 // Check if the controlling expression for this loop is an And or Or.
9179 Value *Op0, *Op1;
9180 bool IsAnd;
9181 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
9182 IsAnd = true;
9183 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
9184 IsAnd = false;
9185 else
9186 return std::nullopt;
9187
9188 // A sub-condition of a non-trivial binop never solely controls the exit,
9189 // whether we exit always depends on both conditions.
9190 ExitLimit EL0 = computeExitLimitFromCondCached(
9191 Cache, L, Op0, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9192 ExitLimit EL1 = computeExitLimitFromCondCached(
9193 Cache, L, Op1, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9194
9195 // EitherMayExit is true in these two cases:
9196 // br (and Op0 Op1), loop, exit
9197 // br (or Op0 Op1), exit, loop
9198 bool EitherMayExit = IsAnd ^ ExitIfTrue;
9199
9200 const SCEV *BECount = getCouldNotCompute();
9201 const SCEV *ConstantMaxBECount = getCouldNotCompute();
9202 const SCEV *SymbolicMaxBECount = getCouldNotCompute();
9203 if (EitherMayExit) {
9204 bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
9205 // Both conditions must be same for the loop to continue executing.
9206 // Choose the less conservative count.
9207 if (EL0.ExactNotTaken != getCouldNotCompute() &&
9208 EL1.ExactNotTaken != getCouldNotCompute()) {
9209 BECount = getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken,
9210 UseSequentialUMin);
9211 }
9212 if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
9213 ConstantMaxBECount = EL1.ConstantMaxNotTaken;
9214 else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
9215 ConstantMaxBECount = EL0.ConstantMaxNotTaken;
9216 else
9217 ConstantMaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
9218 EL1.ConstantMaxNotTaken);
9219 if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
9220 SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
9221 else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
9222 SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
9223 else
9224 SymbolicMaxBECount = getUMinFromMismatchedTypes(
9225 EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
9226 } else {
9227 // Both conditions must be same at the same time for the loop to exit.
9228 // For now, be conservative.
9229 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
9230 BECount = EL0.ExactNotTaken;
9231 }
9232
9233 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
9234 // to be more aggressive when computing BECount than when computing
9235 // ConstantMaxBECount. In these cases it is possible for EL0.ExactNotTaken
9236 // and
9237 // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
9238 // EL1.ConstantMaxNotTaken to not.
9239 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
9240 !isa<SCEVCouldNotCompute>(BECount))
9241 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
9242 if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
9243 SymbolicMaxBECount =
9244 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
9245 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
9246 {ArrayRef(EL0.Predicates), ArrayRef(EL1.Predicates)});
9247}
9248
9249ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9250 const Loop *L, ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9251 bool AllowPredicates) {
9252 // If the condition was exit on true, convert the condition to exit on false
9253 CmpPredicate Pred;
9254 if (!ExitIfTrue)
9255 Pred = ExitCond->getCmpPredicate();
9256 else
9257 Pred = ExitCond->getInverseCmpPredicate();
9258 const ICmpInst::Predicate OriginalPred = Pred;
9259
9260 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
9261 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
9262
9263 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsOnlyExit,
9264 AllowPredicates);
9265 if (EL.hasAnyInfo())
9266 return EL;
9267
9268 auto *ExhaustiveCount =
9269 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9270
9271 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
9272 return ExhaustiveCount;
9273
9274 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
9275 ExitCond->getOperand(1), L, OriginalPred);
9276}
9277ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9278 const Loop *L, CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS,
9279 bool ControlsOnlyExit, bool AllowPredicates) {
9280
9281 // Try to evaluate any dependencies out of the loop.
9282 LHS = getSCEVAtScope(LHS, L);
9283 RHS = getSCEVAtScope(RHS, L);
9284
9285 // At this point, we would like to compute how many iterations of the
9286 // loop the predicate will return true for these inputs.
9287 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
9288 // If there is a loop-invariant, force it into the RHS.
9289 std::swap(LHS, RHS);
9291 }
9292
9293 bool ControllingFiniteLoop = ControlsOnlyExit && loopHasNoAbnormalExits(L) &&
9295 // Simplify the operands before analyzing them.
9296 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0);
9297
9298 // If we have a comparison of a chrec against a constant, try to use value
9299 // ranges to answer this query.
9300 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
9301 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
9302 if (AddRec->getLoop() == L) {
9303 // Form the constant range.
9304 ConstantRange CompRange =
9305 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
9306
9307 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
9308 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
9309 }
9310
9311 // If this loop must exit based on this condition (or execute undefined
9312 // behaviour), see if we can improve wrap flags. This is essentially
9313 // a must execute style proof.
9314 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
9315 // If we can prove the test sequence produced must repeat the same values
9316 // on self-wrap of the IV, then we can infer that IV doesn't self wrap
9317 // because if it did, we'd have an infinite (undefined) loop.
9318 // TODO: We can peel off any functions which are invertible *in L*. Loop
9319 // invariant terms are effectively constants for our purposes here.
9320 SCEVUse InnerLHS = LHS;
9321 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
9322 InnerLHS = ZExt->getOperand();
9323 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS);
9324 AR && !AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
9325 isKnownToBeAPowerOfTwo(AR->getStepRecurrence(*this), /*OrZero=*/true,
9326 /*OrNegative=*/true)) {
9327 auto Flags = AR->getNoWrapFlags();
9328 Flags = setFlags(Flags, SCEV::FlagNW);
9331 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9332 }
9333
9334 // For a slt/ult condition with a positive step, can we prove nsw/nuw?
9335 // From no-self-wrap, this follows trivially from the fact that every
9336 // (un)signed-wrapped, but not self-wrapped value must be LT than the
9337 // last value before (un)signed wrap. Since we know that last value
9338 // didn't exit, nor will any smaller one.
9340 auto WrapType = Pred == ICmpInst::ICMP_SLT ? SCEV::FlagNSW : SCEV::FlagNUW;
9341 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9342 AR && AR->getLoop() == L && AR->isAffine() &&
9343 !AR->getNoWrapFlags(WrapType) && AR->hasNoSelfWrap() &&
9344 isKnownPositive(AR->getStepRecurrence(*this))) {
9345 auto Flags = AR->getNoWrapFlags();
9346 Flags = setFlags(Flags, WrapType);
9349 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9350 }
9351 }
9352 }
9353
9354 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
9355 switch (Pred) {
9356 case ICmpInst::ICMP_NE: { // while (X != Y)
9357 // Convert to: while (X-Y != 0)
9358 if (LHS->getType()->isPointerTy()) {
9361 return LHS;
9362 }
9363 if (RHS->getType()->isPointerTy()) {
9366 return RHS;
9367 }
9368 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit,
9369 AllowPredicates);
9370 if (EL.hasAnyInfo())
9371 return EL;
9372 break;
9373 }
9374 case ICmpInst::ICMP_EQ: { // while (X == Y)
9375 // Convert to: while (X-Y == 0)
9376 if (LHS->getType()->isPointerTy()) {
9379 return LHS;
9380 }
9381 if (RHS->getType()->isPointerTy()) {
9384 return RHS;
9385 }
9386 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
9387 if (EL.hasAnyInfo()) return EL;
9388 break;
9389 }
9390 case ICmpInst::ICMP_SLE:
9391 case ICmpInst::ICMP_ULE:
9392 // Since the loop is finite, an invariant RHS cannot include the boundary
9393 // value, otherwise it would loop forever.
9394 if (!Opts.scalar_evolution_finite_loop || !ControllingFiniteLoop ||
9395 !isLoopInvariant(RHS, L)) {
9396 // Otherwise, perform the addition in a wider type, to avoid overflow.
9397 // If the LHS is an addrec with the appropriate nowrap flag, the
9398 // extension will be sunk into it and the exit count can be analyzed.
9399 auto *OldType = dyn_cast<IntegerType>(LHS->getType());
9400 if (!OldType)
9401 break;
9402 // If RHS < MAX on entry to the loop, RHS + 1 does not wrap.
9403 bool IsSigned = ICmpInst::isSigned(Pred);
9404 APInt Max = IsSigned ? APInt::getSignedMaxValue(OldType->getBitWidth())
9405 : APInt::getMaxValue(OldType->getBitWidth());
9406 auto IsLessThanMax = [&] {
9407 const SCEV *GuardedRHS = applyLoopGuards(RHS, Guards);
9408 return IsSigned ? getSignedRangeMax(GuardedRHS).slt(Max)
9409 : getUnsignedRangeMax(GuardedRHS).ult(Max);
9410 };
9411 if (isLoopInvariant(RHS, L) && IsLessThanMax()) {
9412 // The guard only holds at loop entry, so record the no-wrap fact on
9413 // this use of the add instead of the shared expression.
9415 getOne(OldType), RHS,
9417 ExitLimit EL = howManyLessThans(LHS, Next, L, Guards, IsSigned,
9418 /*Invert=*/false, ControlsOnlyExit,
9419 AllowPredicates);
9420 if (EL.hasFullInfo())
9421 return EL;
9422 }
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 =
9441 howManyLessThans(LHS, RHS, L, Guards, IsSigned,
9442 /*Invert=*/false, ControlsOnlyExit, AllowPredicates);
9443 if (EL.hasAnyInfo())
9444 return EL;
9445 break;
9446 }
9447 case ICmpInst::ICMP_SGE:
9448 case ICmpInst::ICMP_UGE:
9449 // Since the loop is finite, an invariant RHS cannot include the boundary
9450 // value, otherwise it would loop forever.
9451 if (!Opts.scalar_evolution_finite_loop || !ControllingFiniteLoop ||
9452 !isLoopInvariant(RHS, L))
9453 break;
9455 [[fallthrough]];
9456 case ICmpInst::ICMP_SGT:
9457 case ICmpInst::ICMP_UGT: { // while (X > Y)
9458 // "X > Y" is analyzed as the equivalent "~X < ~Y".
9459 bool IsSigned = ICmpInst::isSigned(Pred);
9460 ExitLimit EL =
9461 howManyLessThans(LHS, RHS, L, Guards, IsSigned,
9462 /*Invert=*/true, ControlsOnlyExit, AllowPredicates);
9463 if (EL.hasAnyInfo())
9464 return EL;
9465 break;
9466 }
9467 default:
9468 break;
9469 }
9470
9471 return getCouldNotCompute();
9472}
9473
9474ScalarEvolution::ExitLimit
9475ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
9476 SwitchInst *Switch,
9477 BasicBlock *ExitingBlock,
9478 bool ControlsOnlyExit) {
9479 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
9480
9481 // Give up if the exit is the default dest of a switch.
9482 if (Switch->getDefaultDest() == ExitingBlock)
9483 return getCouldNotCompute();
9484
9485 assert(L->contains(Switch->getDefaultDest()) &&
9486 "Default case must not exit the loop!");
9487 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
9488 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
9489
9490 // while (X != Y) --> while (X-Y != 0)
9491 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit);
9492 if (EL.hasAnyInfo())
9493 return EL;
9494
9495 return getCouldNotCompute();
9496}
9497
9498static ConstantInt *
9500 ScalarEvolution &SE) {
9501 const SCEV *InVal = SE.getConstant(C);
9502 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
9504 "Evaluation of SCEV at constant didn't fold correctly?");
9505 return cast<SCEVConstant>(Val)->getValue();
9506}
9507
9508ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
9509 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
9510 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
9511 if (!RHS)
9512 return getCouldNotCompute();
9513
9514 const BasicBlock *Latch = L->getLoopLatch();
9515 if (!Latch)
9516 return getCouldNotCompute();
9517
9518 const BasicBlock *Predecessor = L->getLoopPredecessor();
9519 if (!Predecessor)
9520 return getCouldNotCompute();
9521
9522 // Return true if V is of the form "LHS `shift_op` <positive constant>".
9523 // Return LHS in OutLHS, shift_op in OutOpCode, and the shift amount in
9524 // OutShiftAmt.
9525 auto MatchPositiveShift = [](Value *V, Value *&OutLHS,
9526 Instruction::BinaryOps &OutOpCode,
9527 unsigned &OutShiftAmt) {
9528 using namespace PatternMatch;
9529
9530 ConstantInt *ShiftAmt;
9531 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9532 OutOpCode = Instruction::LShr;
9533 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9534 OutOpCode = Instruction::AShr;
9535 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9536 OutOpCode = Instruction::Shl;
9537 else
9538 return false;
9539
9540 uint64_t Amt = ShiftAmt->getValue().getLimitedValue();
9541 if (Amt == 0 || Amt >= OutLHS->getType()->getScalarSizeInBits())
9542 return false;
9543 OutShiftAmt = Amt;
9544 return true;
9545 };
9546
9547 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
9548 //
9549 // loop:
9550 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
9551 // %iv.shifted = lshr i32 %iv, <positive constant>
9552 //
9553 // Return true on a successful match. Return the corresponding PHI node (%iv
9554 // above) in PNOut, the opcode of the shift operation in OpCodeOut, and the
9555 // shift amount in ShiftAmtOut.
9556 auto MatchShiftRecurrence = [&](Value *V, PHINode *&PNOut,
9557 Instruction::BinaryOps &OpCodeOut,
9558 unsigned &ShiftAmtOut) {
9559 std::optional<Instruction::BinaryOps> PostShiftOpCode;
9560
9561 {
9563 Value *V;
9564 unsigned Amt;
9565
9566 // If we encounter a shift instruction, "peel off" the shift operation,
9567 // and remember that we did so. Later when we inspect %iv's backedge
9568 // value, we will make sure that the backedge value uses the same
9569 // operation.
9570 //
9571 // Note: the peeled shift operation does not have to be the same
9572 // instruction as the one feeding into the PHI's backedge value. We only
9573 // really care about it being the same *kind* of shift instruction --
9574 // that's all that is required for our later inferences to hold.
9575 if (MatchPositiveShift(LHS, V, OpC, Amt)) {
9576 PostShiftOpCode = OpC;
9577 LHS = V;
9578 }
9579 }
9580
9581 PNOut = dyn_cast<PHINode>(LHS);
9582 if (!PNOut || PNOut->getParent() != L->getHeader())
9583 return false;
9584
9585 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
9586 Value *OpLHS;
9587
9588 return
9589 // The backedge value for the PHI node must be a shift by a positive
9590 // amount
9591 MatchPositiveShift(BEValue, OpLHS, OpCodeOut, ShiftAmtOut) &&
9592
9593 // of the PHI node itself
9594 OpLHS == PNOut &&
9595
9596 // and the kind of shift should be match the kind of shift we peeled
9597 // off, if any.
9598 (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9599 };
9600
9601 PHINode *PN;
9603 unsigned ShiftAmt;
9604 if (!MatchShiftRecurrence(LHS, PN, OpCode, ShiftAmt))
9605 return getCouldNotCompute();
9606
9607 const DataLayout &DL = getDataLayout();
9608
9609 // The key rationale for this optimization is that for some kinds of shift
9610 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
9611 // within a finite number of iterations. If the condition guarding the
9612 // backedge (in the sense that the backedge is taken if the condition is true)
9613 // is false for the value the shift recurrence stabilizes to, then we know
9614 // that the backedge is taken only a finite number of times.
9615
9616 ConstantInt *StableValue = nullptr;
9617 switch (OpCode) {
9618 default:
9619 llvm_unreachable("Impossible case!");
9620
9621 case Instruction::AShr: {
9622 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
9623 // bitwidth(K) iterations.
9624 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
9625 KnownBits Known = computeKnownBits(FirstValue, DL, &AC,
9626 Predecessor->getTerminator(), &DT);
9627 auto *Ty = cast<IntegerType>(RHS->getType());
9628 if (Known.isNonNegative())
9629 StableValue = ConstantInt::get(Ty, 0);
9630 else if (Known.isNegative())
9631 StableValue = ConstantInt::get(Ty, -1, true);
9632 else
9633 return getCouldNotCompute();
9634
9635 break;
9636 }
9637 case Instruction::LShr:
9638 case Instruction::Shl:
9639 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
9640 // stabilize to 0 in at most bitwidth(K) iterations.
9641 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
9642 break;
9643 }
9644
9645 auto *Result =
9646 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
9647 assert(Result->getType()->isIntegerTy(1) &&
9648 "Otherwise cannot be an operand to a branch instruction");
9649
9650 if (Result->isNullValue()) {
9651 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9652 unsigned MaxBTC = BitWidth;
9653
9654 // For right-shift recurrences (lshr/ashr with non-negative start), we can
9655 // compute a tighter max backedge-taken count from the range of the start
9656 // value. After k shifts of ShiftAmt, value = start >> (k * ShiftAmt).
9657 // The value reaches 0 (the stable value) when k * ShiftAmt >=
9658 // activeBits(start), so max BTC = ceil(activeBits(maxStart) / ShiftAmt).
9659 if (OpCode == Instruction::LShr || OpCode == Instruction::AShr) {
9660 Value *StartValue = PN->getIncomingValueForBlock(Predecessor);
9661 const SCEV *StartSCEV = getSCEV(StartValue);
9662 APInt MaxStart = getUnsignedRangeMax(StartSCEV);
9663 if (MaxStart.isStrictlyPositive()) {
9664 unsigned ActiveBits = MaxStart.getActiveBits();
9665 unsigned RangeBTC = divideCeil(ActiveBits, ShiftAmt);
9666 MaxBTC = std::min(MaxBTC, RangeBTC);
9667 }
9668 }
9669
9670 const SCEV *UpperBound =
9672 return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
9673 }
9674
9675 return getCouldNotCompute();
9676}
9677
9678/// Return true if we can constant fold an instruction of the specified type,
9679/// assuming that all operands were constants.
9680static bool canConstantFold(const Instruction *I,
9681 const TargetLibraryInfo *TLI) {
9685 return true;
9686
9687 if (const CallInst *CI = dyn_cast<CallInst>(I))
9688 if (const Function *F = CI->getCalledFunction())
9689 return canConstantFoldCallTo(CI, F, TLI);
9690 return false;
9691}
9692
9693/// Determine whether this instruction can constant evolve within this loop
9694/// assuming its operands can all constant evolve.
9695static bool canConstantEvolve(Instruction *I, const Loop *L,
9696 const TargetLibraryInfo *TLI) {
9697 // An instruction outside of the loop can't be derived from a loop PHI.
9698 if (!L->contains(I)) return false;
9699
9700 if (isa<PHINode>(I)) {
9701 // We don't currently keep track of the control flow needed to evaluate
9702 // PHIs, so we cannot handle PHIs inside of loops.
9703 return L->getHeader() == I->getParent();
9704 }
9705
9706 // If we won't be able to constant fold this expression even if the operands
9707 // are constants, bail early.
9708 return canConstantFold(I, TLI);
9709}
9710
9711/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
9712/// recursing through each instruction operand until reaching a loop header phi.
9713static PHINode *
9714getConstantEvolvingPHIOperands(const AnalysisOptions &Opts,
9715 Instruction *UseInst, const Loop *L,
9717 const TargetLibraryInfo *TLI, unsigned Depth) {
9718 if (Depth > Opts.scalar_evolution_max_constant_evolving_depth)
9719 return nullptr;
9720
9721 // Otherwise, we can evaluate this instruction if all of its operands are
9722 // constant or derived from a PHI node themselves.
9723 PHINode *PHI = nullptr;
9724 for (Value *Op : UseInst->operands()) {
9725 if (isa<Constant>(Op)) continue;
9726
9728 if (!OpInst || !canConstantEvolve(OpInst, L, TLI))
9729 return nullptr;
9730
9731 PHINode *P = dyn_cast<PHINode>(OpInst);
9732 if (!P)
9733 // If this operand is already visited, reuse the prior result.
9734 // We may have P != PHI if this is the deepest point at which the
9735 // inconsistent paths meet.
9736 P = PHIMap.lookup(OpInst);
9737 if (!P) {
9738 // Recurse and memoize the results, whether a phi is found or not.
9739 // This recursive call invalidates pointers into PHIMap.
9740 P = getConstantEvolvingPHIOperands(Opts, OpInst, L, PHIMap, TLI,
9741 Depth + 1);
9742 PHIMap[OpInst] = P;
9743 }
9744 if (!P)
9745 return nullptr; // Not evolving from PHI
9746 if (PHI && PHI != P)
9747 return nullptr; // Evolving from multiple different PHIs.
9748 PHI = P;
9749 }
9750 // This is a expression evolving from a constant PHI!
9751 return PHI;
9752}
9753
9754/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9755/// in the loop that V is derived from. We allow arbitrary operations along the
9756/// way, but the operands of an operation must either be constants or a value
9757/// derived from a constant PHI. If this expression does not fit with these
9758/// constraints, return null.
9759static PHINode *getConstantEvolvingPHI(const AnalysisOptions &Opts, Value *V,
9760 const Loop *L,
9761 const TargetLibraryInfo *TLI) {
9763 if (!I || !canConstantEvolve(I, L, TLI))
9764 return nullptr;
9765
9766 if (PHINode *PN = dyn_cast<PHINode>(I))
9767 return PN;
9768
9769 // Record non-constant instructions contained by the loop.
9771 return getConstantEvolvingPHIOperands(Opts, I, L, PHIMap, TLI, 0);
9772}
9773
9774/// EvaluateExpression - Given an expression that passes the
9775/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9776/// in the loop has the value PHIVal. If we can't fold this expression for some
9777/// reason, return null.
9780 const DataLayout &DL,
9781 const TargetLibraryInfo *TLI) {
9782 // Convenient constant check, but redundant for recursive calls.
9783 if (Constant *C = dyn_cast<Constant>(V)) return C;
9785 if (!I) return nullptr;
9786
9787 if (Constant *C = Vals.lookup(I)) return C;
9788
9789 // An instruction inside the loop depends on a value outside the loop that we
9790 // weren't given a mapping for, or a value such as a call inside the loop.
9791 if (!canConstantEvolve(I, L, TLI))
9792 return nullptr;
9793
9794 // An unmapped PHI can be due to a branch or another loop inside this loop,
9795 // or due to this not being the initial iteration through a loop where we
9796 // couldn't compute the evolution of this particular PHI last time.
9797 if (isa<PHINode>(I)) return nullptr;
9798
9799 std::vector<Constant*> Operands(I->getNumOperands());
9800
9801 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9802 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9803 if (!Operand) {
9804 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9805 if (!Operands[i]) return nullptr;
9806 continue;
9807 }
9808 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9809 Vals[Operand] = C;
9810 if (!C) return nullptr;
9811 Operands[i] = C;
9812 }
9813
9815 /*AllowNonDeterministic=*/false);
9816}
9817
9818
9819// If every incoming value to PN except the one for BB is a specific Constant,
9820// return that, else return nullptr.
9822 Constant *IncomingVal = nullptr;
9823
9824 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9825 if (PN->getIncomingBlock(i) == BB)
9826 continue;
9827
9828 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
9829 if (!CurrentVal)
9830 return nullptr;
9831
9832 if (IncomingVal != CurrentVal) {
9833 if (IncomingVal)
9834 return nullptr;
9835 IncomingVal = CurrentVal;
9836 }
9837 }
9838
9839 return IncomingVal;
9840}
9841
9842/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9843/// in the header of its containing loop, we know the loop executes a
9844/// constant number of times, and the PHI node is just a recurrence
9845/// involving constants, fold it.
9846Constant *
9847ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9848 const APInt &BEs,
9849 const Loop *L) {
9850 auto [I, Inserted] = ConstantEvolutionLoopExitValue.try_emplace(PN);
9851 if (!Inserted)
9852 return I->second;
9853
9854 if (BEs.ugt(Opts.scalar_evolution_max_iterations))
9855 return nullptr; // Not going to evaluate it.
9856
9857 Constant *&RetVal = I->second;
9858
9859 DenseMap<Instruction *, Constant *> CurrentIterVals;
9860 BasicBlock *Header = L->getHeader();
9861 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9862
9863 BasicBlock *Latch = L->getLoopLatch();
9864 if (!Latch)
9865 return nullptr;
9866
9867 for (PHINode &PHI : Header->phis()) {
9868 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9869 CurrentIterVals[&PHI] = StartCST;
9870 }
9871 if (!CurrentIterVals.count(PN))
9872 return RetVal = nullptr;
9873
9874 Value *BEValue = PN->getIncomingValueForBlock(Latch);
9875
9876 // Execute the loop symbolically to determine the exit value.
9877 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
9878 "BEs is <= -scalar-evolution-max-iterations which is an 'unsigned'!");
9879
9880 unsigned NumIterations = BEs.getZExtValue(); // must be in range
9881 unsigned IterationNum = 0;
9882 const DataLayout &DL = getDataLayout();
9883 for (; ; ++IterationNum) {
9884 if (IterationNum == NumIterations)
9885 return RetVal = CurrentIterVals[PN]; // Got exit value!
9886
9887 // Compute the value of the PHIs for the next iteration.
9888 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9889 DenseMap<Instruction *, Constant *> NextIterVals;
9890 Constant *NextPHI =
9891 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9892 if (!NextPHI)
9893 return nullptr; // Couldn't evaluate!
9894 NextIterVals[PN] = NextPHI;
9895
9896 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9897
9898 // Also evaluate the other PHI nodes. However, we don't get to stop if we
9899 // cease to be able to evaluate one of them or if they stop evolving,
9900 // because that doesn't necessarily prevent us from computing PN.
9902 for (const auto &I : CurrentIterVals) {
9903 PHINode *PHI = dyn_cast<PHINode>(I.first);
9904 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
9905 PHIsToCompute.emplace_back(PHI, I.second);
9906 }
9907 // We use two distinct loops because EvaluateExpression may invalidate any
9908 // iterators into CurrentIterVals.
9909 for (const auto &I : PHIsToCompute) {
9910 PHINode *PHI = I.first;
9911 Constant *&NextPHI = NextIterVals[PHI];
9912 if (!NextPHI) { // Not already computed.
9913 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9914 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9915 }
9916 if (NextPHI != I.second)
9917 StoppedEvolving = false;
9918 }
9919
9920 // If all entries in CurrentIterVals == NextIterVals then we can stop
9921 // iterating, the loop can't continue to change.
9922 if (StoppedEvolving)
9923 return RetVal = CurrentIterVals[PN];
9924
9925 CurrentIterVals.swap(NextIterVals);
9926 }
9927}
9928
9929const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
9930 Value *Cond,
9931 bool ExitWhen) {
9932 PHINode *PN = getConstantEvolvingPHI(Opts, Cond, L, &TLI);
9933 if (!PN) return getCouldNotCompute();
9934
9935 // If the loop is canonicalized, the PHI will have exactly two entries.
9936 // That's the only form we support here.
9937 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
9938
9939 DenseMap<Instruction *, Constant *> CurrentIterVals;
9940 BasicBlock *Header = L->getHeader();
9941 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9942
9943 BasicBlock *Latch = L->getLoopLatch();
9944 assert(Latch && "Should follow from NumIncomingValues == 2!");
9945
9946 for (PHINode &PHI : Header->phis()) {
9947 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9948 CurrentIterVals[&PHI] = StartCST;
9949 }
9950 if (!CurrentIterVals.count(PN))
9951 return getCouldNotCompute();
9952
9953 // Okay, we find a PHI node that defines the trip count of this loop. Execute
9954 // the loop symbolically to determine when the condition gets a value of
9955 // "ExitWhen".
9956 unsigned MaxIterations =
9957 Opts.scalar_evolution_max_iterations; // Limit analysis.
9958 const DataLayout &DL = getDataLayout();
9959 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
9960 auto *CondVal = dyn_cast_or_null<ConstantInt>(
9961 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
9962
9963 // Couldn't symbolically evaluate.
9964 if (!CondVal) return getCouldNotCompute();
9965
9966 if (CondVal->getValue() == uint64_t(ExitWhen)) {
9967 ++NumBruteForceTripCountsComputed;
9968 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
9969 }
9970
9971 // Update all the PHI nodes for the next iteration.
9972 DenseMap<Instruction *, Constant *> NextIterVals;
9973
9974 // Create a list of which PHIs we need to compute. We want to do this before
9975 // calling EvaluateExpression on them because that may invalidate iterators
9976 // into CurrentIterVals.
9977 SmallVector<PHINode *, 8> PHIsToCompute;
9978 for (const auto &I : CurrentIterVals) {
9979 PHINode *PHI = dyn_cast<PHINode>(I.first);
9980 if (!PHI || PHI->getParent() != Header) continue;
9981 PHIsToCompute.push_back(PHI);
9982 }
9983 for (PHINode *PHI : PHIsToCompute) {
9984 Constant *&NextPHI = NextIterVals[PHI];
9985 if (NextPHI) continue; // Already computed!
9986
9987 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9988 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9989 }
9990 CurrentIterVals.swap(NextIterVals);
9991 }
9992
9993 // Too many iterations were needed to evaluate.
9994 return getCouldNotCompute();
9995}
9996
9998 if (isa<SCEVConstant>(V))
9999 return V;
10000
10001 auto &Values = ValuesAtScopes[V];
10002 // Check to see if we've folded this expression at this loop before.
10003 for (auto &LS : Values)
10004 if (LS.first == L)
10005 return LS.second ? LS.second : SCEVUse(V);
10006
10007 Values.emplace_back(L, nullptr);
10008
10009 // Otherwise compute it.
10010 SCEVUse C = computeSCEVAtScope(V, L);
10011 for (auto &LS : reverse(ValuesAtScopes[V]))
10012 if (LS.first == L) {
10013 LS.second = C;
10014 // Record the dependency under the bare expression: invalidation walks
10015 // expressions, and any use flags on C do not change which expression
10016 // this is the value at scope of.
10017 if (!isa<SCEVConstant>(C))
10018 ValuesAtScopesUsers[C.getPointer()].push_back({L, V});
10019 break;
10020 }
10021 return C;
10022}
10023
10025 const BasicBlock *ExitingBlock) {
10026 SCEVUse ExitValue = getSCEVAtScope(V, L->getParentLoop());
10027 if (!isLoopInvariant(ExitValue, L)) {
10028 // If we failed to evaluate it in the outer scope, try to evaluate an
10029 // addrec for the specific exit.
10030 // TODO: Generalize this to other expressions.
10031 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
10032 if (!isa<SCEVCouldNotCompute>(ExitCount))
10033 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V))
10034 if (AddRec->getLoop() == L)
10035 ExitValue = AddRec->evaluateAtIteration(ExitCount, *this);
10036 }
10037 return ExitValue;
10038}
10039
10040/// This builds up a Constant using the ConstantExpr interface. That way, we
10041/// will return Constants for objects which aren't represented by a
10042/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
10043/// Returns NULL if the SCEV isn't representable as a Constant.
10045 switch (V->getSCEVType()) {
10046 case scCouldNotCompute:
10047 case scAddRecExpr:
10048 case scVScale:
10049 return nullptr;
10050 case scConstant:
10051 return cast<SCEVConstant>(V)->getValue();
10052 case scUnknown:
10054 case scPtrToAddr: {
10056 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
10057 return ConstantExpr::getPtrToAddr(CastOp, P2I->getType());
10058
10059 return nullptr;
10060 }
10061 case scTruncate: {
10063 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
10064 return ConstantExpr::getTrunc(CastOp, ST->getType());
10065 return nullptr;
10066 }
10067 case scAddExpr: {
10068 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
10069 Constant *C = nullptr;
10070 for (const SCEV *Op : SA->operands()) {
10072 if (!OpC)
10073 return nullptr;
10074 if (!C) {
10075 C = OpC;
10076 continue;
10077 }
10078 assert(!C->getType()->isPointerTy() &&
10079 "Can only have one pointer, and it must be last");
10080 if (OpC->getType()->isPointerTy()) {
10081 // The offsets have been converted to bytes. We can add bytes using
10082 // an i8 GEP.
10083 C = ConstantExpr::getPtrAdd(OpC, C);
10084 } else {
10085 C = ConstantExpr::getAdd(C, OpC);
10086 }
10087 }
10088 return C;
10089 }
10090 case scMulExpr:
10091 case scSignExtend:
10092 case scZeroExtend:
10093 case scUDivExpr:
10094 case scSMaxExpr:
10095 case scUMaxExpr:
10096 case scSMinExpr:
10097 case scUMinExpr:
10099 return nullptr;
10100 }
10101 llvm_unreachable("Unknown SCEV kind!");
10102}
10103
10104const SCEV *ScalarEvolution::getWithOperands(const SCEV *S,
10105 SmallVectorImpl<SCEVUse> &NewOps) {
10106 switch (S->getSCEVType()) {
10107 case scTruncate:
10108 case scZeroExtend:
10109 case scSignExtend:
10110 case scPtrToAddr:
10111 return getCastExpr(S->getSCEVType(), NewOps[0], S->getType());
10112 case scAddRecExpr: {
10113 auto *AddRec = cast<SCEVAddRecExpr>(S);
10114 return getAddRecExpr(NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags());
10115 }
10116 case scAddExpr:
10117 return getAddExpr(NewOps, cast<SCEVAddExpr>(S)->getNoWrapFlags());
10118 case scMulExpr:
10119 return getMulExpr(NewOps, cast<SCEVMulExpr>(S)->getNoWrapFlags());
10120 case scUDivExpr:
10121 return getUDivExpr(NewOps[0], NewOps[1]);
10122 case scUMaxExpr:
10123 case scSMaxExpr:
10124 case scUMinExpr:
10125 case scSMinExpr:
10126 return getMinMaxExpr(S->getSCEVType(), NewOps);
10128 return getSequentialMinMaxExpr(S->getSCEVType(), NewOps);
10129 case scConstant:
10130 case scVScale:
10131 case scUnknown:
10132 return S;
10133 case scCouldNotCompute:
10134 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10135 }
10136 llvm_unreachable("Unknown SCEV kind!");
10137}
10138
10139SCEVUse ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
10140 switch (V->getSCEVType()) {
10141 case scConstant:
10142 case scVScale:
10143 return V;
10144 case scAddRecExpr: {
10145 // If this is a loop recurrence for a loop that does not contain L, then we
10146 // are dealing with the final value computed by the loop.
10147 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(V);
10148 // First, attempt to evaluate each operand.
10149 // Avoid performing the look-up in the common case where the specified
10150 // expression has no loop-variant portions.
10151 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
10152 SCEVUse OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
10153 if (OpAtScope == AddRec->getOperand(i))
10154 continue;
10155
10156 // Okay, at least one of these operands is loop variant but might be
10157 // foldable. Build a new instance of the folded commutative expression.
10159 NewOps.reserve(AddRec->getNumOperands());
10160 append_range(NewOps, AddRec->operands().take_front(i));
10161 NewOps.push_back(OpAtScope);
10162 for (++i; i != e; ++i)
10163 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
10164
10165 // nw does not depend on the start, so only keep it if no other operand
10166 // changed.
10167 const SCEV *FoldedRec = getAddRecExpr(
10168 NewOps, AddRec->getLoop(),
10169 equal(drop_begin(NewOps), drop_begin(AddRec->operands()))
10170 ? AddRec->getNoWrapFlags(SCEV::FlagNW)
10171 : SCEV::FlagNone);
10172 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
10173 // The addrec may be folded to a nonrecurrence, for example, if the
10174 // induction variable is multiplied by zero after constant folding. Go
10175 // ahead and return the folded value.
10176 if (!AddRec)
10177 return FoldedRec;
10178 break;
10179 }
10180
10181 // If the scope is outside the addrec's loop, evaluate it by using the
10182 // loop exit value of the addrec.
10183 if (!AddRec->getLoop()->contains(L)) {
10184 SCEVUse ExitValue = AddRec->getExitValue(*this);
10185 if (isa<SCEVCouldNotCompute>(ExitValue))
10186 return AddRec;
10187 return ExitValue;
10188 }
10189
10190 return AddRec;
10191 }
10192 case scTruncate:
10193 case scZeroExtend:
10194 case scSignExtend:
10195 case scPtrToAddr:
10196 case scAddExpr:
10197 case scMulExpr:
10198 case scUDivExpr:
10199 case scUMaxExpr:
10200 case scSMaxExpr:
10201 case scUMinExpr:
10202 case scSMinExpr:
10203 case scSequentialUMinExpr: {
10204 ArrayRef<SCEVUse> Ops = V->operands();
10205 // Avoid performing the look-up in the common case where the specified
10206 // expression has no loop-variant portions.
10207 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
10208 SCEVUse OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10209 if (OpAtScope != Ops[i].getPointer()) {
10210 // Okay, at least one of these operands is loop variant but might be
10211 // foldable. Build a new instance of the folded commutative expression.
10213 NewOps.reserve(Ops.size());
10214 append_range(NewOps, Ops.take_front(i));
10215 NewOps.push_back(OpAtScope);
10216
10217 for (++i; i != e; ++i) {
10218 OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10219 NewOps.push_back(OpAtScope);
10220 }
10221
10222 return getWithOperands(V, NewOps);
10223 }
10224 }
10225 // If we got here, all operands are loop invariant.
10226 return V;
10227 }
10228 case scUnknown: {
10229 // If this instruction is evolved from a constant-evolving PHI, compute the
10230 // exit value from the loop without using SCEVs.
10231 const SCEVUnknown *SU = cast<SCEVUnknown>(V);
10233 if (!I)
10234 return V; // This is some other type of SCEVUnknown, just return it.
10235
10236 if (PHINode *PN = dyn_cast<PHINode>(I)) {
10237 const Loop *CurrLoop = this->LI[I->getParent()];
10238 // Looking for loop exit value.
10239 if (CurrLoop && CurrLoop->getParentLoop() == L &&
10240 PN->getParent() == CurrLoop->getHeader()) {
10241 // Okay, there is no closed form solution for the PHI node. Check
10242 // to see if the loop that contains it has a known backedge-taken
10243 // count. If so, we may be able to force computation of the exit
10244 // value.
10245 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
10246 // This trivial case can show up in some degenerate cases where
10247 // the incoming IR has not yet been fully simplified.
10248 if (BackedgeTakenCount->isZero()) {
10249 Value *InitValue = nullptr;
10250 bool MultipleInitValues = false;
10251 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
10252 if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
10253 if (!InitValue)
10254 InitValue = PN->getIncomingValue(i);
10255 else if (InitValue != PN->getIncomingValue(i)) {
10256 MultipleInitValues = true;
10257 break;
10258 }
10259 }
10260 }
10261 if (!MultipleInitValues && InitValue)
10262 return getSCEV(InitValue);
10263 }
10264 // Do we have a loop invariant value flowing around the backedge
10265 // for a loop which must execute the backedge?
10266 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
10267 isKnownNonZero(BackedgeTakenCount) &&
10268 PN->getNumIncomingValues() == 2) {
10269
10270 unsigned InLoopPred =
10271 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
10272 Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
10273 if (CurrLoop->isLoopInvariant(BackedgeVal))
10274 return getSCEV(BackedgeVal);
10275 }
10276 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
10277 // Okay, we know how many times the containing loop executes. If
10278 // this is a constant evolving PHI node, get the final value at
10279 // the specified iteration number.
10280 Constant *RV =
10281 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
10282 if (RV)
10283 return getSCEV(RV);
10284 }
10285 }
10286 }
10287
10288 // Okay, this is an expression that we cannot symbolically evaluate
10289 // into a SCEV. Check to see if it's possible to symbolically evaluate
10290 // the arguments into constants, and if so, try to constant propagate the
10291 // result. This is particularly useful for computing loop exit values.
10292 if (!canConstantFold(I, &TLI))
10293 return V; // This is some other type of SCEVUnknown, just return it.
10294
10295 SmallVector<Constant *, 4> Operands;
10296 Operands.reserve(I->getNumOperands());
10297 bool MadeImprovement = false;
10298 for (Value *Op : I->operands()) {
10299 if (Constant *C = dyn_cast<Constant>(Op)) {
10300 Operands.push_back(C);
10301 continue;
10302 }
10303
10304 // If any of the operands is non-constant and if they are
10305 // non-integer and non-pointer, don't even try to analyze them
10306 // with scev techniques.
10307 if (!isSCEVable(Op->getType()))
10308 return V;
10309
10310 const SCEV *OrigV = getSCEV(Op);
10311 const SCEV *OpV = getSCEVAtScope(OrigV, L);
10312 MadeImprovement |= OrigV != OpV;
10313
10315 if (!C)
10316 return V;
10317 assert(C->getType() == Op->getType() && "Type mismatch");
10318 Operands.push_back(C);
10319 }
10320
10321 // Check to see if getSCEVAtScope actually made an improvement.
10322 if (!MadeImprovement)
10323 return V; // This is some other type of SCEVUnknown, just return it.
10324
10325 Constant *C = nullptr;
10326 const DataLayout &DL = getDataLayout();
10327 C = ConstantFoldInstOperands(I, Operands, DL, &TLI,
10328 /*AllowNonDeterministic=*/false);
10329 if (!C)
10330 return V;
10331 return getSCEV(C);
10332 }
10333 case scCouldNotCompute:
10334 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10335 }
10336 llvm_unreachable("Unknown SCEV type!");
10337}
10338
10340 return getSCEVAtScope(getSCEV(V), L);
10341}
10342
10343const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
10345 return stripInjectiveFunctions(ZExt->getOperand());
10347 return stripInjectiveFunctions(SExt->getOperand());
10348 return S;
10349}
10350
10351/// Finds the minimum unsigned root of the following equation:
10352///
10353/// A * X = B (mod N)
10354///
10355/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
10356/// A and B isn't important.
10357///
10358/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
10359static const SCEV *
10362 ScalarEvolution &SE, const Loop *L) {
10363 uint32_t BW = A.getBitWidth();
10364 assert(BW == SE.getTypeSizeInBits(B->getType()));
10365 assert(A != 0 && "A must be non-zero.");
10366
10367 // 1. D = gcd(A, N)
10368 //
10369 // The gcd of A and N may have only one prime factor: 2. The number of
10370 // trailing zeros in A is its multiplicity
10371 uint32_t Mult2 = A.countr_zero();
10372 // D = 2^Mult2
10373
10374 // 2. Check if B is divisible by D.
10375 //
10376 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
10377 // is not less than multiplicity of this prime factor for D.
10378 unsigned MinTZ = SE.getMinTrailingZeros(B);
10379 // Try again with the terminator of the loop predecessor for context-specific
10380 // result, if MinTZ s too small.
10381 if (MinTZ < Mult2 && L->getLoopPredecessor())
10382 MinTZ = SE.getMinTrailingZeros(B, L->getLoopPredecessor()->getTerminator());
10383 if (MinTZ < Mult2) {
10384 // Check if we can prove there's no remainder using URem.
10385 const SCEV *URem =
10386 SE.getURemExpr(B, SE.getConstant(APInt::getOneBitSet(BW, Mult2)));
10387 const SCEV *Zero = SE.getZero(B->getType());
10388 if (!SE.isKnownPredicate(CmpInst::ICMP_EQ, URem, Zero)) {
10389 // Try to add a predicate ensuring B is a multiple of 1 << Mult2.
10390 if (!Predicates)
10391 return SE.getCouldNotCompute();
10392
10393 // Avoid adding a predicate that is known to be false.
10394 if (SE.isKnownPredicate(CmpInst::ICMP_NE, URem, Zero))
10395 return SE.getCouldNotCompute();
10396 Predicates->push_back(SE.getEqualPredicate(URem, Zero));
10397 }
10398 }
10399
10400 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
10401 // modulo (N / D).
10402 //
10403 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
10404 // (N / D) in general. The inverse itself always fits into BW bits, though,
10405 // so we immediately truncate it.
10406 APInt AD = A.lshr(Mult2).trunc(BW - Mult2); // AD = A / D
10407 APInt I = AD.multiplicativeInverse().zext(BW);
10408
10409 // 4. Compute the minimum unsigned root of the equation:
10410 // I * (B / D) mod (N / D)
10411 // To simplify the computation, we factor out the divide by D:
10412 // (I * B mod N) / D
10413 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
10414 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
10415}
10416
10417/// For a given quadratic addrec, generate coefficients of the corresponding
10418/// quadratic equation, multiplied by a common value to ensure that they are
10419/// integers.
10420/// The returned value is a tuple { A, B, C, M, BitWidth }, where
10421/// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
10422/// were multiplied by, and BitWidth is the bit width of the original addrec
10423/// coefficients.
10424/// This function returns std::nullopt if the addrec coefficients are not
10425/// compile- time constants.
10426static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
10428 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
10429 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
10430 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
10431 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
10432 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
10433 << *AddRec << '\n');
10434
10435 // We currently can only solve this if the coefficients are constants.
10436 if (!LC || !MC || !NC) {
10437 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
10438 return std::nullopt;
10439 }
10440
10441 APInt L = LC->getAPInt();
10442 APInt M = MC->getAPInt();
10443 APInt N = NC->getAPInt();
10444 assert(!N.isZero() && "This is not a quadratic addrec");
10445
10446 unsigned BitWidth = LC->getAPInt().getBitWidth();
10447 unsigned NewWidth = BitWidth + 1;
10448 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
10449 << BitWidth << '\n');
10450 // The sign-extension (as opposed to a zero-extension) here matches the
10451 // extension used in SolveQuadraticEquationWrap (with the same motivation).
10452 N = N.sext(NewWidth);
10453 M = M.sext(NewWidth);
10454 L = L.sext(NewWidth);
10455
10456 // The increments are M, M+N, M+2N, ..., so the accumulated values are
10457 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
10458 // L+M, L+2M+N, L+3M+3N, ...
10459 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
10460 //
10461 // The equation Acc = 0 is then
10462 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
10463 // In a quadratic form it becomes:
10464 // N n^2 + (2M-N) n + 2L = 0.
10465
10466 APInt A = N;
10467 APInt B = 2 * M - A;
10468 APInt C = 2 * L;
10469 APInt T = APInt(NewWidth, 2);
10470 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
10471 << "x + " << C << ", coeff bw: " << NewWidth
10472 << ", multiplied by " << T << '\n');
10473 return std::make_tuple(A, B, C, T, BitWidth);
10474}
10475
10476/// Helper function to compare optional APInts:
10477/// (a) if X and Y both exist, return min(X, Y),
10478/// (b) if neither X nor Y exist, return std::nullopt,
10479/// (c) if exactly one of X and Y exists, return that value.
10480static std::optional<APInt> MinOptional(std::optional<APInt> X,
10481 std::optional<APInt> Y) {
10482 if (X && Y) {
10483 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
10484 APInt XW = X->sext(W);
10485 APInt YW = Y->sext(W);
10486 return XW.slt(YW) ? *X : *Y;
10487 }
10488 if (!X && !Y)
10489 return std::nullopt;
10490 return X ? *X : *Y;
10491}
10492
10493/// Helper function to truncate an optional APInt to a given BitWidth.
10494/// When solving addrec-related equations, it is preferable to return a value
10495/// that has the same bit width as the original addrec's coefficients. If the
10496/// solution fits in the original bit width, truncate it (except for i1).
10497/// Returning a value of a different bit width may inhibit some optimizations.
10498///
10499/// In general, a solution to a quadratic equation generated from an addrec
10500/// may require BW+1 bits, where BW is the bit width of the addrec's
10501/// coefficients. The reason is that the coefficients of the quadratic
10502/// equation are BW+1 bits wide (to avoid truncation when converting from
10503/// the addrec to the equation).
10504static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
10505 unsigned BitWidth) {
10506 if (!X)
10507 return std::nullopt;
10508 unsigned W = X->getBitWidth();
10510 return X->trunc(BitWidth);
10511 return X;
10512}
10513
10514/// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
10515/// iterations. The values L, M, N are assumed to be signed, and they
10516/// should all have the same bit widths.
10517/// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
10518/// where BW is the bit width of the addrec's coefficients.
10519/// If the calculated value is a BW-bit integer (for BW > 1), it will be
10520/// returned as such, otherwise the bit width of the returned value may
10521/// be greater than BW.
10522///
10523/// This function returns std::nullopt if
10524/// (a) the addrec coefficients are not constant, or
10525/// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
10526/// like x^2 = 5, no integer solutions exist, in other cases an integer
10527/// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
10528static std::optional<APInt>
10530 APInt A, B, C, M;
10531 unsigned BitWidth;
10532 auto T = GetQuadraticEquation(AddRec);
10533 if (!T)
10534 return std::nullopt;
10535
10536 std::tie(A, B, C, M, BitWidth) = *T;
10537 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
10538 std::optional<APInt> X =
10540 if (!X)
10541 return std::nullopt;
10542
10543 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
10545 if (!V->isZero())
10546 return std::nullopt;
10547
10548 return TruncIfPossible(X, BitWidth);
10549}
10550
10551/// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
10552/// iterations. The values M, N are assumed to be signed, and they
10553/// should all have the same bit widths.
10554/// Find the least n such that c(n) does not belong to the given range,
10555/// while c(n-1) does.
10556///
10557/// This function returns std::nullopt if
10558/// (a) the addrec coefficients are not constant, or
10559/// (b) SolveQuadraticEquationWrap was unable to find a solution for the
10560/// bounds of the range.
10561static std::optional<APInt>
10563 const ConstantRange &Range, ScalarEvolution &SE) {
10564 assert(AddRec->getOperand(0)->isZero() &&
10565 "Starting value of addrec should be 0");
10566 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
10567 << Range << ", addrec " << *AddRec << '\n');
10568 // This case is handled in getNumIterationsInRange. Here we can assume that
10569 // we start in the range.
10570 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
10571 "Addrec's initial value should be in range");
10572
10573 APInt A, B, C, M;
10574 unsigned BitWidth;
10575 auto T = GetQuadraticEquation(AddRec);
10576 if (!T)
10577 return std::nullopt;
10578
10579 // Be careful about the return value: there can be two reasons for not
10580 // returning an actual number. First, if no solutions to the equations
10581 // were found, and second, if the solutions don't leave the given range.
10582 // The first case means that the actual solution is "unknown", the second
10583 // means that it's known, but not valid. If the solution is unknown, we
10584 // cannot make any conclusions.
10585 // Return a pair: the optional solution and a flag indicating if the
10586 // solution was found.
10587 auto SolveForBoundary =
10588 [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
10589 // Solve for signed overflow and unsigned overflow, pick the lower
10590 // solution.
10591 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
10592 << Bound << " (before multiplying by " << M << ")\n");
10593 Bound *= M; // The quadratic equation multiplier.
10594
10595 std::optional<APInt> SO;
10596 if (BitWidth > 1) {
10597 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10598 "signed overflow\n");
10600 }
10601 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10602 "unsigned overflow\n");
10603 std::optional<APInt> UO =
10605
10606 auto LeavesRange = [&] (const APInt &X) {
10607 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
10609 if (Range.contains(V0->getValue()))
10610 return false;
10611 // X should be at least 1, so X-1 is non-negative.
10612 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
10614 if (Range.contains(V1->getValue()))
10615 return true;
10616 return false;
10617 };
10618
10619 // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
10620 // can be a solution, but the function failed to find it. We cannot treat it
10621 // as "no solution".
10622 if (!SO || !UO)
10623 return {std::nullopt, false};
10624
10625 // Check the smaller value first to see if it leaves the range.
10626 // At this point, both SO and UO must have values.
10627 std::optional<APInt> Min = MinOptional(SO, UO);
10628 if (LeavesRange(*Min))
10629 return { Min, true };
10630 std::optional<APInt> Max = Min == SO ? UO : SO;
10631 if (LeavesRange(*Max))
10632 return { Max, true };
10633
10634 // Solutions were found, but were eliminated, hence the "true".
10635 return {std::nullopt, true};
10636 };
10637
10638 std::tie(A, B, C, M, BitWidth) = *T;
10639 // Lower bound is inclusive, subtract 1 to represent the exiting value.
10640 APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
10641 APInt Upper = Range.getUpper().sext(A.getBitWidth());
10642 auto SL = SolveForBoundary(Lower);
10643 auto SU = SolveForBoundary(Upper);
10644 // If any of the solutions was unknown, no meaninigful conclusions can
10645 // be made.
10646 if (!SL.second || !SU.second)
10647 return std::nullopt;
10648
10649 // Claim: The correct solution is not some value between Min and Max.
10650 //
10651 // Justification: Assuming that Min and Max are different values, one of
10652 // them is when the first signed overflow happens, the other is when the
10653 // first unsigned overflow happens. Crossing the range boundary is only
10654 // possible via an overflow (treating 0 as a special case of it, modeling
10655 // an overflow as crossing k*2^W for some k).
10656 //
10657 // The interesting case here is when Min was eliminated as an invalid
10658 // solution, but Max was not. The argument is that if there was another
10659 // overflow between Min and Max, it would also have been eliminated if
10660 // it was considered.
10661 //
10662 // For a given boundary, it is possible to have two overflows of the same
10663 // type (signed/unsigned) without having the other type in between: this
10664 // can happen when the vertex of the parabola is between the iterations
10665 // corresponding to the overflows. This is only possible when the two
10666 // overflows cross k*2^W for the same k. In such case, if the second one
10667 // left the range (and was the first one to do so), the first overflow
10668 // would have to enter the range, which would mean that either we had left
10669 // the range before or that we started outside of it. Both of these cases
10670 // are contradictions.
10671 //
10672 // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
10673 // solution is not some value between the Max for this boundary and the
10674 // Min of the other boundary.
10675 //
10676 // Justification: Assume that we had such Max_A and Min_B corresponding
10677 // to range boundaries A and B and such that Max_A < Min_B. If there was
10678 // a solution between Max_A and Min_B, it would have to be caused by an
10679 // overflow corresponding to either A or B. It cannot correspond to B,
10680 // since Min_B is the first occurrence of such an overflow. If it
10681 // corresponded to A, it would have to be either a signed or an unsigned
10682 // overflow that is larger than both eliminated overflows for A. But
10683 // between the eliminated overflows and this overflow, the values would
10684 // cover the entire value space, thus crossing the other boundary, which
10685 // is a contradiction.
10686
10687 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
10688}
10689
10690ScalarEvolution::ExitLimit ScalarEvolution::howFarToZero(const SCEV *V,
10691 const Loop *L,
10692 bool ControlsOnlyExit,
10693 bool AllowPredicates) {
10694
10695 // This is only used for loops with a "x != y" exit test. The exit condition
10696 // is now expressed as a single expression, V = x-y. So the exit test is
10697 // effectively V != 0. We know and take advantage of the fact that this
10698 // expression only being used in a comparison by zero context.
10699
10701 // If the value is a constant
10702 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10703 // If the value is already zero, the branch will execute zero times.
10704 if (C->getValue()->isZero()) return C;
10705 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10706 }
10707
10708 const SCEVAddRecExpr *AddRec =
10709 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
10710
10711 if (!AddRec && AllowPredicates)
10712 // Try to make this an AddRec using runtime tests, in the first X
10713 // iterations of this loop, where X is the SCEV expression found by the
10714 // algorithm below.
10715 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
10716
10717 if (!AddRec || AddRec->getLoop() != L)
10718 return getCouldNotCompute();
10719
10720 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
10721 // the quadratic equation to solve it.
10722 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
10723 // We can only use this value if the chrec ends up with an exact zero
10724 // value at this index. When solving for "X*X != 5", for example, we
10725 // should not accept a root of 2.
10726 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
10727 const auto *R = cast<SCEVConstant>(getConstant(*S));
10728 return ExitLimit(R, R, R, false, Predicates);
10729 }
10730 return getCouldNotCompute();
10731 }
10732
10733 // Otherwise we can only handle this if it is affine.
10734 if (!AddRec->isAffine())
10735 return getCouldNotCompute();
10736
10737 // If this is an affine expression, the execution count of this branch is
10738 // the minimum unsigned root of the following equation:
10739 //
10740 // Start + Step*N = 0 (mod 2^BW)
10741 //
10742 // equivalent to:
10743 //
10744 // Step*N = -Start (mod 2^BW)
10745 //
10746 // where BW is the common bit width of Start and Step.
10747
10748 // Get the initial value for the loop.
10749 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
10750 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
10751
10752 if (!isLoopInvariant(Step, L))
10753 return getCouldNotCompute();
10754
10755 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
10756 // Specialize step for this loop so we get context sensitive facts below.
10757 const SCEV *StepWLG = applyLoopGuards(Step, Guards);
10758
10759 // For positive steps (counting up until unsigned overflow):
10760 // N = -Start/Step (as unsigned)
10761 // For negative steps (counting down to zero):
10762 // N = Start/-Step
10763 // First compute the unsigned distance from zero in the direction of Step.
10764 bool CountDown = isKnownNegative(StepWLG);
10765 if (!CountDown && !isKnownNonNegative(StepWLG))
10766 return getCouldNotCompute();
10767
10768 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
10769 // Handle unitary steps, which cannot wraparound.
10770 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10771 // N = Distance (as unsigned)
10772
10773 if (match(Step, m_CombineOr(m_scev_One(), m_scev_AllOnes()))) {
10774 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, Guards));
10775 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
10776
10777 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10778 // we end up with a loop whose backedge-taken count is n - 1. Detect this
10779 // case, and see if we can improve the bound.
10780 //
10781 // Explicitly handling this here is necessary because getUnsignedRange
10782 // isn't context-sensitive; it doesn't know that we only care about the
10783 // range inside the loop.
10784 const SCEV *Zero = getZero(Distance->getType());
10785 const SCEV *One = getOne(Distance->getType());
10786 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
10787 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
10788 // If Distance + 1 doesn't overflow, we can compute the maximum distance
10789 // as "unsigned_max(Distance + 1) - 1". Also apply the loop guards to
10790 // Distance + 1; the range of Distance itself may be a wrapped set even
10791 // when the guards bound Distance + 1 tightly.
10792 APInt Max = APIntOps::umin(
10793 getUnsignedRangeMax(applyLoopGuards(DistancePlusOne, Guards)),
10794 getUnsignedRangeMax(DistancePlusOne));
10795 MaxBECount = APIntOps::umin(MaxBECount, Max - 1);
10796 }
10797 return ExitLimit(Distance, getConstant(MaxBECount), Distance, false,
10798 Predicates);
10799 }
10800
10801 // If the condition controls loop exit (the loop exits only if the expression
10802 // is true) and the addition is no-wrap we can use unsigned divide to
10803 // compute the backedge count. In this case, the step may not divide the
10804 // distance, but we don't care because if the condition is "missed" the loop
10805 // will have undefined behavior due to wrapping.
10806 if (ControlsOnlyExit && AddRec->hasNoSelfWrap() &&
10807 loopHasNoAbnormalExits(AddRec->getLoop())) {
10808
10809 // If the stride is zero and the start is non-zero, the loop must be
10810 // infinite. In C++, most loops are finite by assumption, in which case the
10811 // step being zero implies UB must execute if the loop is entered.
10812 if (!(loopIsFiniteByAssumption(L) && isKnownNonZero(Start)) &&
10813 !isKnownNonZero(StepWLG))
10814 return getCouldNotCompute();
10815
10816 const SCEV *Exact =
10817 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10818 const SCEV *ConstantMax = getCouldNotCompute();
10819 if (Exact != getCouldNotCompute()) {
10820 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, Guards));
10821 ConstantMax =
10823 }
10824 const SCEV *SymbolicMax =
10825 isa<SCEVCouldNotCompute>(Exact) ? ConstantMax : Exact;
10826 return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
10827 }
10828
10829 // Solve the general equation.
10830 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
10831 if (!StepC || StepC->getValue()->isZero())
10832 return getCouldNotCompute();
10833 const SCEV *E = SolveLinEquationWithOverflow(
10834 StepC->getAPInt(), getNegativeSCEV(Start),
10835 AllowPredicates ? &Predicates : nullptr, *this, L);
10836
10837 const SCEV *M = E;
10838 if (E != getCouldNotCompute()) {
10839 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, Guards));
10840 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
10841 }
10842 auto *S = isa<SCEVCouldNotCompute>(E) ? M : E;
10843 return ExitLimit(E, M, S, false, Predicates);
10844}
10845
10846ScalarEvolution::ExitLimit
10847ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10848 // Loops that look like: while (X == 0) are very strange indeed. We don't
10849 // handle them yet except for the trivial case. This could be expanded in the
10850 // future as needed.
10851
10852 // If the value is a constant, check to see if it is known to be non-zero
10853 // already. If so, the backedge will execute zero times.
10854 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10855 if (!C->getValue()->isZero())
10856 return getZero(C->getType());
10857 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10858 }
10859
10860 // We could implement others, but I really doubt anyone writes loops like
10861 // this, and if they did, they would already be constant folded.
10862 return getCouldNotCompute();
10863}
10864
10865std::pair<const BasicBlock *, const BasicBlock *>
10866ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10867 const {
10868 // If the block has a unique predecessor, then there is no path from the
10869 // predecessor to the block that does not go through the direct edge
10870 // from the predecessor to the block.
10871 if (const BasicBlock *Pred = BB->getSinglePredecessor())
10872 return {Pred, BB};
10873
10874 // A loop's header is defined to be a block that dominates the loop.
10875 // If the header has a unique predecessor outside the loop, it must be
10876 // a block that has exactly one successor that can reach the loop.
10877 if (const Loop *L = LI.getLoopFor(BB))
10878 return {L->getLoopPredecessor(), L->getHeader()};
10879
10880 return {nullptr, BB};
10881}
10882
10883/// SCEV structural equivalence is usually sufficient for testing whether two
10884/// expressions are equal, however for the purposes of looking for a condition
10885/// guarding a loop, it can be useful to be a little more general, since a
10886/// front-end may have replicated the controlling expression.
10887static bool HasSameValue(const SCEV *A, const SCEV *B) {
10888 // Quick check to see if they are the same SCEV.
10889 if (A == B) return true;
10890
10891 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10892 // Not all instructions that are "identical" compute the same value. For
10893 // instance, two distinct alloca instructions allocating the same type are
10894 // identical and do not read memory; but compute distinct values.
10895 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
10896 };
10897
10898 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10899 // two different instructions with the same value. Check for this case.
10900 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
10901 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
10902 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
10903 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
10904 if (ComputesEqualValues(AI, BI))
10905 return true;
10906
10907 // Otherwise assume they may have a different value.
10908 return false;
10909}
10910
10911static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS) {
10912 const SCEV *Op0, *Op1;
10913 if (!match(S, m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))))
10914 return false;
10915 if (match(Op0, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10916 LHS = Op1;
10917 return true;
10918 }
10919 if (match(Op1, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10920 LHS = Op0;
10921 return true;
10922 }
10923 return false;
10924}
10925
10927 SCEVUse &RHS, unsigned Depth) {
10928 bool Changed = false;
10929 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
10930 // '0 != 0'.
10931 auto TrivialCase = [&](bool TriviallyTrue) {
10933 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
10934 return true;
10935 };
10936 // If we hit the max recursion limit bail out.
10937 if (Depth >= 3)
10938 return false;
10939
10940 const SCEV *NewLHS, *NewRHS;
10941 if (match(LHS, m_scev_c_Mul(m_SCEV(NewLHS), m_SCEVVScale())) &&
10942 match(RHS, m_scev_c_Mul(m_SCEV(NewRHS), m_SCEVVScale()))) {
10943 const SCEVMulExpr *LMul = cast<SCEVMulExpr>(LHS);
10944 const SCEVMulExpr *RMul = cast<SCEVMulExpr>(RHS);
10945
10946 // (X * vscale) pred (Y * vscale) ==> X pred Y
10947 // when both multiples are NSW.
10948 // (X * vscale) uicmp/eq/ne (Y * vscale) ==> X uicmp/eq/ne Y
10949 // when both multiples are NUW.
10950 if ((LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap()) ||
10951 (LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap() &&
10952 !ICmpInst::isSigned(Pred))) {
10953 LHS = NewLHS;
10954 RHS = NewRHS;
10955 Changed = true;
10956 }
10957 }
10958
10959 // Canonicalize a constant to the right side.
10960 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
10961 // Check for both operands constant.
10962 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
10963 if (!ICmpInst::compare(LHSC->getAPInt(), RHSC->getAPInt(), Pred))
10964 return TrivialCase(false);
10965 return TrivialCase(true);
10966 }
10967 // Otherwise swap the operands to put the constant on the right.
10968 std::swap(LHS, RHS);
10970 Changed = true;
10971 }
10972
10973 // (K + A) pred (K + B) --> A pred B
10974 // For equality, no flags are needed.
10975 // For signed, both adds must be NSW. For unsigned, both must be NUW.
10976 {
10977 const SCEVConstant *C = nullptr;
10978 if (match(LHS, m_scev_Add(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
10979 match(RHS, m_scev_Add(m_scev_Specific(C), m_SCEV(NewRHS)))) {
10980 const auto *LAdd = cast<SCEVAddExpr>(LHS);
10981 const auto *RAdd = cast<SCEVAddExpr>(RHS);
10982 bool BothNUW = LAdd->hasNoUnsignedWrap() && RAdd->hasNoUnsignedWrap();
10983 bool BothNSW = LAdd->hasNoSignedWrap() && RAdd->hasNoSignedWrap();
10984 if (ICmpInst::isEquality(Pred) || (ICmpInst::isSigned(Pred) && BothNSW) ||
10985 (ICmpInst::isUnsigned(Pred) && BothNUW)) {
10986 LHS = NewLHS;
10987 RHS = NewRHS;
10988 // Nothing follows about the signs of A and B themselves, as adding K
10989 // may move either A or B across the sign boundary, unless both adds are
10990 // guaranteed not to wrap in either domain.
10991 if (!(BothNUW && BothNSW))
10992 Pred = Pred.dropSameSign();
10993 Changed = true;
10994 }
10995 }
10996 }
10997
10998 // (C * A) pred (C * B) --> A pred B
10999 // For equality predicates, both muls must be NUW or both must be NSW
11000 // (either suffices to make multiplication by C injective; C == 0 is
11001 // impossible because SCEV folds 0 * X to 0).
11002 // For signed ordering, C must be positive and both muls must be NSW.
11003 // For unsigned ordering, both muls must be NUW.
11004 {
11005 const SCEVConstant *C = nullptr;
11006 if (match(LHS, m_scev_Mul(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11007 match(RHS, m_scev_Mul(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11008 const auto *LMul = cast<SCEVMulExpr>(LHS);
11009 const auto *RMul = cast<SCEVMulExpr>(RHS);
11010 bool BothNUW = LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap();
11011 bool BothNSW = LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap();
11012 if ((ICmpInst::isEquality(Pred) && (BothNUW || BothNSW)) ||
11013 (ICmpInst::isSigned(Pred) && BothNSW &&
11014 C->getAPInt().isStrictlyPositive()) ||
11015 (ICmpInst::isUnsigned(Pred) && BothNUW)) {
11016 LHS = NewLHS;
11017 RHS = NewRHS;
11018 Changed = true;
11019 }
11020 }
11021 }
11022
11023 // If we're comparing an addrec with a value which is loop-invariant in the
11024 // addrec's loop, put the addrec on the left. Also make a dominance check,
11025 // as both operands could be addrecs loop-invariant in each other's loop.
11026 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
11027 const Loop *L = AR->getLoop();
11028 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
11029 std::swap(LHS, RHS);
11031 Changed = true;
11032 }
11033 }
11034
11035 // If there's a constant operand, canonicalize comparisons with boundary
11036 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
11037 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
11038 const APInt &RA = RC->getAPInt();
11039
11040 bool SimplifiedByConstantRange = false;
11041
11042 if (!ICmpInst::isEquality(Pred)) {
11044 if (ExactCR.isFullSet())
11045 return TrivialCase(true);
11046 if (ExactCR.isEmptySet())
11047 return TrivialCase(false);
11048
11049 APInt NewRHS;
11050 CmpInst::Predicate NewPred;
11051 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
11052 ICmpInst::isEquality(NewPred)) {
11053 // We were able to convert an inequality to an equality.
11054 Pred = NewPred;
11055 RHS = getConstant(NewRHS);
11056 Changed = SimplifiedByConstantRange = true;
11057 }
11058 }
11059
11060 if (!SimplifiedByConstantRange) {
11061 switch (Pred) {
11062 default:
11063 break;
11064 case ICmpInst::ICMP_EQ:
11065 case ICmpInst::ICMP_NE:
11066 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
11067 if (RA.isZero() && MatchBinarySub(LHS, LHS, RHS))
11068 Changed = true;
11069 break;
11070
11071 // The "Should have been caught earlier!" messages refer to the fact
11072 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
11073 // should have fired on the corresponding cases, and canonicalized the
11074 // check to trivial case.
11075
11076 case ICmpInst::ICMP_UGE:
11077 assert(!RA.isMinValue() && "Should have been caught earlier!");
11078 Pred = ICmpInst::ICMP_UGT;
11079 RHS = getConstant(RA - 1);
11080 Changed = true;
11081 break;
11082 case ICmpInst::ICMP_ULE:
11083 assert(!RA.isMaxValue() && "Should have been caught earlier!");
11084 Pred = ICmpInst::ICMP_ULT;
11085 RHS = getConstant(RA + 1);
11086 Changed = true;
11087 break;
11088 case ICmpInst::ICMP_SGE:
11089 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
11090 Pred = ICmpInst::ICMP_SGT;
11091 RHS = getConstant(RA - 1);
11092 Changed = true;
11093 break;
11094 case ICmpInst::ICMP_SLE:
11095 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
11096 Pred = ICmpInst::ICMP_SLT;
11097 RHS = getConstant(RA + 1);
11098 Changed = true;
11099 break;
11100 }
11101 }
11102 }
11103
11104 // a /u b == 0 => a < b
11105 // a /u b != 0 => a >= b
11106 if (ICmpInst::isEquality(Pred) && RHS->isZero() &&
11107 match(LHS, m_scev_UDiv(m_SCEV(LHS), m_SCEV(RHS)))) {
11109 Changed = true;
11110 }
11111
11112 // Check for obvious equality.
11113 if (HasSameValue(LHS, RHS)) {
11114 if (ICmpInst::isTrueWhenEqual(Pred))
11115 return TrivialCase(true);
11117 return TrivialCase(false);
11118 }
11119
11120 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
11121 // adding or subtracting 1 from one of the operands.
11122 switch (Pred) {
11123 case ICmpInst::ICMP_SLE:
11124 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
11125 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11127 Pred = ICmpInst::ICMP_SLT;
11128 Changed = true;
11129 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
11130 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
11132 Pred = ICmpInst::ICMP_SLT;
11133 Changed = true;
11134 }
11135 break;
11136 case ICmpInst::ICMP_SGE:
11137 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
11138 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
11140 Pred = ICmpInst::ICMP_SGT;
11141 Changed = true;
11142 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
11143 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11145 Pred = ICmpInst::ICMP_SGT;
11146 Changed = true;
11147 }
11148 break;
11149 case ICmpInst::ICMP_ULE:
11150 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
11151 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11153 Pred = ICmpInst::ICMP_ULT;
11154 Changed = true;
11155 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
11156 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
11157 Pred = ICmpInst::ICMP_ULT;
11158 Changed = true;
11159 }
11160 break;
11161 case ICmpInst::ICMP_UGE:
11162 // If RHS is an op we can fold the -1, try that first.
11163 // Otherwise prefer LHS to preserve the nuw flag.
11164 if ((isa<SCEVConstant>(RHS) ||
11166 isa<SCEVConstant>(cast<SCEVNAryExpr>(RHS)->getOperand(0)))) &&
11167 !getUnsignedRangeMin(RHS).isMinValue()) {
11168 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11169 Pred = ICmpInst::ICMP_UGT;
11170 Changed = true;
11171 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
11172 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11174 Pred = ICmpInst::ICMP_UGT;
11175 Changed = true;
11176 } else if (!getUnsignedRangeMin(RHS).isMinValue()) {
11177 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11178 Pred = ICmpInst::ICMP_UGT;
11179 Changed = true;
11180 }
11181 break;
11182 default:
11183 break;
11184 }
11185
11186 // TODO: More simplifications are possible here.
11187
11188 // Recursively simplify until we either hit a recursion limit or nothing
11189 // changes.
11190 if (Changed)
11191 (void)SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1);
11192
11193 return Changed;
11194}
11195
11197 return getSignedRangeMax(S).isNegative();
11198}
11199
11203
11205 return !getSignedRangeMin(S).isNegative();
11206}
11207
11211
11213 // Query push down for cases where the unsigned range is
11214 // less than sufficient.
11215 if (const auto *SExt = dyn_cast<SCEVSignExtendExpr>(S))
11216 return isKnownNonZero(SExt->getOperand(0));
11217 return getUnsignedRangeMin(S) != 0;
11218}
11219
11221 bool OrNegative) {
11222 auto NonRecursive = [OrNegative](const SCEV *S) {
11223 if (auto *C = dyn_cast<SCEVConstant>(S))
11224 return C->getAPInt().isPowerOf2() ||
11225 (OrNegative && C->getAPInt().isNegatedPowerOf2());
11226
11227 // vscale is a power-of-two.
11228 return isa<SCEVVScale>(S);
11229 };
11230
11231 if (NonRecursive(S))
11232 return true;
11233
11234 auto *Mul = dyn_cast<SCEVMulExpr>(S);
11235 if (!Mul)
11236 return false;
11237 return all_of(Mul->operands(), NonRecursive) && (OrZero || isKnownNonZero(S));
11238}
11239
11241 const SCEV *S, uint64_t M,
11243 if (M == 0)
11244 return false;
11245 if (M == 1)
11246 return true;
11247
11248 // For a constant, check that "S % M == 0".
11249 if (auto *Cst = dyn_cast<SCEVConstant>(S)) {
11250 APInt C = Cst->getAPInt();
11251 return C.urem(M) == 0;
11252 }
11253
11254 // Basic tests have failed.
11255 // Check "S % M == 0" at compile time and record runtime Assumptions.
11256 auto *STy = dyn_cast<IntegerType>(S->getType());
11257 const SCEV *SmodM =
11258 getURemExpr(S, getConstant(ConstantInt::get(STy, M, false)));
11259 const SCEV *Zero = getZero(STy);
11260
11261 // Check whether "S % M == 0" is known at compile time.
11263 return true;
11264
11265 // Check whether "S % M != 0" is known at compile time.
11267 return false;
11268
11269 if (!Predicates)
11270 return false;
11271
11272 // Look through Add and AddRec expressions with nuw to improve the
11273 // precision of added predicates. S is a multiple of M if S starts with a
11274 // multiple of M and at every iteration step S only adds multiples of M.
11277 all_of(S->operands(),
11278 [&](SCEVUse Op) { return isKnownMultipleOf(Op, M, Predicates); }))
11279 return true;
11280
11281 // Similarly, look through Mul with nuw, where any operand being a
11282 // known-multiple is sufficient.
11283 if (auto *Mul = dyn_cast<SCEVMulExpr>(S))
11284 if (Mul->hasNoUnsignedWrap() && any_of(S->operands(), [&](SCEVUse Op) {
11285 return isKnownMultipleOf(Op, M, Predicates);
11286 }))
11287 return true;
11288
11289 // Similarly, look through MinMax, with no wrapping arithmetic to consider.
11290 if (isa<SCEVMinMaxExpr>(S) && all_of(S->operands(), [&](SCEVUse Op) {
11291 return isKnownMultipleOf(Op, M, Predicates);
11292 }))
11293 return true;
11294
11296
11297 // Detect redundant predicates.
11298 for (auto *A : *Predicates)
11299 if (A->implies(P, *this))
11300 return true;
11301
11302 // Only record non-redundant predicates.
11303 Predicates->push_back(P);
11304 return true;
11305}
11306
11308 return ((isKnownNonNegative(S1) && isKnownNonNegative(S2)) ||
11310}
11311
11312std::pair<const SCEV *, const SCEV *>
11314 // Compute SCEV on entry of loop L.
11315 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
11316 if (Start == getCouldNotCompute())
11317 return { Start, Start };
11318 // Compute post increment SCEV for loop L.
11319 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
11320 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
11321 return { Start, PostInc };
11322}
11323
11325 SCEVUse RHS) {
11326 // First collect all loops.
11328 getUsedLoops(LHS, LoopsUsed);
11329 getUsedLoops(RHS, LoopsUsed);
11330
11331 if (LoopsUsed.empty())
11332 return false;
11333
11334 // Domination relationship must be a linear order on collected loops.
11335#ifndef NDEBUG
11336 for (const auto *L1 : LoopsUsed)
11337 for (const auto *L2 : LoopsUsed)
11338 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
11339 DT.dominates(L2->getHeader(), L1->getHeader())) &&
11340 "Domination relationship is not a linear order");
11341#endif
11342
11343 const Loop *MDL =
11344 *llvm::max_element(LoopsUsed, [&](const Loop *L1, const Loop *L2) {
11345 return DT.properlyDominates(L1->getHeader(), L2->getHeader());
11346 });
11347
11348 // Get init and post increment value for LHS.
11349 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
11350 // if LHS contains unknown non-invariant SCEV then bail out.
11351 if (SplitLHS.first == getCouldNotCompute())
11352 return false;
11353 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
11354 // Get init and post increment value for RHS.
11355 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
11356 // if RHS contains unknown non-invariant SCEV then bail out.
11357 if (SplitRHS.first == getCouldNotCompute())
11358 return false;
11359 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
11360 // It is possible that init SCEV contains an invariant load but it does
11361 // not dominate MDL and is not available at MDL loop entry, so we should
11362 // check it here.
11363 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
11364 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
11365 return false;
11366
11367 // It seems backedge guard check is faster than entry one so in some cases
11368 // it can speed up whole estimation by short circuit
11369 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
11370 SplitRHS.second) &&
11371 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
11372}
11373
11374/// Try to prove "LHS Pred RHS" by decomposing a min/max on either side into its
11375/// operands, proving the per-operand comparisons with \p Prove. A min/max
11376/// equals one of its operands, so proving the comparison for all of them
11377/// proves it:
11378///
11379/// minmax(X0, ..., Xn) Pred RHS if Xi Pred RHS for all i, and
11380/// LHS Pred minmax(Y0, ..., Yn) if LHS Pred Yi for all i.
11381///
11382/// For LT/LE predicates with matching signedness, one operand is sufficient:
11383///
11384/// min(X0, ..., Xn) Pred RHS if Xi Pred RHS for any i, and
11385/// LHS Pred max(Y0, ..., Yn) if LHS Pred Yi for any i.
11386///
11389 function_ref<bool(CmpPredicate, SCEVUse, SCEVUse)> Prove) {
11390 // Samesign holds for the original operand pair only, not for the per-operand
11391 // sub-queries below.
11392 CmpInst::Predicate P = Pred.dropSameSign();
11394 return false;
11395
11396 // Normalize to LT/LE, so the any-of rule only applies to a min on the LHS or
11397 // a max on the RHS.
11398 if (ICmpInst::isGT(P) || ICmpInst::isGE(P)) {
11399 std::swap(LHS, RHS);
11401 }
11402
11403 // A min/max of kind AnyOfKind needs one operand to hold, others all of them.
11404 auto ViaOperands = [](SCEVUse S, SCEVTypes AnyOfKind, auto Holds) {
11405 const auto *MinMax = dyn_cast<SCEVMinMaxExpr>(S);
11406 if (!MinMax)
11407 return false;
11408 return MinMax->getSCEVType() == AnyOfKind
11409 ? any_of(MinMax->operands(), Holds)
11410 : all_of(MinMax->operands(), Holds);
11411 };
11412 auto HoldsForLHSOp = [&](SCEVUse Op) { return Prove(P, Op, RHS); };
11413 auto HoldsForRHSOp = [&](SCEVUse Op) { return Prove(P, LHS, Op); };
11415 return ViaOperands(LHS, MinKind, HoldsForLHSOp) ||
11416 ViaOperands(RHS, SCEVMinMaxExpr::negate(MinKind), HoldsForRHSOp);
11417}
11418
11419/// Maximum nesting depth of recursive isKnownPredicate calls.
11420static constexpr unsigned MaxKnownPredicateDepth = 4;
11421
11423 SCEVUse RHS, unsigned Depth) {
11425 return false;
11426
11427 // Keep the originals for min/max decomposition below, as
11428 // SimplifyICmpOperands may rewrite a min/max operand into a non-min/max.
11429 CmpPredicate OrigPred = Pred;
11430 SCEVUse OrigLHS = LHS, OrigRHS = RHS;
11431
11432 // Canonicalize the inputs first.
11433 (void)SimplifyICmpOperands(Pred, LHS, RHS);
11434
11435 if (isKnownViaInduction(Pred, LHS, RHS) ||
11436 isKnownPredicateViaSplitting(Pred, LHS, RHS, Depth) ||
11437 isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11438 return true;
11439
11441 OrigPred, OrigLHS, OrigRHS, [&](CmpPredicate P, SCEVUse A, SCEVUse B) {
11442 return isKnownPredicate(P, A, B, Depth + 1);
11443 });
11444}
11445
11447 const SCEV *LHS,
11448 const SCEV *RHS) {
11449 if (isKnownPredicate(Pred, LHS, RHS))
11450 return true;
11452 return false;
11453 return std::nullopt;
11454}
11455
11457 const SCEV *RHS,
11458 const Instruction *CtxI) {
11459 // TODO: Analyze guards and assumes from Context's block.
11460 return isKnownPredicate(Pred, LHS, RHS) ||
11461 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
11462}
11463
11464std::optional<bool>
11466 const SCEV *RHS, const Instruction *CtxI) {
11467 std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
11468 if (KnownWithoutContext)
11469 return KnownWithoutContext;
11470
11471 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
11472 return true;
11474 CtxI->getParent(), ICmpInst::getInverseCmpPredicate(Pred), LHS, RHS))
11475 return false;
11476 return std::nullopt;
11477}
11478
11480 const SCEVAddRecExpr *LHS,
11481 const SCEV *RHS) {
11482 const Loop *L = LHS->getLoop();
11483 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
11484 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
11485}
11486
11487std::optional<ScalarEvolution::MonotonicPredicateType>
11489 ICmpInst::Predicate Pred) {
11490 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
11491
11492#ifndef NDEBUG
11493 // Verify an invariant: inverting the predicate should turn a monotonically
11494 // increasing change to a monotonically decreasing one, and vice versa.
11495 if (Result) {
11496 auto ResultSwapped =
11497 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
11498
11499 assert(*ResultSwapped != *Result &&
11500 "monotonicity should flip as we flip the predicate");
11501 }
11502#endif
11503
11504 return Result;
11505}
11506
11507std::optional<ScalarEvolution::MonotonicPredicateType>
11508ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
11509 ICmpInst::Predicate Pred) {
11510 // A zero step value for LHS means the induction variable is essentially a
11511 // loop invariant value. We don't really depend on the predicate actually
11512 // flipping from false to true (for increasing predicates, and the other way
11513 // around for decreasing predicates), all we care about is that *if* the
11514 // predicate changes then it only changes from false to true.
11515 //
11516 // A zero step value in itself is not very useful, but there may be places
11517 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
11518 // as general as possible.
11519
11520 // Only handle LE/LT/GE/GT predicates.
11521 if (!ICmpInst::isRelational(Pred))
11522 return std::nullopt;
11523
11524 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
11525 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
11526 "Should be greater or less!");
11527
11528 // Check that AR does not wrap.
11529 if (ICmpInst::isUnsigned(Pred)) {
11530 if (!LHS->hasNoUnsignedWrap())
11531 return std::nullopt;
11533 }
11535 "Relational predicate is either signed or unsigned!");
11536 if (!LHS->hasNoSignedWrap())
11537 return std::nullopt;
11538
11539 const SCEV *Step = LHS->getStepRecurrence(*this);
11540
11541 if (isKnownNonNegative(Step))
11543
11544 if (isKnownNonPositive(Step))
11546
11547 return std::nullopt;
11548}
11549
11550std::optional<ScalarEvolution::LoopInvariantPredicate>
11552 const SCEV *RHS, const Loop *L,
11553 const Instruction *CtxI) {
11554 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11555 if (!isLoopInvariant(RHS, L)) {
11556 if (!isLoopInvariant(LHS, L))
11557 return std::nullopt;
11558
11559 std::swap(LHS, RHS);
11561 }
11562
11563 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11564 if (!ArLHS || ArLHS->getLoop() != L)
11565 return std::nullopt;
11566
11567 // Even if both are valid, we need to consistently choose the unsigned or the
11568 // signed predicate for the monotonicity and backedge checks below, not
11569 // mixtures of both. For now, prefer the unsigned predicate.
11570 Pred = Pred.dropSameSign();
11571 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
11572 if (!MonotonicType)
11573 return std::nullopt;
11574 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
11575 // true as the loop iterates, and the backedge is control dependent on
11576 // "ArLHS `Pred` RHS" == true then we can reason as follows:
11577 //
11578 // * if the predicate was false in the first iteration then the predicate
11579 // is never evaluated again, since the loop exits without taking the
11580 // backedge.
11581 // * if the predicate was true in the first iteration then it will
11582 // continue to be true for all future iterations since it is
11583 // monotonically increasing.
11584 //
11585 // For both the above possibilities, we can replace the loop varying
11586 // predicate with its value on the first iteration of the loop (which is
11587 // loop invariant).
11588 //
11589 // A similar reasoning applies for a monotonically decreasing predicate, by
11590 // replacing true with false and false with true in the above two bullets.
11592 auto P = Increasing ? Pred : ICmpInst::getInverseCmpPredicate(Pred);
11593
11594 if (isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
11596 RHS);
11597
11598 if (!CtxI)
11599 return std::nullopt;
11600 // Try to prove via context.
11601 // TODO: Support other cases.
11602 switch (Pred) {
11603 default:
11604 break;
11605 case ICmpInst::ICMP_ULE:
11606 case ICmpInst::ICMP_ULT: {
11607 assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!");
11608 // Given preconditions
11609 // (1) ArLHS does not cross the border of positive and negative parts of
11610 // range because of:
11611 // - Positive step; (TODO: lift this limitation)
11612 // - nuw - does not cross zero boundary;
11613 // - nsw - does not cross SINT_MAX boundary;
11614 // (2) ArLHS <s RHS
11615 // (3) RHS >=s 0
11616 // we can replace the loop variant ArLHS <u RHS condition with loop
11617 // invariant Start(ArLHS) <u RHS.
11618 //
11619 // Because of (1) there are two options:
11620 // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
11621 // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
11622 // It means that ArLHS <s RHS <=> ArLHS <u RHS.
11623 // Because of (2) ArLHS <u RHS is trivially true.
11624 // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
11625 // We can strengthen this to Start(ArLHS) <u RHS.
11626 auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
11627 if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
11628 isKnownPositive(ArLHS->getStepRecurrence(*this)) &&
11629 isKnownNonNegative(RHS) &&
11630 isKnownPredicateAt(SignFlippedPred, ArLHS, RHS, CtxI))
11632 RHS);
11633 }
11634 }
11635
11636 return std::nullopt;
11637}
11638
11639std::optional<ScalarEvolution::LoopInvariantPredicate>
11641 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11642 const Instruction *CtxI, const SCEV *MaxIter) {
11644 Pred, LHS, RHS, L, CtxI, MaxIter))
11645 return LIP;
11646 if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
11647 // Number of iterations expressed as UMIN isn't always great for expressing
11648 // the value on the last iteration. If the straightforward approach didn't
11649 // work, try the following trick: if the a predicate is invariant for X, it
11650 // is also invariant for umin(X, ...). So try to find something that works
11651 // among subexpressions of MaxIter expressed as umin.
11652 for (SCEVUse Op : UMin->operands())
11654 Pred, LHS, RHS, L, CtxI, Op))
11655 return LIP;
11656 return std::nullopt;
11657}
11658
11659std::optional<ScalarEvolution::LoopInvariantPredicate>
11661 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11662 const Instruction *CtxI, const SCEV *MaxIter) {
11663 // Try to prove the following set of facts:
11664 // - The predicate is monotonic in the iteration space.
11665 // - If the check does not fail on the 1st iteration:
11666 // - No overflow will happen during first MaxIter iterations;
11667 // - It will not fail on the MaxIter'th iteration.
11668 // If the check does fail on the 1st iteration, we leave the loop and no
11669 // other checks matter.
11670
11671 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11672 if (!isLoopInvariant(RHS, L)) {
11673 if (!isLoopInvariant(LHS, L))
11674 return std::nullopt;
11675
11676 std::swap(LHS, RHS);
11678 }
11679
11680 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
11681 if (!AR || AR->getLoop() != L)
11682 return std::nullopt;
11683
11684 // Even if both are valid, we need to consistently chose the unsigned or the
11685 // signed predicate below, not mixtures of both. For now, prefer the unsigned
11686 // predicate.
11687 Pred = Pred.dropSameSign();
11688
11689 // The predicate must be relational (i.e. <, <=, >=, >).
11690 if (!ICmpInst::isRelational(Pred))
11691 return std::nullopt;
11692
11693 // TODO: Support steps other than +/- 1.
11694 const SCEV *Step = AR->getStepRecurrence(*this);
11695 auto *One = getOne(Step->getType());
11696 auto *MinusOne = getNegativeSCEV(One);
11697 if (Step != One && Step != MinusOne)
11698 return std::nullopt;
11699
11700 // Type mismatch here means that MaxIter is potentially larger than max
11701 // unsigned value in start type, which mean we cannot prove no wrap for the
11702 // indvar.
11703 if (AR->getType() != MaxIter->getType())
11704 return std::nullopt;
11705
11706 // Value of IV on suggested last iteration.
11707 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
11708 // Does it still meet the requirement?
11709 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
11710 return std::nullopt;
11711 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
11712 // not exceed max unsigned value of this type), this effectively proves
11713 // that there is no wrap during the iteration. To prove that there is no
11714 // signed/unsigned wrap, we need to check that
11715 // Start <= Last for step = 1 or Start >= Last for step = -1.
11716 ICmpInst::Predicate NoOverflowPred =
11718 if (Step == MinusOne)
11719 NoOverflowPred = ICmpInst::getSwappedPredicate(NoOverflowPred);
11720 const SCEV *Start = AR->getStart();
11721 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
11722 return std::nullopt;
11723
11724 // Everything is fine.
11725 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
11726}
11727
11728bool ScalarEvolution::isKnownPredicateViaConstantRanges(CmpPredicate Pred,
11729 SCEVUse LHS,
11730 SCEVUse RHS) {
11731 if (HasSameValue(LHS, RHS))
11732 return ICmpInst::isTrueWhenEqual(Pred);
11733
11734 auto CheckRange = [&](bool IsSigned) {
11735 auto RangeLHS = IsSigned ? getSignedRange(LHS) : getUnsignedRange(LHS);
11736 auto RangeRHS = IsSigned ? getSignedRange(RHS) : getUnsignedRange(RHS);
11737 return RangeLHS.icmp(Pred, RangeRHS);
11738 };
11739
11740 // The check at the top of the function catches the case where the values are
11741 // known to be equal.
11742 if (Pred == CmpInst::ICMP_EQ)
11743 return false;
11744
11745 if (Pred == CmpInst::ICMP_NE) {
11746 if (CheckRange(true) || CheckRange(false))
11747 return true;
11748 auto *Diff = getMinusSCEV(LHS, RHS);
11749 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
11750 }
11751
11752 return CheckRange(CmpInst::isSigned(Pred));
11753}
11754
11755bool ScalarEvolution::isKnownPredicateViaNoOverflow(CmpPredicate Pred,
11757 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
11758 // C1 and C2 are constant integers. If either X or Y are not add expressions,
11759 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
11760 // OutC1 and OutC2.
11761 auto MatchBinaryAddToConst = [this](SCEVUse X, SCEVUse Y, APInt &OutC1,
11762 APInt &OutC2, SCEVFlags ExpectedFlags) {
11763 SCEVUse XNonConstOp, XConstOp;
11764 SCEVUse YNonConstOp, YConstOp;
11765 SCEVFlags XFlagsPresent;
11766 SCEVFlags YFlagsPresent;
11767
11768 // Use nullptr for 0, to avoid creating a zero SCEV.
11769 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
11770 XConstOp = nullptr;
11771 XNonConstOp = X;
11772 XFlagsPresent = ExpectedFlags;
11773 }
11774 if (XConstOp && !isa<SCEVConstant>(XConstOp))
11775 return false;
11776
11777 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
11778 YConstOp = nullptr;
11779 YNonConstOp = Y;
11780 YFlagsPresent = ExpectedFlags;
11781 }
11782
11783 if (YNonConstOp != XNonConstOp)
11784 return false;
11785
11786 if (YConstOp && !isa<SCEVConstant>(YConstOp))
11787 return false;
11788
11789 // When matching ADDs with NUW flags (and unsigned predicates), only the
11790 // second ADD (with the larger constant) requires NUW.
11791 if ((YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11792 return false;
11794 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) {
11795 return false;
11796 }
11797
11798 OutC1 = XConstOp ? cast<SCEVConstant>(XConstOp)->getAPInt()
11799 : APInt::getZero(getTypeSizeInBits(X->getType()));
11800 OutC2 = YConstOp ? cast<SCEVConstant>(YConstOp)->getAPInt()
11801 : APInt::getZero(getTypeSizeInBits(Y->getType()));
11802
11803 return true;
11804 };
11805
11806 APInt C1;
11807 APInt C2;
11808
11809 switch (Pred) {
11810 default:
11811 break;
11812
11813 case ICmpInst::ICMP_SGE:
11814 std::swap(LHS, RHS);
11815 [[fallthrough]];
11816 case ICmpInst::ICMP_SLE:
11817 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
11818 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
11819 return true;
11820
11821 break;
11822
11823 case ICmpInst::ICMP_SGT:
11824 std::swap(LHS, RHS);
11825 [[fallthrough]];
11826 case ICmpInst::ICMP_SLT:
11827 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
11828 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
11829 return true;
11830
11831 break;
11832
11833 case ICmpInst::ICMP_UGE:
11834 std::swap(LHS, RHS);
11835 [[fallthrough]];
11836 case ICmpInst::ICMP_ULE:
11837 // (X + C1) u<= (X + C2)<nuw> for C1 u<= C2.
11838 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ule(C2))
11839 return true;
11840
11841 break;
11842
11843 case ICmpInst::ICMP_UGT:
11844 std::swap(LHS, RHS);
11845 [[fallthrough]];
11846 case ICmpInst::ICMP_ULT:
11847 // (X + C1) u< (X + C2)<nuw> if C1 u< C2.
11848 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ult(C2))
11849 return true;
11850 break;
11851 }
11852
11853 return false;
11854}
11855
11856bool ScalarEvolution::isKnownPredicateViaSplitting(CmpPredicate Pred,
11858 unsigned Depth) {
11859 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
11860 return false;
11861
11862 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
11863 // the stack can result in exponential time complexity.
11864 SaveAndRestore Restore(ProvingSplitPredicate, true);
11865
11866 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
11867 //
11868 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
11869 // isKnownPredicate. isKnownPredicate is more powerful, but also more
11870 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
11871 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
11872 // use isKnownPredicate later if needed.
11873 return isKnownNonNegative(RHS) &&
11875 Depth + 1) &&
11877}
11878
11879bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, CmpPredicate Pred,
11880 const SCEV *LHS, const SCEV *RHS) {
11881 // No need to even try if we know the module has no guards.
11882 if (!HasGuards)
11883 return false;
11884
11885 return any_of(*BB, [&](const Instruction &I) {
11886 using namespace llvm::PatternMatch;
11887
11888 Value *Condition;
11890 m_Value(Condition))) &&
11891 isImpliedCond(Pred, LHS, RHS, Condition, false);
11892 });
11893}
11894
11895/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
11896/// protected by a conditional between LHS and RHS. This is used to
11897/// to eliminate casts.
11899 CmpPredicate Pred,
11900 const SCEV *LHS,
11901 const SCEV *RHS) {
11902 // Interpret a null as meaning no loop, where there is obviously no guard
11903 // (interprocedural conditions notwithstanding). Do not bother about
11904 // unreachable loops.
11905 if (!L || !DT.isReachableFromEntry(L->getHeader()))
11906 return true;
11907
11908 if (Opts.scev_verify_ir)
11909 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
11910 "This cannot be done on broken IR!");
11911
11912
11913 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11914 return true;
11915
11916 BasicBlock *Latch = L->getLoopLatch();
11917 if (!Latch)
11918 return false;
11919
11920 CondBrInst *LoopContinuePredicate =
11922 if (LoopContinuePredicate &&
11923 isImpliedCond(Pred, LHS, RHS, LoopContinuePredicate->getCondition(),
11924 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
11925 return true;
11926
11927 // We don't want more than one activation of the following loops on the stack
11928 // -- that can lead to O(n!) time complexity.
11929 if (WalkingBEDominatingConds)
11930 return false;
11931
11932 SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
11933
11934 // See if we can exploit a trip count to prove the predicate.
11935 const auto &BETakenInfo = getBackedgeTakenInfo(L);
11936 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
11937 if (LatchBECount != getCouldNotCompute()) {
11938 // We know that Latch branches back to the loop header exactly
11939 // LatchBECount times. This means the backdege condition at Latch is
11940 // equivalent to "{0,+,1} u< LatchBECount".
11941 Type *Ty = LatchBECount->getType();
11942 auto NoWrapFlags = SCEVFlags(SCEV::FlagNUW | SCEV::FlagNW);
11943 const SCEV *LoopCounter =
11944 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
11945 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
11946 LatchBECount))
11947 return true;
11948 }
11949
11950 // Check conditions due to any @llvm.assume intrinsics.
11951 for (auto &AssumeVH : AC.assumptions()) {
11952 if (!AssumeVH)
11953 continue;
11954 auto *CI = cast<CallInst>(AssumeVH);
11955 if (!DT.dominates(CI, Latch->getTerminator()))
11956 continue;
11957
11958 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
11959 return true;
11960 }
11961
11962 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
11963 return true;
11964
11965 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
11966 DTN != HeaderDTN; DTN = DTN->getIDom()) {
11967 assert(DTN && "should reach the loop header before reaching the root!");
11968
11969 BasicBlock *BB = DTN->getBlock();
11970 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
11971 return true;
11972
11973 BasicBlock *PBB = BB->getSinglePredecessor();
11974 if (!PBB)
11975 continue;
11976
11978 if (!ContBr || ContBr->getSuccessor(0) == ContBr->getSuccessor(1))
11979 continue;
11980
11981 // If we have an edge `E` within the loop body that dominates the only
11982 // latch, the condition guarding `E` also guards the backedge. This
11983 // reasoning works only for loops with a single latch.
11984 // We're constructively (and conservatively) enumerating edges within the
11985 // loop body that dominate the latch. The dominator tree better agree
11986 // with us on this:
11987 assert(DT.dominates(BasicBlockEdge(PBB, BB), Latch) && "should be!");
11988 if (isImpliedCond(Pred, LHS, RHS, ContBr->getCondition(),
11989 BB != ContBr->getSuccessor(0)))
11990 return true;
11991 }
11992
11993 return false;
11994}
11995
11997 CmpPredicate Pred,
11998 const SCEV *LHS,
11999 const SCEV *RHS) {
12000 // Do not bother proving facts for unreachable code.
12001 if (!DT.isReachableFromEntry(BB))
12002 return true;
12003 if (Opts.scev_verify_ir)
12004 assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
12005 "This cannot be done on broken IR!");
12006
12007 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
12008 // the facts (a >= b && a != b) separately. A typical situation is when the
12009 // non-strict comparison is known from ranges and non-equality is known from
12010 // dominating predicates. If we are proving strict comparison, we always try
12011 // to prove non-equality and non-strict comparison separately.
12012 CmpPredicate NonStrictPredicate = ICmpInst::getNonStrictCmpPredicate(Pred);
12013 const bool ProvingStrictComparison =
12014 Pred != NonStrictPredicate.dropSameSign();
12015 const Instruction *CtxI = &BB->front();
12017
12018 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
12019 auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
12020 Conds.emplace_back(Condition, Inverse);
12021 return isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI);
12022 };
12023
12024 // Starting at the block's predecessor, climb up the predecessor chain, as long
12025 // as there are predecessors that can be found that have unique successors
12026 // leading to the original block.
12027 const Loop *ContainingLoop = LI.getLoopFor(BB);
12028 const BasicBlock *PredBB;
12029 if (ContainingLoop && ContainingLoop->getHeader() == BB)
12030 PredBB = ContainingLoop->getLoopPredecessor();
12031 else
12032 PredBB = BB->getSinglePredecessor();
12033 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
12034 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
12035 const CondBrInst *BlockEntryPredicate =
12036 dyn_cast<CondBrInst>(Pair.first->getTerminator());
12037 if (!BlockEntryPredicate)
12038 continue;
12039
12040 if (ProveViaCond(BlockEntryPredicate->getCondition(),
12041 BlockEntryPredicate->getSuccessor(0) != Pair.second))
12042 return true;
12043 }
12044
12045 // Check conditions due to any @llvm.assume intrinsics.
12046 for (auto &AssumeVH : AC.assumptions()) {
12047 if (!AssumeVH)
12048 continue;
12049 auto *CI = cast<CallInst>(AssumeVH);
12050 if (!DT.dominates(CI, BB))
12051 continue;
12052
12053 if (ProveViaCond(CI->getArgOperand(0), false))
12054 return true;
12055 }
12056
12057 // Check conditions due to any @llvm.experimental.guard intrinsics.
12058 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
12059 F.getParent(), Intrinsic::experimental_guard);
12060 if (GuardDecl)
12061 for (const auto *GU : GuardDecl->users())
12062 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
12063 if (Guard->getFunction() == BB->getParent() && DT.dominates(Guard, BB))
12064 if (ProveViaCond(Guard->getArgOperand(0), false))
12065 return true;
12066
12067 // First try to prove conditions directly, then fall back to proving via the
12068 // non-strict predicate and not-equal.
12069 if (!ProvingStrictComparison)
12070 return false;
12071 auto ProveViaAll = [&](CmpPredicate P) {
12072 return isKnownViaNonRecursiveReasoning(P, LHS, RHS) ||
12073 any_of(Conds, [&](const auto &C) {
12074 return isImpliedCond(P, LHS, RHS, C.first, C.second, CtxI);
12075 });
12076 };
12077 return ProveViaAll(NonStrictPredicate) && ProveViaAll(ICmpInst::ICMP_NE);
12078}
12079
12081 const SCEV *LHS,
12082 const SCEV *RHS) {
12083 // Interpret a null as meaning no loop, where there is obviously no guard
12084 // (interprocedural conditions notwithstanding).
12085 if (!L)
12086 return false;
12087
12088 // Both LHS and RHS must be available at loop entry.
12090 "LHS is not available at Loop Entry");
12092 "RHS is not available at Loop Entry");
12093
12094 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
12095 return true;
12096
12097 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
12098}
12099
12100bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12101 const SCEV *RHS,
12102 const Value *FoundCondValue, bool Inverse,
12103 const Instruction *CtxI) {
12104 // False conditions implies anything. Do not bother analyzing it further.
12105 if (FoundCondValue ==
12106 ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
12107 return true;
12108
12109 if (!PendingLoopPredicates.insert(FoundCondValue).second)
12110 return false;
12111
12112 llvm::scope_exit ClearOnExit(
12113 [&]() { PendingLoopPredicates.erase(FoundCondValue); });
12114
12115 // Recursively handle And and Or conditions.
12116 const Value *Op0, *Op1;
12117 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
12118 if (!Inverse)
12119 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12120 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12121 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
12122 if (Inverse)
12123 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12124 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12125 }
12126
12127 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
12128 if (!ICI) return false;
12129
12130 // Now that we found a conditional branch that dominates the loop or controls
12131 // the loop latch. Check to see if it is the comparison we are looking for.
12132 CmpPredicate FoundPred;
12133 if (Inverse)
12134 FoundPred = ICI->getInverseCmpPredicate();
12135 else
12136 FoundPred = ICI->getCmpPredicate();
12137
12138 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
12139 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
12140
12141 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
12142}
12143
12144bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12145 const SCEV *RHS, CmpPredicate FoundPred,
12146 const SCEV *FoundLHS, const SCEV *FoundRHS,
12147 const Instruction *CtxI) {
12148 // Balance the types.
12149 if (getTypeSizeInBits(LHS->getType()) <
12150 getTypeSizeInBits(FoundLHS->getType())) {
12151 // For unsigned and equality predicates, try to prove that both found
12152 // operands fit into narrow unsigned range. If so, try to prove facts in
12153 // narrow types.
12154 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
12155 !FoundRHS->getType()->isPointerTy()) {
12156 auto *NarrowType = LHS->getType();
12157 auto *WideType = FoundLHS->getType();
12158 auto BitWidth = getTypeSizeInBits(NarrowType);
12159 const SCEV *MaxValue = getZeroExtendExpr(
12161 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
12162 MaxValue) &&
12163 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
12164 MaxValue)) {
12165 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
12166 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
12167 // We cannot preserve samesign after truncation.
12168 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred.dropSameSign(),
12169 TruncFoundLHS, TruncFoundRHS, CtxI))
12170 return true;
12171 }
12172 }
12173
12174 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
12175 return false;
12176 if (CmpInst::isSigned(Pred)) {
12177 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
12178 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
12179 } else {
12180 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
12181 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
12182 }
12183 } else if (getTypeSizeInBits(LHS->getType()) >
12184 getTypeSizeInBits(FoundLHS->getType())) {
12185 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
12186 return false;
12187 if (CmpInst::isSigned(FoundPred)) {
12188 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
12189 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
12190 } else {
12191 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
12192 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
12193 }
12194 }
12195 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
12196 FoundRHS, CtxI);
12197}
12198
12199bool ScalarEvolution::isImpliedCondBalancedTypes(
12200 CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, CmpPredicate FoundPred,
12201 SCEVUse FoundLHS, SCEVUse FoundRHS, const Instruction *CtxI) {
12203 getTypeSizeInBits(FoundLHS->getType()) &&
12204 "Types should be balanced!");
12205 // Canonicalize the query to match the way instcombine will have
12206 // canonicalized the comparison.
12208 if (LHS == RHS)
12210 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
12211 if (FoundLHS == FoundRHS)
12212 return CmpInst::isFalseWhenEqual(FoundPred);
12213
12214 // Check to see if we can make the LHS or RHS match.
12215 if (LHS == FoundRHS || RHS == FoundLHS) {
12216 if (isa<SCEVConstant>(RHS)) {
12217 std::swap(FoundLHS, FoundRHS);
12218 FoundPred = ICmpInst::getSwappedCmpPredicate(FoundPred);
12219 } else {
12220 std::swap(LHS, RHS);
12222 }
12223 }
12224
12225 // Check whether the found predicate is the same as the desired predicate.
12226 if (auto P = CmpPredicate::getMatching(FoundPred, Pred))
12227 return isImpliedCondOperands(*P, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12228
12229 // Check whether swapping the found predicate makes it the same as the
12230 // desired predicate.
12231 if (auto P = CmpPredicate::getMatching(
12233 // We can write the implication
12234 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS
12235 // using one of the following ways:
12236 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS
12237 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS
12238 // Both require swapping the operands of one condition. Don't do this if it
12239 // would break canonical constant/addrec ordering.
12241 return isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P), RHS,
12242 LHS, FoundLHS, FoundRHS, CtxI);
12243 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
12244 return isImpliedCondOperands(*P, LHS, RHS, FoundRHS, FoundLHS, CtxI);
12245
12246 return false;
12247 }
12248
12249 // Try the query as is and with its operands swapped. E.g. "x >s -1" is
12250 // tried as "-1 <s x" too, to match the found condition "x <u y".
12251 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
12253 return CmpInst::isRelational(P2) &&
12255 };
12256 if (IsSignFlippedPredicate(Pred, FoundPred) &&
12257 isImpliedCondViaSignFlippedPred(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12258 return true;
12259 CmpPredicate SwappedPred = ICmpInst::getSwappedCmpPredicate(Pred);
12260 if (IsSignFlippedPredicate(SwappedPred, FoundPred) &&
12261 isImpliedCondViaSignFlippedPred(SwappedPred, RHS, LHS, FoundLHS, FoundRHS,
12262 CtxI))
12263 return true;
12264
12265 // Check if we can make progress by sharpening ranges.
12266 if (FoundPred == ICmpInst::ICMP_NE &&
12267 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
12268
12269 const SCEVConstant *C = nullptr;
12270 const SCEV *V = nullptr;
12271
12272 if (isa<SCEVConstant>(FoundLHS)) {
12273 C = cast<SCEVConstant>(FoundLHS);
12274 V = FoundRHS;
12275 } else {
12276 C = cast<SCEVConstant>(FoundRHS);
12277 V = FoundLHS;
12278 }
12279
12280 // The guarding predicate tells us that C != V. If the known range
12281 // of V is [C, t), we can sharpen the range to [C + 1, t). The
12282 // range we consider has to correspond to same signedness as the
12283 // predicate we're interested in folding.
12284
12285 APInt Min = ICmpInst::isSigned(Pred) ?
12287
12288 if (Min == C->getAPInt()) {
12289 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
12290 // This is true even if (Min + 1) wraps around -- in case of
12291 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
12292
12293 APInt SharperMin = Min + 1;
12294
12295 switch (Pred) {
12296 case ICmpInst::ICMP_SGE:
12297 case ICmpInst::ICMP_UGE:
12298 // We know V `Pred` SharperMin. If this implies LHS `Pred`
12299 // RHS, we're done.
12300 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
12301 CtxI))
12302 return true;
12303 [[fallthrough]];
12304
12305 case ICmpInst::ICMP_SGT:
12306 case ICmpInst::ICMP_UGT:
12307 // We know from the range information that (V `Pred` Min ||
12308 // V == Min). We know from the guarding condition that !(V
12309 // == Min). This gives us
12310 //
12311 // V `Pred` Min || V == Min && !(V == Min)
12312 // => V `Pred` Min
12313 //
12314 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
12315
12316 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
12317 return true;
12318 break;
12319
12320 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
12321 case ICmpInst::ICMP_SLE:
12322 case ICmpInst::ICMP_ULE:
12323 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12324 LHS, V, getConstant(SharperMin), CtxI))
12325 return true;
12326 [[fallthrough]];
12327
12328 case ICmpInst::ICMP_SLT:
12329 case ICmpInst::ICMP_ULT:
12330 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12331 LHS, V, getConstant(Min), CtxI))
12332 return true;
12333 break;
12334
12335 default:
12336 // No change
12337 break;
12338 }
12339 }
12340 }
12341
12342 // Check whether the actual condition is beyond sufficient.
12343 if (FoundPred == ICmpInst::ICMP_EQ)
12345 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12346 return true;
12347 if (Pred == ICmpInst::ICMP_NE)
12348 if (!ICmpInst::isTrueWhenEqual(FoundPred))
12349 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12350 return true;
12351
12352 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS))
12353 return true;
12354
12355 // Otherwise assume the worst.
12356 return false;
12357}
12358
12359bool ScalarEvolution::isImpliedCondViaSignFlippedPred(
12360 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12361 const SCEV *FoundRHS, const Instruction *CtxI) {
12362 CmpPredicate FoundPred = ICmpInst::getFlippedSignednessPredicate(Pred);
12363 // Unsigned comparison is the same as signed comparison when both the
12364 // operands are non-negative or negative.
12365 if (haveSameSign(FoundLHS, FoundRHS))
12366 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12367 // Canonicalize both conditions to "le/lt".
12370 FoundPred = ICmpInst::getSwappedCmpPredicate(FoundPred);
12371 std::swap(LHS, RHS);
12372 std::swap(FoundLHS, FoundRHS);
12373 }
12374 assert((ICmpInst::isLT(Pred) || ICmpInst::isLE(Pred)) && "Must be!");
12375 assert((ICmpInst::isLT(FoundPred) || ICmpInst::isLE(FoundPred)) &&
12376 "Must be!");
12377 if (ICmpInst::isSigned(Pred)) {
12378 // Use implication:
12379 // x <u y && y <=u 2^(n-1) --> x >=s 0,
12380 // x <=u y && y <u 2^(n-1) --> x >=s 0,
12381 // where n is the bit width of x and y.
12382 // In both cases x <u 2^(n-1), so x >=s 0.
12383 // y <=u 2^(n-1) means y >=s 0 or y == INT_MIN.
12384 // If the implication's left part holds, try proving the query from x >=s
12385 // 0.
12386 Type *Ty = FoundLHS->getType();
12387 unsigned BitWidth = getTypeSizeInBits(Ty);
12388 const SCEV *SignedMin = getConstant(APInt::getSignedMinValue(BitWidth));
12389 CmpPredicate BoundPred =
12391 if (isKnownViaNonRecursiveReasoning(BoundPred, FoundRHS, SignedMin)) {
12392 // x >=s 0, written as 0 <=s x, or as -1 <s x to match a strict query.
12393 const SCEV *Bound = ICmpInst::isLE(Pred) ? getZero(Ty) : getMinusOne(Ty);
12394 if (isImpliedCondOperands(Pred, LHS, RHS, Bound, FoundLHS, CtxI))
12395 return true;
12396 }
12397 }
12399 // Use implication:
12400 // x <u y && y >=s 0 --> x <s y.
12401 // If we can prove the left part, the right part is also proven.
12402 return isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS);
12403 }
12405 // Use implication:
12406 // x <s y && y <s 0 --> x <u y.
12407 // If we can prove the left part, the right part is also proven.
12408 return isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS);
12409 }
12410 return false;
12411}
12412
12413bool ScalarEvolution::splitBinaryAdd(SCEVUse Expr, SCEVUse &L, SCEVUse &R,
12414 SCEVFlags &Flags) {
12415 if (!match(Expr, m_scev_Add(m_SCEV(L), m_SCEV(R))))
12416 return false;
12417
12418 Flags = cast<SCEVAddExpr>(Expr)->getNoWrapFlags();
12419 return true;
12420}
12421
12422std::optional<APInt>
12424 // We avoid subtracting expressions here because this function is usually
12425 // fairly deep in the call stack (i.e. is called many times).
12426
12427 unsigned BW = getTypeSizeInBits(More->getType());
12428 APInt Diff(BW, 0);
12429 APInt DiffMul(BW, 1);
12430 // Try various simplifications to reduce the difference to a constant. Limit
12431 // the number of allowed simplifications to keep compile-time low.
12432 for (unsigned I = 0; I < 8; ++I) {
12433 if (More == Less)
12434 return Diff;
12435
12436 // Reduce addrecs with identical steps to their start value.
12438 const auto *LAR = cast<SCEVAddRecExpr>(Less);
12439 const auto *MAR = cast<SCEVAddRecExpr>(More);
12440
12441 if (LAR->getLoop() != MAR->getLoop())
12442 return std::nullopt;
12443
12444 // We look at affine expressions only; not for correctness but to keep
12445 // getStepRecurrence cheap.
12446 if (!LAR->isAffine() || !MAR->isAffine())
12447 return std::nullopt;
12448
12449 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
12450 return std::nullopt;
12451
12452 Less = LAR->getStart();
12453 More = MAR->getStart();
12454 continue;
12455 }
12456
12457 // Try to match a common constant multiply.
12458 auto MatchConstMul =
12459 [](const SCEV *S) -> std::optional<std::pair<const SCEV *, APInt>> {
12460 const APInt *C;
12461 const SCEV *Op;
12462 if (match(S, m_scev_Mul(m_scev_APInt(C), m_SCEV(Op))))
12463 return {{Op, *C}};
12464 return std::nullopt;
12465 };
12466 if (auto MatchedMore = MatchConstMul(More)) {
12467 if (auto MatchedLess = MatchConstMul(Less)) {
12468 if (MatchedMore->second == MatchedLess->second) {
12469 More = MatchedMore->first;
12470 Less = MatchedLess->first;
12471 DiffMul *= MatchedMore->second;
12472 continue;
12473 }
12474 }
12475 }
12476
12477 // Try to cancel out common factors in two add expressions.
12479 auto Add = [&](const SCEV *S, int Mul) {
12480 if (auto *C = dyn_cast<SCEVConstant>(S)) {
12481 if (Mul == 1) {
12482 Diff += C->getAPInt() * DiffMul;
12483 } else {
12484 assert(Mul == -1);
12485 Diff -= C->getAPInt() * DiffMul;
12486 }
12487 } else
12488 Multiplicity[S] += Mul;
12489 };
12490 auto Decompose = [&](const SCEV *S, int Mul) {
12491 if (isa<SCEVAddExpr>(S)) {
12492 for (const SCEV *Op : S->operands())
12493 Add(Op, Mul);
12494 } else
12495 Add(S, Mul);
12496 };
12497 Decompose(More, 1);
12498 Decompose(Less, -1);
12499
12500 // Check whether all the non-constants cancel out, or reduce to new
12501 // More/Less values.
12502 const SCEV *NewMore = nullptr, *NewLess = nullptr;
12503 for (const auto &[S, Mul] : Multiplicity) {
12504 if (Mul == 0)
12505 continue;
12506 if (Mul == 1) {
12507 if (NewMore)
12508 return std::nullopt;
12509 NewMore = S;
12510 } else if (Mul == -1) {
12511 if (NewLess)
12512 return std::nullopt;
12513 NewLess = S;
12514 } else
12515 return std::nullopt;
12516 }
12517
12518 // Values stayed the same, no point in trying further.
12519 if (NewMore == More || NewLess == Less)
12520 return std::nullopt;
12521
12522 More = NewMore;
12523 Less = NewLess;
12524
12525 // Reduced to constant.
12526 if (!More && !Less)
12527 return Diff;
12528
12529 // Left with variable on only one side, bail out.
12530 if (!More || !Less)
12531 return std::nullopt;
12532 }
12533
12534 // Did not reduce to constant.
12535 return std::nullopt;
12536}
12537
12538bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
12539 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12540 const SCEV *FoundRHS, const Instruction *CtxI) {
12541 // Try to recognize the following pattern:
12542 //
12543 // FoundRHS = ...
12544 // ...
12545 // loop:
12546 // FoundLHS = {Start,+,W}
12547 // context_bb: // Basic block from the same loop
12548 // known(Pred, FoundLHS, FoundRHS)
12549 //
12550 // If some predicate is known in the context of a loop, it is also known on
12551 // each iteration of this loop, including the first iteration. Therefore, in
12552 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
12553 // prove the original pred using this fact.
12554 if (!CtxI)
12555 return false;
12556 const BasicBlock *ContextBB = CtxI->getParent();
12557 // Make sure AR varies in the context block.
12558 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
12559 const Loop *L = AR->getLoop();
12560 const auto *Latch = L->getLoopLatch();
12561 // Make sure that context belongs to the loop and executes on 1st iteration
12562 // (if it ever executes at all).
12563 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12564 return false;
12565 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
12566 return false;
12567 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
12568 }
12569
12570 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
12571 const Loop *L = AR->getLoop();
12572 const auto *Latch = L->getLoopLatch();
12573 // Make sure that context belongs to the loop and executes on 1st iteration
12574 // (if it ever executes at all).
12575 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12576 return false;
12577 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
12578 return false;
12579 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
12580 }
12581
12582 return false;
12583}
12584
12585bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(CmpPredicate Pred,
12586 const SCEV *LHS,
12587 const SCEV *RHS,
12588 const SCEV *FoundLHS,
12589 const SCEV *FoundRHS) {
12591 return false;
12592
12593 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
12594 if (!AddRecLHS)
12595 return false;
12596
12597 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12598 if (!AddRecFoundLHS)
12599 return false;
12600
12601 // We'd like to let SCEV reason about control dependencies, so we constrain
12602 // both the inequalities to be about add recurrences on the same loop. This
12603 // way we can use isLoopEntryGuardedByCond later.
12604
12605 const Loop *L = AddRecFoundLHS->getLoop();
12606 if (L != AddRecLHS->getLoop())
12607 return false;
12608
12609 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
12610 //
12611 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
12612 // ... (2)
12613 //
12614 // Informal proof for (2), assuming (1) [*]:
12615 //
12616 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
12617 //
12618 // Then
12619 //
12620 // FoundLHS s< FoundRHS s< INT_MIN - C
12621 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
12622 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
12623 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
12624 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
12625 // <=> FoundLHS + C s< FoundRHS + C
12626 //
12627 // [*]: (1) can be proved by ruling out overflow.
12628 //
12629 // [**]: This can be proved by analyzing all the four possibilities:
12630 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
12631 // (A s>= 0, B s>= 0).
12632 //
12633 // Note:
12634 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
12635 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
12636 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
12637 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
12638 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
12639 // C)".
12640
12641 std::optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
12642 if (!LDiff)
12643 return false;
12644 std::optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
12645 if (!RDiff || *LDiff != *RDiff)
12646 return false;
12647
12648 if (LDiff->isMinValue())
12649 return true;
12650
12651 APInt FoundRHSLimit;
12652
12653 if (Pred == CmpInst::ICMP_ULT) {
12654 FoundRHSLimit = -(*RDiff);
12655 } else {
12656 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
12657 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
12658 }
12659
12660 // Try to prove (1) or (2), as needed.
12661 return isAvailableAtLoopEntry(FoundRHS, L) &&
12662 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
12663 getConstant(FoundRHSLimit));
12664}
12665
12666bool ScalarEvolution::isImpliedViaMerge(CmpPredicate Pred, const SCEV *LHS,
12667 const SCEV *RHS, const SCEV *FoundLHS,
12668 const SCEV *FoundRHS, unsigned Depth) {
12669 const PHINode *LPhi = nullptr, *RPhi = nullptr;
12670
12671 llvm::scope_exit ClearOnExit([&]() {
12672 if (LPhi) {
12673 bool Erased = PendingMerges.erase(LPhi);
12674 assert(Erased && "Failed to erase LPhi!");
12675 (void)Erased;
12676 }
12677 if (RPhi) {
12678 bool Erased = PendingMerges.erase(RPhi);
12679 assert(Erased && "Failed to erase RPhi!");
12680 (void)Erased;
12681 }
12682 });
12683
12684 // Find respective Phis and check that they are not being pending.
12685 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
12686 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
12687 if (!PendingMerges.insert(Phi).second)
12688 return false;
12689 LPhi = Phi;
12690 }
12691 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
12692 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
12693 // If we detect a loop of Phi nodes being processed by this method, for
12694 // example:
12695 //
12696 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
12697 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
12698 //
12699 // we don't want to deal with a case that complex, so return conservative
12700 // answer false.
12701 if (!PendingMerges.insert(Phi).second)
12702 return false;
12703 RPhi = Phi;
12704 }
12705
12706 // If none of LHS, RHS is a Phi, nothing to do here.
12707 if (!LPhi && !RPhi)
12708 return false;
12709
12710 // If there is a SCEVUnknown Phi we are interested in, make it left.
12711 if (!LPhi) {
12712 std::swap(LHS, RHS);
12713 std::swap(FoundLHS, FoundRHS);
12714 std::swap(LPhi, RPhi);
12716 }
12717
12718 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
12719 const BasicBlock *LBB = LPhi->getParent();
12720 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12721
12722 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
12723 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
12724 isImpliedCondOperandsViaRanges(Pred, S1, S2, Pred, FoundLHS, FoundRHS) ||
12725 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
12726 };
12727
12728 if (RPhi && RPhi->getParent() == LBB) {
12729 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
12730 // If we compare two Phis from the same block, and for each entry block
12731 // the predicate is true for incoming values from this block, then the
12732 // predicate is also true for the Phis.
12733 for (const BasicBlock *IncBB : predecessors(LBB)) {
12734 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12735 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
12736 if (!ProvedEasily(L, R))
12737 return false;
12738 }
12739 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
12740 // Case two: RHS is also a Phi from the same basic block, and it is an
12741 // AddRec. It means that there is a loop which has both AddRec and Unknown
12742 // PHIs, for it we can compare incoming values of AddRec from above the loop
12743 // and latch with their respective incoming values of LPhi.
12744 // TODO: Generalize to handle loops with many inputs in a header.
12745 if (LPhi->getNumIncomingValues() != 2) return false;
12746
12747 auto *RLoop = RAR->getLoop();
12748 auto *Predecessor = RLoop->getLoopPredecessor();
12749 assert(Predecessor && "Loop with AddRec with no predecessor?");
12750 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
12751 if (!ProvedEasily(L1, RAR->getStart()))
12752 return false;
12753 auto *Latch = RLoop->getLoopLatch();
12754 assert(Latch && "Loop with AddRec with no latch?");
12755 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
12756 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
12757 return false;
12758 } else {
12759 // In all other cases go over inputs of LHS and compare each of them to RHS,
12760 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
12761 // At this point RHS is either a non-Phi, or it is a Phi from some block
12762 // different from LBB.
12763 for (const BasicBlock *IncBB : predecessors(LBB)) {
12764 // Check that RHS is available in this block.
12765 if (!dominates(RHS, IncBB))
12766 return false;
12767 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12768 // Make sure L does not refer to a value from a potentially previous
12769 // iteration of a loop.
12770 if (!properlyDominates(L, LBB))
12771 return false;
12772 // Addrecs are considered to properly dominate their loop, so are missed
12773 // by the previous check. Discard any values that have computable
12774 // evolution in this loop.
12775 if (auto *Loop = LI.getLoopFor(LBB))
12777 return false;
12778 if (!ProvedEasily(L, RHS))
12779 return false;
12780 }
12781 }
12782 return true;
12783}
12784
12785bool ScalarEvolution::isImpliedCondOperandsViaShift(CmpPredicate Pred,
12786 const SCEV *LHS,
12787 const SCEV *RHS,
12788 const SCEV *FoundLHS,
12789 const SCEV *FoundRHS) {
12790 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make
12791 // sure that we are dealing with same LHS.
12792 if (RHS == FoundRHS) {
12793 std::swap(LHS, RHS);
12794 std::swap(FoundLHS, FoundRHS);
12796 }
12797 if (LHS != FoundLHS)
12798 return false;
12799
12800 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
12801 if (!SUFoundRHS)
12802 return false;
12803
12804 Value *Shiftee, *ShiftValue;
12805
12806 using namespace PatternMatch;
12807 if (match(SUFoundRHS->getValue(),
12808 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
12809 auto *ShifteeS = getSCEV(Shiftee);
12810 // Prove one of the following:
12811 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
12812 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
12813 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12814 // ---> LHS <s RHS
12815 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12816 // ---> LHS <=s RHS
12818 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
12820 if (isKnownNonNegative(ShifteeS))
12821 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
12822 }
12823
12824 return false;
12825}
12826
12827bool ScalarEvolution::isImpliedCondOperandsViaMatchingDiff(
12828 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12829 const SCEV *FoundRHS) {
12830 // Only valid for equality predicates: (A == B) implies (C == D) when
12831 // the SCEV difference A - B equals C - D (they check the same
12832 // underlying relationship at every iteration).
12834 return false;
12835
12836 // Restrict to cases involving loop recurrences - that's where this
12837 // pattern arises (correlated IV comparisons). This avoids calling
12838 // getMinusSCEV on arbitrary non-loop expressions.
12840 (!isa<SCEVAddRecExpr>(FoundLHS) && !isa<SCEVAddRecExpr>(FoundRHS)))
12841 return false;
12842
12843 // AddRecs from different loops can never produce matching differences.
12844 const SCEVAddRecExpr *QueryAddRec = dyn_cast<SCEVAddRecExpr>(LHS);
12845 if (!QueryAddRec)
12846 QueryAddRec = cast<SCEVAddRecExpr>(RHS);
12847 const SCEVAddRecExpr *FoundAddRec = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12848 if (!FoundAddRec)
12849 FoundAddRec = cast<SCEVAddRecExpr>(FoundRHS);
12850 if (QueryAddRec->getLoop() != FoundAddRec->getLoop())
12851 return false;
12852
12853 // If the strides differ, the differences can never match.
12854 if (QueryAddRec->getStepRecurrence(*this) !=
12855 FoundAddRec->getStepRecurrence(*this))
12856 return false;
12857
12858 // Compute differences. For pointer-typed operands sharing the same base,
12859 // getMinusSCEV strips the common base and returns an integer SCEV.
12860 // For example, {base,+,8} - (base+8*n) = {-8n,+,8}
12861 const SCEV *FoundDiff = getMinusSCEV(FoundLHS, FoundRHS);
12862 if (isa<SCEVCouldNotCompute>(FoundDiff))
12863 return false;
12864
12865 const SCEV *Diff = getMinusSCEV(LHS, RHS);
12866 if (isa<SCEVCouldNotCompute>(Diff))
12867 return false;
12868
12869 return Diff == FoundDiff;
12870}
12871
12872bool ScalarEvolution::isImpliedCondOperands(CmpPredicate Pred, const SCEV *LHS,
12873 const SCEV *RHS,
12874 const SCEV *FoundLHS,
12875 const SCEV *FoundRHS,
12876 const Instruction *CtxI) {
12877 return isImpliedCondOperandsViaRanges(Pred, LHS, RHS, Pred, FoundLHS,
12878 FoundRHS) ||
12879 isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS,
12880 FoundRHS) ||
12881 isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS) ||
12882 isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12883 CtxI) ||
12884 isImpliedCondOperandsViaMatchingDiff(Pred, LHS, RHS, FoundLHS,
12885 FoundRHS) ||
12886 isImpliedCondOperandsHelper(Pred, LHS, RHS, FoundLHS, FoundRHS);
12887}
12888
12889/// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
12890template <typename MinMaxExprType>
12891static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
12892 const SCEV *Candidate) {
12893 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12894 if (!MinMaxExpr)
12895 return false;
12896
12897 return is_contained(MinMaxExpr->operands(), Candidate);
12898}
12899
12901 CmpPredicate Pred, const SCEV *LHS,
12902 const SCEV *RHS) {
12903 // If both sides are affine addrecs for the same loop, with equal
12904 // steps, and we know the recurrences don't wrap, then we only
12905 // need to check the predicate on the starting values.
12906
12908 return false;
12909
12910 const SCEV *LStart, *RStart, *Step;
12911 const Loop *L;
12912 if (!match(LHS,
12913 m_scev_AffineAddRec(m_SCEV(LStart), m_SCEV(Step), m_Loop(L))) ||
12915 m_SpecificLoop(L))))
12916 return false;
12920 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
12921 return false;
12922
12923 return SE.isKnownPredicate(Pred, LStart, RStart);
12924}
12925
12926/// Is LHS `Pred` RHS true because one of them is an AddRec that is known not to
12927/// go below its own start value?
12930 const SCEV *LHS,
12931 const SCEV *RHS) {
12932 // Normalize to (AddRec Pred Start).
12935 std::swap(LHS, RHS);
12936 }
12937
12938 // The recurrence is equal to Start in the first iteration, so only the
12939 // non-strict predicate holds.
12941 return false;
12942
12943 const auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
12944 if (!AR || AR->getStart() != RHS)
12945 return false;
12946
12947 return SE.getMonotonicPredicateType(AR, Pred) ==
12949}
12950
12951/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
12952/// expression?
12954 const SCEV *LHS, const SCEV *RHS) {
12955 switch (Pred) {
12956 default:
12957 return false;
12958
12959 case ICmpInst::ICMP_SGE:
12960 std::swap(LHS, RHS);
12961 [[fallthrough]];
12962 case ICmpInst::ICMP_SLE:
12963 return
12964 // min(A, ...) <= A
12966 // A <= max(A, ...)
12968
12969 case ICmpInst::ICMP_UGE:
12970 std::swap(LHS, RHS);
12971 [[fallthrough]];
12972 case ICmpInst::ICMP_ULE:
12973 return
12974 // min(A, ...) <= A
12975 // FIXME: what about umin_seq?
12977 // A <= max(A, ...)
12979
12980 case ICmpInst::ICMP_ULT:
12981 case ICmpInst::ICMP_UGT:
12983 Pred, LHS, RHS, [&SE](CmpPredicate P, SCEVUse A, SCEVUse B) {
12984 assert(P == ICmpInst::ICMP_ULT && "UGT should be normalized to ULT");
12985 std::optional<APInt> Diff = SE.computeConstantDifference(B, A);
12986 return Diff && !Diff->isZero() &&
12987 SE.getUnsignedRangeMin(B).uge(*Diff);
12988 });
12989 }
12990
12991 llvm_unreachable("covered switch fell through?!");
12992}
12993
12994bool ScalarEvolution::isImpliedViaOperations(CmpPredicate Pred, const SCEV *LHS,
12995 const SCEV *RHS,
12996 const SCEV *FoundLHS,
12997 const SCEV *FoundRHS,
12998 unsigned Depth) {
13001 "LHS and RHS have different sizes?");
13002 assert(getTypeSizeInBits(FoundLHS->getType()) ==
13003 getTypeSizeInBits(FoundRHS->getType()) &&
13004 "FoundLHS and FoundRHS have different sizes?");
13005 // We want to avoid hurting the compile time with analysis of too big trees.
13006 if (Depth > Opts.scalar_evolution_max_scev_operations_implication_depth)
13007 return false;
13008
13009 // We only want to work with GT comparison so far.
13010 if (ICmpInst::isLT(Pred)) {
13012 std::swap(LHS, RHS);
13013 std::swap(FoundLHS, FoundRHS);
13014 }
13015
13016 CmpInst::Predicate P = Pred.getPreferredSignedPredicate();
13017
13018 // For unsigned, try to reduce it to corresponding signed comparison.
13019 if (P == ICmpInst::ICMP_UGT)
13020 // We can replace unsigned predicate with its signed counterpart if all
13021 // involved values are non-negative.
13022 // TODO: We could have better support for unsigned.
13023 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
13024 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
13025 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
13026 // use this fact to prove that LHS and RHS are non-negative.
13027 const SCEV *MinusOne = getMinusOne(LHS->getType());
13028 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
13029 FoundRHS) &&
13030 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
13031 FoundRHS))
13033 }
13034
13035 if (P != ICmpInst::ICMP_SGT)
13036 return false;
13037
13038 auto GetOpFromSExt = [&](const SCEV *S) -> const SCEV * {
13039 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
13040 return Ext->getOperand();
13041 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
13042 // the constant in some cases.
13043 return S;
13044 };
13045
13046 // Acquire values from extensions.
13047 auto *OrigLHS = LHS;
13048 auto *OrigFoundLHS = FoundLHS;
13049 LHS = GetOpFromSExt(LHS);
13050 FoundLHS = GetOpFromSExt(FoundLHS);
13051
13052 // Is the SGT predicate can be proved trivially or using the found context.
13053 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
13054 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
13055 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
13056 FoundRHS, Depth + 1);
13057 };
13058
13059 SCEVUse LL;
13060 SCEVUse LR;
13061 if (match(LHS, m_scev_NSWAdd(m_SCEV(LL), m_SCEV(LR)))) {
13062 // We want to avoid creation of any new non-constant SCEV. Since we are
13063 // going to compare the operands to RHS, we should be certain that we don't
13064 // need any size extensions for this. So let's decline all cases when the
13065 // sizes of types of LHS and RHS do not match.
13066 // TODO: Maybe try to get RHS from sext to catch more cases?
13068 return false;
13069
13070 auto *MinusOne = getMinusOne(RHS->getType());
13071
13072 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
13073 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
13074 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
13075 };
13076 // Try to prove the following rule:
13077 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
13078 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
13079 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
13080 return true;
13081 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
13082 Value *LL, *LR;
13083 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
13084
13085 using namespace llvm::PatternMatch;
13086
13087 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
13088 // Rules for division.
13089 // We are going to perform some comparisons with Denominator and its
13090 // derivative expressions. In general case, creating a SCEV for it may
13091 // lead to a complex analysis of the entire graph, and in particular it
13092 // can request trip count recalculation for the same loop. This would
13093 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
13094 // this, we only want to create SCEVs that are constants in this section.
13095 // So we bail if Denominator is not a constant.
13096 if (!isa<ConstantInt>(LR))
13097 return false;
13098
13099 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
13100
13101 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
13102 // then a SCEV for the numerator already exists and matches with FoundLHS.
13103 auto *Numerator = getExistingSCEV(LL);
13104 if (!Numerator || Numerator->getType() != FoundLHS->getType())
13105 return false;
13106
13107 // Make sure that the numerator matches with FoundLHS and the denominator
13108 // is positive.
13109 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
13110 return false;
13111
13112 auto *DTy = Denominator->getType();
13113 auto *FRHSTy = FoundRHS->getType();
13114 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
13115 // One of types is a pointer and another one is not. We cannot extend
13116 // them properly to a wider type, so let us just reject this case.
13117 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
13118 // to avoid this check.
13119 return false;
13120
13121 // Given that:
13122 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
13123 auto *WTy = getWiderType(DTy, FRHSTy);
13124 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
13125 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
13126
13127 // Try to prove the following rule:
13128 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
13129 // For example, given that FoundLHS > 2. It means that FoundLHS is at
13130 // least 3. If we divide it by Denominator < 4, we will have at least 1.
13131 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
13132 if (isKnownNonPositive(RHS) &&
13133 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
13134 return true;
13135
13136 // Try to prove the following rule:
13137 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
13138 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
13139 // If we divide it by Denominator > 2, then:
13140 // 1. If FoundLHS is negative, then the result is 0.
13141 // 2. If FoundLHS is non-negative, then the result is non-negative.
13142 // Anyways, the result is non-negative.
13143 auto *MinusOne = getMinusOne(WTy);
13144 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
13145 if (isKnownNegative(RHS) &&
13146 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
13147 return true;
13148 }
13149 }
13150
13151 // If our expression contained SCEVUnknown Phis, and we split it down and now
13152 // need to prove something for them, try to prove the predicate for every
13153 // possible incoming values of those Phis.
13154 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
13155 return true;
13156
13157 return false;
13158}
13159
13161 const SCEV *RHS) {
13162 // zext x u<= sext x, sext x s<= zext x
13163 const SCEV *Op;
13164 switch (Pred) {
13165 case ICmpInst::ICMP_SGE:
13166 std::swap(LHS, RHS);
13167 [[fallthrough]];
13168 case ICmpInst::ICMP_SLE: {
13169 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt.
13170 return match(LHS, m_scev_SExt(m_SCEV(Op))) &&
13172 }
13173 case ICmpInst::ICMP_UGE:
13174 std::swap(LHS, RHS);
13175 [[fallthrough]];
13176 case ICmpInst::ICMP_ULE: {
13177 // If operand >=u 0 then ZExt == SExt. If operand <u 0 then ZExt <u SExt.
13178 return match(LHS, m_scev_ZExt(m_SCEV(Op))) &&
13180 }
13181 default:
13182 return false;
13183 };
13184 llvm_unreachable("unhandled case");
13185}
13186
13187bool ScalarEvolution::isKnownViaNonRecursiveReasoning(CmpPredicate Pred,
13188 SCEVUse LHS,
13189 SCEVUse RHS) {
13191 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
13195 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
13196}
13197
13198bool ScalarEvolution::isImpliedCondOperandsHelper(CmpPredicate Pred,
13199 const SCEV *LHS,
13200 const SCEV *RHS,
13201 const SCEV *FoundLHS,
13202 const SCEV *FoundRHS) {
13204 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
13205 return true;
13206 } else {
13208 if (isKnownViaNonRecursiveReasoning(NonStrictPred, LHS, FoundLHS) &&
13209 isKnownViaNonRecursiveReasoning(
13210 ICmpInst::getSwappedPredicate(NonStrictPred), RHS, FoundRHS))
13211 return true;
13212 }
13213
13214 // Maybe it can be proved via operations?
13215 return isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS);
13216}
13217
13218bool ScalarEvolution::isImpliedCondOperandsViaRanges(
13219 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, CmpPredicate FoundPred,
13220 const SCEV *FoundLHS, const SCEV *FoundRHS) {
13221 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
13222 // The restriction on `FoundRHS` be lifted easily -- it exists only to
13223 // reduce the compile time impact of this optimization.
13224 return false;
13225
13226 std::optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
13227 if (!Addend)
13228 return false;
13229
13230 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
13231
13232 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
13233 // antecedent "`FoundLHS` `FoundPred` `FoundRHS`".
13234 ConstantRange FoundLHSRange =
13235 ConstantRange::makeExactICmpRegion(FoundPred, ConstFoundRHS);
13236
13237 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
13238 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
13239
13240 // We can also compute the range of values for `LHS` that satisfy the
13241 // consequent, "`LHS` `Pred` `RHS`":
13242 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
13243 // The antecedent implies the consequent if every value of `LHS` that
13244 // satisfies the antecedent also satisfies the consequent.
13245 return LHSRange.icmp(Pred, ConstRHS);
13246}
13247
13248bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
13249 bool IsSigned, bool Invert) {
13250 assert(isKnownPositive(Stride) && "Positive stride expected!");
13251
13252 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13253 const SCEV *One = getOne(Stride->getType());
13254
13255 if (IsSigned) {
13256 APInt MaxRHS = getRangeMax(RHS, /*IsSigned=*/true, Invert);
13257 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
13258 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13259
13260 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
13261 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
13262 }
13263
13264 APInt MaxRHS = getRangeMax(RHS, /*IsSigned=*/false, Invert);
13265 APInt MaxValue = APInt::getMaxValue(BitWidth);
13266 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13267
13268 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
13269 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
13270}
13271
13273 // umin(N, 1) + floor((N - umin(N, 1)) / D)
13274 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
13275 // expression fixes the case of N=0.
13276 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
13277 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
13278 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
13279}
13280
13281const SCEV *
13282ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, const SCEV *Stride,
13283 const SCEV *End, unsigned BitWidth,
13284 bool IsSigned, bool Invert) {
13285 // The logic in this function assumes we can represent a positive stride.
13286 // If we can't, the backedge-taken count must be zero.
13287 if (IsSigned && BitWidth == 1)
13288 return getZero(Stride->getType());
13289
13290 // This code below only been closely audited for negative strides in the
13291 // unsigned comparison case, it may be correct for signed comparison, but
13292 // that needs to be established.
13293 if (IsSigned && isKnownNegative(Stride))
13294 return getCouldNotCompute();
13295
13296 // Calculate the maximum backedge count based on the range of values
13297 // permitted by Start, End, and Stride. If Invert is true, both Start and End
13298 // need inverting. Stride was already negated by the caller.
13299 APInt MinStart = getRangeMin(Start, IsSigned, Invert);
13300
13301 APInt MinStride =
13302 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
13303
13304 // We assume either the stride is positive, or the backedge-taken count
13305 // is zero. So force StrideForMaxBECount to be at least one.
13306 APInt One(BitWidth, 1);
13307 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
13308 : APIntOps::umax(One, MinStride);
13309
13310 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
13311 : APInt::getMaxValue(BitWidth);
13312 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
13313
13314 // Although End can be a MAX expression we estimate MaxEnd considering only
13315 // the case End = RHS of the loop termination condition. This is safe because
13316 // in the other case (End - Start) is zero, leading to a zero maximum backedge
13317 // taken count.
13318 APInt MaxEnd = getRangeMax(End, IsSigned, Invert);
13319 MaxEnd =
13320 IsSigned ? APIntOps::smin(MaxEnd, Limit) : APIntOps::umin(MaxEnd, Limit);
13321
13322 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
13323 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
13324 : APIntOps::umax(MaxEnd, MinStart);
13325
13326 APInt Delta = MaxEnd - MinStart;
13327
13328 // Try to refine Delta in case End - Start (or Start - End if Invert) gives a
13329 // tighter bound after folding.
13330 const SCEV *DeltaExpr =
13331 Invert ? getMinusSCEV(Start, End) : getMinusSCEV(End, Start);
13332 Delta = APIntOps::umin(Delta, getUnsignedRangeMax(DeltaExpr));
13333
13334 return getUDivCeilSCEV(getConstant(Delta), getConstant(StrideForMaxBECount));
13335}
13336
13337ScalarEvolution::ExitLimit ScalarEvolution::howManyLessThans(
13338 const SCEV *LHS, SCEVUse RHS, const Loop *L, LoopGuards &Guards,
13339 bool IsSigned, bool Invert, bool ControlsOnlyExit, bool AllowPredicates) {
13341
13342 // FIXME: Extend the non-invariant RHS analysis to greater-than comparisons.
13343 if (Invert && !isLoopInvariant(RHS, L))
13344 return getCouldNotCompute();
13345
13347 bool PredicatedIV = false;
13348 // FIXME: Generalize the NUW inference below to decreasing IVs.
13349 if (!IV && !Invert) {
13350 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
13351 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
13352 if (AR && AR->getLoop() == L && AR->isAffine()) {
13353 auto canProveNUW = [&]() {
13354 // We can use the comparison to infer no-wrap flags only if it fully
13355 // controls the loop exit.
13356 if (!ControlsOnlyExit)
13357 return false;
13358
13359 if (!isLoopInvariant(RHS, L))
13360 return false;
13361
13362 if (!isKnownNonZero(AR->getStepRecurrence(*this)))
13363 // We need the sequence defined by AR to strictly increase in the
13364 // unsigned integer domain for the logic below to hold.
13365 return false;
13366
13367 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
13368 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
13369 // If RHS <=u Limit, then there must exist a value V in the sequence
13370 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
13371 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned
13372 // overflow occurs. This limit also implies that a signed comparison
13373 // (in the wide bitwidth) is equivalent to an unsigned comparison as
13374 // the high bits on both sides must be zero.
13375 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
13376 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
13377 Limit = Limit.zext(OuterBitWidth);
13378 return getUnsignedRangeMax(applyLoopGuards(RHS, Guards)).ule(Limit);
13379 };
13380 auto Flags = AR->getNoWrapFlags();
13381 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
13382 Flags = setFlags(Flags, SCEV::FlagNUW);
13383
13384 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
13385 if (AR->hasNoUnsignedWrap()) {
13386 // Emulate what getZeroExtendExpr would have done during construction
13387 // if we'd been able to infer the fact just above at that time.
13388 const SCEV *Step = AR->getStepRecurrence(*this);
13389 Type *Ty = ZExt->getType();
13390 const SCEV *S = getAddRecExpr(
13392 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
13394 }
13395 }
13396 }
13397 }
13398
13399 if (!IV && AllowPredicates) {
13400 // Try to make this an AddRec using runtime tests, in the first X
13401 // iterations of this loop, where X is the SCEV expression found by the
13402 // algorithm below.
13403 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13404 PredicatedIV = true;
13405 }
13406
13407 // Avoid weird loops
13408 if (!IV || IV->getLoop() != L || !IV->isAffine())
13409 return getCouldNotCompute();
13410
13411 // A precondition of this method is that the condition being analyzed
13412 // reaches an exiting branch which dominates the latch. Given that, we can
13413 // assume that an increment which violates the nowrap specification and
13414 // produces poison must cause undefined behavior when the resulting poison
13415 // value is branched upon and thus we can conclude that the backedge is
13416 // taken no more often than would be required to produce that poison value.
13417 // Note that a well defined loop can exit on the iteration which violates
13418 // the nowrap specification if there is another exit (either explicit or
13419 // implicit/exceptional) which causes the loop to execute before the
13420 // exiting instruction we're analyzing would trigger UB.
13421 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13422 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13423 // Reverse the ordering for greater-than comparisons.
13425 if (Invert)
13427
13428 // The step of ~IV is the negated step of IV.
13429 const SCEV *Stride = IV->getStepRecurrence(*this);
13430 if (Invert)
13431 Stride = getNegativeSCEV(Stride);
13432 const SCEV *GuardedStride = Stride;
13433
13434 // Whether the IV may reach the maximum (or minimum if inverted) value
13435 // before the exit is taken.
13436 bool IVMayOverflow = true;
13437
13438 bool PositiveStride = isKnownPositive(Stride);
13439 // A dominating guard may prove the stride positive.
13440 if (!PositiveStride) {
13441 const SCEV *LoopGuardedStride = applyLoopGuards(Stride, Guards);
13442 if (isKnownPositive(LoopGuardedStride)) {
13443 GuardedStride = LoopGuardedStride;
13444 PositiveStride = true;
13445 // Encode the context-sensitive stride > 0 fact into the expression
13446 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13447 }
13448 }
13449
13450 // Avoid negative or zero stride values.
13451 if (!PositiveStride) {
13452 // FIXME: Generalize the unknown-stride analysis to decreasing IVs.
13453 if (Invert)
13454 return getCouldNotCompute();
13455
13456 // We can compute the correct backedge taken count for loops with unknown
13457 // strides if we can prove that the loop is not an infinite loop with side
13458 // effects. Here's the loop structure we are trying to handle -
13459 //
13460 // i = start
13461 // do {
13462 // A[i] = i;
13463 // i += s;
13464 // } while (i < end);
13465 //
13466 // The backedge taken count for such loops is evaluated as -
13467 // (max(end, start + stride) - start - 1) /u stride
13468 //
13469 // The additional preconditions that we need to check to prove correctness
13470 // of the above formula is as follows -
13471 //
13472 // a) IV is either nuw or nsw depending upon signedness (indicated by the
13473 // NoWrap flag).
13474 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13475 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13476 // no side effects within the loop) or a predicate is added to ensure
13477 // stride is positive.
13478 // c) loop has a single static exit (with no abnormal exits)
13479 //
13480 // Precondition a) implies that if the stride is negative, this is a single
13481 // trip loop. The backedge taken count formula reduces to zero in this case.
13482 //
13483 // Precondition b) and c) combine to imply that if rhs is invariant in L,
13484 // then a zero stride means the backedge can't be taken without executing
13485 // undefined behavior.
13486 //
13487 // The positive stride case is the same as isKnownPositive(Stride) returning
13488 // true (original behavior of the function).
13489 //
13490 if (PredicatedIV || !NoWrap || !loopHasNoAbnormalExits(L))
13491 return getCouldNotCompute();
13492
13493 if (!loopIsFiniteByAssumption(L)) {
13494 // If the loop may be infinite, add a predicate ensuring Stride is
13495 // positive, to guarantee forward progress.
13496 if (!AllowPredicates || !isLoopInvariant(Stride, L))
13497 return getCouldNotCompute();
13498
13499 const SCEV *Zero = getZero(Stride->getType());
13500 const SCEVPredicate *P =
13502 Predicates.push_back(P);
13503 // When the predicate holds (Stride > 0), umax(Stride, 1) == Stride,
13504 // so the result is unchanged. To prevent div by zero.
13505 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13506 } else if (!isKnownNonZero(Stride)) {
13507 // If we have a step of zero, and RHS isn't invariant in L, we don't know
13508 // if it might eventually be greater than start and if so, on which
13509 // iteration. We can't even produce a useful upper bound.
13510 if (!isLoopInvariant(RHS, L))
13511 return getCouldNotCompute();
13512
13513 // We allow a potentially zero stride, but we need to divide by stride
13514 // below. Since the loop can't be infinite and this check must control
13515 // the sole exit, we can infer the exit must be taken on the first
13516 // iteration (e.g. backedge count = 0) if the stride is zero. Given that,
13517 // we know the numerator in the divides below must be zero, so we can
13518 // pick an arbitrary non-zero value for the denominator (e.g. stride)
13519 // and produce the right result.
13520 // FIXME: Handle the case where Stride is poison?
13521 auto wouldZeroStrideBeUB = [&]() {
13522 // Proof by contradiction. Suppose the stride were zero. If we can
13523 // prove that the backedge *is* taken on the first iteration, then since
13524 // we know this condition controls the sole exit, we must have an
13525 // infinite loop. We can't have a (well defined) infinite loop per
13526 // check just above.
13527 // Note: The (Start - Stride) term is used to get the start' term from
13528 // (start' + stride,+,stride). Remember that we only care about the
13529 // result of this expression when stride == 0 at runtime.
13530 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
13531 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
13532 };
13533 if (!wouldZeroStrideBeUB()) {
13534 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13535 }
13536 }
13537 } else {
13538 // Avoid proven overflow cases: this will ensure that the backedge taken
13539 // count will not generate any unsigned overflow.
13540 IVMayOverflow = canIVOverflowOnLT(RHS, GuardedStride, IsSigned, Invert) &&
13541 canIVOverflowOnLT(applyLoopGuards(RHS, Guards),
13542 GuardedStride, IsSigned, Invert);
13543 if (IVMayOverflow && !NoWrap)
13544 return getCouldNotCompute();
13545 }
13546
13547 // On all paths just preceeding, we established the following invariant:
13548 // IV can be assumed not to overflow up to and including the exiting
13549 // iteration. We proved this in one of two ways:
13550 // 1) We can show overflow doesn't occur before the exiting iteration
13551 // 1a) canIVOverflowOnLT, and b) step of one
13552 // 2) We can show that if overflow occurs, the loop must execute UB
13553 // before any possible exit.
13554 // Note that we have not yet proved RHS invariant (in general).
13555
13556 const SCEV *Start = IV->getStart();
13557
13558 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
13559 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
13560 // Use integer-typed versions for actual computation; we can't subtract
13561 // pointers in general.
13562 const SCEV *OrigStart = Start;
13563 const SCEV *OrigRHS = RHS;
13564 if (Start->getType()->isPointerTy()) {
13565 Start = getPtrToAddrExpr(Start);
13566 if (isa<SCEVCouldNotCompute>(Start))
13567 return Start;
13568 }
13569 if (RHS->getType()->isPointerTy()) {
13572 return RHS;
13573 }
13574
13575 const SCEV *End = nullptr, *BECount = getCouldNotCompute(),
13576 *BECountIfBackedgeTaken = getCouldNotCompute();
13577 if (!isLoopInvariant(RHS, L)) {
13578 assert(!Invert && "RHS must be loop-invariant for Invert");
13579 const auto *RHSAddRec = dyn_cast<SCEVAddRecExpr>(RHS);
13580 if (PositiveStride && RHSAddRec != nullptr && RHSAddRec->getLoop() == L &&
13581 any(RHSAddRec->getNoWrapFlags())) {
13582 // The structure of loop we are trying to calculate backedge count of:
13583 //
13584 // left = left_start
13585 // right = right_start
13586 //
13587 // while(left < right){
13588 // ... do something here ...
13589 // left += s1; // stride of left is s1 (s1 > 0)
13590 // right += s2; // stride of right is s2 (s2 < 0)
13591 // }
13592 //
13593
13594 const SCEV *RHSStart = RHSAddRec->getStart();
13595 const SCEV *RHSStride = RHSAddRec->getStepRecurrence(*this);
13596
13597 // If Stride - RHSStride is positive and does not overflow, we can write
13598 // backedge count as ->
13599 // ceil((End - Start) /u (Stride - RHSStride))
13600 // Where, End = max(RHSStart, Start)
13601
13602 // Check if RHSStride < 0 and Stride - RHSStride will not overflow.
13603 if (isKnownNegative(RHSStride) &&
13604 willNotOverflow(Instruction::Sub, /*Signed=*/true, Stride,
13605 RHSStride)) {
13606
13607 const SCEV *Denominator = getMinusSCEV(Stride, RHSStride);
13608 if (isKnownPositive(Denominator)) {
13609 End = IsSigned ? getSMaxExpr(RHSStart, Start)
13610 : getUMaxExpr(RHSStart, Start);
13611
13612 // We can do this because End >= Start, as End = max(RHSStart, Start)
13613 const SCEV *Delta = getMinusSCEV(End, Start);
13614
13615 BECount = getUDivCeilSCEV(Delta, Denominator);
13616 BECountIfBackedgeTaken =
13617 getUDivCeilSCEV(getMinusSCEV(RHSStart, Start), Denominator);
13618 }
13619 }
13620 }
13621 } else {
13622 // Let End = max(RHS,Start). We use the expression (End-Start)/Stride to
13623 // describe the backedge count: if the backedge is taken at least once then
13624 // End is RHS, and if not End is Start so we get a backedge count of zero.
13625 // Inverted, End is min(RHS, Start).
13626 //
13627 // AddingStrideMinusOneMayOverflow has the following preconditions:
13628 //
13629 // 1. Start <= End, signed if IsSigned (inverted: End <= Start)
13630 // 2. The index variable doesn't overflow.
13631 //
13632 // Therefore, we know N exists such that
13633 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
13634 // doesn't overflow.
13635 //
13636 // Using this information, try to prove whether the addition in
13637 // "(End - Start) + (Stride - 1)" has unsigned overflow.
13638 //
13639 // If the IV cannot overflow, RHS is at least Stride - 1 below the maximum
13640 // value, so the distance End - Start is at most UMAX - (Stride - 1) and
13641 // the (Stride - 1) addition below cannot overflow.
13642 const SCEV *One = getOne(Stride->getType());
13643 bool AddingStrideMinusOneMayOverflow = IVMayOverflow && [&] {
13644 if (isKnownToBeAPowerOfTwo(Stride)) {
13645 // Suppose Stride is a power of two, and Start/End are unsigned
13646 // integers. Let UMAX be the largest representable unsigned
13647 // integer.
13648 //
13649 // By the preconditions of this function, we know
13650 // "(Start + Stride * N) >= End", and this doesn't overflow.
13651 // As a formula:
13652 //
13653 // End <= (Start + Stride * N) <= UMAX
13654 //
13655 // Subtracting Start from all the terms:
13656 //
13657 // End - Start <= Stride * N <= UMAX - Start
13658 //
13659 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore:
13660 //
13661 // End - Start <= Stride * N <= UMAX
13662 //
13663 // Stride * N is a multiple of Stride. Therefore,
13664 //
13665 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
13666 //
13667 // Since Stride is a power of two, UMAX + 1 is divisible by
13668 // Stride. Therefore, UMAX mod Stride == Stride - 1. So we can
13669 // write:
13670 //
13671 // End - Start <= Stride * N <= UMAX - Stride - 1
13672 //
13673 // Dropping the middle term:
13674 //
13675 // End - Start <= UMAX - Stride - 1
13676 //
13677 // Adding Stride - 1 to both sides:
13678 //
13679 // (End - Start) + (Stride - 1) <= UMAX
13680 //
13681 // In other words, the addition doesn't have unsigned overflow.
13682 //
13683 // A similar proof works if we treat Start/End as signed values.
13684 // Just rewrite steps before "End - Start <= Stride * N <= UMAX"
13685 // to use signed max instead of unsigned max. Note that we're
13686 // trying to prove a lack of unsigned overflow in either case.
13687 // Inverted: "Start - End <= Stride * N <= Start - MIN <= UMAX", same.
13688 return false;
13689 }
13690 if (!Invert && (Start == Stride || Start == getMinusSCEV(Stride, One))) {
13691 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End
13692 // - 1. If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1
13693 // <u End. If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End -
13694 // 1 <s End.
13695 //
13696 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 ==
13697 // End.
13698 //
13699 // Both need Start to be the smaller value, so neither applies inverted.
13700 return false;
13701 }
13702 return true;
13703 }();
13704
13705 // If inverted, the analyzed values are complements: "~V - Offset" is "~(V +
13706 // Offset)" and "~To - ~From" is "From - To".
13707 auto StepBack = [&](const SCEV *V, const SCEV *Offset) -> const SCEV * {
13708 if (Invert)
13709 return getAddExpr(V, Offset);
13710 return getMinusSCEV(V, Offset);
13711 };
13712 auto Distance = [&](const SCEV *From, const SCEV *To) {
13713 return Invert ? getMinusSCEV(From, To) : getMinusSCEV(To, From);
13714 };
13715
13716 const SCEV *OrigPrevStart = StepBack(OrigStart, Stride);
13717 assert(isAvailableAtLoopEntry(OrigPrevStart, L) && "Must be!");
13718 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
13719 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
13720 // Can we prove Start - Stride < RHS, and either Start - Stride < Start or
13721 // (via !AddingStrideMinusOneMayOverflow) that (RHS - Start) + (Stride - 1)
13722 // does not overflow?
13723 if ((!AddingStrideMinusOneMayOverflow ||
13724 isLoopEntryGuardedByCond(L, Cond, OrigPrevStart, OrigStart)) &&
13725 isLoopEntryGuardedByCond(L, Cond, OrigPrevStart, OrigRHS)) {
13726 // In this case, we can use a refined formula for computing backedge
13727 // taken count. The general formula remains:
13728 // "End-Start /uceiling Stride"
13729 // We want to use the alternate formula:
13730 // "((RHS - 1) - (Start - Stride)) /u Stride"
13731 // Let's do a quick case analysis to show these are equivalent under
13732 // our preconditions. When inverted, the proof uses complemented Start,
13733 // RHS and End; Stride remains positive.
13734 // * For RHS <= Start (End is Start), the backedge-taken count must be
13735 // zero. Together with the precondition "Start - Stride < RHS", we have
13736 // "Start - Stride < RHS <= Start". Subtracting Start - Stride from
13737 // all sides we get "0 < RHS - (Start - Stride) <= Stride".
13738 // Subtracting 1 we get "0 <= (RHS - 1) - (Start - Stride) < Stride".
13739 // So dividing that by Stride gives zero.
13740 //
13741 // * For RHS > Start (End is RHS), the backedge count must be
13742 // "RHS-Start /uceil Stride", so it is sufficient to show that the
13743 // numerator "((RHS - 1) - (Start - Stride))" does not overflow.
13744 //
13745 // If "Start - Stride < Start" holds, we have
13746 // "RHS > Start > Start - Stride". As such
13747 // "RHS - (Start - Stride) - 1" does not overflow, which is the
13748 // reassociated numerator.
13749 //
13750 // Otherwise !AddingStrideMinusOneMayOverflow guarantees that
13751 // "(End - Start) + (Stride - 1)" does not overflow unsigned. Here
13752 // "End" is "RHS", as "RHS > Start", so this is the reassociated
13753 // numerator. Neither sub-term wraps unsigned: "RHS - Start"
13754 // due to "RHS > Start", and "Stride - 1", as Stride is non-zero.
13755 const SCEV *Numerator =
13756 getMinusSCEV(Distance(StepBack(Start, Stride), RHS), One);
13757 BECount = getUDivExpr(Numerator, Stride);
13758 }
13759
13760 if (isa<SCEVCouldNotCompute>(BECount)) {
13761 auto canProveRHSIsAtOrBeyondStart = [&]() {
13762 // Inverted, the claim is "Start >= RHS". Reverse the comparisons below
13763 // by swapping their operands rather than their predicates:
13764 // isLoopEntryGuardedByCond is sensitive to operand order and loses the
13765 // proof if the IV bound moves to the other side.
13766 auto SwapIfInverted = [&](const SCEV *A, const SCEV *B) {
13767 return Invert ? std::pair(B, A) : std::pair(A, B);
13768 };
13769
13770 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
13771 const SCEV *GuardedRHS = applyLoopGuards(OrigRHS, Guards);
13772 const SCEV *GuardedStart = applyLoopGuards(OrigStart, Guards);
13773 if (Invert)
13774 std::swap(GuardedRHS, GuardedStart);
13775
13776 auto [GELHS, GERHS] = SwapIfInverted(OrigRHS, OrigStart);
13777 if (isLoopEntryGuardedByCond(L, CondGE, GELHS, GERHS) ||
13778 isKnownPredicate(CondGE, GuardedRHS, GuardedStart))
13779 return true;
13780
13781 if ((GuardedRHS != GELHS || GuardedStart != GERHS) &&
13782 isKnownPredicate(CondGE, GELHS, GERHS))
13783 return true;
13784
13785 // (RHS > Start - 1) implies RHS >= Start.
13786 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
13787 // "Start - 1" doesn't overflow.
13788 // * For signed comparison, if Start - 1 does overflow, it's equal
13789 // to INT_MAX, and "RHS >s INT_MAX" is trivially false.
13790 // * For unsigned comparison, if Start - 1 does overflow, it's equal
13791 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
13792 //
13793 // FIXME: Should isLoopEntryGuardedByCond do this for us?
13794 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13795 auto [GTLHS, GTRHS] = SwapIfInverted(OrigRHS, StepBack(OrigStart, One));
13796 return isLoopEntryGuardedByCond(L, CondGT, GTLHS, GTRHS);
13797 };
13798
13799 // If we know that RHS >= Start in the context of loop, then we know
13800 // that max(RHS, Start) = RHS at this point.
13801 if (canProveRHSIsAtOrBeyondStart()) {
13802 End = RHS;
13803 } else {
13804 // If RHS < Start, the backedge will be taken zero times. So in
13805 // general, we can write the backedge-taken count as:
13806 //
13807 // RHS >= Start ? ceil(RHS - Start) / Stride : 0
13808 //
13809 // We convert it to the following to make it more convenient for SCEV:
13810 //
13811 // ceil(max(RHS, Start) - Start) / Stride
13812 //
13813 // Inverted, this is ceil(Start - min(RHS, Start)) / Stride.
13814 if (Invert)
13815 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
13816 else
13817 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
13818
13819 // See what would happen if we assume the backedge is taken. This is
13820 // used to compute MaxBECount.
13821 BECountIfBackedgeTaken = getUDivCeilSCEV(Distance(Start, RHS), Stride);
13822 }
13823
13824 const SCEV *Delta = Distance(Start, End);
13825 if (!AddingStrideMinusOneMayOverflow) {
13826 // floor((D + (S - 1)) / S)
13827 // We prefer this formulation if it's legal because it's fewer
13828 // operations.
13829 BECount =
13830 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13831 } else {
13832 BECount = getUDivCeilSCEV(Delta, Stride);
13833 }
13834 }
13835 }
13836
13837 const SCEV *ConstantMaxBECount;
13838 bool MaxOrZero = false;
13839 if (isa<SCEVConstant>(BECount)) {
13840 ConstantMaxBECount = BECount;
13841 } else {
13842 ConstantMaxBECount = computeMaxBECountForLT(
13843 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned,
13844 Invert);
13845 // If we know exactly how many times the backedge will be taken if it's
13846 // taken at least once, then the backedge count will either be that or
13847 // zero. If that count exceeds the range-based bound, the backedge can
13848 // never be taken.
13849 const APInt *IfTaken, *RangeMax;
13850 if (match(BECountIfBackedgeTaken, m_scev_APInt(IfTaken))) {
13851 if (match(ConstantMaxBECount, m_scev_APInt(RangeMax)) &&
13852 IfTaken->ugt(*RangeMax)) {
13853 ConstantMaxBECount = getZero(BECountIfBackedgeTaken->getType());
13854 } else {
13855 ConstantMaxBECount = BECountIfBackedgeTaken;
13856 MaxOrZero = true;
13857 }
13858 }
13859 }
13860
13861 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
13862 !isa<SCEVCouldNotCompute>(BECount))
13863 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
13864
13865 const SCEV *SymbolicMaxBECount =
13866 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13867 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
13868 Predicates);
13869}
13870
13872 ScalarEvolution &SE) const {
13873 if (Range.isFullSet()) // Infinite loop.
13874 return SE.getCouldNotCompute();
13875
13876 // If the start is a non-zero constant, shift the range to simplify things.
13877 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
13878 if (!SC->getValue()->isZero()) {
13880 Operands[0] = SE.getZero(SC->getType());
13881 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
13883 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
13884 return ShiftedAddRec->getNumIterationsInRange(
13885 Range.subtract(SC->getAPInt()), SE);
13886 // This is strange and shouldn't happen.
13887 return SE.getCouldNotCompute();
13888 }
13889
13890 // The only time we can solve this is when we have all constant indices.
13891 // Otherwise, we cannot determine the overflow conditions.
13893 return SE.getCouldNotCompute();
13894
13895 // Okay at this point we know that all elements of the chrec are constants and
13896 // that the start element is zero.
13897
13898 // First check to see if the range contains zero. If not, the first
13899 // iteration exits.
13900 unsigned BitWidth = SE.getTypeSizeInBits(getType());
13901 if (!Range.contains(APInt(BitWidth, 0)))
13902 return SE.getZero(getType());
13903
13904 if (isAffine()) {
13905 // If this is an affine expression then we have this situation:
13906 // Solve {0,+,A} in Range === Ax in Range
13907
13908 // We know that zero is in the range. If A is positive then we know that
13909 // the upper value of the range must be the first possible exit value.
13910 // If A is negative then the lower of the range is the last possible loop
13911 // value. Also note that we already checked for a full range.
13912 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
13913 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
13914
13915 // The exit value should be (End+A)/A.
13916 APInt ExitVal = (End + A).udiv(A);
13917 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
13918
13919 // Evaluate at the exit value. If we really did fall out of the valid
13920 // range, then we computed our trip count, otherwise wrap around or other
13921 // things must have happened.
13922 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
13923 if (Range.contains(Val->getValue()))
13924 return SE.getCouldNotCompute(); // Something strange happened
13925
13926 // Ensure that the previous value is in the range.
13927 assert(Range.contains(
13929 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
13930 "Linear scev computation is off in a bad way!");
13931 return SE.getConstant(ExitValue);
13932 }
13933
13934 if (isQuadratic()) {
13935 if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
13936 return SE.getConstant(*S);
13937 }
13938
13939 return SE.getCouldNotCompute();
13940}
13941
13942const SCEVAddRecExpr *
13944 assert(getNumOperands() > 1 && "AddRec with zero step?");
13945 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
13946 // but in this case we cannot guarantee that the value returned will be an
13947 // AddRec because SCEV does not have a fixed point where it stops
13948 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
13949 // may happen if we reach arithmetic depth limit while simplifying. So we
13950 // construct the returned value explicitly.
13952 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
13953 // (this + Step) is {A+B,+,B+C,+...,+,N}.
13954 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
13955 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
13956 // We know that the last operand is not a constant zero (otherwise it would
13957 // have been popped out earlier). This guarantees us that if the result has
13958 // the same last operand, then it will also not be popped out, meaning that
13959 // the returned value will be an AddRec.
13960 const SCEV *Last = getOperand(getNumOperands() - 1);
13961 assert(!Last->isZero() && "Recurrency with zero step?");
13962 Ops.push_back(Last);
13964}
13965
13966// Return true when S contains at least an undef value.
13968 return SCEVExprContains(
13969 S, [](const SCEV *S) { return match(S, m_scev_UndefOrPoison()); });
13970}
13971
13972// Return true when S contains a value that is a nullptr.
13974 return SCEVExprContains(S, [](const SCEV *S) {
13975 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
13976 return SU->getValue() == nullptr;
13977 return false;
13978 });
13979}
13980
13981/// Return the size of an element read or written by Inst.
13983 if (!isa<LoadInst, StoreInst>(Inst))
13984 return nullptr;
13986 return getSizeOfExpr(ETy, getLoadStoreType(Inst));
13987}
13988
13989//===----------------------------------------------------------------------===//
13990// SCEVCallbackVH Class Implementation
13991//===----------------------------------------------------------------------===//
13992
13994 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
13995 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
13996 SE->ConstantEvolutionLoopExitValue.erase(PN);
13997 SE->eraseValueFromMap(getValPtr());
13998 // this now dangles!
13999}
14000
14001void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
14002 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14003
14004 // Forget all the expressions associated with users of the old value,
14005 // so that future queries will recompute the expressions using the new
14006 // value.
14007 SE->forgetValue(getValPtr());
14008 // this now dangles!
14009}
14010
14011ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
14012 : CallbackVH(V), SE(se) {}
14013
14014//===----------------------------------------------------------------------===//
14015// ScalarEvolution Class Implementation
14016//===----------------------------------------------------------------------===//
14017
14020 LoopInfo &LI)
14021 : Opts(getAnalysisOptions(F)), F(F), DL(F.getDataLayout()), TLI(TLI),
14022 AC(AC), DT(DT), LI(LI), CouldNotCompute(new SCEVCouldNotCompute()),
14023 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64) {
14024 // To use guards for proving predicates, we need to scan every instruction in
14025 // relevant basic blocks, and not just terminators. Doing this is a waste of
14026 // time if the IR does not actually contain any calls to
14027 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
14028 //
14029 // This pessimizes the case where a pass that preserves ScalarEvolution wants
14030 // to _add_ guards to the module when there weren't any before, and wants
14031 // ScalarEvolution to optimize based on those guards. For now we prefer to be
14032 // efficient in lieu of being smart in that rather obscure case.
14033
14034 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
14035 F.getParent(), Intrinsic::experimental_guard);
14036 HasGuards = GuardDecl && !GuardDecl->use_empty();
14037}
14038
14040 : Opts(Arg.Opts), F(Arg.F), DL(Arg.DL), HasGuards(Arg.HasGuards),
14041 TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), LI(Arg.LI),
14042 CouldNotCompute(std::move(Arg.CouldNotCompute)),
14043 ValueExprMap(std::move(Arg.ValueExprMap)),
14044 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
14045 PendingMerges(std::move(Arg.PendingMerges)),
14046 ConstantMultipleCache(std::move(Arg.ConstantMultipleCache)),
14047 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
14048 PredicatedBackedgeTakenCounts(
14049 std::move(Arg.PredicatedBackedgeTakenCounts)),
14050 BECountUsers(std::move(Arg.BECountUsers)),
14051 ConstantEvolutionLoopExitValue(
14052 std::move(Arg.ConstantEvolutionLoopExitValue)),
14053 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
14054 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
14055 LoopDispositions(std::move(Arg.LoopDispositions)),
14056 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
14057 BlockDispositions(std::move(Arg.BlockDispositions)),
14058 SCEVUsers(std::move(Arg.SCEVUsers)),
14059 UnsignedRanges(std::move(Arg.UnsignedRanges)),
14060 SignedRanges(std::move(Arg.SignedRanges)),
14061 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
14062 UniquePreds(std::move(Arg.UniquePreds)),
14063 SCEVAllocator(std::move(Arg.SCEVAllocator)),
14064 ConstantSCEVs(std::move(Arg.ConstantSCEVs)),
14065 LoopUsers(std::move(Arg.LoopUsers)),
14066 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
14067 FirstUnknown(Arg.FirstUnknown),
14068 NextUnknownOrderID(Arg.NextUnknownOrderID) {
14069 Arg.FirstUnknown = nullptr;
14070}
14071
14073 // Iterate through all the SCEVUnknown instances and call their
14074 // destructors, so that they release their references to their values.
14075 for (SCEVUnknown *U = FirstUnknown; U;) {
14076 SCEVUnknown *Tmp = U;
14077 U = U->Next;
14078 Tmp->~SCEVUnknown();
14079 }
14080 FirstUnknown = nullptr;
14081
14082 ExprValueMap.clear();
14083 ValueExprMap.clear();
14084 HasRecMap.clear();
14085 BackedgeTakenCounts.clear();
14086 PredicatedBackedgeTakenCounts.clear();
14087
14088 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
14089 assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
14090 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
14091 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
14092}
14093
14097
14098/// When printing a top-level SCEV for trip counts, it's helpful to include
14099/// a type for constants which are otherwise hard to disambiguate.
14100static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV* S) {
14101 if (isa<SCEVConstant>(S))
14102 OS << *S->getType() << " ";
14103 OS << *S;
14104}
14105
14107 const Loop *L) {
14108 // Print all inner loops first
14109 for (Loop *I : *L)
14110 PrintLoopInfo(OS, SE, I);
14111
14112 OS << "Loop ";
14113 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14114 OS << ": ";
14115
14116 SmallVector<BasicBlock *, 8> ExitingBlocks;
14117 L->getExitingBlocks(ExitingBlocks);
14118 if (ExitingBlocks.size() != 1)
14119 OS << "<multiple exits> ";
14120
14121 auto *BTC = SE->getBackedgeTakenCount(L);
14122 if (!isa<SCEVCouldNotCompute>(BTC)) {
14123 OS << "backedge-taken count is ";
14124 PrintSCEVWithTypeHint(OS, BTC);
14125 } else
14126 OS << "Unpredictable backedge-taken count.";
14127 OS << "\n";
14128
14129 if (ExitingBlocks.size() > 1)
14130 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14131 OS << " exit count for " << ExitingBlock->getName() << ": ";
14132 const SCEV *EC = SE->getExitCount(L, ExitingBlock);
14133 PrintSCEVWithTypeHint(OS, EC);
14134 if (isa<SCEVCouldNotCompute>(EC)) {
14135 // Retry with predicates.
14137 EC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates);
14138 if (!isa<SCEVCouldNotCompute>(EC)) {
14139 OS << "\n predicated exit count for " << ExitingBlock->getName()
14140 << ": ";
14141 PrintSCEVWithTypeHint(OS, EC);
14142 OS << "\n Predicates:\n";
14143 for (const auto *P : Predicates)
14144 P->print(OS, 4);
14145 }
14146 }
14147 OS << "\n";
14148 }
14149
14150 OS << "Loop ";
14151 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14152 OS << ": ";
14153
14154 auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
14155 if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
14156 OS << "constant max backedge-taken count is ";
14157 PrintSCEVWithTypeHint(OS, ConstantBTC);
14159 OS << ", actual taken count either this or zero.";
14160 } else {
14161 OS << "Unpredictable constant max backedge-taken count. ";
14162 }
14163
14164 OS << "\n"
14165 "Loop ";
14166 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14167 OS << ": ";
14168
14169 auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
14170 if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
14171 OS << "symbolic max backedge-taken count is ";
14172 PrintSCEVWithTypeHint(OS, SymbolicBTC);
14174 OS << ", actual taken count either this or zero.";
14175 } else {
14176 OS << "Unpredictable symbolic max backedge-taken count. ";
14177 }
14178 OS << "\n";
14179
14180 if (ExitingBlocks.size() > 1)
14181 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14182 OS << " symbolic max exit count for " << ExitingBlock->getName() << ": ";
14183 auto *ExitBTC = SE->getExitCount(L, ExitingBlock,
14185 PrintSCEVWithTypeHint(OS, ExitBTC);
14186 if (isa<SCEVCouldNotCompute>(ExitBTC)) {
14187 // Retry with predicates.
14189 ExitBTC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates,
14191 if (!isa<SCEVCouldNotCompute>(ExitBTC)) {
14192 OS << "\n predicated symbolic max exit count for "
14193 << ExitingBlock->getName() << ": ";
14194 PrintSCEVWithTypeHint(OS, ExitBTC);
14195 OS << "\n Predicates:\n";
14196 for (const auto *P : Predicates)
14197 P->print(OS, 4);
14198 }
14199 }
14200 OS << "\n";
14201 }
14202
14204 auto *PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
14205 if (PBT != BTC) {
14206 OS << "Loop ";
14207 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14208 OS << ": ";
14209 if (!isa<SCEVCouldNotCompute>(PBT)) {
14210 OS << "Predicated backedge-taken count is ";
14211 PrintSCEVWithTypeHint(OS, PBT);
14212 } else
14213 OS << "Unpredictable predicated backedge-taken count.";
14214 OS << "\n";
14215 OS << " Predicates:\n";
14216 for (const auto *P : Preds)
14217 P->print(OS, 4);
14218 }
14219 Preds.clear();
14220
14221 auto *PredConstantMax =
14223 if (PredConstantMax != ConstantBTC) {
14224 OS << "Loop ";
14225 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14226 OS << ": ";
14227 if (!isa<SCEVCouldNotCompute>(PredConstantMax)) {
14228 OS << "Predicated constant max backedge-taken count is ";
14229 PrintSCEVWithTypeHint(OS, PredConstantMax);
14230 } else
14231 OS << "Unpredictable predicated constant max backedge-taken count.";
14232 OS << "\n";
14233 OS << " Predicates:\n";
14234 for (const auto *P : Preds)
14235 P->print(OS, 4);
14236 }
14237 Preds.clear();
14238
14239 auto *PredSymbolicMax =
14241 if (SymbolicBTC != PredSymbolicMax) {
14242 OS << "Loop ";
14243 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14244 OS << ": ";
14245 if (!isa<SCEVCouldNotCompute>(PredSymbolicMax)) {
14246 OS << "Predicated symbolic max backedge-taken count is ";
14247 PrintSCEVWithTypeHint(OS, PredSymbolicMax);
14248 } else
14249 OS << "Unpredictable predicated symbolic max backedge-taken count.";
14250 OS << "\n";
14251 OS << " Predicates:\n";
14252 for (const auto *P : Preds)
14253 P->print(OS, 4);
14254 }
14255
14257 OS << "Loop ";
14258 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14259 OS << ": ";
14260 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
14261 }
14262}
14263
14264namespace llvm {
14265// Note: these overloaded operators need to be in the llvm namespace for them
14266// to be resolved correctly. If we put them outside the llvm namespace, the
14267//
14268// OS << ": " << SE.getLoopDisposition(SV, InnerL);
14269//
14270// code below "breaks" and start printing raw enum values as opposed to the
14271// string values.
14274 switch (LD) {
14276 OS << "Variant";
14277 break;
14279 OS << "Invariant";
14280 break;
14282 OS << "Uniform";
14283 break;
14285 OS << "Computable";
14286 break;
14287 }
14288 return OS;
14289}
14290
14293 switch (BD) {
14295 OS << "DoesNotDominate";
14296 break;
14298 OS << "Dominates";
14299 break;
14301 OS << "ProperlyDominates";
14302 break;
14303 }
14304 return OS;
14305}
14306} // namespace llvm
14307
14309 // ScalarEvolution's implementation of the print method is to print
14310 // out SCEV values of all instructions that are interesting. Doing
14311 // this potentially causes it to create new SCEV objects though,
14312 // which technically conflicts with the const qualifier. This isn't
14313 // observable from outside the class though, so casting away the
14314 // const isn't dangerous.
14315 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14316
14317 if (Opts.scalar_evolution_classify_expressions) {
14318 OS << "Classifying expressions for: ";
14319 F.printAsOperand(OS, /*PrintType=*/false);
14320 OS << "\n";
14321 for (Instruction &I : instructions(F))
14322 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
14323 OS << I << '\n';
14324 OS << " --> ";
14325 const SCEV *SV = SE.getSCEV(&I);
14326 SV->print(OS);
14327 if (!isa<SCEVCouldNotCompute>(SV)) {
14328 OS << " U: ";
14329 SE.getUnsignedRange(SV).print(OS);
14330 OS << " S: ";
14331 SE.getSignedRange(SV).print(OS);
14332 }
14333
14334 const Loop *L = LI.getLoopFor(I.getParent());
14335
14336 SCEVUse AtUse = SE.getSCEVAtScope(SV, L);
14337 if (AtUse != SV) {
14338 OS << " --> ";
14339 OS << AtUse;
14340 if (!isa<SCEVCouldNotCompute>(AtUse)) {
14341 OS << " U: ";
14342 SE.getUnsignedRange(AtUse).print(OS);
14343 OS << " S: ";
14344 SE.getSignedRange(AtUse).print(OS);
14345 }
14346 }
14347
14348 if (L) {
14349 OS << "\t\t" "Exits: ";
14350 SCEVUse ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
14351 if (!SE.isLoopInvariant(ExitValue, L)) {
14352 OS << "<<Unknown>>";
14353 } else {
14354 OS << ExitValue;
14355 }
14356
14357 ListSeparator LS(", ", "\t\tLoopDispositions: { ");
14358 for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
14359 OS << LS;
14360 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14361 OS << ": " << SE.getLoopDisposition(SV, Iter);
14362 }
14363
14364 for (const auto *InnerL : depth_first(L)) {
14365 if (InnerL == L)
14366 continue;
14367 OS << LS;
14368 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14369 OS << ": " << SE.getLoopDisposition(SV, InnerL);
14370 }
14371
14372 OS << " }";
14373 }
14374
14375 OS << "\n";
14376 }
14377 }
14378
14379 OS << "Determining loop execution counts for: ";
14380 F.printAsOperand(OS, /*PrintType=*/false);
14381 OS << "\n";
14382 for (Loop *I : LI)
14383 PrintLoopInfo(OS, &SE, I);
14384}
14385
14388 if (isa<SCEVConstant>(S))
14389 return LoopInvariant;
14390
14391 auto &Values = LoopDispositions[S];
14392 for (auto &V : Values) {
14393 if (V.getPointer() == L)
14394 return V.getInt();
14395 }
14396 Values.emplace_back(L, LoopVariant);
14397 LoopDisposition D = computeLoopDisposition(S, L);
14398 auto &Values2 = LoopDispositions[S];
14399 for (auto &V : llvm::reverse(Values2)) {
14400 if (V.getPointer() == L) {
14401 V.setInt(D);
14402 break;
14403 }
14404 }
14405 return D;
14406}
14407
14409ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
14410 switch (S->getSCEVType()) {
14411 case scConstant:
14412 case scVScale:
14413 return LoopInvariant;
14414 case scAddRecExpr: {
14415 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14416
14417 // If L is the addrec's loop, it's computable.
14418 if (AR->getLoop() == L)
14419 return LoopComputable;
14420
14421 // Add recurrences are never invariant in the function-body (null loop).
14422 if (!L)
14423 return LoopVariant;
14424
14425 // Everything that is not defined at loop entry is variant.
14426 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) {
14427 if (L->contains(AR->getLoop()) &&
14428 llvm::all_of(AR->operands(),
14429 [&](const SCEV *Op) { return isLoopUniform(Op, L); }))
14430 return LoopUniform;
14431
14432 return LoopVariant;
14433 }
14434 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
14435 " dominate the contained loop's header?");
14436
14437 // This recurrence is invariant w.r.t. L if AR's loop contains L.
14438 if (AR->getLoop()->contains(L))
14439 return LoopInvariant;
14440
14441 // This recurrence is variant w.r.t. L if any of its operands
14442 // are variant.
14443 for (SCEVUse Op : AR->operands())
14444 if (!isLoopInvariant(Op, L))
14445 return LoopVariant;
14446
14447 // Otherwise it's loop-invariant.
14448 return LoopInvariant;
14449 }
14450 case scTruncate:
14451 case scZeroExtend:
14452 case scSignExtend:
14453 case scPtrToAddr:
14454 case scAddExpr:
14455 case scMulExpr:
14456 case scUDivExpr:
14457 case scUMaxExpr:
14458 case scSMaxExpr:
14459 case scUMinExpr:
14460 case scSMinExpr:
14461 case scSequentialUMinExpr: {
14462 bool HasVarying = false;
14463 bool HasUniform = false;
14464 for (SCEVUse Op : S->operands()) {
14466 if (D == LoopVariant)
14467 return LoopVariant;
14468 if (D == LoopComputable)
14469 HasVarying = true;
14470 if (D == LoopUniform)
14471 HasUniform = true;
14472 }
14473 return HasVarying ? (HasUniform ? LoopVariant : LoopComputable)
14474 : (HasUniform ? LoopUniform : LoopInvariant);
14475 }
14476 case scUnknown:
14477 // All non-instruction values are loop invariant. All instructions are loop
14478 // invariant if they are not contained in the specified loop.
14479 // Instructions are never considered invariant in the function body
14480 // (null loop) because they are defined within the "loop".
14482 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
14483 return LoopInvariant;
14484 case scCouldNotCompute:
14485 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14486 }
14487 llvm_unreachable("Unknown SCEV kind!");
14488}
14489
14490bool ScalarEvolution::isLoopUniform(const SCEV *S, const Loop *L) {
14492 return D == LoopUniform || D == LoopInvariant;
14493}
14494
14496 return getLoopDisposition(S, L) == LoopInvariant;
14497}
14498
14500 return getLoopDisposition(S, L) == LoopComputable;
14501}
14502
14505 if (isa<SCEVConstant>(S))
14507
14508 auto &Values = BlockDispositions[S];
14509 for (auto &V : Values) {
14510 if (V.getPointer() == BB)
14511 return V.getInt();
14512 }
14513 Values.emplace_back(BB, DoesNotDominateBlock);
14514 BlockDisposition D = computeBlockDisposition(S, BB);
14515 auto &Values2 = BlockDispositions[S];
14516 for (auto &V : llvm::reverse(Values2)) {
14517 if (V.getPointer() == BB) {
14518 V.setInt(D);
14519 break;
14520 }
14521 }
14522 return D;
14523}
14524
14526ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
14527 switch (S->getSCEVType()) {
14528 case scConstant:
14529 case scVScale:
14531 case scAddRecExpr: {
14532 // This uses a "dominates" query instead of "properly dominates" query
14533 // to test for proper dominance too, because the instruction which
14534 // produces the addrec's value is a PHI, and a PHI effectively properly
14535 // dominates its entire containing block.
14536 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14537 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
14538 return DoesNotDominateBlock;
14539
14540 // Fall through into SCEVNAryExpr handling.
14541 [[fallthrough]];
14542 }
14543 case scTruncate:
14544 case scZeroExtend:
14545 case scSignExtend:
14546 case scPtrToAddr:
14547 case scAddExpr:
14548 case scMulExpr:
14549 case scUDivExpr:
14550 case scUMaxExpr:
14551 case scSMaxExpr:
14552 case scUMinExpr:
14553 case scSMinExpr:
14554 case scSequentialUMinExpr: {
14555 bool Proper = true;
14556 for (const SCEV *NAryOp : S->operands()) {
14558 if (D == DoesNotDominateBlock)
14559 return DoesNotDominateBlock;
14560 if (D == DominatesBlock)
14561 Proper = false;
14562 }
14563 return Proper ? ProperlyDominatesBlock : DominatesBlock;
14564 }
14565 case scUnknown:
14566 if (Instruction *I =
14568 if (I->getParent() == BB)
14569 return DominatesBlock;
14570 if (DT.properlyDominates(I->getParent(), BB))
14572 return DoesNotDominateBlock;
14573 }
14575 case scCouldNotCompute:
14576 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14577 }
14578 llvm_unreachable("Unknown SCEV kind!");
14579}
14580
14581bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
14582 return getBlockDisposition(S, BB) >= DominatesBlock;
14583}
14584
14587}
14588
14589void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
14590 bool Predicated) {
14591 auto &BECounts =
14592 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14593 auto It = BECounts.find(L);
14594 if (It != BECounts.end()) {
14595 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
14596 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14597 if (!isa<SCEVConstant>(S)) {
14598 auto UserIt = BECountUsers.find(S);
14599 assert(UserIt != BECountUsers.end());
14600 UserIt->second.erase({L, Predicated});
14601 }
14602 }
14603 }
14604 BECounts.erase(It);
14605 }
14606}
14607
14608void ScalarEvolution::forgetMemoizedResults(ArrayRef<SCEVUse> SCEVs) {
14609 SmallPtrSet<const SCEV *, 8> ToForget(llvm::from_range, SCEVs);
14610 SmallVector<SCEVUse, 8> Worklist(ToForget.begin(), ToForget.end());
14611
14612 while (!Worklist.empty()) {
14613 const SCEV *Curr = Worklist.pop_back_val();
14614 auto Users = SCEVUsers.find(Curr);
14615 if (Users != SCEVUsers.end())
14616 for (const auto *User : Users->second)
14617 if (ToForget.insert(User).second)
14618 Worklist.push_back(User);
14619 }
14620
14621 for (const auto *S : ToForget)
14622 forgetMemoizedResultsImpl(S);
14623
14624 PredicatedSCEVRewrites.remove_if(
14625 [&](const auto &Entry) { return ToForget.count(Entry.first.first); });
14626}
14627
14628void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
14629 LoopDispositions.erase(S);
14630 BlockDispositions.erase(S);
14631 UnsignedRanges.erase(S);
14632 SignedRanges.erase(S);
14633 HasRecMap.erase(S);
14634 ConstantMultipleCache.erase(S);
14635
14636 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
14637 UnsignedWrapViaInductionTried.erase(AR);
14638 SignedWrapViaInductionTried.erase(AR);
14639 }
14640
14641 auto ExprIt = ExprValueMap.find(S);
14642 if (ExprIt != ExprValueMap.end()) {
14643 for (Value *V : ExprIt->second) {
14644 auto ValueIt = ValueExprMap.find_as(V);
14645 if (ValueIt != ValueExprMap.end())
14646 ValueExprMap.erase(ValueIt);
14647 }
14648 ExprValueMap.erase(ExprIt);
14649 }
14650
14651 auto ScopeIt = ValuesAtScopes.find(S);
14652 if (ScopeIt != ValuesAtScopes.end()) {
14653 for (const auto &Pair : ScopeIt->second)
14654 if (!isa_and_nonnull<SCEVConstant>(Pair.second))
14655 llvm::erase(ValuesAtScopesUsers[Pair.second.getPointer()],
14656 std::make_pair(Pair.first, S));
14657 ValuesAtScopes.erase(ScopeIt);
14658 }
14659
14660 auto ScopeUserIt = ValuesAtScopesUsers.find(S);
14661 if (ScopeUserIt != ValuesAtScopesUsers.end()) {
14662 for (const auto &Pair : ScopeUserIt->second)
14663 // The recorded value at scope is a use of S, which may carry no-wrap
14664 // flags that are not part of this key.
14665 llvm::erase_if(ValuesAtScopes[Pair.second], [&](const auto &LS) {
14666 return LS.first == Pair.first && LS.second.getPointer() == S;
14667 });
14668 ValuesAtScopesUsers.erase(ScopeUserIt);
14669 }
14670
14671 auto BEUsersIt = BECountUsers.find(S);
14672 if (BEUsersIt != BECountUsers.end()) {
14673 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
14674 auto Copy = BEUsersIt->second;
14675 for (const auto &Pair : Copy)
14676 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
14677 BECountUsers.erase(BEUsersIt);
14678 }
14679
14680 auto FoldUser = FoldCacheUser.find(S);
14681 if (FoldUser != FoldCacheUser.end()) {
14682 for (auto &KV : FoldUser->second)
14683 FoldCache.erase(KV);
14684 FoldCacheUser.erase(FoldUser);
14685 }
14686}
14687
14688void
14689ScalarEvolution::getUsedLoops(const SCEV *S,
14690 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
14691 struct FindUsedLoops {
14692 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
14693 : LoopsUsed(LoopsUsed) {}
14694 SmallPtrSetImpl<const Loop *> &LoopsUsed;
14695 bool follow(const SCEV *S) {
14696 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
14697 LoopsUsed.insert(AR->getLoop());
14698 return true;
14699 }
14700
14701 bool isDone() const { return false; }
14702 };
14703
14704 FindUsedLoops F(LoopsUsed);
14705 SCEVTraversal<FindUsedLoops>(F).visitAll(S);
14706}
14707
14708void ScalarEvolution::getReachableBlocks(
14711 Worklist.push_back(&F.getEntryBlock());
14712 while (!Worklist.empty()) {
14713 BasicBlock *BB = Worklist.pop_back_val();
14714 if (!Reachable.insert(BB).second)
14715 continue;
14716
14717 Value *Cond;
14718 BasicBlock *TrueBB, *FalseBB;
14719 if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
14720 m_BasicBlock(FalseBB)))) {
14721 if (auto *C = dyn_cast<ConstantInt>(Cond)) {
14722 Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
14723 continue;
14724 }
14725
14726 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14727 const SCEV *L = getSCEV(Cmp->getOperand(0));
14728 const SCEV *R = getSCEV(Cmp->getOperand(1));
14729 if (isKnownPredicateViaConstantRanges(Cmp->getCmpPredicate(), L, R)) {
14730 Worklist.push_back(TrueBB);
14731 continue;
14732 }
14733 if (isKnownPredicateViaConstantRanges(Cmp->getInverseCmpPredicate(), L,
14734 R)) {
14735 Worklist.push_back(FalseBB);
14736 continue;
14737 }
14738 }
14739 }
14740
14741 append_range(Worklist, successors(BB));
14742 }
14743}
14744
14746 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14747 ScalarEvolution SE2(F, TLI, AC, DT, LI);
14748
14749 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
14750
14751 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
14752 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
14753 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
14754
14755 const SCEV *visitConstant(const SCEVConstant *Constant) {
14756 return SE.getConstant(Constant->getAPInt());
14757 }
14758
14759 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14760 return SE.getUnknown(Expr->getValue());
14761 }
14762
14763 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
14764 return SE.getCouldNotCompute();
14765 }
14766 };
14767
14768 SCEVMapper SCM(SE2);
14769 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
14770 SE2.getReachableBlocks(ReachableBlocks, F);
14771
14772 auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
14773 if (containsUndefs(Old) || containsUndefs(New)) {
14774 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
14775 // not propagate undef aggressively). This means we can (and do) fail
14776 // verification in cases where a transform makes a value go from "undef"
14777 // to "undef+1" (say). The transform is fine, since in both cases the
14778 // result is "undef", but SCEV thinks the value increased by 1.
14779 return nullptr;
14780 }
14781
14782 // Unless -verify-scev-strict is set, we only compare constant deltas.
14783 const SCEV *Delta = SE2.getMinusSCEV(Old, New);
14784 if (!Opts.verify_scev_strict && !isa<SCEVConstant>(Delta))
14785 return nullptr;
14786
14787 return Delta;
14788 };
14789
14790 while (!LoopStack.empty()) {
14791 auto *L = LoopStack.pop_back_val();
14792 llvm::append_range(LoopStack, *L);
14793
14794 // Only verify BECounts in reachable loops. For an unreachable loop,
14795 // any BECount is legal.
14796 if (!ReachableBlocks.contains(L->getHeader()))
14797 continue;
14798
14799 // Only verify cached BECounts. Computing new BECounts may change the
14800 // results of subsequent SCEV uses.
14801 auto It = BackedgeTakenCounts.find(L);
14802 if (It == BackedgeTakenCounts.end())
14803 continue;
14804
14805 SCEVUse CurBECount =
14806 SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
14807 auto *NewBECount = SE2.getBackedgeTakenCount(L);
14808
14809 if (CurBECount == SE2.getCouldNotCompute() ||
14810 NewBECount == SE2.getCouldNotCompute()) {
14811 // NB! This situation is legal, but is very suspicious -- whatever pass
14812 // change the loop to make a trip count go from could not compute to
14813 // computable or vice-versa *should have* invalidated SCEV. However, we
14814 // choose not to assert here (for now) since we don't want false
14815 // positives.
14816 continue;
14817 }
14818
14819 if (SE.getTypeSizeInBits(CurBECount->getType()) >
14820 SE.getTypeSizeInBits(NewBECount->getType()))
14821 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
14822 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
14823 SE.getTypeSizeInBits(NewBECount->getType()))
14824 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
14825
14826 const SCEV *Delta = GetDelta(CurBECount, NewBECount);
14827 if (Delta && !Delta->isZero()) {
14828 dbgs() << "Trip Count for " << *L << " Changed!\n";
14829 dbgs() << "Old: " << *CurBECount << "\n";
14830 dbgs() << "New: " << *NewBECount << "\n";
14831 dbgs() << "Delta: " << *Delta << "\n";
14832 std::abort();
14833 }
14834 }
14835
14836 // Collect all valid loops currently in LoopInfo.
14837 SmallPtrSet<Loop *, 32> ValidLoops;
14838 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
14839 while (!Worklist.empty()) {
14840 Loop *L = Worklist.pop_back_val();
14841 if (ValidLoops.insert(L).second)
14842 Worklist.append(L->begin(), L->end());
14843 }
14844 for (const auto &KV : ValueExprMap) {
14845#ifndef NDEBUG
14846 // Check for SCEV expressions referencing invalid/deleted loops.
14847 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14848 assert(ValidLoops.contains(AR->getLoop()) &&
14849 "AddRec references invalid loop");
14850 }
14851#endif
14852
14853 // Check that the value is also part of the reverse map.
14854 auto It = ExprValueMap.find(KV.second);
14855 if (It == ExprValueMap.end() || !is_contained(It->second, KV.first)) {
14856 dbgs() << "Value " << *KV.first
14857 << " is in ValueExprMap but not in ExprValueMap\n";
14858 std::abort();
14859 }
14860
14861 if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
14862 if (!ReachableBlocks.contains(I->getParent()))
14863 continue;
14864 const SCEV *OldSCEV = SCM.visit(KV.second);
14865 const SCEV *NewSCEV = SE2.getSCEV(I);
14866 const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14867 if (Delta && !Delta->isZero()) {
14868 dbgs() << "SCEV for value " << *I << " changed!\n"
14869 << "Old: " << *OldSCEV << "\n"
14870 << "New: " << *NewSCEV << "\n"
14871 << "Delta: " << *Delta << "\n";
14872 std::abort();
14873 }
14874 }
14875 }
14876
14877 for (const auto &KV : ExprValueMap) {
14878 for (Value *V : KV.second) {
14879 const SCEV *S = ValueExprMap.lookup(V);
14880 if (!S) {
14881 dbgs() << "Value " << *V
14882 << " is in ExprValueMap but not in ValueExprMap\n";
14883 std::abort();
14884 }
14885 if (S != KV.first) {
14886 dbgs() << "Value " << *V << " mapped to " << *S << " rather than "
14887 << *KV.first << "\n";
14888 std::abort();
14889 }
14890 }
14891 }
14892
14893 // Verify integrity of SCEV users.
14894 for (const auto &S : UniqueSCEVs) {
14895 for (SCEVUse Op : S.operands()) {
14896 // We do not store dependencies of constants.
14897 if (isa<SCEVConstant>(Op))
14898 continue;
14899 auto It = SCEVUsers.find(Op);
14900 if (It != SCEVUsers.end() && It->second.count(&S))
14901 continue;
14902 dbgs() << "Use of operand " << *Op << " by user " << S
14903 << " is not being tracked!\n";
14904 std::abort();
14905 }
14906 }
14907
14908 // Verify integrity of ValuesAtScopes users.
14909 for (const auto &ValueAndVec : ValuesAtScopes) {
14910 const SCEV *Value = ValueAndVec.first;
14911 for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
14912 const Loop *L = LoopAndValueAtScope.first;
14913 SCEVUse ValueAtScope = LoopAndValueAtScope.second;
14914 if (!isa<SCEVConstant>(ValueAtScope)) {
14915 auto It = ValuesAtScopesUsers.find(ValueAtScope.getPointer());
14916 if (It != ValuesAtScopesUsers.end() &&
14917 is_contained(It->second, std::make_pair(L, Value)))
14918 continue;
14919 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14920 << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
14921 std::abort();
14922 }
14923 }
14924 }
14925
14926 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
14927 const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
14928 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
14929 const Loop *L = LoopAndValue.first;
14930 const SCEV *Value = LoopAndValue.second;
14932 auto It = ValuesAtScopes.find(Value);
14933 // The recorded value at scope may carry no-wrap flags that are not part
14934 // of the key it is recorded under.
14935 if (It != ValuesAtScopes.end() && any_of(It->second, [&](const auto &LS) {
14936 return LS.first == L && LS.second.getPointer() == ValueAtScope;
14937 }))
14938 continue;
14939 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14940 << *ValueAtScope << " missing in ValuesAtScopes\n";
14941 std::abort();
14942 }
14943 }
14944
14945 // Verify integrity of BECountUsers.
14946 auto VerifyBECountUsers = [&](bool Predicated) {
14947 auto &BECounts =
14948 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14949 for (const auto &LoopAndBEInfo : BECounts) {
14950 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
14951 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14952 if (!isa<SCEVConstant>(S)) {
14953 auto UserIt = BECountUsers.find(S);
14954 if (UserIt != BECountUsers.end() &&
14955 UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
14956 continue;
14957 dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
14958 << " missing from BECountUsers\n";
14959 std::abort();
14960 }
14961 }
14962 }
14963 }
14964 };
14965 VerifyBECountUsers(/* Predicated */ false);
14966 VerifyBECountUsers(/* Predicated */ true);
14967
14968 // Verify intergity of loop disposition cache.
14969 for (auto &[S, Values] : LoopDispositions) {
14970 for (auto [Loop, CachedDisposition] : Values) {
14971 const auto RecomputedDisposition = SE2.getLoopDisposition(S, Loop);
14972 if (CachedDisposition != RecomputedDisposition) {
14973 dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
14974 << " is incorrect: cached " << CachedDisposition << ", actual "
14975 << RecomputedDisposition << "\n";
14976 std::abort();
14977 }
14978 }
14979 }
14980
14981 // Verify integrity of the block disposition cache.
14982 for (auto &[S, Values] : BlockDispositions) {
14983 for (auto [BB, CachedDisposition] : Values) {
14984 const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
14985 if (CachedDisposition != RecomputedDisposition) {
14986 dbgs() << "Cached disposition of " << *S << " for block %"
14987 << BB->getName() << " is incorrect: cached " << CachedDisposition
14988 << ", actual " << RecomputedDisposition << "\n";
14989 std::abort();
14990 }
14991 }
14992 }
14993
14994 // Verify FoldCache/FoldCacheUser caches.
14995 for (auto [FoldID, Expr] : FoldCache) {
14996 auto I = FoldCacheUser.find(Expr);
14997 if (I == FoldCacheUser.end()) {
14998 dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
14999 << "!\n";
15000 std::abort();
15001 }
15002 if (!is_contained(I->second, FoldID)) {
15003 dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
15004 std::abort();
15005 }
15006 }
15007 for (auto [Expr, IDs] : FoldCacheUser) {
15008 for (auto &FoldID : IDs) {
15009 const SCEV *S = FoldCache.lookup(FoldID);
15010 if (!S) {
15011 dbgs() << "Missing entry in FoldCache for expression " << *Expr
15012 << "!\n";
15013 std::abort();
15014 }
15015 if (S != Expr) {
15016 dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: " << *S
15017 << " != " << *Expr << "!\n";
15018 std::abort();
15019 }
15020 }
15021 }
15022
15023 // Verify that ConstantMultipleCache computations are correct. We check that
15024 // cached multiples and recomputed multiples are multiples of each other to
15025 // verify correctness. It is possible that a recomputed multiple is different
15026 // from the cached multiple due to strengthened no wrap flags or changes in
15027 // KnownBits computations.
15028 for (auto [S, Multiple] : ConstantMultipleCache) {
15029 APInt RecomputedMultiple = SE2.getConstantMultiple(S);
15030 if ((Multiple != 0 && RecomputedMultiple != 0 &&
15031 Multiple.urem(RecomputedMultiple) != 0 &&
15032 RecomputedMultiple.urem(Multiple) != 0)) {
15033 dbgs() << "Incorrect cached computation in ConstantMultipleCache for "
15034 << *S << " : Computed " << RecomputedMultiple
15035 << " but cache contains " << Multiple << "!\n";
15036 std::abort();
15037 }
15038 }
15039}
15040
15042 Function &F, const PreservedAnalyses &PA,
15043 FunctionAnalysisManager::Invalidator &Inv) {
15044 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
15045 // of its dependencies is invalidated.
15046 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
15047 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
15048 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
15049 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
15050 Inv.invalidate<LoopAnalysis>(F, PA);
15051}
15052
15053AnalysisKey ScalarEvolutionAnalysis::Key;
15054
15057 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
15058 auto &AC = AM.getResult<AssumptionAnalysis>(F);
15059 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
15060 auto &LI = AM.getResult<LoopAnalysis>(F);
15061 return ScalarEvolution(F, TLI, AC, DT, LI);
15062}
15063
15069
15072 // For compatibility with opt's -analyze feature under legacy pass manager
15073 // which was not ported to NPM. This keeps tests using
15074 // update_analyze_test_checks.py working.
15075 OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
15076 << F.getName() << "':\n";
15078 return PreservedAnalyses::all();
15079}
15080
15082 "Scalar Evolution Analysis", false, true)
15088 "Scalar Evolution Analysis", false, true)
15089
15090char ScalarEvolutionWrapperPass::ID = 0;
15091
15093
15095 SE.reset(new ScalarEvolution(
15097 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
15099 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
15100 return false;
15101}
15102
15104
15106 SE->print(OS);
15107}
15108
15110 if (!VerifySCEV)
15111 return;
15112
15113 SE->verify();
15114}
15115
15123
15125 const SCEV *RHS) {
15126 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
15127}
15128
15129const SCEVPredicate *
15131 const SCEV *LHS, const SCEV *RHS) {
15133 assert(LHS->getType() == RHS->getType() &&
15134 "Type mismatch between LHS and RHS");
15135 // Unique this node based on the arguments
15136 ID.AddInteger(SCEVPredicate::P_Compare);
15137 ID.AddInteger(Pred);
15138 ID.AddPointer(LHS);
15139 ID.AddPointer(RHS);
15141 if (const auto *S = UniquePreds.lookup(ID, Token))
15142 return S;
15143 SCEVComparePredicate *Eq = new (SCEVAllocator)
15144 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
15145 UniquePreds.insert(Eq, Token);
15146 return Eq;
15147}
15148
15150 const SCEVAddRecExpr *AR,
15153 // Unique this node based on the arguments
15155 ID.AddPointer(AR);
15156 ID.AddInteger(AddedFlags);
15158 if (const auto *S = UniquePreds.lookup(ID, Token))
15159 return S;
15160 auto *OF = new (SCEVAllocator)
15161 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
15162 UniquePreds.insert(OF, Token);
15163 return OF;
15164}
15165
15166namespace {
15167
15168class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
15169public:
15170
15171 /// Rewrites \p S in the context of a loop L and the SCEV predication
15172 /// infrastructure.
15173 ///
15174 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
15175 /// equivalences present in \p Pred.
15176 ///
15177 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
15178 /// \p NewPreds such that the result will be an AddRecExpr.
15179 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
15181 const SCEVPredicate *Pred) {
15182 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
15183 return Rewriter.visit(S);
15184 }
15185
15186 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
15187 if (Pred) {
15188 if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
15189 for (const auto *Pred : U->getPredicates())
15190 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
15191 if (IPred->getLHS() == Expr &&
15192 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15193 return IPred->getRHS();
15194 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
15195 if (IPred->getLHS() == Expr &&
15196 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15197 return IPred->getRHS();
15198 }
15199 }
15200 return convertToAddRecWithPreds(Expr);
15201 }
15202
15203 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
15204 const SCEV *Operand = visit(Expr->getOperand());
15205 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15206 if (AR && AR->getLoop() == L && AR->isAffine()) {
15207 // This couldn't be folded because the operand didn't have the nuw
15208 // flag. Add the nusw flag as an assumption that we could make.
15209 const SCEV *Step = AR->getStepRecurrence(SE);
15210 Type *Ty = Expr->getType();
15211 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
15212 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
15213 SE.getSignExtendExpr(Step, Ty), L,
15214 AR->getNoWrapFlags());
15215 }
15216 return SE.getZeroExtendExpr(Operand, Expr->getType());
15217 }
15218
15219 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
15220 const SCEV *Operand = visit(Expr->getOperand());
15221 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15222 if (AR && AR->getLoop() == L && AR->isAffine()) {
15223 // This couldn't be folded because the operand didn't have the nsw
15224 // flag. Add the nssw flag as an assumption that we could make.
15225 const SCEV *Step = AR->getStepRecurrence(SE);
15226 Type *Ty = Expr->getType();
15227 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
15228 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
15229 SE.getSignExtendExpr(Step, Ty), L,
15230 AR->getNoWrapFlags());
15231 }
15232 return SE.getSignExtendExpr(Operand, Expr->getType());
15233 }
15234
15235private:
15236 explicit SCEVPredicateRewriter(
15237 const Loop *L, ScalarEvolution &SE,
15238 SmallVectorImpl<const SCEVPredicate *> *NewPreds,
15239 const SCEVPredicate *Pred)
15240 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
15241
15242 bool addOverflowAssumption(const SCEVPredicate *P) {
15243 if (!NewPreds) {
15244 // Check if we've already made this assumption.
15245 return Pred && Pred->implies(P, SE);
15246 }
15247 NewPreds->push_back(P);
15248 return true;
15249 }
15250
15251 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
15253 auto *A = SE.getWrapPredicate(AR, AddedFlags);
15254 return addOverflowAssumption(A);
15255 }
15256
15257 // If \p Expr represents a PHINode, we try to see if it can be represented
15258 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
15259 // to add this predicate as a runtime overflow check, we return the AddRec.
15260 // If \p Expr does not meet these conditions (is not a PHI node, or we
15261 // couldn't create an AddRec for it, or couldn't add the predicate), we just
15262 // return \p Expr.
15263 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
15264 if (!isa<PHINode>(Expr->getValue()))
15265 return Expr;
15266 std::optional<
15267 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
15268 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
15269 if (!PredicatedRewrite)
15270 return Expr;
15271 for (const auto *P : PredicatedRewrite->second){
15272 // Wrap predicates from outer loops are not supported.
15273 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
15274 if (L != WP->getExpr()->getLoop())
15275 return Expr;
15276 }
15277 if (!addOverflowAssumption(P))
15278 return Expr;
15279 }
15280 return PredicatedRewrite->first;
15281 }
15282
15283 SmallVectorImpl<const SCEVPredicate *> *NewPreds;
15284 const SCEVPredicate *Pred;
15285 const Loop *L;
15286};
15287
15288} // end anonymous namespace
15289
15290const SCEV *
15292 const SCEVPredicate &Preds) {
15293 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
15294}
15295
15297 const SCEV *S, const Loop *L,
15300 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
15301 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
15302
15303 if (!AddRec)
15304 return nullptr;
15305
15306 // Check if any of the transformed predicates is known to be false. In that
15307 // case, it doesn't make sense to convert to a predicated AddRec, as the
15308 // versioned loop will never execute.
15309 for (const SCEVPredicate *Pred : TransformPreds) {
15310 auto *WrapPred = dyn_cast<SCEVWrapPredicate>(Pred);
15311 if (!WrapPred || WrapPred->getFlags() != SCEVWrapPredicate::IncrementNSSW)
15312 continue;
15313
15314 const SCEVAddRecExpr *AddRecToCheck = WrapPred->getExpr();
15315 const SCEV *ExitCount = getBackedgeTakenCount(AddRecToCheck->getLoop());
15316 if (isa<SCEVCouldNotCompute>(ExitCount))
15317 continue;
15318
15319 const SCEV *Step = AddRecToCheck->getStepRecurrence(*this);
15320 if (!Step->isOne())
15321 continue;
15322
15323 ExitCount = getTruncateOrSignExtend(ExitCount, Step->getType());
15324 const SCEV *Add = getAddExpr(AddRecToCheck->getStart(), ExitCount);
15325 if (isKnownPredicate(CmpInst::ICMP_SLT, Add, AddRecToCheck->getStart()))
15326 return nullptr;
15327 }
15328
15329 // Since the transformation was successful, we can now transfer the SCEV
15330 // predicates.
15331 Preds.append(TransformPreds.begin(), TransformPreds.end());
15332
15333 return AddRec;
15334}
15335
15336/// SCEV predicates
15340
15342 const ICmpInst::Predicate Pred,
15343 const SCEV *LHS, const SCEV *RHS)
15344 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
15345 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
15346 assert(LHS != RHS && "LHS and RHS are the same SCEV");
15347}
15348
15350 ScalarEvolution &SE) const {
15351 const auto *Op = dyn_cast<SCEVComparePredicate>(N);
15352
15353 if (!Op)
15354 return false;
15355
15356 if (Op->LHS != LHS || Op->RHS != RHS)
15357 return false;
15358
15359 return ICmpInst::isImpliedByMatchingCmp(Pred, Op->Pred) == true;
15360}
15361
15362bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
15363
15365 if (Pred == ICmpInst::ICMP_EQ)
15366 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
15367 else
15368 OS.indent(Depth) << "Compare predicate: " << *LHS << " " << Pred << ") "
15369 << *RHS << "\n";
15370
15371}
15372
15374 const SCEVAddRecExpr *AR,
15375 IncrementWrapFlags Flags)
15376 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
15377
15378const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
15379
15381 ScalarEvolution &SE) const {
15382 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
15383 if (!Op || setFlags(Flags, Op->Flags) != Flags)
15384 return false;
15385
15386 if (Op->AR == AR)
15387 return true;
15388
15389 if (Flags != SCEVWrapPredicate::IncrementNSSW &&
15391 return false;
15392
15393 const SCEV *Start = AR->getStart();
15394 const SCEV *OpStart = Op->AR->getStart();
15395 if (Start->getType()->isPointerTy() != OpStart->getType()->isPointerTy())
15396 return false;
15397
15398 // Reject pointers to different address spaces.
15399 if (Start->getType()->isPointerTy() && Start->getType() != OpStart->getType())
15400 return false;
15401
15402 // NUSW/NSSW on a wider-type AddRec does not imply the same on a
15403 // narrower-type AddRec.
15404 if (SE.getTypeSizeInBits(AR->getType()) >
15405 SE.getTypeSizeInBits(Op->AR->getType()))
15406 return false;
15407
15408 const SCEV *Step = AR->getStepRecurrence(SE);
15409 const SCEV *OpStep = Op->AR->getStepRecurrence(SE);
15410 if (!SE.isKnownPositive(Step) || !SE.isKnownPositive(OpStep))
15411 return false;
15412
15413 // If both steps are positive, this implies N, if N's start and step are
15414 // ULE/SLE (for NSUW/NSSW) than this'.
15415 Type *WiderTy = SE.getWiderType(Step->getType(), OpStep->getType());
15416 Step = SE.getNoopOrZeroExtend(Step, WiderTy);
15417 OpStep = SE.getNoopOrZeroExtend(OpStep, WiderTy);
15418
15419 bool IsNUW = Flags == SCEVWrapPredicate::IncrementNUSW;
15420 OpStart = IsNUW ? SE.getNoopOrZeroExtend(OpStart, WiderTy)
15421 : SE.getNoopOrSignExtend(OpStart, WiderTy);
15422 Start = IsNUW ? SE.getNoopOrZeroExtend(Start, WiderTy)
15423 : SE.getNoopOrSignExtend(Start, WiderTy);
15425 return SE.isKnownPredicate(Pred, OpStep, Step) &&
15426 SE.isKnownPredicate(Pred, OpStart, Start);
15427}
15428
15430 SCEVFlags ScevFlags = AR->getNoWrapFlags();
15431 IncrementWrapFlags IFlags = Flags;
15432
15433 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
15434 IFlags = clearFlags(IFlags, IncrementNSSW);
15435
15436 return IFlags == IncrementAnyWrap;
15437}
15438
15439void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
15440 OS.indent(Depth) << *getExpr() << " Added Flags: ";
15442 OS << "<nusw>";
15444 OS << "<nssw>";
15445 OS << "\n";
15446}
15447
15448/// Union predicates don't get cached so create a dummy set ID for it.
15450 ScalarEvolution &SE)
15452 for (const auto *P : Preds)
15453 add(P, SE);
15454}
15455
15457 return all_of(Preds,
15458 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
15459}
15460
15462 ScalarEvolution &SE) const {
15463 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
15464 return all_of(Set->Preds, [this, &SE](const SCEVPredicate *I) {
15465 return this->implies(I, SE);
15466 });
15467
15468 if (is_contained(Preds, N))
15469 return true;
15470
15471 if (any_of(Preds,
15472 [N, &SE](const SCEVPredicate *I) { return I->implies(N, SE); }))
15473 return true;
15474
15475 // A wrap predicate may be implied by a wrap predicate in Preds after applying
15476 // equal predicates.
15477 const auto *NWrap = dyn_cast<SCEVWrapPredicate>(N);
15478 if (!NWrap)
15479 return false;
15480 const Loop *L = NWrap->getExpr()->getLoop();
15481 return any_of(Preds, [&](const SCEVPredicate *I) {
15482 const auto *IWrap = dyn_cast<SCEVWrapPredicate>(I);
15483 if (!IWrap)
15484 return false;
15485 const auto *RewrittenAR = dyn_cast<SCEVAddRecExpr>(
15486 SE.rewriteUsingPredicate(IWrap->getExpr(), L, *this));
15487 return RewrittenAR &&
15488 SE.getWrapPredicate(RewrittenAR, IWrap->getFlags())->implies(N, SE);
15489 });
15490}
15491
15493 for (const auto *Pred : Preds)
15494 Pred->print(OS, Depth);
15495}
15496
15497void SCEVUnionPredicate::add(const SCEVPredicate *N, ScalarEvolution &SE) {
15498 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
15499 for (const auto *Pred : Set->Preds)
15500 add(Pred, SE);
15501 return;
15502 }
15503
15504 // Implication checks are quadratic in the number of predicates. Stop doing
15505 // them if there are many predicates, as they should be too expensive to use
15506 // anyway at that point.
15507 bool CheckImplies = Preds.size() < 16;
15508
15509 // Only add predicate if it is not already implied by this union predicate.
15510 if (CheckImplies && implies(N, SE))
15511 return;
15512
15513 // Build a new vector containing the current predicates, except the ones that
15514 // are implied by the new predicate N.
15516 for (auto *P : Preds) {
15517 if (CheckImplies && N->implies(P, SE))
15518 continue;
15519 PrunedPreds.push_back(P);
15520 }
15521 Preds = std::move(PrunedPreds);
15522 Preds.push_back(N);
15523}
15524
15526 Loop &L)
15527 : SE(SE), L(L) {
15529 Preds = std::make_unique<SCEVUnionPredicate>(Empty, SE);
15530}
15531
15533 for (const SCEV *Op : Ops)
15534 // We do not expect that forgetting cached data for SCEVConstants will ever
15535 // open any prospects for sharpening or introduce any correctness issues,
15536 // so we don't bother storing their dependencies.
15537 if (!isa<SCEVConstant>(Op))
15538 SCEVUsers[Op].insert(User);
15539}
15540
15542 const SCEV *Expr = SE.getSCEV(V);
15543 return getPredicatedSCEV(Expr);
15544}
15545
15547 RewriteEntry &Entry = RewriteMap[Expr];
15548
15549 // If we already have an entry and the version matches, return it.
15550 if (Entry.second && Generation == Entry.first)
15551 return Entry.second;
15552
15553 // We found an entry but it's stale. Rewrite the stale entry
15554 // according to the current predicate.
15555 if (Entry.second)
15556 Expr = Entry.second;
15557
15558 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
15559 Entry = {Generation, NewSCEV};
15560
15561 return NewSCEV;
15562}
15563
15565 if (!BackedgeCount) {
15567 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
15568 for (const auto *P : Preds)
15569 addPredicate(*P);
15570 }
15571 return BackedgeCount;
15572}
15573
15575 if (!SymbolicMaxBackedgeCount) {
15577 SymbolicMaxBackedgeCount =
15578 SE.getPredicatedSymbolicMaxBackedgeTakenCount(&L, Preds);
15579 for (const auto *P : Preds)
15580 addPredicate(*P);
15581 }
15582 return SymbolicMaxBackedgeCount;
15583}
15584
15586 if (!SmallConstantMaxTripCount) {
15588 SmallConstantMaxTripCount = SE.getSmallConstantMaxTripCount(&L, &Preds);
15589 for (const auto *P : Preds)
15590 addPredicate(*P);
15591 }
15592 return *SmallConstantMaxTripCount;
15593}
15594
15596 if (Preds->implies(&Pred, SE))
15597 return;
15598
15599 Preds = std::make_unique<SCEVUnionPredicate>(Preds->getUnionWith(&Pred, SE));
15600 updateGeneration();
15601}
15602
15605 for (const SCEVPredicate *P : Preds)
15606 addPredicate(*P);
15607}
15608
15610 return *Preds;
15611}
15612
15613void PredicatedScalarEvolution::updateGeneration() {
15614 // If the generation number wrapped recompute everything.
15615 if (++Generation == 0) {
15616 for (auto &II : RewriteMap) {
15617 const SCEV *Rewritten = II.second.second;
15618 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
15619 }
15620 }
15621}
15622
15625 const SCEV *Expr = this->getSCEV(V);
15627 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
15628
15629 if (!New)
15630 return nullptr;
15631
15632 if (ExtraPreds) {
15633 ExtraPreds->append(NewPreds);
15634 return New;
15635 }
15636
15637 addPredicates(NewPreds);
15638
15639 RewriteMap[SE.getSCEV(V)] = {Generation, New};
15640 return New;
15641}
15642
15645 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
15646 Preds(std::make_unique<SCEVUnionPredicate>(*Init.Preds)),
15647 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {}
15648
15650 // For each block.
15651 for (auto *BB : L.getBlocks())
15652 for (auto &I : *BB) {
15653 if (!SE.isSCEVable(I.getType()))
15654 continue;
15655
15656 auto *Expr = SE.getSCEV(&I);
15657 auto II = RewriteMap.find(Expr);
15658
15659 if (II == RewriteMap.end())
15660 continue;
15661
15662 // Don't print things that are not interesting.
15663 if (II->second.second == Expr)
15664 continue;
15665
15666 OS.indent(Depth) << "[PSE]" << I << ":\n";
15667 OS.indent(Depth + 2) << *Expr << "\n";
15668 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
15669 }
15670}
15671
15672void ScalarEvolution::LoopGuards::collectPending() {
15673 const Loop *L = PendingLoop;
15674 if (!L)
15675 return;
15676 PendingLoop = nullptr;
15677 BasicBlock *Pred = L->getLoopPredecessor();
15678 if (!Pred)
15679 return;
15681 collectFromBlock(SE, *this, L->getHeader(), Pred, VisitedBlocks);
15682}
15683
15684void ScalarEvolution::LoopGuards::collectFromPHI(
15688 unsigned Depth) {
15689 if (!SE.isSCEVable(Phi.getType()))
15690 return;
15691
15692 using MinMaxPattern = std::pair<const SCEVConstant *, SCEVTypes>;
15693 auto GetMinMaxConst = [&](unsigned IncomingIdx) -> MinMaxPattern {
15694 const BasicBlock *InBlock = Phi.getIncomingBlock(IncomingIdx);
15695 if (!VisitedBlocks.insert(InBlock).second)
15696 return {nullptr, scCouldNotCompute};
15697
15698 // Avoid analyzing unreachable blocks so that we don't get trapped
15699 // traversing cycles with ill-formed dominance or infinite cycles
15700 if (!SE.DT.isReachableFromEntry(InBlock))
15701 return {nullptr, scCouldNotCompute};
15702
15703 auto [G, Inserted] = IncomingGuards.try_emplace(InBlock, LoopGuards(SE));
15704 if (Inserted)
15705 collectFromBlock(SE, G->second, Phi.getParent(), InBlock, VisitedBlocks,
15706 Depth + 1);
15707 auto &RewriteMap = G->second.RewriteMap;
15708 if (RewriteMap.empty())
15709 return {nullptr, scCouldNotCompute};
15710 auto S = RewriteMap.find(SE.getSCEV(Phi.getIncomingValue(IncomingIdx)));
15711 if (S == RewriteMap.end())
15712 return {nullptr, scCouldNotCompute};
15713 auto *SM = dyn_cast_if_present<SCEVMinMaxExpr>(S->second);
15714 if (!SM)
15715 return {nullptr, scCouldNotCompute};
15716 if (const SCEVConstant *C0 = dyn_cast<SCEVConstant>(SM->getOperand(0)))
15717 return {C0, SM->getSCEVType()};
15718 return {nullptr, scCouldNotCompute};
15719 };
15720 auto MergeMinMaxConst = [](MinMaxPattern P1,
15721 MinMaxPattern P2) -> MinMaxPattern {
15722 auto [C1, T1] = P1;
15723 auto [C2, T2] = P2;
15724 if (!C1 || !C2 || T1 != T2)
15725 return {nullptr, scCouldNotCompute};
15726 switch (T1) {
15727 case scUMaxExpr:
15728 return {C1->getAPInt().ult(C2->getAPInt()) ? C1 : C2, T1};
15729 case scSMaxExpr:
15730 return {C1->getAPInt().slt(C2->getAPInt()) ? C1 : C2, T1};
15731 case scUMinExpr:
15732 return {C1->getAPInt().ugt(C2->getAPInt()) ? C1 : C2, T1};
15733 case scSMinExpr:
15734 return {C1->getAPInt().sgt(C2->getAPInt()) ? C1 : C2, T1};
15735 default:
15736 llvm_unreachable("Trying to merge non-MinMaxExpr SCEVs.");
15737 }
15738 };
15739 auto P = GetMinMaxConst(0);
15740 for (unsigned int In = 1; In < Phi.getNumIncomingValues(); In++) {
15741 if (!P.first)
15742 break;
15743 P = MergeMinMaxConst(P, GetMinMaxConst(In));
15744 }
15745 if (P.first) {
15746 const SCEV *LHS = SE.getSCEV(const_cast<PHINode *>(&Phi));
15747 SmallVector<SCEVUse, 2> Ops({P.first, LHS});
15748 const SCEV *RHS = SE.getMinMaxExpr(P.second, Ops);
15749 Guards.RewriteMap.insert({LHS, RHS});
15750 }
15751}
15752
15753// Return a new SCEV that modifies \p Expr to the closest number divides by
15754// \p Divisor and less or equal than Expr. For now, only handle constant
15755// Expr.
15757 const APInt &DivisorVal,
15758 ScalarEvolution &SE) {
15759 const APInt *ExprVal;
15760 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15761 DivisorVal.isNonPositive())
15762 return Expr;
15763 APInt Rem = ExprVal->urem(DivisorVal);
15764 // return the SCEV: Expr - Expr % Divisor
15765 return SE.getConstant(*ExprVal - Rem);
15766}
15767
15768// Return a new SCEV that modifies \p Expr to the closest number divides by
15769// \p Divisor and greater or equal than Expr. For now, only handle constant
15770// Expr.
15771static const SCEV *getNextSCEVDivisibleByDivisor(const SCEV *Expr,
15772 const APInt &DivisorVal,
15773 ScalarEvolution &SE) {
15774 const APInt *ExprVal;
15775 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15776 DivisorVal.isNonPositive())
15777 return Expr;
15778 APInt Rem = ExprVal->urem(DivisorVal);
15779 if (Rem.isZero())
15780 return Expr;
15781 // return the SCEV: Expr + Divisor - Expr % Divisor
15782 return SE.getConstant(*ExprVal + DivisorVal - Rem);
15783}
15784
15786 ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS,
15789 // If we have LHS == 0, check if LHS is computing a property of some unknown
15790 // SCEV %v which we can rewrite %v to express explicitly.
15792 return false;
15793 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
15794 // explicitly express that.
15795 const SCEVUnknown *URemLHS = nullptr;
15796 const SCEV *URemRHS = nullptr;
15797 if (!match(LHS, m_scev_URem(m_SCEVUnknown(URemLHS), m_SCEV(URemRHS), SE)))
15798 return false;
15799
15800 const SCEV *Multiple =
15801 SE.getMulExpr(SE.getUDivExpr(URemLHS, URemRHS), URemRHS);
15802 DivInfo[URemLHS] = Multiple;
15803 if (auto *C = dyn_cast<SCEVConstant>(URemRHS))
15804 Multiples[URemLHS] = C->getAPInt();
15805 return true;
15806}
15807
15808// Check if the condition is a divisibility guard (A % B == 0).
15809static bool isDivisibilityGuard(const SCEV *LHS, const SCEV *RHS,
15810 ScalarEvolution &SE) {
15811 const SCEV *X, *Y;
15812 return match(LHS, m_scev_URem(m_SCEV(X), m_SCEV(Y), SE)) && RHS->isZero();
15813}
15814
15815// Apply divisibility by \p Divisor on MinMaxExpr with constant values,
15816// recursively. This is done by aligning up/down the constant value to the
15817// Divisor.
15818static const SCEV *applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr,
15819 const APInt &Divisor,
15820 ScalarEvolution &SE) {
15821 // Only handle min/max expressions of a non-negative constant and another
15822 // operand.
15823 const SCEVConstant *C;
15824 const SCEV *Op;
15825 if (!match(MinMaxExpr, m_scev_MinMax(m_SCEVConstant(C), m_SCEV(Op))) ||
15826 C->getAPInt().isNegative())
15827 return MinMaxExpr;
15828 auto *DivisibleExpr = isa<SCEVSMinExpr, SCEVUMinExpr>(MinMaxExpr)
15829 ? getPreviousSCEVDivisibleByDivisor(C, Divisor, SE)
15830 : getNextSCEVDivisibleByDivisor(C, Divisor, SE);
15832 DivisibleExpr};
15833 return SE.getMinMaxExpr(MinMaxExpr->getSCEVType(), Ops);
15834}
15835
15836void ScalarEvolution::LoopGuards::collectFromBlock(
15837 ScalarEvolution &SE, ScalarEvolution::LoopGuards &Guards,
15838 const BasicBlock *Block, const BasicBlock *Pred,
15839 SmallPtrSetImpl<const BasicBlock *> &VisitedBlocks, unsigned Depth) {
15840
15842
15843 SmallVector<SCEVUse> ExprsToRewrite;
15844 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
15845 const SCEV *RHS,
15846 DenseMap<const SCEV *, const SCEV *> &RewriteMap,
15847 const LoopGuards &DivGuards) {
15848 // WARNING: It is generally unsound to apply any wrap flags to the proposed
15849 // replacement SCEV which isn't directly implied by the structure of that
15850 // SCEV. In particular, using contextual facts to imply flags is *NOT*
15851 // legal. See the scoping rules for flags in the header to understand why.
15852
15853 // Puts rewrite rule \p From -> \p To into the rewrite map. Also if \p From
15854 // and \p FromRewritten are the same (i.e. there has been no rewrite
15855 // registered for \p From), then puts this value in the list of rewritten
15856 // expressions.
15857 auto AddRewrite = [&](const SCEV *From, const SCEV *FromRewritten,
15858 const SCEV *To) {
15859 if (From == FromRewritten)
15860 ExprsToRewrite.push_back(From);
15861 RewriteMap[From] = To;
15862 };
15863
15864 // Checks whether \p S has already been rewritten. In that case returns the
15865 // existing rewrite because we want to chain further rewrites onto the
15866 // already rewritten value. Otherwise returns \p S.
15867 auto GetMaybeRewritten = [&](const SCEV *S) {
15868 return RewriteMap.lookup_or(S, S);
15869 };
15870
15871 // Check for a condition of the form (-C1 + X < C2). InstCombine will
15872 // create this form when combining two checks of the form (X u< C2 + C1) and
15873 // (X >=u C1).
15874 auto MatchRangeCheckIdiom = [&](ICmpInst::Predicate Pred,
15875 const SCEV *MatchLHS,
15876 const SCEV *MatchRHS) {
15877 const SCEVConstant *C1;
15878 const SCEVUnknown *LHSUnknown;
15879 auto *C2 = dyn_cast<SCEVConstant>(MatchRHS);
15880 if (!match(MatchLHS,
15881 m_scev_Add(m_SCEVConstant(C1), m_SCEVUnknown(LHSUnknown))) ||
15882 !C2)
15883 return false;
15884
15885 auto ExactRegion =
15887 .sub(C1->getAPInt());
15888
15889 // Tighten the raw range with what we already know about LHSUnknown
15890 // from prior guards recorded in RewriteMap, or from SCEV's own range
15891 // analysis.
15892 const SCEV *RewrittenLHS = GetMaybeRewritten(LHSUnknown);
15893 ExactRegion = ExactRegion.intersectWith(SE.getUnsignedRange(RewrittenLHS),
15895
15896 // Bail if the guard is inconsistent with prior facts, or if the range
15897 // is still not a monotonic non-wrapping interval after tightening.
15898 if (ExactRegion.isEmptySet() || ExactRegion.isWrappedSet() ||
15899 ExactRegion.isFullSet())
15900 return false;
15901
15902 const SCEV *RegionMin = SE.getConstant(ExactRegion.getUnsignedMin());
15903 const SCEV *RegionMax = SE.getConstant(ExactRegion.getUnsignedMax());
15904 const SCEV *ClampedLHS =
15905 SE.getUMaxExpr(RegionMin, SE.getUMinExpr(RewrittenLHS, RegionMax));
15906 AddRewrite(LHSUnknown, RewrittenLHS, ClampedLHS);
15907 return true;
15908 };
15909 if (MatchRangeCheckIdiom(Predicate, LHS, RHS))
15910 return;
15911
15912 // Do not apply information for constants or if RHS contains an AddRec.
15914 return;
15915
15916 // If RHS is SCEVUnknown, make sure the information is applied to it.
15918 std::swap(LHS, RHS);
15920 }
15921
15922 // x != C for an extreme non-zero C is a strict comparison. x != 0 is
15923 // handled below.
15924 const APInt *NEC;
15925 if (Predicate == CmpInst::ICMP_NE && match(RHS, m_scev_APInt(NEC)) &&
15926 !NEC->isZero()) {
15927 if (NEC->isMaxSignedValue())
15929 else if (NEC->isMaxValue())
15931 else if (NEC->isMinSignedValue())
15933 }
15934
15935 const SCEV *RewrittenLHS = GetMaybeRewritten(LHS);
15936 // Apply divisibility information when computing the constant multiple.
15937 const APInt &DividesBy =
15938 SE.getConstantMultiple(DivGuards.rewrite(RewrittenLHS));
15939
15940 // Collect rewrites for LHS and its transitive operands based on the
15941 // condition.
15942 // For min/max expressions, also apply the guard to its operands:
15943 // 'min(a, b) >= c' -> '(a >= c) and (b >= c)',
15944 // 'min(a, b) > c' -> '(a > c) and (b > c)',
15945 // 'max(a, b) <= c' -> '(a <= c) and (b <= c)',
15946 // 'max(a, b) < c' -> '(a < c) and (b < c)'.
15947
15948 // We cannot express strict predicates in SCEV, so instead we replace them
15949 // with non-strict ones against plus or minus one of RHS depending on the
15950 // predicate.
15951 const SCEV *One = SE.getOne(RHS->getType());
15952 switch (Predicate) {
15953 case CmpInst::ICMP_ULT:
15954 if (RHS->getType()->isPointerTy())
15955 return;
15956 RHS = SE.getUMaxExpr(RHS, One);
15957 [[fallthrough]];
15958 case CmpInst::ICMP_SLT: {
15959 RHS = SE.getMinusSCEV(RHS, One);
15960 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
15961 break;
15962 }
15963 case CmpInst::ICMP_UGT:
15964 case CmpInst::ICMP_SGT:
15965 RHS = SE.getAddExpr(RHS, One);
15966 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
15967 break;
15968 case CmpInst::ICMP_ULE:
15969 case CmpInst::ICMP_SLE:
15970 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
15971 break;
15972 case CmpInst::ICMP_UGE:
15973 case CmpInst::ICMP_SGE:
15974 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
15975 break;
15976 default:
15977 break;
15978 }
15979
15980 SmallVector<SCEVUse, 16> Worklist(1, LHS);
15981 SmallPtrSet<const SCEV *, 16> Visited;
15982
15983 auto EnqueueOperands = [&Worklist](const SCEVNAryExpr *S) {
15984 append_range(Worklist, S->operands());
15985 };
15986
15987 while (!Worklist.empty()) {
15988 const SCEV *From = Worklist.pop_back_val();
15989 if (isa<SCEVConstant>(From))
15990 continue;
15991 if (!Visited.insert(From).second)
15992 continue;
15993 const SCEV *FromRewritten = GetMaybeRewritten(From);
15994 const SCEV *To = nullptr;
15995
15996 switch (Predicate) {
15997 case CmpInst::ICMP_ULT:
15998 case CmpInst::ICMP_ULE:
15999 To = SE.getUMinExpr(FromRewritten, RHS);
16000 if (auto *UMax = dyn_cast<SCEVUMaxExpr>(FromRewritten))
16001 EnqueueOperands(UMax);
16002 break;
16003 case CmpInst::ICMP_SLT:
16004 case CmpInst::ICMP_SLE:
16005 To = SE.getSMinExpr(FromRewritten, RHS);
16006 if (auto *SMax = dyn_cast<SCEVSMaxExpr>(FromRewritten))
16007 EnqueueOperands(SMax);
16008 break;
16009 case CmpInst::ICMP_UGT:
16010 case CmpInst::ICMP_UGE:
16011 To = SE.getUMaxExpr(FromRewritten, RHS);
16012 if (auto *UMin = dyn_cast<SCEVUMinExpr>(FromRewritten))
16013 EnqueueOperands(UMin);
16014 break;
16015 case CmpInst::ICMP_SGT:
16016 case CmpInst::ICMP_SGE: {
16017 // From s>= RHS s>= 0 implies From u>= RHS, so an earlier
16018 // umax(C, From) with C u<= RHS is redundant. Drop it, as the range of
16019 // the umax may be much less precise than the one of From.
16020 const APInt *C, *RHSC;
16021 if (match(RHS, m_scev_APInt(RHSC)) && RHSC->isNonNegative() &&
16022 match(FromRewritten,
16024 C->ule(*RHSC))
16025 FromRewritten = From;
16026 To = SE.getSMaxExpr(FromRewritten, RHS);
16027 if (auto *SMin = dyn_cast<SCEVSMinExpr>(FromRewritten))
16028 EnqueueOperands(SMin);
16029 break;
16030 }
16031 case CmpInst::ICMP_EQ:
16033 To = RHS;
16034 break;
16035 case CmpInst::ICMP_NE:
16036 if (match(RHS, m_scev_Zero())) {
16037 const SCEV *OneAlignedUp =
16038 getNextSCEVDivisibleByDivisor(One, DividesBy, SE);
16039 To = SE.getUMaxExpr(FromRewritten, OneAlignedUp);
16040 } else {
16041 // LHS != RHS can be rewritten as (LHS - RHS) = UMax(1, LHS - RHS),
16042 // but creating the subtraction eagerly is expensive. Track the
16043 // inequalities in a separate map, and materialize the rewrite lazily
16044 // when encountering a suitable subtraction while re-writing.
16045 if (LHS->getType()->isPointerTy()) {
16046 LHS = SE.getPtrToAddrExpr(LHS);
16047 RHS = SE.getPtrToAddrExpr(RHS);
16049 break;
16050 }
16051 const SCEVConstant *C;
16052 const SCEV *A, *B;
16055 RHS = A;
16056 LHS = B;
16057 }
16058 if (LHS > RHS)
16059 std::swap(LHS, RHS);
16060 Guards.NotEqual.insert({LHS, RHS});
16061 continue;
16062 }
16063 break;
16064 default:
16065 break;
16066 }
16067
16068 if (To)
16069 AddRewrite(From, FromRewritten, To);
16070 }
16071 };
16072
16074 // First, collect information from assumptions dominating the loop.
16075 for (auto &AssumeVH : SE.AC.assumptions()) {
16076 if (!AssumeVH)
16077 continue;
16078 auto *AssumeI = cast<CallInst>(AssumeVH);
16079 if (!SE.DT.dominates(AssumeI, Block))
16080 continue;
16081 Terms.emplace_back(AssumeI->getOperand(0), true);
16082 }
16083
16084 // Second, collect information from llvm.experimental.guards dominating the loop.
16085 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
16086 SE.F.getParent(), Intrinsic::experimental_guard);
16087 if (GuardDecl)
16088 for (const auto *GU : GuardDecl->users())
16089 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
16090 if (Guard->getFunction() == Block->getParent() &&
16091 SE.DT.dominates(Guard, Block))
16092 Terms.emplace_back(Guard->getArgOperand(0), true);
16093
16094 // Third, collect conditions from dominating branches. Starting at the loop
16095 // predecessor, climb up the predecessor chain, as long as there are
16096 // predecessors that can be found that have unique successors leading to the
16097 // original header. If there is no such predecessor, continue at the
16098 // immediate dominator.
16099 // TODO: share this logic with isLoopEntryGuardedByCond.
16100 unsigned NumCollectedConditions = 0;
16101 unsigned NumDomTreeSteps = 0;
16103 std::pair<const BasicBlock *, const BasicBlock *> Pair(Pred, Block);
16104 for (;; Pair = SE.getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
16105 if (!Pair.first) {
16106 // At the first block without a unique predecessor, try to build
16107 // conditions for its phis by merging those of their incoming blocks.
16108 if (!NumDomTreeSteps &&
16109 Depth < SE.Opts.scalar_evolution_max_loop_guard_collection_depth) {
16110 SmallDenseMap<const BasicBlock *, LoopGuards> IncomingGuards;
16111 for (auto &Phi : Pair.second->phis())
16112 collectFromPHI(SE, Guards, Phi, VisitedBlocks, IncomingGuards, Depth);
16113 }
16114 const DomTreeNode *IDom = SE.DT.getNode(Pair.second)->getIDom();
16115 if (!IDom ||
16116 ++NumDomTreeSteps > SE.Opts.scalar_evolution_max_guard_dom_tree_steps)
16117 break;
16118 Pair.first = IDom->getBlock();
16119 continue;
16120 }
16121 VisitedBlocks.insert(Pair.second);
16122 const CondBrInst *LoopEntryPredicate =
16123 dyn_cast<CondBrInst>(Pair.first->getTerminator());
16124 if (!LoopEntryPredicate)
16125 continue;
16126
16127 Terms.emplace_back(LoopEntryPredicate->getCondition(),
16128 LoopEntryPredicate->getSuccessor(0) == Pair.second);
16129 NumCollectedConditions++;
16130
16131 // If we are recursively collecting guards stop after 2
16132 // conditions to limit compile-time impact for now.
16133 if (Depth > 0 && NumCollectedConditions == 2)
16134 break;
16135 }
16136
16137 // Now apply the information from the collected conditions to
16138 // Guards.RewriteMap. Conditions are processed in reverse order, so the
16139 // earliest conditions is processed first, except guards with divisibility
16140 // information, which are moved to the back. This ensures the SCEVs with the
16141 // shortest dependency chains are constructed first.
16143 GuardsToProcess;
16144 for (auto [Term, EnterIfTrue] : reverse(Terms)) {
16145 SmallVector<Value *, 8> Worklist;
16146 SmallPtrSet<Value *, 8> Visited;
16147 Worklist.push_back(Term);
16148 while (!Worklist.empty()) {
16149 Value *Cond = Worklist.pop_back_val();
16150 if (!Visited.insert(Cond).second)
16151 continue;
16152
16153 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
16154 auto Predicate =
16155 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
16156 const auto *LHS = SE.getSCEV(Cmp->getOperand(0));
16157 const auto *RHS = SE.getSCEV(Cmp->getOperand(1));
16158 // If LHS is a constant, apply information to the other expression.
16159 // TODO: If LHS is not a constant, check if using compareSCEVComplexity
16160 // can improve results.
16161 if (isa<SCEVConstant>(LHS)) {
16162 std::swap(LHS, RHS);
16164 }
16165 GuardsToProcess.emplace_back(Predicate, LHS, RHS);
16166 continue;
16167 }
16168
16169 Value *L, *R;
16170 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
16171 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
16172 Worklist.push_back(L);
16173 Worklist.push_back(R);
16174 }
16175 }
16176 }
16177
16178 // Process divisibility guards in reverse order to populate DivGuards early.
16179 DenseMap<const SCEV *, APInt> Multiples;
16180 LoopGuards DivGuards(SE);
16181 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess) {
16182 if (!isDivisibilityGuard(LHS, RHS, SE))
16183 continue;
16184 collectDivisibilityInformation(Predicate, LHS, RHS, DivGuards.RewriteMap,
16185 Multiples, SE);
16186 }
16187
16188 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess)
16189 CollectCondition(Predicate, LHS, RHS, Guards.RewriteMap, DivGuards);
16190
16191 // Apply divisibility information last. This ensures it is applied to the
16192 // outermost expression after other rewrites for the given value.
16193 for (const auto &[K, Divisor] : Multiples) {
16194 const SCEV *DivisorSCEV = SE.getConstant(Divisor);
16195 Guards.RewriteMap[K] =
16197 Guards.rewrite(K), Divisor, SE),
16198 DivisorSCEV),
16199 DivisorSCEV);
16200 ExprsToRewrite.push_back(K);
16201 }
16202
16203 // Let the rewriter preserve NUW/NSW flags if the unsigned/signed ranges of
16204 // the replacement expressions are contained in the ranges of the replaced
16205 // expressions.
16206 Guards.PreserveNUW = true;
16207 Guards.PreserveNSW = true;
16208 for (const SCEV *Expr : ExprsToRewrite) {
16209 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16210 Guards.PreserveNUW &=
16211 SE.getUnsignedRange(Expr).contains(SE.getUnsignedRange(RewriteTo));
16212 Guards.PreserveNSW &=
16213 SE.getSignedRange(Expr).contains(SE.getSignedRange(RewriteTo));
16214 }
16215
16216 // Now that all rewrite information is collect, rewrite the collected
16217 // expressions with the information in the map. This applies information to
16218 // sub-expressions. A collected expression is rewritten when it is first
16219 // looked up, so the rewrites of the expressions it contains are used once
16220 // they are final.
16221 if (ExprsToRewrite.size() > 1) {
16222 constexpr unsigned MaxDepth = 16;
16223 unsigned Depth = 0;
16224 SmallPtrSet<const SCEV *, 16> ToRewrite(llvm::from_range, ExprsToRewrite);
16225 std::function<const SCEV *(const SCEV *)> Lookup = [&](const SCEV *Expr) {
16226 if (Depth < MaxDepth && ToRewrite.erase(Expr)) {
16227 auto It = Guards.RewriteMap.find(Expr);
16228 assert(It != Guards.RewriteMap.end() && "Expected rewrite entry");
16229 const SCEV *RewriteTo = It->second;
16230 Guards.RewriteMap.erase(It);
16231 SaveAndRestore Nest(Depth, Depth + 1);
16232 const SCEV *Rewritten = Guards.rewrite(RewriteTo, Lookup);
16233 Guards.RewriteMap[Expr] = Rewritten;
16234 return Rewritten;
16235 }
16236 return Guards.RewriteMap.lookup(Expr);
16237 };
16238 for (const SCEV *Expr : ExprsToRewrite)
16239 Lookup(Expr);
16240 }
16241}
16242
16243const SCEV *ScalarEvolution::LoopGuards::rewrite(const SCEV *Expr) const {
16244 return rewrite(Expr, nullptr);
16245}
16246
16247const SCEV *ScalarEvolution::LoopGuards::rewrite(
16248 const SCEV *Expr, function_ref<const SCEV *(const SCEV *)> Lookup) const {
16249 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
16250 /// in the map. It skips AddRecExpr because we cannot guarantee that the
16251 /// replacement is loop invariant in the loop of the AddRec.
16252 class SCEVLoopGuardRewriter
16253 : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
16256 function_ref<const SCEV *(const SCEV *)> Lookup;
16257
16258 SCEVFlags FlagMask = SCEV::FlagNone;
16259
16260 const SCEV *lookup(const SCEV *Key) {
16261 return Lookup ? Lookup(Key) : Map.lookup(Key);
16262 }
16263
16264 public:
16265 SCEVLoopGuardRewriter(ScalarEvolution &SE,
16266 const ScalarEvolution::LoopGuards &Guards,
16267 function_ref<const SCEV *(const SCEV *)> Lookup)
16268 : SCEVRewriteVisitor(SE), Map(Guards.RewriteMap),
16269 NotEqual(Guards.NotEqual), Lookup(Lookup) {
16270 if (Guards.PreserveNUW)
16271 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNUW);
16272 if (Guards.PreserveNSW)
16273 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNSW);
16274 }
16275
16276 const SCEV *visit(const SCEV *Expr) {
16279 SCEVMulExpr>(Expr))
16280 if (const SCEV *S = lookup(Expr))
16281 return S;
16282 return SCEVRewriteVisitor::visit(Expr);
16283 }
16284
16285 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
16286
16287 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
16288 // If there is no replacement for the exact ZExt expr, check if there's
16289 // one for a smaller ZExt we can use instead.
16290 Type *Ty = Expr->getType();
16291 const SCEV *Op = Expr->getOperand(0);
16292 unsigned Bitwidth = Ty->getScalarSizeInBits() / 2;
16293 while (Bitwidth % 8 == 0 && Bitwidth >= 8 &&
16294 Bitwidth > Op->getType()->getScalarSizeInBits()) {
16295 Type *NarrowTy = IntegerType::get(SE.getContext(), Bitwidth);
16296 SCEVUse NarrowExt = SE.getZeroExtendExpr(Op, NarrowTy);
16297 if (const SCEV *S = lookup(NarrowExt))
16298 return SE.getZeroExtendExpr(S, Ty);
16299 Bitwidth = Bitwidth / 2;
16300 }
16301
16303 }
16304
16305 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
16306 // Helper to check if S is a subtraction (A - B) where A != B, and if so,
16307 // return UMax(S, 1).
16308 auto RewriteSubtraction = [&](const SCEV *S) -> const SCEV * {
16309 SCEVUse LHS, RHS;
16310 if (MatchBinarySub(S, LHS, RHS)) {
16311 if (LHS > RHS)
16312 std::swap(LHS, RHS);
16313 if (NotEqual.contains({LHS, RHS})) {
16314 const SCEV *OneAlignedUp = getNextSCEVDivisibleByDivisor(
16315 SE.getOne(S->getType()), SE.getConstantMultiple(S), SE);
16316 return SE.getUMaxExpr(OneAlignedUp, S);
16317 }
16318 }
16319 return nullptr;
16320 };
16321
16322 // Check if Expr itself is a subtraction pattern with guard info.
16323 if (const SCEV *Rewritten = RewriteSubtraction(Expr))
16324 return Rewritten;
16325
16326 // Trip count expressions sometimes consist of adding 3 operands, i.e.
16327 // (Const + A + B). There may be guard info for A + B, and if so, apply
16328 // it.
16329 // TODO: Could more generally apply guards to Add sub-expressions.
16330 if (isa<SCEVConstant>(Expr->getOperand(0))) {
16331 if (Expr->getNumOperands() == 3) {
16332 const SCEV *Add =
16333 SE.getAddExpr(Expr->getOperand(1), Expr->getOperand(2));
16334 if (const SCEV *Rewritten = RewriteSubtraction(Add))
16335 return SE.getAddExpr(
16336 Expr->getOperand(0), Rewritten,
16337 ScalarEvolution::maskFlags(Expr->getNoWrapFlags(), FlagMask));
16338 if (const SCEV *S = lookup(Add))
16339 return SE.getAddExpr(Expr->getOperand(0), S);
16340 }
16341
16342 // For expressions of the form (Const + A), check if we have guard info
16343 // for (Const + 1 + A), and rewrite to ((Const + 1 + A) - 1). This makes
16344 // sure we don't lose information when rewriting expressions based on
16345 // back-edge taken counts in some cases.
16346 if (Expr->getNumOperands() == 2) {
16347 const SCEV *S = nullptr;
16348 // Handle (-1 + 1 + A) without constructing SCEVs.
16349 if (match(Expr->getOperand(0), m_scev_AllOnes())) {
16350 S = lookup(Expr->getOperand(1));
16351 } else {
16352 const SCEV *NewC =
16353 SE.getAddExpr(Expr->getOperand(0), SE.getOne(Expr->getType()));
16354 S = lookup(SE.getAddExpr(NewC, Expr->getOperand(1)));
16355 }
16356 if (S)
16357 return SE.getAddExpr(S, SE.getMinusOne(Expr->getType()));
16358 }
16359 }
16361 bool Changed = false;
16362 for (SCEVUse Op : Expr->operands()) {
16363 Operands.push_back(visit(Op));
16364 Changed |= Op != Operands.back();
16365 }
16366 // We are only replacing operands with equivalent values, so transfer the
16367 // flags from the original expression.
16368 return !Changed ? Expr
16369 : SE.getAddExpr(Operands,
16371 Expr->getNoWrapFlags(), FlagMask));
16372 }
16373
16374 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
16376 bool Changed = false;
16377 for (SCEVUse Op : Expr->operands()) {
16378 Operands.push_back(visit(Op));
16379 Changed |= Op != Operands.back();
16380 }
16381 // We are only replacing operands with equivalent values, so transfer the
16382 // flags from the original expression.
16383 return !Changed ? Expr
16384 : SE.getMulExpr(Operands,
16386 Expr->getNoWrapFlags(), FlagMask));
16387 }
16388 };
16389
16390 if (RewriteMap.empty() && NotEqual.empty())
16391 return Expr;
16392
16393 SCEVLoopGuardRewriter Rewriter(SE, *this, Lookup);
16394 return Rewriter.visit(Expr);
16395}
16396
16397const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
16398 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
16399 return applyLoopGuards(Expr, Guards);
16400}
16401
16403 LoopGuards &Guards) {
16404 // Loop guards never rewrite constants and AddRecs, so there is no need to
16405 // collect pending guards for them.
16407 return Expr;
16408 if (Guards.PendingLoop)
16409 Guards.collectPending();
16410 return Guards.rewrite(Expr);
16411}
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
constexpr LLT S1
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
@ PostInc
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
bpf unwind BPF Unwind Lower
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
This file contains the declarations for the subclasses of Constant, which represent the different fla...
SmallPtrSet< const BasicBlock *, 8 > VisitedBlocks
This file defines the DenseMap class.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
static bool isSigned(unsigned Opcode)
This file defines a hash set that can be used to remove duplication of nodes in a graph.
#define op(i)
Hexagon Common GEP
Value * getPointer(Value *Ptr)
IRTranslator LLVM IR MI
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This defines the Use class.
iv Induction Variable Users
Definition IVUsers.cpp:48
static bool lookup(const GsymReader &GR, GsymDataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
static bool hasNoUnsignedWrap(BinaryOperator &I)
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:550
MachineBasicBlock * Folded
SmallVector< MachineOperand, 4 > Cond
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define T
#define T1
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
ppc ctr loops verify
PowerPC Reduce CR logical Operation
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
R600 Clause Merge
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 bool isKnownViaMinMaxDecomposition(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, function_ref< bool(CmpPredicate, SCEVUse, SCEVUse)> Prove)
Try to prove "LHS Pred RHS" by decomposing a min/max on either side into its operands,...
static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow)
static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV *S)
When printing a top-level SCEV for trip counts, it's helpful to include a type for constants which ar...
static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, const Loop *L)
static bool containsConstantInAddMulChain(const SCEV *StartExpr)
Determine if any of the operands in this SCEV are a constant or if any of the add or multiply express...
static const SCEV * getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, ScalarEvolution *SE, unsigned Depth)
static const SCEV * applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr, const APInt &Divisor, ScalarEvolution &SE)
static const SCEV * constantFoldAndGroupOps(const AnalysisOptions &Opts, ScalarEvolution &SE, LoopInfo &LI, DominatorTree &DT, SmallVectorImpl< SCEVUse > &Ops, FoldT Fold, IsIdentityT IsIdentity, IsAbsorberT IsAbsorber)
Performs a number of common optimizations on the passed Ops.
static int compareValueComplexity(const AnalysisOptions &Opts, const LoopInfo *const LI, Value *LV, Value *RV, unsigned Depth)
Compare the two values LV and RV in terms of their "complexity" where "complexity" is a partial (and ...
static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
static const SCEV * getPreStartForExtend(const SCEVAddRecExpr *AR, ScalarEvolution *SE, unsigned Depth)
static bool collectDivisibilityInformation(ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS, DenseMap< const SCEV *, const SCEV * > &DivInfo, DenseMap< const SCEV *, APInt > &Multiples, ScalarEvolution &SE)
static void PushDefUseChildren(Instruction *I, SmallVectorImpl< Instruction * > &Worklist, SmallPtrSetImpl< Instruction * > &Visited)
Push users of the given Instruction onto the given Worklist.
static std::optional< APInt > SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, const ConstantRange &Range, ScalarEvolution &SE)
Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n iterations.
static int compareSCEVComplexity(const AnalysisOptions &Opts, const LoopInfo *const LI, SCEVUse LHS, SCEVUse RHS, DominatorTree &DT)
static bool getOperandsForSelectLikePHI(DominatorTree &DT, PHINode *PN, Value *&Cond, Value *&LHS, Value *&RHS)
static std::optional< std::tuple< APInt, APInt, APInt, APInt, unsigned > > GetQuadraticEquation(const SCEVAddRecExpr *AddRec)
For a given quadratic addrec, generate coefficients of the corresponding quadratic equation,...
static bool CollectAddOperandsWithScales(SmallDenseMap< const SCEV *, APInt, 16 > &M, SmallVectorImpl< SCEVUse > &NewOps, APInt &AccumulatedConstant, ArrayRef< SCEVUse > Ops, const APInt &Scale, ScalarEvolution &SE)
Process the given Ops list, which is a list of operands to be added under the given scale,...
static bool isKnownPredicateExtendIdiom(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
static std::optional< APInt > SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE)
Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n iterations.
static std::optional< APInt > TruncIfPossible(std::optional< APInt > X, unsigned BitWidth)
Helper function to truncate an optional APInt to a given BitWidth.
static SCEVFlags StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, ArrayRef< SCEVUse > Ops, SCEVFlags Flags)
static void groupByComplexity(const AnalysisOptions &Opts, SmallVectorImpl< SCEVUse > &Ops, LoopInfo *LI, DominatorTree &DT)
Given a list of SCEV objects, order them by their complexity, and group objects of the same complexit...
static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, const SCEVConstant *ConstantTerm, const SCEVAddExpr *WholeAddExpr)
static bool canConstantEvolve(Instruction *I, const Loop *L, const TargetLibraryInfo *TLI)
Determine whether this instruction can constant evolve within this loop assuming its operands can all...
static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS)
static std::optional< ConstantRange > GetRangeFromMetadata(Value *V)
Helper method to assign a range to V from metadata present in the IR.
static Type * isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, bool &Signed, ScalarEvolution &SE)
Helper function to createAddRecFromPHIWithCasts.
static Constant * EvaluateExpression(Value *V, const Loop *L, DenseMap< Instruction *, Constant * > &Vals, const DataLayout &DL, const TargetLibraryInfo *TLI)
EvaluateExpression - Given an expression that passes the getConstantEvolvingPHI predicate,...
static const SCEV * getPreviousSCEVDivisibleByDivisor(const SCEV *Expr, const APInt &DivisorVal, ScalarEvolution &SE)
static const SCEV * MatchNotExpr(const SCEV *Expr)
If Expr computes ~A, return A else return nullptr.
static std::pair< ConstantRange, bool > getRangeForAffineARHelper(APInt Step, const ConstantRange &StartRange, const APInt &MaxBECount, bool Signed)
static cl::opt< bool, true > VerifySCEVOpt("verify-scev", cl::Hidden, cl::location(VerifySCEV), cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"))
static const SCEV * getSignedOverflowLimitForStep(const SCEV *Step, ICmpInst::Predicate *Pred, ScalarEvolution *SE)
static bool HasSameValue(const SCEV *A, const SCEV *B)
SCEV structural equivalence is usually sufficient for testing whether two expressions are equal,...
static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow)
Compute the result of "n choose k", the binomial coefficient.
static bool scevUnconditionallyPropagatesPoisonFromOperands(SCEVTypes Kind)
static Constant * getOtherIncomingValue(PHINode *PN, BasicBlock *BB)
static constexpr unsigned MaxKnownPredicateDepth
Maximum nesting depth of recursive isKnownPredicate calls.
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:170
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 unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static std::optional< bool > isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS, const Value *ARHS, const Value *BLHS, const Value *BRHS)
Return true if "icmp Pred BLHS BRHS" is true whenever "icmp PredALHS ARHS" is true.
virt reg Virtual Register Rewriter
static int Lookup(ArrayRef< TableEntry > Table, unsigned Opcode)
Value * RHS
Value * LHS
BinaryOperator * Mul
static const uint32_t IV[8]
Definition blake3_impl.h:83
SCEVCastSinkingRewriter(ScalarEvolution &SE, Type *TargetTy, ConversionFn CreatePtrCast)
static const SCEV * rewrite(const SCEV *Scev, ScalarEvolution &SE, Type *TargetTy, ConversionFn CreatePtrCast)
const SCEV * visitUnknown(const SCEVUnknown *Expr)
const SCEV * visitAddExpr(const SCEVAddExpr *Expr)
const SCEV * visit(const SCEV *S)
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2018
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
APInt abs() const
Get the absolute value.
Definition APInt.h:1815
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:212
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1973
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
bool isNonPositive() const
Determine if this APInt Value is non-positive (<= 0).
Definition APInt.h:357
unsigned countTrailingZeros() const
Definition APInt.h:1667
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:352
unsigned logBase2() const
Definition APInt.h:1781
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:471
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1303
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:401
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
bool isSignBitSet() const
Determine if sign bit of this APInt is set.
Definition APInt.h:337
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1134
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition APInt.h:428
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
bool isMaxValue() const
Determine if this is the largest unsigned value.
Definition APInt.h:395
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:61
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:439
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
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:462
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
LLVM_ABI unsigned getNoWrapKind() const
Returns one of OBO::NoSignedWrap or OBO::NoUnsignedWrap.
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
This class represents a function call, abstracting a target machine's calling convention.
virtual void deleted()
Callback for Value destruction.
void setValPtr(Value *P)
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
bool isFalseWhenEqual() const
This is just a convenience.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
bool isSigned() const
Definition InstrTypes.h:993
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
Predicate getNonStrictPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
Definition InstrTypes.h:934
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
bool isUnsigned() const
Definition InstrTypes.h:999
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Definition InstrTypes.h:989
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
CmpInst::Predicate dropSameSign() const
Drops samesign information.
Conditional Branch instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static LLVM_ABI Constant * getNot(Constant *C)
static Constant * getPtrAdd(Constant *Ptr, Constant *Offset, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReduced=nullptr)
Create a getelementptr i8, ptr, offset constant expression.
Definition Constants.h:1518
static LLVM_ABI Constant * getPtrToAddr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
This class represents a range of values.
LLVM_ABI ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
LLVM_ABI ConstantRange zextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
LLVM_ABI bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const
Set up Pred and RHS such that ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.
const APInt & getLower() const
Return the lower value for this range.
LLVM_ABI ConstantRange urem(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned remainder operation of...
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI ConstantRange zeroExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
LLVM_ABI bool isSignWrappedSet() const
Return true if this set wraps around the signed domain.
LLVM_ABI APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
LLVM_ABI bool isWrappedSet() const
Return true if this set wraps around the unsigned domain.
LLVM_ABI void print(raw_ostream &OS) const
Print out the bounds to a stream.
bool isSingleElement() const
Return true if this set contains exactly one member.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
LLVM_ABI ConstantRange signExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
const APInt & getUpper() const
Return the upper value for this range.
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static LLVM_ABI ConstantRange makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp, const ConstantRange &Other, unsigned NoWrapKind)
Produce the largest range containing all X such that "X BinOp Y" is guaranteed not to wrap (overflow)...
LLVM_ABI unsigned getMinSignedBits() const
Compute the maximal number of bits needed to represent every value in this signed range.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
LLVM_ABI ConstantRange sextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
static LLVM_ABI ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp, const APInt &Other, unsigned NoWrapKind)
Produce the range that contains X if and only if "X BinOp Other" does not wrap.
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
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:793
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:757
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:762
bool empty() const
Definition DenseMap.h:716
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition DenseMap.h:678
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive,...
Definition DenseMap.h:779
void swap(DenseMapBase &RHS)
Definition DenseMap.h:975
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
DomTreeNodeBase * getIDom() const
NodeT * getBlock() const
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction extracts a single (scalar) element from a VectorType value.
This instruction extracts a struct member or array element value from an aggregate value.
Insertion token: a failed lookup fills it in, the matching insert consumes it.
Definition FoldingSet.h:284
This class describes a reference to an interned FoldingSetNodeID, which can be a useful to store node...
Definition FoldingSet.h:123
This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:162
void AddInteger(signed I)
Definition FoldingSet.h:190
This class represents a freeze function that returns random concrete value if an operand is either a ...
FunctionPass(char &pid)
Definition Pass.h:314
Represents flags for the getelementptr instruction/expression.
bool hasNoUnsignedSignedWrap() const
bool hasNoUnsignedWrap() const
static GEPNoWrapFlags none()
static LLVM_ABI Type * getTypeAtIndex(Type *Ty, Value *Idx)
Return the type of the element at the given index of an indexable type.
Module * getParent()
Get the module that this global value is contained inside of...
static bool isPrivateLinkage(LinkageTypes Linkage)
static bool isInternalLinkage(LinkageTypes Linkage)
This instruction compares its operands according to the predicate given to the constructor.
CmpPredicate getCmpPredicate() const
static bool isGE(Predicate P)
Return true if the predicate is SGE or UGE.
CmpPredicate getSwappedCmpPredicate() const
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
static bool isLT(Predicate P)
Return true if the predicate is SLT or ULT.
CmpPredicate getInverseCmpPredicate() const
Predicate getNonStrictCmpPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
static bool isGT(Predicate P)
Return true if the predicate is SGT or UGT.
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
static CmpPredicate getInverseCmpPredicate(CmpPredicate Pred)
bool isEquality() const
Return true if this predicate is either EQ or NE.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
static LLVM_ABI std::optional< bool > isImpliedByMatchingCmp(CmpPredicate Pred1, CmpPredicate Pred2)
Determine if Pred1 implies Pred2 is true, false, or if nothing can be inferred about the implication,...
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
static bool isLE(Predicate P)
Return true if the predicate is SLE or ULE.
This instruction inserts a single (scalar) element into a VectorType value.
This instruction inserts a struct field of array element value into an aggregate value.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI bool isIdenticalToWhenDefined(const Instruction *I, bool IntersectAttrs=false) const LLVM_READONLY
This is like isIdenticalTo, except that it ignores the SubclassOptionalData flags,...
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
A helper class to return the specified delimiter string after the first invocation of operator String...
An instruction for reading from memory.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:598
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
BlockT * getHeader() const
BlockT * getLoopPredecessor() const
If the given loop's header has exactly one unique predecessor outside the loop, return it.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
unsigned getLoopDepth(const BlockT *BB) const
Return the loop nesting level of the specified block.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:623
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
LLVM_ABI bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:64
Metadata node.
Definition Metadata.h:1087
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition Operator.h:113
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition Operator.h:107
iterator_range< const_block_iterator > blocks() const
op_range incoming_values()
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
PointerIntPair - This class implements a pair of a pointer and small integer.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
LLVM_ABI void addPredicate(const SCEVPredicate &Pred)
Adds a new predicate.
LLVM_ABI const SCEVPredicate & getPredicate() const
LLVM_ABI const SCEV * getPredicatedSCEV(const SCEV *Expr)
Returns the rewritten SCEV for Expr in the context of the current SCEV predicate.
LLVM_ABI bool areAddRecsEqualWithPreds(const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2, ArrayRef< const SCEVPredicate * > ExtraPreds={}) const
Check if AR1 and AR2 are equal, while taking into account Equal predicates in Preds and ExtraPreds.
LLVM_ABI const SCEVAddRecExpr * getAsAddRec(Value *V, SmallVectorImpl< const SCEVPredicate * > *WrapPredsAdded=nullptr)
Attempts to produce an AddRecExpr for V by adding additional SCEV predicates.
LLVM_ABI void print(raw_ostream &OS, unsigned Depth) const
Print the SCEV mappings done by the Predicated Scalar Evolution.
LLVM_ABI PredicatedScalarEvolution(ScalarEvolution &SE, Loop &L)
LLVM_ABI unsigned getSmallConstantMaxTripCount()
Returns the upper bound of the loop trip count as a normal unsigned value, or 0 if the trip count is ...
LLVM_ABI void addPredicates(ArrayRef< const SCEVPredicate * > Preds)
Adds all predicates in Preds.
LLVM_ABI const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSymbolicMaxBackedgeTakenCount()
Get the (predicated) symbolic max backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
constexpr bool isValid() const
Definition Register.h:109
This node represents an addition of some number of SCEVs.
This node represents a polynomial recurrence on the trip count of the specified loop.
LLVM_ABI SCEVUse getExitValue(ScalarEvolution &SE) const
Return the value of this recurrences when its loop exits, i.e.
LLVM_ABI const SCEV * evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const
Return the value of this chain of recurrences at the specified iteration number.
void setNoWrapFlags(SCEVFlags Flags)
Set flags for a recurrence without clearing any previously set flags.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
bool isQuadratic() const
Return true if this represents an expression A + B*x + C*x^2 where A, B and C are loop invariant valu...
LLVM_ABI const SCEV * getNumIterationsInRange(const ConstantRange &Range, ScalarEvolution &SE) const
Return the number of iterations of this loop that produce values in the specified constant range.
LLVM_ABI const SCEVAddRecExpr * getPostIncExpr(ScalarEvolution &SE) const
Return an expression representing the value of this expression one iteration of the loop ahead.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This is the base class for unary cast operator classes.
LLVM_ABI SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, SCEVUse op, Type *ty)
This class represents an assumption that the expression LHS Pred RHS evaluates to true,...
SCEVComparePredicate(const FoldingSetNodeIDRef ID, const ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
bool isAlwaysTrue() const override
Returns true if the predicate is always true.
void print(raw_ostream &OS, unsigned Depth=0) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Implementation of the SCEVPredicate interface.
This class represents a constant integer value.
ConstantInt * getValue() const
const APInt & getAPInt() const
This is the base class for unary integral cast operator classes.
LLVM_ABI SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, SCEVUse op, Type *ty)
This node is the base class min/max selections.
static enum SCEVTypes negate(enum SCEVTypes T)
This node represents multiplication of some number of SCEVs.
This node is a base class providing common functionality for n'ary operators.
ArrayRef< SCEVUse > operands() const
SCEVFlags getNoWrapFlags(SCEVFlags Mask=FlagsNoWrapMask) const
SCEVUse getOperand(unsigned i) const
This class represents an assumption made using SCEV expressions which can be checked at run-time.
SCEVPredicate(const SCEVPredicate &)=default
virtual bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const =0
Returns true if this predicate implies N.
SCEVPredicateKind Kind
This class represents a cast from a pointer to a pointer-sized integer value, without capturing the p...
This visitor recursively visits a SCEV expression and re-writes it.
SCEVUse visitZeroExtendExpr(SCEVUseT< const SCEVZeroExtendExpr * > Expr)
This class represents a signed minimum selection.
This node is the base class for sequential/in-order min/max selections.
static SCEVTypes getEquivalentNonSequentialSCEVType(SCEVTypes Ty)
This class represents a sign extension of a small integer value to a larger integer value.
Visit all nodes in the expression tree using worklist traversal.
This class represents a truncation of an integer value to a smaller integer value.
This class represents a binary unsigned division operation.
This class represents an unsigned minimum selection.
This class represents a composition of other SCEV predicates, and is the class that most clients will...
void print(raw_ostream &OS, unsigned Depth) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Returns true if this predicate implies N.
SCEVUnionPredicate(ArrayRef< const SCEVPredicate * > Preds, ScalarEvolution &SE)
Union predicates don't get cached so create a dummy set ID for it.
bool isAlwaysTrue() const override
Implementation of the SCEVPredicate interface.
SCEVUnionPredicate getUnionWith(const SCEVPredicate *N, ScalarEvolution &SE) const
Returns a new SCEVUnionPredicate that is the union of this predicate and the given predicate N.
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
This class represents the value of vscale, as used when defining the length of a scalable vector or r...
This class represents an assumption made on an AddRec expression.
IncrementWrapFlags
Similar to SCEVFlags, but with slightly different semantics for FlagNUSW.
SCEVWrapPredicate(const FoldingSetNodeIDRef ID, const SCEVAddRecExpr *AR, IncrementWrapFlags Flags)
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Returns true if this predicate implies N.
static SCEVWrapPredicate::IncrementWrapFlags setFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OnFlags)
void print(raw_ostream &OS, unsigned Depth=0) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool isAlwaysTrue() const override
Returns true if the predicate is always true.
const SCEVAddRecExpr * getExpr() const
Implementation of the SCEVPredicate interface.
static SCEVWrapPredicate::IncrementWrapFlags clearFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OffFlags)
Convenient IncrementWrapFlags manipulation methods.
IncrementWrapFlags getFlags() const
Returns the set assumed no overflow flags.
This class represents a zero extension of a small integer value to a larger integer value.
This class represents an analyzed expression in the program.
unsigned short getExpressionSize() const
static constexpr auto FlagsNoWrapMask
LLVM_ABI bool isOne() const
Return true if the expression is a constant one.
SCEV(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, unsigned short ExpressionSize, Type *Ty)
static constexpr auto FlagNUW
LLVM_ABI void computeAndSetCanonical(ScalarEvolution &SE)
Compute and set the canonical SCEV, by constructing a SCEV with the same operands,...
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
const SCEV * getCanonical() const
Return the canonical SCEV.
const SCEV * CanonicalSCEV
Pointer to the canonical version of the SCEV, i.e.
LLVM_ABI void dump() const
This method is used for debugging.
LLVM_ABI bool isAllOnesValue() const
Return true if the expression is a constant all-ones value.
LLVM_ABI bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
static constexpr auto FlagNSW
LLVM_ABI ArrayRef< SCEVUse > operands() const
Return operands of this SCEV expression.
Type * getType() const
Return the LLVM type of this SCEV expression.
static constexpr auto FlagNone
LLVM_ABI void print(raw_ostream &OS) const
Print out the internal representation of this scalar to the specified stream.
SCEVTypes getSCEVType() const
static constexpr auto FlagNW
Analysis pass that exposes the ScalarEvolution for a function.
LLVM_ABI ScalarEvolution run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void print(raw_ostream &OS, const Module *=nullptr) const override
print - Print out the internal state of the pass.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
static LoopGuards collectOnDemand(const Loop *L, ScalarEvolution &SE)
Return loop guards for loop L, which are collected on first use.
The main scalar evolution driver.
LLVM_ABI const SCEV * getUDivExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
const SCEV * getConstantMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
const DataLayout & getDataLayout() const
Return the DataLayout associated with the module this SCEV instance is operating on.
LLVM_ABI bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
LLVM_ABI bool isKnownOnEveryIteration(CmpPredicate Pred, const SCEVAddRecExpr *LHS, const SCEV *RHS)
Test if the condition described by Pred, LHS, RHS is known to be true on every iteration of the loop ...
static bool hasFlags(SCEVFlags Flags, SCEVFlags TestFlags)
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantExitCondDuringFirstIterationsImpl(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI, const SCEV *MaxIter)
LLVM_ABI const SCEV * 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 SCEVUse getZeroExtendExprImpl(SCEVUse Op, Type *Ty, unsigned Depth=0)
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 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 * 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 SCEVUse getZeroExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
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 SCEVUse getSignExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI void forgetAllLoops()
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 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 bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, unsigned Depth=0)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
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.
LLVM_ABI SCEVUse getSignExtendExprImpl(SCEVUse Op, Type *Ty, unsigned Depth=0)
APInt getSignedRangeMax(const SCEV *S)
Determine the max of the signed range for a particular SCEV.
LLVM_ABI void verify() const
LLVMContext & getContext() const
This class represents the LLVM 'select' instruction.
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:295
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:745
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:776
TypeSize getSizeInBits() const
Definition DataLayout.h:756
Class to represent struct types.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:291
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
Use & Op()
Definition User.h:171
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition Value.h:545
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:183
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition APInt.h:2274
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition APInt.h:2279
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition APInt.h:2284
LLVM_ABI std::optional< APInt > SolveQuadraticEquationWrap(APInt A, APInt B, APInt C, unsigned RangeWidth)
Let q(n) = An^2 + Bn + C, and BW = bit width of the value range (e.g.
Definition APInt.cpp:2859
LLVM_ABI APInt GreatestCommonDivisor(APInt A, APInt B, bool IsSigned=false)
Compute GCD of two APInt values.
Definition APInt.cpp:826
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2289
constexpr bool any(E Val)
@ Entry
Definition COFF.h:862
int getMaxValue(MCInstrInfo const &MCII, MCInst const &MCI)
Return the maximum value of an extendable operand.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
bind_cst_ty m_scev_APInt(const APInt *&C)
Match an SCEV constant and bind it to an APInt.
cst_pred_ty< is_all_ones > m_scev_AllOnes()
Match an integer with all bits set.
SCEVUnaryExpr_match< SCEVZeroExtendExpr, Op0_t > m_scev_ZExt(const Op0_t &Op0)
is_undef_or_poison m_scev_UndefOrPoison()
Match an SCEVUnknown wrapping undef or poison.
SCEVBinaryExpr_match< SCEVMinMaxExpr, Op0_t, Op1_t > m_scev_MinMax(const Op0_t &Op0, const Op1_t &Op1)
cst_pred_ty< is_one > m_scev_One()
Match an integer 1.
specificloop_ty m_SpecificLoop(const Loop *L)
SCEVUnaryExpr_match< SCEVSignExtendExpr, Op0_t > m_scev_SExt(const Op0_t &Op0)
match_bind< const SCEVMulExpr > m_scev_Mul(const SCEVMulExpr *&V)
cst_pred_ty< is_zero > m_scev_Zero()
Match an integer 0.
SCEVUnaryExpr_match< SCEVTruncateExpr, Op0_t > m_scev_Trunc(const Op0_t &Op0)
bool match(const SCEV *S, const Pattern &P)
SCEVBinaryExpr_match< SCEVUDivExpr, Op0_t, Op1_t > m_scev_UDiv(const Op0_t &Op0, const Op1_t &Op1)
SCEVBinaryExpr_match< SCEVAddExpr, Op0_t, Op1_t, SCEV::FlagNSW > m_scev_NSWAdd(const Op0_t &Op0, const Op1_t &Op1)
specificscev_ty m_scev_Specific(const SCEV *S)
Match if we have a specific specified SCEV.
SCEVAffineAddRec_match< Op0_t, Op1_t, match_isa< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
match_bind< const SCEVUnknown > m_SCEVUnknown(const SCEVUnknown *&V)
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t, SCEV::FlagNUW, true > m_scev_c_NUWMul(const Op0_t &Op0, const Op1_t &Op1)
SCEVBinaryExpr_match< SCEVUMaxExpr, Op0_t, Op1_t, SCEV::FlagNone, true > m_scev_UMax(const Op0_t &Op0, const Op1_t &Op1)
SCEVBinaryExpr_match< SCEVSMaxExpr, Op0_t, Op1_t, SCEV::FlagNone, true > m_scev_SMax(const Op0_t &Op0, const Op1_t &Op1)
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t, SCEV::FlagNone, true > m_scev_c_Mul(const Op0_t &Op0, const Op1_t &Op1)
match_bind< const SCEVAddExpr > m_scev_Add(const SCEVAddExpr *&V)
SCEVURem_match< Op0_t, Op1_t > m_scev_URem(Op0_t LHS, Op1_t RHS, ScalarEvolution &SE)
Match the mathematical pattern A - (A / B) * B, where A and B can be arbitrary expressions.
@ Valid
The data is already valid.
LocationClass< Ty > location(Ty &L)
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
Definition CoroShape.h:32
constexpr double e
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
void visitAll(const SCEV *Root, SV &Visitor)
Use SCEVTraversal to visit all nodes in the given expression tree.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
SaveAndRestore(T &) -> SaveAndRestore< T >
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
LLVM_ABI bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q, SmallVectorImpl< Instruction * > *DropAnnotations=nullptr)
See if we can compute a simplified version of this instruction.
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
SCEVUseT< const SCEV * > SCEVUse
bool set_is_subset(const S1Ty &S1, const S2Ty &S2)
set_is_subset(A, B) - Return true iff A in B
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
void * PointerTy
LLVM_ABI bool VerifySCEV
auto uninitialized_copy(R &&Src, IterTy Dst)
Definition STLExtras.h:2127
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI 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 bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, const DominatorTree &DT)
Returns true if the arithmetic part of the WO 's result is used only along the paths control dependen...
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Function *CtxF=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
const AnalysisOptions & getAnalysisOptions(const LLVMContext &C)
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2220
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI bool isMustProgress(const Loop *L)
Return true if this loop can be assumed to make progress.
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
@ Off
Use window algorithm after SMS algorithm fails.
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:370
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
LLVM_ABI bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ Mul
Product of integers.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ Add
Sum of integers.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
DWARFExpression::Operation Op
auto max_element(R &&Range)
Provide wrappers to std::max_element which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2104
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
SCEVFlags
SCEVFlags are bitfield indices into SCEV's SubclassData.
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2210
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:249
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
LLVM_ABI unsigned computeNumSignBits(const Value *Op, const SimplifyQuery &Q, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
iterator_range< df_iterator< T > > depth_first(const T &G)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2162
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
bool SCEVExprContains(const SCEV *Root, PredTy Pred)
Return true if any node in Root satisfies the predicate Pred.
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
#define NC
Definition regutils.h:42
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
An object of this class is returned by queries that could not be answered.
static LLVM_ABI bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
The no-wrap flags to apply when creating a SCEV expression, to the expression and use respectively.
SCEVFlags ExprFlags
Flags applied directly to a SCEV expression, must be valid wherever the expression is valid.
SCEVFlags UseFlags
Flags only applied to a SCEVUse.
static SCEVUseT getCommon(SCEVUseT A, SCEVUseT B)
bool isCanonical() const
Returns true if the SCEVUse is canonical, i.e.
SCEVPtrT getPointer() const
This class defines a simple visitor class that may be used for various SCEV analysis purposes.
A utility class that uses RAII to save and restore the value of a variable.
Information about the number of loop iterations for which a loop exit's branch condition evaluates to...
LLVM_ABI ExitLimit(const SCEV *E)
Construct either an exact exit limit from a constant, or an unknown one from a SCEVCouldNotCompute.
SmallVector< const SCEVPredicate *, 4 > Predicates
A vector of predicate guards for this ExitLimit.