LLVM 24.0.0git
ScalarEvolution.cpp
Go to the documentation of this file.
1//===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the implementation of the scalar evolution analysis
10// engine, which is used primarily to analyze expressions involving induction
11// variables in loops.
12//
13// There are several aspects to this library. First is the representation of
14// scalar expressions, which are represented as subclasses of the SCEV class.
15// These classes are used to represent certain types of subexpressions that we
16// can handle. We only create one SCEV of a particular shape, so
17// pointer-comparisons for equality are legal.
18//
19// One important aspect of the SCEV objects is that they are never cyclic, even
20// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
21// the PHI node is one of the idioms that we can represent (e.g., a polynomial
22// recurrence) then we represent it directly as a recurrence node, otherwise we
23// represent it as a SCEVUnknown node.
24//
25// In addition to being able to represent expressions of various types, we also
26// have folders that are used to build the *canonical* representation for a
27// particular expression. These folders are capable of using a variety of
28// rewrite rules to simplify the expressions.
29//
30// Once the folders are defined, we can implement the more interesting
31// higher-level code, such as the code that recognizes PHI nodes of various
32// types, computes the execution count of a loop, etc.
33//
34// TODO: We should use these routines and value representations to implement
35// dependence analysis!
36//
37//===----------------------------------------------------------------------===//
38//
39// There are several good references for the techniques used in this analysis.
40//
41// Chains of recurrences -- a method to expedite the evaluation
42// of closed-form functions
43// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
44//
45// On computational properties of chains of recurrences
46// Eugene V. Zima
47//
48// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
49// Robert A. van Engelen
50//
51// Efficient Symbolic Analysis for Optimizing Compilers
52// Robert A. van Engelen
53//
54// Using the chains of recurrences algebra for data dependence testing and
55// induction variable substitution
56// MS Thesis, Johnie Birch
57//
58//===----------------------------------------------------------------------===//
59
61#include "llvm/ADT/APInt.h"
62#include "llvm/ADT/ArrayRef.h"
63#include "llvm/ADT/DenseMap.h"
65#include "llvm/ADT/FoldingSet.h"
66#include "llvm/ADT/STLExtras.h"
67#include "llvm/ADT/ScopeExit.h"
68#include "llvm/ADT/Sequence.h"
71#include "llvm/ADT/Statistic.h"
73#include "llvm/ADT/StringRef.h"
83#include "llvm/Config/llvm-config.h"
84#include "llvm/IR/Argument.h"
85#include "llvm/IR/BasicBlock.h"
86#include "llvm/IR/CFG.h"
87#include "llvm/IR/Constant.h"
89#include "llvm/IR/Constants.h"
90#include "llvm/IR/DataLayout.h"
92#include "llvm/IR/Dominators.h"
93#include "llvm/IR/Function.h"
94#include "llvm/IR/GlobalAlias.h"
95#include "llvm/IR/GlobalValue.h"
97#include "llvm/IR/InstrTypes.h"
98#include "llvm/IR/Instruction.h"
101#include "llvm/IR/Intrinsics.h"
102#include "llvm/IR/LLVMContext.h"
103#include "llvm/IR/Operator.h"
104#include "llvm/IR/PatternMatch.h"
105#include "llvm/IR/Type.h"
106#include "llvm/IR/Use.h"
107#include "llvm/IR/User.h"
108#include "llvm/IR/Value.h"
109#include "llvm/IR/Verifier.h"
111#include "llvm/Pass.h"
112#include "llvm/Support/Casting.h"
115#include "llvm/Support/Debug.h"
121#include <algorithm>
122#include <cassert>
123#include <climits>
124#include <cstdint>
125#include <cstdlib>
126#include <map>
127#include <memory>
128#include <numeric>
129#include <optional>
130#include <tuple>
131#include <utility>
132#include <vector>
133
134using namespace llvm;
135using namespace PatternMatch;
136using namespace SCEVPatternMatch;
137
138#define DEBUG_TYPE "scalar-evolution"
139
140STATISTIC(NumExitCountsComputed,
141 "Number of loop exits with predictable exit counts");
142STATISTIC(NumExitCountsNotComputed,
143 "Number of loop exits without predictable exit counts");
144STATISTIC(NumBruteForceTripCountsComputed,
145 "Number of loops with trip counts computed by force");
146
147#ifdef EXPENSIVE_CHECKS
148bool llvm::VerifySCEV = true;
149#else
150bool llvm::VerifySCEV = false;
151#endif
152
154 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
155 cl::desc("Maximum number of iterations SCEV will "
156 "symbolically execute a constant "
157 "derived loop"),
158 cl::init(100));
159
161 "verify-scev", cl::Hidden, cl::location(VerifySCEV),
162 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
164 "verify-scev-strict", cl::Hidden,
165 cl::desc("Enable stricter verification with -verify-scev is passed"));
166
168 "scev-verify-ir", cl::Hidden,
169 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
170 cl::init(false));
171
173 "scev-mulops-inline-threshold", cl::Hidden,
174 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
175 cl::init(32));
176
178 "scev-addops-inline-threshold", cl::Hidden,
179 cl::desc("Threshold for inlining addition operands into a SCEV"),
180 cl::init(500));
181
183 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
184 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
185 cl::init(2));
186
188 "scalar-evolution-max-value-compare-depth", cl::Hidden,
189 cl::desc("Maximum depth of recursive value complexity comparisons"),
190 cl::init(2));
191
193 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
194 cl::desc("Maximum depth of recursive arithmetics"),
195 cl::init(32));
196
198 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
199 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
200
202 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
203 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
204 cl::init(8));
205
207 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
208 cl::desc("Max coefficients in AddRec during evolving"),
209 cl::init(8));
210
212 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
213 cl::desc("Size of the expression which is considered huge"),
214 cl::init(4096));
215
217 "scev-range-iter-threshold", cl::Hidden,
218 cl::desc("Threshold for switching to iteratively computing SCEV ranges"),
219 cl::init(32));
220
222 "scalar-evolution-max-loop-guard-collection-depth", cl::Hidden,
223 cl::desc("Maximum depth for recursive loop guard collection"), cl::init(1));
224
225static cl::opt<bool>
226ClassifyExpressions("scalar-evolution-classify-expressions",
227 cl::Hidden, cl::init(true),
228 cl::desc("When printing analysis, include information on every instruction"));
229
231 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
232 cl::init(false),
233 cl::desc("Use more powerful methods of sharpening expression ranges. May "
234 "be costly in terms of compile time"));
235
236static cl::opt<bool>
237 EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
238 cl::desc("Handle <= and >= in finite loops"),
239 cl::init(true));
240
242 "scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden,
243 cl::desc("Infer nuw/nsw flags using context where suitable"),
244 cl::init(true));
245
246//===----------------------------------------------------------------------===//
247// SCEV class definitions
248//===----------------------------------------------------------------------===//
249
251 // Leaf nodes are always their own canonical.
252 switch (getSCEVType()) {
253 case scConstant:
254 case scVScale:
255 case scUnknown:
256 CanonicalSCEV = this;
257 return;
258 default:
259 break;
260 }
261
262 // For all other expressions, check whether any immediate operand has a
263 // different canonical. Since operands are always created before their parent,
264 // their canonical pointers are already set — no recursion needed.
265 if (all_of(operands(), [](SCEVUse Op) { return Op.isCanonical(); })) {
266 CanonicalSCEV = this;
267 return;
268 }
269
271 map_range(operands(), [](SCEVUse Op) { return Op.getCanonical(); }));
272 // Rebuild the expression from the canonical operands, stripping use flags.
273 CanonicalSCEV = SE.getWithOperands(this, CanonOps);
274}
275
276//===----------------------------------------------------------------------===//
277// Implementation of the SCEV class.
278//
279
280#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
282 print(dbgs());
283 dbgs() << '\n';
284}
285#endif
286
287void SCEV::print(raw_ostream &OS) const {
288 switch (getSCEVType()) {
289 case scConstant:
290 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
291 return;
292 case scVScale:
293 OS << "vscale";
294 return;
295 case scPtrToAddr: {
296 const SCEVCastExpr *PtrCast = cast<SCEVCastExpr>(this);
297 SCEVUse Op = PtrCast->getOperand();
298 OS << "(ptrtoaddr " << *Op->getType() << " " << Op << " to "
299 << *PtrCast->getType() << ")";
300 return;
301 }
302 case scTruncate: {
303 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
304 SCEVUse Op = Trunc->getOperand();
305 OS << "(trunc " << *Op->getType() << " " << Op << " to "
306 << *Trunc->getType() << ")";
307 return;
308 }
309 case scZeroExtend: {
311 SCEVUse Op = ZExt->getOperand();
312 OS << "(zext " << *Op->getType() << " " << Op << " to " << *ZExt->getType()
313 << ")";
314 return;
315 }
316 case scSignExtend: {
318 SCEVUse Op = SExt->getOperand();
319 OS << "(sext " << *Op->getType() << " " << Op << " to " << *SExt->getType()
320 << ")";
321 return;
322 }
323 case scAddRecExpr: {
324 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
325 OS << "{" << AR->getOperand(0);
326 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
327 OS << ",+," << AR->getOperand(i);
328 OS << "}<";
329 if (AR->hasNoUnsignedWrap())
330 OS << "nuw><";
331 if (AR->hasNoSignedWrap())
332 OS << "nsw><";
333 if (AR->hasNoSelfWrap() && !AR->hasNoUnsignedWrap() &&
334 !AR->hasNoSignedWrap())
335 OS << "nw><";
336 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
337 OS << ">";
338 return;
339 }
340 case scAddExpr:
341 case scMulExpr:
342 case scUMaxExpr:
343 case scSMaxExpr:
344 case scUMinExpr:
345 case scSMinExpr:
347 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
348 const char *OpStr = nullptr;
349 switch (NAry->getSCEVType()) {
350 case scAddExpr: OpStr = " + "; break;
351 case scMulExpr: OpStr = " * "; break;
352 case scUMaxExpr: OpStr = " umax "; break;
353 case scSMaxExpr: OpStr = " smax "; break;
354 case scUMinExpr:
355 OpStr = " umin ";
356 break;
357 case scSMinExpr:
358 OpStr = " smin ";
359 break;
361 OpStr = " umin_seq ";
362 break;
363 default:
364 llvm_unreachable("There are no other nary expression types.");
365 }
366 OS << "(" << llvm::interleaved(NAry->operands(), OpStr) << ")";
367 switch (NAry->getSCEVType()) {
368 case scAddExpr:
369 case scMulExpr:
370 if (NAry->hasNoUnsignedWrap())
371 OS << "<nuw>";
372 if (NAry->hasNoSignedWrap())
373 OS << "<nsw>";
374 break;
375 default:
376 // Nothing to print for other nary expressions.
377 break;
378 }
379 return;
380 }
381 case scUDivExpr: {
382 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
383 OS << "(" << UDiv->getLHS() << " /u " << UDiv->getRHS() << ")";
384 return;
385 }
386 case scUnknown:
387 cast<SCEVUnknown>(this)->getValue()->printAsOperand(OS, false);
388 return;
390 OS << "***COULDNOTCOMPUTE***";
391 return;
392 }
393 llvm_unreachable("Unknown SCEV kind!");
394}
395
397 switch (getSCEVType()) {
398 case scConstant:
399 case scVScale:
400 case scUnknown:
401 return {};
402 case scPtrToAddr:
403 case scTruncate:
404 case scZeroExtend:
405 case scSignExtend:
406 return cast<SCEVCastExpr>(this)->operands();
407 case scAddRecExpr:
408 case scAddExpr:
409 case scMulExpr:
410 case scUMaxExpr:
411 case scSMaxExpr:
412 case scUMinExpr:
413 case scSMinExpr:
415 return cast<SCEVNAryExpr>(this)->operands();
416 case scUDivExpr:
417 return cast<SCEVUDivExpr>(this)->operands();
419 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
420 }
421 llvm_unreachable("Unknown SCEV kind!");
422}
423
424bool SCEV::isZero() const { return match(this, m_scev_Zero()); }
425
426bool SCEV::isOne() const { return match(this, m_scev_One()); }
427
428bool SCEV::isAllOnesValue() const { return match(this, m_scev_AllOnes()); }
429
432 if (!Mul) return false;
433
434 // If there is a constant factor, it will be first.
435 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
436 if (!SC) return false;
437
438 // Return true if the value is negative, this matches things like (-42 * V).
439 return SC->getAPInt().isNegative();
440}
441
444
446 return S->getSCEVType() == scCouldNotCompute;
447}
448
450 auto &Entry = ConstantSCEVs[V];
451 if (Entry)
452 return Entry;
453
456 ID.AddPointer(V);
458 if (SCEVConstant *S =
459 static_cast<SCEVConstant *>(UniqueSCEVs.lookup(ID, Token)))
460 return Entry = S;
461 SCEVConstant *S =
462 new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
463 UniqueSCEVs.insert(S, Token);
464 S->computeAndSetCanonical(*this);
465 return Entry = S;
466}
467
469 return getConstant(ConstantInt::get(getContext(), Val));
470}
471
472const SCEV *
475 // TODO: Avoid implicit trunc?
476 // See https://github.com/llvm/llvm-project/issues/112510.
477 return getConstant(
478 ConstantInt::get(ITy, V, isSigned, /*ImplicitTrunc=*/true));
479}
480
484 ID.AddPointer(Ty);
486 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
487 return S;
488 SCEV *S = new (SCEVAllocator) SCEVVScale(ID.Intern(SCEVAllocator), Ty);
489 UniqueSCEVs.insert(S, Token);
490 S->computeAndSetCanonical(*this);
491 return S;
492}
493
495 SCEVFlags Flags) {
496 const SCEV *Res = getConstant(Ty, EC.getKnownMinValue());
497 if (EC.isScalable())
498 Res = getMulExpr(Res, getVScale(Ty), Flags);
499 return Res;
500}
501
503 SCEVUse op, Type *ty)
504 : SCEV(ID, SCEVTy, computeExpressionSize(op), ty), Op(op) {}
505
506SCEVPtrToAddrExpr::SCEVPtrToAddrExpr(const FoldingSetNodeIDRef ID,
507 const SCEV *Op, Type *ITy)
508 : SCEVCastExpr(ID, scPtrToAddr, Op, ITy) {
509 assert(getOperand()->getType()->isPointerTy() && getType()->isIntegerTy() &&
510 "Must be a non-bit-width-changing pointer-to-integer cast!");
511}
512
517
518SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
519 Type *ty)
521 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
522 "Cannot truncate non-integer value!");
523}
524
525SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
526 Type *ty)
528 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
529 "Cannot zero extend non-integer value!");
530}
531
532SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
533 Type *ty)
535 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
536 "Cannot sign extend non-integer value!");
537}
538
540 // Clear this SCEVUnknown from various maps.
541 SE->forgetMemoizedResults({this});
542
543 // Remove this SCEVUnknown from the uniquing map.
544 SE->UniqueSCEVs.erase(this);
545
546 // Release the value.
547 setValPtr(nullptr);
548}
549
550void SCEVUnknown::allUsesReplacedWith(Value *New) {
551 // Clear this SCEVUnknown from various maps.
552 SE->forgetMemoizedResults({this});
553
554 // Remove this SCEVUnknown from the uniquing map.
555 SE->UniqueSCEVs.erase(this);
556
557 // Replace the value pointer in case someone is still using this SCEVUnknown.
558 setValPtr(New);
559}
560
561//===----------------------------------------------------------------------===//
562// SCEV Utilities
563//===----------------------------------------------------------------------===//
564
565/// Compare the two values \p LV and \p RV in terms of their "complexity" where
566/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
567/// operands in SCEV expressions.
568static int CompareValueComplexity(const LoopInfo *const LI, Value *LV,
569 Value *RV, unsigned Depth) {
571 return 0;
572
573 // Order pointer values after integer values. This helps SCEVExpander form
574 // GEPs.
575 bool LIsPointer = LV->getType()->isPointerTy(),
576 RIsPointer = RV->getType()->isPointerTy();
577 if (LIsPointer != RIsPointer)
578 return (int)LIsPointer - (int)RIsPointer;
579
580 // Compare getValueID values.
581 unsigned LID = LV->getValueID(), RID = RV->getValueID();
582 if (LID != RID)
583 return (int)LID - (int)RID;
584
585 // Sort arguments by their position.
586 if (const auto *LA = dyn_cast<Argument>(LV)) {
587 const auto *RA = cast<Argument>(RV);
588 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
589 return (int)LArgNo - (int)RArgNo;
590 }
591
592 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
593 const auto *RGV = cast<GlobalValue>(RV);
594
595 if (auto L = LGV->getLinkage() - RGV->getLinkage())
596 return L;
597
598 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
599 auto LT = GV->getLinkage();
600 return !(GlobalValue::isPrivateLinkage(LT) ||
602 };
603
604 // Use the names to distinguish the two values, but only if the
605 // names are semantically important.
606 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
607 return LGV->getName().compare(RGV->getName());
608 }
609
610 // For instructions, compare their loop depth, and their operand count. This
611 // is pretty loose.
612 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
613 const auto *RInst = cast<Instruction>(RV);
614
615 // Compare loop depths.
616 const BasicBlock *LParent = LInst->getParent(),
617 *RParent = RInst->getParent();
618 if (LParent != RParent) {
619 unsigned LDepth = LI->getLoopDepth(LParent),
620 RDepth = LI->getLoopDepth(RParent);
621 if (LDepth != RDepth)
622 return (int)LDepth - (int)RDepth;
623 }
624
625 // Compare the number of operands.
626 unsigned LNumOps = LInst->getNumOperands(),
627 RNumOps = RInst->getNumOperands();
628 if (LNumOps != RNumOps)
629 return (int)LNumOps - (int)RNumOps;
630
631 for (unsigned Idx : seq(LNumOps)) {
632 int Result = CompareValueComplexity(LI, LInst->getOperand(Idx),
633 RInst->getOperand(Idx), Depth + 1);
634 if (Result != 0)
635 return Result;
636 }
637 }
638
639 return 0;
640}
641
642// Return negative, zero, or positive, if LHS is less than, equal to, or greater
643// than RHS, respectively. A three-way result allows recursive comparisons to be
644// more efficient. The result is a total order.
645static int CompareSCEVComplexity(const LoopInfo *const LI, SCEVUse LHS,
647 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
648 if (LHS == RHS)
649 return 0;
650
651 if (LHS.getPointer() == RHS.getPointer())
652 return (int)LHS.getUseNoWrapFlags() - (int)RHS.getUseNoWrapFlags();
653
654 // Primarily, sort the SCEVs by their getSCEVType().
655 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
656 if (LType != RType)
657 return (int)LType - (int)RType;
658
659 // Aside from the getSCEVType() ordering, the particular ordering
660 // isn't very important except that it's beneficial to be consistent,
661 // so that (a + b) and (b + a) don't end up as different expressions.
662 switch (LType) {
663 case scUnknown: {
664 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
665 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
666
667 if (int X = CompareValueComplexity(LI, LU->getValue(), RU->getValue(),
668 /*Depth=*/0))
669 return X;
670 return LU->getOrderID() < RU->getOrderID() ? -1 : 1;
671 }
672
673 case scConstant: {
676
677 // Compare constant values.
678 const APInt &LA = LC->getAPInt();
679 const APInt &RA = RC->getAPInt();
680 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
681 if (LBitWidth != RBitWidth)
682 return (int)LBitWidth - (int)RBitWidth;
683 return LA.ult(RA) ? -1 : 1;
684 }
685
686 case scVScale: {
687 const auto *LTy = cast<IntegerType>(cast<SCEVVScale>(LHS)->getType());
688 const auto *RTy = cast<IntegerType>(cast<SCEVVScale>(RHS)->getType());
689 return LTy->getBitWidth() - RTy->getBitWidth();
690 }
691
692 case scAddRecExpr: {
695
696 // There is always a dominance between two recs that are used by one SCEV,
697 // so we can safely sort recs by loop header dominance. We require such
698 // order in getAddExpr.
699 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
700 if (LLoop != RLoop) {
701 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
702 assert(LHead != RHead && "Two loops share the same header?");
703 if (DT.dominates(LHead, RHead))
704 return 1;
705 assert(DT.dominates(RHead, LHead) &&
706 "No dominance between recurrences used by one SCEV?");
707 return -1;
708 }
709
710 [[fallthrough]];
711 }
712
713 case scTruncate:
714 case scZeroExtend:
715 case scSignExtend:
716 case scPtrToAddr:
717 case scAddExpr:
718 case scMulExpr:
719 case scUDivExpr:
720 case scSMaxExpr:
721 case scUMaxExpr:
722 case scSMinExpr:
723 case scUMinExpr:
725 ArrayRef<SCEVUse> LOps = LHS->operands();
726 ArrayRef<SCEVUse> ROps = RHS->operands();
727
728 // Lexicographically compare n-ary-like expressions.
729 unsigned LNumOps = LOps.size(), RNumOps = ROps.size();
730 if (LNumOps != RNumOps)
731 return (int)LNumOps - (int)RNumOps;
732
733 for (unsigned i = 0; i != LNumOps; ++i) {
734 auto X = CompareSCEVComplexity(LI, LOps[i], ROps[i], DT);
735 if (X != 0)
736 return X;
737 }
738
739 assert(isa<SCEVCastExpr>(LHS) && "distinct SCEVs compare equal");
740 unsigned LBitWidth = cast<IntegerType>(LHS->getType())->getBitWidth();
741 unsigned RBitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
742 assert(LBitWidth != RBitWidth && "distinct SCEVs compare equal");
743 return (int)LBitWidth - (int)RBitWidth;
744 }
745
747 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
748 }
749 llvm_unreachable("Unknown SCEV kind!");
750}
751
752/// Given a list of SCEV objects, order them by their complexity, and group
753/// objects of the same complexity together by value. When this routine is
754/// finished, we know that any duplicates in the vector are consecutive and that
755/// complexity is monotonically increasing.
756///
757/// Note that we go take special precautions to ensure that we get deterministic
758/// results from this routine. In other words, we don't want the results of
759/// this to depend on where the addresses of various SCEV objects happened to
760/// land in memory.
762 DominatorTree &DT) {
763 if (Ops.size() < 2) return; // Noop
764
765 // Whether LHS has provably less complexity than RHS.
766 auto IsLessComplex = [&](SCEVUse LHS, SCEVUse RHS) {
767 return CompareSCEVComplexity(LI, LHS, RHS, DT) < 0;
768 };
769 if (Ops.size() == 2) {
770 // This is the common case, which also happens to be trivially simple.
771 // Special case it.
772 SCEVUse &LHS = Ops[0], &RHS = Ops[1];
773 if (IsLessComplex(RHS, LHS))
774 std::swap(LHS, RHS);
775 return;
776 }
777
778 llvm::sort(Ops, IsLessComplex);
779}
780
781/// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
782/// least HugeExprThreshold nodes).
784 return any_of(Ops, [](const SCEV *S) {
786 });
787}
788
789/// Performs a number of common optimizations on the passed \p Ops. If the
790/// whole expression reduces down to a single operand, it will be returned.
791///
792/// The following optimizations are performed:
793/// * Fold constants using the \p Fold function.
794/// * Remove identity constants satisfying \p IsIdentity.
795/// * If a constant satisfies \p IsAbsorber, return it.
796/// * Sort operands by complexity.
797template <typename FoldT, typename IsIdentityT, typename IsAbsorberT>
798static const SCEV *
800 SmallVectorImpl<SCEVUse> &Ops, FoldT Fold,
801 IsIdentityT IsIdentity, IsAbsorberT IsAbsorber) {
802 const SCEVConstant *Folded = nullptr;
803 for (unsigned Idx = 0; Idx < Ops.size();) {
804 const SCEV *Op = Ops[Idx];
805 if (const auto *C = dyn_cast<SCEVConstant>(Op)) {
806 if (!Folded)
807 Folded = C;
808 else
809 Folded = cast<SCEVConstant>(
810 SE.getConstant(Fold(Folded->getAPInt(), C->getAPInt())));
811 Ops.erase(Ops.begin() + Idx);
812 continue;
813 }
814 ++Idx;
815 }
816
817 if (Ops.empty()) {
818 assert(Folded && "Must have folded value");
819 return Folded;
820 }
821
822 if (Folded && IsAbsorber(Folded->getAPInt()))
823 return Folded;
824
825 GroupByComplexity(Ops, &LI, DT);
826 if (Folded && !IsIdentity(Folded->getAPInt()))
827 Ops.insert(Ops.begin(), Folded);
828
829 return Ops.size() == 1 ? Ops[0] : nullptr;
830}
831
832//===----------------------------------------------------------------------===//
833// Simple SCEV method implementations
834//===----------------------------------------------------------------------===//
835
836/// Compute BC(It, K). The result has width W. Assume, K > 0.
837static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
838 ScalarEvolution &SE,
839 Type *ResultTy) {
840 // Handle the simplest case efficiently.
841 if (K == 1)
842 return SE.getTruncateOrZeroExtend(It, ResultTy);
843
844 // We are using the following formula for BC(It, K):
845 //
846 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
847 //
848 // Suppose, W is the bitwidth of the return value. We must be prepared for
849 // overflow. Hence, we must assure that the result of our computation is
850 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
851 // safe in modular arithmetic.
852 //
853 // However, this code doesn't use exactly that formula; the formula it uses
854 // is something like the following, where T is the number of factors of 2 in
855 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
856 // exponentiation:
857 //
858 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
859 //
860 // This formula is trivially equivalent to the previous formula. However,
861 // this formula can be implemented much more efficiently. The trick is that
862 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
863 // arithmetic. To do exact division in modular arithmetic, all we have
864 // to do is multiply by the inverse. Therefore, this step can be done at
865 // width W.
866 //
867 // The next issue is how to safely do the division by 2^T. The way this
868 // is done is by doing the multiplication step at a width of at least W + T
869 // bits. This way, the bottom W+T bits of the product are accurate. Then,
870 // when we perform the division by 2^T (which is equivalent to a right shift
871 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
872 // truncated out after the division by 2^T.
873 //
874 // In comparison to just directly using the first formula, this technique
875 // is much more efficient; using the first formula requires W * K bits,
876 // but this formula less than W + K bits. Also, the first formula requires
877 // a division step, whereas this formula only requires multiplies and shifts.
878 //
879 // It doesn't matter whether the subtraction step is done in the calculation
880 // width or the input iteration count's width; if the subtraction overflows,
881 // the result must be zero anyway. We prefer here to do it in the width of
882 // the induction variable because it helps a lot for certain cases; CodeGen
883 // isn't smart enough to ignore the overflow, which leads to much less
884 // efficient code if the width of the subtraction is wider than the native
885 // register width.
886 //
887 // (It's possible to not widen at all by pulling out factors of 2 before
888 // the multiplication; for example, K=2 can be calculated as
889 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
890 // extra arithmetic, so it's not an obvious win, and it gets
891 // much more complicated for K > 3.)
892
893 // Protection from insane SCEVs; this bound is conservative,
894 // but it probably doesn't matter.
895 if (K > 1000)
896 return SE.getCouldNotCompute();
897
898 unsigned W = SE.getTypeSizeInBits(ResultTy);
899
900 // Calculate K! / 2^T and T; we divide out the factors of two before
901 // multiplying for calculating K! / 2^T to avoid overflow.
902 // Other overflow doesn't matter because we only care about the bottom
903 // W bits of the result.
904 APInt OddFactorial(W, 1);
905 unsigned T = 1;
906 for (unsigned i = 3; i <= K; ++i) {
907 unsigned TwoFactors = countr_zero(i);
908 T += TwoFactors;
909 OddFactorial *= (i >> TwoFactors);
910 }
911
912 // We need at least W + T bits for the multiplication step
913 unsigned CalculationBits = W + T;
914
915 // Calculate 2^T, at width T+W.
916 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
917
918 // Calculate the multiplicative inverse of K! / 2^T;
919 // this multiplication factor will perform the exact division by
920 // K! / 2^T.
921 APInt MultiplyFactor = OddFactorial.multiplicativeInverse();
922
923 // Calculate the product, at width T+W
924 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
925 CalculationBits);
926 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
927 for (unsigned i = 1; i != K; ++i) {
928 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
929 Dividend = SE.getMulExpr(Dividend,
930 SE.getTruncateOrZeroExtend(S, CalculationTy));
931 }
932
933 // Divide by 2^T
934 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
935
936 // Truncate the result, and divide by K! / 2^T.
937
938 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
939 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
940}
941
942/// Return the value of this chain of recurrences at the specified iteration
943/// number. We can evaluate this recurrence by multiplying each element in the
944/// chain by the binomial coefficient corresponding to it. In other words, we
945/// can evaluate {A,+,B,+,C,+,D} as:
946///
947/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
948///
949/// where BC(It, k) stands for binomial coefficient.
951 ScalarEvolution &SE) const {
952 return evaluateAtIteration(operands(), It, SE);
953}
954
956 const SCEV *It, ScalarEvolution &SE,
957 SCEVFlags UseFlags) {
958 assert(Operands.size() > 0);
959 assert((Operands.size() == 2 || UseFlags == SCEV::FlagNone) &&
960 "use-specific flags only supported for affine AddRecs");
961 SCEVUse Result = Operands[0].getPointer();
962 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
963 // The computation is correct in the face of overflow provided that the
964 // multiplication is performed _after_ the evaluation of the binomial
965 // coefficient.
966 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
967 if (isa<SCEVCouldNotCompute>(Coeff))
968 return Coeff;
969
970 SCEVUse Mul = SE.getMulExpr(Operands[i].getPointer(), Coeff,
971 {SCEV::FlagNone, UseFlags});
972 Result = SE.getAddExpr(Result, Mul, {SCEV::FlagNone, UseFlags});
973 }
974 return Result;
975}
976
978 const SCEV *BTC = SE.getBackedgeTakenCount(getLoop());
980 return BTC;
981 // The loop reaches iteration BTC, so the value this recurrence computes there
982 // is the value it had, and that did not wrap.
983 return evaluateAtIteration(operands(), BTC, SE,
986}
987
988//===----------------------------------------------------------------------===//
989// SCEV Expression folder implementations
990//===----------------------------------------------------------------------===//
991
992/// The SCEVCastSinkingRewriter takes a scalar evolution expression,
993/// which computes a pointer-typed value, and rewrites the whole expression
994/// tree so that *all* the computations are done on integers, and the only
995/// pointer-typed operands in the expression are SCEVUnknown.
996/// The CreatePtrCast callback is invoked to create the actual conversion
997/// (ptrtoint or ptrtoaddr) at the SCEVUnknown leaves.
999 : public SCEVRewriteVisitor<SCEVCastSinkingRewriter> {
1001 using ConversionFn = function_ref<const SCEV *(const SCEVUnknown *)>;
1002 Type *TargetTy;
1003 ConversionFn CreatePtrCast;
1004
1005public:
1007 ConversionFn CreatePtrCast)
1008 : Base(SE), TargetTy(TargetTy), CreatePtrCast(std::move(CreatePtrCast)) {}
1009
1010 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
1011 Type *TargetTy, ConversionFn CreatePtrCast) {
1012 SCEVCastSinkingRewriter Rewriter(SE, TargetTy, std::move(CreatePtrCast));
1013 return Rewriter.visit(Scev);
1014 }
1015
1016 const SCEV *visit(const SCEV *S) {
1017 Type *STy = S->getType();
1018 // If the expression is not pointer-typed, just keep it as-is.
1019 if (!STy->isPointerTy())
1020 return S;
1021 // Else, recursively sink the cast down into it.
1022 return Base::visit(S);
1023 }
1024
1025 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1026 // Preserve wrap flags on rewritten SCEVAddExpr, which the default
1027 // implementation drops.
1029 bool Changed = false;
1030 for (SCEVUse Op : Expr->operands()) {
1031 Operands.push_back(visit(Op.getPointer()));
1032 Changed |= Op.getPointer() != Operands.back();
1033 }
1034 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1035 }
1036
1037 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1038 assert(Expr->getType()->isPointerTy() &&
1039 "Should only reach pointer-typed SCEVUnknown's.");
1040 // Perform some basic constant folding. If the operand of the cast is a
1041 // null pointer, don't create a cast SCEV expression (that will be left
1042 // as-is), but produce a zero constant.
1044 return SE.getZero(TargetTy);
1045 return CreatePtrCast(Expr);
1046 }
1047};
1048
1050 assert(Op->getType()->isPointerTy() && "Op must be a pointer");
1051
1052 // Treat pointers with unstable representation conservatively, since the
1053 // address bits may change.
1054 if (DL.hasUnstableRepresentation(Op->getType()))
1055 return getCouldNotCompute();
1056
1057 Type *Ty = DL.getAddressType(Op->getType());
1058
1059 // Use the rewriter to sink the cast down to SCEVUnknown leaves.
1060 // The rewriter handles null pointer constant folding.
1062 Op, *this, Ty, [this, Ty](const SCEVUnknown *U) {
1065 ID.AddPointer(U);
1066 ID.AddPointer(Ty);
1068 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1069 return S;
1070 SCEV *S = new (SCEVAllocator)
1071 SCEVPtrToAddrExpr(ID.Intern(SCEVAllocator), U, Ty);
1072 UniqueSCEVs.insert(S, Token);
1073 S->computeAndSetCanonical(*this);
1074 registerUser(S, {U});
1075 return static_cast<const SCEV *>(S);
1076 });
1077 assert(IntOp->getType()->isIntegerTy() &&
1078 "We must have succeeded in sinking the cast, "
1079 "and ending up with an integer-typed expression!");
1080 return IntOp;
1081}
1082
1084 unsigned Depth) {
1085 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1086 "This is not a truncating conversion!");
1087 assert(isSCEVable(Ty) &&
1088 "This is not a conversion to a SCEVable type!");
1089 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1090 Ty = getEffectiveSCEVType(Ty);
1091
1094 ID.AddPointer(Op.getOpaqueValue());
1095 ID.AddPointer(Ty);
1097 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1098 return S;
1099
1100 // Fold if the operand is constant.
1101 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1102 return getConstant(
1103 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1104
1105 // trunc(trunc(x)) --> trunc(x)
1107 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1108
1109 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1111 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1112
1113 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1115 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1116
1117 if (Depth > MaxCastDepth) {
1118 SCEV *S =
1119 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1120 UniqueSCEVs.insert(S, Token);
1121 S->computeAndSetCanonical(*this);
1122 registerUser(S, Op);
1123 return S;
1124 }
1125
1126 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1127 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1128 // if after transforming we have at most one truncate, not counting truncates
1129 // that replace other casts.
1131 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1133 unsigned numTruncs = 0;
1134 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1135 ++i) {
1136 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1137 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1139 numTruncs++;
1140 Operands.push_back(S);
1141 }
1142 if (numTruncs < 2) {
1143 if (isa<SCEVAddExpr>(Op))
1144 return getAddExpr(Operands);
1145 if (isa<SCEVMulExpr>(Op))
1146 return getMulExpr(Operands);
1147 llvm_unreachable("Unexpected SCEV type for Op.");
1148 }
1149 // Although we checked in the beginning that ID is not in the cache, it is
1150 // possible that during recursion and different modification ID was inserted
1151 // into the cache. So if we find it, just return it.
1152 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1153 return S;
1154 }
1155
1156 // If the input value is a chrec scev, truncate the chrec's operands.
1157 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1159 for (const SCEV *Op : AddRec->operands())
1160 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1161 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagNone);
1162 }
1163
1164 // Return zero if truncating to known zeros.
1165 uint32_t MinTrailingZeros = getMinTrailingZeros(Op);
1166 if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1167 return getZero(Ty);
1168
1169 // The cast wasn't folded; create an explicit cast node. We can reuse
1170 // the existing insert position since if we get here, we won't have
1171 // made any changes which would invalidate it.
1172 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1173 Op, Ty);
1174 UniqueSCEVs.insert(S, Token);
1175 S->computeAndSetCanonical(*this);
1176 registerUser(S, Op);
1177 return S;
1178}
1179
1180// Get the limit of a recurrence such that incrementing by Step cannot cause
1181// signed overflow as long as the value of the recurrence within the
1182// loop does not exceed this limit before incrementing.
1183static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1184 ICmpInst::Predicate *Pred,
1185 ScalarEvolution *SE) {
1186 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1187 if (SE->isKnownPositive(Step)) {
1188 *Pred = ICmpInst::ICMP_SLT;
1190 SE->getSignedRangeMax(Step));
1191 }
1192 if (SE->isKnownNegative(Step)) {
1193 *Pred = ICmpInst::ICMP_SGT;
1195 SE->getSignedRangeMin(Step));
1196 }
1197 return nullptr;
1198}
1199
1200// Get the limit of a recurrence such that incrementing by Step cannot cause
1201// unsigned overflow as long as the value of the recurrence within the loop does
1202// not exceed this limit before incrementing.
1204 ICmpInst::Predicate *Pred,
1205 ScalarEvolution *SE) {
1206 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1207 *Pred = ICmpInst::ICMP_ULT;
1208
1210 SE->getUnsignedRangeMax(Step));
1211}
1212
1213namespace {
1214
1215struct ExtendOpTraitsBase {
1216 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(SCEVUse, Type *,
1217 unsigned);
1218};
1219
1220// Used to make code generic over signed and unsigned overflow.
1221template <typename ExtendOp> struct ExtendOpTraits {
1222 // Members present:
1223 //
1224 // static const SCEVFlags WrapType;
1225 //
1226 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1227 //
1228 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1229 // ICmpInst::Predicate *Pred,
1230 // ScalarEvolution *SE);
1231};
1232
1233template <>
1234struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1235 static const SCEVFlags WrapType = SCEV::FlagNSW;
1236
1237 static const GetExtendExprTy GetExtendExpr;
1238
1239 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1240 ICmpInst::Predicate *Pred,
1241 ScalarEvolution *SE) {
1242 return getSignedOverflowLimitForStep(Step, Pred, SE);
1243 }
1244};
1245
1246const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1248
1249template <>
1250struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1251 static const SCEVFlags WrapType = SCEV::FlagNUW;
1252
1253 static const GetExtendExprTy GetExtendExpr;
1254
1255 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1256 ICmpInst::Predicate *Pred,
1257 ScalarEvolution *SE) {
1258 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1259 }
1260};
1261
1262const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1264
1265} // end anonymous namespace
1266
1267// The recurrence AR has been shown to have no signed/unsigned wrap or something
1268// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1269// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1270// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1271// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1272// expression "Step + sext/zext(PreIncAR)" is congruent with
1273// "sext/zext(PostIncAR)"
1274template <typename ExtendOpTy>
1276 ScalarEvolution *SE, unsigned Depth) {
1277 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1278 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1279
1280 const Loop *L = AR->getLoop();
1281 const SCEV *Start = AR->getStart();
1282 const SCEV *Step = AR->getStepRecurrence(*SE);
1283
1284 // Check for a simple looking step prior to loop entry.
1285 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1286 if (!SA)
1287 return nullptr;
1288
1289 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1290 // subtraction is expensive. For this purpose, perform a quick and dirty
1291 // difference, by checking for Step in the operand list. Note, that
1292 // SA might have repeated ops, like %a + %a + ..., so only remove one.
1293 SmallVector<SCEVUse, 4> DiffOps(SA->operands());
1294 for (auto It = DiffOps.begin(); It != DiffOps.end(); ++It)
1295 if (*It == Step) {
1296 DiffOps.erase(It);
1297 break;
1298 }
1299
1300 if (DiffOps.size() == SA->getNumOperands())
1301 return nullptr;
1302
1303 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1304 // `Step`:
1305
1306 // 1. NSW/NUW flags on the step increment.
1307 auto PreStartFlags =
1309 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1311 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagNone));
1312
1313 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1314 // "S+X does not sign/unsign-overflow".
1315 //
1316
1317 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1318 if (PreAR && any(PreAR->getNoWrapFlags(WrapType)) &&
1319 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1320 return PreStart;
1321
1322 // 2. Direct overflow check on the step operation's expression.
1323 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1324 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1325 const SCEV *OperandExtendedStart =
1326 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1327 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1328 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1329 if (PreAR && any(AR->getNoWrapFlags(WrapType))) {
1330 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1331 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1332 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1333 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1334 }
1335 return PreStart;
1336 }
1337
1338 // 3. Loop precondition.
1340 const SCEV *OverflowLimit =
1341 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1342
1343 if (OverflowLimit &&
1344 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1345 return PreStart;
1346
1347 return nullptr;
1348}
1349
1350// Get the normalized zero or sign extended expression for this AddRec's Start.
1351template <typename ExtendOpTy>
1352static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1353 ScalarEvolution *SE,
1354 unsigned Depth) {
1355 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1356
1357 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, SE, Depth);
1358 if (!PreStart)
1359 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1360
1361 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1362 Depth),
1363 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1364}
1365
1366// Try to prove away overflow by looking at "nearby" add recurrences. A
1367// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1368// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1369//
1370// Formally:
1371//
1372// {S,+,X} == {S-T,+,X} + T
1373// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1374//
1375// If ({S-T,+,X} + T) does not overflow ... (1)
1376//
1377// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1378//
1379// If {S-T,+,X} does not overflow ... (2)
1380//
1381// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1382// == {Ext(S-T)+Ext(T),+,Ext(X)}
1383//
1384// If (S-T)+T does not overflow ... (3)
1385//
1386// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1387// == {Ext(S),+,Ext(X)} == LHS
1388//
1389// Thus, if (1), (2) and (3) are true for some T, then
1390// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1391//
1392// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1393// does not overflow" restricted to the 0th iteration. Therefore we only need
1394// to check for (1) and (2).
1395//
1396// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1397// is `Delta` (defined below).
1398template <typename ExtendOpTy>
1399bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1400 const SCEV *Step,
1401 const Loop *L) {
1402 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1403
1404 // We restrict `Start` to a constant to prevent SCEV from spending too much
1405 // time here. It is correct (but more expensive) to continue with a
1406 // non-constant `Start` and do a general SCEV subtraction to compute
1407 // `PreStart` below.
1408 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1409 if (!StartC)
1410 return false;
1411
1412 APInt StartAI = StartC->getAPInt();
1413
1414 for (unsigned Delta : {-2, -1, 1, 2}) {
1415 const SCEV *PreStart = getConstant(StartAI - Delta);
1416 const auto *PreAR = static_cast<SCEVAddRecExpr *>(
1417 findExistingSCEVInCache(scAddRecExpr, {PreStart, Step}, L));
1418
1419 // Give up if we don't already have the add recurrence we need because
1420 // actually constructing an add recurrence is relatively expensive.
1421 if (PreAR && any(PreAR->getNoWrapFlags(WrapType))) { // proves (2)
1422 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1424 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1425 DeltaS, &Pred, this);
1426 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1427 return true;
1428 }
1429 }
1430
1431 return false;
1432}
1433
1434// Finds an integer D for an expression (C + x + y + ...) such that the top
1435// level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1436// unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1437// maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1438// the (C + x + y + ...) expression is \p WholeAddExpr.
1440 const SCEVConstant *ConstantTerm,
1441 const SCEVAddExpr *WholeAddExpr) {
1442 const APInt &C = ConstantTerm->getAPInt();
1443 const unsigned BitWidth = C.getBitWidth();
1444 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1445 uint32_t TZ = BitWidth;
1446 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1447 TZ = std::min(TZ, SE.getMinTrailingZeros(WholeAddExpr->getOperand(I)));
1448 if (TZ) {
1449 // Set D to be as many least significant bits of C as possible while still
1450 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1451 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1452 }
1453 return APInt(BitWidth, 0);
1454}
1455
1456// Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1457// level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1458// number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1459// ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1461 const APInt &ConstantStart,
1462 const SCEV *Step) {
1463 const unsigned BitWidth = ConstantStart.getBitWidth();
1464 const uint32_t TZ = SE.getMinTrailingZeros(Step);
1465 if (TZ)
1466 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1467 : ConstantStart;
1468 return APInt(BitWidth, 0);
1469}
1470
1472 const ScalarEvolution::FoldID &ID, const SCEV *S,
1475 &FoldCacheUser) {
1476 auto I = FoldCache.insert({ID, S});
1477 if (!I.second) {
1478 // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1479 // entry.
1480 auto &UserIDs = FoldCacheUser[I.first->second];
1481 assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
1482 for (unsigned I = 0; I != UserIDs.size(); ++I)
1483 if (UserIDs[I] == ID) {
1484 std::swap(UserIDs[I], UserIDs.back());
1485 break;
1486 }
1487 UserIDs.pop_back();
1488 I.first->second = S;
1489 }
1490 FoldCacheUser[S].push_back(ID);
1491}
1492
1494 unsigned Depth) {
1495 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1496 "This is not an extending conversion!");
1497 assert(isSCEVable(Ty) &&
1498 "This is not a conversion to a SCEVable type!");
1499 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1500 Ty = getEffectiveSCEVType(Ty);
1501
1502 FoldID ID(scZeroExtend, Op, Ty);
1503 if (const SCEV *S = FoldCache.lookup(ID))
1504 return S;
1505
1506 const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1508 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1509 return S;
1510}
1511
1513 unsigned Depth) {
1514 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1515 "This is not an extending conversion!");
1516 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1517 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1518
1519 // Fold if the operand is constant.
1520 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1521 return getConstant(SC->getAPInt().zext(getTypeSizeInBits(Ty)));
1522
1523 // zext(zext(x)) --> zext(x)
1525 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1526
1527 // If the operand is an affine AddRec with the no-unsigned-wrap flag, the
1528 // zero-extension distributes over the recurrence.
1529 const SCEV *Start, *Step;
1530 const Loop *L;
1531 if (Depth <= MaxCastDepth &&
1532 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1533 const auto *AR = cast<SCEVAddRecExpr>(Op);
1534 if (AR->hasNoUnsignedWrap()) {
1535 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1536 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1537 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1538 }
1539 }
1540
1541 // Before doing any expensive analysis, check to see if we've already
1542 // computed a SCEV for this Op and Ty.
1545 ID.AddPointer(Op.getOpaqueValue());
1546 ID.AddPointer(Ty);
1548 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1549 return S;
1550 if (Depth > MaxCastDepth) {
1551 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1552 Op, Ty);
1553 UniqueSCEVs.insert(S, Token);
1554 S->computeAndSetCanonical(*this);
1555 registerUser(S, Op);
1556 return S;
1557 }
1558
1559 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1561 // It's possible the bits taken off by the truncate were all zero bits. If
1562 // so, we should be able to simplify this further.
1563 const SCEV *X = ST->getOperand();
1565 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1566 unsigned NewBits = getTypeSizeInBits(Ty);
1567 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1568 CR.zextOrTrunc(NewBits)))
1569 return getTruncateOrZeroExtend(X, Ty, Depth);
1570 }
1571
1572 // If the input value is a chrec scev, and we can prove that the value
1573 // did not overflow the old, smaller, value, we can zero extend all of the
1574 // operands (often constants). This allows analysis of something like
1575 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1576 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1577 const auto *AR = cast<SCEVAddRecExpr>(Op);
1578 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1579
1580 // The no-unsigned-wrap case is handled before the uniquing lookup above.
1581
1582 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1583 // Note that this serves two purposes: It filters out loops that are
1584 // simply not analyzable, and it covers the case where this code is
1585 // being called from within backedge-taken count analysis, such that
1586 // attempting to ask for the backedge-taken count would likely result
1587 // in infinite recursion. In the later case, the analysis code will
1588 // cope with a conservative value, and it will take care to purge
1589 // that value once it has finished.
1590 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1591 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1592 // Manually compute the final value for AR, checking for overflow.
1593
1594 // Check whether the backedge-taken count can be losslessly casted to
1595 // the addrec's type. The count is always unsigned.
1596 const SCEV *CastedMaxBECount =
1597 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1598 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1599 CastedMaxBECount, MaxBECount->getType(), Depth);
1600 if (MaxBECount == RecastedMaxBECount) {
1601 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1602 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1603 const SCEV *ZMul =
1604 getMulExpr(CastedMaxBECount, Step, SCEV::FlagNone, Depth + 1);
1605 const SCEV *ZAdd = getZeroExtendExpr(
1606 getAddExpr(Start, ZMul, SCEV::FlagNone, Depth + 1), WideTy,
1607 Depth + 1);
1608 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1609 const SCEV *WideMaxBECount =
1610 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1611 const SCEV *OperandExtendedAdd =
1612 getAddExpr(WideStart,
1613 getMulExpr(WideMaxBECount,
1614 getZeroExtendExpr(Step, WideTy, Depth + 1),
1615 SCEV::FlagNone, Depth + 1),
1616 SCEV::FlagNone, Depth + 1);
1617 if (ZAdd == OperandExtendedAdd) {
1618 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1619 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1620 // Return the expression with the addrec on the outside.
1621 Start =
1623 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1624 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1625 }
1626 // Similar to above, only this time treat the step value as signed.
1627 // This covers loops that count down.
1628 OperandExtendedAdd =
1629 getAddExpr(WideStart,
1630 getMulExpr(WideMaxBECount,
1631 getSignExtendExpr(Step, WideTy, Depth + 1),
1632 SCEV::FlagNone, Depth + 1),
1633 SCEV::FlagNone, Depth + 1);
1634 if (ZAdd == OperandExtendedAdd) {
1635 // Cache knowledge of AR NW, which is propagated to this AddRec.
1636 // Negative step causes unsigned wrap, but it still can't self-wrap.
1637 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1638 // Return the expression with the addrec on the outside.
1639 Start =
1641 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1642 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1643 }
1644 }
1645 }
1646
1647 // Normally, in the cases we can prove no-overflow via a
1648 // backedge guarding condition, we can also compute a backedge
1649 // taken count for the loop. The exceptions are assumptions and
1650 // guards present in the loop -- SCEV is not great at exploiting
1651 // these to compute max backedge taken counts, but can still use
1652 // these to prove lack of overflow. Use this fact to avoid
1653 // doing extra work that may not pay off.
1654 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1655 !AC.assumptions().empty()) {
1656
1657 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1658 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1659 if (AR->hasNoUnsignedWrap()) {
1660 // Same as nuw case above - duplicated here to avoid a compile time
1661 // issue. It's not clear that the order of checks does matter, but
1662 // it's one of two issue possible causes for a change which was
1663 // reverted. Be conservative for the moment.
1664 Start =
1666 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1667 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1668 }
1669
1670 // For a negative step, we can extend the operands iff doing so only
1671 // traverses values in the range zext([0,UINT_MAX]).
1672 if (isKnownNegative(Step)) {
1673 const SCEV *N =
1677 // Cache knowledge of AR NW, which is propagated to this
1678 // AddRec. Negative step causes unsigned wrap, but it
1679 // still can't self-wrap.
1680 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1681 // Return the expression with the addrec on the outside.
1682 Start =
1684 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1685 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1686 }
1687 }
1688 }
1689
1690 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1691 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1692 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1693 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1694 const APInt &C = SC->getAPInt();
1695 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1696 if (D != 0) {
1697 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1698 const SCEV *SResidual =
1699 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1700 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1701 return getAddExpr(SZExtD, SZExtR, SCEV::FlagNSW | SCEV::FlagNUW,
1702 Depth + 1);
1703 }
1704 }
1705
1706 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1707 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1708 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1709 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1710 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1711 }
1712 }
1713
1714 // zext(A % B) --> zext(A) % zext(B)
1715 {
1716 const SCEV *LHS;
1717 const SCEV *RHS;
1718 if (match(Op, m_scev_URem(m_SCEV(LHS), m_SCEV(RHS), *this)))
1719 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1720 getZeroExtendExpr(RHS, Ty, Depth + 1));
1721 }
1722
1723 // zext(A / B) --> zext(A) / zext(B).
1724 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1725 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1726 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1727
1728 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1729 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1730 if (SA->hasNoUnsignedWrap()) {
1731 // If the addition does not unsign overflow then we can, by definition,
1732 // commute the zero extension with the addition operation.
1734 for (SCEVUse Op : SA->operands())
1735 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1736 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1737 }
1738
1739 const APInt *C, *C2;
1740 // zext (C + A)<nsw> -> (sext(C) + sext(A))<nsw> if zext (C + A)<nsw> >=s 0.
1741 // Currently the non-negative check is done manually, as isKnownNonNegative
1742 // is too expensive.
1743 if (SA->hasNoSignedWrap() &&
1745 m_scev_SMax(m_scev_APInt(C2), m_SCEV()))) &&
1746 C->isNegative() && !C->isMinSignedValue() && C2->sge(C->abs())) {
1747 assert(isKnownNonNegative(SA) && "incorrectly determined non-negative");
1748 return getAddExpr(getSignExtendExpr(SA->getOperand(0), Ty, Depth + 1),
1749 getSignExtendExpr(SA->getOperand(1), Ty, Depth + 1),
1750 SCEV::FlagNSW, Depth + 1);
1751 }
1752
1753 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1754 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1755 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1756 //
1757 // Often address arithmetics contain expressions like
1758 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1759 // This transformation is useful while proving that such expressions are
1760 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1761 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1762 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1763 if (D != 0) {
1764 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1765 const SCEV *SResidual =
1767 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1768 return getAddExpr(SZExtD, SZExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1769 Depth + 1);
1770 }
1771 }
1772 }
1773
1774 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1775 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1776 if (SM->hasNoUnsignedWrap()) {
1777 // If the multiply does not unsign overflow then we can, by definition,
1778 // commute the zero extension with the multiply operation.
1780 for (SCEVUse Op : SM->operands())
1781 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1782 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1783 }
1784
1785 // zext(2^K * (trunc X to iN)) to iM ->
1786 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1787 //
1788 // Proof:
1789 //
1790 // zext(2^K * (trunc X to iN)) to iM
1791 // = zext((trunc X to iN) << K) to iM
1792 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1793 // (because shl removes the top K bits)
1794 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1795 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1796 //
1797 const APInt *C;
1798 const SCEV *TruncRHS;
1799 if (match(SM,
1800 m_scev_Mul(m_scev_APInt(C), m_scev_Trunc(m_SCEV(TruncRHS)))) &&
1801 C->isPowerOf2()) {
1802 int NewTruncBits =
1803 getTypeSizeInBits(SM->getOperand(1)->getType()) - C->logBase2();
1804 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1805 return getMulExpr(
1806 getZeroExtendExpr(SM->getOperand(0), Ty),
1807 getZeroExtendExpr(getTruncateExpr(TruncRHS, NewTruncTy), Ty),
1808 SCEV::FlagNUW, Depth + 1);
1809 }
1810 }
1811
1812 // zext(umin(x, y)) -> umin(zext(x), zext(y))
1813 // zext(umax(x, y)) -> umax(zext(x), zext(y))
1817 for (SCEVUse Operand : MinMax->operands())
1818 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1820 return getUMinExpr(Operands);
1821 return getUMaxExpr(Operands);
1822 }
1823
1824 // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
1826 assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!");
1828 for (SCEVUse Operand : MinMax->operands())
1829 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1830 return getUMinExpr(Operands, /*Sequential*/ true);
1831 }
1832
1833 // The cast wasn't folded; create an explicit cast node.
1834 // Recompute the insert position, as it may have been invalidated.
1835 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1836 return S;
1837 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1838 Op, Ty);
1839 UniqueSCEVs.insert(S, Token);
1840 S->computeAndSetCanonical(*this);
1841 registerUser(S, Op);
1842 return S;
1843}
1844
1846 unsigned Depth) {
1847 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1848 "This is not an extending conversion!");
1849 assert(isSCEVable(Ty) &&
1850 "This is not a conversion to a SCEVable type!");
1851 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1852 Ty = getEffectiveSCEVType(Ty);
1853
1854 FoldID ID(scSignExtend, Op, Ty);
1855 if (const SCEV *S = FoldCache.lookup(ID))
1856 return S;
1857
1858 const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
1860 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1861 return S;
1862}
1863
1865 unsigned Depth) {
1866 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1867 "This is not an extending conversion!");
1868 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1869 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1870 Ty = getEffectiveSCEVType(Ty);
1871
1872 // Fold if the operand is constant.
1873 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1874 return getConstant(SC->getAPInt().sext(getTypeSizeInBits(Ty)));
1875
1876 // sext(sext(x)) --> sext(x)
1878 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1879
1880 // sext(zext(x)) --> zext(x)
1882 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1883
1884 // If the operand is an affine AddRec with the no-signed-wrap flag, the
1885 // sign-extension distributes over the recurrence.
1886 const SCEV *Start, *Step;
1887 const Loop *L;
1888 if (Depth <= MaxCastDepth &&
1889 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1890 const auto *AR = cast<SCEVAddRecExpr>(Op);
1891 if (AR->hasNoSignedWrap()) {
1892 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
1893 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1894 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1895 }
1896 }
1897
1898 // Before doing any expensive analysis, check to see if we've already
1899 // computed a SCEV for this Op and Ty.
1902 ID.AddPointer(Op.getOpaqueValue());
1903 ID.AddPointer(Ty);
1905 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1906 return S;
1907 // Limit recursion depth.
1908 if (Depth > MaxCastDepth) {
1909 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1910 Op, Ty);
1911 UniqueSCEVs.insert(S, Token);
1912 S->computeAndSetCanonical(*this);
1913 registerUser(S, Op);
1914 return S;
1915 }
1916
1917 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1919 // It's possible the bits taken off by the truncate were all sign bits. If
1920 // so, we should be able to simplify this further.
1921 const SCEV *X = ST->getOperand();
1923 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1924 unsigned NewBits = getTypeSizeInBits(Ty);
1925 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1926 CR.sextOrTrunc(NewBits)))
1927 return getTruncateOrSignExtend(X, Ty, Depth);
1928 }
1929
1930 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1931 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1932 if (SA->hasNoSignedWrap()) {
1933 // If the addition does not sign overflow then we can, by definition,
1934 // commute the sign extension with the addition operation.
1936 for (SCEVUse Op : SA->operands())
1937 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1938 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1939 }
1940
1941 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1942 // if D + (C - D + x + y + ...) could be proven to not signed wrap
1943 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1944 //
1945 // For instance, this will bring two seemingly different expressions:
1946 // 1 + sext(5 + 20 * %x + 24 * %y) and
1947 // sext(6 + 20 * %x + 24 * %y)
1948 // to the same form:
1949 // 2 + sext(4 + 20 * %x + 24 * %y)
1950 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1951 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1952 if (D != 0) {
1953 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1954 const SCEV *SResidual =
1956 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1957 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1958 Depth + 1);
1959 }
1960 }
1961 }
1962 // If the input value is a chrec scev, and we can prove that the value
1963 // did not overflow the old, smaller, value, we can sign extend all of the
1964 // operands (often constants). This allows analysis of something like
1965 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1966 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1967 const auto *AR = cast<SCEVAddRecExpr>(Op);
1968 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1969
1970 // The no-signed-wrap case is handled before the uniquing lookup above.
1971
1972 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1973 // Note that this serves two purposes: It filters out loops that are
1974 // simply not analyzable, and it covers the case where this code is
1975 // being called from within backedge-taken count analysis, such that
1976 // attempting to ask for the backedge-taken count would likely result
1977 // in infinite recursion. In the later case, the analysis code will
1978 // cope with a conservative value, and it will take care to purge
1979 // that value once it has finished.
1980 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1981 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1982 // Manually compute the final value for AR, checking for
1983 // overflow.
1984
1985 // Check whether the backedge-taken count can be losslessly casted to
1986 // the addrec's type. The count is always unsigned.
1987 const SCEV *CastedMaxBECount =
1988 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1989 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1990 CastedMaxBECount, MaxBECount->getType(), Depth);
1991 if (MaxBECount == RecastedMaxBECount) {
1992 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1993 // Check whether Start+Step*MaxBECount has no signed overflow.
1994 const SCEV *SMul =
1995 getMulExpr(CastedMaxBECount, Step, SCEV::FlagNone, Depth + 1);
1996 const SCEV *SAdd = getSignExtendExpr(
1997 getAddExpr(Start, SMul, SCEV::FlagNone, Depth + 1), WideTy,
1998 Depth + 1);
1999 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2000 const SCEV *WideMaxBECount =
2001 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2002 const SCEV *OperandExtendedAdd =
2003 getAddExpr(WideStart,
2004 getMulExpr(WideMaxBECount,
2005 getSignExtendExpr(Step, WideTy, Depth + 1),
2006 SCEV::FlagNone, Depth + 1),
2007 SCEV::FlagNone, Depth + 1);
2008 if (SAdd == OperandExtendedAdd) {
2009 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2010 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2011 // Return the expression with the addrec on the outside.
2012 Start =
2014 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2015 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2016 }
2017 // Similar to above, only this time treat the step value as unsigned.
2018 // This covers loops that count up with an unsigned step.
2019 OperandExtendedAdd =
2020 getAddExpr(WideStart,
2021 getMulExpr(WideMaxBECount,
2022 getZeroExtendExpr(Step, WideTy, Depth + 1),
2023 SCEV::FlagNone, Depth + 1),
2024 SCEV::FlagNone, Depth + 1);
2025 if (SAdd == OperandExtendedAdd) {
2026 // If AR wraps around then
2027 //
2028 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2029 // => SAdd != OperandExtendedAdd
2030 //
2031 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2032 // (SAdd == OperandExtendedAdd => AR is NW)
2033
2034 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2035
2036 // Return the expression with the addrec on the outside.
2037 Start =
2039 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
2040 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2041 }
2042 }
2043 }
2044
2045 auto NewFlags = proveNoSignedWrapViaInduction(AR);
2046 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2047 if (AR->hasNoSignedWrap()) {
2048 // Same as nsw case above - duplicated here to avoid a compile time
2049 // issue. It's not clear that the order of checks does matter, but
2050 // it's one of two issue possible causes for a change which was
2051 // reverted. Be conservative for the moment.
2052 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2053 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2054 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2055 }
2056
2057 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2058 // if D + (C - D + Step * n) could be proven to not signed wrap
2059 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2060 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2061 const APInt &C = SC->getAPInt();
2062 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2063 if (D != 0) {
2064 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2065 const SCEV *SResidual =
2066 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2067 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2068 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
2069 Depth + 1);
2070 }
2071 }
2072
2073 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2074 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2075 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2076 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2077 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2078 }
2079 }
2080
2081 // If the input value is provably positive and we could not simplify
2082 // away the sext build a zext instead.
2084 return getZeroExtendExpr(Op, Ty, Depth + 1);
2085
2086 // sext(smin(x, y)) -> smin(sext(x), sext(y))
2087 // sext(smax(x, y)) -> smax(sext(x), sext(y))
2091 for (SCEVUse Operand : MinMax->operands())
2092 Operands.push_back(getSignExtendExpr(Operand, Ty));
2094 return getSMinExpr(Operands);
2095 return getSMaxExpr(Operands);
2096 }
2097
2098 // The cast wasn't folded; create an explicit cast node.
2099 // Recompute the insert position, as it may have been invalidated.
2100 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
2101 return S;
2102 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2103 Op, Ty);
2104 UniqueSCEVs.insert(S, Token);
2105 S->computeAndSetCanonical(*this);
2106 registerUser(S, Op);
2107 return S;
2108}
2109
2111 switch (Kind) {
2112 case scTruncate:
2113 return getTruncateExpr(Op, Ty);
2114 case scZeroExtend:
2115 return getZeroExtendExpr(Op, Ty);
2116 case scSignExtend:
2117 return getSignExtendExpr(Op, Ty);
2118 case scPtrToAddr: {
2119 const SCEV *Expr = getPtrToAddrExpr(Op);
2120 assert(Expr->getType() == Ty && "requested type must match");
2121 return Expr;
2122 }
2123 default:
2124 llvm_unreachable("Not a SCEV cast expression!");
2125 }
2126}
2127
2128/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2129/// unspecified bits out to the given type.
2131 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2132 "This is not an extending conversion!");
2133 assert(isSCEVable(Ty) &&
2134 "This is not a conversion to a SCEVable type!");
2135 Ty = getEffectiveSCEVType(Ty);
2136
2137 // Sign-extend negative constants.
2138 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2139 if (SC->getAPInt().isNegative())
2140 return getSignExtendExpr(Op, Ty);
2141
2142 // Peel off a truncate cast.
2144 const SCEV *NewOp = T->getOperand();
2145 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2146 return getAnyExtendExpr(NewOp, Ty);
2147 return getTruncateOrNoop(NewOp, Ty);
2148 }
2149
2150 // Next try a zext cast. If the cast is folded, use it.
2151 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2152 if (!isa<SCEVZeroExtendExpr>(ZExt))
2153 return ZExt;
2154
2155 // Next try a sext cast. If the cast is folded, use it.
2156 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2157 if (!isa<SCEVSignExtendExpr>(SExt))
2158 return SExt;
2159
2160 // Force the cast to be folded into the operands of an addrec.
2161 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2163 for (const SCEV *Op : AR->operands())
2164 Ops.push_back(getAnyExtendExpr(Op, Ty));
2165 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2166 }
2167
2168 // If the expression is obviously signed, use the sext cast value.
2169 if (isa<SCEVSMaxExpr>(Op))
2170 return SExt;
2171
2172 // Absent any other information, use the zext cast value.
2173 return ZExt;
2174}
2175
2176/// Process the given Ops list, which is a list of operands to be added under
2177/// the given scale, update the given map. This is a helper function for
2178/// getAddRecExpr. As an example of what it does, given a sequence of operands
2179/// that would form an add expression like this:
2180///
2181/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2182///
2183/// where A and B are constants, update the map with these values:
2184///
2185/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2186///
2187/// and add 13 + A*B*29 to AccumulatedConstant.
2188/// This will allow getAddRecExpr to produce this:
2189///
2190/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2191///
2192/// This form often exposes folding opportunities that are hidden in
2193/// the original operand list.
2194///
2195/// Return true iff it appears that any interesting folding opportunities
2196/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2197/// the common case where no interesting opportunities are present, and
2198/// is also used as a check to avoid infinite recursion.
2201 APInt &AccumulatedConstant,
2203 const APInt &Scale,
2204 ScalarEvolution &SE) {
2205 bool Interesting = false;
2206
2207 // Iterate over the add operands. They are sorted, with constants first.
2208 unsigned i = 0;
2209 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2210 ++i;
2211 // Pull a buried constant out to the outside.
2212 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2213 Interesting = true;
2214 AccumulatedConstant += Scale * C->getAPInt();
2215 }
2216
2217 // Next comes everything else. We're especially interested in multiplies
2218 // here, but they're in the middle, so just visit the rest with one loop.
2219 for (; i != Ops.size(); ++i) {
2221 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2222 APInt NewScale =
2223 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2224 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2225 // A multiplication of a constant with another add; recurse.
2226 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2227 Interesting |= CollectAddOperandsWithScales(
2228 M, NewOps, AccumulatedConstant, Add->operands(), NewScale, SE);
2229 } else {
2230 // A multiplication of a constant with some other value. Update
2231 // the map.
2232 SmallVector<SCEVUse, 4> MulOps(drop_begin(Mul->operands()));
2233 const SCEV *Key = SE.getMulExpr(MulOps);
2234 auto Pair = M.insert({Key, NewScale});
2235 if (Pair.second) {
2236 NewOps.push_back(Pair.first->first);
2237 } else {
2238 Pair.first->second += NewScale;
2239 // The map already had an entry for this value, which may indicate
2240 // a folding opportunity.
2241 Interesting = true;
2242 }
2243 }
2244 } else {
2245 // An ordinary operand. Update the map.
2246 auto Pair = M.insert({Ops[i], Scale});
2247 if (Pair.second) {
2248 NewOps.push_back(Pair.first->first);
2249 } else {
2250 Pair.first->second += Scale;
2251 // The map already had an entry for this value, which may indicate
2252 // a folding opportunity.
2253 Interesting = true;
2254 }
2255 }
2256 }
2257
2258 return Interesting;
2259}
2260
2262 const SCEV *LHS, const SCEV *RHS,
2263 const Instruction *CtxI) {
2264 auto Operation = [this, BinOp](SCEVUse L, SCEVUse R) -> const SCEV * {
2265 switch (BinOp) {
2266 default:
2267 llvm_unreachable("Unsupported binary op");
2268 case Instruction::Add:
2269 return getAddExpr(L, R);
2270 case Instruction::Sub:
2271 return getMinusSCEV(L, R);
2272 case Instruction::Mul:
2273 return getMulExpr(L, R);
2274 }
2275 };
2276
2277 const SCEV *(ScalarEvolution::*Extension)(SCEVUse, Type *, unsigned) =
2280
2281 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2282 auto *NarrowTy = cast<IntegerType>(LHS->getType());
2283 auto *WideTy =
2284 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2285
2286 const SCEV *A = (this->*Extension)(Operation(LHS, RHS), WideTy, 0);
2287 const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2288 const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2289 const SCEV *B = Operation(LHSB, RHSB);
2290 if (A == B)
2291 return true;
2292 // Can we use context to prove the fact we need?
2293 if (!CtxI)
2294 return false;
2295 // TODO: Support mul.
2296 if (BinOp == Instruction::Mul)
2297 return false;
2298 auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2299 // TODO: Lift this limitation.
2300 if (!RHSC)
2301 return false;
2302 APInt C = RHSC->getAPInt();
2303 unsigned NumBits = C.getBitWidth();
2304 bool IsSub = (BinOp == Instruction::Sub);
2305 bool IsNegativeConst = (Signed && C.isNegative());
2306 // Compute the direction and magnitude by which we need to check overflow.
2307 bool OverflowDown = IsSub ^ IsNegativeConst;
2308 APInt Magnitude = C;
2309 if (IsNegativeConst) {
2310 if (C == APInt::getSignedMinValue(NumBits))
2311 // TODO: SINT_MIN on inversion gives the same negative value, we don't
2312 // want to deal with that.
2313 return false;
2314 Magnitude = -C;
2315 }
2316
2318 if (OverflowDown) {
2319 // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2320 APInt Min = Signed ? APInt::getSignedMinValue(NumBits)
2321 : APInt::getMinValue(NumBits);
2322 APInt Limit = Min + Magnitude;
2323 return isKnownPredicateAt(Pred, getConstant(Limit), LHS, CtxI);
2324 } else {
2325 // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2326 APInt Max = Signed ? APInt::getSignedMaxValue(NumBits)
2327 : APInt::getMaxValue(NumBits);
2328 APInt Limit = Max - Magnitude;
2329 return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2330 }
2331}
2332
2334 const OverflowingBinaryOperator *OBO) {
2335 // It cannot be done any better.
2336 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2337 return std::nullopt;
2338
2340
2341 if (OBO->hasNoUnsignedWrap())
2343 if (OBO->hasNoSignedWrap())
2345
2346 bool Deduced = false;
2347
2349 const SCEV *LHS = getSCEV(OBO->getOperand(0));
2350 const SCEV *RHS = getSCEV(OBO->getOperand(1));
2351
2352 bool CanUseNSW = true;
2353 const APInt *ShiftAmt;
2354 // Treat `shl %a, C` as `mul %a, 1 << C`.
2355 if (match(OBO, m_Shl(m_Value(), m_APInt(ShiftAmt)))) {
2356 unsigned BitWidth = ShiftAmt->getBitWidth();
2357 if (ShiftAmt->uge(BitWidth))
2358 return std::nullopt;
2359 // NSW only transfers if the shift amount is < BitWidth - 1, as INT_MIN * -1
2360 // overflows.
2361 CanUseNSW = ShiftAmt->ult(BitWidth - 1);
2362 Opcode = Instruction::Mul;
2364 } else if (Opcode != Instruction::Add && Opcode != Instruction::Sub &&
2365 Opcode != Instruction::Mul) {
2366 return std::nullopt;
2367 }
2368
2369 const Instruction *CtxI =
2371 if (!OBO->hasNoUnsignedWrap() &&
2372 willNotOverflow(Opcode, /* Signed */ false, LHS, RHS, CtxI)) {
2374 Deduced = true;
2375 }
2376
2377 if (CanUseNSW && !OBO->hasNoSignedWrap() &&
2378 willNotOverflow(Opcode, /* Signed */ true, LHS, RHS, CtxI)) {
2380 Deduced = true;
2381 }
2382
2383 if (Deduced)
2384 return Flags;
2385 return std::nullopt;
2386}
2387
2388// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2389// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2390// can't-overflow flags for the operation if possible.
2393 using namespace std::placeholders;
2394
2395 using OBO = OverflowingBinaryOperator;
2396
2397 bool CanAnalyze =
2399 (void)CanAnalyze;
2400 assert(CanAnalyze && "don't call from other places!");
2401
2402 SCEVFlags SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2403 SCEVFlags SignOrUnsignWrap =
2404 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2405
2406 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2407 auto IsKnownNonNegative = [&](SCEVUse U) {
2408 return SE->isKnownNonNegative(U);
2409 };
2410
2411 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2412 Flags = ScalarEvolution::setFlags(Flags, SignOrUnsignMask);
2413
2414 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2415
2416 if (SignOrUnsignWrap != SignOrUnsignMask &&
2417 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2418 isa<SCEVConstant>(Ops[0])) {
2419
2420 auto Opcode = [&] {
2421 switch (Type) {
2422 case scAddExpr:
2423 return Instruction::Add;
2424 case scMulExpr:
2425 return Instruction::Mul;
2426 default:
2427 llvm_unreachable("Unexpected SCEV op.");
2428 }
2429 }();
2430
2431 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2432
2433 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2434 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2435 auto NSWRegion =
2436 ConstantRange::makeExactNoWrapRegion(Opcode, C, OBO::NoSignedWrap);
2437 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2439 }
2440
2441 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2442 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2443 auto NUWRegion =
2444 ConstantRange::makeExactNoWrapRegion(Opcode, C, OBO::NoUnsignedWrap);
2445 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2447 }
2448 }
2449
2450 // <0,+,nonnegative><nw> is also nuw
2451 // TODO: Add corresponding nsw case
2453 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2454 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2456
2457 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2459 Ops.size() == 2) {
2460 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2461 if (UDiv->getOperand(1) == Ops[1])
2463 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2464 if (UDiv->getOperand(1) == Ops[0])
2466 }
2467
2468 return Flags;
2469}
2470
2472 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2473}
2474
2475/// Get a canonical add expression, or something simpler if possible.
2477 SCEVFlagsPair Flags, unsigned Depth) {
2478 SCEVFlags ExprFlags = Flags.ExprFlags;
2479 SCEVFlags UseFlags = Flags.UseFlags;
2480 assert(!(ExprFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2481 "only nuw or nsw allowed");
2482 assert(!(UseFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2483 "only nuw or nsw allowed");
2484 assert(!Ops.empty() && "Cannot get empty add!");
2485 if (Ops.size() == 1) return Ops[0];
2486#ifndef NDEBUG
2487 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2488 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2489 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2490 "SCEVAddExpr operand types don't match!");
2491 unsigned NumPtrs = count_if(
2492 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2493 assert(NumPtrs <= 1 && "add has at most one pointer operand");
2494#endif
2495
2496 const SCEV *Folded = constantFoldAndGroupOps(
2497 *this, LI, DT, Ops,
2498 [](const APInt &C1, const APInt &C2) { return C1 + C2; },
2499 [](const APInt &C) { return C.isZero(); }, // identity
2500 [](const APInt &C) { return false; }); // absorber
2501 if (Folded)
2502 return Folded;
2503
2504#ifndef NDEBUG
2505 // Keep track of operands after constant folding, for verification when adding
2506 // use-specific flags.
2507 const SmallVector<SCEVUse, 8> OrigOps(Ops.begin(), Ops.end());
2508#endif
2509
2510 unsigned Idx = isa<SCEVConstant>(Ops[0]) ? 1 : 0;
2511
2512 // Delay expensive flag strengthening until necessary.
2513 auto ComputeFlags = [this, ExprFlags](ArrayRef<SCEVUse> Ops) {
2514 return StrengthenNoWrapFlags(this, scAddExpr, Ops, ExprFlags);
2515 };
2516
2517 // Limit recursion calls depth.
2519 return {getOrCreateAddExpr(Ops, ComputeFlags(Ops)), UseFlags};
2520
2521 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2522 // Don't strengthen flags if we have no new information.
2523 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2524 if (Add->getNoWrapFlags(ExprFlags) != ExprFlags)
2525 Add->setNoWrapFlags(ComputeFlags(Ops));
2526 return {S, UseFlags};
2527 }
2528
2529 // Okay, check to see if the same value occurs in the operand list more than
2530 // once. If so, merge them together into an multiply expression. Since we
2531 // sorted the list, these values are required to be adjacent.
2532 Type *Ty = Ops[0]->getType();
2533 bool FoundMatch = false;
2534 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2535 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2536 // Scan ahead to count how many equal operands there are.
2537 unsigned Count = 2;
2538 while (i+Count != e && Ops[i+Count] == Ops[i])
2539 ++Count;
2540 // Merge the values into a multiply.
2541 SCEVUse Scale = getConstant(Ty, Count);
2542 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagNone, Depth + 1);
2543 if (Ops.size() == Count)
2544 return Mul;
2545 Ops[i] = Mul;
2546 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2547 --i; e -= Count - 1;
2548 FoundMatch = true;
2549 }
2550 if (FoundMatch)
2551 return getAddExpr(Ops, ExprFlags, Depth + 1);
2552
2553 // Check for truncates. If all the operands are truncated from the same
2554 // type, see if factoring out the truncate would permit the result to be
2555 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2556 // if the contents of the resulting outer trunc fold to something simple.
2557 auto FindTruncSrcType = [&]() -> Type * {
2558 // We're ultimately looking to fold an addrec of truncs and muls of only
2559 // constants and truncs, so if we find any other types of SCEV
2560 // as operands of the addrec then we bail and return nullptr here.
2561 // Otherwise, we return the type of the operand of a trunc that we find.
2562 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2563 return T->getOperand()->getType();
2564 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2565 SCEVUse LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2566 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2567 return T->getOperand()->getType();
2568 }
2569 return nullptr;
2570 };
2571 if (auto *SrcType = FindTruncSrcType()) {
2572 SmallVector<SCEVUse, 8> LargeOps;
2573 bool Ok = true;
2574 // Check all the operands to see if they can be represented in the
2575 // source type of the truncate.
2576 for (const SCEV *Op : Ops) {
2578 if (T->getOperand()->getType() != SrcType) {
2579 Ok = false;
2580 break;
2581 }
2582 LargeOps.push_back(T->getOperand());
2583 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Op)) {
2584 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2585 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Op)) {
2586 SmallVector<SCEVUse, 8> LargeMulOps;
2587 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2588 if (const SCEVTruncateExpr *T =
2589 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2590 if (T->getOperand()->getType() != SrcType) {
2591 Ok = false;
2592 break;
2593 }
2594 LargeMulOps.push_back(T->getOperand());
2595 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2596 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2597 } else {
2598 Ok = false;
2599 break;
2600 }
2601 }
2602 if (Ok)
2603 LargeOps.push_back(
2604 getMulExpr(LargeMulOps, SCEV::FlagNone, Depth + 1));
2605 } else {
2606 Ok = false;
2607 break;
2608 }
2609 }
2610 if (Ok) {
2611 // Evaluate the expression in the larger type.
2612 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagNone, Depth + 1);
2613 // If it folds to something simple, use it. Otherwise, don't.
2614 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2615 return getTruncateExpr(Fold, Ty);
2616 }
2617 }
2618
2619 if (Ops.size() == 2) {
2620 // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2621 // C2 can be folded in a way that allows retaining wrapping flags of (X +
2622 // C1).
2623 const SCEV *A = Ops[0];
2624 const SCEV *B = Ops[1];
2625 auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2626 auto *C = dyn_cast<SCEVConstant>(A);
2627 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2628 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2629 auto C2 = C->getAPInt();
2630 SCEVFlags PreservedFlags = SCEV::FlagNone;
2631
2632 APInt ConstAdd = C1 + C2;
2633 auto AddFlags = AddExpr->getNoWrapFlags();
2634 // Adding a smaller constant is NUW if the original AddExpr was NUW.
2636 ConstAdd.ule(C1)) {
2637 PreservedFlags =
2639 }
2640
2641 // Adding a constant with the same sign and small magnitude is NSW, if the
2642 // original AddExpr was NSW.
2644 C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2645 ConstAdd.abs().ule(C1.abs())) {
2646 PreservedFlags =
2648 }
2649
2650 if (PreservedFlags != SCEV::FlagNone) {
2651 SmallVector<SCEVUse, 4> NewOps(AddExpr->operands());
2652 NewOps[0] = getConstant(ConstAdd);
2653 return getAddExpr(NewOps, PreservedFlags);
2654 }
2655 }
2656
2657 // Try to push the constant operand into a ZExt: A + zext (-A + B) -> zext
2658 // (B), if trunc (A) + -A + B does not unsigned-wrap.
2659 const SCEVAddExpr *InnerAdd;
2660 if (match(B, m_scev_ZExt(m_scev_Add(InnerAdd)))) {
2661 const SCEV *NarrowA = getTruncateExpr(A, InnerAdd->getType());
2662 if (NarrowA == getNegativeSCEV(InnerAdd->getOperand(0)) &&
2663 getZeroExtendExpr(NarrowA, B->getType()) == A &&
2664 hasFlags(StrengthenNoWrapFlags(this, scAddExpr, {NarrowA, InnerAdd},
2666 SCEV::FlagNUW)) {
2667 return getZeroExtendExpr(getAddExpr(NarrowA, InnerAdd), B->getType());
2668 }
2669 }
2670 }
2671
2672 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2673 const SCEV *Y;
2674 if (Ops.size() == 2 &&
2675 match(Ops[0],
2677 m_scev_URem(m_scev_Specific(Ops[1]), m_SCEV(Y), *this))))
2678 return getMulExpr(Y, getUDivExpr(Ops[1], Y));
2679
2680 // Skip past any other cast SCEVs.
2681 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2682 ++Idx;
2683
2684 // If there are add operands they would be next.
2685 if (Idx < Ops.size()) {
2686 bool DeletedAdd = false;
2687 // If the original flags and all inlined SCEVAddExprs are NUW, use the
2688 // common NUW flag for expression after inlining. Other flags cannot be
2689 // preserved, because they may depend on the original order of operations.
2690 SCEVFlags CommonFlags = maskFlags(ExprFlags, SCEV::FlagNUW);
2691 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2692 if (Ops.size() > AddOpsInlineThreshold ||
2693 Add->getNumOperands() > AddOpsInlineThreshold)
2694 break;
2695 // If we have an add, expand the add operands onto the end of the operands
2696 // list.
2697 Ops.erase(Ops.begin()+Idx);
2698 append_range(Ops, Add->operands());
2699 DeletedAdd = true;
2700 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2701 }
2702
2703 // If we deleted at least one add, we added operands to the end of the list,
2704 // and they are not necessarily sorted. Recurse to resort and resimplify
2705 // any operands we just acquired.
2706 if (DeletedAdd)
2707 return getAddExpr(Ops, CommonFlags, Depth + 1);
2708 }
2709
2710 // Skip over the add expression until we get to a multiply.
2711 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2712 ++Idx;
2713
2714 // Check to see if there are any folding opportunities present with
2715 // operands multiplied by constant values.
2716 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2717 uint64_t BitWidth = getTypeSizeInBits(Ty);
2720 APInt AccumulatedConstant(BitWidth, 0);
2721 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2722 Ops, APInt(BitWidth, 1), *this)) {
2723 struct APIntCompare {
2724 bool operator()(const APInt &LHS, const APInt &RHS) const {
2725 return LHS.ult(RHS);
2726 }
2727 };
2728
2729 // Some interesting folding opportunity is present, so its worthwhile to
2730 // re-generate the operands list. Group the operands by constant scale,
2731 // to avoid multiplying by the same constant scale multiple times.
2732 std::map<APInt, SmallVector<SCEVUse, 4>, APIntCompare> MulOpLists;
2733 for (SCEVUse NewOp : NewOps)
2734 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2735 // Re-generate the operands list.
2736 Ops.clear();
2737 if (AccumulatedConstant != 0)
2738 Ops.push_back(getConstant(AccumulatedConstant));
2739 for (auto &MulOp : MulOpLists) {
2740 if (MulOp.first == 1) {
2741 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagNone, Depth + 1));
2742 } else if (MulOp.first != 0) {
2743 Ops.push_back(
2744 getMulExpr(getConstant(MulOp.first),
2745 getAddExpr(MulOp.second, SCEV::FlagNone, Depth + 1),
2746 SCEV::FlagNone, Depth + 1));
2747 }
2748 }
2749 if (Ops.empty())
2750 return getZero(Ty);
2751 if (Ops.size() == 1)
2752 return Ops[0];
2753 return getAddExpr(Ops, SCEV::FlagNone, Depth + 1);
2754 }
2755 }
2756
2757 // Given a SCEVMulExpr and an operand index, return the product of all
2758 // operands except the one at OpIdx.
2759 auto StripFactor = [&](const SCEVMulExpr *M, unsigned OpIdx) -> SCEVUse {
2760 if (M->getNumOperands() == 2)
2761 return M->getOperand(OpIdx == 0);
2762 SmallVector<SCEVUse, 4> Remaining(M->operands().take_front(OpIdx));
2763 append_range(Remaining, M->operands().drop_front(OpIdx + 1));
2764 return getMulExpr(Remaining, SCEV::FlagNone, Depth + 1);
2765 };
2766
2767 // If we are adding something to a multiply expression, make sure the
2768 // something is not already an operand of the multiply. If so, merge it into
2769 // the multiply.
2770 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2771 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2772 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2773 // Scan all terms to find every occurrence of common factor MulOpSCEV
2774 // and fold them in one shot:
2775 // A1*X + A2*X + ... + An*X --> X * (A1 + A2 + ... + An)
2776 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2777 if (isa<SCEVConstant>(MulOpSCEV))
2778 continue;
2779
2780 // Cofactors: 1 for bare addends matching MulOpSCEV, or the
2781 // remaining product for multiply terms containing MulOpSCEV.
2782 SmallVector<SCEVUse, 4> Cofactors;
2783 SmallVector<unsigned, 4> DeadIndices;
2784 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) {
2785 if (MulOpSCEV == Ops[AddOp]) {
2786 // W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2787 Cofactors.push_back(getOne(Ty));
2788 DeadIndices.push_back(AddOp);
2789 continue;
2790 }
2791
2792 if (AddOp <= Idx || !isa<SCEVMulExpr>(Ops[AddOp]))
2793 continue;
2794
2795 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[AddOp]);
2796 for (unsigned OMulOp = 0, OE = OtherMul->getNumOperands(); OMulOp != OE;
2797 ++OMulOp) {
2798 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2799 // (A*B*C) + (A*D*E) --> A * (B*C + D*E)
2800 Cofactors.push_back(StripFactor(OtherMul, OMulOp));
2801 DeadIndices.push_back(AddOp);
2802 break;
2803 }
2804 }
2805 }
2806
2807 // Fold all collected cofactors with the anchor multiply's cofactor:
2808 // MulOpSCEV * (Cofactor_1 + ... + Cofactor_n + AnchorCofactor)
2809 if (!Cofactors.empty()) {
2810 Cofactors.push_back(StripFactor(Mul, MulOp));
2811
2812 SCEVUse InnerSum = getAddExpr(Cofactors, SCEV::FlagNone, Depth + 1);
2813 SCEVUse OuterMul =
2814 getMulExpr(MulOpSCEV, InnerSum, SCEV::FlagNone, Depth + 1);
2815
2816 // DeadIndices does not include Idx (the anchor), hence +1.
2817 if (Ops.size() == DeadIndices.size() + 1)
2818 return OuterMul;
2819
2820 // Erase Ops[Idx] first, then erase DeadIndices in reverse order.
2821 // The -1 adjustment accounts for the shift from removing Idx;
2822 // reverse order means each erasure only shifts later positions,
2823 // which have already been processed.
2824 Ops.erase(Ops.begin() + Idx);
2825 for (unsigned Dead : reverse(DeadIndices))
2826 Ops.erase(Ops.begin() + (Dead > Idx ? Dead - 1 : Dead));
2827
2828 Ops.push_back(OuterMul);
2829 return getAddExpr(Ops, SCEV::FlagNone, Depth + 1);
2830 }
2831 }
2832 }
2833
2834 // If there are any add recurrences in the operands list, see if any other
2835 // added values are loop invariant. If so, we can fold them into the
2836 // recurrence.
2837 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2838 ++Idx;
2839
2840 // Scan over all recurrences, trying to fold loop invariants into them.
2841 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2842 // Scan all of the other operands to this add and add them to the vector if
2843 // they are loop invariant w.r.t. the recurrence.
2845 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2846 const Loop *AddRecLoop = AddRec->getLoop();
2847 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2848 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2849 LIOps.push_back(Ops[i]);
2850 Ops.erase(Ops.begin()+i);
2851 --i; --e;
2852 }
2853
2854 // If we found some loop invariants, fold them into the recurrence.
2855 if (!LIOps.empty()) {
2856 // Compute nowrap flags for the addition of the loop-invariant ops and
2857 // the addrec. Temporarily push it as an operand for that purpose. These
2858 // flags are valid in the scope of the addrec only.
2859 LIOps.push_back(AddRec);
2860 SCEVFlags Flags = ComputeFlags(LIOps);
2861 LIOps.pop_back();
2862
2863 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2864 LIOps.push_back(AddRec->getStart());
2865
2866 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2867
2868 // It is not in general safe to propagate flags valid on an add within
2869 // the addrec scope to one outside it. We must prove that the inner
2870 // scope is guaranteed to execute if the outer one does to be able to
2871 // safely propagate. We know the program is undefined if poison is
2872 // produced on the inner scoped addrec. We also know that *for this use*
2873 // the outer scoped add can't overflow (because of the flags we just
2874 // computed for the inner scoped add) without the program being undefined.
2875 // Proving that entry to the outer scope neccesitates entry to the inner
2876 // scope, thus proves the program undefined if the flags would be violated
2877 // in the outer scope.
2878 SCEVFlags AddFlags = Flags;
2879 if (AddFlags != SCEV::FlagNone) {
2880 auto *DefI = getDefiningScopeBound(LIOps);
2881 auto *ReachI = &*AddRecLoop->getHeader()->begin();
2882 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2883 AddFlags = SCEV::FlagNone;
2884 }
2885 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2886
2887 // Build the new addrec. Propagate the NUW and NSW flags if both the
2888 // outer add and the inner addrec are guaranteed to have no overflow.
2889 // Always propagate NW.
2890 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2891 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2892
2893 // If all of the other operands were loop invariant, we are done.
2894 if (Ops.size() == 1) return NewRec;
2895
2896 // Otherwise, add the folded AddRec by the non-invariant parts.
2897 for (unsigned i = 0;; ++i)
2898 if (Ops[i] == AddRec) {
2899 Ops[i] = NewRec;
2900 break;
2901 }
2902 return getAddExpr(Ops, SCEV::FlagNone, Depth + 1);
2903 }
2904
2905 // Okay, if there weren't any loop invariants to be folded, check to see if
2906 // there are multiple AddRec's with the same loop induction variable being
2907 // added together. If so, we can fold them.
2908 for (unsigned OtherIdx = Idx+1;
2909 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2910 ++OtherIdx) {
2911 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2912 // so that the 1st found AddRecExpr is dominated by all others.
2913 assert(DT.dominates(
2914 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2915 AddRec->getLoop()->getHeader()) &&
2916 "AddRecExprs are not sorted in reverse dominance order?");
2917 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2918 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2919 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2920 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2921 ++OtherIdx) {
2922 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2923 if (OtherAddRec->getLoop() == AddRecLoop) {
2924 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2925 i != e; ++i) {
2926 if (i >= AddRecOps.size()) {
2927 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
2928 break;
2929 }
2930 AddRecOps[i] =
2931 getAddExpr(AddRecOps[i], OtherAddRec->getOperand(i),
2932 SCEV::FlagNone, Depth + 1);
2933 }
2934 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2935 }
2936 }
2937 // Step size has changed, so we cannot guarantee no self-wraparound.
2938 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagNone);
2939 return getAddExpr(Ops, SCEV::FlagNone, Depth + 1);
2940 }
2941 }
2942
2943 // Otherwise couldn't fold anything into this recurrence. Move onto the
2944 // next one.
2945 }
2946
2947 // Okay, it looks like we really DO need an add expr. Check to see if we
2948 // already have one, otherwise create a new one.
2949 assert((UseFlags == SCEV::FlagNone || equal(OrigOps, Ops)) &&
2950 "Tried to add SCEVUse flags after operands changed");
2951 return {getOrCreateAddExpr(Ops, ComputeFlags(Ops)), UseFlags};
2952}
2953
2954const SCEV *ScalarEvolution::getOrCreateAddExpr(ArrayRef<SCEVUse> Ops,
2955 SCEVFlags Flags) {
2958 for (SCEVUse Op : Ops)
2959 ID.AddPointer(Op.getOpaqueValue());
2961 SCEVAddExpr *S = static_cast<SCEVAddExpr *>(UniqueSCEVs.lookup(ID, Token));
2962 if (!S) {
2963 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
2965 S = new (SCEVAllocator)
2966 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2967 UniqueSCEVs.insert(S, Token);
2968 S->computeAndSetCanonical(*this);
2969 registerUser(S, Ops);
2970 }
2971 S->setNoWrapFlags(Flags);
2972 return S;
2973}
2974
2975const SCEV *ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<SCEVUse> Ops,
2976 const Loop *L,
2977 SCEVFlags Flags) {
2978 FoldingSetNodeID ID;
2979 ID.AddInteger(scAddRecExpr);
2980 for (SCEVUse Op : Ops)
2981 ID.AddPointer(Op.getOpaqueValue());
2982 ID.AddPointer(L);
2983 FoldingSetInsertToken Token;
2984 SCEVAddRecExpr *S =
2985 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.lookup(ID, Token));
2986 if (!S) {
2987 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
2989 S = new (SCEVAllocator)
2990 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2991 UniqueSCEVs.insert(S, Token);
2992 S->computeAndSetCanonical(*this);
2993 LoopUsers[L].push_back(S);
2994 registerUser(S, Ops);
2995 }
2996 setNoWrapFlags(S, Flags);
2997 return S;
2998}
2999
3000const SCEV *ScalarEvolution::getOrCreateMulExpr(ArrayRef<SCEVUse> Ops,
3001 SCEVFlags Flags) {
3002 FoldingSetNodeID ID;
3003 ID.AddInteger(scMulExpr);
3004 for (SCEVUse Op : Ops)
3005 ID.AddPointer(Op.getOpaqueValue());
3006 FoldingSetInsertToken Token;
3007 SCEVMulExpr *S = static_cast<SCEVMulExpr *>(UniqueSCEVs.lookup(ID, Token));
3008 if (!S) {
3009 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3011 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
3012 O, Ops.size());
3013 UniqueSCEVs.insert(S, Token);
3014 S->computeAndSetCanonical(*this);
3015 registerUser(S, Ops);
3016 }
3017 S->setNoWrapFlags(Flags);
3018 return S;
3019}
3020
3021const SCEV *ScalarEvolution::getOrCreateUDivExpr(SCEVUse LHS, SCEVUse RHS) {
3022 FoldingSetNodeID ID;
3023 ID.AddInteger(scUDivExpr);
3024 ID.AddPointer(LHS.getOpaqueValue());
3025 ID.AddPointer(RHS.getOpaqueValue());
3026 FoldingSetInsertToken Token;
3027 SCEV *S = UniqueSCEVs.lookup(ID, Token);
3028 if (!S) {
3029 S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), LHS, RHS);
3030 UniqueSCEVs.insert(S, Token);
3031 S->computeAndSetCanonical(*this);
3032 registerUser(S, {LHS, RHS});
3033 }
3034 return S;
3035}
3036
3037static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
3038 uint64_t k = i*j;
3039 if (j > 1 && k / j != i) Overflow = true;
3040 return k;
3041}
3042
3043/// Compute the result of "n choose k", the binomial coefficient. If an
3044/// intermediate computation overflows, Overflow will be set and the return will
3045/// be garbage. Overflow is not cleared on absence of overflow.
3046static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3047 // We use the multiplicative formula:
3048 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3049 // At each iteration, we take the n-th term of the numeral and divide by the
3050 // (k-n)th term of the denominator. This division will always produce an
3051 // integral result, and helps reduce the chance of overflow in the
3052 // intermediate computations. However, we can still overflow even when the
3053 // final result would fit.
3054
3055 if (n == 0 || n == k) return 1;
3056 if (k > n) return 0;
3057
3058 if (k > n/2)
3059 k = n-k;
3060
3061 uint64_t r = 1;
3062 for (uint64_t i = 1; i <= k; ++i) {
3063 r = umul_ov(r, n-(i-1), Overflow);
3064 r /= i;
3065 }
3066 return r;
3067}
3068
3069/// Determine if any of the operands in this SCEV are a constant or if
3070/// any of the add or multiply expressions in this SCEV contain a constant.
3071static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3072 struct FindConstantInAddMulChain {
3073 bool FoundConstant = false;
3074
3075 bool follow(const SCEV *S) {
3076 FoundConstant |= isa<SCEVConstant>(S);
3077 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3078 }
3079
3080 bool isDone() const {
3081 return FoundConstant;
3082 }
3083 };
3084
3085 FindConstantInAddMulChain F;
3087 ST.visitAll(StartExpr);
3088 return F.FoundConstant;
3089}
3090
3091/// Get a canonical multiply expression, or something simpler if possible.
3093 SCEVFlagsPair Flags, unsigned Depth) {
3094 SCEVFlags ExprFlags = Flags.ExprFlags;
3095 SCEVFlags UseFlags = Flags.UseFlags;
3096 assert(ExprFlags == maskFlags(ExprFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3097 "only nuw or nsw allowed");
3098 assert(UseFlags == maskFlags(UseFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3099 "only nuw or nsw allowed");
3100 assert(!Ops.empty() && "Cannot get empty mul!");
3101 if (Ops.size() == 1) return Ops[0];
3102#ifndef NDEBUG
3103 Type *ETy = Ops[0]->getType();
3104 assert(!ETy->isPointerTy());
3105 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3106 assert(Ops[i]->getType() == ETy &&
3107 "SCEVMulExpr operand types don't match!");
3108#endif
3109
3110 const SCEV *Folded = constantFoldAndGroupOps(
3111 *this, LI, DT, Ops,
3112 [](const APInt &C1, const APInt &C2) { return C1 * C2; },
3113 [](const APInt &C) { return C.isOne(); }, // identity
3114 [](const APInt &C) { return C.isZero(); }); // absorber
3115 if (Folded)
3116 return Folded;
3117
3118#ifndef NDEBUG
3119 // Keep track of operands after constant folding, for verification when adding
3120 // use-specific flags.
3121 const SmallVector<SCEVUse, 8> OrigOps(Ops.begin(), Ops.end());
3122#endif
3123
3124 // Delay expensive flag strengthening until necessary.
3125 auto ComputeFlags = [this, ExprFlags](const ArrayRef<SCEVUse> Ops) {
3126 return StrengthenNoWrapFlags(this, scMulExpr, Ops, ExprFlags);
3127 };
3128
3129 // Limit recursion calls depth.
3131 return {getOrCreateMulExpr(Ops, ComputeFlags(Ops)), UseFlags};
3132
3133 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3134 // Don't strengthen flags if we have no new information.
3135 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3136 if (Mul->getNoWrapFlags(ExprFlags) != ExprFlags)
3137 Mul->setNoWrapFlags(ComputeFlags(Ops));
3138 return {S, UseFlags};
3139 }
3140
3141 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3142 if (Ops.size() == 2) {
3143 // C1*(C2+V) -> C1*C2 + C1*V
3144 // If any of Add's ops are Adds or Muls with a constant, apply this
3145 // transformation as well.
3146 //
3147 // TODO: There are some cases where this transformation is not
3148 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
3149 // this transformation should be narrowed down.
3150 const SCEV *Op0, *Op1;
3151 if (match(Ops[1], m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))) &&
3153 const SCEV *LHS = getMulExpr(LHSC, Op0, SCEV::FlagNone, Depth + 1);
3154 const SCEV *RHS = getMulExpr(LHSC, Op1, SCEV::FlagNone, Depth + 1);
3155 return getAddExpr(LHS, RHS, SCEV::FlagNone, Depth + 1);
3156 }
3157
3158 if (Ops[0]->isAllOnesValue()) {
3159 // If we have a mul by -1 of an add, try distributing the -1 among the
3160 // add operands.
3161 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3163 bool AnyFolded = false;
3164 for (const SCEV *AddOp : Add->operands()) {
3165 const SCEV *Mul =
3166 getMulExpr(Ops[0], SCEVUse(AddOp), SCEV::FlagNone, Depth + 1);
3167 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3168 NewOps.push_back(Mul);
3169 }
3170 if (AnyFolded)
3171 return getAddExpr(NewOps, SCEV::FlagNone, Depth + 1);
3172 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3173 // Negation preserves a recurrence's no self-wrap property.
3175 for (const SCEV *AddRecOp : AddRec->operands())
3176 Operands.push_back(getMulExpr(Ops[0], SCEVUse(AddRecOp),
3177 SCEV::FlagNone, Depth + 1));
3178 // Let M be the minimum representable signed value. AddRec with nsw
3179 // multiplied by -1 can have signed overflow if and only if it takes a
3180 // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3181 // maximum signed value. In all other cases signed overflow is
3182 // impossible.
3183 auto FlagsMask = SCEV::FlagNW;
3184 if (AddRec->hasNoSignedWrap()) {
3185 auto MinInt =
3186 APInt::getSignedMinValue(getTypeSizeInBits(AddRec->getType()));
3187 if (getSignedRangeMin(AddRec) != MinInt)
3189 }
3190 return getAddRecExpr(Operands, AddRec->getLoop(),
3191 AddRec->getNoWrapFlags(FlagsMask));
3192 }
3193 }
3194
3195 // Try to push the constant operand into a ZExt: C * zext (A + B) ->
3196 // zext (C*A + C*B) if trunc (C) * (A + B) does not unsigned-wrap.
3197 const SCEVAddExpr *InnerAdd;
3198 if (match(Ops[1], m_scev_ZExt(m_scev_Add(InnerAdd)))) {
3199 const SCEV *NarrowC = getTruncateExpr(LHSC, InnerAdd->getType());
3200 if (isa<SCEVConstant>(InnerAdd->getOperand(0)) &&
3201 getZeroExtendExpr(NarrowC, Ops[1]->getType()) == LHSC &&
3202 hasFlags(StrengthenNoWrapFlags(this, scMulExpr, {NarrowC, InnerAdd},
3204 SCEV::FlagNUW)) {
3205 const SCEV *Res =
3206 getMulExpr(NarrowC, InnerAdd, SCEV::FlagNUW, Depth + 1);
3207 return getZeroExtendExpr(Res, Ops[1]->getType(), Depth + 1);
3208 };
3209 }
3210
3211 // Try to fold (C1 * D /u C2) -> C1/C2 * D, if C1 and C2 are powers-of-2,
3212 // D is a multiple of C2, and C1 is a multiple of C2. If C2 is a multiple
3213 // of C1, fold to (D /u (C2 /u C1)).
3214 const SCEV *D;
3215 APInt C1V = LHSC->getAPInt();
3216 // (C1 * D /u C2) == -1 * -C1 * D /u C2 when C1 != INT_MIN. Don't treat -1
3217 // as -1 * 1, as it won't enable additional folds.
3218 if (C1V.isNegative() && !C1V.isMinSignedValue() && !C1V.isAllOnes())
3219 C1V = C1V.abs();
3220 const SCEVConstant *C2;
3221 if (C1V.isPowerOf2() &&
3223 C2->getAPInt().isPowerOf2() &&
3224 C1V.logBase2() <= getMinTrailingZeros(D)) {
3225 const SCEV *NewMul = nullptr;
3226 if (C1V.uge(C2->getAPInt())) {
3227 NewMul = getMulExpr(getUDivExpr(getConstant(C1V), C2), D);
3228 } else if (C2->getAPInt().logBase2() <= getMinTrailingZeros(D)) {
3229 assert(C1V.ugt(1) && "C1 <= 1 should have been folded earlier");
3230 NewMul = getUDivExpr(D, getUDivExpr(C2, getConstant(C1V)));
3231 }
3232 if (NewMul)
3233 return C1V == LHSC->getAPInt() ? NewMul : getNegativeSCEV(NewMul);
3234 }
3235 }
3236 }
3237
3238 // Skip over the add expression until we get to a multiply.
3239 unsigned Idx = 0;
3240 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3241 ++Idx;
3242
3243 // If there are mul operands inline them all into this expression.
3244 if (Idx < Ops.size()) {
3245 bool DeletedMul = false;
3246 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3247 if (Ops.size() > MulOpsInlineThreshold)
3248 break;
3249 // If we have an mul, expand the mul operands onto the end of the
3250 // operands list.
3251 Ops.erase(Ops.begin()+Idx);
3252 append_range(Ops, Mul->operands());
3253 DeletedMul = true;
3254 }
3255
3256 // If we deleted at least one mul, we added operands to the end of the
3257 // list, and they are not necessarily sorted. Recurse to resort and
3258 // resimplify any operands we just acquired.
3259 if (DeletedMul)
3260 return getMulExpr(Ops, SCEV::FlagNone, Depth + 1);
3261 }
3262
3263 // If there are any add recurrences in the operands list, see if any other
3264 // added values are loop invariant. If so, we can fold them into the
3265 // recurrence.
3266 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3267 ++Idx;
3268
3269 // Scan over all recurrences, trying to fold loop invariants into them.
3270 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3271 // Scan all of the other operands to this mul and add them to the vector
3272 // if they are loop invariant w.r.t. the recurrence.
3274 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3275 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3276 if (isAvailableAtLoopEntry(Ops[i], AddRec->getLoop())) {
3277 LIOps.push_back(Ops[i]);
3278 Ops.erase(Ops.begin()+i);
3279 --i; --e;
3280 }
3281
3282 // If we found some loop invariants, fold them into the recurrence.
3283 if (!LIOps.empty()) {
3284 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3286 NewOps.reserve(AddRec->getNumOperands());
3287 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagNone, Depth + 1);
3288
3289 // If both the mul and addrec are nuw, we can preserve nuw.
3290 // If both the mul and addrec are nsw, we can only preserve nsw if either
3291 // a) they are also nuw, or
3292 // b) all multiplications of addrec operands with scale are nsw.
3293 SCEVFlags Flags = AddRec->getNoWrapFlags(ComputeFlags({Scale, AddRec}));
3294
3295 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3296 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3297 SCEV::FlagNone, Depth + 1));
3298
3299 if (hasFlags(Flags, SCEV::FlagNSW) && !hasFlags(Flags, SCEV::FlagNUW)) {
3301 Instruction::Mul, getSignedRange(Scale),
3303 if (!NSWRegion.contains(getSignedRange(AddRec->getOperand(i))))
3304 Flags = clearFlags(Flags, SCEV::FlagNSW);
3305 }
3306 }
3307
3308 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(), Flags);
3309
3310 // If all of the other operands were loop invariant, we are done.
3311 if (Ops.size() == 1) return NewRec;
3312
3313 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3314 for (unsigned i = 0;; ++i)
3315 if (Ops[i] == AddRec) {
3316 Ops[i] = NewRec;
3317 break;
3318 }
3319 return getMulExpr(Ops, SCEV::FlagNone, Depth + 1);
3320 }
3321
3322 // Okay, if there weren't any loop invariants to be folded, check to see
3323 // if there are multiple AddRec's with the same loop induction variable
3324 // being multiplied together. If so, we can fold them.
3325
3326 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3327 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3328 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3329 // ]]],+,...up to x=2n}.
3330 // Note that the arguments to choose() are always integers with values
3331 // known at compile time, never SCEV objects.
3332 //
3333 // The implementation avoids pointless extra computations when the two
3334 // addrec's are of different length (mathematically, it's equivalent to
3335 // an infinite stream of zeros on the right).
3336 bool OpsModified = false;
3337 for (unsigned OtherIdx = Idx+1;
3338 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3339 ++OtherIdx) {
3340 const SCEVAddRecExpr *OtherAddRec =
3341 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3342 if (!OtherAddRec || OtherAddRec->getLoop() != AddRec->getLoop())
3343 continue;
3344
3345 // Limit max number of arguments to avoid creation of unreasonably big
3346 // SCEVAddRecs with very complex operands.
3347 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3348 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3349 continue;
3350
3351 bool Overflow = false;
3352 Type *Ty = AddRec->getType();
3353 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3354 SmallVector<SCEVUse, 7> AddRecOps;
3355 for (int x = 0, xe = AddRec->getNumOperands() +
3356 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3358 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3359 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3360 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3361 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3362 z < ze && !Overflow; ++z) {
3363 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3364 uint64_t Coeff;
3365 if (LargerThan64Bits)
3366 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3367 else
3368 Coeff = Coeff1*Coeff2;
3369 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3370 const SCEV *Term1 = AddRec->getOperand(y-z);
3371 const SCEV *Term2 = OtherAddRec->getOperand(z);
3372 SumOps.push_back(
3373 getMulExpr(CoeffTerm, Term1, Term2, SCEV::FlagNone, Depth + 1));
3374 }
3375 }
3376 if (SumOps.empty())
3377 SumOps.push_back(getZero(Ty));
3378 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagNone, Depth + 1));
3379 }
3380 if (!Overflow) {
3381 const SCEV *NewAddRec =
3382 getAddRecExpr(AddRecOps, AddRec->getLoop(), SCEV::FlagNone);
3383 if (Ops.size() == 2) return NewAddRec;
3384 Ops[Idx] = NewAddRec;
3385 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3386 OpsModified = true;
3387 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3388 if (!AddRec)
3389 break;
3390 }
3391 }
3392 if (OpsModified)
3393 return getMulExpr(Ops, SCEV::FlagNone, Depth + 1);
3394
3395 // Otherwise couldn't fold anything into this recurrence. Move onto the
3396 // next one.
3397 }
3398
3399 // Okay, it looks like we really DO need an mul expr. Check to see if we
3400 // already have one, otherwise create a new one.
3401 assert((UseFlags == SCEV::FlagNone || equal(OrigOps, Ops)) &&
3402 "Tried to add SCEVUse flags after operands changed");
3403 return {getOrCreateMulExpr(Ops, ComputeFlags(Ops)), UseFlags};
3404}
3405
3406/// Represents an unsigned remainder expression based on unsigned division.
3408 assert(getEffectiveSCEVType(LHS->getType()) ==
3409 getEffectiveSCEVType(RHS->getType()) &&
3410 "SCEVURemExpr operand types don't match!");
3411
3412 // Short-circuit easy cases
3413 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3414 // If constant is one, the result is trivial
3415 if (RHSC->getValue()->isOne())
3416 return getZero(LHS->getType()); // X urem 1 --> 0
3417
3418 // If constant is a power of two, fold into a zext(trunc(LHS)).
3419 if (RHSC->getAPInt().isPowerOf2()) {
3420 Type *FullTy = LHS->getType();
3421 Type *TruncTy =
3422 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3423 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3424 }
3425 }
3426
3427 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3428 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3429 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3430 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3431}
3432
3433/// Get a canonical unsigned division expression, or something simpler if
3434/// possible.
3436 assert(!LHS->getType()->isPointerTy() &&
3437 "SCEVUDivExpr operand can't be pointer!");
3438 assert(LHS->getType() == RHS->getType() &&
3439 "SCEVUDivExpr operand types don't match!");
3440
3441 if (SCEV *S = findExistingSCEVInCache(scUDivExpr, {LHS, RHS}))
3442 return S;
3443
3444 // 0 udiv Y == 0
3445 if (match(LHS, m_scev_Zero()))
3446 return LHS;
3447
3448 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3449 if (RHSC->getValue()->isOne())
3450 return LHS; // X udiv 1 --> x
3451 // If the denominator is zero, the result of the udiv is undefined. Don't
3452 // try to analyze it, because the resolution chosen here may differ from
3453 // the resolution chosen in other parts of the compiler.
3454 if (!RHSC->getValue()->isZero()) {
3455 // Determine if the division can be folded into the operands of
3456 // its operands.
3457 // TODO: Generalize this to non-constants by using known-bits information.
3458 Type *Ty = LHS->getType();
3459 unsigned LZ = RHSC->getAPInt().countl_zero();
3460 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3461 // For non-power-of-two values, effectively round the value up to the
3462 // nearest power of two.
3463 if (!RHSC->getAPInt().isPowerOf2())
3464 ++MaxShiftAmt;
3465 IntegerType *ExtTy =
3466 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3467 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3468 if (const SCEVConstant *Step =
3469 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3470 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3471 const APInt &StepInt = Step->getAPInt();
3472 const APInt &DivInt = RHSC->getAPInt();
3473 if (!StepInt.urem(DivInt) &&
3474 getZeroExtendExpr(AR, ExtTy) ==
3475 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3476 getZeroExtendExpr(Step, ExtTy), AR->getLoop(),
3477 SCEV::FlagNone)) {
3479 for (const SCEV *Op : AR->operands())
3480 Operands.push_back(getUDivExpr(Op, RHS));
3481 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3482 }
3483 /// Get a canonical UDivExpr for a recurrence.
3484 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3485 const APInt *StartRem;
3486 if (!DivInt.urem(StepInt) && match(getURemExpr(AR->getStart(), Step),
3487 m_scev_APInt(StartRem))) {
3488 bool NoWrap =
3489 getZeroExtendExpr(AR, ExtTy) ==
3490 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3491 getZeroExtendExpr(Step, ExtTy), AR->getLoop(),
3493
3494 // With N <= C and both N, C as powers-of-2, the transformation
3495 // {X,+,N}/C => {(X - X%N),+,N}/C preserves division results even
3496 // if wrapping occurs, as the division results remain equivalent for
3497 // all offsets in [[(X - X%N), X).
3498 bool CanFoldWithWrap = StepInt.ule(DivInt) && // N <= C
3499 StepInt.isPowerOf2() && DivInt.isPowerOf2();
3500 // Only fold if the subtraction can be folded in the start
3501 // expression.
3502 const SCEV *NewStart =
3503 getMinusSCEV(AR->getStart(), getConstant(*StartRem));
3504 if (*StartRem != 0 && (NoWrap || CanFoldWithWrap) &&
3505 !isa<SCEVAddExpr>(NewStart)) {
3506 const SCEV *NewLHS =
3507 getAddRecExpr(NewStart, Step, AR->getLoop(),
3508 NoWrap ? SCEV::FlagNW : SCEV::FlagNone);
3509 if (LHS != NewLHS)
3510 return getUDivExpr(NewLHS, RHS);
3511 }
3512 }
3513 }
3514 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3515 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3516 if (M->hasNoUnsignedWrap()) {
3517 // Find an operand that's safely divisible.
3518 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3519 const SCEV *Op = M->getOperand(i);
3520 const SCEV *Div = getUDivExpr(Op, RHSC);
3521 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3522 SmallVector<SCEVUse, 4> Operands(M->operands());
3523 Operands[i] = Div;
3524 return getMulExpr(Operands);
3525 }
3526 }
3527
3528 // Even if it's not divisible, try to remove a common factor.
3529 if (const auto *LHSC = dyn_cast<SCEVConstant>(M->getOperand(0))) {
3530 APInt Factor = APIntOps::GreatestCommonDivisor(LHSC->getAPInt(),
3531 RHSC->getAPInt());
3532 if (!Factor.isIntN(1)) {
3533 SmallVector<SCEVUse, 2> NewOperands;
3534 NewOperands.push_back(getConstant(LHSC->getAPInt().udiv(Factor)));
3535 append_range(NewOperands, M->operands().drop_front());
3536 const SCEV *NewMul = getMulExpr(NewOperands);
3537 return getUDivExpr(NewMul,
3538 getConstant(RHSC->getAPInt().udiv(Factor)));
3539 }
3540 }
3541 }
3542 }
3543
3544 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3545 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3546 if (auto *DivisorConstant =
3547 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3548 bool Overflow = false;
3549 APInt NewRHS =
3550 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3551 if (Overflow) {
3552 return getConstant(RHSC->getType(), 0, false);
3553 }
3554 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3555 }
3556 }
3557
3558 // (A+B)/C --> (A/C + B/C) if the add does not unsigned wrap and A/C and
3559 // B/C can be folded.
3560 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3561 if (A->hasNoUnsignedWrap()) {
3563 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3564 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3565 if (isa<SCEVUDivExpr>(Op) ||
3566 getMulExpr(Op, RHS) != A->getOperand(i))
3567 break;
3568 Operands.push_back(Op);
3569 }
3570 if (Operands.size() == A->getNumOperands())
3571 return getAddExpr(Operands);
3572 }
3573 }
3574
3575 // ((N - M) + (M * A)) / N --> ((N - 1) + (M * A)) / N
3576 // This is an idiom for rounding A up to the next multiple of N, where A
3577 // is aready known to be a multiple of M. In this case, instcombine can
3578 // see that some low bits of the added constant are unused, so can clear
3579 // them, but we want to canonicalise to set the low bits. This makes the
3580 // pattern easier to match, without needing to check for known bits in
3581 // A*M.
3582 const APInt &N = RHSC->getAPInt();
3583 const APInt *NMinusM, *M;
3584 const SCEV *A;
3585 if (match(LHS, m_scev_Add(m_scev_APInt(NMinusM),
3586 m_scev_Mul(m_scev_APInt(M), m_SCEV(A))))) {
3587 if (N.isPowerOf2() && M->isPowerOf2() && M->ult(N) &&
3588 *NMinusM == N - *M) {
3589 return getUDivExpr(
3591 RHS);
3592 }
3593 }
3594
3595 // Fold if both operands are constant.
3596 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3597 return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3598 }
3599 }
3600
3601 // ((-C + (C smax %x)) /u %x) evaluates to zero, for any positive constant C.
3602 const APInt *NegC, *C;
3603 if (match(LHS,
3606 NegC->isNegative() && !NegC->isMinSignedValue() && *C == -*NegC)
3607 return getZero(LHS->getType());
3608
3609 // (%a * %b)<nuw> / %b -> %a
3610 const auto *Mul = dyn_cast<SCEVMulExpr>(LHS);
3611 if (Mul && Mul->hasNoUnsignedWrap()) {
3612 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3613 if (Mul->getOperand(i) == RHS) {
3615 append_range(Operands, Mul->operands().take_front(i));
3616 append_range(Operands, Mul->operands().drop_front(i + 1));
3617 return getMulExpr(Operands);
3618 }
3619 }
3620 }
3621
3622 // TODO: Generalize to handle any common factors.
3623 // udiv (mul nuw a, vscale), (mul nuw b, vscale) --> udiv a, b
3624 const SCEV *NewLHS, *NewRHS;
3625 if (match(LHS, m_scev_c_NUWMul(m_SCEV(NewLHS), m_SCEVVScale())) &&
3626 match(RHS, m_scev_c_NUWMul(m_SCEV(NewRHS), m_SCEVVScale())))
3627 return getUDivExpr(NewLHS, NewRHS);
3628
3629 return getOrCreateUDivExpr(LHS, RHS);
3630}
3631
3632/// Get a canonical unsigned division expression, or something simpler if
3633/// possible. There is no representation for an exact udiv in SCEV IR, but we
3634/// can attempt to optimize it prior to construction.
3636 // Currently there is no exact specific logic.
3637
3638 return getUDivExpr(LHS, RHS);
3639}
3640
3641/// Get an add recurrence expression for the specified loop. Simplify the
3642/// expression as much as possible.
3644 const Loop *L, SCEVFlagsPair Flags) {
3646 Operands.push_back(Start);
3647 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3648 if (StepChrec->getLoop() == L) {
3649 append_range(Operands, StepChrec->operands());
3650 // The use flags describe the two-operand recurrence, not the flattened
3651 // one built here, so drop them just like the expression's NUW/NSW.
3652 return getAddRecExpr(Operands, L,
3653 maskFlags(Flags.ExprFlags, SCEV::FlagNW));
3654 }
3655
3656 Operands.push_back(Step);
3657 return getAddRecExpr(Operands, L, Flags);
3658}
3659
3660/// Get an add recurrence expression for the specified loop. Simplify the
3661/// expression as much as possible.
3663 const Loop *L, SCEVFlagsPair NWFlags) {
3664 SCEVFlags ExprFlags = NWFlags.ExprFlags;
3665 SCEVFlags UseFlags = NWFlags.UseFlags;
3666 assert(!(UseFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
3667 "only nuw or nsw allowed");
3668 if (Operands.size() == 1) return Operands[0];
3669#ifndef NDEBUG
3671 for (const SCEV *Op : llvm::drop_begin(Operands)) {
3672 assert(getEffectiveSCEVType(Op->getType()) == ETy &&
3673 "SCEVAddRecExpr operand types don't match!");
3674 assert(!Op->getType()->isPointerTy() && "Step must be integer");
3675 }
3676 for (const SCEV *Op : Operands)
3678 "SCEVAddRecExpr operand is not available at loop entry!");
3679
3680 // Keep track of the original operands, for verification when adding
3681 // use-specific flags.
3682 const SmallVector<SCEVUse, 4> OrigOperands(Operands.begin(), Operands.end());
3683#endif
3684
3685 if (Operands.back()->isZero()) {
3686 Operands.pop_back();
3687 return getAddRecExpr(Operands, L, SCEV::FlagNone); // {X,+,0} --> X
3688 }
3689
3690 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3691 // use that information to infer NUW and NSW flags. However, computing a
3692 // BE count requires calling getAddRecExpr, so we may not yet have a
3693 // meaningful BE count at this point (and if we don't, we'd be stuck
3694 // with a SCEVCouldNotCompute as the cached BE count).
3695
3696 ExprFlags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, ExprFlags);
3697
3698 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3699 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3700 const Loop *NestedLoop = NestedAR->getLoop();
3701 if (L->contains(NestedLoop)
3702 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3703 : (!NestedLoop->contains(L) &&
3704 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3705 SmallVector<SCEVUse, 4> NestedOperands(NestedAR->operands());
3706 Operands[0] = NestedAR->getStart();
3707 // AddRecs require their operands be loop-invariant with respect to their
3708 // loops. Don't perform this transformation if it would break this
3709 // requirement.
3710 bool AllInvariant = all_of(
3711 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3712
3713 if (AllInvariant) {
3714 // Create a recurrence for the outer loop with the same step size.
3715 //
3716 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3717 // inner recurrence has the same property.
3718 SCEVFlags OuterFlags =
3719 maskFlags(ExprFlags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3720
3721 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3722 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3723 return isLoopInvariant(Op, NestedLoop);
3724 });
3725
3726 if (AllInvariant) {
3727 // Ok, both add recurrences are valid after the transformation.
3728 //
3729 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3730 // the outer recurrence has the same property.
3731 SCEVFlags InnerFlags =
3732 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | ExprFlags);
3733 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3734 }
3735 }
3736 // Reset Operands to its original state.
3737 Operands[0] = NestedAR;
3738 }
3739 }
3740
3741 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3742 // already have one, otherwise create a new one.
3743 assert((UseFlags == SCEV::FlagNone || equal(OrigOperands, Operands)) &&
3744 "Tried to add SCEVUse flags after operands changed");
3745 return {getOrCreateAddRecExpr(Operands, L, ExprFlags), UseFlags};
3746}
3747
3749 ArrayRef<SCEVUse> IndexExprs) {
3750 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3751 // getSCEV(Base)->getType() has the same address space as Base->getType()
3752 // because SCEV::getType() preserves the address space.
3753 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
3754 if (NW != GEPNoWrapFlags::none()) {
3755 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3756 // but to do that, we have to ensure that said flag is valid in the entire
3757 // defined scope of the SCEV.
3758 // TODO: non-instructions have global scope. We might be able to prove
3759 // some global scope cases
3760 auto *GEPI = dyn_cast<Instruction>(GEP);
3761 if (!GEPI || !isSCEVExprNeverPoison(GEPI))
3762 NW = GEPNoWrapFlags::none();
3763 }
3764
3765 return getGEPExpr(BaseExpr, IndexExprs, GEP->getSourceElementType(), NW);
3766}
3767
3769 ArrayRef<SCEVUse> IndexExprs,
3770 Type *SrcElementTy, GEPNoWrapFlags NW) {
3771 SCEVFlags OffsetWrap = SCEV::FlagNone;
3772 if (NW.hasNoUnsignedSignedWrap())
3773 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNSW);
3774 if (NW.hasNoUnsignedWrap())
3775 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNUW);
3776
3777 Type *CurTy = BaseExpr->getType();
3778 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3779 bool FirstIter = true;
3781 for (SCEVUse IndexExpr : IndexExprs) {
3782 // Compute the (potentially symbolic) offset in bytes for this index.
3783 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3784 // For a struct, add the member offset.
3785 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3786 unsigned FieldNo = Index->getZExtValue();
3787 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3788 Offsets.push_back(FieldOffset);
3789
3790 // Update CurTy to the type of the field at Index.
3791 CurTy = STy->getTypeAtIndex(Index);
3792 } else {
3793 // Update CurTy to its element type.
3794 if (FirstIter) {
3795 assert(isa<PointerType>(CurTy) &&
3796 "The first index of a GEP indexes a pointer");
3797 CurTy = SrcElementTy;
3798 FirstIter = false;
3799 } else {
3800 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3801 }
3802 // For an array, add the element offset, explicitly scaled.
3803 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3804 // Getelementptr indices are signed.
3805 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3806
3807 // Multiply the index by the element size to compute the element offset.
3808 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3809 Offsets.push_back(LocalOffset);
3810 }
3811 }
3812
3813 // Handle degenerate case of GEP without offsets.
3814 if (Offsets.empty())
3815 return BaseExpr;
3816
3817 // Add the offsets together, assuming nsw if inbounds.
3818 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3819 // Add the base address and the offset. We cannot use the nsw flag, as the
3820 // base address is unsigned. However, if we know that the offset is
3821 // non-negative, we can use nuw.
3822 bool NUW = NW.hasNoUnsignedWrap() ||
3824 SCEVFlags BaseWrap = NUW ? SCEV::FlagNUW : SCEV::FlagNone;
3825 const SCEV *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3826 assert(BaseExpr->getType() == GEPExpr->getType() &&
3827 "GEP should not change type mid-flight.");
3828 return GEPExpr;
3829}
3830
3831SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3833 const Loop *L) {
3834 assert((SCEVType != scAddRecExpr || L) &&
3835 "L must be passed to find existing AddRecs");
3837 ID.AddInteger(SCEVType);
3838 for (SCEVUse Op : Ops)
3839 ID.AddPointer(Op.getOpaqueValue());
3840 if (L)
3841 ID.AddPointer(L);
3843 return UniqueSCEVs.lookup(ID, Token);
3844}
3845
3846const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3847 SCEVFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagNone;
3848 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3849}
3850
3853 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3854 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3855 if (Ops.size() == 1) return Ops[0];
3856#ifndef NDEBUG
3857 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3858 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3859 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3860 "Operand types don't match!");
3861 assert(Ops[0]->getType()->isPointerTy() ==
3862 Ops[i]->getType()->isPointerTy() &&
3863 "min/max should be consistently pointerish");
3864 }
3865#endif
3866
3867 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3868 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3869
3870 const SCEV *Folded = constantFoldAndGroupOps(
3871 *this, LI, DT, Ops,
3872 [&](const APInt &C1, const APInt &C2) {
3873 switch (Kind) {
3874 case scSMaxExpr:
3875 return APIntOps::smax(C1, C2);
3876 case scSMinExpr:
3877 return APIntOps::smin(C1, C2);
3878 case scUMaxExpr:
3879 return APIntOps::umax(C1, C2);
3880 case scUMinExpr:
3881 return APIntOps::umin(C1, C2);
3882 default:
3883 llvm_unreachable("Unknown SCEV min/max opcode");
3884 }
3885 },
3886 [&](const APInt &C) {
3887 // identity
3888 if (IsMax)
3889 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3890 else
3891 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3892 },
3893 [&](const APInt &C) {
3894 // absorber
3895 if (IsMax)
3896 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3897 else
3898 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3899 });
3900 if (Folded)
3901 return Folded;
3902
3903 // Check if we have created the same expression before.
3904 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3905 return S;
3906 }
3907
3908 // Find the first operation of the same kind
3909 unsigned Idx = 0;
3910 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3911 ++Idx;
3912
3913 // Check to see if one of the operands is of the same kind. If so, expand its
3914 // operands onto our operand list, and recurse to simplify.
3915 if (Idx < Ops.size()) {
3916 bool DeletedAny = false;
3917 while (Ops[Idx]->getSCEVType() == Kind) {
3918 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3919 Ops.erase(Ops.begin()+Idx);
3920 append_range(Ops, SMME->operands());
3921 DeletedAny = true;
3922 }
3923
3924 if (DeletedAny)
3925 return getMinMaxExpr(Kind, Ops);
3926 }
3927
3928 // Okay, check to see if the same value occurs in the operand list twice. If
3929 // so, delete one. Since we sorted the list, these values are required to
3930 // be adjacent.
3935 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3936 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3937 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3938 if (Ops[i] == Ops[i + 1] ||
3939 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3940 // X op Y op Y --> X op Y
3941 // X op Y --> X, if we know X, Y are ordered appropriately
3942 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3943 --i;
3944 --e;
3945 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3946 Ops[i + 1])) {
3947 // X op Y --> Y, if we know X, Y are ordered appropriately
3948 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3949 --i;
3950 --e;
3951 }
3952 }
3953
3954 if (Ops.size() == 1) return Ops[0];
3955
3956 assert(!Ops.empty() && "Reduced smax down to nothing!");
3957
3958 // Okay, it looks like we really DO need an expr. Check to see if we
3959 // already have one, otherwise create a new one.
3961 ID.AddInteger(Kind);
3962 for (SCEVUse Op : Ops)
3963 ID.AddPointer(Op.getOpaqueValue());
3965 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
3966 if (ExistingSCEV)
3967 return ExistingSCEV;
3968 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3970 SCEV *S = new (SCEVAllocator)
3971 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3972
3973 UniqueSCEVs.insert(S, Token);
3974 S->computeAndSetCanonical(*this);
3975 registerUser(S, Ops);
3976 return S;
3977}
3978
3979namespace {
3980
3981class SCEVSequentialMinMaxDeduplicatingVisitor final
3982 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
3983 std::optional<const SCEV *>> {
3984 using RetVal = std::optional<const SCEV *>;
3985
3986 ScalarEvolution &SE;
3987 const SCEVTypes RootKind; // Must be a sequential min/max expression.
3988 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
3990
3991 bool canRecurseInto(SCEVTypes Kind) const {
3992 // We can only recurse into the SCEV expression of the same effective type
3993 // as the type of our root SCEV expression.
3994 return RootKind == Kind || NonSequentialRootKind == Kind;
3995 };
3996
3997 RetVal visit(const SCEV *S) {
3998 // Has the whole operand been seen already?
3999 if (!SeenOps.insert(S).second)
4000 return std::nullopt;
4002 SCEVTypes Kind = S->getSCEVType();
4003
4004 if (!canRecurseInto(Kind))
4005 return S;
4006
4007 auto *NAry = cast<SCEVNAryExpr>(S);
4008 SmallVector<SCEVUse> NewOps;
4009 bool Changed = visit(Kind, NAry->operands(), NewOps);
4010
4011 if (!Changed)
4012 return S;
4013 if (NewOps.empty())
4014 return std::nullopt;
4015
4017 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
4018 : SE.getMinMaxExpr(Kind, NewOps);
4019 }
4020 return S;
4021 }
4022
4023public:
4024 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
4025 SCEVTypes RootKind)
4026 : SE(SE), RootKind(RootKind),
4027 NonSequentialRootKind(
4028 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4029 RootKind)) {}
4030
4031 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<SCEVUse> OrigOps,
4032 SmallVectorImpl<SCEVUse> &NewOps) {
4033 bool Changed = false;
4035 Ops.reserve(OrigOps.size());
4036
4037 for (const SCEV *Op : OrigOps) {
4038 RetVal NewOp = visit(Op);
4039 if (NewOp != Op)
4040 Changed = true;
4041 if (NewOp)
4042 Ops.emplace_back(*NewOp);
4043 }
4044
4045 if (Changed)
4046 NewOps = std::move(Ops);
4047 return Changed;
4048 }
4049};
4050
4051} // namespace
4052
4054 switch (Kind) {
4055 case scConstant:
4056 case scVScale:
4057 case scTruncate:
4058 case scZeroExtend:
4059 case scSignExtend:
4060 case scPtrToAddr:
4061 case scAddExpr:
4062 case scMulExpr:
4063 case scUDivExpr:
4064 case scAddRecExpr:
4065 case scUMaxExpr:
4066 case scSMaxExpr:
4067 case scUMinExpr:
4068 case scSMinExpr:
4069 case scUnknown:
4070 // If any operand is poison, the whole expression is poison.
4071 return true;
4073 // FIXME: if the *first* operand is poison, the whole expression is poison.
4074 return false; // Pessimistically, say that it does not propagate poison.
4075 case scCouldNotCompute:
4076 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4077 }
4078 llvm_unreachable("Unknown SCEV kind!");
4079}
4080
4081namespace {
4082// The only way poison may be introduced in a SCEV expression is from a
4083// poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4084// not SCEVConstant). Notably, SCEVFlags on SCEV nodes can *not*
4085// introduce poison -- they encode guaranteed, non-speculated knowledge.
4086//
4087// Additionally, all SCEV nodes propagate poison from inputs to outputs,
4088// with the notable exception of umin_seq, where only poison from the first
4089// operand is (unconditionally) propagated.
4090struct SCEVPoisonCollector {
4091 bool LookThroughMaybePoisonBlocking;
4092 SmallPtrSet<const SCEVUnknown *, 4> MaybePoison;
4093 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4094 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4095
4096 bool follow(const SCEV *S) {
4097 if (!LookThroughMaybePoisonBlocking &&
4099 return false;
4100
4101 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4102 if (!isGuaranteedNotToBePoison(SU->getValue()))
4103 MaybePoison.insert(SU);
4104 }
4105 return true;
4106 }
4107 bool isDone() const { return false; }
4108};
4109} // namespace
4110
4111/// Return true if V is poison given that AssumedPoison is already poison.
4112static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4113 // First collect all SCEVs that might result in AssumedPoison to be poison.
4114 // We need to look through potentially poison-blocking operations here,
4115 // because we want to find all SCEVs that *might* result in poison, not only
4116 // those that are *required* to.
4117 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4118 visitAll(AssumedPoison, PC1);
4119
4120 // AssumedPoison is never poison. As the assumption is false, the implication
4121 // is true. Don't bother walking the other SCEV in this case.
4122 if (PC1.MaybePoison.empty())
4123 return true;
4124
4125 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4126 // as well. We cannot look through potentially poison-blocking operations
4127 // here, as their arguments only *may* make the result poison.
4128 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4129 visitAll(S, PC2);
4130
4131 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4132 // it will also make S poison by being part of PC2.MaybePoison.
4133 return llvm::set_is_subset(PC1.MaybePoison, PC2.MaybePoison);
4134}
4135
4137 SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4138 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4139 visitAll(S, PC);
4140 for (const SCEVUnknown *SU : PC.MaybePoison)
4141 Result.insert(SU->getValue());
4142}
4143
4145 const SCEV *S, Instruction *I,
4146 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
4147 // If the instruction cannot be poison, it's always safe to reuse.
4149 return true;
4150
4151 // Otherwise, it is possible that I is more poisonous that S. Collect the
4152 // poison-contributors of S, and then check whether I has any additional
4153 // poison-contributors. Poison that is contributed through poison-generating
4154 // flags is handled by dropping those flags instead.
4156 getPoisonGeneratingValues(PoisonVals, S);
4157
4158 SmallVector<Value *> Worklist;
4160 Worklist.push_back(I);
4161 unsigned NumVisitedInsts = 0;
4162 const unsigned InstLimit = std::max<unsigned>(16, S->getExpressionSize());
4163 while (!Worklist.empty()) {
4164 Value *V = Worklist.pop_back_val();
4165 if (!Visited.insert(V).second)
4166 continue;
4167
4168 // Either the value can't be poison, or the S would also be poison if it
4169 // is.
4170 if (PoisonVals.contains(V) || ::isGuaranteedNotToBePoison(V))
4171 continue;
4172
4173 // Avoid walking large instruction graphs.
4174 if (++NumVisitedInsts > InstLimit)
4175 return false;
4176
4177 auto *I = dyn_cast<Instruction>(V);
4178 if (!I)
4179 return false;
4180
4181 // Disjoint or instructions are interpreted as adds by SCEV. However, we
4182 // can't replace an arbitrary add with disjoint or, even if we drop the
4183 // flag. We would need to convert the or into an add.
4184 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
4185 if (PDI->isDisjoint())
4186 return false;
4187
4188 // FIXME: Ignore vscale, even though it technically could be poison. Do this
4189 // because SCEV currently assumes it can't be poison. Remove this special
4190 // case once we proper model when vscale can be poison.
4191 if (auto *II = dyn_cast<IntrinsicInst>(I);
4192 II && II->getIntrinsicID() == Intrinsic::vscale)
4193 continue;
4194
4195 if (canCreatePoison(cast<Operator>(I), /*ConsiderFlagsAndMetadata*/ false))
4196 return false;
4197
4198 // If the instruction can't create poison, we can recurse to its operands.
4199 if (I->hasPoisonGeneratingAnnotations())
4200 DropPoisonGeneratingInsts.push_back(I);
4201
4202 llvm::append_range(Worklist, I->operands());
4203 }
4204 return true;
4205}
4206
4207const SCEV *
4210 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4211 "Not a SCEVSequentialMinMaxExpr!");
4212 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4213 if (Ops.size() == 1)
4214 return Ops[0];
4215#ifndef NDEBUG
4216 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4217 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4218 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4219 "Operand types don't match!");
4220 assert(Ops[0]->getType()->isPointerTy() ==
4221 Ops[i]->getType()->isPointerTy() &&
4222 "min/max should be consistently pointerish");
4223 }
4224#endif
4225
4226 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4227 // so we can *NOT* do any kind of sorting of the expressions!
4228
4229 // Check if we have created the same expression before.
4230 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4231 return S;
4232
4233 // FIXME: there are *some* simplifications that we can do here.
4234
4235 // Keep only the first instance of an operand.
4236 {
4237 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4238 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4239 if (Changed)
4240 return getSequentialMinMaxExpr(Kind, Ops);
4241 }
4242
4243 // Check to see if one of the operands is of the same kind. If so, expand its
4244 // operands onto our operand list, and recurse to simplify.
4245 {
4246 unsigned Idx = 0;
4247 bool DeletedAny = false;
4248 while (Idx < Ops.size()) {
4249 if (Ops[Idx]->getSCEVType() != Kind) {
4250 ++Idx;
4251 continue;
4252 }
4253 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4254 Ops.erase(Ops.begin() + Idx);
4255 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4256 SMME->operands().end());
4257 DeletedAny = true;
4258 }
4259
4260 if (DeletedAny)
4261 return getSequentialMinMaxExpr(Kind, Ops);
4262 }
4263
4264 const SCEV *SaturationPoint;
4266 switch (Kind) {
4268 SaturationPoint = getZero(Ops[0]->getType());
4269 Pred = ICmpInst::ICMP_ULE;
4270 break;
4271 default:
4272 llvm_unreachable("Not a sequential min/max type.");
4273 }
4274
4275 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4276 if (!isGuaranteedNotToCauseUB(Ops[i]))
4277 continue;
4278 // We can replace %x umin_seq %y with %x umin %y if either:
4279 // * %y being poison implies %x is also poison.
4280 // * %x cannot be the saturating value (e.g. zero for umin).
4281 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4282 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4283 SaturationPoint)) {
4284 SmallVector<SCEVUse, 2> SeqOps = {Ops[i - 1], Ops[i]};
4285 Ops[i - 1] = getMinMaxExpr(
4287 SeqOps);
4288 Ops.erase(Ops.begin() + i);
4289 return getSequentialMinMaxExpr(Kind, Ops);
4290 }
4291 // Fold %x umin_seq %y to %x if %x ule %y.
4292 // TODO: We might be able to prove the predicate for a later operand.
4293 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4294 Ops.erase(Ops.begin() + i);
4295 return getSequentialMinMaxExpr(Kind, Ops);
4296 }
4297 }
4298
4299 // Okay, it looks like we really DO need an expr. Check to see if we
4300 // already have one, otherwise create a new one.
4302 ID.AddInteger(Kind);
4303 for (SCEVUse Op : Ops)
4304 ID.AddPointer(Op.getOpaqueValue());
4306 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
4307 if (ExistingSCEV)
4308 return ExistingSCEV;
4309
4310 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4312 SCEV *S = new (SCEVAllocator)
4313 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4314
4315 UniqueSCEVs.insert(S, Token);
4316 S->computeAndSetCanonical(*this);
4317 registerUser(S, Ops);
4318 return S;
4319}
4320
4325
4329
4334
4338
4343
4347
4349 bool Sequential) {
4350 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4351 return getUMinExpr(Ops, Sequential);
4352}
4353
4359
4360const SCEV *
4362 const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4363 if (Size.isScalable())
4364 Res = getMulExpr(Res, getVScale(IntTy));
4365 return Res;
4366}
4367
4369 return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4370}
4371
4373 return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4374}
4375
4377 StructType *STy,
4378 unsigned FieldNo) {
4379 // We can bypass creating a target-independent constant expression and then
4380 // folding it back into a ConstantInt. This is just a compile-time
4381 // optimization.
4382 const StructLayout *SL = getDataLayout().getStructLayout(STy);
4383 assert(!SL->getSizeInBits().isScalable() &&
4384 "Cannot get offset for structure containing scalable vector types");
4385 return getConstant(IntTy, SL->getElementOffset(FieldNo));
4386}
4387
4389 // Don't attempt to do anything other than create a SCEVUnknown object
4390 // here. createSCEV only calls getUnknown after checking for all other
4391 // interesting possibilities, and any other code that calls getUnknown
4392 // is doing so in order to hide a value from SCEV canonicalization.
4393
4396 ID.AddPointer(V);
4398 if (SCEV *S = UniqueSCEVs.lookup(ID, Token)) {
4399 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4400 "Stale SCEVUnknown in uniquing map!");
4401 return S;
4402 }
4403 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4404 FirstUnknown, NextUnknownOrderID++);
4405 FirstUnknown = cast<SCEVUnknown>(S);
4406 UniqueSCEVs.insert(S, Token);
4407 S->computeAndSetCanonical(*this);
4408 return S;
4409}
4410
4411//===----------------------------------------------------------------------===//
4412// Basic SCEV Analysis and PHI Idiom Recognition Code
4413//
4414
4415/// Test if values of the given type are analyzable within the SCEV
4416/// framework. This primarily includes integer types, and it can optionally
4417/// include pointer types if the ScalarEvolution class has access to
4418/// target-specific information.
4420 // Integers and pointers are always SCEVable.
4421 return Ty->isIntOrPtrTy();
4422}
4423
4424/// Return the size in bits of the specified type, for which isSCEVable must
4425/// return true.
4427 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4428 if (Ty->isPointerTy())
4430 return getDataLayout().getTypeSizeInBits(Ty);
4431}
4432
4433/// Return a type with the same bitwidth as the given type and which represents
4434/// how SCEV will treat the given type, for which isSCEVable must return
4435/// true. For pointer types, this is the pointer index sized integer type.
4437 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4438
4439 if (Ty->isIntegerTy())
4440 return Ty;
4441
4442 // The only other support type is pointer.
4443 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4444 return getDataLayout().getIndexType(Ty);
4445}
4446
4448 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4449}
4450
4452 const SCEV *B) {
4453 /// For a valid use point to exist, the defining scope of one operand
4454 /// must dominate the other.
4455 bool PreciseA, PreciseB;
4456 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4457 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4458 if (!PreciseA || !PreciseB)
4459 // Can't tell.
4460 return false;
4461 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4462 DT.dominates(ScopeB, ScopeA);
4463}
4464
4466 return CouldNotCompute.get();
4467}
4468
4469bool ScalarEvolution::checkValidity(const SCEV *S) const {
4470 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4471 auto *SU = dyn_cast<SCEVUnknown>(S);
4472 return SU && SU->getValue() == nullptr;
4473 });
4474
4475 return !ContainsNulls;
4476}
4477
4479 HasRecMapType::iterator I = HasRecMap.find(S);
4480 if (I != HasRecMap.end())
4481 return I->second;
4482
4483 bool FoundAddRec =
4484 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4485 HasRecMap.insert({S, FoundAddRec});
4486 return FoundAddRec;
4487}
4488
4489/// Return the ValueOffsetPair set for \p S. \p S can be represented
4490/// by the value and offset from any ValueOffsetPair in the set.
4491ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4492 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4493 if (SI == ExprValueMap.end())
4494 return {};
4495 return SI->second.getArrayRef();
4496}
4497
4498/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4499/// cannot be used separately. eraseValueFromMap should be used to remove
4500/// V from ValueExprMap and ExprValueMap at the same time.
4501void ScalarEvolution::eraseValueFromMap(Value *V) {
4502 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4503 if (I != ValueExprMap.end()) {
4504 auto EVIt = ExprValueMap.find(I->second);
4505 bool Removed = EVIt->second.remove(V);
4506 (void) Removed;
4507 assert(Removed && "Value not in ExprValueMap?");
4508 ValueExprMap.erase(I);
4509 }
4510}
4511
4512void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4513 // A recursive query may have already computed the SCEV. It should be
4514 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4515 // inferred nowrap flags.
4516 auto It = ValueExprMap.find_as(V);
4517 if (It == ValueExprMap.end()) {
4518 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4519 ExprValueMap[S].insert(V);
4520 }
4521}
4522
4523/// Return an existing SCEV if it exists, otherwise analyze the expression and
4524/// create a new one.
4526 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4527
4528 if (const SCEV *S = getExistingSCEV(V))
4529 return S;
4530 return createSCEVIter(V);
4531}
4532
4534 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4535
4536 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4537 if (I != ValueExprMap.end()) {
4538 const SCEV *S = I->second;
4539 assert(checkValidity(S) &&
4540 "existing SCEV has not been properly invalidated");
4541 return S;
4542 }
4543 return nullptr;
4544}
4545
4546/// Return a SCEV corresponding to -V = -1*V
4548 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4549 return getConstant(
4550 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4551
4552 Type *Ty = V->getType();
4553 Ty = getEffectiveSCEVType(Ty);
4554 return getMulExpr(V, getMinusOne(Ty), Flags);
4555}
4556
4557/// If Expr computes ~A, return A else return nullptr
4558static const SCEV *MatchNotExpr(const SCEV *Expr) {
4559 const SCEV *MulOp;
4560 if (match(Expr, m_scev_Add(m_scev_AllOnes(),
4561 m_scev_Mul(m_scev_AllOnes(), m_SCEV(MulOp)))))
4562 return MulOp;
4563 return nullptr;
4564}
4565
4566/// Return a SCEV corresponding to ~V = -1-V
4568 assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4569
4570 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4571 return getConstant(
4572 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4573
4574 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4575 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4576 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4577 SmallVector<SCEVUse, 2> MatchedOperands;
4578 for (const SCEV *Operand : MME->operands()) {
4579 const SCEV *Matched = MatchNotExpr(Operand);
4580 if (!Matched)
4581 return (const SCEV *)nullptr;
4582 MatchedOperands.push_back(Matched);
4583 }
4584 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4585 MatchedOperands);
4586 };
4587 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4588 return Replaced;
4589 }
4590
4591 Type *Ty = V->getType();
4592 Ty = getEffectiveSCEVType(Ty);
4593 return getMinusSCEV(getMinusOne(Ty), V);
4594}
4595
4597 assert(P->getType()->isPointerTy());
4598
4599 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4600 // The base of an AddRec is the first operand.
4601 SmallVector<SCEVUse> Ops{AddRec->operands()};
4602 Ops[0] = removePointerBase(Ops[0]);
4603 // Don't try to transfer nowrap flags for now. We could in some cases
4604 // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4605 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagNone);
4606 }
4607 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4608 // The base of an Add is the pointer operand.
4609 SmallVector<SCEVUse> Ops{Add->operands()};
4610 SCEVUse *PtrOp = nullptr;
4611 for (SCEVUse &AddOp : Ops) {
4612 if (AddOp->getType()->isPointerTy()) {
4613 assert(!PtrOp && "Cannot have multiple pointer ops");
4614 PtrOp = &AddOp;
4615 }
4616 }
4617 *PtrOp = removePointerBase(*PtrOp);
4618 // Don't try to transfer nowrap flags for now. We could in some cases
4619 // (for example, if the pointer operand of the Add is a SCEVUnknown).
4620 return getAddExpr(Ops);
4621 }
4622 // Any other expression must be a pointer base.
4623 return getZero(P->getType());
4624}
4625
4627 SCEVFlags Flags, unsigned Depth) {
4628 // Fast path: X - X --> 0.
4629 if (LHS == RHS)
4630 return getZero(LHS->getType());
4631
4632 // If we subtract two pointers with different pointer bases, bail.
4633 // Eventually, we're going to add an assertion to getMulExpr that we
4634 // can't multiply by a pointer.
4635 if (RHS->getType()->isPointerTy()) {
4636 if (!LHS->getType()->isPointerTy() ||
4637 getPointerBase(LHS) != getPointerBase(RHS))
4638 return getCouldNotCompute();
4639 LHS = removePointerBase(LHS);
4640 RHS = removePointerBase(RHS);
4641 }
4642
4643 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4644 // makes it so that we cannot make much use of NUW.
4645 auto AddFlags = SCEV::FlagNone;
4646 const bool RHSIsNotMinSigned =
4648 if (hasFlags(Flags, SCEV::FlagNSW)) {
4649 // Let M be the minimum representable signed value. Then (-1)*RHS
4650 // signed-wraps if and only if RHS is M. That can happen even for
4651 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4652 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4653 // (-1)*RHS, we need to prove that RHS != M.
4654 //
4655 // If LHS is non-negative and we know that LHS - RHS does not
4656 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4657 // either by proving that RHS > M or that LHS >= 0.
4658 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4659 AddFlags = SCEV::FlagNSW;
4660 }
4661 }
4662
4663 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4664 // RHS is NSW and LHS >= 0.
4665 //
4666 // The difficulty here is that the NSW flag may have been proven
4667 // relative to a loop that is to be found in a recurrence in LHS and
4668 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4669 // larger scope than intended.
4670 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagNone;
4671
4672 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4673}
4674
4676 unsigned Depth) {
4677 Type *SrcTy = V->getType();
4678 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4679 "Cannot truncate or zero extend with non-integer arguments!");
4680 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4681 return V; // No conversion
4682 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4683 return getTruncateExpr(V, Ty, Depth);
4684 return getZeroExtendExpr(V, Ty, Depth);
4685}
4686
4688 unsigned Depth) {
4689 Type *SrcTy = V->getType();
4690 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4691 "Cannot truncate or zero extend with non-integer arguments!");
4692 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4693 return V; // No conversion
4694 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4695 return getTruncateExpr(V, Ty, Depth);
4696 return getSignExtendExpr(V, Ty, Depth);
4697}
4698
4700 Type *SrcTy = V->getType();
4701 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4702 "Cannot noop or zero extend with non-integer arguments!");
4704 "getNoopOrZeroExtend cannot truncate!");
4705 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4706 return V; // No conversion
4707 return getZeroExtendExpr(V, Ty);
4708}
4709
4711 Type *SrcTy = V->getType();
4712 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4713 "Cannot noop or sign extend with non-integer arguments!");
4715 "getNoopOrSignExtend cannot truncate!");
4716 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4717 return V; // No conversion
4718 return getSignExtendExpr(V, Ty);
4719}
4720
4722 Type *SrcTy = V->getType();
4723 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4724 "Cannot noop or any extend with non-integer arguments!");
4726 "getNoopOrAnyExtend cannot truncate!");
4727 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4728 return V; // No conversion
4729 return getAnyExtendExpr(V, Ty);
4730}
4731
4733 Type *SrcTy = V->getType();
4734 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4735 "Cannot truncate or noop with non-integer arguments!");
4737 "getTruncateOrNoop cannot extend!");
4738 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4739 return V; // No conversion
4740 return getTruncateExpr(V, Ty);
4741}
4742
4744 const SCEV *RHS) {
4745 const SCEV *PromotedLHS = LHS;
4746 const SCEV *PromotedRHS = RHS;
4747
4748 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4749 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4750 else
4751 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4752
4753 return getUMaxExpr(PromotedLHS, PromotedRHS);
4754}
4755
4757 const SCEV *RHS,
4758 bool Sequential) {
4759 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4760 return getUMinFromMismatchedTypes(Ops, Sequential);
4761}
4762
4763const SCEV *
4765 bool Sequential) {
4766 assert(!Ops.empty() && "At least one operand must be!");
4767 // Trivial case.
4768 if (Ops.size() == 1)
4769 return Ops[0];
4770
4771 // Find the max type first.
4772 Type *MaxType = nullptr;
4773 for (SCEVUse S : Ops)
4774 if (MaxType)
4775 MaxType = getWiderType(MaxType, S->getType());
4776 else
4777 MaxType = S->getType();
4778 assert(MaxType && "Failed to find maximum type!");
4779
4780 // Extend all ops to max type.
4781 SmallVector<SCEVUse, 2> PromotedOps;
4782 for (SCEVUse S : Ops)
4783 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4784
4785 // Generate umin.
4786 return getUMinExpr(PromotedOps, Sequential);
4787}
4788
4790 // A pointer operand may evaluate to a nonpointer expression, such as null.
4791 if (!V->getType()->isPointerTy())
4792 return V;
4793
4794 while (true) {
4795 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4796 V = AddRec->getStart();
4797 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4798 const SCEV *PtrOp = nullptr;
4799 for (const SCEV *AddOp : Add->operands()) {
4800 if (AddOp->getType()->isPointerTy()) {
4801 assert(!PtrOp && "Cannot have multiple pointer ops");
4802 PtrOp = AddOp;
4803 }
4804 }
4805 assert(PtrOp && "Must have pointer op");
4806 V = PtrOp;
4807 } else // Not something we can look further into.
4808 return V;
4809 }
4810}
4811
4812/// Push users of the given Instruction onto the given Worklist.
4816 // Push the def-use children onto the Worklist stack.
4817 for (User *U : I->users()) {
4818 auto *UserInsn = cast<Instruction>(U);
4819 if (Visited.insert(UserInsn).second)
4820 Worklist.push_back(UserInsn);
4821 }
4822}
4823
4824namespace {
4825
4826/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4827/// expression in case its Loop is L. If it is not L then
4828/// if IgnoreOtherLoops is true then use AddRec itself
4829/// otherwise rewrite cannot be done.
4830/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4831class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4832public:
4833 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4834 bool IgnoreOtherLoops = true) {
4835 SCEVInitRewriter Rewriter(L, SE);
4836 const SCEV *Result = Rewriter.visit(S);
4837 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4838 return SE.getCouldNotCompute();
4839 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4840 ? SE.getCouldNotCompute()
4841 : Result;
4842 }
4843
4844 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4845 if (!SE.isLoopInvariant(Expr, L))
4846 SeenLoopVariantSCEVUnknown = true;
4847 return Expr;
4848 }
4849
4850 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4851 // Only re-write AddRecExprs for this loop.
4852 if (Expr->getLoop() == L)
4853 return Expr->getStart();
4854 SeenOtherLoops = true;
4855 return Expr;
4856 }
4857
4858 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4859
4860 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4861
4862private:
4863 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4864 : SCEVRewriteVisitor(SE), L(L) {}
4865
4866 const Loop *L;
4867 bool SeenLoopVariantSCEVUnknown = false;
4868 bool SeenOtherLoops = false;
4869};
4870
4871/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4872/// increment expression in case its Loop is L. If it is not L then
4873/// use AddRec itself.
4874/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4875class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4876public:
4877 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4878 SCEVPostIncRewriter Rewriter(L, SE);
4879 const SCEV *Result = Rewriter.visit(S);
4880 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4881 ? SE.getCouldNotCompute()
4882 : Result;
4883 }
4884
4885 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4886 if (!SE.isLoopInvariant(Expr, L))
4887 SeenLoopVariantSCEVUnknown = true;
4888 return Expr;
4889 }
4890
4891 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4892 // Only re-write AddRecExprs for this loop.
4893 if (Expr->getLoop() == L)
4894 return Expr->getPostIncExpr(SE);
4895 SeenOtherLoops = true;
4896 return Expr;
4897 }
4898
4899 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4900
4901 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4902
4903private:
4904 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4905 : SCEVRewriteVisitor(SE), L(L) {}
4906
4907 const Loop *L;
4908 bool SeenLoopVariantSCEVUnknown = false;
4909 bool SeenOtherLoops = false;
4910};
4911
4912/// This class evaluates the compare condition by matching it against the
4913/// condition of loop latch. If there is a match we assume a true value
4914/// for the condition while building SCEV nodes.
4915class SCEVBackedgeConditionFolder
4916 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4917public:
4918 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4919 ScalarEvolution &SE) {
4920 bool IsPosBECond = false;
4921 Value *BECond = nullptr;
4922 if (BasicBlock *Latch = L->getLoopLatch()) {
4923 if (CondBrInst *BI = dyn_cast<CondBrInst>(Latch->getTerminator())) {
4924 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4925 "Both outgoing branches should not target same header!");
4926 BECond = BI->getCondition();
4927 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4928 } else {
4929 return S;
4930 }
4931 }
4932 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4933 return Rewriter.visit(S);
4934 }
4935
4936 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4937 const SCEV *Result = Expr;
4938 bool InvariantF = SE.isLoopInvariant(Expr, L);
4939
4940 if (!InvariantF) {
4942 switch (I->getOpcode()) {
4943 case Instruction::Select: {
4944 SelectInst *SI = cast<SelectInst>(I);
4945 std::optional<const SCEV *> Res =
4946 compareWithBackedgeCondition(SI->getCondition());
4947 if (Res) {
4948 bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
4949 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4950 }
4951 break;
4952 }
4953 default: {
4954 std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4955 if (Res)
4956 Result = *Res;
4957 break;
4958 }
4959 }
4960 }
4961 return Result;
4962 }
4963
4964private:
4965 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4966 bool IsPosBECond, ScalarEvolution &SE)
4967 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4968 IsPositiveBECond(IsPosBECond) {}
4969
4970 std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4971
4972 const Loop *L;
4973 /// Loop back condition.
4974 Value *BackedgeCond = nullptr;
4975 /// Set to true if loop back is on positive branch condition.
4976 bool IsPositiveBECond;
4977};
4978
4979std::optional<const SCEV *>
4980SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4981
4982 // If value matches the backedge condition for loop latch,
4983 // then return a constant evolution node based on loopback
4984 // branch taken.
4985 if (BackedgeCond == IC)
4986 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4988 return std::nullopt;
4989}
4990
4991class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4992public:
4993 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4994 ScalarEvolution &SE) {
4995 SCEVShiftRewriter Rewriter(L, SE);
4996 const SCEV *Result = Rewriter.visit(S);
4997 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4998 }
4999
5000 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5001 // Only allow AddRecExprs for this loop.
5002 if (!SE.isLoopInvariant(Expr, L))
5003 Valid = false;
5004 return Expr;
5005 }
5006
5007 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5008 if (Expr->getLoop() == L && Expr->isAffine())
5009 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
5010 Valid = false;
5011 return Expr;
5012 }
5013
5014 bool isValid() { return Valid; }
5015
5016private:
5017 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
5018 : SCEVRewriteVisitor(SE), L(L) {}
5019
5020 const Loop *L;
5021 bool Valid = true;
5022};
5023
5024} // end anonymous namespace
5025
5026void ScalarEvolution::inferNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
5027 if (!AR->isAffine())
5028 return;
5029
5030 // Force computation of ranges, which will also perform range-based flag
5031 // inference.
5032 if (!AR->hasNoSignedWrap())
5033 (void)getSignedRange(AR);
5034
5035 if (!AR->hasNoUnsignedWrap())
5036 (void)getUnsignedRange(AR);
5037
5038 if (!AR->hasNoSelfWrap()) {
5039 const SCEV *BECount = getConstantMaxBackedgeTakenCount(AR->getLoop());
5040 if (const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(BECount)) {
5041 ConstantRange StepCR = getSignedRange(AR->getStepRecurrence(*this));
5042 const APInt &BECountAP = BECountMax->getAPInt();
5043 unsigned NoOverflowBitWidth =
5044 BECountAP.getActiveBits() + StepCR.getMinSignedBits();
5045 if (NoOverflowBitWidth <= getTypeSizeInBits(AR->getType()))
5046 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
5047 }
5048 }
5049}
5050
5052ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5054
5055 if (AR->hasNoSignedWrap())
5056 return Result;
5057
5058 if (!AR->isAffine())
5059 return Result;
5060
5061 // This function can be expensive, only try to prove NSW once per AddRec.
5062 if (!SignedWrapViaInductionTried.insert(AR).second)
5063 return Result;
5064
5065 const SCEV *Step = AR->getStepRecurrence(*this);
5066 const Loop *L = AR->getLoop();
5067
5068 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5069 // Note that this serves two purposes: It filters out loops that are
5070 // simply not analyzable, and it covers the case where this code is
5071 // being called from within backedge-taken count analysis, such that
5072 // attempting to ask for the backedge-taken count would likely result
5073 // in infinite recursion. In the later case, the analysis code will
5074 // cope with a conservative value, and it will take care to purge
5075 // that value once it has finished.
5076 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5077
5078 // Normally, in the cases we can prove no-overflow via a
5079 // backedge guarding condition, we can also compute a backedge
5080 // taken count for the loop. The exceptions are assumptions and
5081 // guards present in the loop -- SCEV is not great at exploiting
5082 // these to compute max backedge taken counts, but can still use
5083 // these to prove lack of overflow. Use this fact to avoid
5084 // doing extra work that may not pay off.
5085
5086 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5087 AC.assumptions().empty())
5088 return Result;
5089
5090 // If the backedge is guarded by a comparison with the pre-inc value the
5091 // addrec is safe. Also, if the entry is guarded by a comparison with the
5092 // start value and the backedge is guarded by a comparison with the post-inc
5093 // value, the addrec is safe.
5095 const SCEV *OverflowLimit =
5096 getSignedOverflowLimitForStep(Step, &Pred, this);
5097 if (OverflowLimit &&
5098 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5099 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
5100 Result = setFlags(Result, SCEV::FlagNSW);
5101 }
5102 return Result;
5103}
5105ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5107
5108 if (AR->hasNoUnsignedWrap())
5109 return Result;
5110
5111 if (!AR->isAffine())
5112 return Result;
5113
5114 // This function can be expensive, only try to prove NUW once per AddRec.
5115 if (!UnsignedWrapViaInductionTried.insert(AR).second)
5116 return Result;
5117
5118 const SCEV *Step = AR->getStepRecurrence(*this);
5119 const Loop *L = AR->getLoop();
5120
5121 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5122 // Note that this serves two purposes: It filters out loops that are
5123 // simply not analyzable, and it covers the case where this code is
5124 // being called from within backedge-taken count analysis, such that
5125 // attempting to ask for the backedge-taken count would likely result
5126 // in infinite recursion. In the later case, the analysis code will
5127 // cope with a conservative value, and it will take care to purge
5128 // that value once it has finished.
5129 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5130
5131 // Normally, in the cases we can prove no-overflow via a
5132 // backedge guarding condition, we can also compute a backedge
5133 // taken count for the loop. The exceptions are assumptions and
5134 // guards present in the loop -- SCEV is not great at exploiting
5135 // these to compute max backedge taken counts, but can still use
5136 // these to prove lack of overflow. Use this fact to avoid
5137 // doing extra work that may not pay off.
5138
5139 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5140 AC.assumptions().empty())
5141 return Result;
5142
5143 // If the backedge is guarded by a comparison with the pre-inc value the
5144 // addrec is safe. Also, if the entry is guarded by a comparison with the
5145 // start value and the backedge is guarded by a comparison with the post-inc
5146 // value, the addrec is safe.
5147 if (isKnownPositive(Step)) {
5149 const SCEV *OverflowLimit =
5150 getUnsignedOverflowLimitForStep(Step, &Pred, this);
5151 if (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5152 isKnownOnEveryIteration(Pred, AR, OverflowLimit))
5153 Result = setFlags(Result, SCEV::FlagNUW);
5154 }
5155 return Result;
5156}
5157
5158namespace {
5159
5160/// Represents an abstract binary operation. This may exist as a
5161/// normal instruction or constant expression, or may have been
5162/// derived from an expression tree.
5163struct BinaryOp {
5164 unsigned Opcode;
5165 Value *LHS;
5166 Value *RHS;
5167 bool IsNSW = false;
5168 bool IsNUW = false;
5169
5170 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5171 /// constant expression.
5172 Operator *Op = nullptr;
5173
5174 explicit BinaryOp(Operator *Op)
5175 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5176 Op(Op) {
5177 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5178 IsNSW = OBO->hasNoSignedWrap();
5179 IsNUW = OBO->hasNoUnsignedWrap();
5180 }
5181 }
5182
5183 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5184 bool IsNUW = false)
5185 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5186};
5187
5188} // end anonymous namespace
5189
5190/// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
5191static std::optional<BinaryOp> MatchBinaryOp(Value *V, const DataLayout &DL,
5192 AssumptionCache &AC,
5193 const DominatorTree &DT,
5194 const Instruction *CtxI) {
5195 auto *Op = dyn_cast<Operator>(V);
5196 if (!Op)
5197 return std::nullopt;
5198
5199 // Implementation detail: all the cleverness here should happen without
5200 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5201 // SCEV expressions when possible, and we should not break that.
5202
5203 switch (Op->getOpcode()) {
5204 case Instruction::Add:
5205 case Instruction::Sub:
5206 case Instruction::Mul:
5207 case Instruction::UDiv:
5208 case Instruction::URem:
5209 case Instruction::And:
5210 case Instruction::AShr:
5211 case Instruction::Shl:
5212 return BinaryOp(Op);
5213
5214 case Instruction::Or: {
5215 // Convert or disjoint into add nuw nsw.
5216 if (cast<PossiblyDisjointInst>(Op)->isDisjoint()) {
5217 BinaryOp BinOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
5218 /*IsNSW=*/true, /*IsNUW=*/true);
5219 // Keep the reference to the original instruction so that we can later
5220 // check whether it can produce poison value or not.
5221 BinOp.Op = Op;
5222 return BinOp;
5223 }
5224 return BinaryOp(Op);
5225 }
5226
5227 case Instruction::Xor:
5228 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5229 // If the RHS of the xor is a signmask, then this is just an add.
5230 // Instcombine turns add of signmask into xor as a strength reduction step.
5231 if (RHSC->getValue().isSignMask())
5232 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5233 // Binary `xor` is a bit-wise `add`.
5234 if (V->getType()->isIntegerTy(1))
5235 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5236 return BinaryOp(Op);
5237
5238 case Instruction::LShr:
5239 // Turn logical shift right of a constant into a unsigned divide.
5240 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5241 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5242
5243 // If the shift count is not less than the bitwidth, the result of
5244 // the shift is undefined. Don't try to analyze it, because the
5245 // resolution chosen here may differ from the resolution chosen in
5246 // other parts of the compiler.
5247 if (SA->getValue().ult(BitWidth)) {
5248 Constant *X =
5249 ConstantInt::get(SA->getContext(),
5250 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5251 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5252 }
5253 }
5254 return BinaryOp(Op);
5255
5256 case Instruction::ExtractValue: {
5257 auto *EVI = cast<ExtractValueInst>(Op);
5258 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5259 break;
5260
5261 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5262 if (!WO)
5263 break;
5264
5265 Instruction::BinaryOps BinOp = WO->getBinaryOp();
5266 bool Signed = WO->isSigned();
5267 // TODO: Should add nuw/nsw flags for mul as well.
5268 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5269 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5270
5271 // Now that we know that all uses of the arithmetic-result component of
5272 // CI are guarded by the overflow check, we can go ahead and pretend
5273 // that the arithmetic is non-overflowing.
5274 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5275 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5276 }
5277
5278 default:
5279 break;
5280 }
5281
5282 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5283 // semantics as a Sub, return a binary sub expression.
5284 if (auto *II = dyn_cast<IntrinsicInst>(V))
5285 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5286 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5287
5288 return std::nullopt;
5289}
5290
5291/// Helper function to createAddRecFromPHIWithCasts. We have a phi
5292/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5293/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5294/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5295/// follows one of the following patterns:
5296/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5297/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5298/// If the SCEV expression of \p Op conforms with one of the expected patterns
5299/// we return the type of the truncation operation, and indicate whether the
5300/// truncated type should be treated as signed/unsigned by setting
5301/// \p Signed to true/false, respectively.
5302static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5303 bool &Signed, ScalarEvolution &SE) {
5304 // The case where Op == SymbolicPHI (that is, with no type conversions on
5305 // the way) is handled by the regular add recurrence creating logic and
5306 // would have already been triggered in createAddRecForPHI. Reaching it here
5307 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5308 // because one of the other operands of the SCEVAddExpr updating this PHI is
5309 // not invariant).
5310 //
5311 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5312 // this case predicates that allow us to prove that Op == SymbolicPHI will
5313 // be added.
5314 if (Op == SymbolicPHI)
5315 return nullptr;
5316
5317 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5318 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5319 if (SourceBits != NewBits)
5320 return nullptr;
5321
5322 if (match(Op, m_scev_SExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5323 Signed = true;
5324 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5325 }
5326 if (match(Op, m_scev_ZExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5327 Signed = false;
5328 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5329 }
5330 return nullptr;
5331}
5332
5333static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5334 if (!PN->getType()->isIntegerTy())
5335 return nullptr;
5336 const Loop *L = LI.getLoopFor(PN->getParent());
5337 if (!L || L->getHeader() != PN->getParent())
5338 return nullptr;
5339 return L;
5340}
5341
5342// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5343// computation that updates the phi follows the following pattern:
5344// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5345// which correspond to a phi->trunc->sext/zext->add->phi update chain.
5346// If so, try to see if it can be rewritten as an AddRecExpr under some
5347// Predicates. If successful, return them as a pair. Also cache the results
5348// of the analysis.
5349//
5350// Example usage scenario:
5351// Say the Rewriter is called for the following SCEV:
5352// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5353// where:
5354// %X = phi i64 (%Start, %BEValue)
5355// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5356// and call this function with %SymbolicPHI = %X.
5357//
5358// The analysis will find that the value coming around the backedge has
5359// the following SCEV:
5360// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5361// Upon concluding that this matches the desired pattern, the function
5362// will return the pair {NewAddRec, SmallPredsVec} where:
5363// NewAddRec = {%Start,+,%Step}
5364// SmallPredsVec = {P1, P2, P3} as follows:
5365// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5366// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5367// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5368// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5369// under the predicates {P1,P2,P3}.
5370// This predicated rewrite will be cached in PredicatedSCEVRewrites:
5371// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5372//
5373// TODO's:
5374//
5375// 1) Extend the Induction descriptor to also support inductions that involve
5376// casts: When needed (namely, when we are called in the context of the
5377// vectorizer induction analysis), a Set of cast instructions will be
5378// populated by this method, and provided back to isInductionPHI. This is
5379// needed to allow the vectorizer to properly record them to be ignored by
5380// the cost model and to avoid vectorizing them (otherwise these casts,
5381// which are redundant under the runtime overflow checks, will be
5382// vectorized, which can be costly).
5383//
5384// 2) Support additional induction/PHISCEV patterns: We also want to support
5385// inductions where the sext-trunc / zext-trunc operations (partly) occur
5386// after the induction update operation (the induction increment):
5387//
5388// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5389// which correspond to a phi->add->trunc->sext/zext->phi update chain.
5390//
5391// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5392// which correspond to a phi->trunc->add->sext/zext->phi update chain.
5393//
5394// 3) Outline common code with createAddRecFromPHI to avoid duplication.
5395std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5396ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5398
5399 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5400 // return an AddRec expression under some predicate.
5401
5402 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5403 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5404 assert(L && "Expecting an integer loop header phi");
5405
5406 // The loop may have multiple entrances or multiple exits; we can analyze
5407 // this phi as an addrec if it has a unique entry value and a unique
5408 // backedge value.
5409 Value *BEValueV = nullptr, *StartValueV = nullptr;
5410 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5411 Value *V = PN->getIncomingValue(i);
5412 if (L->contains(PN->getIncomingBlock(i))) {
5413 if (!BEValueV) {
5414 BEValueV = V;
5415 } else if (BEValueV != V) {
5416 BEValueV = nullptr;
5417 break;
5418 }
5419 } else if (!StartValueV) {
5420 StartValueV = V;
5421 } else if (StartValueV != V) {
5422 StartValueV = nullptr;
5423 break;
5424 }
5425 }
5426 if (!BEValueV || !StartValueV)
5427 return std::nullopt;
5428
5429 const SCEV *BEValue = getSCEV(BEValueV);
5430
5431 // If the value coming around the backedge is an add with the symbolic
5432 // value we just inserted, possibly with casts that we can ignore under
5433 // an appropriate runtime guard, then we found a simple induction variable!
5434 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5435 if (!Add)
5436 return std::nullopt;
5437
5438 // If there is a single occurrence of the symbolic value, possibly
5439 // casted, replace it with a recurrence.
5440 unsigned FoundIndex = Add->getNumOperands();
5441 Type *TruncTy = nullptr;
5442 bool Signed;
5443 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5444 if ((TruncTy =
5445 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5446 if (FoundIndex == e) {
5447 FoundIndex = i;
5448 break;
5449 }
5450
5451 if (FoundIndex == Add->getNumOperands())
5452 return std::nullopt;
5453
5454 // Create an add with everything but the specified operand.
5456 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5457 if (i != FoundIndex)
5458 Ops.push_back(Add->getOperand(i));
5459 const SCEV *Accum = getAddExpr(Ops);
5460
5461 // The runtime checks will not be valid if the step amount is
5462 // varying inside the loop.
5463 if (!isLoopInvariant(Accum, L))
5464 return std::nullopt;
5465
5466 // *** Part2: Create the predicates
5467
5468 // Analysis was successful: we have a phi-with-cast pattern for which we
5469 // can return an AddRec expression under the following predicates:
5470 //
5471 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5472 // fits within the truncated type (does not overflow) for i = 0 to n-1.
5473 // P2: An Equal predicate that guarantees that
5474 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5475 // P3: An Equal predicate that guarantees that
5476 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5477 //
5478 // As we next prove, the above predicates guarantee that:
5479 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5480 //
5481 //
5482 // More formally, we want to prove that:
5483 // Expr(i+1) = Start + (i+1) * Accum
5484 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5485 //
5486 // Given that:
5487 // 1) Expr(0) = Start
5488 // 2) Expr(1) = Start + Accum
5489 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5490 // 3) Induction hypothesis (step i):
5491 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5492 //
5493 // Proof:
5494 // Expr(i+1) =
5495 // = Start + (i+1)*Accum
5496 // = (Start + i*Accum) + Accum
5497 // = Expr(i) + Accum
5498 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5499 // :: from step i
5500 //
5501 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5502 //
5503 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5504 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
5505 // + Accum :: from P3
5506 //
5507 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5508 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5509 //
5510 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5511 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5512 //
5513 // By induction, the same applies to all iterations 1<=i<n:
5514 //
5515
5516 // Create a truncated addrec for which we will add a no overflow check (P1).
5517 const SCEV *StartVal = getSCEV(StartValueV);
5518 const SCEV *PHISCEV =
5519 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5520 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagNone);
5521
5522 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5523 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5524 // will be constant.
5525 //
5526 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5527 // add P1.
5528 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5532 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5533 Predicates.push_back(AddRecPred);
5534 }
5535
5536 // Create the Equal Predicates P2,P3:
5537
5538 // It is possible that the predicates P2 and/or P3 are computable at
5539 // compile time due to StartVal and/or Accum being constants.
5540 // If either one is, then we can check that now and escape if either P2
5541 // or P3 is false.
5542
5543 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5544 // for each of StartVal and Accum
5545 auto getExtendedExpr = [&](const SCEV *Expr,
5546 bool CreateSignExtend) -> const SCEV * {
5547 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5548 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5549 const SCEV *ExtendedExpr =
5550 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5551 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5552 return ExtendedExpr;
5553 };
5554
5555 // Given:
5556 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5557 // = getExtendedExpr(Expr)
5558 // Determine whether the predicate P: Expr == ExtendedExpr
5559 // is known to be false at compile time
5560 auto PredIsKnownFalse = [&](const SCEV *Expr,
5561 const SCEV *ExtendedExpr) -> bool {
5562 return Expr != ExtendedExpr &&
5563 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5564 };
5565
5566 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5567 if (PredIsKnownFalse(StartVal, StartExtended)) {
5568 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5569 return std::nullopt;
5570 }
5571
5572 // The Step is always Signed (because the overflow checks are either
5573 // NSSW or NUSW)
5574 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5575 if (PredIsKnownFalse(Accum, AccumExtended)) {
5576 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5577 return std::nullopt;
5578 }
5579
5580 auto AppendPredicate = [&](const SCEV *Expr,
5581 const SCEV *ExtendedExpr) -> void {
5582 if (Expr != ExtendedExpr &&
5583 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5584 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5585 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5586 Predicates.push_back(Pred);
5587 }
5588 };
5589
5590 AppendPredicate(StartVal, StartExtended);
5591 AppendPredicate(Accum, AccumExtended);
5592
5593 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5594 // which the casts had been folded away. The caller can rewrite SymbolicPHI
5595 // into NewAR if it will also add the runtime overflow checks specified in
5596 // Predicates.
5597 const SCEV *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagNone);
5598
5599 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5600 std::make_pair(NewAR, Predicates);
5601 // Remember the result of the analysis for this SCEV at this locayyytion.
5602 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5603 return PredRewrite;
5604}
5605
5606std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5608 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5609 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5610 if (!L)
5611 return std::nullopt;
5612
5613 // Check to see if we already analyzed this PHI.
5614 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5615 if (I != PredicatedSCEVRewrites.end()) {
5616 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5617 I->second;
5618 // Analysis was done before and failed to create an AddRec:
5619 if (Rewrite.first == SymbolicPHI)
5620 return std::nullopt;
5621 // Analysis was done before and succeeded to create an AddRec under
5622 // a predicate:
5623 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5624 assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5625 return Rewrite;
5626 }
5627
5628 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5629 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5630
5631 // Record in the cache that the analysis failed
5632 if (!Rewrite) {
5634 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5635 return std::nullopt;
5636 }
5637
5638 return Rewrite;
5639}
5640
5641// FIXME: This utility is currently required because the Rewriter currently
5642// does not rewrite this expression:
5643// {0, +, (sext ix (trunc iy to ix) to iy)}
5644// into {0, +, %step},
5645// even when the following Equal predicate exists:
5646// "%step == (sext ix (trunc iy to ix) to iy)".
5648 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2,
5649 ArrayRef<const SCEVPredicate *> NoWrapPreds) const {
5650 if (AR1 == AR2)
5651 return true;
5652
5653 SCEVUnionPredicate NoWrapUnionPred(NoWrapPreds, SE);
5654 SCEVUnionPredicate AllPreds = Preds->getUnionWith(&NoWrapUnionPred, SE);
5655 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5656 if (Expr1 != Expr2 &&
5657 !AllPreds.implies(SE.getEqualPredicate(Expr1, Expr2), SE) &&
5658 !AllPreds.implies(SE.getEqualPredicate(Expr2, Expr1), SE))
5659 return false;
5660 return true;
5661 };
5662
5663 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5664 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5665 return false;
5666 return true;
5667}
5668
5670 ScalarEvolution &SE) {
5671 SCEVFlags Flags = SCEV::FlagNone;
5672 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
5673 // If the increment has any nowrap flags, then we know the address
5674 // space cannot be wrapped around.
5675 if (NW != GEPNoWrapFlags::none())
5677 // If the GEP is nuw or nusw with non-negative offset, we know that
5678 // no unsigned wrap occurs. We cannot set the nsw flag as only the
5679 // offset is treated as signed, while the base is unsigned.
5680 if (NW.hasNoUnsignedWrap() ||
5681 (NW.hasNoUnsignedSignedWrap() && SE.isKnownNonNegative(Accum)))
5683
5684 return Flags;
5685}
5686
5687/// A helper function for createAddRecFromPHI to handle simple cases.
5688///
5689/// This function tries to find an AddRec expression for the simplest (yet most
5690/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5691/// If it fails, createAddRecFromPHI will use a more general, but slow,
5692/// technique for finding the AddRec expression.
5693const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5694 Value *BEValueV,
5695 Value *StartValueV) {
5696 const Loop *L = LI.getLoopFor(PN->getParent());
5697 assert(L && L->getHeader() == PN->getParent());
5698 assert(BEValueV && StartValueV);
5699
5700 const SCEV *Accum = nullptr;
5702 if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
5703 if (BO->Opcode != Instruction::Add)
5704 return nullptr;
5705
5706 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5707 Accum = getSCEV(BO->RHS);
5708 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5709 Accum = getSCEV(BO->LHS);
5710
5711 if (!Accum)
5712 return nullptr;
5713
5714 if (BO->IsNUW)
5715 Flags = setFlags(Flags, SCEV::FlagNUW);
5716 if (BO->IsNSW)
5717 Flags = setFlags(Flags, SCEV::FlagNSW);
5718 } else {
5719 // Handle pointer induction variable: PN = PHI(Start, gep PN,
5720 // LoopInvariant).
5721 auto *GEP = dyn_cast<GEPOperator>(BEValueV);
5722 if (!GEP || GEP->getPointerOperand() != PN || GEP->getNumIndices() != 1)
5723 return nullptr;
5724 Value *Idx = *GEP->idx_begin();
5725 if (!L->isLoopInvariant(Idx))
5726 return nullptr;
5727
5728 Type *IntIdxTy = getEffectiveSCEVType(GEP->getType());
5729 Accum = getMulExpr(getTruncateOrSignExtend(getSCEV(Idx), IntIdxTy),
5730 getSizeOfExpr(IntIdxTy, GEP->getSourceElementType()));
5731 Flags = getNoWrapFlagsForGEP(GEP, Accum, *this);
5732 }
5733
5734 const SCEV *StartVal = getSCEV(StartValueV);
5735 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5736 insertValueToMap(PN, PHISCEV);
5737
5738 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5739 inferNoWrapViaConstantRanges(AR);
5740
5741 // We can add Flags to the post-inc expression only if we
5742 // know that it is *undefined behavior* for BEValueV to
5743 // overflow.
5744 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5745 assert(isLoopInvariant(Accum, L) &&
5746 "Accum is defined outside L, but is not invariant?");
5747 if (isAddRecNeverPoison(BEInst, L))
5748 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5749 }
5750
5751 return PHISCEV;
5752}
5753
5754const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5755 const Loop *L = LI.getLoopFor(PN->getParent());
5756 if (!L || L->getHeader() != PN->getParent())
5757 return nullptr;
5758
5759 // The loop may have multiple entrances or multiple exits; we can analyze
5760 // this phi as an addrec if it has a unique entry value and a unique
5761 // backedge value.
5762 Value *BEValueV = nullptr, *StartValueV = nullptr;
5763 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5764 Value *V = PN->getIncomingValue(i);
5765 if (L->contains(PN->getIncomingBlock(i))) {
5766 if (!BEValueV) {
5767 BEValueV = V;
5768 } else if (BEValueV != V) {
5769 BEValueV = nullptr;
5770 break;
5771 }
5772 } else if (!StartValueV) {
5773 StartValueV = V;
5774 } else if (StartValueV != V) {
5775 StartValueV = nullptr;
5776 break;
5777 }
5778 }
5779 if (!BEValueV || !StartValueV)
5780 return nullptr;
5781
5782 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5783 "PHI node already processed?");
5784
5785 // First, try to find AddRec expression without creating a fictituos symbolic
5786 // value for PN.
5787 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5788 return S;
5789
5790 // Handle PHI node value symbolically.
5791 const SCEV *SymbolicName = getUnknown(PN);
5792 insertValueToMap(PN, SymbolicName);
5793
5794 // Using this symbolic name for the PHI, analyze the value coming around
5795 // the back-edge.
5796 const SCEV *BEValue = getSCEV(BEValueV);
5797
5798 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5799 // has a special value for the first iteration of the loop.
5800
5801 // If the value coming around the backedge is an add with the symbolic
5802 // value we just inserted, then we found a simple induction variable!
5803 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5804 // If there is a single occurrence of the symbolic value, replace it
5805 // with a recurrence.
5806 unsigned FoundIndex = Add->getNumOperands();
5807 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5808 if (Add->getOperand(i) == SymbolicName)
5809 if (FoundIndex == e) {
5810 FoundIndex = i;
5811 break;
5812 }
5813
5814 if (FoundIndex != Add->getNumOperands()) {
5815 // Create an add with everything but the specified operand.
5817 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5818 if (i != FoundIndex)
5819 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5820 L, *this));
5821 const SCEV *Accum = getAddExpr(Ops);
5822
5823 // This is not a valid addrec if the step amount is varying each
5824 // loop iteration, but is not itself an addrec in this loop.
5825 if (isLoopInvariant(Accum, L) ||
5826 (isa<SCEVAddRecExpr>(Accum) &&
5827 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5829
5830 if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
5831 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5832 if (BO->IsNUW)
5833 Flags = setFlags(Flags, SCEV::FlagNUW);
5834 if (BO->IsNSW)
5835 Flags = setFlags(Flags, SCEV::FlagNSW);
5836 }
5837 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5838 if (GEP->getOperand(0) == PN)
5839 Flags = getNoWrapFlagsForGEP(GEP, Accum, *this);
5840
5841 // We cannot transfer nuw and nsw flags from subtraction
5842 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5843 // for instance.
5844 }
5845
5846 const SCEV *StartVal = getSCEV(StartValueV);
5847 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5848
5849 // Okay, for the entire analysis of this edge we assumed the PHI
5850 // to be symbolic. We now need to go back and purge all of the
5851 // entries for the scalars that use the symbolic expression.
5852 forgetMemoizedResults({SymbolicName});
5853 insertValueToMap(PN, PHISCEV);
5854
5855 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5856 inferNoWrapViaConstantRanges(AR);
5857
5858 // We can add Flags to the post-inc expression only if we
5859 // know that it is *undefined behavior* for BEValueV to
5860 // overflow.
5861 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5862 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5863 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5864
5865 return PHISCEV;
5866 }
5867 }
5868 } else {
5869 // Otherwise, this could be a loop like this:
5870 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5871 // In this case, j = {1,+,1} and BEValue is j.
5872 // Because the other in-value of i (0) fits the evolution of BEValue
5873 // i really is an addrec evolution.
5874 //
5875 // We can generalize this saying that i is the shifted value of BEValue
5876 // by one iteration:
5877 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5878
5879 // Do not allow refinement in rewriting of BEValue.
5880 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5881 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5882 if (Shifted != getCouldNotCompute() && Start != getCouldNotCompute() &&
5883 isGuaranteedNotToCauseUB(Shifted) && ::impliesPoison(Shifted, Start)) {
5884 const SCEV *StartVal = getSCEV(StartValueV);
5885 if (Start == StartVal) {
5886 // Okay, for the entire analysis of this edge we assumed the PHI
5887 // to be symbolic. We now need to go back and purge all of the
5888 // entries for the scalars that use the symbolic expression.
5889 forgetMemoizedResults({SymbolicName});
5890 insertValueToMap(PN, Shifted);
5891 return Shifted;
5892 }
5893 }
5894 }
5895
5896 // Remove the temporary PHI node SCEV that has been inserted while intending
5897 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5898 // as it will prevent later (possibly simpler) SCEV expressions to be added
5899 // to the ValueExprMap.
5900 eraseValueFromMap(PN);
5901
5902 return nullptr;
5903}
5904
5905// Try to match a control flow sequence that branches out at BI and merges back
5906// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5907// match.
5909 Value *&C, Value *&LHS, Value *&RHS) {
5910 C = BI->getCondition();
5911
5912 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5913 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5914
5915 Use &LeftUse = Merge->getOperandUse(0);
5916 Use &RightUse = Merge->getOperandUse(1);
5917
5918 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5919 LHS = LeftUse;
5920 RHS = RightUse;
5921 return true;
5922 }
5923
5924 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5925 LHS = RightUse;
5926 RHS = LeftUse;
5927 return true;
5928 }
5929
5930 return false;
5931}
5932
5934 Value *&Cond, Value *&LHS,
5935 Value *&RHS) {
5936 auto IsReachable =
5937 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5938 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5939 // Try to match
5940 //
5941 // br %cond, label %left, label %right
5942 // left:
5943 // br label %merge
5944 // right:
5945 // br label %merge
5946 // merge:
5947 // V = phi [ %x, %left ], [ %y, %right ]
5948 //
5949 // as "select %cond, %x, %y"
5950
5951 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5952 assert(IDom && "At least the entry block should dominate PN");
5953
5954 auto *BI = dyn_cast<CondBrInst>(IDom->getTerminator());
5955 return BI && BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS);
5956 }
5957 return false;
5958}
5959
5960const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5961 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5962 if (getOperandsForSelectLikePHI(DT, PN, Cond, LHS, RHS) &&
5965 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5966
5967 return nullptr;
5968}
5969
5971 BinaryOperator *CommonInst = nullptr;
5972 // Check if instructions are identical.
5973 for (Value *Incoming : PN->incoming_values()) {
5974 auto *IncomingInst = dyn_cast<BinaryOperator>(Incoming);
5975 if (!IncomingInst)
5976 return nullptr;
5977 if (CommonInst) {
5978 if (!CommonInst->isIdenticalToWhenDefined(IncomingInst))
5979 return nullptr; // Not identical, give up
5980 } else {
5981 // Remember binary operator
5982 CommonInst = IncomingInst;
5983 }
5984 }
5985 return CommonInst;
5986}
5987
5988/// Returns SCEV for the first operand of a phi if all phi operands have
5989/// identical opcodes and operands
5990/// eg.
5991/// a: %add = %a + %b
5992/// br %c
5993/// b: %add1 = %a + %b
5994/// br %c
5995/// c: %phi = phi [%add, a], [%add1, b]
5996/// scev(%phi) => scev(%add)
5997const SCEV *
5998ScalarEvolution::createNodeForPHIWithIdenticalOperands(PHINode *PN) {
5999 BinaryOperator *CommonInst = getCommonInstForPHI(PN);
6000 if (!CommonInst)
6001 return nullptr;
6002
6003 // Check if SCEV exprs for instructions are identical.
6004 const SCEV *CommonSCEV = getSCEV(CommonInst);
6005 bool SCEVExprsIdentical =
6007 [this, CommonSCEV](Value *V) { return CommonSCEV == getSCEV(V); });
6008 return SCEVExprsIdentical ? CommonSCEV : nullptr;
6009}
6010
6011const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
6012 if (const SCEV *S = createAddRecFromPHI(PN))
6013 return S;
6014
6015 // We do not allow simplifying phi (undef, X) to X here, to avoid reusing the
6016 // phi node for X.
6017 if (Value *V = simplifyInstruction(
6018 PN, {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
6019 /*UseInstrInfo=*/true, /*CanUseUndef=*/false}))
6020 return getSCEV(V);
6021
6022 if (const SCEV *S = createNodeForPHIWithIdenticalOperands(PN))
6023 return S;
6024
6025 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
6026 return S;
6027
6028 // If it's not a loop phi, we can't handle it yet.
6029 return getUnknown(PN);
6030}
6031
6032bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
6033 SCEVTypes RootKind) {
6034 struct FindClosure {
6035 const SCEV *OperandToFind;
6036 const SCEVTypes RootKind; // Must be a sequential min/max expression.
6037 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
6038
6039 bool Found = false;
6040
6041 bool canRecurseInto(SCEVTypes Kind) const {
6042 // We can only recurse into the SCEV expression of the same effective type
6043 // as the type of our root SCEV expression, and into zero-extensions.
6044 return RootKind == Kind || NonSequentialRootKind == Kind ||
6045 scZeroExtend == Kind;
6046 };
6047
6048 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
6049 : OperandToFind(OperandToFind), RootKind(RootKind),
6050 NonSequentialRootKind(
6052 RootKind)) {}
6053
6054 bool follow(const SCEV *S) {
6055 Found = S == OperandToFind;
6056
6057 return !isDone() && canRecurseInto(S->getSCEVType());
6058 }
6059
6060 bool isDone() const { return Found; }
6061 };
6062
6063 FindClosure FC(OperandToFind, RootKind);
6064 visitAll(Root, FC);
6065 return FC.Found;
6066}
6067
6068std::optional<const SCEV *>
6069ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
6070 ICmpInst *Cond,
6071 Value *TrueVal,
6072 Value *FalseVal) {
6073 // Try to match some simple smax or umax patterns.
6074 auto *ICI = Cond;
6075
6076 Value *LHS = ICI->getOperand(0);
6077 Value *RHS = ICI->getOperand(1);
6078
6079 switch (ICI->getPredicate()) {
6080 case ICmpInst::ICMP_SLT:
6081 case ICmpInst::ICMP_SLE:
6082 case ICmpInst::ICMP_ULT:
6083 case ICmpInst::ICMP_ULE:
6084 std::swap(LHS, RHS);
6085 [[fallthrough]];
6086 case ICmpInst::ICMP_SGT:
6087 case ICmpInst::ICMP_SGE:
6088 case ICmpInst::ICMP_UGT:
6089 case ICmpInst::ICMP_UGE:
6090 // a > b ? a+x : b+x -> max(a, b)+x
6091 // a > b ? b+x : a+x -> min(a, b)+x
6093 bool Signed = ICI->isSigned();
6094 const SCEV *LA = getSCEV(TrueVal);
6095 const SCEV *RA = getSCEV(FalseVal);
6096 const SCEV *LS = getSCEV(LHS);
6097 const SCEV *RS = getSCEV(RHS);
6098 if (LA->getType()->isPointerTy()) {
6099 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6100 // Need to make sure we can't produce weird expressions involving
6101 // negated pointers.
6102 if (LA == LS && RA == RS)
6103 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6104 if (LA == RS && RA == LS)
6105 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6106 }
6107 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6108 if (Op->getType()->isPointerTy()) {
6111 return Op;
6112 }
6113 if (Signed)
6114 Op = getNoopOrSignExtend(Op, Ty);
6115 else
6116 Op = getNoopOrZeroExtend(Op, Ty);
6117 return Op;
6118 };
6119 LS = CoerceOperand(LS);
6120 RS = CoerceOperand(RS);
6122 break;
6123 const SCEV *LDiff = getMinusSCEV(LA, LS);
6124 const SCEV *RDiff = getMinusSCEV(RA, RS);
6125 if (LDiff == RDiff)
6126 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6127 LDiff);
6128 LDiff = getMinusSCEV(LA, RS);
6129 RDiff = getMinusSCEV(RA, LS);
6130 if (LDiff == RDiff)
6131 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6132 LDiff);
6133 }
6134 break;
6135 case ICmpInst::ICMP_NE:
6136 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
6137 std::swap(TrueVal, FalseVal);
6138 [[fallthrough]];
6139 case ICmpInst::ICMP_EQ:
6140 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
6143 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6144 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y
6145 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y
6146 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6147 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y
6148 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6149 return getAddExpr(getUMaxExpr(X, C), Y);
6150 }
6151 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
6152 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
6153 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
6154 // -> umin_seq(x, umin (..., umin_seq(...), ...))
6156 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6157 const SCEV *X = getSCEV(LHS);
6158 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6159 X = ZExt->getOperand();
6160 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6161 const SCEV *FalseValExpr = getSCEV(FalseVal);
6162 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6163 return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6164 /*Sequential=*/true);
6165 }
6166 }
6167 break;
6168 default:
6169 break;
6170 }
6171
6172 return std::nullopt;
6173}
6174
6175static std::optional<const SCEV *>
6177 const SCEV *TrueExpr, const SCEV *FalseExpr) {
6178 assert(CondExpr->getType()->isIntegerTy(1) &&
6179 TrueExpr->getType() == FalseExpr->getType() &&
6180 TrueExpr->getType()->isIntegerTy(1) &&
6181 "Unexpected operands of a select.");
6182
6183 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
6184 // --> C + (umin_seq cond, x - C)
6185 //
6186 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
6187 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6188 // --> C + (umin_seq ~cond, x - C)
6189
6190 // FIXME: while we can't legally model the case where both of the hands
6191 // are fully variable, we only require that the *difference* is constant.
6192 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6193 return std::nullopt;
6194
6195 const SCEV *X, *C;
6196 if (isa<SCEVConstant>(TrueExpr)) {
6197 CondExpr = SE->getNotSCEV(CondExpr);
6198 X = FalseExpr;
6199 C = TrueExpr;
6200 } else {
6201 X = TrueExpr;
6202 C = FalseExpr;
6203 }
6204 return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6205 /*Sequential=*/true));
6206}
6207
6208static std::optional<const SCEV *>
6210 Value *FalseVal) {
6211 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6212 return std::nullopt;
6213
6214 const auto *SECond = SE->getSCEV(Cond);
6215 const auto *SETrue = SE->getSCEV(TrueVal);
6216 const auto *SEFalse = SE->getSCEV(FalseVal);
6217 return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6218}
6219
6220const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6221 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6222 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6223 assert(TrueVal->getType() == FalseVal->getType() &&
6224 V->getType() == TrueVal->getType() &&
6225 "Types of select hands and of the result must match.");
6226
6227 // For now, only deal with i1-typed `select`s.
6228 if (!V->getType()->isIntegerTy(1))
6229 return getUnknown(V);
6230
6231 if (std::optional<const SCEV *> S =
6232 createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6233 return *S;
6234
6235 return getUnknown(V);
6236}
6237
6238const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6239 Value *TrueVal,
6240 Value *FalseVal) {
6241 // Handle "constant" branch or select. This can occur for instance when a
6242 // loop pass transforms an inner loop and moves on to process the outer loop.
6243 if (auto *CI = dyn_cast<ConstantInt>(Cond))
6244 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6245
6246 if (auto *I = dyn_cast<Instruction>(V)) {
6247 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6248 if (std::optional<const SCEV *> S =
6249 createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6250 TrueVal, FalseVal))
6251 return *S;
6252 }
6253 }
6254
6255 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6256}
6257
6258/// Expand GEP instructions into add and multiply operations. This allows them
6259/// to be analyzed by regular SCEV code.
6260const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6261 assert(GEP->getSourceElementType()->isSized() &&
6262 "GEP source element type must be sized");
6263
6264 SmallVector<SCEVUse, 4> IndexExprs;
6265 for (Value *Index : GEP->indices())
6266 IndexExprs.push_back(getSCEV(Index));
6267 return getGEPExpr(GEP, IndexExprs);
6268}
6269
6270APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S,
6271 const Instruction *CtxI) {
6273 auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6274 return TrailingZeros >= BitWidth
6276 : APInt::getOneBitSet(BitWidth, TrailingZeros);
6277 };
6278 auto GetGCDMultiple = [this, CtxI](const SCEVNAryExpr *N) {
6279 // The result is GCD of all operands results.
6280 APInt Res = getConstantMultiple(N->getOperand(0), CtxI);
6281 for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6283 Res, getConstantMultiple(N->getOperand(I), CtxI));
6284 return Res;
6285 };
6286
6287 switch (S->getSCEVType()) {
6288 case scConstant:
6289 return cast<SCEVConstant>(S)->getAPInt();
6290 case scPtrToAddr:
6291 return getConstantMultiple(cast<SCEVCastExpr>(S)->getOperand());
6292 case scUDivExpr:
6293 case scVScale:
6294 return APInt(BitWidth, 1);
6295 case scTruncate: {
6296 // Only multiples that are a power of 2 will hold after truncation.
6297 const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6298 uint32_t TZ = getMinTrailingZeros(T->getOperand(), CtxI);
6299 return GetShiftedByZeros(TZ);
6300 }
6301 case scZeroExtend: {
6302 const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(S);
6303 return getConstantMultiple(Z->getOperand(), CtxI).zext(BitWidth);
6304 }
6305 case scSignExtend: {
6306 // Only multiples that are a power of 2 will hold after sext.
6307 const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6308 uint32_t TZ = getMinTrailingZeros(E->getOperand(), CtxI);
6309 return GetShiftedByZeros(TZ);
6310 }
6311 case scMulExpr: {
6312 const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6313 if (M->hasNoUnsignedWrap()) {
6314 // The result is the product of all operand results.
6315 APInt Res = getConstantMultiple(M->getOperand(0), CtxI);
6316 for (const SCEV *Operand : M->operands().drop_front())
6317 Res = Res * getConstantMultiple(Operand, CtxI);
6318 return Res;
6319 }
6320
6321 // If there are no wrap guarentees, find the trailing zeros, which is the
6322 // sum of trailing zeros for all its operands.
6323 uint32_t TZ = 0;
6324 for (const SCEV *Operand : M->operands())
6325 TZ += getMinTrailingZeros(Operand, CtxI);
6326 return GetShiftedByZeros(TZ);
6327 }
6328 case scAddExpr:
6329 case scAddRecExpr: {
6330 const SCEVNAryExpr *N = cast<SCEVNAryExpr>(S);
6331 if (N->hasNoUnsignedWrap())
6332 return GetGCDMultiple(N);
6333 // Find the trailing bits, which is the minimum of its operands.
6334 uint32_t TZ = getMinTrailingZeros(N->getOperand(0), CtxI);
6335 for (const SCEV *Operand : N->operands().drop_front())
6336 TZ = std::min(TZ, getMinTrailingZeros(Operand, CtxI));
6337 return GetShiftedByZeros(TZ);
6338 }
6339 case scUMaxExpr:
6340 case scSMaxExpr:
6341 case scUMinExpr:
6342 case scSMinExpr:
6344 return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6345 case scUnknown: {
6346 // Ask ValueTracking for known bits. SCEVUnknown only become available at
6347 // the point their underlying IR instruction has been defined. If CtxI was
6348 // not provided, use:
6349 // * the first instruction in the entry block if it is an argument
6350 // * the instruction itself otherwise.
6351 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6352 if (!CtxI) {
6353 if (isa<Argument>(U->getValue()))
6354 CtxI = &*F.getEntryBlock().begin();
6355 else if (auto *I = dyn_cast<Instruction>(U->getValue()))
6356 CtxI = I;
6357 }
6358 unsigned Known =
6359 computeKnownBits(U->getValue(),
6360 SimplifyQuery(getDataLayout(), &DT, &AC, CtxI)
6361 .allowEphemerals(true))
6362 .countMinTrailingZeros();
6363 return GetShiftedByZeros(Known);
6364 }
6365 case scCouldNotCompute:
6366 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6367 }
6368 llvm_unreachable("Unknown SCEV kind!");
6369}
6370
6372 const Instruction *CtxI) {
6373 // Skip looking up and updating the cache if there is a context instruction,
6374 // as the result will only be valid in the specified context.
6375 if (CtxI)
6376 return getConstantMultipleImpl(S, CtxI);
6377
6378 auto I = ConstantMultipleCache.find(S);
6379 if (I != ConstantMultipleCache.end())
6380 return I->second;
6381
6382 APInt Result = getConstantMultipleImpl(S, CtxI);
6383 auto InsertPair = ConstantMultipleCache.insert({S, Result});
6384 assert(InsertPair.second && "Should insert a new key");
6385 return InsertPair.first->second;
6386}
6387
6389 APInt Multiple = getConstantMultiple(S);
6390 return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6391}
6392
6394 const Instruction *CtxI) {
6395 return std::min(getConstantMultiple(S, CtxI).countTrailingZeros(),
6396 (unsigned)getTypeSizeInBits(S->getType()));
6397}
6398
6399/// Helper method to assign a range to V from metadata present in the IR.
6400static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6402 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6403 return getConstantRangeFromMetadata(*MD);
6404 if (const auto *CB = dyn_cast<CallBase>(V))
6405 if (std::optional<ConstantRange> Range = CB->getRange())
6406 return Range;
6407 }
6408 if (auto *A = dyn_cast<Argument>(V))
6409 if (std::optional<ConstantRange> Range = A->getRange())
6410 return Range;
6411
6412 return std::nullopt;
6413}
6414
6416 SCEVFlags NWFlags = Flags & SCEV::FlagsNoWrapMask;
6417 if (AddRec->getNoWrapFlags(NWFlags) != NWFlags) {
6418 AddRec->setNoWrapFlags(NWFlags);
6419 UnsignedRanges.erase(AddRec);
6420 SignedRanges.erase(AddRec);
6421 ConstantMultipleCache.erase(AddRec);
6422 }
6423}
6424
6425ConstantRange ScalarEvolution::
6426getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6427 const DataLayout &DL = getDataLayout();
6428
6429 unsigned BitWidth = getTypeSizeInBits(U->getType());
6430 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6431
6432 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6433 // use information about the trip count to improve our available range. Note
6434 // that the trip count independent cases are already handled by known bits.
6435 // WARNING: The definition of recurrence used here is subtly different than
6436 // the one used by AddRec (and thus most of this file). Step is allowed to
6437 // be arbitrarily loop varying here, where AddRec allows only loop invariant
6438 // and other addrecs in the same loop (for non-affine addrecs). The code
6439 // below intentionally handles the case where step is not loop invariant.
6440 auto *P = dyn_cast<PHINode>(U->getValue());
6441 if (!P)
6442 return FullSet;
6443
6444 // Make sure that no Phi input comes from an unreachable block. Otherwise,
6445 // even the values that are not available in these blocks may come from them,
6446 // and this leads to false-positive recurrence test.
6447 for (auto *Pred : predecessors(P->getParent()))
6448 if (!DT.isReachableFromEntry(Pred))
6449 return FullSet;
6450
6451 BinaryOperator *BO;
6452 Value *Start, *Step;
6453 if (!matchSimpleRecurrence(P, BO, Start, Step))
6454 return FullSet;
6455
6456 // If we found a recurrence in reachable code, we must be in a loop. Note
6457 // that BO might be in some subloop of L, and that's completely okay.
6458 auto *L = LI.getLoopFor(P->getParent());
6459 assert(L && L->getHeader() == P->getParent());
6460 if (!L->contains(BO->getParent()))
6461 // NOTE: This bailout should be an assert instead. However, asserting
6462 // the condition here exposes a case where LoopFusion is querying SCEV
6463 // with malformed loop information during the midst of the transform.
6464 // There doesn't appear to be an obvious fix, so for the moment bailout
6465 // until the caller issue can be fixed. PR49566 tracks the bug.
6466 return FullSet;
6467
6468 // TODO: Extend to other opcodes such as mul, and div
6469 switch (BO->getOpcode()) {
6470 default:
6471 return FullSet;
6472 case Instruction::AShr:
6473 case Instruction::LShr:
6474 case Instruction::Shl:
6475 break;
6476 };
6477
6478 if (BO->getOperand(0) != P)
6479 // TODO: Handle the power function forms some day.
6480 return FullSet;
6481
6482 unsigned TC = getSmallConstantMaxTripCount(L);
6483 if (!TC || TC >= BitWidth)
6484 return FullSet;
6485
6486 auto KnownStart = computeKnownBits(Start, DL, &AC, nullptr, &DT);
6487 auto KnownStep = computeKnownBits(Step, DL, &AC, nullptr, &DT);
6488 assert(KnownStart.getBitWidth() == BitWidth &&
6489 KnownStep.getBitWidth() == BitWidth);
6490
6491 // Compute total shift amount, being careful of overflow and bitwidths.
6492 auto MaxShiftAmt = KnownStep.getMaxValue();
6493 APInt TCAP(BitWidth, TC-1);
6494 bool Overflow = false;
6495 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6496 if (Overflow)
6497 return FullSet;
6498
6499 switch (BO->getOpcode()) {
6500 default:
6501 llvm_unreachable("filtered out above");
6502 case Instruction::AShr: {
6503 // For each ashr, three cases:
6504 // shift = 0 => unchanged value
6505 // saturation => 0 or -1
6506 // other => a value closer to zero (of the same sign)
6507 // Thus, the end value is closer to zero than the start.
6508 auto KnownEnd = KnownBits::ashr(KnownStart,
6509 KnownBits::makeConstant(TotalShift));
6510 if (KnownStart.isNonNegative())
6511 // Analogous to lshr (simply not yet canonicalized)
6512 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6513 KnownStart.getMaxValue() + 1);
6514 if (KnownStart.isNegative())
6515 // End >=u Start && End <=s Start
6516 return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6517 KnownEnd.getMaxValue() + 1);
6518 break;
6519 }
6520 case Instruction::LShr: {
6521 // For each lshr, three cases:
6522 // shift = 0 => unchanged value
6523 // saturation => 0
6524 // other => a smaller positive number
6525 // Thus, the low end of the unsigned range is the last value produced.
6526 auto KnownEnd = KnownBits::lshr(KnownStart,
6527 KnownBits::makeConstant(TotalShift));
6528 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6529 KnownStart.getMaxValue() + 1);
6530 }
6531 case Instruction::Shl: {
6532 // Iff no bits are shifted out, value increases on every shift.
6533 auto KnownEnd = KnownBits::shl(KnownStart,
6534 KnownBits::makeConstant(TotalShift));
6535 if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6536 return ConstantRange(KnownStart.getMinValue(),
6537 KnownEnd.getMaxValue() + 1);
6538 break;
6539 }
6540 };
6541 return FullSet;
6542}
6543
6544// The goal of this function is to check if recursively visiting the operands
6545// of this PHI might lead to an infinite loop. If we do see such a loop,
6546// there's no good way to break it, so we avoid analyzing such cases.
6547//
6548// getRangeRef previously used a visited set to avoid infinite loops, but this
6549// caused other issues: the result was dependent on the order of getRangeRef
6550// calls, and the interaction with createSCEVIter could cause a stack overflow
6551// in some cases (see issue #148253).
6552//
6553// FIXME: The way this is implemented is overly conservative; this checks
6554// for a few obviously safe patterns, but anything that doesn't lead to
6555// recursion is fine.
6557 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6559 return true;
6560
6561 if (all_of(PHI->operands(),
6562 [&](Value *Operand) { return DT.dominates(Operand, PHI); }))
6563 return true;
6564
6565 return false;
6566}
6567
6568const ConstantRange &
6569ScalarEvolution::getRangeRefIter(const SCEV *S,
6570 ScalarEvolution::RangeSignHint SignHint) {
6571 DenseMap<const SCEV *, ConstantRange> &Cache =
6572 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6573 : SignedRanges;
6574 SmallVector<SCEVUse> WorkList;
6575 SmallPtrSet<const SCEV *, 8> Seen;
6576
6577 // Add Expr to the worklist, if Expr is either an N-ary expression or a
6578 // SCEVUnknown PHI node.
6579 auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6580 if (!Seen.insert(Expr).second)
6581 return;
6582 if (Cache.contains(Expr))
6583 return;
6584 switch (Expr->getSCEVType()) {
6585 case scUnknown:
6587 break;
6588 [[fallthrough]];
6589 case scConstant:
6590 case scVScale:
6591 case scTruncate:
6592 case scZeroExtend:
6593 case scSignExtend:
6594 case scPtrToAddr:
6595 case scAddExpr:
6596 case scMulExpr:
6597 case scUDivExpr:
6598 case scAddRecExpr:
6599 case scUMaxExpr:
6600 case scSMaxExpr:
6601 case scUMinExpr:
6602 case scSMinExpr:
6604 WorkList.push_back(Expr);
6605 break;
6606 case scCouldNotCompute:
6607 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6608 }
6609 };
6610 AddToWorklist(S);
6611
6612 // Build worklist by queuing operands of N-ary expressions and phi nodes.
6613 for (unsigned I = 0; I != WorkList.size(); ++I) {
6614 const SCEV *P = WorkList[I];
6615 auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6616 // If it is not a `SCEVUnknown`, just recurse into operands.
6617 if (!UnknownS) {
6618 for (const SCEV *Op : P->operands())
6619 AddToWorklist(Op);
6620 continue;
6621 }
6622 // `SCEVUnknown`'s require special treatment.
6623 if (PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6624 if (!RangeRefPHIAllowedOperands(DT, P))
6625 continue;
6626 for (auto &Op : reverse(P->operands()))
6627 AddToWorklist(getSCEV(Op));
6628 }
6629 }
6630
6631 if (!WorkList.empty()) {
6632 // Use getRangeRef to compute ranges for items in the worklist in reverse
6633 // order. This will force ranges for earlier operands to be computed before
6634 // their users in most cases.
6635 for (const SCEV *P : reverse(drop_begin(WorkList))) {
6636 getRangeRef(P, SignHint);
6637 }
6638 }
6639
6640 return getRangeRef(S, SignHint, 0);
6641}
6642
6643const APInt *ScalarEvolution::getConstantAPIntOrNull(const SCEV *S) {
6644 if (const auto *C = dyn_cast<SCEVConstant>(S))
6645 return &C->getAPInt();
6646 return nullptr;
6647}
6648
6649/// Determine the range for a particular SCEV. If SignHint is
6650/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6651/// with a "cleaner" unsigned (resp. signed) representation.
6652const ConstantRange &ScalarEvolution::getRangeRef(
6653 const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6654 DenseMap<const SCEV *, ConstantRange> &Cache =
6655 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6656 : SignedRanges;
6658 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6660
6661 // See if we've computed this range already.
6662 auto I = Cache.find(S);
6663 if (I != Cache.end())
6664 return I->second;
6665
6666 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6667 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6668
6669 // Switch to iteratively computing the range for S, if it is part of a deeply
6670 // nested expression.
6672 return getRangeRefIter(S, SignHint);
6673
6674 unsigned BitWidth = getTypeSizeInBits(S->getType());
6675 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6676 using OBO = OverflowingBinaryOperator;
6677
6678 // If the value has known zeros, the maximum value will have those known zeros
6679 // as well.
6680 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6681 APInt Multiple = getNonZeroConstantMultiple(S);
6682 APInt Remainder = APInt::getMaxValue(BitWidth).urem(Multiple);
6683 if (!Remainder.isZero())
6684 ConservativeResult =
6685 ConstantRange(APInt::getMinValue(BitWidth),
6686 APInt::getMaxValue(BitWidth) - Remainder + 1);
6687 }
6688 else {
6689 uint32_t TZ = getMinTrailingZeros(S);
6690 if (TZ != 0) {
6691 ConservativeResult = ConstantRange(
6693 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6694 }
6695 }
6696
6697 switch (S->getSCEVType()) {
6698 case scConstant:
6699 llvm_unreachable("Already handled above.");
6700 case scVScale:
6701 return setRange(S, SignHint, getVScaleRange(&F, BitWidth));
6702 case scTruncate: {
6703 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6704 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6705 return setRange(
6706 Trunc, SignHint,
6707 ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6708 }
6709 case scZeroExtend: {
6710 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6711 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6712 return setRange(
6713 ZExt, SignHint,
6714 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6715 }
6716 case scSignExtend: {
6717 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6718 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6719 return setRange(
6720 SExt, SignHint,
6721 ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6722 }
6723 case scPtrToAddr: {
6724 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6725 ConstantRange X = getRangeRef(Cast->getOperand(), SignHint, Depth + 1);
6726 return setRange(Cast, SignHint, X);
6727 }
6728 case scAddExpr: {
6729 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6730 // Check if this is a URem pattern: A - (A / B) * B, which is always < B.
6731 const SCEV *URemLHS = nullptr, *URemRHS = nullptr;
6732 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED &&
6733 match(S, m_scev_URem(m_SCEV(URemLHS), m_SCEV(URemRHS), *this))) {
6734 ConstantRange LHSRange = getRangeRef(URemLHS, SignHint, Depth + 1);
6735 ConstantRange RHSRange = getRangeRef(URemRHS, SignHint, Depth + 1);
6736 ConservativeResult =
6737 ConservativeResult.intersectWith(LHSRange.urem(RHSRange), RangeType);
6738 }
6739 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6740 unsigned WrapType = OBO::AnyWrap;
6741 if (Add->hasNoSignedWrap())
6742 WrapType |= OBO::NoSignedWrap;
6743 if (Add->hasNoUnsignedWrap())
6744 WrapType |= OBO::NoUnsignedWrap;
6745 for (const SCEV *Op : drop_begin(Add->operands()))
6746 X = X.addWithNoWrap(getRangeRef(Op, SignHint, Depth + 1), WrapType,
6747 RangeType);
6748 return setRange(Add, SignHint,
6749 ConservativeResult.intersectWith(X, RangeType));
6750 }
6751 case scMulExpr: {
6752 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6753 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6754 for (const SCEV *Op : drop_begin(Mul->operands()))
6755 X = X.multiply(getRangeRef(Op, SignHint, Depth + 1));
6756 return setRange(Mul, SignHint,
6757 ConservativeResult.intersectWith(X, RangeType));
6758 }
6759 case scUDivExpr: {
6760 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6761 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6762 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6763 return setRange(UDiv, SignHint,
6764 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6765 }
6766 case scAddRecExpr: {
6767 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6768 // If there's no unsigned wrap, the value will never be less than its
6769 // initial value.
6770 if (AddRec->hasNoUnsignedWrap()) {
6771 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6772 if (!UnsignedMinValue.isZero())
6773 ConservativeResult = ConservativeResult.intersectWith(
6774 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6775 }
6776
6777 // If there's no signed wrap, and all the operands except initial value have
6778 // the same sign or zero, the value won't ever be:
6779 // 1: smaller than initial value if operands are non negative,
6780 // 2: bigger than initial value if operands are non positive.
6781 // For both cases, value can not cross signed min/max boundary.
6782 if (AddRec->hasNoSignedWrap()) {
6783 bool AllNonNeg = true;
6784 bool AllNonPos = true;
6785 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6786 if (!isKnownNonNegative(AddRec->getOperand(i)))
6787 AllNonNeg = false;
6788 if (!isKnownNonPositive(AddRec->getOperand(i)))
6789 AllNonPos = false;
6790 }
6791 if (AllNonNeg)
6792 ConservativeResult = ConservativeResult.intersectWith(
6795 RangeType);
6796 else if (AllNonPos)
6797 ConservativeResult = ConservativeResult.intersectWith(
6799 getSignedRangeMax(AddRec->getStart()) +
6800 1),
6801 RangeType);
6802 }
6803
6804 // TODO: non-affine addrec
6805 if (AddRec->isAffine()) {
6806 const SCEV *MaxBEScev =
6808 if (!isa<SCEVCouldNotCompute>(MaxBEScev)) {
6809 APInt MaxBECount = cast<SCEVConstant>(MaxBEScev)->getAPInt();
6810
6811 // Adjust MaxBECount to the same bitwidth as AddRec. We can truncate if
6812 // MaxBECount's active bits are all <= AddRec's bit width.
6813 if (MaxBECount.getBitWidth() > BitWidth &&
6814 MaxBECount.getActiveBits() <= BitWidth)
6815 MaxBECount = MaxBECount.trunc(BitWidth);
6816 else if (MaxBECount.getBitWidth() < BitWidth)
6817 MaxBECount = MaxBECount.zext(BitWidth);
6818
6819 if (MaxBECount.getBitWidth() == BitWidth) {
6820 auto [RangeFromAffine, Flags] = getRangeForAffineAR(
6821 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6822 ConservativeResult =
6823 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6824 const_cast<SCEVAddRecExpr *>(AddRec)->setNoWrapFlags(Flags);
6825
6826 auto RangeFromFactoring = getRangeViaFactoring(
6827 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6828 ConservativeResult =
6829 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6830 }
6831 }
6832
6833 // Now try symbolic BE count and more powerful methods.
6835 const SCEV *SymbolicMaxBECount =
6837 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6838 getTypeSizeInBits(MaxBEScev->getType()) <= BitWidth &&
6839 AddRec->hasNoSelfWrap()) {
6840 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6841 AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6842 ConservativeResult =
6843 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6844 }
6845 }
6846 }
6847
6848 return setRange(AddRec, SignHint, std::move(ConservativeResult));
6849 }
6850 case scUMaxExpr:
6851 case scSMaxExpr:
6852 case scUMinExpr:
6853 case scSMinExpr:
6854 case scSequentialUMinExpr: {
6856 switch (S->getSCEVType()) {
6857 case scUMaxExpr:
6858 ID = Intrinsic::umax;
6859 break;
6860 case scSMaxExpr:
6861 ID = Intrinsic::smax;
6862 break;
6863 case scUMinExpr:
6865 ID = Intrinsic::umin;
6866 break;
6867 case scSMinExpr:
6868 ID = Intrinsic::smin;
6869 break;
6870 default:
6871 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6872 }
6873
6874 const auto *NAry = cast<SCEVNAryExpr>(S);
6875 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
6876 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6877 X = X.intrinsic(
6878 ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
6879 return setRange(S, SignHint,
6880 ConservativeResult.intersectWith(X, RangeType));
6881 }
6882 case scUnknown: {
6883 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6884 Value *V = U->getValue();
6885
6886 // Check if the IR explicitly contains !range metadata.
6887 std::optional<ConstantRange> MDRange = GetRangeFromMetadata(V);
6888 if (MDRange)
6889 ConservativeResult =
6890 ConservativeResult.intersectWith(*MDRange, RangeType);
6891
6892 // Use facts about recurrences in the underlying IR. Note that add
6893 // recurrences are AddRecExprs and thus don't hit this path. This
6894 // primarily handles shift recurrences.
6895 auto CR = getRangeForUnknownRecurrence(U);
6896 ConservativeResult = ConservativeResult.intersectWith(CR);
6897
6898 // See if ValueTracking can give us a useful range.
6899 const DataLayout &DL = getDataLayout();
6900 KnownBits Known = computeKnownBits(V, DL, &AC, nullptr, &DT);
6901 if (Known.getBitWidth() != BitWidth)
6902 Known = Known.zextOrTrunc(BitWidth);
6903
6904 // ValueTracking may be able to compute a tighter result for the number of
6905 // sign bits than for the value of those sign bits.
6906 unsigned NS = ComputeNumSignBits(V, DL, &AC, nullptr, &DT);
6907 if (U->getType()->isPointerTy()) {
6908 // NS counts the sign bits of the whole pointer; drop those above the
6909 // index bits.
6910 unsigned PtrIdxDiff =
6911 DL.getPointerTypeSizeInBits(U->getType()) - BitWidth;
6912 NS = NS > PtrIdxDiff ? NS - PtrIdxDiff : 1;
6913 }
6914
6915 if (NS > 1) {
6916 // If we know any of the sign bits, we know all of the sign bits.
6917 if (!Known.Zero.getHiBits(NS).isZero())
6918 Known.Zero.setHighBits(NS);
6919 if (!Known.One.getHiBits(NS).isZero())
6920 Known.One.setHighBits(NS);
6921 }
6922
6923 if (Known.getMinValue() != Known.getMaxValue() + 1)
6924 ConservativeResult = ConservativeResult.intersectWith(
6925 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6926 RangeType);
6927 if (NS > 1)
6928 ConservativeResult = ConservativeResult.intersectWith(
6929 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6930 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6931 RangeType);
6932
6933 if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
6934 // Strengthen the range if the underlying IR value is a
6935 // global/alloca/heap allocation using the size of the object.
6936 bool CanBeNull;
6937 uint64_t DerefBytes = V->getPointerDereferenceableBytes(
6938 DL, CanBeNull, /*CanBeFreed=*/nullptr);
6939 if (DerefBytes > 1 && isUIntN(BitWidth, DerefBytes)) {
6940 // The highest address the object can start is DerefBytes bytes before
6941 // the end (unsigned max value). If this value is not a multiple of the
6942 // alignment, the last possible start value is the next lowest multiple
6943 // of the alignment. Note: The computations below cannot overflow,
6944 // because if they would there's no possible start address for the
6945 // object.
6946 APInt MaxVal =
6947 APInt::getMaxValue(BitWidth) - APInt(BitWidth, DerefBytes);
6948 uint64_t Align = U->getValue()->getPointerAlignment(DL).value();
6949 uint64_t Rem = MaxVal.urem(Align);
6950 MaxVal -= APInt(BitWidth, Rem);
6951 APInt MinVal = APInt::getZero(BitWidth);
6952 if (llvm::isKnownNonZero(V, DL))
6953 MinVal = Align;
6954 ConservativeResult = ConservativeResult.intersectWith(
6955 ConstantRange::getNonEmpty(MinVal, MaxVal + 1), RangeType);
6956 }
6957 }
6958
6959 // A range of Phi is a subset of union of all ranges of its input.
6960 if (PHINode *Phi = dyn_cast<PHINode>(V)) {
6961 // SCEVExpander sometimes creates SCEVUnknowns that are secretly
6962 // AddRecs; return the range for the corresponding AddRec.
6963 if (auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V)))
6964 return getRangeRef(AR, SignHint, Depth + 1);
6965
6966 // Make sure that we do not run over cycled Phis.
6967 if (RangeRefPHIAllowedOperands(DT, Phi)) {
6968 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6969
6970 for (const auto &Op : Phi->operands()) {
6971 auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
6972 RangeFromOps = RangeFromOps.unionWith(OpRange);
6973 // No point to continue if we already have a full set.
6974 if (RangeFromOps.isFullSet())
6975 break;
6976 }
6977 ConservativeResult =
6978 ConservativeResult.intersectWith(RangeFromOps, RangeType);
6979 }
6980 }
6981
6982 // vscale can't be equal to zero
6983 if (const auto *II = dyn_cast<IntrinsicInst>(V))
6984 if (II->getIntrinsicID() == Intrinsic::vscale) {
6985 ConstantRange Disallowed = APInt::getZero(BitWidth);
6986 ConservativeResult = ConservativeResult.difference(Disallowed);
6987 }
6988
6989 return setRange(U, SignHint, std::move(ConservativeResult));
6990 }
6991 case scCouldNotCompute:
6992 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6993 }
6994
6995 return setRange(S, SignHint, std::move(ConservativeResult));
6996}
6997
6998// Given a StartRange, Step and MaxBECount for an expression compute a range of
6999// values that the expression can take. Initially, the expression has a value
7000// from StartRange and then is changed by Step up to MaxBECount times. Signed
7001// argument defines if we treat Step as signed or unsigned. The second return
7002// value indicates that no wrapping occurred.
7003static std::pair<ConstantRange, bool>
7005 const APInt &MaxBECount, bool Signed) {
7006 unsigned BitWidth = Step.getBitWidth();
7007 assert(BitWidth == StartRange.getBitWidth() &&
7008 BitWidth == MaxBECount.getBitWidth() && "mismatched bit widths");
7009 // If either Step or MaxBECount is 0, then the expression won't change, and we
7010 // just need to return the initial range.
7011 if (Step == 0 || MaxBECount == 0)
7012 return {StartRange, true};
7013
7014 // If we don't know anything about the initial value (i.e. StartRange is
7015 // FullRange), then we don't know anything about the final range either.
7016 // Return FullRange.
7017 if (StartRange.isFullSet())
7018 return {ConstantRange::getFull(BitWidth), false};
7019
7020 // If Step is signed and negative, then we use its absolute value, but we also
7021 // note that we're moving in the opposite direction.
7022 bool Descending = Signed && Step.isNegative();
7023
7024 if (Signed)
7025 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
7026 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
7027 // This equations hold true due to the well-defined wrap-around behavior of
7028 // APInt.
7029 Step = Step.abs();
7030
7031 // Check if Offset is more than full span of BitWidth. If it is, the
7032 // expression is guaranteed to overflow.
7033 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
7034 return {ConstantRange::getFull(BitWidth), false};
7035
7036 // Offset is by how much the expression can change. Checks above guarantee no
7037 // overflow here.
7038 APInt Offset = Step * MaxBECount;
7039
7040 // Minimum value of the final range will match the minimal value of StartRange
7041 // if the expression is increasing and will be decreased by Offset otherwise.
7042 // Maximum value of the final range will match the maximal value of StartRange
7043 // if the expression is decreasing and will be increased by Offset otherwise.
7044 APInt StartLower = StartRange.getLower();
7045 APInt StartUpper = StartRange.getUpper() - 1;
7046 bool Overflow;
7047 APInt MovedBoundary;
7048 if (Signed) {
7049 // This does not use sadd_ov, as we want to check overflow for a signed
7050 // start with an unsigned offset.
7051 if (Descending) {
7052 MovedBoundary = StartLower - std::move(Offset);
7053 Overflow = MovedBoundary.sgt(StartLower) || StartRange.isSignWrappedSet();
7054 } else {
7055 MovedBoundary = StartUpper + std::move(Offset);
7056 Overflow = MovedBoundary.slt(StartUpper) || StartRange.isSignWrappedSet();
7057 }
7058 } else {
7059 MovedBoundary = StartUpper.uadd_ov(std::move(Offset), Overflow);
7060 Overflow |= StartRange.isWrappedSet();
7061 }
7062
7063 // It's possible that the new minimum/maximum value will fall into the initial
7064 // range (due to wrap around). This means that the expression can take any
7065 // value in this bitwidth, and we have to return full range.
7066 if (StartRange.contains(MovedBoundary))
7067 return {ConstantRange::getFull(BitWidth), false};
7068
7069 APInt NewLower =
7070 Descending ? std::move(MovedBoundary) : std::move(StartLower);
7071 APInt NewUpper =
7072 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
7073 NewUpper += 1;
7074
7075 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
7076 return {ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)),
7077 !Overflow};
7078}
7079
7080std::pair<ConstantRange, SCEVFlags>
7081ScalarEvolution::getRangeForAffineAR(const SCEV *Start, const SCEV *Step,
7082 const APInt &MaxBECount) {
7083 assert(getTypeSizeInBits(Start->getType()) ==
7084 getTypeSizeInBits(Step->getType()) &&
7085 getTypeSizeInBits(Start->getType()) == MaxBECount.getBitWidth() &&
7086 "mismatched bit widths");
7087
7088 // First, consider step signed.
7089 ConstantRange StartSRange = getSignedRange(Start);
7090 ConstantRange StepSRange = getSignedRange(Step);
7091
7092 // If Step can be both positive and negative, we need to find ranges for the
7093 // maximum absolute step values in both directions and union them.
7094 auto [SR1, NSW1] = getRangeForAffineARHelper(
7095 StepSRange.getSignedMin(), StartSRange, MaxBECount, /*Signed=*/true);
7096 auto [SR2, NSW2] = getRangeForAffineARHelper(StepSRange.getSignedMax(),
7097 StartSRange, MaxBECount,
7098 /*Signed=*/true);
7099 ConstantRange SR = SR1.unionWith(SR2);
7100
7101 // Next, consider step unsigned.
7102 auto [UR, NUW] = getRangeForAffineARHelper(
7103 getUnsignedRangeMax(Step), getUnsignedRange(Start), MaxBECount,
7104 /*Signed=*/false);
7105
7107 if (NUW)
7109 if (NSW1 && NSW2)
7111
7112 // Finally, intersect signed and unsigned ranges.
7114}
7115
7116ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
7117 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
7118 ScalarEvolution::RangeSignHint SignHint) {
7119 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
7120 assert(AddRec->hasNoSelfWrap() &&
7121 "This only works for non-self-wrapping AddRecs!");
7122 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
7123 const SCEV *Step = AddRec->getStepRecurrence(*this);
7124 // Only deal with constant step to save compile time.
7125 if (!isa<SCEVConstant>(Step))
7126 return ConstantRange::getFull(BitWidth);
7127 // Let's make sure that we can prove that we do not self-wrap during
7128 // MaxBECount iterations. We need this because MaxBECount is a maximum
7129 // iteration count estimate, and we might infer nw from some exit for which we
7130 // do not know max exit count (or any other side reasoning).
7131 // TODO: Turn into assert at some point.
7132 if (getTypeSizeInBits(MaxBECount->getType()) >
7133 getTypeSizeInBits(AddRec->getType()))
7134 return ConstantRange::getFull(BitWidth);
7135 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
7136 const SCEV *RangeWidth = getMinusOne(AddRec->getType());
7137 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
7138 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
7139 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
7140 MaxItersWithoutWrap))
7141 return ConstantRange::getFull(BitWidth);
7142
7143 ICmpInst::Predicate LEPred =
7145 ICmpInst::Predicate GEPred =
7147 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7148
7149 // We know that there is no self-wrap. Let's take Start and End values and
7150 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7151 // the iteration. They either lie inside the range [Min(Start, End),
7152 // Max(Start, End)] or outside it:
7153 //
7154 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
7155 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
7156 //
7157 // No self wrap flag guarantees that the intermediate values cannot be BOTH
7158 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7159 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7160 // Start <= End and step is positive, or Start >= End and step is negative.
7161 const SCEV *Start = applyLoopGuards(AddRec->getStart(), AddRec->getLoop());
7162 ConstantRange StartRange = getRangeRef(Start, SignHint);
7163 ConstantRange EndRange = getRangeRef(End, SignHint);
7164 ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7165 // If they already cover full iteration space, we will know nothing useful
7166 // even if we prove what we want to prove.
7167 if (RangeBetween.isFullSet())
7168 return RangeBetween;
7169 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7170 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7171 : RangeBetween.isWrappedSet();
7172 if (IsWrappedSet)
7173 return ConstantRange::getFull(BitWidth);
7174
7175 if (isKnownPositive(Step) &&
7176 isKnownPredicateViaConstantRanges(LEPred, Start, End))
7177 return RangeBetween;
7178 if (isKnownNegative(Step) &&
7179 isKnownPredicateViaConstantRanges(GEPred, Start, End))
7180 return RangeBetween;
7181 return ConstantRange::getFull(BitWidth);
7182}
7183
7184ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7185 const SCEV *Step,
7186 const APInt &MaxBECount) {
7187 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7188 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7189
7190 unsigned BitWidth = MaxBECount.getBitWidth();
7191 assert(getTypeSizeInBits(Start->getType()) == BitWidth &&
7192 getTypeSizeInBits(Step->getType()) == BitWidth &&
7193 "mismatched bit widths");
7194
7195 struct SelectPattern {
7196 Value *Condition = nullptr;
7197 APInt TrueValue;
7198 APInt FalseValue;
7199
7200 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7201 const SCEV *S) {
7202 std::optional<unsigned> CastOp;
7203 APInt Offset(BitWidth, 0);
7204
7206 "Should be!");
7207
7208 // Peel off a constant offset. In the future we could consider being
7209 // smarter here and handle {Start+Step,+,Step} too.
7210 const APInt *Off;
7211 if (match(S, m_scev_Add(m_scev_APInt(Off), m_SCEV(S))))
7212 Offset = *Off;
7213
7214 // Peel off a cast operation
7215 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7216 CastOp = SCast->getSCEVType();
7217 S = SCast->getOperand();
7218 }
7219
7220 using namespace llvm::PatternMatch;
7221
7222 auto *SU = dyn_cast<SCEVUnknown>(S);
7223 const APInt *TrueVal, *FalseVal;
7224 if (!SU ||
7225 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7226 m_APInt(FalseVal)))) {
7227 Condition = nullptr;
7228 return;
7229 }
7230
7231 TrueValue = *TrueVal;
7232 FalseValue = *FalseVal;
7233
7234 // Re-apply the cast we peeled off earlier
7235 if (CastOp)
7236 switch (*CastOp) {
7237 default:
7238 llvm_unreachable("Unknown SCEV cast type!");
7239
7240 case scTruncate:
7241 TrueValue = TrueValue.trunc(BitWidth);
7242 FalseValue = FalseValue.trunc(BitWidth);
7243 break;
7244 case scZeroExtend:
7245 TrueValue = TrueValue.zext(BitWidth);
7246 FalseValue = FalseValue.zext(BitWidth);
7247 break;
7248 case scSignExtend:
7249 TrueValue = TrueValue.sext(BitWidth);
7250 FalseValue = FalseValue.sext(BitWidth);
7251 break;
7252 }
7253
7254 // Re-apply the constant offset we peeled off earlier
7255 TrueValue += Offset;
7256 FalseValue += Offset;
7257 }
7258
7259 bool isRecognized() { return Condition != nullptr; }
7260 };
7261
7262 SelectPattern StartPattern(*this, BitWidth, Start);
7263 if (!StartPattern.isRecognized())
7264 return ConstantRange::getFull(BitWidth);
7265
7266 SelectPattern StepPattern(*this, BitWidth, Step);
7267 if (!StepPattern.isRecognized())
7268 return ConstantRange::getFull(BitWidth);
7269
7270 if (StartPattern.Condition != StepPattern.Condition) {
7271 // We don't handle this case today; but we could, by considering four
7272 // possibilities below instead of two. I'm not sure if there are cases where
7273 // that will help over what getRange already does, though.
7274 return ConstantRange::getFull(BitWidth);
7275 }
7276
7277 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7278 // construct arbitrary general SCEV expressions here. This function is called
7279 // from deep in the call stack, and calling getSCEV (on a sext instruction,
7280 // say) can end up caching a suboptimal value.
7281
7282 // FIXME: without the explicit `this` receiver below, MSVC errors out with
7283 // C2352 and C2512 (otherwise it isn't needed).
7284
7285 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7286 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7287 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7288 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7289
7290 ConstantRange TrueRange =
7291 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount).first;
7292 ConstantRange FalseRange =
7293 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount).first;
7294
7295 return TrueRange.unionWith(FalseRange);
7296}
7297
7298SCEVFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7299 if (isa<ConstantExpr>(V))
7300 return SCEV::FlagNone;
7301 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7302
7303 // Return early if there are no flags to propagate to the SCEV.
7305 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(BinOp);
7306 PDI && PDI->isDisjoint()) {
7308 } else {
7309 if (BinOp->hasNoUnsignedWrap())
7311 if (BinOp->hasNoSignedWrap())
7313 }
7314 if (Flags == SCEV::FlagNone)
7315 return SCEV::FlagNone;
7316
7317 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagNone;
7318}
7319
7320const Instruction *
7321ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7322 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7323 return &*AddRec->getLoop()->getHeader()->begin();
7324 if (auto *U = dyn_cast<SCEVUnknown>(S))
7325 if (auto *I = dyn_cast<Instruction>(U->getValue()))
7326 return I;
7327 return nullptr;
7328}
7329
7330const Instruction *ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops,
7331 bool &Precise) {
7332 Precise = true;
7333 // Do a bounded search of the def relation of the requested SCEVs.
7334 SmallPtrSet<const SCEV *, 16> Visited;
7335 SmallVector<SCEVUse> Worklist;
7336 auto pushOp = [&](const SCEV *S) {
7337 if (!Visited.insert(S).second)
7338 return;
7339 // Threshold of 30 here is arbitrary.
7340 if (Visited.size() > 30) {
7341 Precise = false;
7342 return;
7343 }
7344 Worklist.push_back(S);
7345 };
7346
7347 for (SCEVUse S : Ops)
7348 pushOp(S);
7349
7350 const Instruction *Bound = nullptr;
7351 while (!Worklist.empty()) {
7352 SCEVUse S = Worklist.pop_back_val();
7353 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7354 if (!Bound || DT.dominates(Bound, DefI))
7355 Bound = DefI;
7356 } else {
7357 for (SCEVUse Op : S->operands())
7358 pushOp(Op);
7359 }
7360 }
7361 return Bound ? Bound : &*F.getEntryBlock().begin();
7362}
7363
7364const Instruction *
7365ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops) {
7366 bool Discard;
7367 return getDefiningScopeBound(Ops, Discard);
7368}
7369
7370bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7371 const Instruction *B) {
7372 if (A->getParent() == B->getParent() &&
7374 B->getIterator()))
7375 return true;
7376
7377 auto *BLoop = LI.getLoopFor(B->getParent());
7378 if (BLoop && BLoop->getHeader() == B->getParent() &&
7379 BLoop->getLoopPreheader() == A->getParent() &&
7381 A->getParent()->end()) &&
7382 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7383 B->getIterator()))
7384 return true;
7385 return false;
7386}
7387
7389 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ true);
7390 visitAll(Op, PC);
7391 return PC.MaybePoison.empty();
7392}
7393
7394bool ScalarEvolution::isGuaranteedNotToCauseUB(const SCEV *Op) {
7395 return !SCEVExprContains(Op, [this](const SCEV *S) {
7396 const SCEV *Op1;
7397 bool M = match(S, m_scev_UDiv(m_SCEV(), m_SCEV(Op1)));
7398 // The UDiv may be UB if the divisor is poison or zero. Unless the divisor
7399 // is a non-zero constant, we have to assume the UDiv may be UB.
7400 return M && (!isKnownNonZero(Op1) || !isGuaranteedNotToBePoison(Op1));
7401 });
7402}
7403
7404bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7405 // Only proceed if we can prove that I does not yield poison.
7407 return false;
7408
7409 // At this point we know that if I is executed, then it does not wrap
7410 // according to at least one of NSW or NUW. If I is not executed, then we do
7411 // not know if the calculation that I represents would wrap. Multiple
7412 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7413 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7414 // derived from other instructions that map to the same SCEV. We cannot make
7415 // that guarantee for cases where I is not executed. So we need to find a
7416 // upper bound on the defining scope for the SCEV, and prove that I is
7417 // executed every time we enter that scope. When the bounding scope is a
7418 // loop (the common case), this is equivalent to proving I executes on every
7419 // iteration of that loop.
7420 SmallVector<SCEVUse> SCEVOps;
7421 for (const Use &Op : I->operands()) {
7422 // I could be an extractvalue from a call to an overflow intrinsic.
7423 // TODO: We can do better here in some cases.
7424 if (isSCEVable(Op->getType()))
7425 SCEVOps.push_back(getSCEV(Op));
7426 }
7427 auto *DefI = getDefiningScopeBound(SCEVOps);
7428 return isGuaranteedToTransferExecutionTo(DefI, I);
7429}
7430
7431bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7432 // If we know that \c I can never be poison period, then that's enough.
7433 if (isSCEVExprNeverPoison(I))
7434 return true;
7435
7436 // If the loop only has one exit, then we know that, if the loop is entered,
7437 // any instruction dominating that exit will be executed. If any such
7438 // instruction would result in UB, the addrec cannot be poison.
7439 //
7440 // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7441 // also handles uses outside the loop header (they just need to dominate the
7442 // single exit).
7443
7444 auto *ExitingBB = L->getExitingBlock();
7445 if (!ExitingBB || !loopHasNoAbnormalExits(L))
7446 return false;
7447
7448 SmallPtrSet<const Value *, 16> KnownPoison;
7450
7451 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
7452 // things that are known to be poison under that assumption go on the
7453 // Worklist.
7454 KnownPoison.insert(I);
7455 Worklist.push_back(I);
7456
7457 while (!Worklist.empty()) {
7458 const Instruction *Poison = Worklist.pop_back_val();
7459
7460 for (const Use &U : Poison->uses()) {
7461 const Instruction *PoisonUser = cast<Instruction>(U.getUser());
7462 if (mustTriggerUB(PoisonUser, KnownPoison) &&
7463 DT.dominates(PoisonUser->getParent(), ExitingBB))
7464 return true;
7465
7466 if (propagatesPoison(U) && L->contains(PoisonUser))
7467 if (KnownPoison.insert(PoisonUser).second)
7468 Worklist.push_back(PoisonUser);
7469 }
7470 }
7471
7472 return false;
7473}
7474
7475ScalarEvolution::LoopProperties
7476ScalarEvolution::getLoopProperties(const Loop *L) {
7477 using LoopProperties = ScalarEvolution::LoopProperties;
7478
7479 auto Itr = LoopPropertiesCache.find(L);
7480 if (Itr == LoopPropertiesCache.end()) {
7481 auto HasSideEffects = [](Instruction *I) {
7482 if (auto *SI = dyn_cast<StoreInst>(I))
7483 return !SI->isSimple();
7484
7485 if (I->mayThrow())
7486 return true;
7487
7488 // Non-volatile memset / memcpy do not count as side-effect for forward
7489 // progress.
7490 if (isa<MemIntrinsic>(I) && !I->isVolatile())
7491 return false;
7492
7493 return I->mayWriteToMemory();
7494 };
7495
7496 LoopProperties LP = {/* HasNoAbnormalExits */ true,
7497 /*HasNoSideEffects*/ true};
7498
7499 for (auto *BB : L->getBlocks())
7500 for (auto &I : *BB) {
7502 LP.HasNoAbnormalExits = false;
7503 if (HasSideEffects(&I))
7504 LP.HasNoSideEffects = false;
7505 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7506 break; // We're already as pessimistic as we can get.
7507 }
7508
7509 auto InsertPair = LoopPropertiesCache.insert({L, LP});
7510 assert(InsertPair.second && "We just checked!");
7511 Itr = InsertPair.first;
7512 }
7513
7514 return Itr->second;
7515}
7516
7518 // A mustprogress loop without side effects must be finite.
7519 // TODO: The check used here is very conservative. It's only *specific*
7520 // side effects which are well defined in infinite loops.
7521 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7522}
7523
7524const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7525 // Worklist item with a Value and a bool indicating whether all operands have
7526 // been visited already.
7529
7530 Stack.emplace_back(V, false);
7531 while (!Stack.empty()) {
7532 auto E = Stack.back();
7533 Value *CurV = E.getPointer();
7534
7535 if (getExistingSCEV(CurV)) {
7536 Stack.pop_back();
7537 continue;
7538 }
7539
7541 const SCEV *CreatedSCEV = nullptr;
7542 // If all operands have been visited already, create the SCEV.
7543 if (E.getInt()) {
7544 CreatedSCEV = createSCEV(CurV);
7545 } else {
7546 // Otherwise get the operands we need to create SCEV's for before creating
7547 // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7548 // just use it.
7549 CreatedSCEV = getOperandsToCreate(CurV, Ops);
7550 }
7551
7552 if (CreatedSCEV) {
7553 insertValueToMap(CurV, CreatedSCEV);
7554 Stack.pop_back();
7555 } else {
7556 Stack.back().setInt(true);
7557 // Queue its operands which need to be constructed.
7558 for (Value *Op : Ops)
7559 Stack.emplace_back(Op, false);
7560 }
7561 }
7562
7563 return getExistingSCEV(V);
7564}
7565
7566const SCEV *
7567ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7568 if (!isSCEVable(V->getType()))
7569 return getUnknown(V);
7570
7571 if (Instruction *I = dyn_cast<Instruction>(V)) {
7572 // Don't attempt to analyze instructions in blocks that aren't
7573 // reachable. Such instructions don't matter, and they aren't required
7574 // to obey basic rules for definitions dominating uses which this
7575 // analysis depends on.
7576 if (!DT.isReachableFromEntry(I->getParent()))
7577 return getUnknown(PoisonValue::get(V->getType()));
7578 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7579 return getConstant(CI);
7580 else if (isa<GlobalAlias>(V))
7581 return getUnknown(V);
7582 else if (!isa<ConstantExpr>(V))
7583 return getUnknown(V);
7584
7586 if (auto BO =
7588 bool IsConstArg = isa<ConstantInt>(BO->RHS);
7589 switch (BO->Opcode) {
7590 case Instruction::Add:
7591 case Instruction::Mul: {
7592 // For additions and multiplications, traverse add/mul chains for which we
7593 // can potentially create a single SCEV, to reduce the number of
7594 // get{Add,Mul}Expr calls.
7595 do {
7596 if (BO->Op) {
7597 if (BO->Op != V && getExistingSCEV(BO->Op)) {
7598 Ops.push_back(BO->Op);
7599 break;
7600 }
7601 }
7602 Ops.push_back(BO->RHS);
7603 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7605 if (!NewBO ||
7606 (BO->Opcode == Instruction::Add &&
7607 (NewBO->Opcode != Instruction::Add &&
7608 NewBO->Opcode != Instruction::Sub)) ||
7609 (BO->Opcode == Instruction::Mul &&
7610 NewBO->Opcode != Instruction::Mul)) {
7611 Ops.push_back(BO->LHS);
7612 break;
7613 }
7614 // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7615 // requires a SCEV for the LHS.
7616 if (BO->Op && (BO->IsNSW || BO->IsNUW)) {
7617 auto *I = dyn_cast<Instruction>(BO->Op);
7618 if (I && programUndefinedIfPoison(I)) {
7619 Ops.push_back(BO->LHS);
7620 break;
7621 }
7622 }
7623 BO = NewBO;
7624 } while (true);
7625 return nullptr;
7626 }
7627 case Instruction::Sub:
7628 case Instruction::UDiv:
7629 case Instruction::URem:
7630 break;
7631 case Instruction::AShr:
7632 case Instruction::Shl:
7633 case Instruction::Xor:
7634 if (!IsConstArg)
7635 return nullptr;
7636 break;
7637 case Instruction::And:
7638 case Instruction::Or:
7639 if (!IsConstArg && !BO->LHS->getType()->isIntegerTy(1))
7640 return nullptr;
7641 break;
7642 case Instruction::LShr:
7643 return getUnknown(V);
7644 default:
7645 llvm_unreachable("Unhandled binop");
7646 break;
7647 }
7648
7649 Ops.push_back(BO->LHS);
7650 Ops.push_back(BO->RHS);
7651 return nullptr;
7652 }
7653
7654 switch (U->getOpcode()) {
7655 case Instruction::Trunc:
7656 case Instruction::ZExt:
7657 case Instruction::SExt:
7658 case Instruction::PtrToAddr:
7659 case Instruction::PtrToInt:
7660 Ops.push_back(U->getOperand(0));
7661 return nullptr;
7662
7663 case Instruction::BitCast:
7664 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
7665 Ops.push_back(U->getOperand(0));
7666 return nullptr;
7667 }
7668 return getUnknown(V);
7669
7670 case Instruction::SDiv:
7671 case Instruction::SRem:
7672 Ops.push_back(U->getOperand(0));
7673 Ops.push_back(U->getOperand(1));
7674 return nullptr;
7675
7676 case Instruction::GetElementPtr:
7677 assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7678 "GEP source element type must be sized");
7679 llvm::append_range(Ops, U->operands());
7680 return nullptr;
7681
7682 case Instruction::IntToPtr:
7683 return getUnknown(V);
7684
7685 case Instruction::PHI:
7686 // getNodeForPHI has four ways to turn a PHI into a SCEV; retrieve the
7687 // relevant nodes for each of them.
7688 //
7689 // The first is just to call simplifyInstruction, and get something back
7690 // that isn't a PHI.
7691 if (Value *V = simplifyInstruction(
7692 cast<PHINode>(U),
7693 {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
7694 /*UseInstrInfo=*/true, /*CanUseUndef=*/false})) {
7695 assert(V);
7696 Ops.push_back(V);
7697 return nullptr;
7698 }
7699 // The second is createNodeForPHIWithIdenticalOperands: this looks for
7700 // operands which all perform the same operation, but haven't been
7701 // CSE'ed for whatever reason.
7702 if (BinaryOperator *BO = getCommonInstForPHI(cast<PHINode>(U))) {
7703 assert(BO);
7704 Ops.push_back(BO);
7705 return nullptr;
7706 }
7707 // The third is createNodeFromSelectLikePHI; this takes a PHI which
7708 // is equivalent to a select, and analyzes it like a select.
7709 {
7710 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
7712 assert(Cond);
7713 assert(LHS);
7714 assert(RHS);
7715 if (auto *CondICmp = dyn_cast<ICmpInst>(Cond)) {
7716 Ops.push_back(CondICmp->getOperand(0));
7717 Ops.push_back(CondICmp->getOperand(1));
7718 }
7719 Ops.push_back(Cond);
7720 Ops.push_back(LHS);
7721 Ops.push_back(RHS);
7722 return nullptr;
7723 }
7724 }
7725 // The fourth way is createAddRecFromPHI. It's complicated to handle here,
7726 // so just construct it recursively.
7727 //
7728 // In addition to getNodeForPHI, also construct nodes which might be needed
7729 // by getRangeRef.
7731 for (Value *V : cast<PHINode>(U)->operands())
7732 Ops.push_back(V);
7733 return nullptr;
7734 }
7735 return nullptr;
7736
7737 case Instruction::Select: {
7738 // Check if U is a select that can be simplified to a SCEVUnknown.
7739 auto CanSimplifyToUnknown = [this, U]() {
7740 if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
7741 return false;
7742
7743 auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
7744 if (!ICI)
7745 return false;
7746 Value *LHS = ICI->getOperand(0);
7747 Value *RHS = ICI->getOperand(1);
7748 if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7749 ICI->getPredicate() == CmpInst::ICMP_NE) {
7751 return true;
7752 } else if (getTypeSizeInBits(LHS->getType()) >
7753 getTypeSizeInBits(U->getType()))
7754 return true;
7755 return false;
7756 };
7757 if (CanSimplifyToUnknown())
7758 return getUnknown(U);
7759
7760 llvm::append_range(Ops, U->operands());
7761 return nullptr;
7762 break;
7763 }
7764 case Instruction::Call:
7765 case Instruction::Invoke:
7766 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7767 Ops.push_back(RV);
7768 return nullptr;
7769 }
7770
7771 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7772 switch (II->getIntrinsicID()) {
7773 case Intrinsic::abs:
7774 Ops.push_back(II->getArgOperand(0));
7775 return nullptr;
7776 case Intrinsic::umax:
7777 case Intrinsic::umin:
7778 case Intrinsic::smax:
7779 case Intrinsic::smin:
7780 case Intrinsic::usub_sat:
7781 case Intrinsic::uadd_sat:
7782 Ops.push_back(II->getArgOperand(0));
7783 Ops.push_back(II->getArgOperand(1));
7784 return nullptr;
7785 case Intrinsic::start_loop_iterations:
7786 case Intrinsic::annotation:
7787 case Intrinsic::ptr_annotation:
7788 Ops.push_back(II->getArgOperand(0));
7789 return nullptr;
7790 default:
7791 break;
7792 }
7793 }
7794 break;
7795 }
7796
7797 return nullptr;
7798}
7799
7800const SCEV *ScalarEvolution::createSCEV(Value *V) {
7801 if (!isSCEVable(V->getType()))
7802 return getUnknown(V);
7803
7804 if (Instruction *I = dyn_cast<Instruction>(V)) {
7805 // Don't attempt to analyze instructions in blocks that aren't
7806 // reachable. Such instructions don't matter, and they aren't required
7807 // to obey basic rules for definitions dominating uses which this
7808 // analysis depends on.
7809 if (!DT.isReachableFromEntry(I->getParent()))
7810 return getUnknown(PoisonValue::get(V->getType()));
7811 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7812 return getConstant(CI);
7813 else if (isa<GlobalAlias>(V))
7814 return getUnknown(V);
7815 else if (!isa<ConstantExpr>(V))
7816 return getUnknown(V);
7817
7818 const SCEV *LHS;
7819 const SCEV *RHS;
7820
7822 if (auto BO =
7824 switch (BO->Opcode) {
7825 case Instruction::Add: {
7826 // The simple thing to do would be to just call getSCEV on both operands
7827 // and call getAddExpr with the result. However if we're looking at a
7828 // bunch of things all added together, this can be quite inefficient,
7829 // because it leads to N-1 getAddExpr calls for N ultimate operands.
7830 // Instead, gather up all the operands and make a single getAddExpr call.
7831 // LLVM IR canonical form means we need only traverse the left operands.
7833 do {
7834 if (BO->Op) {
7835 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7836 AddOps.push_back(OpSCEV);
7837 break;
7838 }
7839
7840 // If a NUW or NSW flag can be applied to the SCEV for this
7841 // addition, then compute the SCEV for this addition by itself
7842 // with a separate call to getAddExpr. We need to do that
7843 // instead of pushing the operands of the addition onto AddOps,
7844 // since the flags are only known to apply to this particular
7845 // addition - they may not apply to other additions that can be
7846 // formed with operands from AddOps.
7847 const SCEV *RHS = getSCEV(BO->RHS);
7848 SCEVFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7849 if (Flags != SCEV::FlagNone) {
7850 const SCEV *LHS = getSCEV(BO->LHS);
7851 if (BO->Opcode == Instruction::Sub)
7852 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7853 else
7854 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7855 break;
7856 }
7857 }
7858
7859 if (BO->Opcode == Instruction::Sub)
7860 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7861 else
7862 AddOps.push_back(getSCEV(BO->RHS));
7863
7864 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7866 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7867 NewBO->Opcode != Instruction::Sub)) {
7868 AddOps.push_back(getSCEV(BO->LHS));
7869 break;
7870 }
7871 BO = NewBO;
7872 } while (true);
7873
7874 return getAddExpr(AddOps);
7875 }
7876
7877 case Instruction::Mul: {
7879 do {
7880 if (BO->Op) {
7881 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7882 MulOps.push_back(OpSCEV);
7883 break;
7884 }
7885
7886 SCEVFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7887 if (Flags != SCEV::FlagNone) {
7888 LHS = getSCEV(BO->LHS);
7889 RHS = getSCEV(BO->RHS);
7890 MulOps.push_back(getMulExpr(LHS, RHS, Flags));
7891 break;
7892 }
7893 }
7894
7895 MulOps.push_back(getSCEV(BO->RHS));
7896 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7898 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7899 MulOps.push_back(getSCEV(BO->LHS));
7900 break;
7901 }
7902 BO = NewBO;
7903 } while (true);
7904
7905 return getMulExpr(MulOps);
7906 }
7907 case Instruction::UDiv:
7908 LHS = getSCEV(BO->LHS);
7909 RHS = getSCEV(BO->RHS);
7910 return getUDivExpr(LHS, RHS);
7911 case Instruction::URem:
7912 LHS = getSCEV(BO->LHS);
7913 RHS = getSCEV(BO->RHS);
7914 return getURemExpr(LHS, RHS);
7915 case Instruction::Sub: {
7917 if (BO->Op)
7918 Flags = getNoWrapFlagsFromUB(BO->Op);
7919
7920 // Try to use ptrtoaddr for subtracts with at least one ptrtoint
7921 // operand. While we don't model ptrtoint directly in SCEV, the
7922 // difference between two pointer addresses is well-defined.
7923 Value *PtrLHS = nullptr, *PtrRHS = nullptr;
7924 bool HasPtrLHS = match(BO->LHS, m_PtrToInt(m_Value(PtrLHS)));
7925 bool HasPtrRHS = match(BO->RHS, m_PtrToInt(m_Value(PtrRHS)));
7926 if (HasPtrLHS || HasPtrRHS) {
7927 // Convert a ptrtoint operand (OrigOp) to ptrtoaddr of its pointer
7928 // PtrOp. When only one side is ptrtoint (BothPtr is false), skip
7929 // SCEVUnknown pointers since wrapping them in ptrtoaddr adds no
7930 // useful structure.
7931 auto GetOp = [&](bool HasPtr, Value *PtrOp, Value *OrigOp,
7932 bool BothPtr) -> const SCEV * {
7933 if (!HasPtr)
7934 return getSCEV(OrigOp);
7935 const SCEV *PtrSCEV = getSCEV(PtrOp);
7936 if (BothPtr || !isa<SCEVUnknown>(PtrSCEV)) {
7937 const SCEV *Addr = getPtrToAddrExpr(PtrSCEV);
7938 if (!isa<SCEVCouldNotCompute>(Addr) &&
7939 getTypeSizeInBits(OrigOp->getType()) <=
7940 getTypeSizeInBits(Addr->getType()))
7941 return getTruncateOrNoop(Addr, OrigOp->getType());
7942 }
7943 return getSCEV(OrigOp);
7944 };
7945 const SCEV *L = GetOp(HasPtrLHS, PtrLHS, BO->LHS, HasPtrRHS);
7946 const SCEV *R = GetOp(HasPtrRHS, PtrRHS, BO->RHS, HasPtrLHS);
7947 return getMinusSCEV(L, R, Flags);
7948 }
7949
7950 LHS = getSCEV(BO->LHS);
7951 RHS = getSCEV(BO->RHS);
7952 return getMinusSCEV(LHS, RHS, Flags);
7953 }
7954 case Instruction::And:
7955 // For an expression like x&255 that merely masks off the high bits,
7956 // use zext(trunc(x)) as the SCEV expression.
7957 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7958 if (CI->isZero())
7959 return getSCEV(BO->RHS);
7960 if (CI->isMinusOne())
7961 return getSCEV(BO->LHS);
7962 const APInt &A = CI->getValue();
7963
7964 // Instcombine's ShrinkDemandedConstant may strip bits out of
7965 // constants, obscuring what would otherwise be a low-bits mask.
7966 // Use computeKnownBits to compute what ShrinkDemandedConstant
7967 // knew about to reconstruct a low-bits mask value.
7968 unsigned LZ = A.countl_zero();
7969 unsigned TZ = A.countr_zero();
7970 unsigned BitWidth = A.getBitWidth();
7971 KnownBits Known(BitWidth);
7972 computeKnownBits(BO->LHS, Known, getDataLayout(), &AC, nullptr, &DT);
7973
7974 APInt EffectiveMask =
7975 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
7976 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
7977 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
7978 const SCEV *LHS = getSCEV(BO->LHS);
7979 const SCEV *ShiftedLHS = nullptr;
7980 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
7981 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
7982 // For an expression like (x * 8) & 8, simplify the multiply.
7983 unsigned MulZeros = OpC->getAPInt().countr_zero();
7984 unsigned GCD = std::min(MulZeros, TZ);
7985 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
7987 MulOps.push_back(getConstant(OpC->getAPInt().ashr(GCD)));
7988 append_range(MulOps, LHSMul->operands().drop_front());
7989 const SCEV *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
7990 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
7991 }
7992 }
7993 if (!ShiftedLHS)
7994 ShiftedLHS = getUDivExpr(LHS, MulCount);
7995 return getMulExpr(
7997 getTruncateExpr(ShiftedLHS,
7998 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
7999 BO->LHS->getType()),
8000 MulCount);
8001 }
8002 }
8003 // Binary `and` is a bit-wise `umin`.
8004 if (BO->LHS->getType()->isIntegerTy(1)) {
8005 LHS = getSCEV(BO->LHS);
8006 RHS = getSCEV(BO->RHS);
8007 return getUMinExpr(LHS, RHS);
8008 }
8009 break;
8010
8011 case Instruction::Or:
8012 // Binary `or` is a bit-wise `umax`.
8013 if (BO->LHS->getType()->isIntegerTy(1)) {
8014 LHS = getSCEV(BO->LHS);
8015 RHS = getSCEV(BO->RHS);
8016 return getUMaxExpr(LHS, RHS);
8017 }
8018 break;
8019
8020 case Instruction::Xor:
8021 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
8022 // If the RHS of xor is -1, then this is a not operation.
8023 if (CI->isMinusOne())
8024 return getNotSCEV(getSCEV(BO->LHS));
8025
8026 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
8027 // This is a variant of the check for xor with -1, and it handles
8028 // the case where instcombine has trimmed non-demanded bits out
8029 // of an xor with -1.
8030 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
8031 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
8032 if (LBO->getOpcode() == Instruction::And &&
8033 LCI->getValue() == CI->getValue())
8034 if (const SCEVZeroExtendExpr *Z =
8036 Type *UTy = BO->LHS->getType();
8037 const SCEV *Z0 = Z->getOperand();
8038 Type *Z0Ty = Z0->getType();
8039 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
8040
8041 // If C is a low-bits mask, the zero extend is serving to
8042 // mask off the high bits. Complement the operand and
8043 // re-apply the zext.
8044 if (CI->getValue().isMask(Z0TySize))
8045 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
8046
8047 // If C is a single bit, it may be in the sign-bit position
8048 // before the zero-extend. In this case, represent the xor
8049 // using an add, which is equivalent, and re-apply the zext.
8050 APInt Trunc = CI->getValue().trunc(Z0TySize);
8051 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
8052 Trunc.isSignMask())
8053 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
8054 UTy);
8055 }
8056 }
8057 break;
8058
8059 case Instruction::Shl:
8060 // Turn shift left of a constant amount into a multiply.
8061 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
8062 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
8063
8064 // If the shift count is not less than the bitwidth, the result of
8065 // the shift is undefined. Don't try to analyze it, because the
8066 // resolution chosen here may differ from the resolution chosen in
8067 // other parts of the compiler.
8068 if (SA->getValue().uge(BitWidth))
8069 break;
8070
8071 // We can safely preserve the nuw flag in all cases. It's also safe to
8072 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
8073 // requires special handling. It can be preserved as long as we're not
8074 // left shifting by bitwidth - 1.
8075 auto Flags = SCEV::FlagNone;
8076 if (BO->Op) {
8077 auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
8078 if (any(MulFlags & SCEV::FlagNSW) &&
8079 (any(MulFlags & SCEV::FlagNUW) ||
8080 SA->getValue().ult(BitWidth - 1)))
8082 if (any(MulFlags & SCEV::FlagNUW))
8084 }
8085
8086 ConstantInt *X = ConstantInt::get(
8087 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
8088 return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
8089 }
8090 break;
8091
8092 case Instruction::AShr:
8093 // AShr X, C, where C is a constant.
8094 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
8095 if (!CI)
8096 break;
8097
8098 Type *OuterTy = BO->LHS->getType();
8100 // If the shift count is not less than the bitwidth, the result of
8101 // the shift is undefined. Don't try to analyze it, because the
8102 // resolution chosen here may differ from the resolution chosen in
8103 // other parts of the compiler.
8104 if (CI->getValue().uge(BitWidth))
8105 break;
8106
8107 if (CI->isZero())
8108 return getSCEV(BO->LHS); // shift by zero --> noop
8109
8110 uint64_t AShrAmt = CI->getZExtValue();
8111 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
8112
8113 Operator *L = dyn_cast<Operator>(BO->LHS);
8114 const SCEV *AddTruncateExpr = nullptr;
8115 ConstantInt *ShlAmtCI = nullptr;
8116 const SCEV *AddConstant = nullptr;
8117
8118 if (L && L->getOpcode() == Instruction::Add) {
8119 // X = Shl A, n
8120 // Y = Add X, c
8121 // Z = AShr Y, m
8122 // n, c and m are constants.
8123
8124 Operator *LShift = dyn_cast<Operator>(L->getOperand(0));
8125 ConstantInt *AddOperandCI = dyn_cast<ConstantInt>(L->getOperand(1));
8126 if (LShift && LShift->getOpcode() == Instruction::Shl) {
8127 if (AddOperandCI) {
8128 const SCEV *ShlOp0SCEV = getSCEV(LShift->getOperand(0));
8129 ShlAmtCI = dyn_cast<ConstantInt>(LShift->getOperand(1));
8130 // since we truncate to TruncTy, the AddConstant should be of the
8131 // same type, so create a new Constant with type same as TruncTy.
8132 // Also, the Add constant should be shifted right by AShr amount.
8133 APInt AddOperand = AddOperandCI->getValue().ashr(AShrAmt);
8134 AddConstant = getConstant(AddOperand.trunc(BitWidth - AShrAmt));
8135 // we model the expression as sext(add(trunc(A), c << n)), since the
8136 // sext(trunc) part is already handled below, we create a
8137 // AddExpr(TruncExp) which will be used later.
8138 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8139 }
8140 }
8141 } else if (L && L->getOpcode() == Instruction::Shl) {
8142 // X = Shl A, n
8143 // Y = AShr X, m
8144 // Both n and m are constant.
8145
8146 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
8147 ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
8148 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8149 }
8150
8151 if (AddTruncateExpr && ShlAmtCI) {
8152 // We can merge the two given cases into a single SCEV statement,
8153 // incase n = m, the mul expression will be 2^0, so it gets resolved to
8154 // a simpler case. The following code handles the two cases:
8155 //
8156 // 1) For a two-shift sext-inreg, i.e. n = m,
8157 // use sext(trunc(x)) as the SCEV expression.
8158 //
8159 // 2) When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
8160 // expression. We already checked that ShlAmt < BitWidth, so
8161 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
8162 // ShlAmt - AShrAmt < Amt.
8163 const APInt &ShlAmt = ShlAmtCI->getValue();
8164 if (ShlAmt.ult(BitWidth) && ShlAmt.uge(AShrAmt)) {
8165 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
8166 ShlAmtCI->getZExtValue() - AShrAmt);
8167 const SCEV *CompositeExpr =
8168 getMulExpr(AddTruncateExpr, getConstant(Mul));
8169 if (L->getOpcode() != Instruction::Shl)
8170 CompositeExpr = getAddExpr(CompositeExpr, AddConstant);
8171
8172 return getSignExtendExpr(CompositeExpr, OuterTy);
8173 }
8174 }
8175 break;
8176 }
8177 }
8178
8179 switch (U->getOpcode()) {
8180 case Instruction::Trunc:
8181 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
8182
8183 case Instruction::ZExt:
8184 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8185
8186 case Instruction::SExt:
8187 if (auto BO = MatchBinaryOp(U->getOperand(0), getDataLayout(), AC, DT,
8189 // The NSW flag of a subtract does not always survive the conversion to
8190 // A + (-1)*B. By pushing sign extension onto its operands we are much
8191 // more likely to preserve NSW and allow later AddRec optimisations.
8192 //
8193 // NOTE: This is effectively duplicating this logic from getSignExtend:
8194 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
8195 // but by that point the NSW information has potentially been lost.
8196 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
8197 Type *Ty = U->getType();
8198 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
8199 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
8200 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
8201 }
8202 }
8203 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8204
8205 case Instruction::BitCast:
8206 // BitCasts are no-op casts so we just eliminate the cast.
8207 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
8208 return getSCEV(U->getOperand(0));
8209 break;
8210
8211 case Instruction::PtrToAddr: {
8212 const SCEV *IntOp = getPtrToAddrExpr(getSCEV(U->getOperand(0)));
8213 if (isa<SCEVCouldNotCompute>(IntOp))
8214 return getUnknown(V);
8215 return IntOp;
8216 }
8217
8218 case Instruction::PtrToInt:
8219 // SCEV only models ptrtoaddr.
8220 return getUnknown(V);
8221
8222 case Instruction::IntToPtr:
8223 // Just don't deal with inttoptr casts.
8224 return getUnknown(V);
8225
8226 case Instruction::SDiv:
8227 // If both operands are non-negative, this is just an udiv.
8228 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8229 isKnownNonNegative(getSCEV(U->getOperand(1))))
8230 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8231 break;
8232
8233 case Instruction::SRem:
8234 // If both operands are non-negative, this is just an urem.
8235 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8236 isKnownNonNegative(getSCEV(U->getOperand(1))))
8237 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8238 break;
8239
8240 case Instruction::GetElementPtr:
8241 return createNodeForGEP(cast<GEPOperator>(U));
8242
8243 case Instruction::PHI:
8244 return createNodeForPHI(cast<PHINode>(U));
8245
8246 case Instruction::Select:
8247 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
8248 U->getOperand(2));
8249
8250 case Instruction::Call:
8251 case Instruction::Invoke:
8252 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
8253 return getSCEV(RV);
8254
8255 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
8256 switch (II->getIntrinsicID()) {
8257 case Intrinsic::abs:
8258 return getAbsExpr(
8259 getSCEV(II->getArgOperand(0)),
8260 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
8261 case Intrinsic::umax:
8262 LHS = getSCEV(II->getArgOperand(0));
8263 RHS = getSCEV(II->getArgOperand(1));
8264 return getUMaxExpr(LHS, RHS);
8265 case Intrinsic::umin:
8266 LHS = getSCEV(II->getArgOperand(0));
8267 RHS = getSCEV(II->getArgOperand(1));
8268 return getUMinExpr(LHS, RHS);
8269 case Intrinsic::smax:
8270 LHS = getSCEV(II->getArgOperand(0));
8271 RHS = getSCEV(II->getArgOperand(1));
8272 return getSMaxExpr(LHS, RHS);
8273 case Intrinsic::smin:
8274 LHS = getSCEV(II->getArgOperand(0));
8275 RHS = getSCEV(II->getArgOperand(1));
8276 return getSMinExpr(LHS, RHS);
8277 case Intrinsic::usub_sat: {
8278 const SCEV *X = getSCEV(II->getArgOperand(0));
8279 const SCEV *Y = getSCEV(II->getArgOperand(1));
8280 const SCEV *ClampedY = getUMinExpr(X, Y);
8281 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
8282 }
8283 case Intrinsic::uadd_sat: {
8284 const SCEV *X = getSCEV(II->getArgOperand(0));
8285 const SCEV *Y = getSCEV(II->getArgOperand(1));
8286 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
8287 return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
8288 }
8289 case Intrinsic::start_loop_iterations:
8290 case Intrinsic::annotation:
8291 case Intrinsic::ptr_annotation:
8292 // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8293 // just eqivalent to the first operand for SCEV purposes.
8294 return getSCEV(II->getArgOperand(0));
8295 case Intrinsic::vscale:
8296 return getVScale(II->getType());
8297 default:
8298 break;
8299 }
8300 }
8301 break;
8302 }
8303
8304 return getUnknown(V);
8305}
8306
8307//===----------------------------------------------------------------------===//
8308// Iteration Count Computation Code
8309//
8310
8312 if (isa<SCEVCouldNotCompute>(ExitCount))
8313 return getCouldNotCompute();
8314
8315 auto *ExitCountType = ExitCount->getType();
8316 assert(ExitCountType->isIntegerTy());
8317 auto *EvalTy = Type::getIntNTy(ExitCountType->getContext(),
8318 1 + ExitCountType->getScalarSizeInBits());
8319 return getTripCountFromExitCount(ExitCount, EvalTy, nullptr);
8320}
8321
8323 Type *EvalTy,
8324 const Loop *L) {
8325 if (isa<SCEVCouldNotCompute>(ExitCount))
8326 return getCouldNotCompute();
8327
8328 unsigned ExitCountSize = getTypeSizeInBits(ExitCount->getType());
8329 unsigned EvalSize = EvalTy->getPrimitiveSizeInBits();
8330
8331 auto CanAddOneWithoutOverflow = [&]() {
8332 ConstantRange ExitCountRange =
8333 getRangeRef(ExitCount, RangeSignHint::HINT_RANGE_UNSIGNED);
8334 if (!ExitCountRange.contains(APInt::getMaxValue(ExitCountSize)))
8335 return true;
8336
8337 return L && isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
8338 getMinusOne(ExitCount->getType()));
8339 };
8340
8341 // If we need to zero extend the backedge count, check if we can add one to
8342 // it prior to zero extending without overflow. Provided this is safe, it
8343 // allows better simplification of the +1.
8344 if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8345 return getZeroExtendExpr(
8346 getAddExpr(ExitCount, getOne(ExitCount->getType())), EvalTy);
8347
8348 // Get the total trip count from the count by adding 1. This may wrap.
8349 return getAddExpr(getTruncateOrZeroExtend(ExitCount, EvalTy), getOne(EvalTy));
8350}
8351
8352static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8353 if (!ExitCount)
8354 return 0;
8355
8356 ConstantInt *ExitConst = ExitCount->getValue();
8357
8358 // Guard against huge trip counts.
8359 if (ExitConst->getValue().getActiveBits() > 32)
8360 return 0;
8361
8362 // In case of integer overflow, this returns 0, which is correct.
8363 return ((unsigned)ExitConst->getZExtValue()) + 1;
8364}
8365
8367 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
8368 return getConstantTripCount(ExitCount);
8369}
8370
8371unsigned
8373 const BasicBlock *ExitingBlock) {
8374 assert(ExitingBlock && "Must pass a non-null exiting block!");
8375 assert(L->isLoopExiting(ExitingBlock) &&
8376 "Exiting block must actually branch out of the loop!");
8377 const SCEVConstant *ExitCount =
8378 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
8379 return getConstantTripCount(ExitCount);
8380}
8381
8383 const Loop *L, SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8384
8385 const auto *MaxExitCount =
8386 Predicates ? getPredicatedConstantMaxBackedgeTakenCount(L, *Predicates)
8388 return getConstantTripCount(dyn_cast<SCEVConstant>(MaxExitCount));
8389}
8390
8392 SmallVector<BasicBlock *, 8> ExitingBlocks;
8393 L->getExitingBlocks(ExitingBlocks);
8394
8395 // An exit with an uncomputable exit count makes the result 1.
8396 if (ExitingBlocks.empty() ||
8397 any_of(ExitingBlocks, [this, L](BasicBlock *ExitingBB) {
8398 return isa<SCEVCouldNotCompute>(getExitCount(L, ExitingBB));
8399 }))
8400 return 1;
8401
8402 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
8403 unsigned Res = 0;
8404 for (BasicBlock *ExitingBB : ExitingBlocks)
8405 Res = std::gcd(
8406 Res, getSmallConstantTripMultiple(getExitCount(L, ExitingBB), Guards));
8407 return Res;
8408}
8409
8410unsigned ScalarEvolution::getSmallConstantTripMultiple(const SCEV *ExitCount,
8411 LoopGuards &Guards) {
8412 assert(!isa<SCEVCouldNotCompute>(ExitCount) && "Must be computable!");
8413
8414 // Get the trip count
8415 const SCEV *TCExpr =
8416 getTripCountFromExitCount(applyLoopGuards(ExitCount, Guards));
8417
8418 APInt Multiple = getNonZeroConstantMultiple(TCExpr);
8419 // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8420 // the greatest power of 2 divisor less than 2^32.
8421 return Multiple.getActiveBits() > 32
8422 ? 1U << std::min(31U, Multiple.countTrailingZeros())
8423 : (unsigned)Multiple.getZExtValue();
8424}
8425
8427 const SCEV *ExitCount) {
8428 if (isa<SCEVCouldNotCompute>(ExitCount))
8429 return 1;
8430
8431 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
8432 return getSmallConstantTripMultiple(ExitCount, Guards);
8433}
8434
8435/// Returns the largest constant divisor of the trip count of this loop as a
8436/// normal unsigned value, if possible. This means that the actual trip count is
8437/// always a multiple of the returned value (don't forget the trip count could
8438/// very well be zero as well!).
8439///
8440/// Returns 1 if the trip count is unknown or not guaranteed to be the
8441/// multiple of a constant (which is also the case if the trip count is simply
8442/// constant, use getSmallConstantTripCount for that case), Will also return 1
8443/// if the trip count is very large (>= 2^32).
8444///
8445/// As explained in the comments for getSmallConstantTripCount, this assumes
8446/// that control exits the loop via ExitingBlock.
8447unsigned
8449 const BasicBlock *ExitingBlock) {
8450 assert(ExitingBlock && "Must pass a non-null exiting block!");
8451 assert(L->isLoopExiting(ExitingBlock) &&
8452 "Exiting block must actually branch out of the loop!");
8453 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8454 return getSmallConstantTripMultiple(L, ExitCount);
8455}
8456
8458 const BasicBlock *ExitingBlock,
8459 ExitCountKind Kind) {
8460 switch (Kind) {
8461 case Exact:
8462 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8463 case SymbolicMaximum:
8464 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8465 case ConstantMaximum:
8466 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8467 };
8468 llvm_unreachable("Invalid ExitCountKind!");
8469}
8470
8472 const Loop *L, const BasicBlock *ExitingBlock,
8474 switch (Kind) {
8475 case Exact:
8476 return getPredicatedBackedgeTakenInfo(L).getExact(ExitingBlock, this,
8477 Predicates);
8478 case SymbolicMaximum:
8479 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this,
8480 Predicates);
8481 case ConstantMaximum:
8482 return getPredicatedBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this,
8483 Predicates);
8484 };
8485 llvm_unreachable("Invalid ExitCountKind!");
8486}
8487
8490 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8491}
8492
8494 ExitCountKind Kind) {
8495 switch (Kind) {
8496 case Exact:
8497 return getBackedgeTakenInfo(L).getExact(L, this);
8498 case ConstantMaximum:
8499 return getBackedgeTakenInfo(L).getConstantMax(this);
8500 case SymbolicMaximum:
8501 return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8502 };
8503 llvm_unreachable("Invalid ExitCountKind!");
8504}
8505
8508 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(L, this, &Preds);
8509}
8510
8513 return getPredicatedBackedgeTakenInfo(L).getConstantMax(this, &Preds);
8514}
8515
8517 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8518}
8519
8520/// Push PHI nodes in the header of the given loop onto the given Worklist.
8521static void PushLoopPHIs(const Loop *L,
8524 BasicBlock *Header = L->getHeader();
8525
8526 // Push all Loop-header PHIs onto the Worklist stack.
8527 for (PHINode &PN : Header->phis())
8528 if (Visited.insert(&PN).second)
8529 Worklist.push_back(&PN);
8530}
8531
8532ScalarEvolution::BackedgeTakenInfo &
8533ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8534 auto &BTI = getBackedgeTakenInfo(L);
8535 if (BTI.hasFullInfo())
8536 return BTI;
8537
8538 auto Pair = PredicatedBackedgeTakenCounts.try_emplace(L);
8539
8540 if (!Pair.second)
8541 return Pair.first->second;
8542
8543 BackedgeTakenInfo Result =
8544 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8545
8546 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8547}
8548
8549ScalarEvolution::BackedgeTakenInfo &
8550ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8551 // Initially insert an invalid entry for this loop. If the insertion
8552 // succeeds, proceed to actually compute a backedge-taken count and
8553 // update the value. The temporary CouldNotCompute value tells SCEV
8554 // code elsewhere that it shouldn't attempt to request a new
8555 // backedge-taken count, which could result in infinite recursion.
8556 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8557 BackedgeTakenCounts.try_emplace(L);
8558 if (!Pair.second)
8559 return Pair.first->second;
8560
8561 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8562 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8563 // must be cleared in this scope.
8564 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8565
8566 // Now that we know more about the trip count for this loop, forget any
8567 // existing SCEV values for PHI nodes in this loop since they are only
8568 // conservative estimates made without the benefit of trip count
8569 // information. This invalidation is not necessary for correctness, and is
8570 // only done to produce more precise results.
8571 if (Result.hasAnyInfo()) {
8572 // Invalidate any expression using an addrec in this loop.
8573 SmallVector<SCEVUse, 8> ToForget;
8574 auto LoopUsersIt = LoopUsers.find(L);
8575 if (LoopUsersIt != LoopUsers.end())
8576 append_range(ToForget, LoopUsersIt->second);
8577 forgetMemoizedResults(ToForget);
8578
8579 // Invalidate constant-evolved loop header phis.
8580 for (PHINode &PN : L->getHeader()->phis())
8581 ConstantEvolutionLoopExitValue.erase(&PN);
8582 }
8583
8584 // Re-lookup the insert position, since the call to
8585 // computeBackedgeTakenCount above could result in a
8586 // recusive call to getBackedgeTakenInfo (on a different
8587 // loop), which would invalidate the iterator computed
8588 // earlier.
8589 return BackedgeTakenCounts.find(L)->second = std::move(Result);
8590}
8591
8593 // This method is intended to forget all info about loops. It should
8594 // invalidate caches as if the following happened:
8595 // - The trip counts of all loops have changed arbitrarily
8596 // - Every llvm::Value has been updated in place to produce a different
8597 // result.
8598 BackedgeTakenCounts.clear();
8599 PredicatedBackedgeTakenCounts.clear();
8600 BECountUsers.clear();
8601 LoopPropertiesCache.clear();
8602 ConstantEvolutionLoopExitValue.clear();
8603 ValueExprMap.clear();
8604 ValuesAtScopes.clear();
8605 ValuesAtScopesUsers.clear();
8606 LoopDispositions.clear();
8607 BlockDispositions.clear();
8608 UnsignedRanges.clear();
8609 SignedRanges.clear();
8610 ExprValueMap.clear();
8611 HasRecMap.clear();
8612 ConstantMultipleCache.clear();
8613 PredicatedSCEVRewrites.clear();
8614 FoldCache.clear();
8615 FoldCacheUser.clear();
8616}
8617void ScalarEvolution::visitAndClearUsers(
8620 SmallVectorImpl<SCEVUse> &ToForget) {
8621 // Nothing can be invalidated if no value has a SCEV yet.
8622 if (ValueExprMap.empty()) {
8623 Worklist.clear();
8624 return;
8625 }
8626 while (!Worklist.empty()) {
8627 Instruction *I = Worklist.pop_back_val();
8628 if (!isSCEVable(I->getType()) && !isa<WithOverflowInst>(I))
8629 continue;
8630
8632 ValueExprMap.find_as(static_cast<Value *>(I));
8633 if (It != ValueExprMap.end()) {
8634 ToForget.push_back(It->second);
8635 eraseValueFromMap(It->first);
8636 if (PHINode *PN = dyn_cast<PHINode>(I))
8637 ConstantEvolutionLoopExitValue.erase(PN);
8638 }
8639
8640 PushDefUseChildren(I, Worklist, Visited);
8641 }
8642}
8643
8645 SmallVector<const Loop *, 16> LoopWorklist(1, L);
8648 SmallVector<SCEVUse, 16> ToForget;
8649
8650 // Iterate over all the loops and sub-loops to drop SCEV information.
8651 while (!LoopWorklist.empty()) {
8652 auto *CurrL = LoopWorklist.pop_back_val();
8653
8654 // Drop any stored trip count value.
8655 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8656 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8657
8658 // Drop information about predicated SCEV rewrites for this loop.
8659 PredicatedSCEVRewrites.remove_if(
8660 [&](const auto &Entry) { return Entry.first.second == CurrL; });
8661
8662 auto LoopUsersItr = LoopUsers.find(CurrL);
8663 if (LoopUsersItr != LoopUsers.end())
8664 llvm::append_range(ToForget, LoopUsersItr->second);
8665
8666 // Drop information about expressions based on loop-header PHIs.
8667 PushLoopPHIs(CurrL, Worklist, Visited);
8668 visitAndClearUsers(Worklist, Visited, ToForget);
8669
8670 LoopPropertiesCache.erase(CurrL);
8671 // Forget all contained loops too, to avoid dangling entries in the
8672 // ValuesAtScopes map.
8673 LoopWorklist.append(CurrL->begin(), CurrL->end());
8674 }
8675 forgetMemoizedResults(ToForget);
8676}
8677
8679 forgetLoop(L->getOutermostLoop());
8680}
8681
8684 if (!I) return;
8685
8686 // Drop information about expressions based on loop-header PHIs.
8689 SmallVector<SCEVUse, 8> ToForget;
8690 Worklist.push_back(I);
8691 Visited.insert(I);
8692 visitAndClearUsers(Worklist, Visited, ToForget);
8693
8694 forgetMemoizedResults(ToForget);
8695}
8696
8700 SmallVector<SCEVUse, 8> ToForget;
8701 for (Value *V : Values)
8702 if (auto *I = dyn_cast<Instruction>(V))
8703 if (Visited.insert(I).second)
8704 Worklist.push_back(I);
8705 visitAndClearUsers(Worklist, Visited, ToForget);
8706
8707 forgetMemoizedResults(ToForget);
8708}
8709
8711 // If SCEV looked through a trivial LCSSA phi node, we might have SCEV's
8712 // directly using a SCEVUnknown/SCEVAddRec defined in the loop. After an
8713 // extra predecessor is added, this is no longer valid. Find all Unknowns and
8714 // AddRecs defined in the loop and invalidate any SCEV's making use of them.
8715 auto InvalidateValue = [&](Value *Val) {
8716 if (!isSCEVable(Val->getType()))
8717 return;
8718 if (const SCEV *S = getExistingSCEV(Val)) {
8719 struct InvalidationRootCollector {
8720 Loop *L;
8722
8723 InvalidationRootCollector(Loop *L) : L(L) {}
8724
8725 bool follow(const SCEV *S) {
8726 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
8727 if (auto *I = dyn_cast<Instruction>(SU->getValue()))
8728 if (L->contains(I))
8729 Roots.push_back(S);
8730 } else if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
8731 if (L->contains(AddRec->getLoop()))
8732 Roots.push_back(S);
8733 }
8734 return true;
8735 }
8736 bool isDone() const { return false; }
8737 };
8738
8739 InvalidationRootCollector C(L);
8740 visitAll(S, C);
8741 forgetMemoizedResults(C.Roots);
8742 }
8743 };
8744
8745 InvalidateValue(V);
8746
8747 // If V has a non-SCEV-able type (e.g. {i64, i1} from a with.overflow
8748 // intrinsic), its users (e.g. extractvalue) may have stale SCEV
8749 // expressions referencing loop-internal values.
8750 if (!isSCEVable(V->getType()) &&
8751 any_of(V->incoming_values(), IsaPred<WithOverflowInst>))
8752 for (User *U : V->users())
8753 InvalidateValue(U);
8754 // Also perform the normal invalidation.
8755 forgetValue(V);
8756}
8757
8758void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8759
8761 // Unless a specific value is passed to invalidation, completely clear both
8762 // caches.
8763 if (!V) {
8764 BlockDispositions.clear();
8765 LoopDispositions.clear();
8766 return;
8767 }
8768
8769 if (!isSCEVable(V->getType()))
8770 return;
8771
8772 const SCEV *S = getExistingSCEV(V);
8773 if (!S)
8774 return;
8775
8776 // Invalidate the block and loop dispositions cached for S. Dispositions of
8777 // S's users may change if S's disposition changes (i.e. a user may change to
8778 // loop-invariant, if S changes to loop invariant), so also invalidate
8779 // dispositions of S's users recursively.
8780 SmallVector<SCEVUse, 8> Worklist = {S};
8782 while (!Worklist.empty()) {
8783 const SCEV *Curr = Worklist.pop_back_val();
8784 bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8785 bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8786 if (!LoopDispoRemoved && !BlockDispoRemoved)
8787 continue;
8788 auto Users = SCEVUsers.find(Curr);
8789 if (Users != SCEVUsers.end())
8790 for (const auto *User : Users->second)
8791 if (Seen.insert(User).second)
8792 Worklist.push_back(User);
8793 }
8794}
8795
8796/// Get the exact loop backedge taken count considering all loop exits. A
8797/// computable result can only be returned for loops with all exiting blocks
8798/// dominating the latch. howFarToZero assumes that the limit of each loop test
8799/// is never skipped. This is a valid assumption as long as the loop exits via
8800/// that test. For precise results, it is the caller's responsibility to specify
8801/// the relevant loop exiting block using getExact(ExitingBlock, SE).
8802const SCEV *ScalarEvolution::BackedgeTakenInfo::getExact(
8803 const Loop *L, ScalarEvolution *SE,
8805 // If any exits were not computable, the loop is not computable.
8806 if (!isComplete() || ExitNotTaken.empty())
8807 return SE->getCouldNotCompute();
8808
8809 const BasicBlock *Latch = L->getLoopLatch();
8810 // All exiting blocks we have collected must dominate the only backedge.
8811 if (!Latch)
8812 return SE->getCouldNotCompute();
8813
8814 // All exiting blocks we have gathered dominate loop's latch, so exact trip
8815 // count is simply a minimum out of all these calculated exit counts.
8817 for (const auto &ENT : ExitNotTaken) {
8818 const SCEV *BECount = ENT.ExactNotTaken;
8819 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8820 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8821 "We should only have known counts for exiting blocks that dominate "
8822 "latch!");
8823
8824 Ops.push_back(BECount);
8825
8826 if (Preds)
8827 append_range(*Preds, ENT.Predicates);
8828
8829 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8830 "Predicate should be always true!");
8831 }
8832
8833 // If an earlier exit exits on the first iteration (exit count zero), then
8834 // a later poison exit count should not propagate into the result. This are
8835 // exactly the semantics provided by umin_seq.
8836 return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8837}
8838
8839const ScalarEvolution::ExitNotTakenInfo *
8840ScalarEvolution::BackedgeTakenInfo::getExitNotTaken(
8841 const BasicBlock *ExitingBlock,
8842 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8843 for (const auto &ENT : ExitNotTaken)
8844 if (ENT.ExitingBlock == ExitingBlock) {
8845 if (ENT.hasAlwaysTruePredicate())
8846 return &ENT;
8847 else if (Predicates) {
8848 append_range(*Predicates, ENT.Predicates);
8849 return &ENT;
8850 }
8851 }
8852
8853 return nullptr;
8854}
8855
8856/// getConstantMax - Get the constant max backedge taken count for the loop.
8857const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8858 ScalarEvolution *SE,
8859 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8860 if (!getConstantMax())
8861 return SE->getCouldNotCompute();
8862
8863 for (const auto &ENT : ExitNotTaken)
8864 if (!ENT.hasAlwaysTruePredicate()) {
8865 if (!Predicates)
8866 return SE->getCouldNotCompute();
8867 append_range(*Predicates, ENT.Predicates);
8868 }
8869
8870 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8871 isa<SCEVConstant>(getConstantMax())) &&
8872 "No point in having a non-constant max backedge taken count!");
8873 return getConstantMax();
8874}
8875
8876const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8877 const Loop *L, ScalarEvolution *SE,
8878 SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8879 if (!SymbolicMax) {
8880 // Form an expression for the maximum exit count possible for this loop. We
8881 // merge the max and exact information to approximate a version of
8882 // getConstantMaxBackedgeTakenCount which isn't restricted to just
8883 // constants.
8884 SmallVector<SCEVUse, 4> ExitCounts;
8885
8886 for (const auto &ENT : ExitNotTaken) {
8887 const SCEV *ExitCount = ENT.SymbolicMaxNotTaken;
8888 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
8889 assert(SE->DT.dominates(ENT.ExitingBlock, L->getLoopLatch()) &&
8890 "We should only have known counts for exiting blocks that "
8891 "dominate latch!");
8892 ExitCounts.push_back(ExitCount);
8893 if (Predicates)
8894 append_range(*Predicates, ENT.Predicates);
8895
8896 assert((Predicates || ENT.hasAlwaysTruePredicate()) &&
8897 "Predicate should be always true!");
8898 }
8899 }
8900 if (ExitCounts.empty())
8901 SymbolicMax = SE->getCouldNotCompute();
8902 else
8903 SymbolicMax =
8904 SE->getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
8905 }
8906 return SymbolicMax;
8907}
8908
8909bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8910 ScalarEvolution *SE) const {
8911 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8912 return !ENT.hasAlwaysTruePredicate();
8913 };
8914 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8915}
8916
8919
8921 const SCEV *E, const SCEV *ConstantMaxNotTaken,
8922 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8926 // If we prove the max count is zero, so is the symbolic bound. This happens
8927 // in practice due to differences in a) how context sensitive we've chosen
8928 // to be and b) how we reason about bounds implied by UB.
8929 if (ConstantMaxNotTaken->isZero()) {
8930 this->ExactNotTaken = E = ConstantMaxNotTaken;
8931 this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
8932 }
8933
8936 "Exact is not allowed to be less precise than Constant Max");
8939 "Exact is not allowed to be less precise than Symbolic Max");
8942 "Symbolic Max is not allowed to be less precise than Constant Max");
8945 "No point in having a non-constant max backedge taken count!");
8947 for (const auto PredList : PredLists)
8948 for (const auto *P : PredList) {
8949 if (SeenPreds.contains(P))
8950 continue;
8951 assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!");
8952 SeenPreds.insert(P);
8953 Predicates.push_back(P);
8954 }
8955 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8956 "Backedge count should be int");
8958 !ConstantMaxNotTaken->getType()->isPointerTy()) &&
8959 "Max backedge count should be int");
8960}
8961
8969
8970/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8971/// computable exit into a persistent ExitNotTakenInfo array.
8972ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8974 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
8975 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8976 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8977
8978 ExitNotTaken.reserve(ExitCounts.size());
8979 std::transform(ExitCounts.begin(), ExitCounts.end(),
8980 std::back_inserter(ExitNotTaken),
8981 [&](const EdgeExitInfo &EEI) {
8982 BasicBlock *ExitBB = EEI.first;
8983 const ExitLimit &EL = EEI.second;
8984 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
8985 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
8986 EL.Predicates);
8987 });
8988 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
8989 isa<SCEVConstant>(ConstantMax)) &&
8990 "No point in having a non-constant max backedge taken count!");
8991}
8992
8993/// Compute the number of times the backedge of the specified loop will execute.
8994ScalarEvolution::BackedgeTakenInfo
8995ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
8996 bool AllowPredicates) {
8997 SmallVector<BasicBlock *, 8> ExitingBlocks;
8998 L->getExitingBlocks(ExitingBlocks);
8999
9000 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
9001
9003 bool CouldComputeBECount = true;
9004 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
9005 const SCEV *MustExitMaxBECount = nullptr;
9006 const SCEV *MayExitMaxBECount = nullptr;
9007 bool MustExitMaxOrZero = false;
9008 bool IsOnlyExit = ExitingBlocks.size() == 1;
9009
9010 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
9011 // and compute maxBECount.
9012 // Do a union of all the predicates here.
9013 for (BasicBlock *ExitBB : ExitingBlocks) {
9014 // We canonicalize untaken exits to br (constant), ignore them so that
9015 // proving an exit untaken doesn't negatively impact our ability to reason
9016 // about the loop as whole.
9017 if (auto *BI = dyn_cast<CondBrInst>(ExitBB->getTerminator()))
9018 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
9019 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9020 if (ExitIfTrue == CI->isZero())
9021 continue;
9022 }
9023
9024 ExitLimit EL = computeExitLimit(L, ExitBB, IsOnlyExit, AllowPredicates);
9025
9026 assert((AllowPredicates || EL.Predicates.empty()) &&
9027 "Predicated exit limit when predicates are not allowed!");
9028
9029 // 1. For each exit that can be computed, add an entry to ExitCounts.
9030 // CouldComputeBECount is true only if all exits can be computed.
9031 if (EL.ExactNotTaken != getCouldNotCompute())
9032 ++NumExitCountsComputed;
9033 else
9034 // We couldn't compute an exact value for this exit, so
9035 // we won't be able to compute an exact value for the loop.
9036 CouldComputeBECount = false;
9037 // Remember exit count if either exact or symbolic is known. Because
9038 // Exact always implies symbolic, only check symbolic.
9039 if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
9040 ExitCounts.emplace_back(ExitBB, EL);
9041 else {
9042 assert(EL.ExactNotTaken == getCouldNotCompute() &&
9043 "Exact is known but symbolic isn't?");
9044 ++NumExitCountsNotComputed;
9045 }
9046
9047 // 2. Derive the loop's MaxBECount from each exit's max number of
9048 // non-exiting iterations. Partition the loop exits into two kinds:
9049 // LoopMustExits and LoopMayExits.
9050 //
9051 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
9052 // is a LoopMayExit. If any computable LoopMustExit is found, then
9053 // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
9054 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
9055 // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
9056 // any
9057 // computable EL.ConstantMaxNotTaken.
9058 if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
9059 DT.dominates(ExitBB, Latch)) {
9060 if (!MustExitMaxBECount) {
9061 MustExitMaxBECount = EL.ConstantMaxNotTaken;
9062 MustExitMaxOrZero = EL.MaxOrZero;
9063 } else {
9064 MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
9065 EL.ConstantMaxNotTaken);
9066 }
9067 } else if (MayExitMaxBECount != getCouldNotCompute()) {
9068 if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
9069 MayExitMaxBECount = EL.ConstantMaxNotTaken;
9070 else {
9071 MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
9072 EL.ConstantMaxNotTaken);
9073 }
9074 }
9075 }
9076 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
9077 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
9078 // The loop backedge will be taken the maximum or zero times if there's
9079 // a single exit that must be taken the maximum or zero times.
9080 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
9081
9082 // Remember which SCEVs are used in exit limits for invalidation purposes.
9083 // We only care about non-constant SCEVs here, so we can ignore
9084 // EL.ConstantMaxNotTaken
9085 // and MaxBECount, which must be SCEVConstant.
9086 for (const auto &Pair : ExitCounts) {
9087 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
9088 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
9089 if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
9090 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
9091 {L, AllowPredicates});
9092 }
9093 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
9094 MaxBECount, MaxOrZero);
9095}
9096
9097ScalarEvolution::ExitLimit
9098ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
9099 bool IsOnlyExit, bool AllowPredicates) {
9100 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
9101 // If our exiting block does not dominate the latch, then its connection with
9102 // loop's exit limit may be far from trivial.
9103 const BasicBlock *Latch = L->getLoopLatch();
9104 if (!Latch || !DT.dominates(ExitingBlock, Latch))
9105 return getCouldNotCompute();
9106
9107 Instruction *Term = ExitingBlock->getTerminator();
9108 if (CondBrInst *BI = dyn_cast<CondBrInst>(Term)) {
9109 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9110 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
9111 "It should have one successor in loop and one exit block!");
9112 // Proceed to the next level to examine the exit condition expression.
9113 return computeExitLimitFromCond(L, BI->getCondition(), ExitIfTrue,
9114 /*ControlsOnlyExit=*/IsOnlyExit,
9115 AllowPredicates);
9116 }
9117
9118 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
9119 // For switch, make sure that there is a single exit from the loop.
9120 BasicBlock *Exit = nullptr;
9121 for (auto *SBB : successors(ExitingBlock))
9122 if (!L->contains(SBB)) {
9123 if (Exit) // Multiple exit successors.
9124 return getCouldNotCompute();
9125 Exit = SBB;
9126 }
9127 assert(Exit && "Exiting block must have at least one exit");
9128 return computeExitLimitFromSingleExitSwitch(
9129 L, SI, Exit, /*ControlsOnlyExit=*/IsOnlyExit);
9130 }
9131
9132 return getCouldNotCompute();
9133}
9134
9136 const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9137 bool AllowPredicates) {
9138 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
9139 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
9140 ControlsOnlyExit, AllowPredicates);
9141}
9142
9143std::optional<ScalarEvolution::ExitLimit>
9144ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
9145 bool ExitIfTrue, bool ControlsOnlyExit,
9146 bool AllowPredicates) {
9147 (void)this->L;
9148 (void)this->ExitIfTrue;
9149 (void)this->AllowPredicates;
9150
9151 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9152 this->AllowPredicates == AllowPredicates &&
9153 "Variance in assumed invariant key components!");
9154 auto Itr = TripCountMap.find({ExitCond, ControlsOnlyExit});
9155 if (Itr == TripCountMap.end())
9156 return std::nullopt;
9157 return Itr->second;
9158}
9159
9160void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
9161 bool ExitIfTrue,
9162 bool ControlsOnlyExit,
9163 bool AllowPredicates,
9164 const ExitLimit &EL) {
9165 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9166 this->AllowPredicates == AllowPredicates &&
9167 "Variance in assumed invariant key components!");
9168
9169 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsOnlyExit}, EL});
9170 assert(InsertResult.second && "Expected successful insertion!");
9171 (void)InsertResult;
9172 (void)ExitIfTrue;
9173}
9174
9175ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
9176 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9177 bool ControlsOnlyExit, bool AllowPredicates) {
9178
9179 if (auto MaybeEL = Cache.find(L, ExitCond, ExitIfTrue, ControlsOnlyExit,
9180 AllowPredicates))
9181 return *MaybeEL;
9182
9183 ExitLimit EL = computeExitLimitFromCondImpl(
9184 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates);
9185 Cache.insert(L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates, EL);
9186 return EL;
9187}
9188
9189ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
9190 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9191 bool ControlsOnlyExit, bool AllowPredicates) {
9192 // Handle BinOp conditions (And, Or).
9193 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
9194 Cache, L, ExitCond, ExitIfTrue, AllowPredicates))
9195 return *LimitFromBinOp;
9196
9197 // With an icmp, it may be feasible to compute an exact backedge-taken count.
9198 // Proceed to the next level to examine the icmp.
9199 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
9200 ExitLimit EL =
9201 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsOnlyExit);
9202 if (EL.hasFullInfo() || !AllowPredicates)
9203 return EL;
9204
9205 // Try again, but use SCEV predicates this time.
9206 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue,
9207 ControlsOnlyExit,
9208 /*AllowPredicates=*/true);
9209 }
9210
9211 // Check for a constant condition. These are normally stripped out by
9212 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
9213 // preserve the CFG and is temporarily leaving constant conditions
9214 // in place.
9215 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
9216 if (ExitIfTrue == !CI->getZExtValue())
9217 // The backedge is always taken.
9218 return getCouldNotCompute();
9219 // The backedge is never taken.
9220 return getZero(CI->getType());
9221 }
9222
9223 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
9224 // with a constant step, we can form an equivalent icmp predicate and figure
9225 // out how many iterations will be taken before we exit.
9226 const WithOverflowInst *WO;
9227 const APInt *C;
9228 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
9229 match(WO->getRHS(), m_APInt(C))) {
9230 ConstantRange NWR =
9232 WO->getNoWrapKind());
9233 CmpInst::Predicate Pred;
9234 APInt NewRHSC, Offset;
9235 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
9236 if (!ExitIfTrue)
9237 Pred = ICmpInst::getInversePredicate(Pred);
9238 auto *LHS = getSCEV(WO->getLHS());
9239 if (Offset != 0)
9241 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
9242 ControlsOnlyExit, AllowPredicates);
9243 if (EL.hasAnyInfo())
9244 return EL;
9245 }
9246
9247 // If it's not an integer or pointer comparison then compute it the hard way.
9248 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9249}
9250
9251std::optional<ScalarEvolution::ExitLimit>
9252ScalarEvolution::computeExitLimitFromCondFromBinOp(ExitLimitCacheTy &Cache,
9253 const Loop *L,
9254 Value *ExitCond,
9255 bool ExitIfTrue,
9256 bool AllowPredicates) {
9257 // Check if the controlling expression for this loop is an And or Or.
9258 Value *Op0, *Op1;
9259 bool IsAnd;
9260 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
9261 IsAnd = true;
9262 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
9263 IsAnd = false;
9264 else
9265 return std::nullopt;
9266
9267 // A sub-condition of a non-trivial binop never solely controls the exit,
9268 // whether we exit always depends on both conditions.
9269 ExitLimit EL0 = computeExitLimitFromCondCached(
9270 Cache, L, Op0, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9271 ExitLimit EL1 = computeExitLimitFromCondCached(
9272 Cache, L, Op1, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9273
9274 // EitherMayExit is true in these two cases:
9275 // br (and Op0 Op1), loop, exit
9276 // br (or Op0 Op1), exit, loop
9277 bool EitherMayExit = IsAnd ^ ExitIfTrue;
9278
9279 const SCEV *BECount = getCouldNotCompute();
9280 const SCEV *ConstantMaxBECount = getCouldNotCompute();
9281 const SCEV *SymbolicMaxBECount = getCouldNotCompute();
9282 if (EitherMayExit) {
9283 bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
9284 // Both conditions must be same for the loop to continue executing.
9285 // Choose the less conservative count.
9286 if (EL0.ExactNotTaken != getCouldNotCompute() &&
9287 EL1.ExactNotTaken != getCouldNotCompute()) {
9288 BECount = getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken,
9289 UseSequentialUMin);
9290 }
9291 if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
9292 ConstantMaxBECount = EL1.ConstantMaxNotTaken;
9293 else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
9294 ConstantMaxBECount = EL0.ConstantMaxNotTaken;
9295 else
9296 ConstantMaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
9297 EL1.ConstantMaxNotTaken);
9298 if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
9299 SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
9300 else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
9301 SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
9302 else
9303 SymbolicMaxBECount = getUMinFromMismatchedTypes(
9304 EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
9305 } else {
9306 // Both conditions must be same at the same time for the loop to exit.
9307 // For now, be conservative.
9308 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
9309 BECount = EL0.ExactNotTaken;
9310 }
9311
9312 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
9313 // to be more aggressive when computing BECount than when computing
9314 // ConstantMaxBECount. In these cases it is possible for EL0.ExactNotTaken
9315 // and
9316 // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
9317 // EL1.ConstantMaxNotTaken to not.
9318 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
9319 !isa<SCEVCouldNotCompute>(BECount))
9320 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
9321 if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
9322 SymbolicMaxBECount =
9323 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
9324 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
9325 {ArrayRef(EL0.Predicates), ArrayRef(EL1.Predicates)});
9326}
9327
9328ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9329 const Loop *L, ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9330 bool AllowPredicates) {
9331 // If the condition was exit on true, convert the condition to exit on false
9332 CmpPredicate Pred;
9333 if (!ExitIfTrue)
9334 Pred = ExitCond->getCmpPredicate();
9335 else
9336 Pred = ExitCond->getInverseCmpPredicate();
9337 const ICmpInst::Predicate OriginalPred = Pred;
9338
9339 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
9340 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
9341
9342 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsOnlyExit,
9343 AllowPredicates);
9344 if (EL.hasAnyInfo())
9345 return EL;
9346
9347 auto *ExhaustiveCount =
9348 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9349
9350 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
9351 return ExhaustiveCount;
9352
9353 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
9354 ExitCond->getOperand(1), L, OriginalPred);
9355}
9356ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9357 const Loop *L, CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS,
9358 bool ControlsOnlyExit, bool AllowPredicates) {
9359
9360 // Try to evaluate any dependencies out of the loop.
9361 LHS = getSCEVAtScope(LHS, L);
9362 RHS = getSCEVAtScope(RHS, L);
9363
9364 // At this point, we would like to compute how many iterations of the
9365 // loop the predicate will return true for these inputs.
9366 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
9367 // If there is a loop-invariant, force it into the RHS.
9368 std::swap(LHS, RHS);
9370 }
9371
9372 bool ControllingFiniteLoop = ControlsOnlyExit && loopHasNoAbnormalExits(L) &&
9374 // Simplify the operands before analyzing them.
9375 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0);
9376
9377 // If we have a comparison of a chrec against a constant, try to use value
9378 // ranges to answer this query.
9379 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
9380 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
9381 if (AddRec->getLoop() == L) {
9382 // Form the constant range.
9383 ConstantRange CompRange =
9384 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
9385
9386 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
9387 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
9388 }
9389
9390 // If this loop must exit based on this condition (or execute undefined
9391 // behaviour), see if we can improve wrap flags. This is essentially
9392 // a must execute style proof.
9393 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
9394 // If we can prove the test sequence produced must repeat the same values
9395 // on self-wrap of the IV, then we can infer that IV doesn't self wrap
9396 // because if it did, we'd have an infinite (undefined) loop.
9397 // TODO: We can peel off any functions which are invertible *in L*. Loop
9398 // invariant terms are effectively constants for our purposes here.
9399 SCEVUse InnerLHS = LHS;
9400 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
9401 InnerLHS = ZExt->getOperand();
9402 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS);
9403 AR && !AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
9404 isKnownToBeAPowerOfTwo(AR->getStepRecurrence(*this), /*OrZero=*/true,
9405 /*OrNegative=*/true)) {
9406 auto Flags = AR->getNoWrapFlags();
9407 Flags = setFlags(Flags, SCEV::FlagNW);
9410 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9411 }
9412
9413 // For a slt/ult condition with a positive step, can we prove nsw/nuw?
9414 // From no-self-wrap, this follows trivially from the fact that every
9415 // (un)signed-wrapped, but not self-wrapped value must be LT than the
9416 // last value before (un)signed wrap. Since we know that last value
9417 // didn't exit, nor will any smaller one.
9418 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT) {
9419 auto WrapType = Pred == ICmpInst::ICMP_SLT ? SCEV::FlagNSW : SCEV::FlagNUW;
9420 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9421 AR && AR->getLoop() == L && AR->isAffine() &&
9422 !AR->getNoWrapFlags(WrapType) && AR->hasNoSelfWrap() &&
9423 isKnownPositive(AR->getStepRecurrence(*this))) {
9424 auto Flags = AR->getNoWrapFlags();
9425 Flags = setFlags(Flags, WrapType);
9428 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9429 }
9430 }
9431 }
9432
9433 switch (Pred) {
9434 case ICmpInst::ICMP_NE: { // while (X != Y)
9435 // Convert to: while (X-Y != 0)
9436 if (LHS->getType()->isPointerTy()) {
9439 return LHS;
9440 }
9441 if (RHS->getType()->isPointerTy()) {
9444 return RHS;
9445 }
9446 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit,
9447 AllowPredicates);
9448 if (EL.hasAnyInfo())
9449 return EL;
9450 break;
9451 }
9452 case ICmpInst::ICMP_EQ: { // while (X == Y)
9453 // Convert to: while (X-Y == 0)
9454 if (LHS->getType()->isPointerTy()) {
9457 return LHS;
9458 }
9459 if (RHS->getType()->isPointerTy()) {
9462 return RHS;
9463 }
9464 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
9465 if (EL.hasAnyInfo()) return EL;
9466 break;
9467 }
9468 case ICmpInst::ICMP_SLE:
9469 case ICmpInst::ICMP_ULE:
9470 // Since the loop is finite, an invariant RHS cannot include the boundary
9471 // value, otherwise it would loop forever.
9472 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9473 !isLoopInvariant(RHS, L)) {
9474 // Otherwise, perform the addition in a wider type, to avoid overflow.
9475 // If the LHS is an addrec with the appropriate nowrap flag, the
9476 // extension will be sunk into it and the exit count can be analyzed.
9477 auto *OldType = dyn_cast<IntegerType>(LHS->getType());
9478 if (!OldType)
9479 break;
9480 // Prefer doubling the bitwidth over adding a single bit to make it more
9481 // likely that we use a legal type.
9482 auto *NewType =
9483 Type::getIntNTy(OldType->getContext(), OldType->getBitWidth() * 2);
9484 if (ICmpInst::isSigned(Pred)) {
9485 LHS = getSignExtendExpr(LHS, NewType);
9486 RHS = getSignExtendExpr(RHS, NewType);
9487 } else {
9488 LHS = getZeroExtendExpr(LHS, NewType);
9489 RHS = getZeroExtendExpr(RHS, NewType);
9490 }
9491 }
9493 [[fallthrough]];
9494 case ICmpInst::ICMP_SLT:
9495 case ICmpInst::ICMP_ULT: { // while (X < Y)
9496 bool IsSigned = ICmpInst::isSigned(Pred);
9497 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, /*Invert=*/false,
9498 ControlsOnlyExit, AllowPredicates);
9499 if (EL.hasAnyInfo())
9500 return EL;
9501 break;
9502 }
9503 case ICmpInst::ICMP_SGE:
9504 case ICmpInst::ICMP_UGE:
9505 // Since the loop is finite, an invariant RHS cannot include the boundary
9506 // value, otherwise it would loop forever.
9507 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9508 !isLoopInvariant(RHS, L))
9509 break;
9511 [[fallthrough]];
9512 case ICmpInst::ICMP_SGT:
9513 case ICmpInst::ICMP_UGT: { // while (X > Y)
9514 // "X > Y" is analyzed as the equivalent "~X < ~Y".
9515 bool IsSigned = ICmpInst::isSigned(Pred);
9516 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, /*Invert=*/true,
9517 ControlsOnlyExit, AllowPredicates);
9518 if (EL.hasAnyInfo())
9519 return EL;
9520 break;
9521 }
9522 default:
9523 break;
9524 }
9525
9526 return getCouldNotCompute();
9527}
9528
9529ScalarEvolution::ExitLimit
9530ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
9531 SwitchInst *Switch,
9532 BasicBlock *ExitingBlock,
9533 bool ControlsOnlyExit) {
9534 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
9535
9536 // Give up if the exit is the default dest of a switch.
9537 if (Switch->getDefaultDest() == ExitingBlock)
9538 return getCouldNotCompute();
9539
9540 assert(L->contains(Switch->getDefaultDest()) &&
9541 "Default case must not exit the loop!");
9542 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
9543 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
9544
9545 // while (X != Y) --> while (X-Y != 0)
9546 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit);
9547 if (EL.hasAnyInfo())
9548 return EL;
9549
9550 return getCouldNotCompute();
9551}
9552
9553static ConstantInt *
9555 ScalarEvolution &SE) {
9556 const SCEV *InVal = SE.getConstant(C);
9557 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
9559 "Evaluation of SCEV at constant didn't fold correctly?");
9560 return cast<SCEVConstant>(Val)->getValue();
9561}
9562
9563ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
9564 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
9565 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
9566 if (!RHS)
9567 return getCouldNotCompute();
9568
9569 const BasicBlock *Latch = L->getLoopLatch();
9570 if (!Latch)
9571 return getCouldNotCompute();
9572
9573 const BasicBlock *Predecessor = L->getLoopPredecessor();
9574 if (!Predecessor)
9575 return getCouldNotCompute();
9576
9577 // Return true if V is of the form "LHS `shift_op` <positive constant>".
9578 // Return LHS in OutLHS, shift_op in OutOpCode, and the shift amount in
9579 // OutShiftAmt.
9580 auto MatchPositiveShift = [](Value *V, Value *&OutLHS,
9581 Instruction::BinaryOps &OutOpCode,
9582 unsigned &OutShiftAmt) {
9583 using namespace PatternMatch;
9584
9585 ConstantInt *ShiftAmt;
9586 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9587 OutOpCode = Instruction::LShr;
9588 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9589 OutOpCode = Instruction::AShr;
9590 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9591 OutOpCode = Instruction::Shl;
9592 else
9593 return false;
9594
9595 uint64_t Amt = ShiftAmt->getValue().getLimitedValue();
9596 if (Amt == 0 || Amt >= OutLHS->getType()->getScalarSizeInBits())
9597 return false;
9598 OutShiftAmt = Amt;
9599 return true;
9600 };
9601
9602 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
9603 //
9604 // loop:
9605 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
9606 // %iv.shifted = lshr i32 %iv, <positive constant>
9607 //
9608 // Return true on a successful match. Return the corresponding PHI node (%iv
9609 // above) in PNOut, the opcode of the shift operation in OpCodeOut, and the
9610 // shift amount in ShiftAmtOut.
9611 auto MatchShiftRecurrence = [&](Value *V, PHINode *&PNOut,
9612 Instruction::BinaryOps &OpCodeOut,
9613 unsigned &ShiftAmtOut) {
9614 std::optional<Instruction::BinaryOps> PostShiftOpCode;
9615
9616 {
9618 Value *V;
9619 unsigned Amt;
9620
9621 // If we encounter a shift instruction, "peel off" the shift operation,
9622 // and remember that we did so. Later when we inspect %iv's backedge
9623 // value, we will make sure that the backedge value uses the same
9624 // operation.
9625 //
9626 // Note: the peeled shift operation does not have to be the same
9627 // instruction as the one feeding into the PHI's backedge value. We only
9628 // really care about it being the same *kind* of shift instruction --
9629 // that's all that is required for our later inferences to hold.
9630 if (MatchPositiveShift(LHS, V, OpC, Amt)) {
9631 PostShiftOpCode = OpC;
9632 LHS = V;
9633 }
9634 }
9635
9636 PNOut = dyn_cast<PHINode>(LHS);
9637 if (!PNOut || PNOut->getParent() != L->getHeader())
9638 return false;
9639
9640 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
9641 Value *OpLHS;
9642
9643 return
9644 // The backedge value for the PHI node must be a shift by a positive
9645 // amount
9646 MatchPositiveShift(BEValue, OpLHS, OpCodeOut, ShiftAmtOut) &&
9647
9648 // of the PHI node itself
9649 OpLHS == PNOut &&
9650
9651 // and the kind of shift should be match the kind of shift we peeled
9652 // off, if any.
9653 (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9654 };
9655
9656 PHINode *PN;
9658 unsigned ShiftAmt;
9659 if (!MatchShiftRecurrence(LHS, PN, OpCode, ShiftAmt))
9660 return getCouldNotCompute();
9661
9662 const DataLayout &DL = getDataLayout();
9663
9664 // The key rationale for this optimization is that for some kinds of shift
9665 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
9666 // within a finite number of iterations. If the condition guarding the
9667 // backedge (in the sense that the backedge is taken if the condition is true)
9668 // is false for the value the shift recurrence stabilizes to, then we know
9669 // that the backedge is taken only a finite number of times.
9670
9671 ConstantInt *StableValue = nullptr;
9672 switch (OpCode) {
9673 default:
9674 llvm_unreachable("Impossible case!");
9675
9676 case Instruction::AShr: {
9677 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
9678 // bitwidth(K) iterations.
9679 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
9680 KnownBits Known = computeKnownBits(FirstValue, DL, &AC,
9681 Predecessor->getTerminator(), &DT);
9682 auto *Ty = cast<IntegerType>(RHS->getType());
9683 if (Known.isNonNegative())
9684 StableValue = ConstantInt::get(Ty, 0);
9685 else if (Known.isNegative())
9686 StableValue = ConstantInt::get(Ty, -1, true);
9687 else
9688 return getCouldNotCompute();
9689
9690 break;
9691 }
9692 case Instruction::LShr:
9693 case Instruction::Shl:
9694 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
9695 // stabilize to 0 in at most bitwidth(K) iterations.
9696 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
9697 break;
9698 }
9699
9700 auto *Result =
9701 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
9702 assert(Result->getType()->isIntegerTy(1) &&
9703 "Otherwise cannot be an operand to a branch instruction");
9704
9705 if (Result->isNullValue()) {
9706 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9707 unsigned MaxBTC = BitWidth;
9708
9709 // For right-shift recurrences (lshr/ashr with non-negative start), we can
9710 // compute a tighter max backedge-taken count from the range of the start
9711 // value. After k shifts of ShiftAmt, value = start >> (k * ShiftAmt).
9712 // The value reaches 0 (the stable value) when k * ShiftAmt >=
9713 // activeBits(start), so max BTC = ceil(activeBits(maxStart) / ShiftAmt).
9714 if (OpCode == Instruction::LShr || OpCode == Instruction::AShr) {
9715 Value *StartValue = PN->getIncomingValueForBlock(Predecessor);
9716 const SCEV *StartSCEV = getSCEV(StartValue);
9717 APInt MaxStart = getUnsignedRangeMax(StartSCEV);
9718 if (MaxStart.isStrictlyPositive()) {
9719 unsigned ActiveBits = MaxStart.getActiveBits();
9720 unsigned RangeBTC = divideCeil(ActiveBits, ShiftAmt);
9721 MaxBTC = std::min(MaxBTC, RangeBTC);
9722 }
9723 }
9724
9725 const SCEV *UpperBound =
9727 return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
9728 }
9729
9730 return getCouldNotCompute();
9731}
9732
9733/// Return true if we can constant fold an instruction of the specified type,
9734/// assuming that all operands were constants.
9735static bool canConstantFold(const Instruction *I,
9736 const TargetLibraryInfo *TLI) {
9740 return true;
9741
9742 if (const CallInst *CI = dyn_cast<CallInst>(I))
9743 if (const Function *F = CI->getCalledFunction())
9744 return canConstantFoldCallTo(CI, F, TLI);
9745 return false;
9746}
9747
9748/// Determine whether this instruction can constant evolve within this loop
9749/// assuming its operands can all constant evolve.
9750static bool canConstantEvolve(Instruction *I, const Loop *L,
9751 const TargetLibraryInfo *TLI) {
9752 // An instruction outside of the loop can't be derived from a loop PHI.
9753 if (!L->contains(I)) return false;
9754
9755 if (isa<PHINode>(I)) {
9756 // We don't currently keep track of the control flow needed to evaluate
9757 // PHIs, so we cannot handle PHIs inside of loops.
9758 return L->getHeader() == I->getParent();
9759 }
9760
9761 // If we won't be able to constant fold this expression even if the operands
9762 // are constants, bail early.
9763 return canConstantFold(I, TLI);
9764}
9765
9766/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
9767/// recursing through each instruction operand until reaching a loop header phi.
9768static PHINode *
9771 const TargetLibraryInfo *TLI, unsigned Depth) {
9773 return nullptr;
9774
9775 // Otherwise, we can evaluate this instruction if all of its operands are
9776 // constant or derived from a PHI node themselves.
9777 PHINode *PHI = nullptr;
9778 for (Value *Op : UseInst->operands()) {
9779 if (isa<Constant>(Op)) continue;
9780
9782 if (!OpInst || !canConstantEvolve(OpInst, L, TLI))
9783 return nullptr;
9784
9785 PHINode *P = dyn_cast<PHINode>(OpInst);
9786 if (!P)
9787 // If this operand is already visited, reuse the prior result.
9788 // We may have P != PHI if this is the deepest point at which the
9789 // inconsistent paths meet.
9790 P = PHIMap.lookup(OpInst);
9791 if (!P) {
9792 // Recurse and memoize the results, whether a phi is found or not.
9793 // This recursive call invalidates pointers into PHIMap.
9794 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, TLI, Depth + 1);
9795 PHIMap[OpInst] = P;
9796 }
9797 if (!P)
9798 return nullptr; // Not evolving from PHI
9799 if (PHI && PHI != P)
9800 return nullptr; // Evolving from multiple different PHIs.
9801 PHI = P;
9802 }
9803 // This is a expression evolving from a constant PHI!
9804 return PHI;
9805}
9806
9807/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9808/// in the loop that V is derived from. We allow arbitrary operations along the
9809/// way, but the operands of an operation must either be constants or a value
9810/// derived from a constant PHI. If this expression does not fit with these
9811/// constraints, return null.
9813 const TargetLibraryInfo *TLI) {
9815 if (!I || !canConstantEvolve(I, L, TLI))
9816 return nullptr;
9817
9818 if (PHINode *PN = dyn_cast<PHINode>(I))
9819 return PN;
9820
9821 // Record non-constant instructions contained by the loop.
9823 return getConstantEvolvingPHIOperands(I, L, PHIMap, TLI, 0);
9824}
9825
9826/// EvaluateExpression - Given an expression that passes the
9827/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9828/// in the loop has the value PHIVal. If we can't fold this expression for some
9829/// reason, return null.
9832 const DataLayout &DL,
9833 const TargetLibraryInfo *TLI) {
9834 // Convenient constant check, but redundant for recursive calls.
9835 if (Constant *C = dyn_cast<Constant>(V)) return C;
9837 if (!I) return nullptr;
9838
9839 if (Constant *C = Vals.lookup(I)) return C;
9840
9841 // An instruction inside the loop depends on a value outside the loop that we
9842 // weren't given a mapping for, or a value such as a call inside the loop.
9843 if (!canConstantEvolve(I, L, TLI))
9844 return nullptr;
9845
9846 // An unmapped PHI can be due to a branch or another loop inside this loop,
9847 // or due to this not being the initial iteration through a loop where we
9848 // couldn't compute the evolution of this particular PHI last time.
9849 if (isa<PHINode>(I)) return nullptr;
9850
9851 std::vector<Constant*> Operands(I->getNumOperands());
9852
9853 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9854 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9855 if (!Operand) {
9856 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9857 if (!Operands[i]) return nullptr;
9858 continue;
9859 }
9860 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9861 Vals[Operand] = C;
9862 if (!C) return nullptr;
9863 Operands[i] = C;
9864 }
9865
9866 return ConstantFoldInstOperands(I, Operands, DL, TLI,
9867 /*AllowNonDeterministic=*/false);
9868}
9869
9870
9871// If every incoming value to PN except the one for BB is a specific Constant,
9872// return that, else return nullptr.
9874 Constant *IncomingVal = nullptr;
9875
9876 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9877 if (PN->getIncomingBlock(i) == BB)
9878 continue;
9879
9880 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
9881 if (!CurrentVal)
9882 return nullptr;
9883
9884 if (IncomingVal != CurrentVal) {
9885 if (IncomingVal)
9886 return nullptr;
9887 IncomingVal = CurrentVal;
9888 }
9889 }
9890
9891 return IncomingVal;
9892}
9893
9894/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9895/// in the header of its containing loop, we know the loop executes a
9896/// constant number of times, and the PHI node is just a recurrence
9897/// involving constants, fold it.
9898Constant *
9899ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9900 const APInt &BEs,
9901 const Loop *L) {
9902 auto [I, Inserted] = ConstantEvolutionLoopExitValue.try_emplace(PN);
9903 if (!Inserted)
9904 return I->second;
9905
9907 return nullptr; // Not going to evaluate it.
9908
9909 Constant *&RetVal = I->second;
9910
9911 DenseMap<Instruction *, Constant *> CurrentIterVals;
9912 BasicBlock *Header = L->getHeader();
9913 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9914
9915 BasicBlock *Latch = L->getLoopLatch();
9916 if (!Latch)
9917 return nullptr;
9918
9919 for (PHINode &PHI : Header->phis()) {
9920 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9921 CurrentIterVals[&PHI] = StartCST;
9922 }
9923 if (!CurrentIterVals.count(PN))
9924 return RetVal = nullptr;
9925
9926 Value *BEValue = PN->getIncomingValueForBlock(Latch);
9927
9928 // Execute the loop symbolically to determine the exit value.
9929 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
9930 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
9931
9932 unsigned NumIterations = BEs.getZExtValue(); // must be in range
9933 unsigned IterationNum = 0;
9934 const DataLayout &DL = getDataLayout();
9935 for (; ; ++IterationNum) {
9936 if (IterationNum == NumIterations)
9937 return RetVal = CurrentIterVals[PN]; // Got exit value!
9938
9939 // Compute the value of the PHIs for the next iteration.
9940 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9941 DenseMap<Instruction *, Constant *> NextIterVals;
9942 Constant *NextPHI =
9943 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9944 if (!NextPHI)
9945 return nullptr; // Couldn't evaluate!
9946 NextIterVals[PN] = NextPHI;
9947
9948 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9949
9950 // Also evaluate the other PHI nodes. However, we don't get to stop if we
9951 // cease to be able to evaluate one of them or if they stop evolving,
9952 // because that doesn't necessarily prevent us from computing PN.
9954 for (const auto &I : CurrentIterVals) {
9955 PHINode *PHI = dyn_cast<PHINode>(I.first);
9956 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
9957 PHIsToCompute.emplace_back(PHI, I.second);
9958 }
9959 // We use two distinct loops because EvaluateExpression may invalidate any
9960 // iterators into CurrentIterVals.
9961 for (const auto &I : PHIsToCompute) {
9962 PHINode *PHI = I.first;
9963 Constant *&NextPHI = NextIterVals[PHI];
9964 if (!NextPHI) { // Not already computed.
9965 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9966 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9967 }
9968 if (NextPHI != I.second)
9969 StoppedEvolving = false;
9970 }
9971
9972 // If all entries in CurrentIterVals == NextIterVals then we can stop
9973 // iterating, the loop can't continue to change.
9974 if (StoppedEvolving)
9975 return RetVal = CurrentIterVals[PN];
9976
9977 CurrentIterVals.swap(NextIterVals);
9978 }
9979}
9980
9981const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
9982 Value *Cond,
9983 bool ExitWhen) {
9984 PHINode *PN = getConstantEvolvingPHI(Cond, L, &TLI);
9985 if (!PN) return getCouldNotCompute();
9986
9987 // If the loop is canonicalized, the PHI will have exactly two entries.
9988 // That's the only form we support here.
9989 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
9990
9991 DenseMap<Instruction *, Constant *> CurrentIterVals;
9992 BasicBlock *Header = L->getHeader();
9993 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9994
9995 BasicBlock *Latch = L->getLoopLatch();
9996 assert(Latch && "Should follow from NumIncomingValues == 2!");
9997
9998 for (PHINode &PHI : Header->phis()) {
9999 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
10000 CurrentIterVals[&PHI] = StartCST;
10001 }
10002 if (!CurrentIterVals.count(PN))
10003 return getCouldNotCompute();
10004
10005 // Okay, we find a PHI node that defines the trip count of this loop. Execute
10006 // the loop symbolically to determine when the condition gets a value of
10007 // "ExitWhen".
10008 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
10009 const DataLayout &DL = getDataLayout();
10010 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
10011 auto *CondVal = dyn_cast_or_null<ConstantInt>(
10012 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
10013
10014 // Couldn't symbolically evaluate.
10015 if (!CondVal) return getCouldNotCompute();
10016
10017 if (CondVal->getValue() == uint64_t(ExitWhen)) {
10018 ++NumBruteForceTripCountsComputed;
10019 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
10020 }
10021
10022 // Update all the PHI nodes for the next iteration.
10023 DenseMap<Instruction *, Constant *> NextIterVals;
10024
10025 // Create a list of which PHIs we need to compute. We want to do this before
10026 // calling EvaluateExpression on them because that may invalidate iterators
10027 // into CurrentIterVals.
10028 SmallVector<PHINode *, 8> PHIsToCompute;
10029 for (const auto &I : CurrentIterVals) {
10030 PHINode *PHI = dyn_cast<PHINode>(I.first);
10031 if (!PHI || PHI->getParent() != Header) continue;
10032 PHIsToCompute.push_back(PHI);
10033 }
10034 for (PHINode *PHI : PHIsToCompute) {
10035 Constant *&NextPHI = NextIterVals[PHI];
10036 if (NextPHI) continue; // Already computed!
10037
10038 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
10039 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
10040 }
10041 CurrentIterVals.swap(NextIterVals);
10042 }
10043
10044 // Too many iterations were needed to evaluate.
10045 return getCouldNotCompute();
10046}
10047
10049 if (isa<SCEVConstant>(V))
10050 return V;
10051
10052 auto &Values = ValuesAtScopes[V];
10053 // Check to see if we've folded this expression at this loop before.
10054 for (auto &LS : Values)
10055 if (LS.first == L)
10056 return LS.second ? LS.second : SCEVUse(V);
10057
10058 Values.emplace_back(L, nullptr);
10059
10060 // Otherwise compute it.
10061 SCEVUse C = computeSCEVAtScope(V, L);
10062 for (auto &LS : reverse(ValuesAtScopes[V]))
10063 if (LS.first == L) {
10064 LS.second = C;
10065 // Record the dependency under the bare expression: invalidation walks
10066 // expressions, and any use flags on C do not change which expression
10067 // this is the value at scope of.
10068 if (!isa<SCEVConstant>(C))
10069 ValuesAtScopesUsers[C.getPointer()].push_back({L, V});
10070 break;
10071 }
10072 return C;
10073}
10074
10076 const BasicBlock *ExitingBlock) {
10077 SCEVUse ExitValue = getSCEVAtScope(V, L->getParentLoop());
10078 if (!isLoopInvariant(ExitValue, L)) {
10079 // If we failed to evaluate it in the outer scope, try to evaluate an
10080 // addrec for the specific exit.
10081 // TODO: Generalize this to other expressions.
10082 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
10083 if (!isa<SCEVCouldNotCompute>(ExitCount))
10084 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V))
10085 if (AddRec->getLoop() == L)
10086 ExitValue = AddRec->evaluateAtIteration(ExitCount, *this);
10087 }
10088 return ExitValue;
10089}
10090
10091/// This builds up a Constant using the ConstantExpr interface. That way, we
10092/// will return Constants for objects which aren't represented by a
10093/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
10094/// Returns NULL if the SCEV isn't representable as a Constant.
10096 switch (V->getSCEVType()) {
10097 case scCouldNotCompute:
10098 case scAddRecExpr:
10099 case scVScale:
10100 return nullptr;
10101 case scConstant:
10102 return cast<SCEVConstant>(V)->getValue();
10103 case scUnknown:
10105 case scPtrToAddr: {
10107 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
10108 return ConstantExpr::getPtrToAddr(CastOp, P2I->getType());
10109
10110 return nullptr;
10111 }
10112 case scTruncate: {
10114 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
10115 return ConstantExpr::getTrunc(CastOp, ST->getType());
10116 return nullptr;
10117 }
10118 case scAddExpr: {
10119 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
10120 Constant *C = nullptr;
10121 for (const SCEV *Op : SA->operands()) {
10123 if (!OpC)
10124 return nullptr;
10125 if (!C) {
10126 C = OpC;
10127 continue;
10128 }
10129 assert(!C->getType()->isPointerTy() &&
10130 "Can only have one pointer, and it must be last");
10131 if (OpC->getType()->isPointerTy()) {
10132 // The offsets have been converted to bytes. We can add bytes using
10133 // an i8 GEP.
10134 C = ConstantExpr::getPtrAdd(OpC, C);
10135 } else {
10136 C = ConstantExpr::getAdd(C, OpC);
10137 }
10138 }
10139 return C;
10140 }
10141 case scMulExpr:
10142 case scSignExtend:
10143 case scZeroExtend:
10144 case scUDivExpr:
10145 case scSMaxExpr:
10146 case scUMaxExpr:
10147 case scSMinExpr:
10148 case scUMinExpr:
10150 return nullptr;
10151 }
10152 llvm_unreachable("Unknown SCEV kind!");
10153}
10154
10155const SCEV *ScalarEvolution::getWithOperands(const SCEV *S,
10156 SmallVectorImpl<SCEVUse> &NewOps) {
10157 switch (S->getSCEVType()) {
10158 case scTruncate:
10159 case scZeroExtend:
10160 case scSignExtend:
10161 case scPtrToAddr:
10162 return getCastExpr(S->getSCEVType(), NewOps[0], S->getType());
10163 case scAddRecExpr: {
10164 auto *AddRec = cast<SCEVAddRecExpr>(S);
10165 return getAddRecExpr(NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags());
10166 }
10167 case scAddExpr:
10168 return getAddExpr(NewOps, cast<SCEVAddExpr>(S)->getNoWrapFlags());
10169 case scMulExpr:
10170 return getMulExpr(NewOps, cast<SCEVMulExpr>(S)->getNoWrapFlags());
10171 case scUDivExpr:
10172 return getUDivExpr(NewOps[0], NewOps[1]);
10173 case scUMaxExpr:
10174 case scSMaxExpr:
10175 case scUMinExpr:
10176 case scSMinExpr:
10177 return getMinMaxExpr(S->getSCEVType(), NewOps);
10179 return getSequentialMinMaxExpr(S->getSCEVType(), NewOps);
10180 case scConstant:
10181 case scVScale:
10182 case scUnknown:
10183 return S;
10184 case scCouldNotCompute:
10185 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10186 }
10187 llvm_unreachable("Unknown SCEV kind!");
10188}
10189
10190SCEVUse ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
10191 switch (V->getSCEVType()) {
10192 case scConstant:
10193 case scVScale:
10194 return V;
10195 case scAddRecExpr: {
10196 // If this is a loop recurrence for a loop that does not contain L, then we
10197 // are dealing with the final value computed by the loop.
10198 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(V);
10199 // First, attempt to evaluate each operand.
10200 // Avoid performing the look-up in the common case where the specified
10201 // expression has no loop-variant portions.
10202 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
10203 SCEVUse OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
10204 if (OpAtScope == AddRec->getOperand(i))
10205 continue;
10206
10207 // Okay, at least one of these operands is loop variant but might be
10208 // foldable. Build a new instance of the folded commutative expression.
10210 NewOps.reserve(AddRec->getNumOperands());
10211 append_range(NewOps, AddRec->operands().take_front(i));
10212 NewOps.push_back(OpAtScope);
10213 for (++i; i != e; ++i)
10214 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
10215
10216 const SCEV *FoldedRec = getAddRecExpr(
10217 NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags(SCEV::FlagNW));
10218 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
10219 // The addrec may be folded to a nonrecurrence, for example, if the
10220 // induction variable is multiplied by zero after constant folding. Go
10221 // ahead and return the folded value.
10222 if (!AddRec)
10223 return FoldedRec;
10224 break;
10225 }
10226
10227 // If the scope is outside the addrec's loop, evaluate it by using the
10228 // loop exit value of the addrec.
10229 if (!AddRec->getLoop()->contains(L)) {
10230 SCEVUse ExitValue = AddRec->getExitValue(*this);
10231 if (isa<SCEVCouldNotCompute>(ExitValue))
10232 return AddRec;
10233 return ExitValue;
10234 }
10235
10236 return AddRec;
10237 }
10238 case scTruncate:
10239 case scZeroExtend:
10240 case scSignExtend:
10241 case scPtrToAddr:
10242 case scAddExpr:
10243 case scMulExpr:
10244 case scUDivExpr:
10245 case scUMaxExpr:
10246 case scSMaxExpr:
10247 case scUMinExpr:
10248 case scSMinExpr:
10249 case scSequentialUMinExpr: {
10250 ArrayRef<SCEVUse> Ops = V->operands();
10251 // Avoid performing the look-up in the common case where the specified
10252 // expression has no loop-variant portions.
10253 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
10254 SCEVUse OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10255 if (OpAtScope != Ops[i].getPointer()) {
10256 // Okay, at least one of these operands is loop variant but might be
10257 // foldable. Build a new instance of the folded commutative expression.
10259 NewOps.reserve(Ops.size());
10260 append_range(NewOps, Ops.take_front(i));
10261 NewOps.push_back(OpAtScope);
10262
10263 for (++i; i != e; ++i) {
10264 OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10265 NewOps.push_back(OpAtScope);
10266 }
10267
10268 return getWithOperands(V, NewOps);
10269 }
10270 }
10271 // If we got here, all operands are loop invariant.
10272 return V;
10273 }
10274 case scUnknown: {
10275 // If this instruction is evolved from a constant-evolving PHI, compute the
10276 // exit value from the loop without using SCEVs.
10277 const SCEVUnknown *SU = cast<SCEVUnknown>(V);
10279 if (!I)
10280 return V; // This is some other type of SCEVUnknown, just return it.
10281
10282 if (PHINode *PN = dyn_cast<PHINode>(I)) {
10283 const Loop *CurrLoop = this->LI[I->getParent()];
10284 // Looking for loop exit value.
10285 if (CurrLoop && CurrLoop->getParentLoop() == L &&
10286 PN->getParent() == CurrLoop->getHeader()) {
10287 // Okay, there is no closed form solution for the PHI node. Check
10288 // to see if the loop that contains it has a known backedge-taken
10289 // count. If so, we may be able to force computation of the exit
10290 // value.
10291 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
10292 // This trivial case can show up in some degenerate cases where
10293 // the incoming IR has not yet been fully simplified.
10294 if (BackedgeTakenCount->isZero()) {
10295 Value *InitValue = nullptr;
10296 bool MultipleInitValues = false;
10297 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
10298 if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
10299 if (!InitValue)
10300 InitValue = PN->getIncomingValue(i);
10301 else if (InitValue != PN->getIncomingValue(i)) {
10302 MultipleInitValues = true;
10303 break;
10304 }
10305 }
10306 }
10307 if (!MultipleInitValues && InitValue)
10308 return getSCEV(InitValue);
10309 }
10310 // Do we have a loop invariant value flowing around the backedge
10311 // for a loop which must execute the backedge?
10312 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
10313 isKnownNonZero(BackedgeTakenCount) &&
10314 PN->getNumIncomingValues() == 2) {
10315
10316 unsigned InLoopPred =
10317 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
10318 Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
10319 if (CurrLoop->isLoopInvariant(BackedgeVal))
10320 return getSCEV(BackedgeVal);
10321 }
10322 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
10323 // Okay, we know how many times the containing loop executes. If
10324 // this is a constant evolving PHI node, get the final value at
10325 // the specified iteration number.
10326 Constant *RV =
10327 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
10328 if (RV)
10329 return getSCEV(RV);
10330 }
10331 }
10332 }
10333
10334 // Okay, this is an expression that we cannot symbolically evaluate
10335 // into a SCEV. Check to see if it's possible to symbolically evaluate
10336 // the arguments into constants, and if so, try to constant propagate the
10337 // result. This is particularly useful for computing loop exit values.
10338 if (!canConstantFold(I, &TLI))
10339 return V; // This is some other type of SCEVUnknown, just return it.
10340
10341 SmallVector<Constant *, 4> Operands;
10342 Operands.reserve(I->getNumOperands());
10343 bool MadeImprovement = false;
10344 for (Value *Op : I->operands()) {
10345 if (Constant *C = dyn_cast<Constant>(Op)) {
10346 Operands.push_back(C);
10347 continue;
10348 }
10349
10350 // If any of the operands is non-constant and if they are
10351 // non-integer and non-pointer, don't even try to analyze them
10352 // with scev techniques.
10353 if (!isSCEVable(Op->getType()))
10354 return V;
10355
10356 const SCEV *OrigV = getSCEV(Op);
10357 const SCEV *OpV = getSCEVAtScope(OrigV, L);
10358 MadeImprovement |= OrigV != OpV;
10359
10361 if (!C)
10362 return V;
10363 assert(C->getType() == Op->getType() && "Type mismatch");
10364 Operands.push_back(C);
10365 }
10366
10367 // Check to see if getSCEVAtScope actually made an improvement.
10368 if (!MadeImprovement)
10369 return V; // This is some other type of SCEVUnknown, just return it.
10370
10371 Constant *C = nullptr;
10372 const DataLayout &DL = getDataLayout();
10373 C = ConstantFoldInstOperands(I, Operands, DL, &TLI,
10374 /*AllowNonDeterministic=*/false);
10375 if (!C)
10376 return V;
10377 return getSCEV(C);
10378 }
10379 case scCouldNotCompute:
10380 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10381 }
10382 llvm_unreachable("Unknown SCEV type!");
10383}
10384
10386 return getSCEVAtScope(getSCEV(V), L);
10387}
10388
10389const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
10391 return stripInjectiveFunctions(ZExt->getOperand());
10393 return stripInjectiveFunctions(SExt->getOperand());
10394 return S;
10395}
10396
10397/// Finds the minimum unsigned root of the following equation:
10398///
10399/// A * X = B (mod N)
10400///
10401/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
10402/// A and B isn't important.
10403///
10404/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
10405static const SCEV *
10408 ScalarEvolution &SE, const Loop *L) {
10409 uint32_t BW = A.getBitWidth();
10410 assert(BW == SE.getTypeSizeInBits(B->getType()));
10411 assert(A != 0 && "A must be non-zero.");
10412
10413 // 1. D = gcd(A, N)
10414 //
10415 // The gcd of A and N may have only one prime factor: 2. The number of
10416 // trailing zeros in A is its multiplicity
10417 uint32_t Mult2 = A.countr_zero();
10418 // D = 2^Mult2
10419
10420 // 2. Check if B is divisible by D.
10421 //
10422 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
10423 // is not less than multiplicity of this prime factor for D.
10424 unsigned MinTZ = SE.getMinTrailingZeros(B);
10425 // Try again with the terminator of the loop predecessor for context-specific
10426 // result, if MinTZ s too small.
10427 if (MinTZ < Mult2 && L->getLoopPredecessor())
10428 MinTZ = SE.getMinTrailingZeros(B, L->getLoopPredecessor()->getTerminator());
10429 if (MinTZ < Mult2) {
10430 // Check if we can prove there's no remainder using URem.
10431 const SCEV *URem =
10432 SE.getURemExpr(B, SE.getConstant(APInt::getOneBitSet(BW, Mult2)));
10433 const SCEV *Zero = SE.getZero(B->getType());
10434 if (!SE.isKnownPredicate(CmpInst::ICMP_EQ, URem, Zero)) {
10435 // Try to add a predicate ensuring B is a multiple of 1 << Mult2.
10436 if (!Predicates)
10437 return SE.getCouldNotCompute();
10438
10439 // Avoid adding a predicate that is known to be false.
10440 if (SE.isKnownPredicate(CmpInst::ICMP_NE, URem, Zero))
10441 return SE.getCouldNotCompute();
10442 Predicates->push_back(SE.getEqualPredicate(URem, Zero));
10443 }
10444 }
10445
10446 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
10447 // modulo (N / D).
10448 //
10449 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
10450 // (N / D) in general. The inverse itself always fits into BW bits, though,
10451 // so we immediately truncate it.
10452 APInt AD = A.lshr(Mult2).trunc(BW - Mult2); // AD = A / D
10453 APInt I = AD.multiplicativeInverse().zext(BW);
10454
10455 // 4. Compute the minimum unsigned root of the equation:
10456 // I * (B / D) mod (N / D)
10457 // To simplify the computation, we factor out the divide by D:
10458 // (I * B mod N) / D
10459 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
10460 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
10461}
10462
10463/// For a given quadratic addrec, generate coefficients of the corresponding
10464/// quadratic equation, multiplied by a common value to ensure that they are
10465/// integers.
10466/// The returned value is a tuple { A, B, C, M, BitWidth }, where
10467/// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
10468/// were multiplied by, and BitWidth is the bit width of the original addrec
10469/// coefficients.
10470/// This function returns std::nullopt if the addrec coefficients are not
10471/// compile- time constants.
10472static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
10474 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
10475 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
10476 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
10477 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
10478 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
10479 << *AddRec << '\n');
10480
10481 // We currently can only solve this if the coefficients are constants.
10482 if (!LC || !MC || !NC) {
10483 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
10484 return std::nullopt;
10485 }
10486
10487 APInt L = LC->getAPInt();
10488 APInt M = MC->getAPInt();
10489 APInt N = NC->getAPInt();
10490 assert(!N.isZero() && "This is not a quadratic addrec");
10491
10492 unsigned BitWidth = LC->getAPInt().getBitWidth();
10493 unsigned NewWidth = BitWidth + 1;
10494 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
10495 << BitWidth << '\n');
10496 // The sign-extension (as opposed to a zero-extension) here matches the
10497 // extension used in SolveQuadraticEquationWrap (with the same motivation).
10498 N = N.sext(NewWidth);
10499 M = M.sext(NewWidth);
10500 L = L.sext(NewWidth);
10501
10502 // The increments are M, M+N, M+2N, ..., so the accumulated values are
10503 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
10504 // L+M, L+2M+N, L+3M+3N, ...
10505 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
10506 //
10507 // The equation Acc = 0 is then
10508 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
10509 // In a quadratic form it becomes:
10510 // N n^2 + (2M-N) n + 2L = 0.
10511
10512 APInt A = N;
10513 APInt B = 2 * M - A;
10514 APInt C = 2 * L;
10515 APInt T = APInt(NewWidth, 2);
10516 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
10517 << "x + " << C << ", coeff bw: " << NewWidth
10518 << ", multiplied by " << T << '\n');
10519 return std::make_tuple(A, B, C, T, BitWidth);
10520}
10521
10522/// Helper function to compare optional APInts:
10523/// (a) if X and Y both exist, return min(X, Y),
10524/// (b) if neither X nor Y exist, return std::nullopt,
10525/// (c) if exactly one of X and Y exists, return that value.
10526static std::optional<APInt> MinOptional(std::optional<APInt> X,
10527 std::optional<APInt> Y) {
10528 if (X && Y) {
10529 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
10530 APInt XW = X->sext(W);
10531 APInt YW = Y->sext(W);
10532 return XW.slt(YW) ? *X : *Y;
10533 }
10534 if (!X && !Y)
10535 return std::nullopt;
10536 return X ? *X : *Y;
10537}
10538
10539/// Helper function to truncate an optional APInt to a given BitWidth.
10540/// When solving addrec-related equations, it is preferable to return a value
10541/// that has the same bit width as the original addrec's coefficients. If the
10542/// solution fits in the original bit width, truncate it (except for i1).
10543/// Returning a value of a different bit width may inhibit some optimizations.
10544///
10545/// In general, a solution to a quadratic equation generated from an addrec
10546/// may require BW+1 bits, where BW is the bit width of the addrec's
10547/// coefficients. The reason is that the coefficients of the quadratic
10548/// equation are BW+1 bits wide (to avoid truncation when converting from
10549/// the addrec to the equation).
10550static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
10551 unsigned BitWidth) {
10552 if (!X)
10553 return std::nullopt;
10554 unsigned W = X->getBitWidth();
10556 return X->trunc(BitWidth);
10557 return X;
10558}
10559
10560/// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
10561/// iterations. The values L, M, N are assumed to be signed, and they
10562/// should all have the same bit widths.
10563/// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
10564/// where BW is the bit width of the addrec's coefficients.
10565/// If the calculated value is a BW-bit integer (for BW > 1), it will be
10566/// returned as such, otherwise the bit width of the returned value may
10567/// be greater than BW.
10568///
10569/// This function returns std::nullopt if
10570/// (a) the addrec coefficients are not constant, or
10571/// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
10572/// like x^2 = 5, no integer solutions exist, in other cases an integer
10573/// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
10574static std::optional<APInt>
10576 APInt A, B, C, M;
10577 unsigned BitWidth;
10578 auto T = GetQuadraticEquation(AddRec);
10579 if (!T)
10580 return std::nullopt;
10581
10582 std::tie(A, B, C, M, BitWidth) = *T;
10583 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
10584 std::optional<APInt> X =
10586 if (!X)
10587 return std::nullopt;
10588
10589 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
10590 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
10591 if (!V->isZero())
10592 return std::nullopt;
10593
10594 return TruncIfPossible(X, BitWidth);
10595}
10596
10597/// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
10598/// iterations. The values M, N are assumed to be signed, and they
10599/// should all have the same bit widths.
10600/// Find the least n such that c(n) does not belong to the given range,
10601/// while c(n-1) does.
10602///
10603/// This function returns std::nullopt if
10604/// (a) the addrec coefficients are not constant, or
10605/// (b) SolveQuadraticEquationWrap was unable to find a solution for the
10606/// bounds of the range.
10607static std::optional<APInt>
10609 const ConstantRange &Range, ScalarEvolution &SE) {
10610 assert(AddRec->getOperand(0)->isZero() &&
10611 "Starting value of addrec should be 0");
10612 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
10613 << Range << ", addrec " << *AddRec << '\n');
10614 // This case is handled in getNumIterationsInRange. Here we can assume that
10615 // we start in the range.
10616 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
10617 "Addrec's initial value should be in range");
10618
10619 APInt A, B, C, M;
10620 unsigned BitWidth;
10621 auto T = GetQuadraticEquation(AddRec);
10622 if (!T)
10623 return std::nullopt;
10624
10625 // Be careful about the return value: there can be two reasons for not
10626 // returning an actual number. First, if no solutions to the equations
10627 // were found, and second, if the solutions don't leave the given range.
10628 // The first case means that the actual solution is "unknown", the second
10629 // means that it's known, but not valid. If the solution is unknown, we
10630 // cannot make any conclusions.
10631 // Return a pair: the optional solution and a flag indicating if the
10632 // solution was found.
10633 auto SolveForBoundary =
10634 [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
10635 // Solve for signed overflow and unsigned overflow, pick the lower
10636 // solution.
10637 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
10638 << Bound << " (before multiplying by " << M << ")\n");
10639 Bound *= M; // The quadratic equation multiplier.
10640
10641 std::optional<APInt> SO;
10642 if (BitWidth > 1) {
10643 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10644 "signed overflow\n");
10646 }
10647 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10648 "unsigned overflow\n");
10649 std::optional<APInt> UO =
10651
10652 auto LeavesRange = [&] (const APInt &X) {
10653 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
10654 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
10655 if (Range.contains(V0->getValue()))
10656 return false;
10657 // X should be at least 1, so X-1 is non-negative.
10658 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
10660 if (Range.contains(V1->getValue()))
10661 return true;
10662 return false;
10663 };
10664
10665 // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
10666 // can be a solution, but the function failed to find it. We cannot treat it
10667 // as "no solution".
10668 if (!SO || !UO)
10669 return {std::nullopt, false};
10670
10671 // Check the smaller value first to see if it leaves the range.
10672 // At this point, both SO and UO must have values.
10673 std::optional<APInt> Min = MinOptional(SO, UO);
10674 if (LeavesRange(*Min))
10675 return { Min, true };
10676 std::optional<APInt> Max = Min == SO ? UO : SO;
10677 if (LeavesRange(*Max))
10678 return { Max, true };
10679
10680 // Solutions were found, but were eliminated, hence the "true".
10681 return {std::nullopt, true};
10682 };
10683
10684 std::tie(A, B, C, M, BitWidth) = *T;
10685 // Lower bound is inclusive, subtract 1 to represent the exiting value.
10686 APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
10687 APInt Upper = Range.getUpper().sext(A.getBitWidth());
10688 auto SL = SolveForBoundary(Lower);
10689 auto SU = SolveForBoundary(Upper);
10690 // If any of the solutions was unknown, no meaninigful conclusions can
10691 // be made.
10692 if (!SL.second || !SU.second)
10693 return std::nullopt;
10694
10695 // Claim: The correct solution is not some value between Min and Max.
10696 //
10697 // Justification: Assuming that Min and Max are different values, one of
10698 // them is when the first signed overflow happens, the other is when the
10699 // first unsigned overflow happens. Crossing the range boundary is only
10700 // possible via an overflow (treating 0 as a special case of it, modeling
10701 // an overflow as crossing k*2^W for some k).
10702 //
10703 // The interesting case here is when Min was eliminated as an invalid
10704 // solution, but Max was not. The argument is that if there was another
10705 // overflow between Min and Max, it would also have been eliminated if
10706 // it was considered.
10707 //
10708 // For a given boundary, it is possible to have two overflows of the same
10709 // type (signed/unsigned) without having the other type in between: this
10710 // can happen when the vertex of the parabola is between the iterations
10711 // corresponding to the overflows. This is only possible when the two
10712 // overflows cross k*2^W for the same k. In such case, if the second one
10713 // left the range (and was the first one to do so), the first overflow
10714 // would have to enter the range, which would mean that either we had left
10715 // the range before or that we started outside of it. Both of these cases
10716 // are contradictions.
10717 //
10718 // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
10719 // solution is not some value between the Max for this boundary and the
10720 // Min of the other boundary.
10721 //
10722 // Justification: Assume that we had such Max_A and Min_B corresponding
10723 // to range boundaries A and B and such that Max_A < Min_B. If there was
10724 // a solution between Max_A and Min_B, it would have to be caused by an
10725 // overflow corresponding to either A or B. It cannot correspond to B,
10726 // since Min_B is the first occurrence of such an overflow. If it
10727 // corresponded to A, it would have to be either a signed or an unsigned
10728 // overflow that is larger than both eliminated overflows for A. But
10729 // between the eliminated overflows and this overflow, the values would
10730 // cover the entire value space, thus crossing the other boundary, which
10731 // is a contradiction.
10732
10733 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
10734}
10735
10736ScalarEvolution::ExitLimit ScalarEvolution::howFarToZero(const SCEV *V,
10737 const Loop *L,
10738 bool ControlsOnlyExit,
10739 bool AllowPredicates) {
10740
10741 // This is only used for loops with a "x != y" exit test. The exit condition
10742 // is now expressed as a single expression, V = x-y. So the exit test is
10743 // effectively V != 0. We know and take advantage of the fact that this
10744 // expression only being used in a comparison by zero context.
10745
10747 // If the value is a constant
10748 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10749 // If the value is already zero, the branch will execute zero times.
10750 if (C->getValue()->isZero()) return C;
10751 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10752 }
10753
10754 const SCEVAddRecExpr *AddRec =
10755 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
10756
10757 if (!AddRec && AllowPredicates)
10758 // Try to make this an AddRec using runtime tests, in the first X
10759 // iterations of this loop, where X is the SCEV expression found by the
10760 // algorithm below.
10761 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
10762
10763 if (!AddRec || AddRec->getLoop() != L)
10764 return getCouldNotCompute();
10765
10766 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
10767 // the quadratic equation to solve it.
10768 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
10769 // We can only use this value if the chrec ends up with an exact zero
10770 // value at this index. When solving for "X*X != 5", for example, we
10771 // should not accept a root of 2.
10772 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
10773 const auto *R = cast<SCEVConstant>(getConstant(*S));
10774 return ExitLimit(R, R, R, false, Predicates);
10775 }
10776 return getCouldNotCompute();
10777 }
10778
10779 // Otherwise we can only handle this if it is affine.
10780 if (!AddRec->isAffine())
10781 return getCouldNotCompute();
10782
10783 // If this is an affine expression, the execution count of this branch is
10784 // the minimum unsigned root of the following equation:
10785 //
10786 // Start + Step*N = 0 (mod 2^BW)
10787 //
10788 // equivalent to:
10789 //
10790 // Step*N = -Start (mod 2^BW)
10791 //
10792 // where BW is the common bit width of Start and Step.
10793
10794 // Get the initial value for the loop.
10795 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
10796 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
10797
10798 if (!isLoopInvariant(Step, L))
10799 return getCouldNotCompute();
10800
10801 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
10802 // Specialize step for this loop so we get context sensitive facts below.
10803 const SCEV *StepWLG = applyLoopGuards(Step, Guards);
10804
10805 // For positive steps (counting up until unsigned overflow):
10806 // N = -Start/Step (as unsigned)
10807 // For negative steps (counting down to zero):
10808 // N = Start/-Step
10809 // First compute the unsigned distance from zero in the direction of Step.
10810 bool CountDown = isKnownNegative(StepWLG);
10811 if (!CountDown && !isKnownNonNegative(StepWLG))
10812 return getCouldNotCompute();
10813
10814 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
10815 // Handle unitary steps, which cannot wraparound.
10816 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10817 // N = Distance (as unsigned)
10818
10819 if (match(Step, m_CombineOr(m_scev_One(), m_scev_AllOnes()))) {
10820 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, Guards));
10821 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
10822
10823 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10824 // we end up with a loop whose backedge-taken count is n - 1. Detect this
10825 // case, and see if we can improve the bound.
10826 //
10827 // Explicitly handling this here is necessary because getUnsignedRange
10828 // isn't context-sensitive; it doesn't know that we only care about the
10829 // range inside the loop.
10830 const SCEV *Zero = getZero(Distance->getType());
10831 const SCEV *One = getOne(Distance->getType());
10832 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
10833 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
10834 // If Distance + 1 doesn't overflow, we can compute the maximum distance
10835 // as "unsigned_max(Distance + 1) - 1". Also apply the loop guards to
10836 // Distance + 1; the range of Distance itself may be a wrapped set even
10837 // when the guards bound Distance + 1 tightly.
10838 APInt Max = APIntOps::umin(
10839 getUnsignedRangeMax(applyLoopGuards(DistancePlusOne, Guards)),
10840 getUnsignedRangeMax(DistancePlusOne));
10841 MaxBECount = APIntOps::umin(MaxBECount, Max - 1);
10842 }
10843 return ExitLimit(Distance, getConstant(MaxBECount), Distance, false,
10844 Predicates);
10845 }
10846
10847 // If the condition controls loop exit (the loop exits only if the expression
10848 // is true) and the addition is no-wrap we can use unsigned divide to
10849 // compute the backedge count. In this case, the step may not divide the
10850 // distance, but we don't care because if the condition is "missed" the loop
10851 // will have undefined behavior due to wrapping.
10852 if (ControlsOnlyExit && AddRec->hasNoSelfWrap() &&
10853 loopHasNoAbnormalExits(AddRec->getLoop())) {
10854
10855 // If the stride is zero and the start is non-zero, the loop must be
10856 // infinite. In C++, most loops are finite by assumption, in which case the
10857 // step being zero implies UB must execute if the loop is entered.
10858 if (!(loopIsFiniteByAssumption(L) && isKnownNonZero(Start)) &&
10859 !isKnownNonZero(StepWLG))
10860 return getCouldNotCompute();
10861
10862 const SCEV *Exact =
10863 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10864 const SCEV *ConstantMax = getCouldNotCompute();
10865 if (Exact != getCouldNotCompute()) {
10866 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, Guards));
10867 ConstantMax =
10869 }
10870 const SCEV *SymbolicMax =
10871 isa<SCEVCouldNotCompute>(Exact) ? ConstantMax : Exact;
10872 return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
10873 }
10874
10875 // Solve the general equation.
10876 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
10877 if (!StepC || StepC->getValue()->isZero())
10878 return getCouldNotCompute();
10879 const SCEV *E = SolveLinEquationWithOverflow(
10880 StepC->getAPInt(), getNegativeSCEV(Start),
10881 AllowPredicates ? &Predicates : nullptr, *this, L);
10882
10883 const SCEV *M = E;
10884 if (E != getCouldNotCompute()) {
10885 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, Guards));
10886 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
10887 }
10888 auto *S = isa<SCEVCouldNotCompute>(E) ? M : E;
10889 return ExitLimit(E, M, S, false, Predicates);
10890}
10891
10892ScalarEvolution::ExitLimit
10893ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10894 // Loops that look like: while (X == 0) are very strange indeed. We don't
10895 // handle them yet except for the trivial case. This could be expanded in the
10896 // future as needed.
10897
10898 // If the value is a constant, check to see if it is known to be non-zero
10899 // already. If so, the backedge will execute zero times.
10900 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10901 if (!C->getValue()->isZero())
10902 return getZero(C->getType());
10903 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10904 }
10905
10906 // We could implement others, but I really doubt anyone writes loops like
10907 // this, and if they did, they would already be constant folded.
10908 return getCouldNotCompute();
10909}
10910
10911std::pair<const BasicBlock *, const BasicBlock *>
10912ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10913 const {
10914 // If the block has a unique predecessor, then there is no path from the
10915 // predecessor to the block that does not go through the direct edge
10916 // from the predecessor to the block.
10917 if (const BasicBlock *Pred = BB->getSinglePredecessor())
10918 return {Pred, BB};
10919
10920 // A loop's header is defined to be a block that dominates the loop.
10921 // If the header has a unique predecessor outside the loop, it must be
10922 // a block that has exactly one successor that can reach the loop.
10923 if (const Loop *L = LI.getLoopFor(BB))
10924 return {L->getLoopPredecessor(), L->getHeader()};
10925
10926 return {nullptr, BB};
10927}
10928
10929/// SCEV structural equivalence is usually sufficient for testing whether two
10930/// expressions are equal, however for the purposes of looking for a condition
10931/// guarding a loop, it can be useful to be a little more general, since a
10932/// front-end may have replicated the controlling expression.
10933static bool HasSameValue(const SCEV *A, const SCEV *B) {
10934 // Quick check to see if they are the same SCEV.
10935 if (A == B) return true;
10936
10937 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10938 // Not all instructions that are "identical" compute the same value. For
10939 // instance, two distinct alloca instructions allocating the same type are
10940 // identical and do not read memory; but compute distinct values.
10941 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
10942 };
10943
10944 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10945 // two different instructions with the same value. Check for this case.
10946 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
10947 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
10948 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
10949 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
10950 if (ComputesEqualValues(AI, BI))
10951 return true;
10952
10953 // Otherwise assume they may have a different value.
10954 return false;
10955}
10956
10957static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS) {
10958 const SCEV *Op0, *Op1;
10959 if (!match(S, m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))))
10960 return false;
10961 if (match(Op0, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10962 LHS = Op1;
10963 return true;
10964 }
10965 if (match(Op1, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10966 LHS = Op0;
10967 return true;
10968 }
10969 return false;
10970}
10971
10973 SCEVUse &RHS, unsigned Depth) {
10974 bool Changed = false;
10975 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
10976 // '0 != 0'.
10977 auto TrivialCase = [&](bool TriviallyTrue) {
10979 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
10980 return true;
10981 };
10982 // If we hit the max recursion limit bail out.
10983 if (Depth >= 3)
10984 return false;
10985
10986 const SCEV *NewLHS, *NewRHS;
10987 if (match(LHS, m_scev_c_Mul(m_SCEV(NewLHS), m_SCEVVScale())) &&
10988 match(RHS, m_scev_c_Mul(m_SCEV(NewRHS), m_SCEVVScale()))) {
10989 const SCEVMulExpr *LMul = cast<SCEVMulExpr>(LHS);
10990 const SCEVMulExpr *RMul = cast<SCEVMulExpr>(RHS);
10991
10992 // (X * vscale) pred (Y * vscale) ==> X pred Y
10993 // when both multiples are NSW.
10994 // (X * vscale) uicmp/eq/ne (Y * vscale) ==> X uicmp/eq/ne Y
10995 // when both multiples are NUW.
10996 if ((LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap()) ||
10997 (LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap() &&
10998 !ICmpInst::isSigned(Pred))) {
10999 LHS = NewLHS;
11000 RHS = NewRHS;
11001 Changed = true;
11002 }
11003 }
11004
11005 // Canonicalize a constant to the right side.
11006 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
11007 // Check for both operands constant.
11008 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
11009 if (!ICmpInst::compare(LHSC->getAPInt(), RHSC->getAPInt(), Pred))
11010 return TrivialCase(false);
11011 return TrivialCase(true);
11012 }
11013 // Otherwise swap the operands to put the constant on the right.
11014 std::swap(LHS, RHS);
11016 Changed = true;
11017 }
11018
11019 // (K + A) pred (K + B) --> A pred B
11020 // For equality, no flags are needed.
11021 // For signed, both adds must be NSW. For unsigned, both must be NUW.
11022 {
11023 const SCEVConstant *C = nullptr;
11024 if (match(LHS, m_scev_Add(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11025 match(RHS, m_scev_Add(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11026 const auto *LAdd = cast<SCEVAddExpr>(LHS);
11027 const auto *RAdd = cast<SCEVAddExpr>(RHS);
11028 if (ICmpInst::isEquality(Pred) ||
11029 (ICmpInst::isSigned(Pred) && LAdd->hasNoSignedWrap() &&
11030 RAdd->hasNoSignedWrap()) ||
11031 (ICmpInst::isUnsigned(Pred) && LAdd->hasNoUnsignedWrap() &&
11032 RAdd->hasNoUnsignedWrap())) {
11033 LHS = NewLHS;
11034 RHS = NewRHS;
11035 Changed = true;
11036 }
11037 }
11038 }
11039
11040 // (C * A) pred (C * B) --> A pred B
11041 // For equality predicates, both muls must be NUW or both must be NSW
11042 // (either suffices to make multiplication by C injective; C == 0 is
11043 // impossible because SCEV folds 0 * X to 0).
11044 // For signed ordering, C must be positive and both muls must be NSW.
11045 // For unsigned ordering, both muls must be NUW.
11046 {
11047 const SCEVConstant *C = nullptr;
11048 if (match(LHS, m_scev_Mul(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11049 match(RHS, m_scev_Mul(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11050 const auto *LMul = cast<SCEVMulExpr>(LHS);
11051 const auto *RMul = cast<SCEVMulExpr>(RHS);
11052 bool BothNUW = LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap();
11053 bool BothNSW = LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap();
11054 if ((ICmpInst::isEquality(Pred) && (BothNUW || BothNSW)) ||
11055 (ICmpInst::isSigned(Pred) && BothNSW &&
11056 C->getAPInt().isStrictlyPositive()) ||
11057 (ICmpInst::isUnsigned(Pred) && BothNUW)) {
11058 LHS = NewLHS;
11059 RHS = NewRHS;
11060 Changed = true;
11061 }
11062 }
11063 }
11064
11065 // If we're comparing an addrec with a value which is loop-invariant in the
11066 // addrec's loop, put the addrec on the left. Also make a dominance check,
11067 // as both operands could be addrecs loop-invariant in each other's loop.
11068 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
11069 const Loop *L = AR->getLoop();
11070 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
11071 std::swap(LHS, RHS);
11073 Changed = true;
11074 }
11075 }
11076
11077 // If there's a constant operand, canonicalize comparisons with boundary
11078 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
11079 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
11080 const APInt &RA = RC->getAPInt();
11081
11082 bool SimplifiedByConstantRange = false;
11083
11084 if (!ICmpInst::isEquality(Pred)) {
11086 if (ExactCR.isFullSet())
11087 return TrivialCase(true);
11088 if (ExactCR.isEmptySet())
11089 return TrivialCase(false);
11090
11091 APInt NewRHS;
11092 CmpInst::Predicate NewPred;
11093 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
11094 ICmpInst::isEquality(NewPred)) {
11095 // We were able to convert an inequality to an equality.
11096 Pred = NewPred;
11097 RHS = getConstant(NewRHS);
11098 Changed = SimplifiedByConstantRange = true;
11099 }
11100 }
11101
11102 if (!SimplifiedByConstantRange) {
11103 switch (Pred) {
11104 default:
11105 break;
11106 case ICmpInst::ICMP_EQ:
11107 case ICmpInst::ICMP_NE:
11108 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
11109 if (RA.isZero() && MatchBinarySub(LHS, LHS, RHS))
11110 Changed = true;
11111 break;
11112
11113 // The "Should have been caught earlier!" messages refer to the fact
11114 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
11115 // should have fired on the corresponding cases, and canonicalized the
11116 // check to trivial case.
11117
11118 case ICmpInst::ICMP_UGE:
11119 assert(!RA.isMinValue() && "Should have been caught earlier!");
11120 Pred = ICmpInst::ICMP_UGT;
11121 RHS = getConstant(RA - 1);
11122 Changed = true;
11123 break;
11124 case ICmpInst::ICMP_ULE:
11125 assert(!RA.isMaxValue() && "Should have been caught earlier!");
11126 Pred = ICmpInst::ICMP_ULT;
11127 RHS = getConstant(RA + 1);
11128 Changed = true;
11129 break;
11130 case ICmpInst::ICMP_SGE:
11131 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
11132 Pred = ICmpInst::ICMP_SGT;
11133 RHS = getConstant(RA - 1);
11134 Changed = true;
11135 break;
11136 case ICmpInst::ICMP_SLE:
11137 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
11138 Pred = ICmpInst::ICMP_SLT;
11139 RHS = getConstant(RA + 1);
11140 Changed = true;
11141 break;
11142 }
11143 }
11144 }
11145
11146 // a /u b == 0 => a < b
11147 // a /u b != 0 => a >= b
11148 if (ICmpInst::isEquality(Pred) && RHS->isZero() &&
11149 match(LHS, m_scev_UDiv(m_SCEV(LHS), m_SCEV(RHS)))) {
11151 Changed = true;
11152 }
11153
11154 // Check for obvious equality.
11155 if (HasSameValue(LHS, RHS)) {
11156 if (ICmpInst::isTrueWhenEqual(Pred))
11157 return TrivialCase(true);
11159 return TrivialCase(false);
11160 }
11161
11162 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
11163 // adding or subtracting 1 from one of the operands.
11164 switch (Pred) {
11165 case ICmpInst::ICMP_SLE:
11166 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
11167 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11169 Pred = ICmpInst::ICMP_SLT;
11170 Changed = true;
11171 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
11172 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
11174 Pred = ICmpInst::ICMP_SLT;
11175 Changed = true;
11176 }
11177 break;
11178 case ICmpInst::ICMP_SGE:
11179 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
11180 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
11182 Pred = ICmpInst::ICMP_SGT;
11183 Changed = true;
11184 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
11185 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11187 Pred = ICmpInst::ICMP_SGT;
11188 Changed = true;
11189 }
11190 break;
11191 case ICmpInst::ICMP_ULE:
11192 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
11193 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11195 Pred = ICmpInst::ICMP_ULT;
11196 Changed = true;
11197 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
11198 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
11199 Pred = ICmpInst::ICMP_ULT;
11200 Changed = true;
11201 }
11202 break;
11203 case ICmpInst::ICMP_UGE:
11204 // If RHS is an op we can fold the -1, try that first.
11205 // Otherwise prefer LHS to preserve the nuw flag.
11206 if ((isa<SCEVConstant>(RHS) ||
11208 isa<SCEVConstant>(cast<SCEVNAryExpr>(RHS)->getOperand(0)))) &&
11209 !getUnsignedRangeMin(RHS).isMinValue()) {
11210 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11211 Pred = ICmpInst::ICMP_UGT;
11212 Changed = true;
11213 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
11214 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11216 Pred = ICmpInst::ICMP_UGT;
11217 Changed = true;
11218 } else if (!getUnsignedRangeMin(RHS).isMinValue()) {
11219 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11220 Pred = ICmpInst::ICMP_UGT;
11221 Changed = true;
11222 }
11223 break;
11224 default:
11225 break;
11226 }
11227
11228 // TODO: More simplifications are possible here.
11229
11230 // Recursively simplify until we either hit a recursion limit or nothing
11231 // changes.
11232 if (Changed)
11233 (void)SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1);
11234
11235 return Changed;
11236}
11237
11239 return getSignedRangeMax(S).isNegative();
11240}
11241
11245
11247 return !getSignedRangeMin(S).isNegative();
11248}
11249
11253
11255 // Query push down for cases where the unsigned range is
11256 // less than sufficient.
11257 if (const auto *SExt = dyn_cast<SCEVSignExtendExpr>(S))
11258 return isKnownNonZero(SExt->getOperand(0));
11259 return getUnsignedRangeMin(S) != 0;
11260}
11261
11263 bool OrNegative) {
11264 auto NonRecursive = [OrNegative](const SCEV *S) {
11265 if (auto *C = dyn_cast<SCEVConstant>(S))
11266 return C->getAPInt().isPowerOf2() ||
11267 (OrNegative && C->getAPInt().isNegatedPowerOf2());
11268
11269 // vscale is a power-of-two.
11270 return isa<SCEVVScale>(S);
11271 };
11272
11273 if (NonRecursive(S))
11274 return true;
11275
11276 auto *Mul = dyn_cast<SCEVMulExpr>(S);
11277 if (!Mul)
11278 return false;
11279 return all_of(Mul->operands(), NonRecursive) && (OrZero || isKnownNonZero(S));
11280}
11281
11283 const SCEV *S, uint64_t M,
11285 if (M == 0)
11286 return false;
11287 if (M == 1)
11288 return true;
11289
11290 // For a constant, check that "S % M == 0".
11291 if (auto *Cst = dyn_cast<SCEVConstant>(S)) {
11292 APInt C = Cst->getAPInt();
11293 return C.urem(M) == 0;
11294 }
11295
11296 // Basic tests have failed.
11297 // Check "S % M == 0" at compile time and record runtime Assumptions.
11298 auto *STy = dyn_cast<IntegerType>(S->getType());
11299 const SCEV *SmodM =
11300 getURemExpr(S, getConstant(ConstantInt::get(STy, M, false)));
11301 const SCEV *Zero = getZero(STy);
11302
11303 // Check whether "S % M == 0" is known at compile time.
11304 if (isKnownPredicate(ICmpInst::ICMP_EQ, SmodM, Zero))
11305 return true;
11306
11307 // Check whether "S % M != 0" is known at compile time.
11308 if (isKnownPredicate(ICmpInst::ICMP_NE, SmodM, Zero))
11309 return false;
11310
11311 if (!Predicates)
11312 return false;
11313
11314 // Look through Add and AddRec expressions with nuw to improve the
11315 // precision of added predicates. S is a multiple of M if S starts with a
11316 // multiple of M and at every iteration step S only adds multiples of M.
11319 all_of(S->operands(),
11320 [&](SCEVUse Op) { return isKnownMultipleOf(Op, M, Predicates); }))
11321 return true;
11322
11323 // Similarly, look through Mul with nuw, where any operand being a
11324 // known-multiple is sufficient.
11325 if (auto *Mul = dyn_cast<SCEVMulExpr>(S))
11326 if (Mul->hasNoUnsignedWrap() && any_of(S->operands(), [&](SCEVUse Op) {
11327 return isKnownMultipleOf(Op, M, Predicates);
11328 }))
11329 return true;
11330
11331 // Similarly, look through MinMax, with no wrapping arithmetic to consider.
11332 if (isa<SCEVMinMaxExpr>(S) && all_of(S->operands(), [&](SCEVUse Op) {
11333 return isKnownMultipleOf(Op, M, Predicates);
11334 }))
11335 return true;
11336
11338
11339 // Detect redundant predicates.
11340 for (auto *A : *Predicates)
11341 if (A->implies(P, *this))
11342 return true;
11343
11344 // Only record non-redundant predicates.
11345 Predicates->push_back(P);
11346 return true;
11347}
11348
11350 return ((isKnownNonNegative(S1) && isKnownNonNegative(S2)) ||
11352}
11353
11354std::pair<const SCEV *, const SCEV *>
11356 // Compute SCEV on entry of loop L.
11357 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
11358 if (Start == getCouldNotCompute())
11359 return { Start, Start };
11360 // Compute post increment SCEV for loop L.
11361 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
11362 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
11363 return { Start, PostInc };
11364}
11365
11367 SCEVUse RHS) {
11368 // First collect all loops.
11370 getUsedLoops(LHS, LoopsUsed);
11371 getUsedLoops(RHS, LoopsUsed);
11372
11373 if (LoopsUsed.empty())
11374 return false;
11375
11376 // Domination relationship must be a linear order on collected loops.
11377#ifndef NDEBUG
11378 for (const auto *L1 : LoopsUsed)
11379 for (const auto *L2 : LoopsUsed)
11380 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
11381 DT.dominates(L2->getHeader(), L1->getHeader())) &&
11382 "Domination relationship is not a linear order");
11383#endif
11384
11385 const Loop *MDL =
11386 *llvm::max_element(LoopsUsed, [&](const Loop *L1, const Loop *L2) {
11387 return DT.properlyDominates(L1->getHeader(), L2->getHeader());
11388 });
11389
11390 // Get init and post increment value for LHS.
11391 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
11392 // if LHS contains unknown non-invariant SCEV then bail out.
11393 if (SplitLHS.first == getCouldNotCompute())
11394 return false;
11395 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
11396 // Get init and post increment value for RHS.
11397 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
11398 // if RHS contains unknown non-invariant SCEV then bail out.
11399 if (SplitRHS.first == getCouldNotCompute())
11400 return false;
11401 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
11402 // It is possible that init SCEV contains an invariant load but it does
11403 // not dominate MDL and is not available at MDL loop entry, so we should
11404 // check it here.
11405 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
11406 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
11407 return false;
11408
11409 // It seems backedge guard check is faster than entry one so in some cases
11410 // it can speed up whole estimation by short circuit
11411 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
11412 SplitRHS.second) &&
11413 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
11414}
11415
11417 SCEVUse RHS) {
11418 // Canonicalize the inputs first.
11419 (void)SimplifyICmpOperands(Pred, LHS, RHS);
11420
11421 return isKnownViaInduction(Pred, LHS, RHS) ||
11422 isKnownPredicateViaSplitting(Pred, LHS, RHS) ||
11423 isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
11424}
11425
11427 const SCEV *LHS,
11428 const SCEV *RHS) {
11429 if (isKnownPredicate(Pred, LHS, RHS))
11430 return true;
11432 return false;
11433 return std::nullopt;
11434}
11435
11437 const SCEV *RHS,
11438 const Instruction *CtxI) {
11439 // TODO: Analyze guards and assumes from Context's block.
11440 return isKnownPredicate(Pred, LHS, RHS) ||
11441 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
11442}
11443
11444std::optional<bool>
11446 const SCEV *RHS, const Instruction *CtxI) {
11447 std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
11448 if (KnownWithoutContext)
11449 return KnownWithoutContext;
11450
11451 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
11452 return true;
11454 CtxI->getParent(), ICmpInst::getInverseCmpPredicate(Pred), LHS, RHS))
11455 return false;
11456 return std::nullopt;
11457}
11458
11460 const SCEVAddRecExpr *LHS,
11461 const SCEV *RHS) {
11462 const Loop *L = LHS->getLoop();
11463 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
11464 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
11465}
11466
11467std::optional<ScalarEvolution::MonotonicPredicateType>
11469 ICmpInst::Predicate Pred) {
11470 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
11471
11472#ifndef NDEBUG
11473 // Verify an invariant: inverting the predicate should turn a monotonically
11474 // increasing change to a monotonically decreasing one, and vice versa.
11475 if (Result) {
11476 auto ResultSwapped =
11477 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
11478
11479 assert(*ResultSwapped != *Result &&
11480 "monotonicity should flip as we flip the predicate");
11481 }
11482#endif
11483
11484 return Result;
11485}
11486
11487std::optional<ScalarEvolution::MonotonicPredicateType>
11488ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
11489 ICmpInst::Predicate Pred) {
11490 // A zero step value for LHS means the induction variable is essentially a
11491 // loop invariant value. We don't really depend on the predicate actually
11492 // flipping from false to true (for increasing predicates, and the other way
11493 // around for decreasing predicates), all we care about is that *if* the
11494 // predicate changes then it only changes from false to true.
11495 //
11496 // A zero step value in itself is not very useful, but there may be places
11497 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
11498 // as general as possible.
11499
11500 // Only handle LE/LT/GE/GT predicates.
11501 if (!ICmpInst::isRelational(Pred))
11502 return std::nullopt;
11503
11504 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
11505 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
11506 "Should be greater or less!");
11507
11508 // Check that AR does not wrap.
11509 if (ICmpInst::isUnsigned(Pred)) {
11510 if (!LHS->hasNoUnsignedWrap())
11511 return std::nullopt;
11513 }
11514 assert(ICmpInst::isSigned(Pred) &&
11515 "Relational predicate is either signed or unsigned!");
11516 if (!LHS->hasNoSignedWrap())
11517 return std::nullopt;
11518
11519 const SCEV *Step = LHS->getStepRecurrence(*this);
11520
11521 if (isKnownNonNegative(Step))
11523
11524 if (isKnownNonPositive(Step))
11526
11527 return std::nullopt;
11528}
11529
11530std::optional<ScalarEvolution::LoopInvariantPredicate>
11532 const SCEV *RHS, const Loop *L,
11533 const Instruction *CtxI) {
11534 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11535 if (!isLoopInvariant(RHS, L)) {
11536 if (!isLoopInvariant(LHS, L))
11537 return std::nullopt;
11538
11539 std::swap(LHS, RHS);
11541 }
11542
11543 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11544 if (!ArLHS || ArLHS->getLoop() != L)
11545 return std::nullopt;
11546
11547 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
11548 if (!MonotonicType)
11549 return std::nullopt;
11550 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
11551 // true as the loop iterates, and the backedge is control dependent on
11552 // "ArLHS `Pred` RHS" == true then we can reason as follows:
11553 //
11554 // * if the predicate was false in the first iteration then the predicate
11555 // is never evaluated again, since the loop exits without taking the
11556 // backedge.
11557 // * if the predicate was true in the first iteration then it will
11558 // continue to be true for all future iterations since it is
11559 // monotonically increasing.
11560 //
11561 // For both the above possibilities, we can replace the loop varying
11562 // predicate with its value on the first iteration of the loop (which is
11563 // loop invariant).
11564 //
11565 // A similar reasoning applies for a monotonically decreasing predicate, by
11566 // replacing true with false and false with true in the above two bullets.
11568 auto P = Increasing ? Pred : ICmpInst::getInverseCmpPredicate(Pred);
11569
11570 if (isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
11572 RHS);
11573
11574 if (!CtxI)
11575 return std::nullopt;
11576 // Try to prove via context.
11577 // TODO: Support other cases.
11578 switch (Pred) {
11579 default:
11580 break;
11581 case ICmpInst::ICMP_ULE:
11582 case ICmpInst::ICMP_ULT: {
11583 assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!");
11584 // Given preconditions
11585 // (1) ArLHS does not cross the border of positive and negative parts of
11586 // range because of:
11587 // - Positive step; (TODO: lift this limitation)
11588 // - nuw - does not cross zero boundary;
11589 // - nsw - does not cross SINT_MAX boundary;
11590 // (2) ArLHS <s RHS
11591 // (3) RHS >=s 0
11592 // we can replace the loop variant ArLHS <u RHS condition with loop
11593 // invariant Start(ArLHS) <u RHS.
11594 //
11595 // Because of (1) there are two options:
11596 // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
11597 // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
11598 // It means that ArLHS <s RHS <=> ArLHS <u RHS.
11599 // Because of (2) ArLHS <u RHS is trivially true.
11600 // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
11601 // We can strengthen this to Start(ArLHS) <u RHS.
11602 auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
11603 if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
11604 isKnownPositive(ArLHS->getStepRecurrence(*this)) &&
11605 isKnownNonNegative(RHS) &&
11606 isKnownPredicateAt(SignFlippedPred, ArLHS, RHS, CtxI))
11608 RHS);
11609 }
11610 }
11611
11612 return std::nullopt;
11613}
11614
11615std::optional<ScalarEvolution::LoopInvariantPredicate>
11617 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11618 const Instruction *CtxI, const SCEV *MaxIter) {
11620 Pred, LHS, RHS, L, CtxI, MaxIter))
11621 return LIP;
11622 if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
11623 // Number of iterations expressed as UMIN isn't always great for expressing
11624 // the value on the last iteration. If the straightforward approach didn't
11625 // work, try the following trick: if the a predicate is invariant for X, it
11626 // is also invariant for umin(X, ...). So try to find something that works
11627 // among subexpressions of MaxIter expressed as umin.
11628 for (SCEVUse Op : UMin->operands())
11630 Pred, LHS, RHS, L, CtxI, Op))
11631 return LIP;
11632 return std::nullopt;
11633}
11634
11635std::optional<ScalarEvolution::LoopInvariantPredicate>
11637 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11638 const Instruction *CtxI, const SCEV *MaxIter) {
11639 // Try to prove the following set of facts:
11640 // - The predicate is monotonic in the iteration space.
11641 // - If the check does not fail on the 1st iteration:
11642 // - No overflow will happen during first MaxIter iterations;
11643 // - It will not fail on the MaxIter'th iteration.
11644 // If the check does fail on the 1st iteration, we leave the loop and no
11645 // other checks matter.
11646
11647 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11648 if (!isLoopInvariant(RHS, L)) {
11649 if (!isLoopInvariant(LHS, L))
11650 return std::nullopt;
11651
11652 std::swap(LHS, RHS);
11654 }
11655
11656 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
11657 if (!AR || AR->getLoop() != L)
11658 return std::nullopt;
11659
11660 // Even if both are valid, we need to consistently chose the unsigned or the
11661 // signed predicate below, not mixtures of both. For now, prefer the unsigned
11662 // predicate.
11663 Pred = Pred.dropSameSign();
11664
11665 // The predicate must be relational (i.e. <, <=, >=, >).
11666 if (!ICmpInst::isRelational(Pred))
11667 return std::nullopt;
11668
11669 // TODO: Support steps other than +/- 1.
11670 const SCEV *Step = AR->getStepRecurrence(*this);
11671 auto *One = getOne(Step->getType());
11672 auto *MinusOne = getNegativeSCEV(One);
11673 if (Step != One && Step != MinusOne)
11674 return std::nullopt;
11675
11676 // Type mismatch here means that MaxIter is potentially larger than max
11677 // unsigned value in start type, which mean we cannot prove no wrap for the
11678 // indvar.
11679 if (AR->getType() != MaxIter->getType())
11680 return std::nullopt;
11681
11682 // Value of IV on suggested last iteration.
11683 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
11684 // Does it still meet the requirement?
11685 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
11686 return std::nullopt;
11687 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
11688 // not exceed max unsigned value of this type), this effectively proves
11689 // that there is no wrap during the iteration. To prove that there is no
11690 // signed/unsigned wrap, we need to check that
11691 // Start <= Last for step = 1 or Start >= Last for step = -1.
11692 ICmpInst::Predicate NoOverflowPred =
11694 if (Step == MinusOne)
11695 NoOverflowPred = ICmpInst::getSwappedPredicate(NoOverflowPred);
11696 const SCEV *Start = AR->getStart();
11697 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
11698 return std::nullopt;
11699
11700 // Everything is fine.
11701 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
11702}
11703
11704bool ScalarEvolution::isKnownPredicateViaConstantRanges(CmpPredicate Pred,
11705 SCEVUse LHS,
11706 SCEVUse RHS) {
11707 if (HasSameValue(LHS, RHS))
11708 return ICmpInst::isTrueWhenEqual(Pred);
11709
11710 auto CheckRange = [&](bool IsSigned) {
11711 auto RangeLHS = IsSigned ? getSignedRange(LHS) : getUnsignedRange(LHS);
11712 auto RangeRHS = IsSigned ? getSignedRange(RHS) : getUnsignedRange(RHS);
11713 return RangeLHS.icmp(Pred, RangeRHS);
11714 };
11715
11716 // The check at the top of the function catches the case where the values are
11717 // known to be equal.
11718 if (Pred == CmpInst::ICMP_EQ)
11719 return false;
11720
11721 if (Pred == CmpInst::ICMP_NE) {
11722 if (CheckRange(true) || CheckRange(false))
11723 return true;
11724 auto *Diff = getMinusSCEV(LHS, RHS);
11725 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
11726 }
11727
11728 return CheckRange(CmpInst::isSigned(Pred));
11729}
11730
11731bool ScalarEvolution::isKnownPredicateViaNoOverflow(CmpPredicate Pred,
11733 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
11734 // C1 and C2 are constant integers. If either X or Y are not add expressions,
11735 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
11736 // OutC1 and OutC2.
11737 auto MatchBinaryAddToConst = [this](SCEVUse X, SCEVUse Y, APInt &OutC1,
11738 APInt &OutC2, SCEVFlags ExpectedFlags) {
11739 SCEVUse XNonConstOp, XConstOp;
11740 SCEVUse YNonConstOp, YConstOp;
11741 SCEVFlags XFlagsPresent;
11742 SCEVFlags YFlagsPresent;
11743
11744 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
11745 XConstOp = getZero(X->getType());
11746 XNonConstOp = X;
11747 XFlagsPresent = ExpectedFlags;
11748 }
11749 if (!isa<SCEVConstant>(XConstOp))
11750 return false;
11751
11752 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
11753 YConstOp = getZero(Y->getType());
11754 YNonConstOp = Y;
11755 YFlagsPresent = ExpectedFlags;
11756 }
11757
11758 if (YNonConstOp != XNonConstOp)
11759 return false;
11760
11761 if (!isa<SCEVConstant>(YConstOp))
11762 return false;
11763
11764 // When matching ADDs with NUW flags (and unsigned predicates), only the
11765 // second ADD (with the larger constant) requires NUW.
11766 if ((YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11767 return false;
11768 if (ExpectedFlags != SCEV::FlagNUW &&
11769 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) {
11770 return false;
11771 }
11772
11773 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
11774 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
11775
11776 return true;
11777 };
11778
11779 APInt C1;
11780 APInt C2;
11781
11782 switch (Pred) {
11783 default:
11784 break;
11785
11786 case ICmpInst::ICMP_SGE:
11787 std::swap(LHS, RHS);
11788 [[fallthrough]];
11789 case ICmpInst::ICMP_SLE:
11790 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
11791 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
11792 return true;
11793
11794 break;
11795
11796 case ICmpInst::ICMP_SGT:
11797 std::swap(LHS, RHS);
11798 [[fallthrough]];
11799 case ICmpInst::ICMP_SLT:
11800 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
11801 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
11802 return true;
11803
11804 break;
11805
11806 case ICmpInst::ICMP_UGE:
11807 std::swap(LHS, RHS);
11808 [[fallthrough]];
11809 case ICmpInst::ICMP_ULE:
11810 // (X + C1) u<= (X + C2)<nuw> for C1 u<= C2.
11811 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ule(C2))
11812 return true;
11813
11814 break;
11815
11816 case ICmpInst::ICMP_UGT:
11817 std::swap(LHS, RHS);
11818 [[fallthrough]];
11819 case ICmpInst::ICMP_ULT:
11820 // (X + C1) u< (X + C2)<nuw> if C1 u< C2.
11821 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ult(C2))
11822 return true;
11823 break;
11824 }
11825
11826 return false;
11827}
11828
11829bool ScalarEvolution::isKnownPredicateViaSplitting(CmpPredicate Pred,
11831 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
11832 return false;
11833
11834 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
11835 // the stack can result in exponential time complexity.
11836 SaveAndRestore Restore(ProvingSplitPredicate, true);
11837
11838 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
11839 //
11840 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
11841 // isKnownPredicate. isKnownPredicate is more powerful, but also more
11842 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
11843 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
11844 // use isKnownPredicate later if needed.
11845 return isKnownNonNegative(RHS) &&
11848}
11849
11850bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, CmpPredicate Pred,
11851 const SCEV *LHS, const SCEV *RHS) {
11852 // No need to even try if we know the module has no guards.
11853 if (!HasGuards)
11854 return false;
11855
11856 return any_of(*BB, [&](const Instruction &I) {
11857 using namespace llvm::PatternMatch;
11858
11859 Value *Condition;
11861 m_Value(Condition))) &&
11862 isImpliedCond(Pred, LHS, RHS, Condition, false);
11863 });
11864}
11865
11866/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
11867/// protected by a conditional between LHS and RHS. This is used to
11868/// to eliminate casts.
11870 CmpPredicate Pred,
11871 const SCEV *LHS,
11872 const SCEV *RHS) {
11873 // Interpret a null as meaning no loop, where there is obviously no guard
11874 // (interprocedural conditions notwithstanding). Do not bother about
11875 // unreachable loops.
11876 if (!L || !DT.isReachableFromEntry(L->getHeader()))
11877 return true;
11878
11879 if (VerifyIR)
11880 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
11881 "This cannot be done on broken IR!");
11882
11883
11884 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11885 return true;
11886
11887 BasicBlock *Latch = L->getLoopLatch();
11888 if (!Latch)
11889 return false;
11890
11891 CondBrInst *LoopContinuePredicate =
11893 if (LoopContinuePredicate &&
11894 isImpliedCond(Pred, LHS, RHS, LoopContinuePredicate->getCondition(),
11895 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
11896 return true;
11897
11898 // We don't want more than one activation of the following loops on the stack
11899 // -- that can lead to O(n!) time complexity.
11900 if (WalkingBEDominatingConds)
11901 return false;
11902
11903 SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
11904
11905 // See if we can exploit a trip count to prove the predicate.
11906 const auto &BETakenInfo = getBackedgeTakenInfo(L);
11907 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
11908 if (LatchBECount != getCouldNotCompute()) {
11909 // We know that Latch branches back to the loop header exactly
11910 // LatchBECount times. This means the backdege condition at Latch is
11911 // equivalent to "{0,+,1} u< LatchBECount".
11912 Type *Ty = LatchBECount->getType();
11913 auto NoWrapFlags = SCEVFlags(SCEV::FlagNUW | SCEV::FlagNW);
11914 const SCEV *LoopCounter =
11915 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
11916 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
11917 LatchBECount))
11918 return true;
11919 }
11920
11921 // Check conditions due to any @llvm.assume intrinsics.
11922 for (auto &AssumeVH : AC.assumptions()) {
11923 if (!AssumeVH)
11924 continue;
11925 auto *CI = cast<CallInst>(AssumeVH);
11926 if (!DT.dominates(CI, Latch->getTerminator()))
11927 continue;
11928
11929 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
11930 return true;
11931 }
11932
11933 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
11934 return true;
11935
11936 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
11937 DTN != HeaderDTN; DTN = DTN->getIDom()) {
11938 assert(DTN && "should reach the loop header before reaching the root!");
11939
11940 BasicBlock *BB = DTN->getBlock();
11941 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
11942 return true;
11943
11944 BasicBlock *PBB = BB->getSinglePredecessor();
11945 if (!PBB)
11946 continue;
11947
11949 if (!ContBr || ContBr->getSuccessor(0) == ContBr->getSuccessor(1))
11950 continue;
11951
11952 // If we have an edge `E` within the loop body that dominates the only
11953 // latch, the condition guarding `E` also guards the backedge. This
11954 // reasoning works only for loops with a single latch.
11955 // We're constructively (and conservatively) enumerating edges within the
11956 // loop body that dominate the latch. The dominator tree better agree
11957 // with us on this:
11958 assert(DT.dominates(BasicBlockEdge(PBB, BB), Latch) && "should be!");
11959 if (isImpliedCond(Pred, LHS, RHS, ContBr->getCondition(),
11960 BB != ContBr->getSuccessor(0)))
11961 return true;
11962 }
11963
11964 return false;
11965}
11966
11968 CmpPredicate Pred,
11969 const SCEV *LHS,
11970 const SCEV *RHS) {
11971 // Do not bother proving facts for unreachable code.
11972 if (!DT.isReachableFromEntry(BB))
11973 return true;
11974 if (VerifyIR)
11975 assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
11976 "This cannot be done on broken IR!");
11977
11978 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
11979 // the facts (a >= b && a != b) separately. A typical situation is when the
11980 // non-strict comparison is known from ranges and non-equality is known from
11981 // dominating predicates. If we are proving strict comparison, we always try
11982 // to prove non-equality and non-strict comparison separately.
11983 CmpPredicate NonStrictPredicate = ICmpInst::getNonStrictCmpPredicate(Pred);
11984 const bool ProvingStrictComparison =
11985 Pred != NonStrictPredicate.dropSameSign();
11986 bool ProvedNonStrictComparison = false;
11987 bool ProvedNonEquality = false;
11988
11989 auto SplitAndProve = [&](std::function<bool(CmpPredicate)> Fn) -> bool {
11990 if (!ProvedNonStrictComparison)
11991 ProvedNonStrictComparison = Fn(NonStrictPredicate);
11992 if (!ProvedNonEquality)
11993 ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
11994 if (ProvedNonStrictComparison && ProvedNonEquality)
11995 return true;
11996 return false;
11997 };
11998
11999 if (ProvingStrictComparison) {
12000 auto ProofFn = [&](CmpPredicate P) {
12001 return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
12002 };
12003 if (SplitAndProve(ProofFn))
12004 return true;
12005 }
12006
12007 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
12008 auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
12009 const Instruction *CtxI = &BB->front();
12010 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
12011 return true;
12012 if (ProvingStrictComparison) {
12013 auto ProofFn = [&](CmpPredicate P) {
12014 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
12015 };
12016 if (SplitAndProve(ProofFn))
12017 return true;
12018 }
12019 return false;
12020 };
12021
12022 // Starting at the block's predecessor, climb up the predecessor chain, as long
12023 // as there are predecessors that can be found that have unique successors
12024 // leading to the original block.
12025 const Loop *ContainingLoop = LI.getLoopFor(BB);
12026 const BasicBlock *PredBB;
12027 if (ContainingLoop && ContainingLoop->getHeader() == BB)
12028 PredBB = ContainingLoop->getLoopPredecessor();
12029 else
12030 PredBB = BB->getSinglePredecessor();
12031 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
12032 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
12033 const CondBrInst *BlockEntryPredicate =
12034 dyn_cast<CondBrInst>(Pair.first->getTerminator());
12035 if (!BlockEntryPredicate)
12036 continue;
12037
12038 if (ProveViaCond(BlockEntryPredicate->getCondition(),
12039 BlockEntryPredicate->getSuccessor(0) != Pair.second))
12040 return true;
12041 }
12042
12043 // Check conditions due to any @llvm.assume intrinsics.
12044 for (auto &AssumeVH : AC.assumptions()) {
12045 if (!AssumeVH)
12046 continue;
12047 auto *CI = cast<CallInst>(AssumeVH);
12048 if (!DT.dominates(CI, BB))
12049 continue;
12050
12051 if (ProveViaCond(CI->getArgOperand(0), false))
12052 return true;
12053 }
12054
12055 // Check conditions due to any @llvm.experimental.guard intrinsics.
12056 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
12057 F.getParent(), Intrinsic::experimental_guard);
12058 if (GuardDecl)
12059 for (const auto *GU : GuardDecl->users())
12060 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
12061 if (Guard->getFunction() == BB->getParent() && DT.dominates(Guard, BB))
12062 if (ProveViaCond(Guard->getArgOperand(0), false))
12063 return true;
12064 return false;
12065}
12066
12068 const SCEV *LHS,
12069 const SCEV *RHS) {
12070 // Interpret a null as meaning no loop, where there is obviously no guard
12071 // (interprocedural conditions notwithstanding).
12072 if (!L)
12073 return false;
12074
12075 // Both LHS and RHS must be available at loop entry.
12077 "LHS is not available at Loop Entry");
12079 "RHS is not available at Loop Entry");
12080
12081 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
12082 return true;
12083
12084 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
12085}
12086
12087bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12088 const SCEV *RHS,
12089 const Value *FoundCondValue, bool Inverse,
12090 const Instruction *CtxI) {
12091 // False conditions implies anything. Do not bother analyzing it further.
12092 if (FoundCondValue ==
12093 ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
12094 return true;
12095
12096 if (!PendingLoopPredicates.insert(FoundCondValue).second)
12097 return false;
12098
12099 llvm::scope_exit ClearOnExit(
12100 [&]() { PendingLoopPredicates.erase(FoundCondValue); });
12101
12102 // Recursively handle And and Or conditions.
12103 const Value *Op0, *Op1;
12104 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
12105 if (!Inverse)
12106 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12107 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12108 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
12109 if (Inverse)
12110 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12111 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12112 }
12113
12114 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
12115 if (!ICI) return false;
12116
12117 // Now that we found a conditional branch that dominates the loop or controls
12118 // the loop latch. Check to see if it is the comparison we are looking for.
12119 CmpPredicate FoundPred;
12120 if (Inverse)
12121 FoundPred = ICI->getInverseCmpPredicate();
12122 else
12123 FoundPred = ICI->getCmpPredicate();
12124
12125 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
12126 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
12127
12128 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
12129}
12130
12131bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12132 const SCEV *RHS, CmpPredicate FoundPred,
12133 const SCEV *FoundLHS, const SCEV *FoundRHS,
12134 const Instruction *CtxI) {
12135 // Balance the types.
12136 if (getTypeSizeInBits(LHS->getType()) <
12137 getTypeSizeInBits(FoundLHS->getType())) {
12138 // For unsigned and equality predicates, try to prove that both found
12139 // operands fit into narrow unsigned range. If so, try to prove facts in
12140 // narrow types.
12141 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
12142 !FoundRHS->getType()->isPointerTy()) {
12143 auto *NarrowType = LHS->getType();
12144 auto *WideType = FoundLHS->getType();
12145 auto BitWidth = getTypeSizeInBits(NarrowType);
12146 const SCEV *MaxValue = getZeroExtendExpr(
12148 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
12149 MaxValue) &&
12150 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
12151 MaxValue)) {
12152 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
12153 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
12154 // We cannot preserve samesign after truncation.
12155 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred.dropSameSign(),
12156 TruncFoundLHS, TruncFoundRHS, CtxI))
12157 return true;
12158 }
12159 }
12160
12161 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
12162 return false;
12163 if (CmpInst::isSigned(Pred)) {
12164 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
12165 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
12166 } else {
12167 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
12168 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
12169 }
12170 } else if (getTypeSizeInBits(LHS->getType()) >
12171 getTypeSizeInBits(FoundLHS->getType())) {
12172 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
12173 return false;
12174 if (CmpInst::isSigned(FoundPred)) {
12175 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
12176 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
12177 } else {
12178 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
12179 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
12180 }
12181 }
12182 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
12183 FoundRHS, CtxI);
12184}
12185
12186bool ScalarEvolution::isImpliedCondBalancedTypes(
12187 CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, CmpPredicate FoundPred,
12188 SCEVUse FoundLHS, SCEVUse FoundRHS, const Instruction *CtxI) {
12190 getTypeSizeInBits(FoundLHS->getType()) &&
12191 "Types should be balanced!");
12192 // Canonicalize the query to match the way instcombine will have
12193 // canonicalized the comparison.
12194 if (SimplifyICmpOperands(Pred, LHS, RHS))
12195 if (LHS == RHS)
12196 return CmpInst::isTrueWhenEqual(Pred);
12197 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
12198 if (FoundLHS == FoundRHS)
12199 return CmpInst::isFalseWhenEqual(FoundPred);
12200
12201 // Check to see if we can make the LHS or RHS match.
12202 if (LHS == FoundRHS || RHS == FoundLHS) {
12203 if (isa<SCEVConstant>(RHS)) {
12204 std::swap(FoundLHS, FoundRHS);
12205 FoundPred = ICmpInst::getSwappedCmpPredicate(FoundPred);
12206 } else {
12207 std::swap(LHS, RHS);
12209 }
12210 }
12211
12212 // Check whether the found predicate is the same as the desired predicate.
12213 if (auto P = CmpPredicate::getMatching(FoundPred, Pred))
12214 return isImpliedCondOperands(*P, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12215
12216 // Check whether swapping the found predicate makes it the same as the
12217 // desired predicate.
12218 if (auto P = CmpPredicate::getMatching(
12219 ICmpInst::getSwappedCmpPredicate(FoundPred), Pred)) {
12220 // We can write the implication
12221 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS
12222 // using one of the following ways:
12223 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS
12224 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS
12225 // Both require swapping the operands of one condition. Don't do this if it
12226 // would break canonical constant/addrec ordering.
12228 return isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P), RHS,
12229 LHS, FoundLHS, FoundRHS, CtxI);
12230 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
12231 return isImpliedCondOperands(*P, LHS, RHS, FoundRHS, FoundLHS, CtxI);
12232
12233 return false;
12234 }
12235
12236 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
12238 assert(P1 != P2 && "Handled earlier!");
12239 return CmpInst::isRelational(P2) &&
12241 };
12242 if (IsSignFlippedPredicate(Pred, FoundPred)) {
12243 // Unsigned comparison is the same as signed comparison when both the
12244 // operands are non-negative or negative.
12245 if (haveSameSign(FoundLHS, FoundRHS))
12246 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12247 // Create local copies that we can freely swap and canonicalize our
12248 // conditions to "le/lt".
12249 CmpPredicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
12250 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
12251 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
12252 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
12253 CanonicalPred = ICmpInst::getSwappedCmpPredicate(CanonicalPred);
12254 CanonicalFoundPred = ICmpInst::getSwappedCmpPredicate(CanonicalFoundPred);
12255 std::swap(CanonicalLHS, CanonicalRHS);
12256 std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
12257 }
12258 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
12259 "Must be!");
12260 assert((ICmpInst::isLT(CanonicalFoundPred) ||
12261 ICmpInst::isLE(CanonicalFoundPred)) &&
12262 "Must be!");
12263 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
12264 // Use implication:
12265 // x <u y && y >=s 0 --> x <s y.
12266 // If we can prove the left part, the right part is also proven.
12267 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
12268 CanonicalRHS, CanonicalFoundLHS,
12269 CanonicalFoundRHS);
12270 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
12271 // Use implication:
12272 // x <s y && y <s 0 --> x <u y.
12273 // If we can prove the left part, the right part is also proven.
12274 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
12275 CanonicalRHS, CanonicalFoundLHS,
12276 CanonicalFoundRHS);
12277 }
12278
12279 // Check if we can make progress by sharpening ranges.
12280 if (FoundPred == ICmpInst::ICMP_NE &&
12281 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
12282
12283 const SCEVConstant *C = nullptr;
12284 const SCEV *V = nullptr;
12285
12286 if (isa<SCEVConstant>(FoundLHS)) {
12287 C = cast<SCEVConstant>(FoundLHS);
12288 V = FoundRHS;
12289 } else {
12290 C = cast<SCEVConstant>(FoundRHS);
12291 V = FoundLHS;
12292 }
12293
12294 // The guarding predicate tells us that C != V. If the known range
12295 // of V is [C, t), we can sharpen the range to [C + 1, t). The
12296 // range we consider has to correspond to same signedness as the
12297 // predicate we're interested in folding.
12298
12299 APInt Min = ICmpInst::isSigned(Pred) ?
12301
12302 if (Min == C->getAPInt()) {
12303 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
12304 // This is true even if (Min + 1) wraps around -- in case of
12305 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
12306
12307 APInt SharperMin = Min + 1;
12308
12309 switch (Pred) {
12310 case ICmpInst::ICMP_SGE:
12311 case ICmpInst::ICMP_UGE:
12312 // We know V `Pred` SharperMin. If this implies LHS `Pred`
12313 // RHS, we're done.
12314 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
12315 CtxI))
12316 return true;
12317 [[fallthrough]];
12318
12319 case ICmpInst::ICMP_SGT:
12320 case ICmpInst::ICMP_UGT:
12321 // We know from the range information that (V `Pred` Min ||
12322 // V == Min). We know from the guarding condition that !(V
12323 // == Min). This gives us
12324 //
12325 // V `Pred` Min || V == Min && !(V == Min)
12326 // => V `Pred` Min
12327 //
12328 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
12329
12330 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
12331 return true;
12332 break;
12333
12334 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
12335 case ICmpInst::ICMP_SLE:
12336 case ICmpInst::ICMP_ULE:
12337 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12338 LHS, V, getConstant(SharperMin), CtxI))
12339 return true;
12340 [[fallthrough]];
12341
12342 case ICmpInst::ICMP_SLT:
12343 case ICmpInst::ICMP_ULT:
12344 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12345 LHS, V, getConstant(Min), CtxI))
12346 return true;
12347 break;
12348
12349 default:
12350 // No change
12351 break;
12352 }
12353 }
12354 }
12355
12356 // Check whether the actual condition is beyond sufficient.
12357 if (FoundPred == ICmpInst::ICMP_EQ)
12358 if (ICmpInst::isTrueWhenEqual(Pred))
12359 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12360 return true;
12361 if (Pred == ICmpInst::ICMP_NE)
12362 if (!ICmpInst::isTrueWhenEqual(FoundPred))
12363 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12364 return true;
12365
12366 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS))
12367 return true;
12368
12369 // Otherwise assume the worst.
12370 return false;
12371}
12372
12373bool ScalarEvolution::splitBinaryAdd(SCEVUse Expr, SCEVUse &L, SCEVUse &R,
12374 SCEVFlags &Flags) {
12375 if (!match(Expr, m_scev_Add(m_SCEV(L), m_SCEV(R))))
12376 return false;
12377
12378 Flags = cast<SCEVAddExpr>(Expr)->getNoWrapFlags();
12379 return true;
12380}
12381
12382std::optional<APInt>
12384 // We avoid subtracting expressions here because this function is usually
12385 // fairly deep in the call stack (i.e. is called many times).
12386
12387 unsigned BW = getTypeSizeInBits(More->getType());
12388 APInt Diff(BW, 0);
12389 APInt DiffMul(BW, 1);
12390 // Try various simplifications to reduce the difference to a constant. Limit
12391 // the number of allowed simplifications to keep compile-time low.
12392 for (unsigned I = 0; I < 8; ++I) {
12393 if (More == Less)
12394 return Diff;
12395
12396 // Reduce addrecs with identical steps to their start value.
12398 const auto *LAR = cast<SCEVAddRecExpr>(Less);
12399 const auto *MAR = cast<SCEVAddRecExpr>(More);
12400
12401 if (LAR->getLoop() != MAR->getLoop())
12402 return std::nullopt;
12403
12404 // We look at affine expressions only; not for correctness but to keep
12405 // getStepRecurrence cheap.
12406 if (!LAR->isAffine() || !MAR->isAffine())
12407 return std::nullopt;
12408
12409 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
12410 return std::nullopt;
12411
12412 Less = LAR->getStart();
12413 More = MAR->getStart();
12414 continue;
12415 }
12416
12417 // Try to match a common constant multiply.
12418 auto MatchConstMul =
12419 [](const SCEV *S) -> std::optional<std::pair<const SCEV *, APInt>> {
12420 const APInt *C;
12421 const SCEV *Op;
12422 if (match(S, m_scev_Mul(m_scev_APInt(C), m_SCEV(Op))))
12423 return {{Op, *C}};
12424 return std::nullopt;
12425 };
12426 if (auto MatchedMore = MatchConstMul(More)) {
12427 if (auto MatchedLess = MatchConstMul(Less)) {
12428 if (MatchedMore->second == MatchedLess->second) {
12429 More = MatchedMore->first;
12430 Less = MatchedLess->first;
12431 DiffMul *= MatchedMore->second;
12432 continue;
12433 }
12434 }
12435 }
12436
12437 // Try to cancel out common factors in two add expressions.
12439 auto Add = [&](const SCEV *S, int Mul) {
12440 if (auto *C = dyn_cast<SCEVConstant>(S)) {
12441 if (Mul == 1) {
12442 Diff += C->getAPInt() * DiffMul;
12443 } else {
12444 assert(Mul == -1);
12445 Diff -= C->getAPInt() * DiffMul;
12446 }
12447 } else
12448 Multiplicity[S] += Mul;
12449 };
12450 auto Decompose = [&](const SCEV *S, int Mul) {
12451 if (isa<SCEVAddExpr>(S)) {
12452 for (const SCEV *Op : S->operands())
12453 Add(Op, Mul);
12454 } else
12455 Add(S, Mul);
12456 };
12457 Decompose(More, 1);
12458 Decompose(Less, -1);
12459
12460 // Check whether all the non-constants cancel out, or reduce to new
12461 // More/Less values.
12462 const SCEV *NewMore = nullptr, *NewLess = nullptr;
12463 for (const auto &[S, Mul] : Multiplicity) {
12464 if (Mul == 0)
12465 continue;
12466 if (Mul == 1) {
12467 if (NewMore)
12468 return std::nullopt;
12469 NewMore = S;
12470 } else if (Mul == -1) {
12471 if (NewLess)
12472 return std::nullopt;
12473 NewLess = S;
12474 } else
12475 return std::nullopt;
12476 }
12477
12478 // Values stayed the same, no point in trying further.
12479 if (NewMore == More || NewLess == Less)
12480 return std::nullopt;
12481
12482 More = NewMore;
12483 Less = NewLess;
12484
12485 // Reduced to constant.
12486 if (!More && !Less)
12487 return Diff;
12488
12489 // Left with variable on only one side, bail out.
12490 if (!More || !Less)
12491 return std::nullopt;
12492 }
12493
12494 // Did not reduce to constant.
12495 return std::nullopt;
12496}
12497
12498bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
12499 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12500 const SCEV *FoundRHS, const Instruction *CtxI) {
12501 // Try to recognize the following pattern:
12502 //
12503 // FoundRHS = ...
12504 // ...
12505 // loop:
12506 // FoundLHS = {Start,+,W}
12507 // context_bb: // Basic block from the same loop
12508 // known(Pred, FoundLHS, FoundRHS)
12509 //
12510 // If some predicate is known in the context of a loop, it is also known on
12511 // each iteration of this loop, including the first iteration. Therefore, in
12512 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
12513 // prove the original pred using this fact.
12514 if (!CtxI)
12515 return false;
12516 const BasicBlock *ContextBB = CtxI->getParent();
12517 // Make sure AR varies in the context block.
12518 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
12519 const Loop *L = AR->getLoop();
12520 const auto *Latch = L->getLoopLatch();
12521 // Make sure that context belongs to the loop and executes on 1st iteration
12522 // (if it ever executes at all).
12523 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12524 return false;
12525 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
12526 return false;
12527 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
12528 }
12529
12530 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
12531 const Loop *L = AR->getLoop();
12532 const auto *Latch = L->getLoopLatch();
12533 // Make sure that context belongs to the loop and executes on 1st iteration
12534 // (if it ever executes at all).
12535 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12536 return false;
12537 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
12538 return false;
12539 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
12540 }
12541
12542 return false;
12543}
12544
12545bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(CmpPredicate Pred,
12546 const SCEV *LHS,
12547 const SCEV *RHS,
12548 const SCEV *FoundLHS,
12549 const SCEV *FoundRHS) {
12550 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
12551 return false;
12552
12553 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
12554 if (!AddRecLHS)
12555 return false;
12556
12557 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12558 if (!AddRecFoundLHS)
12559 return false;
12560
12561 // We'd like to let SCEV reason about control dependencies, so we constrain
12562 // both the inequalities to be about add recurrences on the same loop. This
12563 // way we can use isLoopEntryGuardedByCond later.
12564
12565 const Loop *L = AddRecFoundLHS->getLoop();
12566 if (L != AddRecLHS->getLoop())
12567 return false;
12568
12569 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
12570 //
12571 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
12572 // ... (2)
12573 //
12574 // Informal proof for (2), assuming (1) [*]:
12575 //
12576 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
12577 //
12578 // Then
12579 //
12580 // FoundLHS s< FoundRHS s< INT_MIN - C
12581 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
12582 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
12583 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
12584 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
12585 // <=> FoundLHS + C s< FoundRHS + C
12586 //
12587 // [*]: (1) can be proved by ruling out overflow.
12588 //
12589 // [**]: This can be proved by analyzing all the four possibilities:
12590 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
12591 // (A s>= 0, B s>= 0).
12592 //
12593 // Note:
12594 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
12595 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
12596 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
12597 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
12598 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
12599 // C)".
12600
12601 std::optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
12602 if (!LDiff)
12603 return false;
12604 std::optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
12605 if (!RDiff || *LDiff != *RDiff)
12606 return false;
12607
12608 if (LDiff->isMinValue())
12609 return true;
12610
12611 APInt FoundRHSLimit;
12612
12613 if (Pred == CmpInst::ICMP_ULT) {
12614 FoundRHSLimit = -(*RDiff);
12615 } else {
12616 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
12617 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
12618 }
12619
12620 // Try to prove (1) or (2), as needed.
12621 return isAvailableAtLoopEntry(FoundRHS, L) &&
12622 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
12623 getConstant(FoundRHSLimit));
12624}
12625
12626bool ScalarEvolution::isImpliedViaMerge(CmpPredicate Pred, const SCEV *LHS,
12627 const SCEV *RHS, const SCEV *FoundLHS,
12628 const SCEV *FoundRHS, unsigned Depth) {
12629 const PHINode *LPhi = nullptr, *RPhi = nullptr;
12630
12631 llvm::scope_exit ClearOnExit([&]() {
12632 if (LPhi) {
12633 bool Erased = PendingMerges.erase(LPhi);
12634 assert(Erased && "Failed to erase LPhi!");
12635 (void)Erased;
12636 }
12637 if (RPhi) {
12638 bool Erased = PendingMerges.erase(RPhi);
12639 assert(Erased && "Failed to erase RPhi!");
12640 (void)Erased;
12641 }
12642 });
12643
12644 // Find respective Phis and check that they are not being pending.
12645 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
12646 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
12647 if (!PendingMerges.insert(Phi).second)
12648 return false;
12649 LPhi = Phi;
12650 }
12651 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
12652 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
12653 // If we detect a loop of Phi nodes being processed by this method, for
12654 // example:
12655 //
12656 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
12657 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
12658 //
12659 // we don't want to deal with a case that complex, so return conservative
12660 // answer false.
12661 if (!PendingMerges.insert(Phi).second)
12662 return false;
12663 RPhi = Phi;
12664 }
12665
12666 // If none of LHS, RHS is a Phi, nothing to do here.
12667 if (!LPhi && !RPhi)
12668 return false;
12669
12670 // If there is a SCEVUnknown Phi we are interested in, make it left.
12671 if (!LPhi) {
12672 std::swap(LHS, RHS);
12673 std::swap(FoundLHS, FoundRHS);
12674 std::swap(LPhi, RPhi);
12676 }
12677
12678 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
12679 const BasicBlock *LBB = LPhi->getParent();
12680 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12681
12682 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
12683 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
12684 isImpliedCondOperandsViaRanges(Pred, S1, S2, Pred, FoundLHS, FoundRHS) ||
12685 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
12686 };
12687
12688 if (RPhi && RPhi->getParent() == LBB) {
12689 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
12690 // If we compare two Phis from the same block, and for each entry block
12691 // the predicate is true for incoming values from this block, then the
12692 // predicate is also true for the Phis.
12693 for (const BasicBlock *IncBB : predecessors(LBB)) {
12694 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12695 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
12696 if (!ProvedEasily(L, R))
12697 return false;
12698 }
12699 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
12700 // Case two: RHS is also a Phi from the same basic block, and it is an
12701 // AddRec. It means that there is a loop which has both AddRec and Unknown
12702 // PHIs, for it we can compare incoming values of AddRec from above the loop
12703 // and latch with their respective incoming values of LPhi.
12704 // TODO: Generalize to handle loops with many inputs in a header.
12705 if (LPhi->getNumIncomingValues() != 2) return false;
12706
12707 auto *RLoop = RAR->getLoop();
12708 auto *Predecessor = RLoop->getLoopPredecessor();
12709 assert(Predecessor && "Loop with AddRec with no predecessor?");
12710 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
12711 if (!ProvedEasily(L1, RAR->getStart()))
12712 return false;
12713 auto *Latch = RLoop->getLoopLatch();
12714 assert(Latch && "Loop with AddRec with no latch?");
12715 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
12716 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
12717 return false;
12718 } else {
12719 // In all other cases go over inputs of LHS and compare each of them to RHS,
12720 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
12721 // At this point RHS is either a non-Phi, or it is a Phi from some block
12722 // different from LBB.
12723 for (const BasicBlock *IncBB : predecessors(LBB)) {
12724 // Check that RHS is available in this block.
12725 if (!dominates(RHS, IncBB))
12726 return false;
12727 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12728 // Make sure L does not refer to a value from a potentially previous
12729 // iteration of a loop.
12730 if (!properlyDominates(L, LBB))
12731 return false;
12732 // Addrecs are considered to properly dominate their loop, so are missed
12733 // by the previous check. Discard any values that have computable
12734 // evolution in this loop.
12735 if (auto *Loop = LI.getLoopFor(LBB))
12737 return false;
12738 if (!ProvedEasily(L, RHS))
12739 return false;
12740 }
12741 }
12742 return true;
12743}
12744
12745bool ScalarEvolution::isImpliedCondOperandsViaShift(CmpPredicate Pred,
12746 const SCEV *LHS,
12747 const SCEV *RHS,
12748 const SCEV *FoundLHS,
12749 const SCEV *FoundRHS) {
12750 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make
12751 // sure that we are dealing with same LHS.
12752 if (RHS == FoundRHS) {
12753 std::swap(LHS, RHS);
12754 std::swap(FoundLHS, FoundRHS);
12756 }
12757 if (LHS != FoundLHS)
12758 return false;
12759
12760 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
12761 if (!SUFoundRHS)
12762 return false;
12763
12764 Value *Shiftee, *ShiftValue;
12765
12766 using namespace PatternMatch;
12767 if (match(SUFoundRHS->getValue(),
12768 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
12769 auto *ShifteeS = getSCEV(Shiftee);
12770 // Prove one of the following:
12771 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
12772 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
12773 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12774 // ---> LHS <s RHS
12775 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12776 // ---> LHS <=s RHS
12777 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
12778 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
12779 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
12780 if (isKnownNonNegative(ShifteeS))
12781 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
12782 }
12783
12784 return false;
12785}
12786
12787bool ScalarEvolution::isImpliedCondOperandsViaMatchingDiff(
12788 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12789 const SCEV *FoundRHS) {
12790 // Only valid for equality predicates: (A == B) implies (C == D) when
12791 // the SCEV difference A - B equals C - D (they check the same
12792 // underlying relationship at every iteration).
12793 if (!ICmpInst::isEquality(Pred))
12794 return false;
12795
12796 // Restrict to cases involving loop recurrences - that's where this
12797 // pattern arises (correlated IV comparisons). This avoids calling
12798 // getMinusSCEV on arbitrary non-loop expressions.
12800 (!isa<SCEVAddRecExpr>(FoundLHS) && !isa<SCEVAddRecExpr>(FoundRHS)))
12801 return false;
12802
12803 // AddRecs from different loops can never produce matching differences.
12804 const SCEVAddRecExpr *QueryAddRec = dyn_cast<SCEVAddRecExpr>(LHS);
12805 if (!QueryAddRec)
12806 QueryAddRec = cast<SCEVAddRecExpr>(RHS);
12807 const SCEVAddRecExpr *FoundAddRec = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12808 if (!FoundAddRec)
12809 FoundAddRec = cast<SCEVAddRecExpr>(FoundRHS);
12810 if (QueryAddRec->getLoop() != FoundAddRec->getLoop())
12811 return false;
12812
12813 // If the strides differ, the differences can never match.
12814 if (QueryAddRec->getStepRecurrence(*this) !=
12815 FoundAddRec->getStepRecurrence(*this))
12816 return false;
12817
12818 // Compute differences. For pointer-typed operands sharing the same base,
12819 // getMinusSCEV strips the common base and returns an integer SCEV.
12820 // For example, {base,+,8} - (base+8*n) = {-8n,+,8}
12821 const SCEV *FoundDiff = getMinusSCEV(FoundLHS, FoundRHS);
12822 if (isa<SCEVCouldNotCompute>(FoundDiff))
12823 return false;
12824
12825 const SCEV *Diff = getMinusSCEV(LHS, RHS);
12826 if (isa<SCEVCouldNotCompute>(Diff))
12827 return false;
12828
12829 return Diff == FoundDiff;
12830}
12831
12832bool ScalarEvolution::isImpliedCondOperands(CmpPredicate Pred, const SCEV *LHS,
12833 const SCEV *RHS,
12834 const SCEV *FoundLHS,
12835 const SCEV *FoundRHS,
12836 const Instruction *CtxI) {
12837 return isImpliedCondOperandsViaRanges(Pred, LHS, RHS, Pred, FoundLHS,
12838 FoundRHS) ||
12839 isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS,
12840 FoundRHS) ||
12841 isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS) ||
12842 isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12843 CtxI) ||
12844 isImpliedCondOperandsViaMatchingDiff(Pred, LHS, RHS, FoundLHS,
12845 FoundRHS) ||
12846 isImpliedCondOperandsHelper(Pred, LHS, RHS, FoundLHS, FoundRHS);
12847}
12848
12849/// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
12850template <typename MinMaxExprType>
12851static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
12852 const SCEV *Candidate) {
12853 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12854 if (!MinMaxExpr)
12855 return false;
12856
12857 return is_contained(MinMaxExpr->operands(), Candidate);
12858}
12859
12861 CmpPredicate Pred, const SCEV *LHS,
12862 const SCEV *RHS) {
12863 // If both sides are affine addrecs for the same loop, with equal
12864 // steps, and we know the recurrences don't wrap, then we only
12865 // need to check the predicate on the starting values.
12866
12867 if (!ICmpInst::isRelational(Pred))
12868 return false;
12869
12870 const SCEV *LStart, *RStart, *Step;
12871 const Loop *L;
12872 if (!match(LHS,
12873 m_scev_AffineAddRec(m_SCEV(LStart), m_SCEV(Step), m_Loop(L))) ||
12875 m_SpecificLoop(L))))
12876 return false;
12880 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
12881 return false;
12882
12883 return SE.isKnownPredicate(Pred, LStart, RStart);
12884}
12885
12886/// Is LHS `Pred` RHS true because one of them is an AddRec that is known not to
12887/// go below its own start value?
12889 CmpPredicate Pred,
12890 const SCEV *LHS,
12891 const SCEV *RHS) {
12892 // Normalize to (AddRec Pred Start).
12895 std::swap(LHS, RHS);
12896 }
12897
12898 // The recurrence is equal to Start in the first iteration, so only the
12899 // non-strict predicate holds.
12900 if (Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE)
12901 return false;
12902
12903 const auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
12904 if (!AR || AR->getStart() != RHS)
12905 return false;
12906
12907 return SE.getMonotonicPredicateType(AR, Pred) ==
12909}
12910
12911/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
12912/// expression?
12914 const SCEV *LHS, const SCEV *RHS) {
12915 switch (Pred) {
12916 default:
12917 return false;
12918
12919 case ICmpInst::ICMP_SGE:
12920 std::swap(LHS, RHS);
12921 [[fallthrough]];
12922 case ICmpInst::ICMP_SLE:
12923 return
12924 // min(A, ...) <= A
12926 // A <= max(A, ...)
12928
12929 case ICmpInst::ICMP_UGE:
12930 std::swap(LHS, RHS);
12931 [[fallthrough]];
12932 case ICmpInst::ICMP_ULE:
12933 return
12934 // min(A, ...) <= A
12935 // FIXME: what about umin_seq?
12937 // A <= max(A, ...)
12939
12940 case ICmpInst::ICMP_UGT:
12941 std::swap(LHS, RHS);
12942 [[fallthrough]];
12943 case ICmpInst::ICMP_ULT:
12944 // umin(Ops) u<= each Op, so proving Op u< RHS for any Op proves
12945 // umin(Ops) u< RHS.
12946 //
12947 // Use computeConstantDifference instead of the more powerful
12948 // isKnownPredicate to keep this check cheap: isKnownPredicateViaMinOrMax
12949 // is called from isKnownViaNonRecursiveReasoning, so recursing into
12950 // the full predicate prover would be expensive.
12951 if (const auto *Min = dyn_cast<SCEVUMinExpr>(LHS)) {
12952 for (SCEVUse Op : Min->operands()) {
12953 std::optional<APInt> Diff = SE.computeConstantDifference(RHS, Op);
12954 // When Op and RHS share a common base differing by a
12955 // constant offset D (RHS - Op = D), Op u< RHS holds iff D != 0 and
12956 // RHS >= D (unsigned), i.e. the subtraction doesn't underflow.
12957 if (Diff && !Diff->isZero() && SE.getUnsignedRangeMin(RHS).uge(*Diff))
12958 return true;
12959 }
12960 }
12961 return false;
12962 }
12963
12964 llvm_unreachable("covered switch fell through?!");
12965}
12966
12967bool ScalarEvolution::isImpliedViaOperations(CmpPredicate Pred, const SCEV *LHS,
12968 const SCEV *RHS,
12969 const SCEV *FoundLHS,
12970 const SCEV *FoundRHS,
12971 unsigned Depth) {
12974 "LHS and RHS have different sizes?");
12975 assert(getTypeSizeInBits(FoundLHS->getType()) ==
12976 getTypeSizeInBits(FoundRHS->getType()) &&
12977 "FoundLHS and FoundRHS have different sizes?");
12978 // We want to avoid hurting the compile time with analysis of too big trees.
12980 return false;
12981
12982 // We only want to work with GT comparison so far.
12983 if (ICmpInst::isLT(Pred)) {
12985 std::swap(LHS, RHS);
12986 std::swap(FoundLHS, FoundRHS);
12987 }
12988
12990
12991 // For unsigned, try to reduce it to corresponding signed comparison.
12992 if (P == ICmpInst::ICMP_UGT)
12993 // We can replace unsigned predicate with its signed counterpart if all
12994 // involved values are non-negative.
12995 // TODO: We could have better support for unsigned.
12996 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
12997 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
12998 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
12999 // use this fact to prove that LHS and RHS are non-negative.
13000 const SCEV *MinusOne = getMinusOne(LHS->getType());
13001 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
13002 FoundRHS) &&
13003 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
13004 FoundRHS))
13006 }
13007
13008 if (P != ICmpInst::ICMP_SGT)
13009 return false;
13010
13011 auto GetOpFromSExt = [&](const SCEV *S) -> const SCEV * {
13012 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
13013 return Ext->getOperand();
13014 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
13015 // the constant in some cases.
13016 return S;
13017 };
13018
13019 // Acquire values from extensions.
13020 auto *OrigLHS = LHS;
13021 auto *OrigFoundLHS = FoundLHS;
13022 LHS = GetOpFromSExt(LHS);
13023 FoundLHS = GetOpFromSExt(FoundLHS);
13024
13025 // Is the SGT predicate can be proved trivially or using the found context.
13026 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
13027 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
13028 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
13029 FoundRHS, Depth + 1);
13030 };
13031
13032 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
13033 // We want to avoid creation of any new non-constant SCEV. Since we are
13034 // going to compare the operands to RHS, we should be certain that we don't
13035 // need any size extensions for this. So let's decline all cases when the
13036 // sizes of types of LHS and RHS do not match.
13037 // TODO: Maybe try to get RHS from sext to catch more cases?
13039 return false;
13040
13041 // Should not overflow.
13042 if (!LHSAddExpr->hasNoSignedWrap())
13043 return false;
13044
13045 SCEVUse LL = LHSAddExpr->getOperand(0);
13046 SCEVUse LR = LHSAddExpr->getOperand(1);
13047 auto *MinusOne = getMinusOne(RHS->getType());
13048
13049 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
13050 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
13051 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
13052 };
13053 // Try to prove the following rule:
13054 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
13055 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
13056 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
13057 return true;
13058 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
13059 Value *LL, *LR;
13060 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
13061
13062 using namespace llvm::PatternMatch;
13063
13064 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
13065 // Rules for division.
13066 // We are going to perform some comparisons with Denominator and its
13067 // derivative expressions. In general case, creating a SCEV for it may
13068 // lead to a complex analysis of the entire graph, and in particular it
13069 // can request trip count recalculation for the same loop. This would
13070 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
13071 // this, we only want to create SCEVs that are constants in this section.
13072 // So we bail if Denominator is not a constant.
13073 if (!isa<ConstantInt>(LR))
13074 return false;
13075
13076 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
13077
13078 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
13079 // then a SCEV for the numerator already exists and matches with FoundLHS.
13080 auto *Numerator = getExistingSCEV(LL);
13081 if (!Numerator || Numerator->getType() != FoundLHS->getType())
13082 return false;
13083
13084 // Make sure that the numerator matches with FoundLHS and the denominator
13085 // is positive.
13086 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
13087 return false;
13088
13089 auto *DTy = Denominator->getType();
13090 auto *FRHSTy = FoundRHS->getType();
13091 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
13092 // One of types is a pointer and another one is not. We cannot extend
13093 // them properly to a wider type, so let us just reject this case.
13094 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
13095 // to avoid this check.
13096 return false;
13097
13098 // Given that:
13099 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
13100 auto *WTy = getWiderType(DTy, FRHSTy);
13101 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
13102 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
13103
13104 // Try to prove the following rule:
13105 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
13106 // For example, given that FoundLHS > 2. It means that FoundLHS is at
13107 // least 3. If we divide it by Denominator < 4, we will have at least 1.
13108 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
13109 if (isKnownNonPositive(RHS) &&
13110 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
13111 return true;
13112
13113 // Try to prove the following rule:
13114 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
13115 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
13116 // If we divide it by Denominator > 2, then:
13117 // 1. If FoundLHS is negative, then the result is 0.
13118 // 2. If FoundLHS is non-negative, then the result is non-negative.
13119 // Anyways, the result is non-negative.
13120 auto *MinusOne = getMinusOne(WTy);
13121 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
13122 if (isKnownNegative(RHS) &&
13123 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
13124 return true;
13125 }
13126 }
13127
13128 // If our expression contained SCEVUnknown Phis, and we split it down and now
13129 // need to prove something for them, try to prove the predicate for every
13130 // possible incoming values of those Phis.
13131 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
13132 return true;
13133
13134 return false;
13135}
13136
13138 const SCEV *RHS) {
13139 // zext x u<= sext x, sext x s<= zext x
13140 const SCEV *Op;
13141 switch (Pred) {
13142 case ICmpInst::ICMP_SGE:
13143 std::swap(LHS, RHS);
13144 [[fallthrough]];
13145 case ICmpInst::ICMP_SLE: {
13146 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt.
13147 return match(LHS, m_scev_SExt(m_SCEV(Op))) &&
13149 }
13150 case ICmpInst::ICMP_UGE:
13151 std::swap(LHS, RHS);
13152 [[fallthrough]];
13153 case ICmpInst::ICMP_ULE: {
13154 // If operand >=u 0 then ZExt == SExt. If operand <u 0 then ZExt <u SExt.
13155 return match(LHS, m_scev_ZExt(m_SCEV(Op))) &&
13157 }
13158 default:
13159 return false;
13160 };
13161 llvm_unreachable("unhandled case");
13162}
13163
13164bool ScalarEvolution::isKnownViaNonRecursiveReasoning(CmpPredicate Pred,
13165 SCEVUse LHS,
13166 SCEVUse RHS) {
13167 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
13168 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
13169 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
13170 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
13172 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
13173}
13174
13175bool ScalarEvolution::isImpliedCondOperandsHelper(CmpPredicate Pred,
13176 const SCEV *LHS,
13177 const SCEV *RHS,
13178 const SCEV *FoundLHS,
13179 const SCEV *FoundRHS) {
13180 switch (Pred) {
13181 default:
13182 llvm_unreachable("Unexpected CmpPredicate value!");
13183 case ICmpInst::ICMP_EQ:
13184 case ICmpInst::ICMP_NE:
13185 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
13186 return true;
13187 break;
13188 case ICmpInst::ICMP_SLT:
13189 case ICmpInst::ICMP_SLE:
13190 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
13191 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
13192 return true;
13193 break;
13194 case ICmpInst::ICMP_SGT:
13195 case ICmpInst::ICMP_SGE:
13196 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
13197 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
13198 return true;
13199 break;
13200 case ICmpInst::ICMP_ULT:
13201 case ICmpInst::ICMP_ULE:
13202 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
13203 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
13204 return true;
13205 break;
13206 case ICmpInst::ICMP_UGT:
13207 case ICmpInst::ICMP_UGE:
13208 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
13209 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
13210 return true;
13211 break;
13212 }
13213
13214 // Maybe it can be proved via operations?
13215 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
13216 return true;
13217
13218 return false;
13219}
13220
13221bool ScalarEvolution::isImpliedCondOperandsViaRanges(
13222 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, CmpPredicate FoundPred,
13223 const SCEV *FoundLHS, const SCEV *FoundRHS) {
13224 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
13225 // The restriction on `FoundRHS` be lifted easily -- it exists only to
13226 // reduce the compile time impact of this optimization.
13227 return false;
13228
13229 std::optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
13230 if (!Addend)
13231 return false;
13232
13233 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
13234
13235 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
13236 // antecedent "`FoundLHS` `FoundPred` `FoundRHS`".
13237 ConstantRange FoundLHSRange =
13238 ConstantRange::makeExactICmpRegion(FoundPred, ConstFoundRHS);
13239
13240 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
13241 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
13242
13243 // We can also compute the range of values for `LHS` that satisfy the
13244 // consequent, "`LHS` `Pred` `RHS`":
13245 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
13246 // The antecedent implies the consequent if every value of `LHS` that
13247 // satisfies the antecedent also satisfies the consequent.
13248 return LHSRange.icmp(Pred, ConstRHS);
13249}
13250
13251bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
13252 bool IsSigned, bool Invert) {
13253 assert(isKnownPositive(Stride) && "Positive stride expected!");
13254
13255 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13256 const SCEV *One = getOne(Stride->getType());
13257
13258 if (IsSigned) {
13259 APInt MaxRHS = getRangeMax(RHS, /*IsSigned=*/true, Invert);
13260 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
13261 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13262
13263 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
13264 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
13265 }
13266
13267 APInt MaxRHS = getRangeMax(RHS, /*IsSigned=*/false, Invert);
13268 APInt MaxValue = APInt::getMaxValue(BitWidth);
13269 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13270
13271 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
13272 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
13273}
13274
13276 // umin(N, 1) + floor((N - umin(N, 1)) / D)
13277 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
13278 // expression fixes the case of N=0.
13279 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
13280 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
13281 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
13282}
13283
13284const SCEV *
13285ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, const SCEV *Stride,
13286 const SCEV *End, unsigned BitWidth,
13287 bool IsSigned, bool Invert) {
13288 // The logic in this function assumes we can represent a positive stride.
13289 // If we can't, the backedge-taken count must be zero.
13290 if (IsSigned && BitWidth == 1)
13291 return getZero(Stride->getType());
13292
13293 // This code below only been closely audited for negative strides in the
13294 // unsigned comparison case, it may be correct for signed comparison, but
13295 // that needs to be established.
13296 if (IsSigned && isKnownNegative(Stride))
13297 return getCouldNotCompute();
13298
13299 // Calculate the maximum backedge count based on the range of values
13300 // permitted by Start, End, and Stride. If Invert is true, both Start and End
13301 // need inverting. Stride was already negated by the caller.
13302 APInt MinStart = getRangeMin(Start, IsSigned, Invert);
13303
13304 APInt MinStride =
13305 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
13306
13307 // We assume either the stride is positive, or the backedge-taken count
13308 // is zero. So force StrideForMaxBECount to be at least one.
13309 APInt One(BitWidth, 1);
13310 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
13311 : APIntOps::umax(One, MinStride);
13312
13313 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
13314 : APInt::getMaxValue(BitWidth);
13315 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
13316
13317 // Although End can be a MAX expression we estimate MaxEnd considering only
13318 // the case End = RHS of the loop termination condition. This is safe because
13319 // in the other case (End - Start) is zero, leading to a zero maximum backedge
13320 // taken count.
13321 APInt MaxEnd = getRangeMax(End, IsSigned, Invert);
13322 MaxEnd =
13323 IsSigned ? APIntOps::smin(MaxEnd, Limit) : APIntOps::umin(MaxEnd, Limit);
13324
13325 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
13326 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
13327 : APIntOps::umax(MaxEnd, MinStart);
13328
13329 APInt Delta = MaxEnd - MinStart;
13330
13331 // Try to refine Delta in case End - Start (or Start - End if Invert) gives a
13332 // tighter bound after folding.
13333 const SCEV *DeltaExpr =
13334 Invert ? getMinusSCEV(Start, End) : getMinusSCEV(End, Start);
13335 Delta = APIntOps::umin(Delta, getUnsignedRangeMax(DeltaExpr));
13336
13337 return getUDivCeilSCEV(getConstant(Delta), getConstant(StrideForMaxBECount));
13338}
13339
13341ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
13342 const Loop *L, bool IsSigned, bool Invert,
13343 bool ControlsOnlyExit, bool AllowPredicates) {
13345
13346 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
13347
13348 // FIXME: Extend the non-invariant RHS analysis to greater-than comparisons.
13349 if (Invert && !isLoopInvariant(RHS, L))
13350 return getCouldNotCompute();
13351
13353 bool PredicatedIV = false;
13354 // FIXME: Generalize the NUW inference below to decreasing IVs.
13355 if (!IV && !Invert) {
13356 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
13357 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
13358 if (AR && AR->getLoop() == L && AR->isAffine()) {
13359 auto canProveNUW = [&]() {
13360 // We can use the comparison to infer no-wrap flags only if it fully
13361 // controls the loop exit.
13362 if (!ControlsOnlyExit)
13363 return false;
13364
13365 if (!isLoopInvariant(RHS, L))
13366 return false;
13367
13368 if (!isKnownNonZero(AR->getStepRecurrence(*this)))
13369 // We need the sequence defined by AR to strictly increase in the
13370 // unsigned integer domain for the logic below to hold.
13371 return false;
13372
13373 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
13374 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
13375 // If RHS <=u Limit, then there must exist a value V in the sequence
13376 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
13377 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned
13378 // overflow occurs. This limit also implies that a signed comparison
13379 // (in the wide bitwidth) is equivalent to an unsigned comparison as
13380 // the high bits on both sides must be zero.
13381 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
13382 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
13383 Limit = Limit.zext(OuterBitWidth);
13384 return getUnsignedRangeMax(applyLoopGuards(RHS, Guards)).ule(Limit);
13385 };
13386 auto Flags = AR->getNoWrapFlags();
13387 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
13388 Flags = setFlags(Flags, SCEV::FlagNUW);
13389
13390 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
13391 if (AR->hasNoUnsignedWrap()) {
13392 // Emulate what getZeroExtendExpr would have done during construction
13393 // if we'd been able to infer the fact just above at that time.
13394 const SCEV *Step = AR->getStepRecurrence(*this);
13395 Type *Ty = ZExt->getType();
13396 const SCEV *S = getAddRecExpr(
13398 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
13400 }
13401 }
13402 }
13403 }
13404
13405 if (!IV && AllowPredicates) {
13406 // Try to make this an AddRec using runtime tests, in the first X
13407 // iterations of this loop, where X is the SCEV expression found by the
13408 // algorithm below.
13409 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13410 PredicatedIV = true;
13411 }
13412
13413 // Avoid weird loops
13414 if (!IV || IV->getLoop() != L || !IV->isAffine())
13415 return getCouldNotCompute();
13416
13417 // A precondition of this method is that the condition being analyzed
13418 // reaches an exiting branch which dominates the latch. Given that, we can
13419 // assume that an increment which violates the nowrap specification and
13420 // produces poison must cause undefined behavior when the resulting poison
13421 // value is branched upon and thus we can conclude that the backedge is
13422 // taken no more often than would be required to produce that poison value.
13423 // Note that a well defined loop can exit on the iteration which violates
13424 // the nowrap specification if there is another exit (either explicit or
13425 // implicit/exceptional) which causes the loop to execute before the
13426 // exiting instruction we're analyzing would trigger UB.
13427 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13428 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13429 // Reverse the ordering for greater-than comparisons.
13431 if (Invert)
13433
13434 // The step of ~IV is the negated step of IV.
13435 const SCEV *Stride = IV->getStepRecurrence(*this);
13436 if (Invert)
13437 Stride = getNegativeSCEV(Stride);
13438 const SCEV *GuardedStride = Stride;
13439
13440 // Whether the IV may reach the maximum (or minimum if inverted) value
13441 // before the exit is taken.
13442 bool IVMayOverflow = true;
13443
13444 bool PositiveStride = isKnownPositive(Stride);
13445 // A dominating guard may prove the stride positive.
13446 if (!PositiveStride) {
13447 const SCEV *LoopGuardedStride = applyLoopGuards(Stride, Guards);
13448 if (isKnownPositive(LoopGuardedStride)) {
13449 GuardedStride = LoopGuardedStride;
13450 PositiveStride = true;
13451 // Encode the context-sensitive stride > 0 fact into the expression
13452 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13453 }
13454 }
13455
13456 // Avoid negative or zero stride values.
13457 if (!PositiveStride) {
13458 // FIXME: Generalize the unknown-stride analysis to decreasing IVs.
13459 if (Invert)
13460 return getCouldNotCompute();
13461
13462 // We can compute the correct backedge taken count for loops with unknown
13463 // strides if we can prove that the loop is not an infinite loop with side
13464 // effects. Here's the loop structure we are trying to handle -
13465 //
13466 // i = start
13467 // do {
13468 // A[i] = i;
13469 // i += s;
13470 // } while (i < end);
13471 //
13472 // The backedge taken count for such loops is evaluated as -
13473 // (max(end, start + stride) - start - 1) /u stride
13474 //
13475 // The additional preconditions that we need to check to prove correctness
13476 // of the above formula is as follows -
13477 //
13478 // a) IV is either nuw or nsw depending upon signedness (indicated by the
13479 // NoWrap flag).
13480 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13481 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13482 // no side effects within the loop) or a predicate is added to ensure
13483 // stride is positive.
13484 // c) loop has a single static exit (with no abnormal exits)
13485 //
13486 // Precondition a) implies that if the stride is negative, this is a single
13487 // trip loop. The backedge taken count formula reduces to zero in this case.
13488 //
13489 // Precondition b) and c) combine to imply that if rhs is invariant in L,
13490 // then a zero stride means the backedge can't be taken without executing
13491 // undefined behavior.
13492 //
13493 // The positive stride case is the same as isKnownPositive(Stride) returning
13494 // true (original behavior of the function).
13495 //
13496 if (PredicatedIV || !NoWrap || !loopHasNoAbnormalExits(L))
13497 return getCouldNotCompute();
13498
13499 if (!loopIsFiniteByAssumption(L)) {
13500 // If the loop may be infinite, add a predicate ensuring Stride is
13501 // positive, to guarantee forward progress.
13502 if (!AllowPredicates || !isLoopInvariant(Stride, L))
13503 return getCouldNotCompute();
13504
13505 const SCEV *Zero = getZero(Stride->getType());
13506 const SCEVPredicate *P =
13508 Predicates.push_back(P);
13509 // When the predicate holds (Stride > 0), umax(Stride, 1) == Stride,
13510 // so the result is unchanged. To prevent div by zero.
13511 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13512 } else if (!isKnownNonZero(Stride)) {
13513 // If we have a step of zero, and RHS isn't invariant in L, we don't know
13514 // if it might eventually be greater than start and if so, on which
13515 // iteration. We can't even produce a useful upper bound.
13516 if (!isLoopInvariant(RHS, L))
13517 return getCouldNotCompute();
13518
13519 // We allow a potentially zero stride, but we need to divide by stride
13520 // below. Since the loop can't be infinite and this check must control
13521 // the sole exit, we can infer the exit must be taken on the first
13522 // iteration (e.g. backedge count = 0) if the stride is zero. Given that,
13523 // we know the numerator in the divides below must be zero, so we can
13524 // pick an arbitrary non-zero value for the denominator (e.g. stride)
13525 // and produce the right result.
13526 // FIXME: Handle the case where Stride is poison?
13527 auto wouldZeroStrideBeUB = [&]() {
13528 // Proof by contradiction. Suppose the stride were zero. If we can
13529 // prove that the backedge *is* taken on the first iteration, then since
13530 // we know this condition controls the sole exit, we must have an
13531 // infinite loop. We can't have a (well defined) infinite loop per
13532 // check just above.
13533 // Note: The (Start - Stride) term is used to get the start' term from
13534 // (start' + stride,+,stride). Remember that we only care about the
13535 // result of this expression when stride == 0 at runtime.
13536 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
13537 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
13538 };
13539 if (!wouldZeroStrideBeUB()) {
13540 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13541 }
13542 }
13543 } else {
13544 // Avoid proven overflow cases: this will ensure that the backedge taken
13545 // count will not generate any unsigned overflow.
13546 IVMayOverflow = canIVOverflowOnLT(RHS, GuardedStride, IsSigned, Invert);
13547 if (IVMayOverflow && !NoWrap)
13548 return getCouldNotCompute();
13549 }
13550
13551 // On all paths just preceeding, we established the following invariant:
13552 // IV can be assumed not to overflow up to and including the exiting
13553 // iteration. We proved this in one of two ways:
13554 // 1) We can show overflow doesn't occur before the exiting iteration
13555 // 1a) canIVOverflowOnLT, and b) step of one
13556 // 2) We can show that if overflow occurs, the loop must execute UB
13557 // before any possible exit.
13558 // Note that we have not yet proved RHS invariant (in general).
13559
13560 const SCEV *Start = IV->getStart();
13561
13562 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
13563 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
13564 // Use integer-typed versions for actual computation; we can't subtract
13565 // pointers in general.
13566 const SCEV *OrigStart = Start;
13567 const SCEV *OrigRHS = RHS;
13568 if (Start->getType()->isPointerTy()) {
13569 Start = getPtrToAddrExpr(Start);
13570 if (isa<SCEVCouldNotCompute>(Start))
13571 return Start;
13572 }
13573 if (RHS->getType()->isPointerTy()) {
13576 return RHS;
13577 }
13578
13579 const SCEV *End = nullptr, *BECount = getCouldNotCompute(),
13580 *BECountIfBackedgeTaken = getCouldNotCompute();
13581 if (!isLoopInvariant(RHS, L)) {
13582 assert(!Invert && "RHS must be loop-invariant for Invert");
13583 const auto *RHSAddRec = dyn_cast<SCEVAddRecExpr>(RHS);
13584 if (PositiveStride && RHSAddRec != nullptr && RHSAddRec->getLoop() == L &&
13585 any(RHSAddRec->getNoWrapFlags())) {
13586 // The structure of loop we are trying to calculate backedge count of:
13587 //
13588 // left = left_start
13589 // right = right_start
13590 //
13591 // while(left < right){
13592 // ... do something here ...
13593 // left += s1; // stride of left is s1 (s1 > 0)
13594 // right += s2; // stride of right is s2 (s2 < 0)
13595 // }
13596 //
13597
13598 const SCEV *RHSStart = RHSAddRec->getStart();
13599 const SCEV *RHSStride = RHSAddRec->getStepRecurrence(*this);
13600
13601 // If Stride - RHSStride is positive and does not overflow, we can write
13602 // backedge count as ->
13603 // ceil((End - Start) /u (Stride - RHSStride))
13604 // Where, End = max(RHSStart, Start)
13605
13606 // Check if RHSStride < 0 and Stride - RHSStride will not overflow.
13607 if (isKnownNegative(RHSStride) &&
13608 willNotOverflow(Instruction::Sub, /*Signed=*/true, Stride,
13609 RHSStride)) {
13610
13611 const SCEV *Denominator = getMinusSCEV(Stride, RHSStride);
13612 if (isKnownPositive(Denominator)) {
13613 End = IsSigned ? getSMaxExpr(RHSStart, Start)
13614 : getUMaxExpr(RHSStart, Start);
13615
13616 // We can do this because End >= Start, as End = max(RHSStart, Start)
13617 const SCEV *Delta = getMinusSCEV(End, Start);
13618
13619 BECount = getUDivCeilSCEV(Delta, Denominator);
13620 BECountIfBackedgeTaken =
13621 getUDivCeilSCEV(getMinusSCEV(RHSStart, Start), Denominator);
13622 }
13623 }
13624 }
13625 } else {
13626 // Let End = max(RHS,Start). We use the expression (End-Start)/Stride to
13627 // describe the backedge count: if the backedge is taken at least once then
13628 // End is RHS, and if not End is Start so we get a backedge count of zero.
13629 // Inverted, End is min(RHS, Start).
13630 //
13631 // AddingStrideMinusOneMayOverflow has the following preconditions:
13632 //
13633 // 1. Start <= End, signed if IsSigned (inverted: End <= Start)
13634 // 2. The index variable doesn't overflow.
13635 //
13636 // Therefore, we know N exists such that
13637 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
13638 // doesn't overflow.
13639 //
13640 // Using this information, try to prove whether the addition in
13641 // "(End - Start) + (Stride - 1)" has unsigned overflow.
13642 //
13643 // If the IV cannot overflow, RHS is at least Stride - 1 below the maximum
13644 // value, so the distance End - Start is at most UMAX - (Stride - 1) and
13645 // the (Stride - 1) addition below cannot overflow.
13646 const SCEV *One = getOne(Stride->getType());
13647 bool AddingStrideMinusOneMayOverflow = IVMayOverflow && [&] {
13648 if (isKnownToBeAPowerOfTwo(Stride)) {
13649 // Suppose Stride is a power of two, and Start/End are unsigned
13650 // integers. Let UMAX be the largest representable unsigned
13651 // integer.
13652 //
13653 // By the preconditions of this function, we know
13654 // "(Start + Stride * N) >= End", and this doesn't overflow.
13655 // As a formula:
13656 //
13657 // End <= (Start + Stride * N) <= UMAX
13658 //
13659 // Subtracting Start from all the terms:
13660 //
13661 // End - Start <= Stride * N <= UMAX - Start
13662 //
13663 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore:
13664 //
13665 // End - Start <= Stride * N <= UMAX
13666 //
13667 // Stride * N is a multiple of Stride. Therefore,
13668 //
13669 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
13670 //
13671 // Since Stride is a power of two, UMAX + 1 is divisible by
13672 // Stride. Therefore, UMAX mod Stride == Stride - 1. So we can
13673 // write:
13674 //
13675 // End - Start <= Stride * N <= UMAX - Stride - 1
13676 //
13677 // Dropping the middle term:
13678 //
13679 // End - Start <= UMAX - Stride - 1
13680 //
13681 // Adding Stride - 1 to both sides:
13682 //
13683 // (End - Start) + (Stride - 1) <= UMAX
13684 //
13685 // In other words, the addition doesn't have unsigned overflow.
13686 //
13687 // A similar proof works if we treat Start/End as signed values.
13688 // Just rewrite steps before "End - Start <= Stride * N <= UMAX"
13689 // to use signed max instead of unsigned max. Note that we're
13690 // trying to prove a lack of unsigned overflow in either case.
13691 // Inverted: "Start - End <= Stride * N <= Start - MIN <= UMAX", same.
13692 return false;
13693 }
13694 if (!Invert && (Start == Stride || Start == getMinusSCEV(Stride, One))) {
13695 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End
13696 // - 1. If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1
13697 // <u End. If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End -
13698 // 1 <s End.
13699 //
13700 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 ==
13701 // End.
13702 //
13703 // Both need Start to be the smaller value, so neither applies inverted.
13704 return false;
13705 }
13706 return true;
13707 }();
13708
13709 // If inverted, the analyzed values are complements: "~V - Offset" is "~(V +
13710 // Offset)" and "~To - ~From" is "From - To".
13711 auto StepBack = [&](const SCEV *V, const SCEV *Offset) -> const SCEV * {
13712 if (Invert)
13713 return getAddExpr(V, Offset);
13714 return getMinusSCEV(V, Offset);
13715 };
13716 auto Distance = [&](const SCEV *From, const SCEV *To) {
13717 return Invert ? getMinusSCEV(From, To) : getMinusSCEV(To, From);
13718 };
13719
13720 const SCEV *OrigPrevStart = StepBack(OrigStart, Stride);
13721 assert(isAvailableAtLoopEntry(OrigPrevStart, L) && "Must be!");
13722 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
13723 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
13724 // Can we prove Start - Stride < RHS, and either Start - Stride < Start or
13725 // (via !AddingStrideMinusOneMayOverflow) that (RHS - Start) + (Stride - 1)
13726 // does not overflow?
13727 if ((!AddingStrideMinusOneMayOverflow ||
13728 isLoopEntryGuardedByCond(L, Cond, OrigPrevStart, OrigStart)) &&
13729 isLoopEntryGuardedByCond(L, Cond, OrigPrevStart, OrigRHS)) {
13730 // In this case, we can use a refined formula for computing backedge
13731 // taken count. The general formula remains:
13732 // "End-Start /uceiling Stride"
13733 // We want to use the alternate formula:
13734 // "((RHS - 1) - (Start - Stride)) /u Stride"
13735 // Let's do a quick case analysis to show these are equivalent under
13736 // our preconditions. When inverted, the proof uses complemented Start,
13737 // RHS and End; Stride remains positive.
13738 // * For RHS <= Start (End is Start), the backedge-taken count must be
13739 // zero. Together with the precondition "Start - Stride < RHS", we have
13740 // "Start - Stride < RHS <= Start". Subtracting Start - Stride from
13741 // all sides we get "0 < RHS - (Start - Stride) <= Stride".
13742 // Subtracting 1 we get "0 <= (RHS - 1) - (Start - Stride) < Stride".
13743 // So dividing that by Stride gives zero.
13744 //
13745 // * For RHS > Start (End is RHS), the backedge count must be
13746 // "RHS-Start /uceil Stride", so it is sufficient to show that the
13747 // numerator "((RHS - 1) - (Start - Stride))" does not overflow.
13748 //
13749 // If "Start - Stride < Start" holds, we have
13750 // "RHS > Start > Start - Stride". As such
13751 // "RHS - (Start - Stride) - 1" does not overflow, which is the
13752 // reassociated numerator.
13753 //
13754 // Otherwise !AddingStrideMinusOneMayOverflow guarantees that
13755 // "(End - Start) + (Stride - 1)" does not overflow unsigned. Here
13756 // "End" is "RHS", as "RHS > Start", so this is the reassociated
13757 // numerator. Neither sub-term wraps unsigned: "RHS - Start"
13758 // due to "RHS > Start", and "Stride - 1", as Stride is non-zero.
13759 const SCEV *Numerator =
13760 getMinusSCEV(Distance(StepBack(Start, Stride), RHS), One);
13761 BECount = getUDivExpr(Numerator, Stride);
13762 }
13763
13764 if (isa<SCEVCouldNotCompute>(BECount)) {
13765 auto canProveRHSIsAtOrBeyondStart = [&]() {
13766 // Inverted, the claim is "Start >= RHS". Reverse the comparisons below
13767 // by swapping their operands rather than their predicates:
13768 // isLoopEntryGuardedByCond is sensitive to operand order and loses the
13769 // proof if the IV bound moves to the other side.
13770 auto SwapIfInverted = [&](const SCEV *A, const SCEV *B) {
13771 return Invert ? std::pair(B, A) : std::pair(A, B);
13772 };
13773
13774 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
13775 const SCEV *GuardedRHS = applyLoopGuards(OrigRHS, Guards);
13776 const SCEV *GuardedStart = applyLoopGuards(OrigStart, Guards);
13777 if (Invert)
13778 std::swap(GuardedRHS, GuardedStart);
13779
13780 auto [GELHS, GERHS] = SwapIfInverted(OrigRHS, OrigStart);
13781 if (isLoopEntryGuardedByCond(L, CondGE, GELHS, GERHS) ||
13782 isKnownPredicate(CondGE, GuardedRHS, GuardedStart))
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 : F(F), DL(F.getDataLayout()), TLI(TLI), AC(AC), DT(DT), LI(LI),
14022 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
14023 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 : F(Arg.F), DL(Arg.DL), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC),
14041 DT(Arg.DT), LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
14042 ValueExprMap(std::move(Arg.ValueExprMap)),
14043 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
14044 PendingMerges(std::move(Arg.PendingMerges)),
14045 ConstantMultipleCache(std::move(Arg.ConstantMultipleCache)),
14046 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
14047 PredicatedBackedgeTakenCounts(
14048 std::move(Arg.PredicatedBackedgeTakenCounts)),
14049 BECountUsers(std::move(Arg.BECountUsers)),
14050 ConstantEvolutionLoopExitValue(
14051 std::move(Arg.ConstantEvolutionLoopExitValue)),
14052 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
14053 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
14054 LoopDispositions(std::move(Arg.LoopDispositions)),
14055 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
14056 BlockDispositions(std::move(Arg.BlockDispositions)),
14057 SCEVUsers(std::move(Arg.SCEVUsers)),
14058 UnsignedRanges(std::move(Arg.UnsignedRanges)),
14059 SignedRanges(std::move(Arg.SignedRanges)),
14060 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
14061 UniquePreds(std::move(Arg.UniquePreds)),
14062 SCEVAllocator(std::move(Arg.SCEVAllocator)),
14063 ConstantSCEVs(std::move(Arg.ConstantSCEVs)),
14064 LoopUsers(std::move(Arg.LoopUsers)),
14065 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
14066 FirstUnknown(Arg.FirstUnknown),
14067 NextUnknownOrderID(Arg.NextUnknownOrderID) {
14068 Arg.FirstUnknown = nullptr;
14069}
14070
14072 // Iterate through all the SCEVUnknown instances and call their
14073 // destructors, so that they release their references to their values.
14074 for (SCEVUnknown *U = FirstUnknown; U;) {
14075 SCEVUnknown *Tmp = U;
14076 U = U->Next;
14077 Tmp->~SCEVUnknown();
14078 }
14079 FirstUnknown = nullptr;
14080
14081 ExprValueMap.clear();
14082 ValueExprMap.clear();
14083 HasRecMap.clear();
14084 BackedgeTakenCounts.clear();
14085 PredicatedBackedgeTakenCounts.clear();
14086
14087 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
14088 assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
14089 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
14090 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
14091}
14092
14096
14097/// When printing a top-level SCEV for trip counts, it's helpful to include
14098/// a type for constants which are otherwise hard to disambiguate.
14099static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV* S) {
14100 if (isa<SCEVConstant>(S))
14101 OS << *S->getType() << " ";
14102 OS << *S;
14103}
14104
14106 const Loop *L) {
14107 // Print all inner loops first
14108 for (Loop *I : *L)
14109 PrintLoopInfo(OS, SE, I);
14110
14111 OS << "Loop ";
14112 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14113 OS << ": ";
14114
14115 SmallVector<BasicBlock *, 8> ExitingBlocks;
14116 L->getExitingBlocks(ExitingBlocks);
14117 if (ExitingBlocks.size() != 1)
14118 OS << "<multiple exits> ";
14119
14120 auto *BTC = SE->getBackedgeTakenCount(L);
14121 if (!isa<SCEVCouldNotCompute>(BTC)) {
14122 OS << "backedge-taken count is ";
14123 PrintSCEVWithTypeHint(OS, BTC);
14124 } else
14125 OS << "Unpredictable backedge-taken count.";
14126 OS << "\n";
14127
14128 if (ExitingBlocks.size() > 1)
14129 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14130 OS << " exit count for " << ExitingBlock->getName() << ": ";
14131 const SCEV *EC = SE->getExitCount(L, ExitingBlock);
14132 PrintSCEVWithTypeHint(OS, EC);
14133 if (isa<SCEVCouldNotCompute>(EC)) {
14134 // Retry with predicates.
14136 EC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates);
14137 if (!isa<SCEVCouldNotCompute>(EC)) {
14138 OS << "\n predicated exit count for " << ExitingBlock->getName()
14139 << ": ";
14140 PrintSCEVWithTypeHint(OS, EC);
14141 OS << "\n Predicates:\n";
14142 for (const auto *P : Predicates)
14143 P->print(OS, 4);
14144 }
14145 }
14146 OS << "\n";
14147 }
14148
14149 OS << "Loop ";
14150 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14151 OS << ": ";
14152
14153 auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
14154 if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
14155 OS << "constant max backedge-taken count is ";
14156 PrintSCEVWithTypeHint(OS, ConstantBTC);
14158 OS << ", actual taken count either this or zero.";
14159 } else {
14160 OS << "Unpredictable constant max backedge-taken count. ";
14161 }
14162
14163 OS << "\n"
14164 "Loop ";
14165 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14166 OS << ": ";
14167
14168 auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
14169 if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
14170 OS << "symbolic max backedge-taken count is ";
14171 PrintSCEVWithTypeHint(OS, SymbolicBTC);
14173 OS << ", actual taken count either this or zero.";
14174 } else {
14175 OS << "Unpredictable symbolic max backedge-taken count. ";
14176 }
14177 OS << "\n";
14178
14179 if (ExitingBlocks.size() > 1)
14180 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14181 OS << " symbolic max exit count for " << ExitingBlock->getName() << ": ";
14182 auto *ExitBTC = SE->getExitCount(L, ExitingBlock,
14184 PrintSCEVWithTypeHint(OS, ExitBTC);
14185 if (isa<SCEVCouldNotCompute>(ExitBTC)) {
14186 // Retry with predicates.
14188 ExitBTC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates,
14190 if (!isa<SCEVCouldNotCompute>(ExitBTC)) {
14191 OS << "\n predicated symbolic max exit count for "
14192 << ExitingBlock->getName() << ": ";
14193 PrintSCEVWithTypeHint(OS, ExitBTC);
14194 OS << "\n Predicates:\n";
14195 for (const auto *P : Predicates)
14196 P->print(OS, 4);
14197 }
14198 }
14199 OS << "\n";
14200 }
14201
14203 auto *PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
14204 if (PBT != BTC) {
14205 OS << "Loop ";
14206 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14207 OS << ": ";
14208 if (!isa<SCEVCouldNotCompute>(PBT)) {
14209 OS << "Predicated backedge-taken count is ";
14210 PrintSCEVWithTypeHint(OS, PBT);
14211 } else
14212 OS << "Unpredictable predicated backedge-taken count.";
14213 OS << "\n";
14214 OS << " Predicates:\n";
14215 for (const auto *P : Preds)
14216 P->print(OS, 4);
14217 }
14218 Preds.clear();
14219
14220 auto *PredConstantMax =
14222 if (PredConstantMax != ConstantBTC) {
14223 OS << "Loop ";
14224 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14225 OS << ": ";
14226 if (!isa<SCEVCouldNotCompute>(PredConstantMax)) {
14227 OS << "Predicated constant max backedge-taken count is ";
14228 PrintSCEVWithTypeHint(OS, PredConstantMax);
14229 } else
14230 OS << "Unpredictable predicated constant max backedge-taken count.";
14231 OS << "\n";
14232 OS << " Predicates:\n";
14233 for (const auto *P : Preds)
14234 P->print(OS, 4);
14235 }
14236 Preds.clear();
14237
14238 auto *PredSymbolicMax =
14240 if (SymbolicBTC != PredSymbolicMax) {
14241 OS << "Loop ";
14242 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14243 OS << ": ";
14244 if (!isa<SCEVCouldNotCompute>(PredSymbolicMax)) {
14245 OS << "Predicated symbolic max backedge-taken count is ";
14246 PrintSCEVWithTypeHint(OS, PredSymbolicMax);
14247 } else
14248 OS << "Unpredictable predicated symbolic max backedge-taken count.";
14249 OS << "\n";
14250 OS << " Predicates:\n";
14251 for (const auto *P : Preds)
14252 P->print(OS, 4);
14253 }
14254
14256 OS << "Loop ";
14257 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14258 OS << ": ";
14259 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
14260 }
14261}
14262
14263namespace llvm {
14264// Note: these overloaded operators need to be in the llvm namespace for them
14265// to be resolved correctly. If we put them outside the llvm namespace, the
14266//
14267// OS << ": " << SE.getLoopDisposition(SV, InnerL);
14268//
14269// code below "breaks" and start printing raw enum values as opposed to the
14270// string values.
14273 switch (LD) {
14275 OS << "Variant";
14276 break;
14278 OS << "Invariant";
14279 break;
14281 OS << "Uniform";
14282 break;
14284 OS << "Computable";
14285 break;
14286 }
14287 return OS;
14288}
14289
14292 switch (BD) {
14294 OS << "DoesNotDominate";
14295 break;
14297 OS << "Dominates";
14298 break;
14300 OS << "ProperlyDominates";
14301 break;
14302 }
14303 return OS;
14304}
14305} // namespace llvm
14306
14308 // ScalarEvolution's implementation of the print method is to print
14309 // out SCEV values of all instructions that are interesting. Doing
14310 // this potentially causes it to create new SCEV objects though,
14311 // which technically conflicts with the const qualifier. This isn't
14312 // observable from outside the class though, so casting away the
14313 // const isn't dangerous.
14314 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14315
14316 if (ClassifyExpressions) {
14317 OS << "Classifying expressions for: ";
14318 F.printAsOperand(OS, /*PrintType=*/false);
14319 OS << "\n";
14320 for (Instruction &I : instructions(F))
14321 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
14322 OS << I << '\n';
14323 OS << " --> ";
14324 const SCEV *SV = SE.getSCEV(&I);
14325 SV->print(OS);
14326 if (!isa<SCEVCouldNotCompute>(SV)) {
14327 OS << " U: ";
14328 SE.getUnsignedRange(SV).print(OS);
14329 OS << " S: ";
14330 SE.getSignedRange(SV).print(OS);
14331 }
14332
14333 const Loop *L = LI.getLoopFor(I.getParent());
14334
14335 SCEVUse AtUse = SE.getSCEVAtScope(SV, L);
14336 if (AtUse != SV) {
14337 OS << " --> ";
14338 OS << AtUse;
14339 if (!isa<SCEVCouldNotCompute>(AtUse)) {
14340 OS << " U: ";
14341 SE.getUnsignedRange(AtUse).print(OS);
14342 OS << " S: ";
14343 SE.getSignedRange(AtUse).print(OS);
14344 }
14345 }
14346
14347 if (L) {
14348 OS << "\t\t" "Exits: ";
14349 SCEVUse ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
14350 if (!SE.isLoopInvariant(ExitValue, L)) {
14351 OS << "<<Unknown>>";
14352 } else {
14353 OS << ExitValue;
14354 }
14355
14356 ListSeparator LS(", ", "\t\tLoopDispositions: { ");
14357 for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
14358 OS << LS;
14359 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14360 OS << ": " << SE.getLoopDisposition(SV, Iter);
14361 }
14362
14363 for (const auto *InnerL : depth_first(L)) {
14364 if (InnerL == L)
14365 continue;
14366 OS << LS;
14367 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14368 OS << ": " << SE.getLoopDisposition(SV, InnerL);
14369 }
14370
14371 OS << " }";
14372 }
14373
14374 OS << "\n";
14375 }
14376 }
14377
14378 OS << "Determining loop execution counts for: ";
14379 F.printAsOperand(OS, /*PrintType=*/false);
14380 OS << "\n";
14381 for (Loop *I : LI)
14382 PrintLoopInfo(OS, &SE, I);
14383}
14384
14387 if (isa<SCEVConstant>(S))
14388 return LoopInvariant;
14389
14390 auto &Values = LoopDispositions[S];
14391 for (auto &V : Values) {
14392 if (V.getPointer() == L)
14393 return V.getInt();
14394 }
14395 Values.emplace_back(L, LoopVariant);
14396 LoopDisposition D = computeLoopDisposition(S, L);
14397 auto &Values2 = LoopDispositions[S];
14398 for (auto &V : llvm::reverse(Values2)) {
14399 if (V.getPointer() == L) {
14400 V.setInt(D);
14401 break;
14402 }
14403 }
14404 return D;
14405}
14406
14408ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
14409 switch (S->getSCEVType()) {
14410 case scConstant:
14411 case scVScale:
14412 return LoopInvariant;
14413 case scAddRecExpr: {
14414 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14415
14416 // If L is the addrec's loop, it's computable.
14417 if (AR->getLoop() == L)
14418 return LoopComputable;
14419
14420 // Add recurrences are never invariant in the function-body (null loop).
14421 if (!L)
14422 return LoopVariant;
14423
14424 // Everything that is not defined at loop entry is variant.
14425 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) {
14426 if (L->contains(AR->getLoop()) &&
14427 llvm::all_of(AR->operands(),
14428 [&](const SCEV *Op) { return isLoopUniform(Op, L); }))
14429 return LoopUniform;
14430
14431 return LoopVariant;
14432 }
14433 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
14434 " dominate the contained loop's header?");
14435
14436 // This recurrence is invariant w.r.t. L if AR's loop contains L.
14437 if (AR->getLoop()->contains(L))
14438 return LoopInvariant;
14439
14440 // This recurrence is variant w.r.t. L if any of its operands
14441 // are variant.
14442 for (SCEVUse Op : AR->operands())
14443 if (!isLoopInvariant(Op, L))
14444 return LoopVariant;
14445
14446 // Otherwise it's loop-invariant.
14447 return LoopInvariant;
14448 }
14449 case scTruncate:
14450 case scZeroExtend:
14451 case scSignExtend:
14452 case scPtrToAddr:
14453 case scAddExpr:
14454 case scMulExpr:
14455 case scUDivExpr:
14456 case scUMaxExpr:
14457 case scSMaxExpr:
14458 case scUMinExpr:
14459 case scSMinExpr:
14460 case scSequentialUMinExpr: {
14461 bool HasVarying = false;
14462 bool HasUniform = false;
14463 for (SCEVUse Op : S->operands()) {
14465 if (D == LoopVariant)
14466 return LoopVariant;
14467 if (D == LoopComputable)
14468 HasVarying = true;
14469 if (D == LoopUniform)
14470 HasUniform = true;
14471 }
14472 return HasVarying ? (HasUniform ? LoopVariant : LoopComputable)
14473 : (HasUniform ? LoopUniform : LoopInvariant);
14474 }
14475 case scUnknown:
14476 // All non-instruction values are loop invariant. All instructions are loop
14477 // invariant if they are not contained in the specified loop.
14478 // Instructions are never considered invariant in the function body
14479 // (null loop) because they are defined within the "loop".
14481 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
14482 return LoopInvariant;
14483 case scCouldNotCompute:
14484 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14485 }
14486 llvm_unreachable("Unknown SCEV kind!");
14487}
14488
14489bool ScalarEvolution::isLoopUniform(const SCEV *S, const Loop *L) {
14491 return D == LoopUniform || D == LoopInvariant;
14492}
14493
14495 return getLoopDisposition(S, L) == LoopInvariant;
14496}
14497
14499 return getLoopDisposition(S, L) == LoopComputable;
14500}
14501
14504 if (isa<SCEVConstant>(S))
14506
14507 auto &Values = BlockDispositions[S];
14508 for (auto &V : Values) {
14509 if (V.getPointer() == BB)
14510 return V.getInt();
14511 }
14512 Values.emplace_back(BB, DoesNotDominateBlock);
14513 BlockDisposition D = computeBlockDisposition(S, BB);
14514 auto &Values2 = BlockDispositions[S];
14515 for (auto &V : llvm::reverse(Values2)) {
14516 if (V.getPointer() == BB) {
14517 V.setInt(D);
14518 break;
14519 }
14520 }
14521 return D;
14522}
14523
14525ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
14526 switch (S->getSCEVType()) {
14527 case scConstant:
14528 case scVScale:
14530 case scAddRecExpr: {
14531 // This uses a "dominates" query instead of "properly dominates" query
14532 // to test for proper dominance too, because the instruction which
14533 // produces the addrec's value is a PHI, and a PHI effectively properly
14534 // dominates its entire containing block.
14535 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14536 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
14537 return DoesNotDominateBlock;
14538
14539 // Fall through into SCEVNAryExpr handling.
14540 [[fallthrough]];
14541 }
14542 case scTruncate:
14543 case scZeroExtend:
14544 case scSignExtend:
14545 case scPtrToAddr:
14546 case scAddExpr:
14547 case scMulExpr:
14548 case scUDivExpr:
14549 case scUMaxExpr:
14550 case scSMaxExpr:
14551 case scUMinExpr:
14552 case scSMinExpr:
14553 case scSequentialUMinExpr: {
14554 bool Proper = true;
14555 for (const SCEV *NAryOp : S->operands()) {
14557 if (D == DoesNotDominateBlock)
14558 return DoesNotDominateBlock;
14559 if (D == DominatesBlock)
14560 Proper = false;
14561 }
14562 return Proper ? ProperlyDominatesBlock : DominatesBlock;
14563 }
14564 case scUnknown:
14565 if (Instruction *I =
14567 if (I->getParent() == BB)
14568 return DominatesBlock;
14569 if (DT.properlyDominates(I->getParent(), BB))
14571 return DoesNotDominateBlock;
14572 }
14574 case scCouldNotCompute:
14575 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14576 }
14577 llvm_unreachable("Unknown SCEV kind!");
14578}
14579
14580bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
14581 return getBlockDisposition(S, BB) >= DominatesBlock;
14582}
14583
14586}
14587
14588void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
14589 bool Predicated) {
14590 auto &BECounts =
14591 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14592 auto It = BECounts.find(L);
14593 if (It != BECounts.end()) {
14594 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
14595 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14596 if (!isa<SCEVConstant>(S)) {
14597 auto UserIt = BECountUsers.find(S);
14598 assert(UserIt != BECountUsers.end());
14599 UserIt->second.erase({L, Predicated});
14600 }
14601 }
14602 }
14603 BECounts.erase(It);
14604 }
14605}
14606
14607void ScalarEvolution::forgetMemoizedResults(ArrayRef<SCEVUse> SCEVs) {
14608 SmallPtrSet<const SCEV *, 8> ToForget(llvm::from_range, SCEVs);
14609 SmallVector<SCEVUse, 8> Worklist(ToForget.begin(), ToForget.end());
14610
14611 while (!Worklist.empty()) {
14612 const SCEV *Curr = Worklist.pop_back_val();
14613 auto Users = SCEVUsers.find(Curr);
14614 if (Users != SCEVUsers.end())
14615 for (const auto *User : Users->second)
14616 if (ToForget.insert(User).second)
14617 Worklist.push_back(User);
14618 }
14619
14620 for (const auto *S : ToForget)
14621 forgetMemoizedResultsImpl(S);
14622
14623 PredicatedSCEVRewrites.remove_if(
14624 [&](const auto &Entry) { return ToForget.count(Entry.first.first); });
14625}
14626
14627void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
14628 LoopDispositions.erase(S);
14629 BlockDispositions.erase(S);
14630 UnsignedRanges.erase(S);
14631 SignedRanges.erase(S);
14632 HasRecMap.erase(S);
14633 ConstantMultipleCache.erase(S);
14634
14635 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
14636 UnsignedWrapViaInductionTried.erase(AR);
14637 SignedWrapViaInductionTried.erase(AR);
14638 }
14639
14640 auto ExprIt = ExprValueMap.find(S);
14641 if (ExprIt != ExprValueMap.end()) {
14642 for (Value *V : ExprIt->second) {
14643 auto ValueIt = ValueExprMap.find_as(V);
14644 if (ValueIt != ValueExprMap.end())
14645 ValueExprMap.erase(ValueIt);
14646 }
14647 ExprValueMap.erase(ExprIt);
14648 }
14649
14650 auto ScopeIt = ValuesAtScopes.find(S);
14651 if (ScopeIt != ValuesAtScopes.end()) {
14652 for (const auto &Pair : ScopeIt->second)
14653 if (!isa_and_nonnull<SCEVConstant>(Pair.second))
14654 llvm::erase(ValuesAtScopesUsers[Pair.second.getPointer()],
14655 std::make_pair(Pair.first, S));
14656 ValuesAtScopes.erase(ScopeIt);
14657 }
14658
14659 auto ScopeUserIt = ValuesAtScopesUsers.find(S);
14660 if (ScopeUserIt != ValuesAtScopesUsers.end()) {
14661 for (const auto &Pair : ScopeUserIt->second)
14662 // The recorded value at scope is a use of S, which may carry no-wrap
14663 // flags that are not part of this key.
14664 llvm::erase_if(ValuesAtScopes[Pair.second], [&](const auto &LS) {
14665 return LS.first == Pair.first && LS.second.getPointer() == S;
14666 });
14667 ValuesAtScopesUsers.erase(ScopeUserIt);
14668 }
14669
14670 auto BEUsersIt = BECountUsers.find(S);
14671 if (BEUsersIt != BECountUsers.end()) {
14672 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
14673 auto Copy = BEUsersIt->second;
14674 for (const auto &Pair : Copy)
14675 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
14676 BECountUsers.erase(BEUsersIt);
14677 }
14678
14679 auto FoldUser = FoldCacheUser.find(S);
14680 if (FoldUser != FoldCacheUser.end())
14681 for (auto &KV : FoldUser->second)
14682 FoldCache.erase(KV);
14683 FoldCacheUser.erase(S);
14684}
14685
14686void
14687ScalarEvolution::getUsedLoops(const SCEV *S,
14688 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
14689 struct FindUsedLoops {
14690 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
14691 : LoopsUsed(LoopsUsed) {}
14692 SmallPtrSetImpl<const Loop *> &LoopsUsed;
14693 bool follow(const SCEV *S) {
14694 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
14695 LoopsUsed.insert(AR->getLoop());
14696 return true;
14697 }
14698
14699 bool isDone() const { return false; }
14700 };
14701
14702 FindUsedLoops F(LoopsUsed);
14703 SCEVTraversal<FindUsedLoops>(F).visitAll(S);
14704}
14705
14706void ScalarEvolution::getReachableBlocks(
14709 Worklist.push_back(&F.getEntryBlock());
14710 while (!Worklist.empty()) {
14711 BasicBlock *BB = Worklist.pop_back_val();
14712 if (!Reachable.insert(BB).second)
14713 continue;
14714
14715 Value *Cond;
14716 BasicBlock *TrueBB, *FalseBB;
14717 if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
14718 m_BasicBlock(FalseBB)))) {
14719 if (auto *C = dyn_cast<ConstantInt>(Cond)) {
14720 Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
14721 continue;
14722 }
14723
14724 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14725 const SCEV *L = getSCEV(Cmp->getOperand(0));
14726 const SCEV *R = getSCEV(Cmp->getOperand(1));
14727 if (isKnownPredicateViaConstantRanges(Cmp->getCmpPredicate(), L, R)) {
14728 Worklist.push_back(TrueBB);
14729 continue;
14730 }
14731 if (isKnownPredicateViaConstantRanges(Cmp->getInverseCmpPredicate(), L,
14732 R)) {
14733 Worklist.push_back(FalseBB);
14734 continue;
14735 }
14736 }
14737 }
14738
14739 append_range(Worklist, successors(BB));
14740 }
14741}
14742
14744 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14745 ScalarEvolution SE2(F, TLI, AC, DT, LI);
14746
14747 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
14748
14749 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
14750 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
14751 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
14752
14753 const SCEV *visitConstant(const SCEVConstant *Constant) {
14754 return SE.getConstant(Constant->getAPInt());
14755 }
14756
14757 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14758 return SE.getUnknown(Expr->getValue());
14759 }
14760
14761 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
14762 return SE.getCouldNotCompute();
14763 }
14764 };
14765
14766 SCEVMapper SCM(SE2);
14767 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
14768 SE2.getReachableBlocks(ReachableBlocks, F);
14769
14770 auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
14771 if (containsUndefs(Old) || containsUndefs(New)) {
14772 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
14773 // not propagate undef aggressively). This means we can (and do) fail
14774 // verification in cases where a transform makes a value go from "undef"
14775 // to "undef+1" (say). The transform is fine, since in both cases the
14776 // result is "undef", but SCEV thinks the value increased by 1.
14777 return nullptr;
14778 }
14779
14780 // Unless VerifySCEVStrict is set, we only compare constant deltas.
14781 const SCEV *Delta = SE2.getMinusSCEV(Old, New);
14782 if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
14783 return nullptr;
14784
14785 return Delta;
14786 };
14787
14788 while (!LoopStack.empty()) {
14789 auto *L = LoopStack.pop_back_val();
14790 llvm::append_range(LoopStack, *L);
14791
14792 // Only verify BECounts in reachable loops. For an unreachable loop,
14793 // any BECount is legal.
14794 if (!ReachableBlocks.contains(L->getHeader()))
14795 continue;
14796
14797 // Only verify cached BECounts. Computing new BECounts may change the
14798 // results of subsequent SCEV uses.
14799 auto It = BackedgeTakenCounts.find(L);
14800 if (It == BackedgeTakenCounts.end())
14801 continue;
14802
14803 auto *CurBECount =
14804 SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
14805 auto *NewBECount = SE2.getBackedgeTakenCount(L);
14806
14807 if (CurBECount == SE2.getCouldNotCompute() ||
14808 NewBECount == SE2.getCouldNotCompute()) {
14809 // NB! This situation is legal, but is very suspicious -- whatever pass
14810 // change the loop to make a trip count go from could not compute to
14811 // computable or vice-versa *should have* invalidated SCEV. However, we
14812 // choose not to assert here (for now) since we don't want false
14813 // positives.
14814 continue;
14815 }
14816
14817 if (SE.getTypeSizeInBits(CurBECount->getType()) >
14818 SE.getTypeSizeInBits(NewBECount->getType()))
14819 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
14820 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
14821 SE.getTypeSizeInBits(NewBECount->getType()))
14822 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
14823
14824 const SCEV *Delta = GetDelta(CurBECount, NewBECount);
14825 if (Delta && !Delta->isZero()) {
14826 dbgs() << "Trip Count for " << *L << " Changed!\n";
14827 dbgs() << "Old: " << *CurBECount << "\n";
14828 dbgs() << "New: " << *NewBECount << "\n";
14829 dbgs() << "Delta: " << *Delta << "\n";
14830 std::abort();
14831 }
14832 }
14833
14834 // Collect all valid loops currently in LoopInfo.
14835 SmallPtrSet<Loop *, 32> ValidLoops;
14836 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
14837 while (!Worklist.empty()) {
14838 Loop *L = Worklist.pop_back_val();
14839 if (ValidLoops.insert(L).second)
14840 Worklist.append(L->begin(), L->end());
14841 }
14842 for (const auto &KV : ValueExprMap) {
14843#ifndef NDEBUG
14844 // Check for SCEV expressions referencing invalid/deleted loops.
14845 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14846 assert(ValidLoops.contains(AR->getLoop()) &&
14847 "AddRec references invalid loop");
14848 }
14849#endif
14850
14851 // Check that the value is also part of the reverse map.
14852 auto It = ExprValueMap.find(KV.second);
14853 if (It == ExprValueMap.end() || !It->second.contains(KV.first)) {
14854 dbgs() << "Value " << *KV.first
14855 << " is in ValueExprMap but not in ExprValueMap\n";
14856 std::abort();
14857 }
14858
14859 if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
14860 if (!ReachableBlocks.contains(I->getParent()))
14861 continue;
14862 const SCEV *OldSCEV = SCM.visit(KV.second);
14863 const SCEV *NewSCEV = SE2.getSCEV(I);
14864 const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14865 if (Delta && !Delta->isZero()) {
14866 dbgs() << "SCEV for value " << *I << " changed!\n"
14867 << "Old: " << *OldSCEV << "\n"
14868 << "New: " << *NewSCEV << "\n"
14869 << "Delta: " << *Delta << "\n";
14870 std::abort();
14871 }
14872 }
14873 }
14874
14875 for (const auto &KV : ExprValueMap) {
14876 for (Value *V : KV.second) {
14877 const SCEV *S = ValueExprMap.lookup(V);
14878 if (!S) {
14879 dbgs() << "Value " << *V
14880 << " is in ExprValueMap but not in ValueExprMap\n";
14881 std::abort();
14882 }
14883 if (S != KV.first) {
14884 dbgs() << "Value " << *V << " mapped to " << *S << " rather than "
14885 << *KV.first << "\n";
14886 std::abort();
14887 }
14888 }
14889 }
14890
14891 // Verify integrity of SCEV users.
14892 for (const auto &S : UniqueSCEVs) {
14893 for (SCEVUse Op : S.operands()) {
14894 // We do not store dependencies of constants.
14895 if (isa<SCEVConstant>(Op))
14896 continue;
14897 auto It = SCEVUsers.find(Op);
14898 if (It != SCEVUsers.end() && It->second.count(&S))
14899 continue;
14900 dbgs() << "Use of operand " << *Op << " by user " << S
14901 << " is not being tracked!\n";
14902 std::abort();
14903 }
14904 }
14905
14906 // Verify integrity of ValuesAtScopes users.
14907 for (const auto &ValueAndVec : ValuesAtScopes) {
14908 const SCEV *Value = ValueAndVec.first;
14909 for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
14910 const Loop *L = LoopAndValueAtScope.first;
14911 SCEVUse ValueAtScope = LoopAndValueAtScope.second;
14912 if (!isa<SCEVConstant>(ValueAtScope)) {
14913 auto It = ValuesAtScopesUsers.find(ValueAtScope.getPointer());
14914 if (It != ValuesAtScopesUsers.end() &&
14915 is_contained(It->second, std::make_pair(L, Value)))
14916 continue;
14917 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14918 << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
14919 std::abort();
14920 }
14921 }
14922 }
14923
14924 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
14925 const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
14926 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
14927 const Loop *L = LoopAndValue.first;
14928 const SCEV *Value = LoopAndValue.second;
14930 auto It = ValuesAtScopes.find(Value);
14931 // The recorded value at scope may carry no-wrap flags that are not part
14932 // of the key it is recorded under.
14933 if (It != ValuesAtScopes.end() && any_of(It->second, [&](const auto &LS) {
14934 return LS.first == L && LS.second.getPointer() == ValueAtScope;
14935 }))
14936 continue;
14937 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14938 << *ValueAtScope << " missing in ValuesAtScopes\n";
14939 std::abort();
14940 }
14941 }
14942
14943 // Verify integrity of BECountUsers.
14944 auto VerifyBECountUsers = [&](bool Predicated) {
14945 auto &BECounts =
14946 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14947 for (const auto &LoopAndBEInfo : BECounts) {
14948 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
14949 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14950 if (!isa<SCEVConstant>(S)) {
14951 auto UserIt = BECountUsers.find(S);
14952 if (UserIt != BECountUsers.end() &&
14953 UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
14954 continue;
14955 dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
14956 << " missing from BECountUsers\n";
14957 std::abort();
14958 }
14959 }
14960 }
14961 }
14962 };
14963 VerifyBECountUsers(/* Predicated */ false);
14964 VerifyBECountUsers(/* Predicated */ true);
14965
14966 // Verify intergity of loop disposition cache.
14967 for (auto &[S, Values] : LoopDispositions) {
14968 for (auto [Loop, CachedDisposition] : Values) {
14969 const auto RecomputedDisposition = SE2.getLoopDisposition(S, Loop);
14970 if (CachedDisposition != RecomputedDisposition) {
14971 dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
14972 << " is incorrect: cached " << CachedDisposition << ", actual "
14973 << RecomputedDisposition << "\n";
14974 std::abort();
14975 }
14976 }
14977 }
14978
14979 // Verify integrity of the block disposition cache.
14980 for (auto &[S, Values] : BlockDispositions) {
14981 for (auto [BB, CachedDisposition] : Values) {
14982 const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
14983 if (CachedDisposition != RecomputedDisposition) {
14984 dbgs() << "Cached disposition of " << *S << " for block %"
14985 << BB->getName() << " is incorrect: cached " << CachedDisposition
14986 << ", actual " << RecomputedDisposition << "\n";
14987 std::abort();
14988 }
14989 }
14990 }
14991
14992 // Verify FoldCache/FoldCacheUser caches.
14993 for (auto [FoldID, Expr] : FoldCache) {
14994 auto I = FoldCacheUser.find(Expr);
14995 if (I == FoldCacheUser.end()) {
14996 dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
14997 << "!\n";
14998 std::abort();
14999 }
15000 if (!is_contained(I->second, FoldID)) {
15001 dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
15002 std::abort();
15003 }
15004 }
15005 for (auto [Expr, IDs] : FoldCacheUser) {
15006 for (auto &FoldID : IDs) {
15007 const SCEV *S = FoldCache.lookup(FoldID);
15008 if (!S) {
15009 dbgs() << "Missing entry in FoldCache for expression " << *Expr
15010 << "!\n";
15011 std::abort();
15012 }
15013 if (S != Expr) {
15014 dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: " << *S
15015 << " != " << *Expr << "!\n";
15016 std::abort();
15017 }
15018 }
15019 }
15020
15021 // Verify that ConstantMultipleCache computations are correct. We check that
15022 // cached multiples and recomputed multiples are multiples of each other to
15023 // verify correctness. It is possible that a recomputed multiple is different
15024 // from the cached multiple due to strengthened no wrap flags or changes in
15025 // KnownBits computations.
15026 for (auto [S, Multiple] : ConstantMultipleCache) {
15027 APInt RecomputedMultiple = SE2.getConstantMultiple(S);
15028 if ((Multiple != 0 && RecomputedMultiple != 0 &&
15029 Multiple.urem(RecomputedMultiple) != 0 &&
15030 RecomputedMultiple.urem(Multiple) != 0)) {
15031 dbgs() << "Incorrect cached computation in ConstantMultipleCache for "
15032 << *S << " : Computed " << RecomputedMultiple
15033 << " but cache contains " << Multiple << "!\n";
15034 std::abort();
15035 }
15036 }
15037}
15038
15040 Function &F, const PreservedAnalyses &PA,
15041 FunctionAnalysisManager::Invalidator &Inv) {
15042 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
15043 // of its dependencies is invalidated.
15044 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
15045 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
15046 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
15047 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
15048 Inv.invalidate<LoopAnalysis>(F, PA);
15049}
15050
15051AnalysisKey ScalarEvolutionAnalysis::Key;
15052
15055 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
15056 auto &AC = AM.getResult<AssumptionAnalysis>(F);
15057 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
15058 auto &LI = AM.getResult<LoopAnalysis>(F);
15059 return ScalarEvolution(F, TLI, AC, DT, LI);
15060}
15061
15067
15070 // For compatibility with opt's -analyze feature under legacy pass manager
15071 // which was not ported to NPM. This keeps tests using
15072 // update_analyze_test_checks.py working.
15073 OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
15074 << F.getName() << "':\n";
15076 return PreservedAnalyses::all();
15077}
15078
15080 "Scalar Evolution Analysis", false, true)
15086 "Scalar Evolution Analysis", false, true)
15087
15088char ScalarEvolutionWrapperPass::ID = 0;
15089
15091
15093 SE.reset(new ScalarEvolution(
15095 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
15097 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
15098 return false;
15099}
15100
15102
15104 SE->print(OS);
15105}
15106
15108 if (!VerifySCEV)
15109 return;
15110
15111 SE->verify();
15112}
15113
15121
15123 const SCEV *RHS) {
15124 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
15125}
15126
15127const SCEVPredicate *
15129 const SCEV *LHS, const SCEV *RHS) {
15131 assert(LHS->getType() == RHS->getType() &&
15132 "Type mismatch between LHS and RHS");
15133 // Unique this node based on the arguments
15134 ID.AddInteger(SCEVPredicate::P_Compare);
15135 ID.AddInteger(Pred);
15136 ID.AddPointer(LHS);
15137 ID.AddPointer(RHS);
15139 if (const auto *S = UniquePreds.lookup(ID, Token))
15140 return S;
15141 SCEVComparePredicate *Eq = new (SCEVAllocator)
15142 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
15143 UniquePreds.insert(Eq, Token);
15144 return Eq;
15145}
15146
15148 const SCEVAddRecExpr *AR,
15151 // Unique this node based on the arguments
15153 ID.AddPointer(AR);
15154 ID.AddInteger(AddedFlags);
15156 if (const auto *S = UniquePreds.lookup(ID, Token))
15157 return S;
15158 auto *OF = new (SCEVAllocator)
15159 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
15160 UniquePreds.insert(OF, Token);
15161 return OF;
15162}
15163
15164namespace {
15165
15166class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
15167public:
15168
15169 /// Rewrites \p S in the context of a loop L and the SCEV predication
15170 /// infrastructure.
15171 ///
15172 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
15173 /// equivalences present in \p Pred.
15174 ///
15175 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
15176 /// \p NewPreds such that the result will be an AddRecExpr.
15177 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
15179 const SCEVPredicate *Pred) {
15180 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
15181 return Rewriter.visit(S);
15182 }
15183
15184 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
15185 if (Pred) {
15186 if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
15187 for (const auto *Pred : U->getPredicates())
15188 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
15189 if (IPred->getLHS() == Expr &&
15190 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15191 return IPred->getRHS();
15192 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
15193 if (IPred->getLHS() == Expr &&
15194 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15195 return IPred->getRHS();
15196 }
15197 }
15198 return convertToAddRecWithPreds(Expr);
15199 }
15200
15201 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
15202 const SCEV *Operand = visit(Expr->getOperand());
15203 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15204 if (AR && AR->getLoop() == L && AR->isAffine()) {
15205 // This couldn't be folded because the operand didn't have the nuw
15206 // flag. Add the nusw flag as an assumption that we could make.
15207 const SCEV *Step = AR->getStepRecurrence(SE);
15208 Type *Ty = Expr->getType();
15209 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
15210 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
15211 SE.getSignExtendExpr(Step, Ty), L,
15212 AR->getNoWrapFlags());
15213 }
15214 return SE.getZeroExtendExpr(Operand, Expr->getType());
15215 }
15216
15217 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
15218 const SCEV *Operand = visit(Expr->getOperand());
15219 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15220 if (AR && AR->getLoop() == L && AR->isAffine()) {
15221 // This couldn't be folded because the operand didn't have the nsw
15222 // flag. Add the nssw flag as an assumption that we could make.
15223 const SCEV *Step = AR->getStepRecurrence(SE);
15224 Type *Ty = Expr->getType();
15225 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
15226 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
15227 SE.getSignExtendExpr(Step, Ty), L,
15228 AR->getNoWrapFlags());
15229 }
15230 return SE.getSignExtendExpr(Operand, Expr->getType());
15231 }
15232
15233private:
15234 explicit SCEVPredicateRewriter(
15235 const Loop *L, ScalarEvolution &SE,
15236 SmallVectorImpl<const SCEVPredicate *> *NewPreds,
15237 const SCEVPredicate *Pred)
15238 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
15239
15240 bool addOverflowAssumption(const SCEVPredicate *P) {
15241 if (!NewPreds) {
15242 // Check if we've already made this assumption.
15243 return Pred && Pred->implies(P, SE);
15244 }
15245 NewPreds->push_back(P);
15246 return true;
15247 }
15248
15249 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
15251 auto *A = SE.getWrapPredicate(AR, AddedFlags);
15252 return addOverflowAssumption(A);
15253 }
15254
15255 // If \p Expr represents a PHINode, we try to see if it can be represented
15256 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
15257 // to add this predicate as a runtime overflow check, we return the AddRec.
15258 // If \p Expr does not meet these conditions (is not a PHI node, or we
15259 // couldn't create an AddRec for it, or couldn't add the predicate), we just
15260 // return \p Expr.
15261 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
15262 if (!isa<PHINode>(Expr->getValue()))
15263 return Expr;
15264 std::optional<
15265 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
15266 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
15267 if (!PredicatedRewrite)
15268 return Expr;
15269 for (const auto *P : PredicatedRewrite->second){
15270 // Wrap predicates from outer loops are not supported.
15271 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
15272 if (L != WP->getExpr()->getLoop())
15273 return Expr;
15274 }
15275 if (!addOverflowAssumption(P))
15276 return Expr;
15277 }
15278 return PredicatedRewrite->first;
15279 }
15280
15281 SmallVectorImpl<const SCEVPredicate *> *NewPreds;
15282 const SCEVPredicate *Pred;
15283 const Loop *L;
15284};
15285
15286} // end anonymous namespace
15287
15288const SCEV *
15290 const SCEVPredicate &Preds) {
15291 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
15292}
15293
15295 const SCEV *S, const Loop *L,
15298 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
15299 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
15300
15301 if (!AddRec)
15302 return nullptr;
15303
15304 // Check if any of the transformed predicates is known to be false. In that
15305 // case, it doesn't make sense to convert to a predicated AddRec, as the
15306 // versioned loop will never execute.
15307 for (const SCEVPredicate *Pred : TransformPreds) {
15308 auto *WrapPred = dyn_cast<SCEVWrapPredicate>(Pred);
15309 if (!WrapPred || WrapPred->getFlags() != SCEVWrapPredicate::IncrementNSSW)
15310 continue;
15311
15312 const SCEVAddRecExpr *AddRecToCheck = WrapPred->getExpr();
15313 const SCEV *ExitCount = getBackedgeTakenCount(AddRecToCheck->getLoop());
15314 if (isa<SCEVCouldNotCompute>(ExitCount))
15315 continue;
15316
15317 const SCEV *Step = AddRecToCheck->getStepRecurrence(*this);
15318 if (!Step->isOne())
15319 continue;
15320
15321 ExitCount = getTruncateOrSignExtend(ExitCount, Step->getType());
15322 const SCEV *Add = getAddExpr(AddRecToCheck->getStart(), ExitCount);
15323 if (isKnownPredicate(CmpInst::ICMP_SLT, Add, AddRecToCheck->getStart()))
15324 return nullptr;
15325 }
15326
15327 // Since the transformation was successful, we can now transfer the SCEV
15328 // predicates.
15329 Preds.append(TransformPreds.begin(), TransformPreds.end());
15330
15331 return AddRec;
15332}
15333
15334/// SCEV predicates
15338
15340 const ICmpInst::Predicate Pred,
15341 const SCEV *LHS, const SCEV *RHS)
15342 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
15343 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
15344 assert(LHS != RHS && "LHS and RHS are the same SCEV");
15345}
15346
15348 ScalarEvolution &SE) const {
15349 const auto *Op = dyn_cast<SCEVComparePredicate>(N);
15350
15351 if (!Op)
15352 return false;
15353
15354 if (Pred != ICmpInst::ICMP_EQ)
15355 return false;
15356
15357 return Op->LHS == LHS && Op->RHS == RHS;
15358}
15359
15360bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
15361
15363 if (Pred == ICmpInst::ICMP_EQ)
15364 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
15365 else
15366 OS.indent(Depth) << "Compare predicate: " << *LHS << " " << Pred << ") "
15367 << *RHS << "\n";
15368
15369}
15370
15372 const SCEVAddRecExpr *AR,
15373 IncrementWrapFlags Flags)
15374 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
15375
15376const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
15377
15379 ScalarEvolution &SE) const {
15380 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
15381 if (!Op || setFlags(Flags, Op->Flags) != Flags)
15382 return false;
15383
15384 if (Op->AR == AR)
15385 return true;
15386
15387 if (Flags != SCEVWrapPredicate::IncrementNSSW &&
15389 return false;
15390
15391 const SCEV *Start = AR->getStart();
15392 const SCEV *OpStart = Op->AR->getStart();
15393 if (Start->getType()->isPointerTy() != OpStart->getType()->isPointerTy())
15394 return false;
15395
15396 // Reject pointers to different address spaces.
15397 if (Start->getType()->isPointerTy() && Start->getType() != OpStart->getType())
15398 return false;
15399
15400 // NUSW/NSSW on a wider-type AddRec does not imply the same on a
15401 // narrower-type AddRec.
15402 if (SE.getTypeSizeInBits(AR->getType()) >
15403 SE.getTypeSizeInBits(Op->AR->getType()))
15404 return false;
15405
15406 const SCEV *Step = AR->getStepRecurrence(SE);
15407 const SCEV *OpStep = Op->AR->getStepRecurrence(SE);
15408 if (!SE.isKnownPositive(Step) || !SE.isKnownPositive(OpStep))
15409 return false;
15410
15411 // If both steps are positive, this implies N, if N's start and step are
15412 // ULE/SLE (for NSUW/NSSW) than this'.
15413 Type *WiderTy = SE.getWiderType(Step->getType(), OpStep->getType());
15414 Step = SE.getNoopOrZeroExtend(Step, WiderTy);
15415 OpStep = SE.getNoopOrZeroExtend(OpStep, WiderTy);
15416
15417 bool IsNUW = Flags == SCEVWrapPredicate::IncrementNUSW;
15418 OpStart = IsNUW ? SE.getNoopOrZeroExtend(OpStart, WiderTy)
15419 : SE.getNoopOrSignExtend(OpStart, WiderTy);
15420 Start = IsNUW ? SE.getNoopOrZeroExtend(Start, WiderTy)
15421 : SE.getNoopOrSignExtend(Start, WiderTy);
15423 return SE.isKnownPredicate(Pred, OpStep, Step) &&
15424 SE.isKnownPredicate(Pred, OpStart, Start);
15425}
15426
15428 SCEVFlags ScevFlags = AR->getNoWrapFlags();
15429 IncrementWrapFlags IFlags = Flags;
15430
15431 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
15432 IFlags = clearFlags(IFlags, IncrementNSSW);
15433
15434 return IFlags == IncrementAnyWrap;
15435}
15436
15437void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
15438 OS.indent(Depth) << *getExpr() << " Added Flags: ";
15440 OS << "<nusw>";
15442 OS << "<nssw>";
15443 OS << "\n";
15444}
15445
15446/// Union predicates don't get cached so create a dummy set ID for it.
15448 ScalarEvolution &SE)
15450 for (const auto *P : Preds)
15451 add(P, SE);
15452}
15453
15455 return all_of(Preds,
15456 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
15457}
15458
15460 ScalarEvolution &SE) const {
15461 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
15462 return all_of(Set->Preds, [this, &SE](const SCEVPredicate *I) {
15463 return this->implies(I, SE);
15464 });
15465
15466 if (any_of(Preds,
15467 [N, &SE](const SCEVPredicate *I) { return I->implies(N, SE); }))
15468 return true;
15469
15470 // A wrap predicate may be implied by a wrap predicate in Preds after applying
15471 // equal predicates.
15472 const auto *NWrap = dyn_cast<SCEVWrapPredicate>(N);
15473 if (!NWrap)
15474 return false;
15475 const Loop *L = NWrap->getExpr()->getLoop();
15476 return any_of(Preds, [&](const SCEVPredicate *I) {
15477 const auto *IWrap = dyn_cast<SCEVWrapPredicate>(I);
15478 if (!IWrap)
15479 return false;
15480 const auto *RewrittenAR = dyn_cast<SCEVAddRecExpr>(
15481 SE.rewriteUsingPredicate(IWrap->getExpr(), L, *this));
15482 return RewrittenAR &&
15483 SE.getWrapPredicate(RewrittenAR, IWrap->getFlags())->implies(N, SE);
15484 });
15485}
15486
15488 for (const auto *Pred : Preds)
15489 Pred->print(OS, Depth);
15490}
15491
15492void SCEVUnionPredicate::add(const SCEVPredicate *N, ScalarEvolution &SE) {
15493 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
15494 for (const auto *Pred : Set->Preds)
15495 add(Pred, SE);
15496 return;
15497 }
15498
15499 // Implication checks are quadratic in the number of predicates. Stop doing
15500 // them if there are many predicates, as they should be too expensive to use
15501 // anyway at that point.
15502 bool CheckImplies = Preds.size() < 16;
15503
15504 // Only add predicate if it is not already implied by this union predicate.
15505 if (CheckImplies && implies(N, SE))
15506 return;
15507
15508 // Build a new vector containing the current predicates, except the ones that
15509 // are implied by the new predicate N.
15511 for (auto *P : Preds) {
15512 if (CheckImplies && N->implies(P, SE))
15513 continue;
15514 PrunedPreds.push_back(P);
15515 }
15516 Preds = std::move(PrunedPreds);
15517 Preds.push_back(N);
15518}
15519
15521 Loop &L)
15522 : SE(SE), L(L) {
15524 Preds = std::make_unique<SCEVUnionPredicate>(Empty, SE);
15525}
15526
15528 for (const SCEV *Op : Ops)
15529 // We do not expect that forgetting cached data for SCEVConstants will ever
15530 // open any prospects for sharpening or introduce any correctness issues,
15531 // so we don't bother storing their dependencies.
15532 if (!isa<SCEVConstant>(Op))
15533 SCEVUsers[Op].insert(User);
15534}
15535
15537 const SCEV *Expr = SE.getSCEV(V);
15538 return getPredicatedSCEV(Expr);
15539}
15540
15542 RewriteEntry &Entry = RewriteMap[Expr];
15543
15544 // If we already have an entry and the version matches, return it.
15545 if (Entry.second && Generation == Entry.first)
15546 return Entry.second;
15547
15548 // We found an entry but it's stale. Rewrite the stale entry
15549 // according to the current predicate.
15550 if (Entry.second)
15551 Expr = Entry.second;
15552
15553 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
15554 Entry = {Generation, NewSCEV};
15555
15556 return NewSCEV;
15557}
15558
15560 if (!BackedgeCount) {
15562 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
15563 for (const auto *P : Preds)
15564 addPredicate(*P);
15565 }
15566 return BackedgeCount;
15567}
15568
15570 if (!SymbolicMaxBackedgeCount) {
15572 SymbolicMaxBackedgeCount =
15573 SE.getPredicatedSymbolicMaxBackedgeTakenCount(&L, Preds);
15574 for (const auto *P : Preds)
15575 addPredicate(*P);
15576 }
15577 return SymbolicMaxBackedgeCount;
15578}
15579
15581 if (!SmallConstantMaxTripCount) {
15583 SmallConstantMaxTripCount = SE.getSmallConstantMaxTripCount(&L, &Preds);
15584 for (const auto *P : Preds)
15585 addPredicate(*P);
15586 }
15587 return *SmallConstantMaxTripCount;
15588}
15589
15591 if (Preds->implies(&Pred, SE))
15592 return;
15593
15594 SmallVector<const SCEVPredicate *, 4> NewPreds(Preds->getPredicates());
15595 NewPreds.push_back(&Pred);
15596 Preds = std::make_unique<SCEVUnionPredicate>(NewPreds, SE);
15597 updateGeneration();
15598}
15599
15602 for (const SCEVPredicate *P : Preds)
15603 addPredicate(*P);
15604}
15605
15607 return *Preds;
15608}
15609
15610void PredicatedScalarEvolution::updateGeneration() {
15611 // If the generation number wrapped recompute everything.
15612 if (++Generation == 0) {
15613 for (auto &II : RewriteMap) {
15614 const SCEV *Rewritten = II.second.second;
15615 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
15616 }
15617 }
15618}
15619
15622 const SCEV *Expr = this->getSCEV(V);
15624 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
15625
15626 if (!New)
15627 return nullptr;
15628
15629 if (ExtraPreds) {
15630 ExtraPreds->append(NewPreds);
15631 return New;
15632 }
15633
15634 addPredicates(NewPreds);
15635
15636 RewriteMap[SE.getSCEV(V)] = {Generation, New};
15637 return New;
15638}
15639
15642 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
15643 Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates(),
15644 SE)),
15645 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {}
15646
15648 // For each block.
15649 for (auto *BB : L.getBlocks())
15650 for (auto &I : *BB) {
15651 if (!SE.isSCEVable(I.getType()))
15652 continue;
15653
15654 auto *Expr = SE.getSCEV(&I);
15655 auto II = RewriteMap.find(Expr);
15656
15657 if (II == RewriteMap.end())
15658 continue;
15659
15660 // Don't print things that are not interesting.
15661 if (II->second.second == Expr)
15662 continue;
15663
15664 OS.indent(Depth) << "[PSE]" << I << ":\n";
15665 OS.indent(Depth + 2) << *Expr << "\n";
15666 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
15667 }
15668}
15669
15670void ScalarEvolution::LoopGuards::collectPending() {
15671 const Loop *L = PendingLoop;
15672 if (!L)
15673 return;
15674 PendingLoop = nullptr;
15675 BasicBlock *Pred = L->getLoopPredecessor();
15676 if (!Pred)
15677 return;
15679 collectFromBlock(SE, *this, L->getHeader(), Pred, VisitedBlocks);
15680}
15681
15682void ScalarEvolution::LoopGuards::collectFromPHI(
15686 unsigned Depth) {
15687 if (!SE.isSCEVable(Phi.getType()))
15688 return;
15689
15690 using MinMaxPattern = std::pair<const SCEVConstant *, SCEVTypes>;
15691 auto GetMinMaxConst = [&](unsigned IncomingIdx) -> MinMaxPattern {
15692 const BasicBlock *InBlock = Phi.getIncomingBlock(IncomingIdx);
15693 if (!VisitedBlocks.insert(InBlock).second)
15694 return {nullptr, scCouldNotCompute};
15695
15696 // Avoid analyzing unreachable blocks so that we don't get trapped
15697 // traversing cycles with ill-formed dominance or infinite cycles
15698 if (!SE.DT.isReachableFromEntry(InBlock))
15699 return {nullptr, scCouldNotCompute};
15700
15701 auto [G, Inserted] = IncomingGuards.try_emplace(InBlock, LoopGuards(SE));
15702 if (Inserted)
15703 collectFromBlock(SE, G->second, Phi.getParent(), InBlock, VisitedBlocks,
15704 Depth + 1);
15705 auto &RewriteMap = G->second.RewriteMap;
15706 if (RewriteMap.empty())
15707 return {nullptr, scCouldNotCompute};
15708 auto S = RewriteMap.find(SE.getSCEV(Phi.getIncomingValue(IncomingIdx)));
15709 if (S == RewriteMap.end())
15710 return {nullptr, scCouldNotCompute};
15711 auto *SM = dyn_cast_if_present<SCEVMinMaxExpr>(S->second);
15712 if (!SM)
15713 return {nullptr, scCouldNotCompute};
15714 if (const SCEVConstant *C0 = dyn_cast<SCEVConstant>(SM->getOperand(0)))
15715 return {C0, SM->getSCEVType()};
15716 return {nullptr, scCouldNotCompute};
15717 };
15718 auto MergeMinMaxConst = [](MinMaxPattern P1,
15719 MinMaxPattern P2) -> MinMaxPattern {
15720 auto [C1, T1] = P1;
15721 auto [C2, T2] = P2;
15722 if (!C1 || !C2 || T1 != T2)
15723 return {nullptr, scCouldNotCompute};
15724 switch (T1) {
15725 case scUMaxExpr:
15726 return {C1->getAPInt().ult(C2->getAPInt()) ? C1 : C2, T1};
15727 case scSMaxExpr:
15728 return {C1->getAPInt().slt(C2->getAPInt()) ? C1 : C2, T1};
15729 case scUMinExpr:
15730 return {C1->getAPInt().ugt(C2->getAPInt()) ? C1 : C2, T1};
15731 case scSMinExpr:
15732 return {C1->getAPInt().sgt(C2->getAPInt()) ? C1 : C2, T1};
15733 default:
15734 llvm_unreachable("Trying to merge non-MinMaxExpr SCEVs.");
15735 }
15736 };
15737 auto P = GetMinMaxConst(0);
15738 for (unsigned int In = 1; In < Phi.getNumIncomingValues(); In++) {
15739 if (!P.first)
15740 break;
15741 P = MergeMinMaxConst(P, GetMinMaxConst(In));
15742 }
15743 if (P.first) {
15744 const SCEV *LHS = SE.getSCEV(const_cast<PHINode *>(&Phi));
15745 SmallVector<SCEVUse, 2> Ops({P.first, LHS});
15746 const SCEV *RHS = SE.getMinMaxExpr(P.second, Ops);
15747 Guards.RewriteMap.insert({LHS, RHS});
15748 }
15749}
15750
15751// Return a new SCEV that modifies \p Expr to the closest number divides by
15752// \p Divisor and less or equal than Expr. For now, only handle constant
15753// Expr.
15755 const APInt &DivisorVal,
15756 ScalarEvolution &SE) {
15757 const APInt *ExprVal;
15758 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15759 DivisorVal.isNonPositive())
15760 return Expr;
15761 APInt Rem = ExprVal->urem(DivisorVal);
15762 // return the SCEV: Expr - Expr % Divisor
15763 return SE.getConstant(*ExprVal - Rem);
15764}
15765
15766// Return a new SCEV that modifies \p Expr to the closest number divides by
15767// \p Divisor and greater or equal than Expr. For now, only handle constant
15768// Expr.
15769static const SCEV *getNextSCEVDivisibleByDivisor(const SCEV *Expr,
15770 const APInt &DivisorVal,
15771 ScalarEvolution &SE) {
15772 const APInt *ExprVal;
15773 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15774 DivisorVal.isNonPositive())
15775 return Expr;
15776 APInt Rem = ExprVal->urem(DivisorVal);
15777 if (Rem.isZero())
15778 return Expr;
15779 // return the SCEV: Expr + Divisor - Expr % Divisor
15780 return SE.getConstant(*ExprVal + DivisorVal - Rem);
15781}
15782
15784 ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS,
15787 // If we have LHS == 0, check if LHS is computing a property of some unknown
15788 // SCEV %v which we can rewrite %v to express explicitly.
15790 return false;
15791 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
15792 // explicitly express that.
15793 const SCEVUnknown *URemLHS = nullptr;
15794 const SCEV *URemRHS = nullptr;
15795 if (!match(LHS, m_scev_URem(m_SCEVUnknown(URemLHS), m_SCEV(URemRHS), SE)))
15796 return false;
15797
15798 const SCEV *Multiple =
15799 SE.getMulExpr(SE.getUDivExpr(URemLHS, URemRHS), URemRHS);
15800 DivInfo[URemLHS] = Multiple;
15801 if (auto *C = dyn_cast<SCEVConstant>(URemRHS))
15802 Multiples[URemLHS] = C->getAPInt();
15803 return true;
15804}
15805
15806// Check if the condition is a divisibility guard (A % B == 0).
15807static bool isDivisibilityGuard(const SCEV *LHS, const SCEV *RHS,
15808 ScalarEvolution &SE) {
15809 const SCEV *X, *Y;
15810 return match(LHS, m_scev_URem(m_SCEV(X), m_SCEV(Y), SE)) && RHS->isZero();
15811}
15812
15813// Apply divisibility by \p Divisor on MinMaxExpr with constant values,
15814// recursively. This is done by aligning up/down the constant value to the
15815// Divisor.
15816static const SCEV *applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr,
15817 APInt Divisor,
15818 ScalarEvolution &SE) {
15819 // Return true if \p Expr is a MinMax SCEV expression with a non-negative
15820 // constant operand. If so, return in \p SCTy the SCEV type and in \p RHS
15821 // the non-constant operand and in \p LHS the constant operand.
15822 auto IsMinMaxSCEVWithNonNegativeConstant =
15823 [&](const SCEV *Expr, SCEVTypes &SCTy, const SCEV *&LHS,
15824 const SCEV *&RHS) {
15825 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr)) {
15826 if (MinMax->getNumOperands() != 2)
15827 return false;
15828 if (auto *C = dyn_cast<SCEVConstant>(MinMax->getOperand(0))) {
15829 if (C->getAPInt().isNegative())
15830 return false;
15831 SCTy = MinMax->getSCEVType();
15832 LHS = MinMax->getOperand(0);
15833 RHS = MinMax->getOperand(1);
15834 return true;
15835 }
15836 }
15837 return false;
15838 };
15839
15840 const SCEV *MinMaxLHS = nullptr, *MinMaxRHS = nullptr;
15841 SCEVTypes SCTy;
15842 if (!IsMinMaxSCEVWithNonNegativeConstant(MinMaxExpr, SCTy, MinMaxLHS,
15843 MinMaxRHS))
15844 return MinMaxExpr;
15845 auto IsMin = isa<SCEVSMinExpr>(MinMaxExpr) || isa<SCEVUMinExpr>(MinMaxExpr);
15846 assert(SE.isKnownNonNegative(MinMaxLHS) && "Expected non-negative operand!");
15847 auto *DivisibleExpr =
15848 IsMin ? getPreviousSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE)
15849 : getNextSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE);
15851 applyDivisibilityOnMinMaxExpr(MinMaxRHS, Divisor, SE), DivisibleExpr};
15852 return SE.getMinMaxExpr(SCTy, Ops);
15853}
15854
15855void ScalarEvolution::LoopGuards::collectFromBlock(
15856 ScalarEvolution &SE, ScalarEvolution::LoopGuards &Guards,
15857 const BasicBlock *Block, const BasicBlock *Pred,
15858 SmallPtrSetImpl<const BasicBlock *> &VisitedBlocks, unsigned Depth) {
15859
15861
15862 SmallVector<SCEVUse> ExprsToRewrite;
15863 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
15864 const SCEV *RHS,
15865 DenseMap<const SCEV *, const SCEV *> &RewriteMap,
15866 const LoopGuards &DivGuards) {
15867 // WARNING: It is generally unsound to apply any wrap flags to the proposed
15868 // replacement SCEV which isn't directly implied by the structure of that
15869 // SCEV. In particular, using contextual facts to imply flags is *NOT*
15870 // legal. See the scoping rules for flags in the header to understand why.
15871
15872 // Puts rewrite rule \p From -> \p To into the rewrite map. Also if \p From
15873 // and \p FromRewritten are the same (i.e. there has been no rewrite
15874 // registered for \p From), then puts this value in the list of rewritten
15875 // expressions.
15876 auto AddRewrite = [&](const SCEV *From, const SCEV *FromRewritten,
15877 const SCEV *To) {
15878 if (From == FromRewritten)
15879 ExprsToRewrite.push_back(From);
15880 RewriteMap[From] = To;
15881 };
15882
15883 // Checks whether \p S has already been rewritten. In that case returns the
15884 // existing rewrite because we want to chain further rewrites onto the
15885 // already rewritten value. Otherwise returns \p S.
15886 auto GetMaybeRewritten = [&](const SCEV *S) {
15887 return RewriteMap.lookup_or(S, S);
15888 };
15889
15890 // Check for a condition of the form (-C1 + X < C2). InstCombine will
15891 // create this form when combining two checks of the form (X u< C2 + C1) and
15892 // (X >=u C1).
15893 auto MatchRangeCheckIdiom = [&](ICmpInst::Predicate Pred,
15894 const SCEV *MatchLHS,
15895 const SCEV *MatchRHS) {
15896 const SCEVConstant *C1;
15897 const SCEVUnknown *LHSUnknown;
15898 auto *C2 = dyn_cast<SCEVConstant>(MatchRHS);
15899 if (!match(MatchLHS,
15900 m_scev_Add(m_SCEVConstant(C1), m_SCEVUnknown(LHSUnknown))) ||
15901 !C2)
15902 return false;
15903
15904 auto ExactRegion =
15905 ConstantRange::makeExactICmpRegion(Pred, C2->getAPInt())
15906 .sub(C1->getAPInt());
15907
15908 // Tighten the raw range with what we already know about LHSUnknown
15909 // from prior guards recorded in RewriteMap, or from SCEV's own range
15910 // analysis.
15911 const SCEV *RewrittenLHS = GetMaybeRewritten(LHSUnknown);
15912 ExactRegion = ExactRegion.intersectWith(SE.getUnsignedRange(RewrittenLHS),
15914
15915 // Bail if the guard is inconsistent with prior facts, or if the range
15916 // is still not a monotonic non-wrapping interval after tightening.
15917 if (ExactRegion.isEmptySet() || ExactRegion.isWrappedSet() ||
15918 ExactRegion.isFullSet())
15919 return false;
15920
15921 const SCEV *RegionMin = SE.getConstant(ExactRegion.getUnsignedMin());
15922 const SCEV *RegionMax = SE.getConstant(ExactRegion.getUnsignedMax());
15923 const SCEV *ClampedLHS =
15924 SE.getUMaxExpr(RegionMin, SE.getUMinExpr(RewrittenLHS, RegionMax));
15925 AddRewrite(LHSUnknown, RewrittenLHS, ClampedLHS);
15926 return true;
15927 };
15928 if (MatchRangeCheckIdiom(Predicate, LHS, RHS))
15929 return;
15930
15931 // Do not apply information for constants or if RHS contains an AddRec.
15933 return;
15934
15935 // If RHS is SCEVUnknown, make sure the information is applied to it.
15937 std::swap(LHS, RHS);
15939 }
15940
15941 const SCEV *RewrittenLHS = GetMaybeRewritten(LHS);
15942 // Apply divisibility information when computing the constant multiple.
15943 const APInt &DividesBy =
15944 SE.getConstantMultiple(DivGuards.rewrite(RewrittenLHS));
15945
15946 // Collect rewrites for LHS and its transitive operands based on the
15947 // condition.
15948 // For min/max expressions, also apply the guard to its operands:
15949 // 'min(a, b) >= c' -> '(a >= c) and (b >= c)',
15950 // 'min(a, b) > c' -> '(a > c) and (b > c)',
15951 // 'max(a, b) <= c' -> '(a <= c) and (b <= c)',
15952 // 'max(a, b) < c' -> '(a < c) and (b < c)'.
15953
15954 // We cannot express strict predicates in SCEV, so instead we replace them
15955 // with non-strict ones against plus or minus one of RHS depending on the
15956 // predicate.
15957 const SCEV *One = SE.getOne(RHS->getType());
15958 switch (Predicate) {
15959 case CmpInst::ICMP_ULT:
15960 if (RHS->getType()->isPointerTy())
15961 return;
15962 RHS = SE.getUMaxExpr(RHS, One);
15963 [[fallthrough]];
15964 case CmpInst::ICMP_SLT: {
15965 RHS = SE.getMinusSCEV(RHS, One);
15966 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
15967 break;
15968 }
15969 case CmpInst::ICMP_UGT:
15970 case CmpInst::ICMP_SGT:
15971 RHS = SE.getAddExpr(RHS, One);
15972 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
15973 break;
15974 case CmpInst::ICMP_ULE:
15975 case CmpInst::ICMP_SLE:
15976 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
15977 break;
15978 case CmpInst::ICMP_UGE:
15979 case CmpInst::ICMP_SGE:
15980 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
15981 break;
15982 default:
15983 break;
15984 }
15985
15986 SmallVector<SCEVUse, 16> Worklist(1, LHS);
15987 SmallPtrSet<const SCEV *, 16> Visited;
15988
15989 auto EnqueueOperands = [&Worklist](const SCEVNAryExpr *S) {
15990 append_range(Worklist, S->operands());
15991 };
15992
15993 while (!Worklist.empty()) {
15994 const SCEV *From = Worklist.pop_back_val();
15995 if (isa<SCEVConstant>(From))
15996 continue;
15997 if (!Visited.insert(From).second)
15998 continue;
15999 const SCEV *FromRewritten = GetMaybeRewritten(From);
16000 const SCEV *To = nullptr;
16001
16002 switch (Predicate) {
16003 case CmpInst::ICMP_ULT:
16004 case CmpInst::ICMP_ULE:
16005 To = SE.getUMinExpr(FromRewritten, RHS);
16006 if (auto *UMax = dyn_cast<SCEVUMaxExpr>(FromRewritten))
16007 EnqueueOperands(UMax);
16008 break;
16009 case CmpInst::ICMP_SLT:
16010 case CmpInst::ICMP_SLE:
16011 To = SE.getSMinExpr(FromRewritten, RHS);
16012 if (auto *SMax = dyn_cast<SCEVSMaxExpr>(FromRewritten))
16013 EnqueueOperands(SMax);
16014 break;
16015 case CmpInst::ICMP_UGT:
16016 case CmpInst::ICMP_UGE:
16017 To = SE.getUMaxExpr(FromRewritten, RHS);
16018 if (auto *UMin = dyn_cast<SCEVUMinExpr>(FromRewritten))
16019 EnqueueOperands(UMin);
16020 break;
16021 case CmpInst::ICMP_SGT:
16022 case CmpInst::ICMP_SGE:
16023 To = SE.getSMaxExpr(FromRewritten, RHS);
16024 if (auto *SMin = dyn_cast<SCEVSMinExpr>(FromRewritten))
16025 EnqueueOperands(SMin);
16026 break;
16027 case CmpInst::ICMP_EQ:
16029 To = RHS;
16030 break;
16031 case CmpInst::ICMP_NE:
16032 if (match(RHS, m_scev_Zero())) {
16033 const SCEV *OneAlignedUp =
16034 getNextSCEVDivisibleByDivisor(One, DividesBy, SE);
16035 To = SE.getUMaxExpr(FromRewritten, OneAlignedUp);
16036 } else {
16037 // LHS != RHS can be rewritten as (LHS - RHS) = UMax(1, LHS - RHS),
16038 // but creating the subtraction eagerly is expensive. Track the
16039 // inequalities in a separate map, and materialize the rewrite lazily
16040 // when encountering a suitable subtraction while re-writing.
16041 if (LHS->getType()->isPointerTy()) {
16042 LHS = SE.getPtrToAddrExpr(LHS);
16043 RHS = SE.getPtrToAddrExpr(RHS);
16045 break;
16046 }
16047 const SCEVConstant *C;
16048 const SCEV *A, *B;
16051 RHS = A;
16052 LHS = B;
16053 }
16054 if (LHS > RHS)
16055 std::swap(LHS, RHS);
16056 Guards.NotEqual.insert({LHS, RHS});
16057 continue;
16058 }
16059 break;
16060 default:
16061 break;
16062 }
16063
16064 if (To)
16065 AddRewrite(From, FromRewritten, To);
16066 }
16067 };
16068
16070 // First, collect information from assumptions dominating the loop.
16071 for (auto &AssumeVH : SE.AC.assumptions()) {
16072 if (!AssumeVH)
16073 continue;
16074 auto *AssumeI = cast<CallInst>(AssumeVH);
16075 if (!SE.DT.dominates(AssumeI, Block))
16076 continue;
16077 Terms.emplace_back(AssumeI->getOperand(0), true);
16078 }
16079
16080 // Second, collect information from llvm.experimental.guards dominating the loop.
16081 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
16082 SE.F.getParent(), Intrinsic::experimental_guard);
16083 if (GuardDecl)
16084 for (const auto *GU : GuardDecl->users())
16085 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
16086 if (Guard->getFunction() == Block->getParent() &&
16087 SE.DT.dominates(Guard, Block))
16088 Terms.emplace_back(Guard->getArgOperand(0), true);
16089
16090 // Third, collect conditions from dominating branches. Starting at the loop
16091 // predecessor, climb up the predecessor chain, as long as there are
16092 // predecessors that can be found that have unique successors leading to the
16093 // original header.
16094 // TODO: share this logic with isLoopEntryGuardedByCond.
16095 unsigned NumCollectedConditions = 0;
16097 std::pair<const BasicBlock *, const BasicBlock *> Pair(Pred, Block);
16098 for (; Pair.first;
16099 Pair = SE.getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
16100 VisitedBlocks.insert(Pair.second);
16101 const CondBrInst *LoopEntryPredicate =
16102 dyn_cast<CondBrInst>(Pair.first->getTerminator());
16103 if (!LoopEntryPredicate)
16104 continue;
16105
16106 Terms.emplace_back(LoopEntryPredicate->getCondition(),
16107 LoopEntryPredicate->getSuccessor(0) == Pair.second);
16108 NumCollectedConditions++;
16109
16110 // If we are recursively collecting guards stop after 2
16111 // conditions to limit compile-time impact for now.
16112 if (Depth > 0 && NumCollectedConditions == 2)
16113 break;
16114 }
16115 // Finally, if we stopped climbing the predecessor chain because
16116 // there wasn't a unique one to continue, try to collect conditions
16117 // for PHINodes by recursively following all of their incoming
16118 // blocks and try to merge the found conditions to build a new one
16119 // for the Phi.
16120 if (Pair.second->hasNPredecessorsOrMore(2) &&
16122 SmallDenseMap<const BasicBlock *, LoopGuards> IncomingGuards;
16123 for (auto &Phi : Pair.second->phis())
16124 collectFromPHI(SE, Guards, Phi, VisitedBlocks, IncomingGuards, Depth);
16125 }
16126
16127 // Now apply the information from the collected conditions to
16128 // Guards.RewriteMap. Conditions are processed in reverse order, so the
16129 // earliest conditions is processed first, except guards with divisibility
16130 // information, which are moved to the back. This ensures the SCEVs with the
16131 // shortest dependency chains are constructed first.
16133 GuardsToProcess;
16134 for (auto [Term, EnterIfTrue] : reverse(Terms)) {
16135 SmallVector<Value *, 8> Worklist;
16136 SmallPtrSet<Value *, 8> Visited;
16137 Worklist.push_back(Term);
16138 while (!Worklist.empty()) {
16139 Value *Cond = Worklist.pop_back_val();
16140 if (!Visited.insert(Cond).second)
16141 continue;
16142
16143 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
16144 auto Predicate =
16145 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
16146 const auto *LHS = SE.getSCEV(Cmp->getOperand(0));
16147 const auto *RHS = SE.getSCEV(Cmp->getOperand(1));
16148 // If LHS is a constant, apply information to the other expression.
16149 // TODO: If LHS is not a constant, check if using CompareSCEVComplexity
16150 // can improve results.
16151 if (isa<SCEVConstant>(LHS)) {
16152 std::swap(LHS, RHS);
16154 }
16155 GuardsToProcess.emplace_back(Predicate, LHS, RHS);
16156 continue;
16157 }
16158
16159 Value *L, *R;
16160 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
16161 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
16162 Worklist.push_back(L);
16163 Worklist.push_back(R);
16164 }
16165 }
16166 }
16167
16168 // Process divisibility guards in reverse order to populate DivGuards early.
16169 DenseMap<const SCEV *, APInt> Multiples;
16170 LoopGuards DivGuards(SE);
16171 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess) {
16172 if (!isDivisibilityGuard(LHS, RHS, SE))
16173 continue;
16174 collectDivisibilityInformation(Predicate, LHS, RHS, DivGuards.RewriteMap,
16175 Multiples, SE);
16176 }
16177
16178 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess)
16179 CollectCondition(Predicate, LHS, RHS, Guards.RewriteMap, DivGuards);
16180
16181 // Apply divisibility information last. This ensures it is applied to the
16182 // outermost expression after other rewrites for the given value.
16183 for (const auto &[K, Divisor] : Multiples) {
16184 const SCEV *DivisorSCEV = SE.getConstant(Divisor);
16185 Guards.RewriteMap[K] =
16187 Guards.rewrite(K), Divisor, SE),
16188 DivisorSCEV),
16189 DivisorSCEV);
16190 ExprsToRewrite.push_back(K);
16191 }
16192
16193 // Let the rewriter preserve NUW/NSW flags if the unsigned/signed ranges of
16194 // the replacement expressions are contained in the ranges of the replaced
16195 // expressions.
16196 Guards.PreserveNUW = true;
16197 Guards.PreserveNSW = true;
16198 for (const SCEV *Expr : ExprsToRewrite) {
16199 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16200 Guards.PreserveNUW &=
16201 SE.getUnsignedRange(Expr).contains(SE.getUnsignedRange(RewriteTo));
16202 Guards.PreserveNSW &=
16203 SE.getSignedRange(Expr).contains(SE.getSignedRange(RewriteTo));
16204 }
16205
16206 // Now that all rewrite information is collect, rewrite the collected
16207 // expressions with the information in the map. This applies information to
16208 // sub-expressions.
16209 if (ExprsToRewrite.size() > 1) {
16210 for (const SCEV *Expr : ExprsToRewrite) {
16211 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16212 Guards.RewriteMap.erase(Expr);
16213 Guards.RewriteMap.insert({Expr, Guards.rewrite(RewriteTo)});
16214 }
16215 }
16216}
16217
16219 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
16220 /// in the map. It skips AddRecExpr because we cannot guarantee that the
16221 /// replacement is loop invariant in the loop of the AddRec.
16222 class SCEVLoopGuardRewriter
16223 : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
16226
16227 SCEVFlags FlagMask = SCEV::FlagNone;
16228
16229 public:
16230 SCEVLoopGuardRewriter(ScalarEvolution &SE,
16231 const ScalarEvolution::LoopGuards &Guards)
16232 : SCEVRewriteVisitor(SE), Map(Guards.RewriteMap),
16233 NotEqual(Guards.NotEqual) {
16234 if (Guards.PreserveNUW)
16235 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNUW);
16236 if (Guards.PreserveNSW)
16237 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNSW);
16238 }
16239
16240 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
16241
16242 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
16243 return Map.lookup_or(Expr, Expr);
16244 }
16245
16246 const SCEV *visitPtrToAddrExpr(const SCEVPtrToAddrExpr *Expr) {
16247 if (const SCEV *S = Map.lookup(Expr))
16248 return S;
16250 Expr);
16251 }
16252
16253 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
16254 if (const SCEV *S = Map.lookup(Expr))
16255 return S;
16256
16257 // If we didn't find the extact ZExt expr in the map, check if there's
16258 // an entry for a smaller ZExt we can use instead.
16259 Type *Ty = Expr->getType();
16260 const SCEV *Op = Expr->getOperand(0);
16261 unsigned Bitwidth = Ty->getScalarSizeInBits() / 2;
16262 while (Bitwidth % 8 == 0 && Bitwidth >= 8 &&
16263 Bitwidth > Op->getType()->getScalarSizeInBits()) {
16264 Type *NarrowTy = IntegerType::get(SE.getContext(), Bitwidth);
16265 auto *NarrowExt = SE.getZeroExtendExpr(Op, NarrowTy);
16266 if (const SCEV *S = Map.lookup(NarrowExt))
16267 return SE.getZeroExtendExpr(S, Ty);
16268 Bitwidth = Bitwidth / 2;
16269 }
16270
16272 Expr);
16273 }
16274
16275 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
16276 if (const SCEV *S = Map.lookup(Expr))
16277 return S;
16279 Expr);
16280 }
16281
16282 const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
16283 if (const SCEV *S = Map.lookup(Expr))
16284 return S;
16286 }
16287
16288 const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
16289 if (const SCEV *S = Map.lookup(Expr))
16290 return S;
16292 }
16293
16294 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
16295 if (const SCEV *S = Map.lookup(Expr))
16296 return S;
16297
16298 // Helper to check if S is a subtraction (A - B) where A != B, and if so,
16299 // return UMax(S, 1).
16300 auto RewriteSubtraction = [&](const SCEV *S) -> const SCEV * {
16301 SCEVUse LHS, RHS;
16302 if (MatchBinarySub(S, LHS, RHS)) {
16303 if (LHS > RHS)
16304 std::swap(LHS, RHS);
16305 if (NotEqual.contains({LHS, RHS})) {
16306 const SCEV *OneAlignedUp = getNextSCEVDivisibleByDivisor(
16307 SE.getOne(S->getType()), SE.getConstantMultiple(S), SE);
16308 return SE.getUMaxExpr(OneAlignedUp, S);
16309 }
16310 }
16311 return nullptr;
16312 };
16313
16314 // Check if Expr itself is a subtraction pattern with guard info.
16315 if (const SCEV *Rewritten = RewriteSubtraction(Expr))
16316 return Rewritten;
16317
16318 // Trip count expressions sometimes consist of adding 3 operands, i.e.
16319 // (Const + A + B). There may be guard info for A + B, and if so, apply
16320 // it.
16321 // TODO: Could more generally apply guards to Add sub-expressions.
16322 if (isa<SCEVConstant>(Expr->getOperand(0))) {
16323 if (Expr->getNumOperands() == 3) {
16324 const SCEV *Add =
16325 SE.getAddExpr(Expr->getOperand(1), Expr->getOperand(2));
16326 if (const SCEV *Rewritten = RewriteSubtraction(Add))
16327 return SE.getAddExpr(
16328 Expr->getOperand(0), Rewritten,
16329 ScalarEvolution::maskFlags(Expr->getNoWrapFlags(), FlagMask));
16330 if (const SCEV *S = Map.lookup(Add))
16331 return SE.getAddExpr(Expr->getOperand(0), S);
16332 }
16333
16334 // For expressions of the form (Const + A), check if we have guard info
16335 // for (Const + 1 + A), and rewrite to ((Const + 1 + A) - 1). This makes
16336 // sure we don't lose information when rewriting expressions based on
16337 // back-edge taken counts in some cases.
16338 if (Expr->getNumOperands() == 2) {
16339 const SCEV *S = nullptr;
16340 // Handle (-1 + 1 + A) without constructing SCEVs.
16341 if (match(Expr->getOperand(0), m_scev_AllOnes())) {
16342 S = Map.lookup(Expr->getOperand(1));
16343 } else {
16344 const SCEV *NewC =
16345 SE.getAddExpr(Expr->getOperand(0), SE.getOne(Expr->getType()));
16346 S = Map.lookup(SE.getAddExpr(NewC, Expr->getOperand(1)));
16347 }
16348 if (S)
16349 return SE.getAddExpr(S, SE.getMinusOne(Expr->getType()));
16350 }
16351 }
16353 bool Changed = false;
16354 for (SCEVUse Op : Expr->operands()) {
16355 Operands.push_back(
16357 Changed |= Op != Operands.back();
16358 }
16359 // We are only replacing operands with equivalent values, so transfer the
16360 // flags from the original expression.
16361 return !Changed ? Expr
16362 : SE.getAddExpr(Operands,
16364 Expr->getNoWrapFlags(), FlagMask));
16365 }
16366
16367 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
16369 bool Changed = false;
16370 for (SCEVUse Op : Expr->operands()) {
16371 Operands.push_back(
16373 Changed |= Op != Operands.back();
16374 }
16375 // We are only replacing operands with equivalent values, so transfer the
16376 // flags from the original expression.
16377 return !Changed ? Expr
16378 : SE.getMulExpr(Operands,
16380 Expr->getNoWrapFlags(), FlagMask));
16381 }
16382 };
16383
16384 if (RewriteMap.empty() && NotEqual.empty())
16385 return Expr;
16386
16387 SCEVLoopGuardRewriter Rewriter(SE, *this);
16388 return Rewriter.visit(Expr);
16389}
16390
16391const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
16392 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
16393 return applyLoopGuards(Expr, Guards);
16394}
16395
16397 LoopGuards &Guards) {
16398 // Loop guards never rewrite constants and AddRecs, so there is no need to
16399 // collect pending guards for them.
16401 return Expr;
16402 if (Guards.PendingLoop)
16403 Guards.collectPending();
16404 return Guards.rewrite(Expr);
16405}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
constexpr LLT S1
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
@ PostInc
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:686
This file contains the declarations for the subclasses of Constant, which represent the different fla...
SmallPtrSet< const BasicBlock *, 8 > VisitedBlocks
This file defines the DenseMap class.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
static bool isSigned(unsigned Opcode)
This file defines a hash set that can be used to remove duplication of nodes in a graph.
#define op(i)
Hexagon Common GEP
Value * getPointer(Value *Ptr)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This defines the Use class.
iv Induction Variable Users
Definition IVUsers.cpp:48
static bool hasNoUnsignedWrap(BinaryOperator &I)
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:540
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define T
#define T1
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
ppc ctr loops verify
PowerPC Reduce CR logical Operation
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
R600 Clause Merge
const SmallVectorImpl< MachineOperand > & Cond
static DominatorTree getDomTree(Function &F)
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
SI Fold Operands
SI optimize exec mask operations pre RA
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
This file contains some templates that are useful if you are working with the STL at all.
This file provides utility classes that use RAII to save and restore values.
bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind, SCEVTypes RootKind)
static cl::opt< unsigned > MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, cl::desc("Max coefficients in AddRec during evolving"), cl::init(8))
static cl::opt< unsigned > RangeIterThreshold("scev-range-iter-threshold", cl::Hidden, cl::desc("Threshold for switching to iteratively computing SCEV ranges"), cl::init(32))
static const Loop * isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI)
static unsigned getConstantTripCount(const SCEVConstant *ExitCount)
static int CompareValueComplexity(const LoopInfo *const LI, Value *LV, Value *RV, unsigned Depth)
Compare the two values LV and RV in terms of their "complexity" where "complexity" is a partial (and ...
static const SCEV * getNextSCEVDivisibleByDivisor(const SCEV *Expr, const APInt &DivisorVal, ScalarEvolution &SE)
static void PushLoopPHIs(const Loop *L, SmallVectorImpl< Instruction * > &Worklist, SmallPtrSetImpl< Instruction * > &Visited)
Push PHI nodes in the header of the given loop onto the given Worklist.
static void insertFoldCacheEntry(const ScalarEvolution::FoldID &ID, const SCEV *S, DenseMap< ScalarEvolution::FoldID, const SCEV * > &FoldCache, DenseMap< const SCEV *, SmallVector< ScalarEvolution::FoldID, 2 > > &FoldCacheUser)
static cl::opt< bool > ClassifyExpressions("scalar-evolution-classify-expressions", cl::Hidden, cl::init(true), cl::desc("When printing analysis, include information on every instruction"))
static bool hasHugeExpression(ArrayRef< SCEVUse > Ops)
Returns true if Ops contains a huge SCEV (the subtree of S contains at least HugeExprThreshold nodes)...
static cl::opt< unsigned > AddOpsInlineThreshold("scev-addops-inline-threshold", cl::Hidden, cl::desc("Threshold for inlining addition operands into a SCEV"), cl::init(500))
static cl::opt< unsigned > MaxLoopGuardCollectionDepth("scalar-evolution-max-loop-guard-collection-depth", cl::Hidden, cl::desc("Maximum depth for recursive loop guard collection"), cl::init(1))
static cl::opt< bool > VerifyIR("scev-verify-ir", cl::Hidden, cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), cl::init(false))
static bool RangeRefPHIAllowedOperands(DominatorTree &DT, PHINode *PHI)
static bool IsKnownPredicateViaAddRecMonotonicity(ScalarEvolution &SE, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Is LHS Pred RHS true because one of them is an AddRec that is known not to go below its own start val...
static std::optional< APInt > MinOptional(std::optional< APInt > X, std::optional< APInt > Y)
Helper function to compare optional APInts: (a) if X and Y both exist, return min(X,...
static PHINode * getConstantEvolvingPHI(Value *V, const Loop *L, const TargetLibraryInfo *TLI)
getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node in the loop that V is deri...
static bool canConstantFold(const Instruction *I, const TargetLibraryInfo *TLI)
Return true if we can constant fold an instruction of the specified type, assuming that all operands ...
static cl::opt< unsigned > MulOpsInlineThreshold("scev-mulops-inline-threshold", cl::Hidden, cl::desc("Threshold for inlining multiplication operands into a SCEV"), cl::init(32))
static BinaryOperator * getCommonInstForPHI(PHINode *PN)
static PHINode * getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, DenseMap< Instruction *, PHINode * > &PHIMap, const TargetLibraryInfo *TLI, unsigned Depth)
getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by recursing through each instructi...
static bool isDivisibilityGuard(const SCEV *LHS, const SCEV *RHS, ScalarEvolution &SE)
static std::optional< const SCEV * > createNodeForSelectViaUMinSeq(ScalarEvolution *SE, const SCEV *CondExpr, const SCEV *TrueExpr, const SCEV *FalseExpr)
static Constant * BuildConstantFromSCEV(const SCEV *V)
This builds up a Constant using the ConstantExpr interface.
static ConstantInt * EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, ScalarEvolution &SE)
static const SCEV * BinomialCoefficient(const SCEV *It, unsigned K, ScalarEvolution &SE, Type *ResultTy)
Compute BC(It, K). The result has width W. Assume, K > 0.
static cl::opt< unsigned > MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), cl::init(8))
static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, const SCEV *Candidate)
Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
static 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 cl::opt< unsigned > MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, cl::desc("Maximum number of iterations SCEV will " "symbolically execute a constant " "derived loop"), cl::init(100))
static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow)
static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV *S)
When printing a top-level SCEV for trip counts, it's helpful to include a type for constants which ar...
static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, const Loop *L)
static bool containsConstantInAddMulChain(const SCEV *StartExpr)
Determine if any of the operands in this SCEV are a constant or if any of the add or multiply express...
static const SCEV * getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, ScalarEvolution *SE, unsigned Depth)
static bool CollectAddOperandsWithScales(SmallDenseMap< SCEVUse, APInt, 16 > &M, SmallVectorImpl< SCEVUse > &NewOps, APInt &AccumulatedConstant, ArrayRef< SCEVUse > Ops, const APInt &Scale, ScalarEvolution &SE)
Process the given Ops list, which is a list of operands to be added under the given scale,...
static const SCEV * constantFoldAndGroupOps(ScalarEvolution &SE, LoopInfo &LI, DominatorTree &DT, SmallVectorImpl< SCEVUse > &Ops, FoldT Fold, IsIdentityT IsIdentity, IsAbsorberT IsAbsorber)
Performs a number of common optimizations on the passed Ops.
static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
static const SCEV * getPreStartForExtend(const SCEVAddRecExpr *AR, ScalarEvolution *SE, unsigned Depth)
static void GroupByComplexity(SmallVectorImpl< SCEVUse > &Ops, LoopInfo *LI, DominatorTree &DT)
Given a list of SCEV objects, order them by their complexity, and group objects of the same complexit...
static bool collectDivisibilityInformation(ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS, DenseMap< const SCEV *, const SCEV * > &DivInfo, DenseMap< const SCEV *, APInt > &Multiples, ScalarEvolution &SE)
static cl::opt< unsigned > MaxSCEVOperationsImplicationDepth("scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, cl::desc("Maximum depth of recursive SCEV operations implication analysis"), cl::init(2))
static void PushDefUseChildren(Instruction *I, SmallVectorImpl< Instruction * > &Worklist, SmallPtrSetImpl< Instruction * > &Visited)
Push users of the given Instruction onto the given Worklist.
static std::optional< APInt > SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, const ConstantRange &Range, ScalarEvolution &SE)
Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n iterations.
static cl::opt< bool > UseContextForNoWrapFlagInference("scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden, cl::desc("Infer nuw/nsw flags using context where suitable"), cl::init(true))
static cl::opt< bool > EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden, cl::desc("Handle <= and >= in finite loops"), cl::init(true))
static bool getOperandsForSelectLikePHI(DominatorTree &DT, PHINode *PN, Value *&Cond, Value *&LHS, Value *&RHS)
static std::optional< std::tuple< APInt, APInt, APInt, APInt, unsigned > > GetQuadraticEquation(const SCEVAddRecExpr *AddRec)
For a given quadratic addrec, generate coefficients of the corresponding quadratic equation,...
static bool isKnownPredicateExtendIdiom(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
static std::optional< 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 APInt extractConstantWithoutWrapping(ScalarEvolution &SE, const SCEVConstant *ConstantTerm, const SCEVAddExpr *WholeAddExpr)
static int CompareSCEVComplexity(const LoopInfo *const LI, SCEVUse LHS, SCEVUse RHS, DominatorTree &DT)
static cl::opt< unsigned > MaxConstantEvolvingDepth("scalar-evolution-max-constant-evolving-depth", cl::Hidden, cl::desc("Maximum depth of recursive constant evolving"), cl::init(32))
static bool canConstantEvolve(Instruction *I, const Loop *L, const TargetLibraryInfo *TLI)
Determine whether this instruction can constant evolve within this loop assuming its operands can all...
static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS)
static std::optional< ConstantRange > GetRangeFromMetadata(Value *V)
Helper method to assign a range to V from metadata present in the IR.
static cl::opt< unsigned > HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, cl::desc("Size of the expression which is considered huge"), cl::init(4096))
static Type * isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, bool &Signed, ScalarEvolution &SE)
Helper function to createAddRecFromPHIWithCasts.
static Constant * EvaluateExpression(Value *V, const Loop *L, DenseMap< Instruction *, Constant * > &Vals, const DataLayout &DL, const TargetLibraryInfo *TLI)
EvaluateExpression - Given an expression that passes the getConstantEvolvingPHI predicate,...
static const SCEV * getPreviousSCEVDivisibleByDivisor(const SCEV *Expr, const APInt &DivisorVal, ScalarEvolution &SE)
static const SCEV * MatchNotExpr(const SCEV *Expr)
If Expr computes ~A, return A else return nullptr.
static std::pair< ConstantRange, bool > getRangeForAffineARHelper(APInt Step, const ConstantRange &StartRange, const APInt &MaxBECount, bool Signed)
static cl::opt< unsigned > MaxValueCompareDepth("scalar-evolution-max-value-compare-depth", cl::Hidden, cl::desc("Maximum depth of recursive value complexity comparisons"), cl::init(2))
static const SCEV * applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr, APInt Divisor, ScalarEvolution &SE)
static cl::opt< bool, true > VerifySCEVOpt("verify-scev", cl::Hidden, cl::location(VerifySCEV), cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"))
static const SCEV * getSignedOverflowLimitForStep(const SCEV *Step, ICmpInst::Predicate *Pred, ScalarEvolution *SE)
static cl::opt< unsigned > MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, cl::desc("Maximum depth of recursive arithmetics"), cl::init(32))
static bool HasSameValue(const SCEV *A, const SCEV *B)
SCEV structural equivalence is usually sufficient for testing whether two expressions are equal,...
static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow)
Compute the result of "n choose k", the binomial coefficient.
static bool scevUnconditionallyPropagatesPoisonFromOperands(SCEVTypes Kind)
static cl::opt< bool > VerifySCEVStrict("verify-scev-strict", cl::Hidden, cl::desc("Enable stricter verification with -verify-scev is passed"))
static Constant * getOtherIncomingValue(PHINode *PN, BasicBlock *BB)
static std::optional< BinaryOp > MatchBinaryOp(Value *V, const DataLayout &DL, AssumptionCache &AC, const DominatorTree &DT, const Instruction *CtxI)
Try to map V into a BinaryOp, and return std::nullopt on failure.
static cl::opt< bool > UseExpensiveRangeSharpening("scalar-evolution-use-expensive-range-sharpening", cl::Hidden, cl::init(false), cl::desc("Use more powerful methods of sharpening expression ranges. May " "be costly in terms of compile time"))
static const SCEV * getUnsignedOverflowLimitForStep(const SCEV *Step, ICmpInst::Predicate *Pred, ScalarEvolution *SE)
static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Is LHS Pred RHS true on the virtue of LHS or RHS being a Min or Max expression?
static bool BrPHIToSelect(DominatorTree &DT, CondBrInst *BI, PHINode *Merge, Value *&C, Value *&LHS, Value *&RHS)
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
static bool InBlock(const Value *V, const BasicBlock *BB)
Provides some synthesis utilities to produce sequences of values.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
static std::optional< bool > isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS, const Value *ARHS, const Value *BLHS, const Value *BRHS)
Return true if "icmp Pred BLHS BRHS" is true whenever "icmp PredALHS ARHS" is true.
virt reg Virtual Register Rewriter
Value * RHS
Value * LHS
BinaryOperator * Mul
static const uint32_t IV[8]
Definition blake3_impl.h:83
SCEVCastSinkingRewriter(ScalarEvolution &SE, Type *TargetTy, ConversionFn CreatePtrCast)
static const SCEV * rewrite(const SCEV *Scev, ScalarEvolution &SE, Type *TargetTy, ConversionFn CreatePtrCast)
const SCEV * visitUnknown(const SCEVUnknown *Expr)
const SCEV * visitAddExpr(const SCEVAddExpr *Expr)
const SCEV * visit(const SCEV *S)
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2009
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
APInt abs() const
Get the absolute value.
Definition APInt.h:1815
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition APInt.h:462
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:212
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1170
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1973
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
bool isNonPositive() const
Determine if this APInt Value is non-positive (<= 0).
Definition APInt.h:357
unsigned countTrailingZeros() const
Definition APInt.h:1667
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:352
unsigned logBase2() const
Definition APInt.h:1781
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:471
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1303
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
bool isSignBitSet() const
Determine if sign bit of this APInt is set.
Definition APInt.h:337
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1134
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition APInt.h:428
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
AnalysisUsage & addRequiredTransitive()
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
MutableArrayRef< WeakVH > assumptions()
Access the list of assumption handles currently tracked for this function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction & front() const
Definition BasicBlock.h:469
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI unsigned getNoWrapKind() const
Returns one of OBO::NoSignedWrap or OBO::NoUnsignedWrap.
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
This class represents a function call, abstracting a target machine's calling convention.
virtual void deleted()
Callback for Value destruction.
void setValPtr(Value *P)
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
bool isFalseWhenEqual() const
This is just a convenience.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
bool isSigned() const
Definition InstrTypes.h:993
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
bool isUnsigned() const
Definition InstrTypes.h:999
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Definition InstrTypes.h:989
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
LLVM_ABI CmpInst::Predicate getPreferredSignedPredicate() const
Attempts to return a signed CmpInst::Predicate from the CmpPredicate.
CmpInst::Predicate dropSameSign() const
Drops samesign information.
Conditional Branch instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static LLVM_ABI Constant * getNot(Constant *C)
static Constant * getPtrAdd(Constant *Ptr, Constant *Offset, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReduced=nullptr)
Create a getelementptr i8, ptr, offset constant expression.
Definition Constants.h: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.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
LLVM_ABI ConstantRange signExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
const APInt & getUpper() const
Return the upper value for this range.
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static LLVM_ABI ConstantRange makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp, const ConstantRange &Other, unsigned NoWrapKind)
Produce the largest range containing all X such that "X BinOp Y" is guaranteed not to wrap (overflow)...
LLVM_ABI unsigned getMinSignedBits() const
Compute the maximal number of bits needed to represent every value in this signed range.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
LLVM_ABI ConstantRange sextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
static LLVM_ABI ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp, const APInt &Other, unsigned NoWrapKind)
Produce the range that contains X if and only if "X BinOp Other" does not wrap.
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
LLVM_ABI IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:791
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:758
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:763
bool empty() const
Definition DenseMap.h:717
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:767
iterator end()
Definition DenseMap.h:687
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition DenseMap.h:679
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:794
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive,...
Definition DenseMap.h:780
void swap(DenseMapBase &RHS)
Definition DenseMap.h:978
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:828
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:857
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction extracts a single (scalar) element from a VectorType value.
This instruction extracts a struct member or array element value from an aggregate value.
Insertion token: a failed lookup fills it in, the matching insert consumes it.
Definition FoldingSet.h:284
This class describes a reference to an interned FoldingSetNodeID, which can be a useful to store node...
Definition FoldingSet.h:123
This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:162
void AddInteger(signed I)
Definition FoldingSet.h:190
This class represents a freeze function that returns random concrete value if an operand is either a ...
FunctionPass(char &pid)
Definition Pass.h:316
Represents flags for the getelementptr instruction/expression.
bool hasNoUnsignedSignedWrap() const
bool hasNoUnsignedWrap() const
static GEPNoWrapFlags none()
static LLVM_ABI Type * getTypeAtIndex(Type *Ty, Value *Idx)
Return the type of the element at the given index of an indexable type.
Module * getParent()
Get the module that this global value is contained inside of...
static bool isPrivateLinkage(LinkageTypes Linkage)
static bool isInternalLinkage(LinkageTypes Linkage)
This instruction compares its operands according to the predicate given to the constructor.
CmpPredicate getCmpPredicate() const
static bool isGE(Predicate P)
Return true if the predicate is SGE or UGE.
CmpPredicate getSwappedCmpPredicate() const
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
static bool isLT(Predicate P)
Return true if the predicate is SLT or ULT.
CmpPredicate getInverseCmpPredicate() const
Predicate getNonStrictCmpPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
static bool isGT(Predicate P)
Return true if the predicate is SGT or UGT.
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
static CmpPredicate getInverseCmpPredicate(CmpPredicate Pred)
bool isEquality() const
Return true if this predicate is either EQ or NE.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
static bool isLE(Predicate P)
Return true if the predicate is SLE or ULE.
This instruction inserts a single (scalar) element into a VectorType value.
This instruction inserts a struct field of array element value into an aggregate value.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI bool isIdenticalToWhenDefined(const Instruction *I, bool IntersectAttrs=false) const LLVM_READONLY
This is like isIdenticalTo, except that it ignores the SubclassOptionalData flags,...
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
A helper class to return the specified delimiter string after the first invocation of operator String...
An instruction for reading from memory.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
BlockT * getHeader() const
unsigned getLoopDepth() const
Return the nesting level of this loop.
BlockT * getLoopPredecessor() const
If the given loop's header has exactly one unique predecessor outside the loop, return it.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
unsigned getLoopDepth(const BlockT *BB) const
Return the loop nesting level of the specified block.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:619
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:67
Metadata node.
Definition Metadata.h:1081
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition Operator.h:113
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition Operator.h:107
iterator_range< const_block_iterator > blocks() const
op_range incoming_values()
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
PointerIntPair - This class implements a pair of a pointer and small integer.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
LLVM_ABI void addPredicate(const SCEVPredicate &Pred)
Adds a new predicate.
LLVM_ABI const SCEVPredicate & getPredicate() const
LLVM_ABI const SCEV * getPredicatedSCEV(const SCEV *Expr)
Returns the rewritten SCEV for Expr in the context of the current SCEV predicate.
LLVM_ABI bool areAddRecsEqualWithPreds(const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2, ArrayRef< const SCEVPredicate * > ExtraPreds={}) const
Check if AR1 and AR2 are equal, while taking into account Equal predicates in Preds and ExtraPreds.
LLVM_ABI const SCEVAddRecExpr * getAsAddRec(Value *V, SmallVectorImpl< const SCEVPredicate * > *WrapPredsAdded=nullptr)
Attempts to produce an AddRecExpr for V by adding additional SCEV predicates.
LLVM_ABI void print(raw_ostream &OS, unsigned Depth) const
Print the SCEV mappings done by the Predicated Scalar Evolution.
LLVM_ABI PredicatedScalarEvolution(ScalarEvolution &SE, Loop &L)
LLVM_ABI unsigned getSmallConstantMaxTripCount()
Returns the upper bound of the loop trip count as a normal unsigned value, or 0 if the trip count is ...
LLVM_ABI void addPredicates(ArrayRef< const SCEVPredicate * > Preds)
Adds all predicates in Preds.
LLVM_ABI const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSymbolicMaxBackedgeTakenCount()
Get the (predicated) symbolic max backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
constexpr bool isValid() const
Definition Register.h:112
This node represents an addition of some number of SCEVs.
This node represents a polynomial recurrence on the trip count of the specified loop.
LLVM_ABI SCEVUse getExitValue(ScalarEvolution &SE) const
Return the value of this recurrences when its loop exits, i.e.
LLVM_ABI const SCEV * evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const
Return the value of this chain of recurrences at the specified iteration number.
void setNoWrapFlags(SCEVFlags Flags)
Set flags for a recurrence without clearing any previously set flags.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
bool isQuadratic() const
Return true if this represents an expression A + B*x + C*x^2 where A, B and C are loop invariant valu...
LLVM_ABI const SCEV * getNumIterationsInRange(const ConstantRange &Range, ScalarEvolution &SE) const
Return the number of iterations of this loop that produce values in the specified constant range.
LLVM_ABI const SCEVAddRecExpr * getPostIncExpr(ScalarEvolution &SE) const
Return an expression representing the value of this expression one iteration of the loop ahead.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This is the base class for unary cast operator classes.
LLVM_ABI SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, SCEVUse op, Type *ty)
This class represents an assumption that the expression LHS Pred RHS evaluates to true,...
SCEVComparePredicate(const FoldingSetNodeIDRef ID, const ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
bool isAlwaysTrue() const override
Returns true if the predicate is always true.
void print(raw_ostream &OS, unsigned Depth=0) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Implementation of the SCEVPredicate interface.
This class represents a constant integer value.
ConstantInt * getValue() const
const APInt & getAPInt() const
This is the base class for unary integral cast operator classes.
LLVM_ABI SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, SCEVUse op, Type *ty)
This node is the base class min/max selections.
static enum SCEVTypes negate(enum SCEVTypes T)
This node represents multiplication of some number of SCEVs.
This node is a base class providing common functionality for n'ary operators.
ArrayRef< SCEVUse > operands() const
SCEVFlags getNoWrapFlags(SCEVFlags Mask=FlagsNoWrapMask) const
SCEVUse getOperand(unsigned i) const
This class represents an assumption made using SCEV expressions which can be checked at run-time.
SCEVPredicate(const SCEVPredicate &)=default
virtual bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const =0
Returns true if this predicate implies N.
SCEVPredicateKind Kind
This class represents a cast from a pointer to a pointer-sized integer value, without capturing the p...
This visitor recursively visits a SCEV expression and re-writes it.
const SCEV * visitPtrToAddrExpr(const SCEVPtrToAddrExpr *Expr)
const SCEV * visitSignExtendExpr(const SCEVSignExtendExpr *Expr)
const SCEV * visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr)
const SCEV * visitSMinExpr(const SCEVSMinExpr *Expr)
const SCEV * visitUMinExpr(const SCEVUMinExpr *Expr)
This class represents a signed minimum selection.
This node is the base class for sequential/in-order min/max selections.
static SCEVTypes getEquivalentNonSequentialSCEVType(SCEVTypes Ty)
This class represents a sign extension of a small integer value to a larger integer value.
Visit all nodes in the expression tree using worklist traversal.
This class represents a truncation of an integer value to a smaller integer value.
This class represents a binary unsigned division operation.
This class represents an unsigned minimum selection.
This class represents a composition of other SCEV predicates, and is the class that most clients will...
void print(raw_ostream &OS, unsigned Depth) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Returns true if this predicate implies N.
SCEVUnionPredicate(ArrayRef< const SCEVPredicate * > Preds, ScalarEvolution &SE)
Union predicates don't get cached so create a dummy set ID for it.
bool isAlwaysTrue() const override
Implementation of the SCEVPredicate interface.
SCEVUnionPredicate getUnionWith(const SCEVPredicate *N, ScalarEvolution &SE) const
Returns a new SCEVUnionPredicate that is the union of this predicate and the given predicate N.
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
This class represents the value of vscale, as used when defining the length of a scalable vector or r...
This class represents an assumption made on an AddRec expression.
IncrementWrapFlags
Similar to SCEVFlags, but with slightly different semantics for FlagNUSW.
SCEVWrapPredicate(const FoldingSetNodeIDRef ID, const SCEVAddRecExpr *AR, IncrementWrapFlags Flags)
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Returns true if this predicate implies N.
static SCEVWrapPredicate::IncrementWrapFlags setFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OnFlags)
void print(raw_ostream &OS, unsigned Depth=0) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool isAlwaysTrue() const override
Returns true if the predicate is always true.
const SCEVAddRecExpr * getExpr() const
Implementation of the SCEVPredicate interface.
static SCEVWrapPredicate::IncrementWrapFlags clearFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OffFlags)
Convenient IncrementWrapFlags manipulation methods.
IncrementWrapFlags getFlags() const
Returns the set assumed no overflow flags.
This class represents a zero extension of a small integer value to a larger integer value.
This class represents an analyzed expression in the program.
unsigned short getExpressionSize() const
static constexpr auto FlagsNoWrapMask
LLVM_ABI bool isOne() const
Return true if the expression is a constant one.
SCEV(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, unsigned short ExpressionSize, Type *Ty)
static constexpr auto FlagNUW
LLVM_ABI void computeAndSetCanonical(ScalarEvolution &SE)
Compute and set the canonical SCEV, by constructing a SCEV with the same operands,...
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
const SCEV * CanonicalSCEV
Pointer to the canonical version of the SCEV, i.e.
LLVM_ABI void dump() const
This method is used for debugging.
LLVM_ABI bool isAllOnesValue() const
Return true if the expression is a constant all-ones value.
LLVM_ABI bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
static constexpr auto FlagNSW
LLVM_ABI ArrayRef< SCEVUse > operands() const
Return operands of this SCEV expression.
Type * getType() const
Return the LLVM type of this SCEV expression.
static constexpr auto FlagNone
LLVM_ABI void print(raw_ostream &OS) const
Print out the internal representation of this scalar to the specified stream.
SCEVTypes getSCEVType() const
static constexpr auto FlagNW
Analysis pass that exposes the ScalarEvolution for a function.
LLVM_ABI ScalarEvolution run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void print(raw_ostream &OS, const Module *=nullptr) const override
print - Print out the internal state of the pass.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
static LoopGuards collectOnDemand(const Loop *L, ScalarEvolution &SE)
Return loop guards for loop L, which are collected on first use.
LLVM_ABI const SCEV * rewrite(const SCEV *Expr) const
Try to apply the collected loop guards to Expr.
The main scalar evolution driver.
LLVM_ABI const SCEV * getUDivExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
const SCEV * getConstantMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
const DataLayout & getDataLayout() const
Return the DataLayout associated with the module this SCEV instance is operating on.
LLVM_ABI bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
LLVM_ABI bool isKnownOnEveryIteration(CmpPredicate Pred, const SCEVAddRecExpr *LHS, const SCEV *RHS)
Test if the condition described by Pred, LHS, RHS is known to be true on every iteration of the loop ...
static bool hasFlags(SCEVFlags Flags, SCEVFlags TestFlags)
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantExitCondDuringFirstIterationsImpl(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI, const SCEV *MaxIter)
LLVM_ABI const SCEV * getZeroExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getUDivCeilSCEV(const SCEV *N, const SCEV *D)
Compute ceil(N / D).
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantExitCondDuringFirstIterations(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI, const SCEV *MaxIter)
If the result of the predicate LHS Pred RHS is loop invariant with respect to L at given Context duri...
LLVM_ABI Type * getWiderType(Type *Ty1, Type *Ty2) const
LLVM_ABI const SCEV * getAbsExpr(const SCEV *Op, bool IsNSW)
LLVM_ABI bool isKnownNonPositive(const SCEV *S)
Test if the given expression is known to be non-positive.
LLVM_ABI const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEVFlags Flags=SCEV::FlagNone)
LLVM_ABI bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
LLVM_ABI const SCEV * getPredicatedConstantMaxBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getConstantMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
LLVM_ABI const SCEV * removePointerBase(const SCEV *S)
Compute an expression equivalent to S - getPointerBase(S).
LLVM_ABI bool isLoopEntryGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the loop is protected by a conditional between LHS and RHS.
LLVM_ABI bool isKnownNonZero(const SCEV *S)
Test if the given expression is known to be non-zero.
LLVM_ABI const SCEV * getURemExpr(SCEVUse LHS, SCEVUse RHS)
Represents an unsigned remainder expression based on unsigned division.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LLVM_ABI const SCEV * getSMinExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI const SCEV * getUMaxFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS)
Promote the operands to the wider of the types using zero-extension, and then perform a umax operatio...
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
LLVM_ABI bool willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI=nullptr)
Is operation BinOp between LHS and RHS provably does not have a signed/unsigned overflow (Signed)?
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI ExitLimit computeExitLimitFromCond(const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit, bool AllowPredicates=false)
Compute the number of times the backedge of the specified loop will execute if its exit condition wer...
LLVM_ABI const SCEV * getMinMaxExpr(SCEVTypes Kind, SmallVectorImpl< SCEVUse > &Operands)
LLVM_ABI const SCEVPredicate * getEqualPredicate(const SCEV *LHS, const SCEV *RHS)
LLVM_ABI unsigned getSmallConstantTripMultiple(const Loop *L, const SCEV *ExitCount)
Returns the largest constant divisor of the trip count as a normal unsigned value,...
LLVM_ABI SCEVUse getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
LLVM_ABI uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
LLVM_ABI void registerUser(const SCEV *User, ArrayRef< SCEVUse > Ops)
Notify this ScalarEvolution that User directly uses SCEVs in Ops.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getPredicatedBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getBackedgeTakenCount, except it will add a set of SCEV predicates to Predicates that are ...
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
ConstantRange getSignedRange(const SCEV *S)
Determine the signed range for a particular SCEV.
LLVM_ABI const SCEV * getNoopOrSignExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
static SCEVFlags setFlags(SCEVFlags Flags, SCEVFlags OnFlags)
static LLVM_ABI bool isGuaranteedNotToBePoison(const SCEV *Op)
Returns true if Op is guaranteed to not be poison.
bool loopHasNoAbnormalExits(const Loop *L)
Return true if the loop has no abnormal exits.
LLVM_ABI const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
LLVM_ABI ScalarEvolution(Function &F, TargetLibraryInfo &TLI, AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI)
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI const SCEV * getTruncateOrNoop(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI void forgetValues(ArrayRef< Value * > Values)
Batched forgetValue: invalidates all Values in one shared def-use walk, avoiding the redundant re-tra...
LLVM_ABI const SCEV * getSequentialMinMaxExpr(SCEVTypes Kind, SmallVectorImpl< SCEVUse > &Operands)
LLVM_ABI const SCEV * getCastExpr(SCEVTypes Kind, SCEVUse Op, Type *Ty)
LLVM_ABI std::optional< bool > evaluatePredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Check whether the condition described by Pred, LHS, and RHS is true or false in the given Context.
LLVM_ABI SCEVUse getAddRecExpr(SCEVUse Start, SCEVUse Step, const Loop *L, SCEVFlagsPair Flags)
Get an add recurrence expression for the specified loop.
LLVM_ABI unsigned getSmallConstantMaxTripCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Returns the upper bound of the loop trip count as a normal unsigned value.
LLVM_ABI bool isKnownMultipleOf(const SCEV *S, uint64_t M, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Check that S is a multiple of M.
LLVM_ABI bool isBackedgeTakenCountMaxOrZero(const Loop *L)
Return true if the backedge taken count is either the value returned by getConstantMaxBackedgeTakenCo...
LLVM_ABI void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI bool isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
LLVM_ABI bool SimplifyICmpOperands(CmpPredicate &Pred, SCEVUse &LHS, SCEVUse &RHS, unsigned Depth=0)
Simplify LHS and RHS in a comparison with predicate Pred.
APInt getUnsignedRangeMin(const SCEV *S)
Determine the min of the unsigned range for a particular SCEV.
static SCEVFlags clearFlags(SCEVFlags Flags, SCEVFlags OffFlags)
LLVM_ABI const SCEV * getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo)
Return an expression for offsetof on the given field with type IntTy.
LLVM_ABI LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L)
Return the "disposition" of the given SCEV with respect to the given loop.
static SCEVFlags maskFlags(SCEVFlags Flags, SCEVFlags Mask)
Convenient SCEVFlags manipulation.
LLVM_ABI bool containsAddRecurrence(const SCEV *S)
Return true if the SCEV is a scAddRecExpr or it contains scAddRecExpr.
LLVM_ABI const SCEV * getTruncateExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI SCEVUse getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI const SCEV * getZeroExtendExprImpl(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI Type * getEffectiveSCEVType(Type *Ty) const
Return a type with the same bitwidth as the given type and which represents how SCEV will treat the g...
LLVM_ABI const SCEVPredicate * getComparePredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
LLVM_ABI bool haveSameSign(const SCEV *S1, const SCEV *S2)
Return true if we know that S1 and S2 must have the same sign.
LLVM_ABI const SCEV * getNotSCEV(const SCEV *V)
Return the SCEV object corresponding to ~V.
LLVM_ABI bool instructionCouldExistWithOperands(const SCEV *A, const SCEV *B)
Return true if there exists a point in the program at which both A and B could be operands to the sam...
LLVM_ABI std::optional< SCEVFlags > getStrengthenedNoWrapFlagsFromBinOp(const OverflowingBinaryOperator *OBO)
Parse NSW/NUW flags from add/sub/mul IR binary operation Op into SCEV no-wrap flags,...
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
LLVM_ABI void print(raw_ostream &OS) const
LLVM_ABI const SCEV * getAnyExtendExpr(SCEVUse Op, Type *Ty)
getAnyExtendExpr - Return a SCEV for the given operand extended with unspecified bits out to the give...
LLVM_ABI const SCEV * getPredicatedExitCount(const Loop *L, const BasicBlock *ExitingBlock, SmallVectorImpl< const SCEVPredicate * > *Predicates, ExitCountKind Kind=Exact)
Same as above except this uses the predicated backedge taken info and may require predicates.
LLVM_ABI void forgetTopmostLoop(const Loop *L)
LLVM_ABI void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
APInt getSignedRangeMin(const SCEV *S)
Determine the min of the signed range for a particular SCEV.
LLVM_ABI bool isLoopUniform(const SCEV *S, const Loop *L)
Returns true if the given SCEV is loop-uniform with respect to the specified loop L.
LLVM_ABI const SCEV * getNoopOrAnyExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
LLVM_ABI const SCEV * getSignExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getUMaxExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantPredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI=nullptr)
If the result of the predicate LHS Pred RHS is loop invariant with respect to L, return a LoopInvaria...
LLVM_ABI const SCEV * getStoreSizeOfExpr(Type *IntTy, Type *StoreTy)
Return an expression for the store size of StoreTy that is type IntTy.
LLVM_ABI const SCEVPredicate * getWrapPredicate(const SCEVAddRecExpr *AR, SCEVWrapPredicate::IncrementWrapFlags AddedFlags)
LLVM_ABI bool isLoopBackedgeGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether the backedge of the loop is protected by a conditional between LHS and RHS.
LLVM_ABI APInt getNonZeroConstantMultiple(const SCEV *S)
const SCEV * getMinusOne(Type *Ty)
Return a SCEV for the constant -1 of a specific type.
LLVM_ABI bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count.
LLVM_ABI BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB)
Return the "disposition" of the given SCEV with respect to the given block.
LLVM_ABI const SCEV * getNoopOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
LLVM_ABI const SCEV * getUMinFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS, bool Sequential=false)
Promote the operands to the wider of the types using zero-extension, and then perform a umin operatio...
LLVM_ABI bool loopIsFiniteByAssumption(const Loop *L)
Return true if this loop is finite by assumption.
LLVM_ABI SCEVUse getSCEVAtExit(const SCEV *S, const Loop *L, const BasicBlock *ExitingBlock)
Return the SCEV expression at the specified loop exit.
LLVM_ABI const SCEV * getExistingSCEV(Value *V)
Return an existing SCEV for V if there is one, otherwise return nullptr.
LLVM_ABI APInt getConstantMultiple(const SCEV *S, const Instruction *CtxI=nullptr)
Returns the max constant multiple of S.
LoopDisposition
An enum describing the relationship between a SCEV and a loop.
@ LoopComputable
The SCEV varies predictably with the loop.
@ LoopVariant
The SCEV is loop-variant (unknown).
@ LoopInvariant
The SCEV is loop-invariant.
@ LoopUniform
The SCEV is loop-uniform.
LLVM_ABI bool isKnownToBeAPowerOfTwo(const SCEV *S, bool OrZero=false, bool OrNegative=false)
Test if the given expression is known to be a power of 2.
LLVM_ABI void forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V)
Forget LCSSA phi node V of loop L to which a new predecessor was added, such that it may no longer be...
LLVM_ABI bool containsUndefs(const SCEV *S) const
Return true if the SCEV expression contains an undef value.
LLVM_ABI std::optional< MonotonicPredicateType > getMonotonicPredicateType(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred)
If, for all loop invariant X, the predicate "LHS `Pred` X" is monotonically increasing or decreasing,...
LLVM_ABI const SCEV * getCouldNotCompute()
LLVM_ABI bool isAvailableAtLoopEntry(const SCEV *S, const Loop *L)
Determine if the SCEV can be evaluated at loop's entry.
LLVM_ABI uint32_t getMinTrailingZeros(const SCEV *S, const Instruction *CtxI=nullptr)
Determine the minimum number of zero bits that S is guaranteed to end in (at every loop iteration).
BlockDisposition
An enum describing the relationship between a SCEV and a basic block.
@ DominatesBlock
The SCEV dominates the block.
@ ProperlyDominatesBlock
The SCEV properly dominates the block.
@ DoesNotDominateBlock
The SCEV does not dominate the block.
LLVM_ABI const SCEV * getExitCount(const Loop *L, const BasicBlock *ExitingBlock, ExitCountKind Kind=Exact)
Return the number of times the backedge executes before the given exit would be taken; if not exactly...
LLVM_ABI void getPoisonGeneratingValues(SmallPtrSetImpl< const Value * > &Result, const SCEV *S)
Return the set of Values that, if poison, will definitively result in S being poison as well.
LLVM_ABI void setNoWrapFlags(SCEVAddRecExpr *AddRec, SCEVFlags Flags)
Update no-wrap flags of an AddRec.
LLVM_ABI void forgetLoopDispositions()
Called when the client has changed the disposition of values in this loop.
LLVM_ABI const SCEV * getVScale(Type *Ty)
LLVM_ABI SCEVUse getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
LLVM_ABI unsigned getSmallConstantTripCount(const Loop *L)
Returns the exact trip count of the loop if we can compute it, and the result is a small constant.
LLVM_ABI bool hasComputableLoopEvolution(const SCEV *S, const Loop *L)
Return true if the given SCEV changes value in a known way in the specified loop.
LLVM_ABI const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
LLVM_ABI void forgetAllLoops()
LLVM_ABI const SCEV * getSignExtendExprImpl(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool dominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV dominate the specified basic block.
APInt getUnsignedRangeMax(const SCEV *S)
Determine the max of the unsigned range for a particular SCEV.
ExitCountKind
The terms "backedge taken count" and "exit count" are used interchangeably to refer to the number of ...
@ SymbolicMaximum
An expression which provides an upper bound on the exact trip count.
@ ConstantMaximum
A constant which provides an upper bound on the exact trip count.
@ Exact
An expression exactly describing the number of times the backedge has executed when a loop is exited.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
LLVM_ABI const SCEV * getPtrToAddrExpr(const SCEV *Op)
LLVM_ABI const SCEVAddRecExpr * convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Preds)
Tries to convert the S expression to an AddRec expression, adding additional predicates to Preds as r...
LLVM_ABI const SCEV * getSMaxExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI const SCEV * getElementSize(Instruction *Inst)
Return the size of an element read or written by Inst.
LLVM_ABI const SCEV * getSizeOfExpr(Type *IntTy, TypeSize Size)
Return an expression for a TypeSize.
LLVM_ABI std::optional< bool > evaluatePredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Check whether the condition described by Pred, LHS, and RHS is true or false.
LLVM_ABI const SCEV * getUnknown(Value *V)
LLVM_ABI std::optional< std::pair< const SCEV *, SmallVector< const SCEVPredicate *, 3 > > > createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI)
Checks if SymbolicPHI can be rewritten as an AddRecExpr under some Predicates.
LLVM_ABI const SCEV * getTruncateOrZeroExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool isKnownViaInduction(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
We'd like to check the predicate on every iteration of the most dominated loop between loops used in ...
LLVM_ABI std::optional< APInt > computeConstantDifference(const SCEV *LHS, const SCEV *RHS)
Compute LHS - RHS and returns the result as an APInt if it is a constant, and std::nullopt if it isn'...
LLVM_ABI bool properlyDominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV properly dominate the specified basic block.
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEVFlags Flags=SCEV::FlagNone)
Return the SCEV object corresponding to -V.
LLVM_ABI const SCEV * getUDivExactExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
LLVM_ABI const SCEV * rewriteUsingPredicate(const SCEV *S, const Loop *L, const SCEVPredicate &A)
Re-writes the SCEV according to the Predicates in A.
LLVM_ABI std::pair< const SCEV *, const SCEV * > SplitIntoInitAndPostInc(const Loop *L, const SCEV *S)
Splits SCEV expression S into two SCEVs.
LLVM_ABI bool canReuseInstruction(const SCEV *S, Instruction *I, SmallVectorImpl< Instruction * > &DropPoisonGeneratingInsts)
Check whether it is poison-safe to represent the expression S using the instruction I.
LLVM_ABI bool isKnownPredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * getPredicatedSymbolicMaxBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getSymbolicMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
LLVM_ABI const SCEV * getGEPExpr(GEPOperator *GEP, ArrayRef< SCEVUse > IndexExprs)
Returns an expression for a GEP.
LLVM_ABI const SCEV * getUMinExpr(SCEVUse LHS, SCEVUse RHS, bool Sequential=false)
LLVM_ABI bool isBasicBlockEntryGuardedByCond(const BasicBlock *BB, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the basic block is protected by a conditional between LHS and RHS.
LLVM_ABI const SCEV * getTruncateOrSignExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool containsErasedValue(const SCEV *S) const
Return true if the SCEV expression contains a Value that has been optimised out and is now a nullptr.
const SCEV * getSymbolicMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEV that is greater than or equal to (i.e.
APInt getSignedRangeMax(const SCEV *S)
Determine the max of the signed range for a particular SCEV.
LLVM_ABI void verify() const
LLVMContext & getContext() const
This class represents the LLVM 'select' instruction.
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:293
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:743
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
TypeSize getSizeInBits() const
Definition DataLayout.h:754
Class to represent struct types.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
Use & Op()
Definition User.h:171
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition Value.h:545
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition APInt.h:2274
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition APInt.h:2279
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition APInt.h:2284
LLVM_ABI std::optional< APInt > SolveQuadraticEquationWrap(APInt A, APInt B, APInt C, unsigned RangeWidth)
Let q(n) = An^2 + Bn + C, and BW = bit width of the value range (e.g.
Definition APInt.cpp:2850
LLVM_ABI APInt GreatestCommonDivisor(APInt A, APInt B, bool IsSigned=false)
Compute GCD of two APInt values.
Definition APInt.cpp:826
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2289
constexpr bool any(E Val)
@ Entry
Definition COFF.h:862
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
bind_cst_ty m_scev_APInt(const APInt *&C)
Match an SCEV constant and bind it to an APInt.
cst_pred_ty< is_all_ones > m_scev_AllOnes()
Match an integer with all bits set.
SCEVUnaryExpr_match< SCEVZeroExtendExpr, Op0_t > m_scev_ZExt(const Op0_t &Op0)
is_undef_or_poison m_scev_UndefOrPoison()
Match an SCEVUnknown wrapping undef or poison.
cst_pred_ty< is_one > m_scev_One()
Match an integer 1.
specificloop_ty m_SpecificLoop(const Loop *L)
SCEVUnaryExpr_match< SCEVSignExtendExpr, Op0_t > m_scev_SExt(const Op0_t &Op0)
match_bind< const SCEVMulExpr > m_scev_Mul(const SCEVMulExpr *&V)
cst_pred_ty< is_zero > m_scev_Zero()
Match an integer 0.
SCEVUnaryExpr_match< SCEVTruncateExpr, Op0_t > m_scev_Trunc(const Op0_t &Op0)
bool match(const SCEV *S, const Pattern &P)
SCEVBinaryExpr_match< SCEVUDivExpr, Op0_t, Op1_t > m_scev_UDiv(const Op0_t &Op0, const Op1_t &Op1)
specificscev_ty m_scev_Specific(const SCEV *S)
Match if we have a specific specified SCEV.
SCEVAffineAddRec_match< Op0_t, Op1_t, match_isa< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
match_bind< const SCEVUnknown > m_SCEVUnknown(const SCEVUnknown *&V)
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t, SCEV::FlagNUW, true > m_scev_c_NUWMul(const Op0_t &Op0, const Op1_t &Op1)
SCEVBinaryExpr_match< SCEVSMaxExpr, Op0_t, Op1_t, SCEV::FlagNone, true > m_scev_SMax(const Op0_t &Op0, const Op1_t &Op1)
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t, SCEV::FlagNone, true > m_scev_c_Mul(const Op0_t &Op0, const Op1_t &Op1)
match_bind< const SCEVAddExpr > m_scev_Add(const SCEVAddExpr *&V)
SCEVURem_match< Op0_t, Op1_t > m_scev_URem(Op0_t LHS, Op1_t RHS, ScalarEvolution &SE)
Match the mathematical pattern A - (A / B) * B, where A and B can be arbitrary expressions.
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
Definition CoroShape.h:32
constexpr double e
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
void visitAll(const SCEV *Root, SV &Visitor)
Use SCEVTraversal to visit all nodes in the given expression tree.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
SaveAndRestore(T &) -> SaveAndRestore< T >
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
LLVM_ABI bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
LLVM_ABI bool mustTriggerUB(const Instruction *I, const SmallPtrSetImpl< const Value * > &KnownPoison)
Return true if the given instruction must trigger undefined behavior when I is executed with any oper...
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
@ Known
Known to have no common set bits.
@ Dead
Unused definition.
InterleavedRange< Range > interleaved(const Range &R, StringRef Separator=", ", StringRef Prefix="", StringRef Suffix="")
Output range R as a sequence of interleaved elements.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
auto successors(const MachineBasicBlock *BB)
scope_exit(Callable) -> scope_exit< Callable >
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
@ BinaryOp
One of the operands is a binary op.
constexpr from_range_t from_range
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
bool set_is_subset(const S1Ty &S1, const S2Ty &S2)
set_is_subset(A, B) - Return true iff A in B
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
void * PointerTy
LLVM_ABI bool VerifySCEV
auto uninitialized_copy(R &&Src, IterTy Dst)
Definition STLExtras.h:2127
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
LLVM_ABI bool canConstantFoldCallTo(const CallBase *Call, const Function *F, const TargetLibraryInfo *TLI=nullptr)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, const DominatorTree &DT)
Returns true if the arithmetic part of the WO 's result is used only along the paths control dependen...
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Function *CtxF=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2216
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI bool isMustProgress(const Loop *L)
Return true if this loop can be assumed to make progress.
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI bool isFinite(const Loop *L)
Return true if this loop can be assumed to run for a finite number of iterations.
unsigned short computeExpressionSize(ArrayRef< SCEVUse > Args)
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:381
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
LLVM_ABI bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ Mul
Product of integers.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ Add
Sum of integers.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
DWARFExpression::Operation Op
auto max_element(R &&Range)
Provide wrappers to std::max_element which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2104
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
SCEVFlags
SCEVFlags are bitfield indices into SCEV's SubclassData.
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:249
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
iterator_range< df_iterator< T > > depth_first(const T &G)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2162
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:267
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
SCEVUseT< const SCEV * > SCEVUse
bool SCEVExprContains(const SCEV *Root, PredTy Pred)
Return true if any node in Root satisfies the predicate Pred.
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
#define NC
Definition regutils.h:42
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
An object of this class is returned by queries that could not be answered.
static LLVM_ABI bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
The no-wrap flags to apply when creating a SCEV expression, to the expression and use respectively.
SCEVFlags ExprFlags
Flags applied directly to a SCEV expression, must be valid wherever the expression is valid.
SCEVFlags UseFlags
Flags only applied to a SCEVUse.
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.