LLVM 24.0.0git
ScalarEvolution.cpp
Go to the documentation of this file.
1//===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the implementation of the scalar evolution analysis
10// engine, which is used primarily to analyze expressions involving induction
11// variables in loops.
12//
13// There are several aspects to this library. First is the representation of
14// scalar expressions, which are represented as subclasses of the SCEV class.
15// These classes are used to represent certain types of subexpressions that we
16// can handle. We only create one SCEV of a particular shape, so
17// pointer-comparisons for equality are legal.
18//
19// One important aspect of the SCEV objects is that they are never cyclic, even
20// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
21// the PHI node is one of the idioms that we can represent (e.g., a polynomial
22// recurrence) then we represent it directly as a recurrence node, otherwise we
23// represent it as a SCEVUnknown node.
24//
25// In addition to being able to represent expressions of various types, we also
26// have folders that are used to build the *canonical* representation for a
27// particular expression. These folders are capable of using a variety of
28// rewrite rules to simplify the expressions.
29//
30// Once the folders are defined, we can implement the more interesting
31// higher-level code, such as the code that recognizes PHI nodes of various
32// types, computes the execution count of a loop, etc.
33//
34// TODO: We should use these routines and value representations to implement
35// dependence analysis!
36//
37//===----------------------------------------------------------------------===//
38//
39// There are several good references for the techniques used in this analysis.
40//
41// Chains of recurrences -- a method to expedite the evaluation
42// of closed-form functions
43// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
44//
45// On computational properties of chains of recurrences
46// Eugene V. Zima
47//
48// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
49// Robert A. van Engelen
50//
51// Efficient Symbolic Analysis for Optimizing Compilers
52// Robert A. van Engelen
53//
54// Using the chains of recurrences algebra for data dependence testing and
55// induction variable substitution
56// MS Thesis, Johnie Birch
57//
58//===----------------------------------------------------------------------===//
59
61#include "llvm/ADT/APInt.h"
62#include "llvm/ADT/ArrayRef.h"
63#include "llvm/ADT/DenseMap.h"
65#include "llvm/ADT/FoldingSet.h"
66#include "llvm/ADT/STLExtras.h"
67#include "llvm/ADT/ScopeExit.h"
68#include "llvm/ADT/Sequence.h"
71#include "llvm/ADT/Statistic.h"
73#include "llvm/ADT/StringRef.h"
83#include "llvm/Config/llvm-config.h"
84#include "llvm/IR/Argument.h"
85#include "llvm/IR/BasicBlock.h"
86#include "llvm/IR/CFG.h"
87#include "llvm/IR/Constant.h"
89#include "llvm/IR/Constants.h"
90#include "llvm/IR/DataLayout.h"
92#include "llvm/IR/Dominators.h"
93#include "llvm/IR/Function.h"
94#include "llvm/IR/GlobalAlias.h"
95#include "llvm/IR/GlobalValue.h"
97#include "llvm/IR/InstrTypes.h"
98#include "llvm/IR/Instruction.h"
101#include "llvm/IR/Intrinsics.h"
102#include "llvm/IR/LLVMContext.h"
103#include "llvm/IR/Operator.h"
104#include "llvm/IR/PatternMatch.h"
105#include "llvm/IR/Type.h"
106#include "llvm/IR/Use.h"
107#include "llvm/IR/User.h"
108#include "llvm/IR/Value.h"
109#include "llvm/IR/Verifier.h"
111#include "llvm/Pass.h"
112#include "llvm/Support/Casting.h"
115#include "llvm/Support/Debug.h"
121#include <algorithm>
122#include <cassert>
123#include <climits>
124#include <cstdint>
125#include <cstdlib>
126#include <map>
127#include <memory>
128#include <numeric>
129#include <optional>
130#include <tuple>
131#include <utility>
132#include <vector>
133
134using namespace llvm;
135using namespace PatternMatch;
136using namespace SCEVPatternMatch;
137
138#define DEBUG_TYPE "scalar-evolution"
139
140STATISTIC(NumExitCountsComputed,
141 "Number of loop exits with predictable exit counts");
142STATISTIC(NumExitCountsNotComputed,
143 "Number of loop exits without predictable exit counts");
144STATISTIC(NumBruteForceTripCountsComputed,
145 "Number of loops with trip counts computed by force");
146
147#ifdef EXPENSIVE_CHECKS
148bool llvm::VerifySCEV = true;
149#else
150bool llvm::VerifySCEV = false;
151#endif
152
154 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
155 cl::desc("Maximum number of iterations SCEV will "
156 "symbolically execute a constant "
157 "derived loop"),
158 cl::init(100));
159
161 "verify-scev", cl::Hidden, cl::location(VerifySCEV),
162 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
164 "verify-scev-strict", cl::Hidden,
165 cl::desc("Enable stricter verification with -verify-scev is passed"));
166
168 "scev-verify-ir", cl::Hidden,
169 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
170 cl::init(false));
171
173 "scev-mulops-inline-threshold", cl::Hidden,
174 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
175 cl::init(32));
176
178 "scev-addops-inline-threshold", cl::Hidden,
179 cl::desc("Threshold for inlining addition operands into a SCEV"),
180 cl::init(500));
181
183 "scalar-evolution-max-scev-compare-depth", cl::Hidden,
184 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
185 cl::init(32));
186
188 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
189 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
190 cl::init(2));
191
193 "scalar-evolution-max-value-compare-depth", cl::Hidden,
194 cl::desc("Maximum depth of recursive value complexity comparisons"),
195 cl::init(2));
196
198 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
199 cl::desc("Maximum depth of recursive arithmetics"),
200 cl::init(32));
201
203 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
204 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
205
207 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
208 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
209 cl::init(8));
210
212 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
213 cl::desc("Max coefficients in AddRec during evolving"),
214 cl::init(8));
215
217 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
218 cl::desc("Size of the expression which is considered huge"),
219 cl::init(4096));
220
222 "scev-range-iter-threshold", cl::Hidden,
223 cl::desc("Threshold for switching to iteratively computing SCEV ranges"),
224 cl::init(32));
225
227 "scalar-evolution-max-loop-guard-collection-depth", cl::Hidden,
228 cl::desc("Maximum depth for recursive loop guard collection"), cl::init(1));
229
230static cl::opt<bool>
231ClassifyExpressions("scalar-evolution-classify-expressions",
232 cl::Hidden, cl::init(true),
233 cl::desc("When printing analysis, include information on every instruction"));
234
236 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
237 cl::init(false),
238 cl::desc("Use more powerful methods of sharpening expression ranges. May "
239 "be costly in terms of compile time"));
240
241static cl::opt<bool>
242 EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
243 cl::desc("Handle <= and >= in finite loops"),
244 cl::init(true));
245
247 "scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden,
248 cl::desc("Infer nuw/nsw flags using context where suitable"),
249 cl::init(true));
250
251//===----------------------------------------------------------------------===//
252// SCEV class definitions
253//===----------------------------------------------------------------------===//
254
256 // Leaf nodes are always their own canonical.
257 switch (getSCEVType()) {
258 case scConstant:
259 case scVScale:
260 case scUnknown:
261 CanonicalSCEV = this;
262 return;
263 default:
264 break;
265 }
266
267 // For all other expressions, check whether any immediate operand has a
268 // different canonical. Since operands are always created before their parent,
269 // their canonical pointers are already set — no recursion needed.
270 bool Changed = false;
272 for (SCEVUse Op : operands()) {
273 CanonOps.push_back(Op->getCanonical());
274 Changed |= CanonOps.back() != Op;
275 }
276
277 if (!Changed) {
278 CanonicalSCEV = this;
279 return;
280 }
281
282 auto *NAry = dyn_cast<SCEVNAryExpr>(this);
283 SCEV::NoWrapFlags Flags = NAry ? NAry->getNoWrapFlags() : SCEV::FlagAnyWrap;
284 switch (getSCEVType()) {
285 case scPtrToAddr:
286 CanonicalSCEV = SE.getPtrToAddrExpr(CanonOps[0]);
287 return;
288 case scTruncate:
289 CanonicalSCEV = SE.getTruncateExpr(CanonOps[0], getType());
290 return;
291 case scZeroExtend:
292 CanonicalSCEV = SE.getZeroExtendExpr(CanonOps[0], getType());
293 return;
294 case scSignExtend:
295 CanonicalSCEV = SE.getSignExtendExpr(CanonOps[0], getType());
296 return;
297 case scUDivExpr:
298 CanonicalSCEV = SE.getUDivExpr(CanonOps[0], CanonOps[1]);
299 return;
300 case scAddExpr:
301 CanonicalSCEV = SE.getAddExpr(CanonOps, Flags);
302 return;
303 case scMulExpr:
304 CanonicalSCEV = SE.getMulExpr(CanonOps, Flags);
305 return;
306 case scAddRecExpr:
308 CanonOps, cast<SCEVAddRecExpr>(this)->getLoop(), Flags);
309 return;
310 case scSMaxExpr:
311 CanonicalSCEV = SE.getSMaxExpr(CanonOps);
312 return;
313 case scUMaxExpr:
314 CanonicalSCEV = SE.getUMaxExpr(CanonOps);
315 return;
316 case scSMinExpr:
317 CanonicalSCEV = SE.getSMinExpr(CanonOps);
318 return;
319 case scUMinExpr:
320 CanonicalSCEV = SE.getUMinExpr(CanonOps);
321 return;
323 CanonicalSCEV = SE.getUMinExpr(CanonOps, /*Sequential=*/true);
324 return;
325 default:
326 llvm_unreachable("Unknown SCEV type");
327 }
328}
329
330//===----------------------------------------------------------------------===//
331// Implementation of the SCEV class.
332//
333
334#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
336 print(dbgs());
337 dbgs() << '\n';
338}
339#endif
340
341void SCEV::print(raw_ostream &OS) const {
342 switch (getSCEVType()) {
343 case scConstant:
344 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
345 return;
346 case scVScale:
347 OS << "vscale";
348 return;
349 case scPtrToAddr: {
350 const SCEVCastExpr *PtrCast = cast<SCEVCastExpr>(this);
351 SCEVUse Op = PtrCast->getOperand();
352 OS << "(ptrtoaddr " << *Op->getType() << " " << Op << " to "
353 << *PtrCast->getType() << ")";
354 return;
355 }
356 case scTruncate: {
357 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
358 SCEVUse Op = Trunc->getOperand();
359 OS << "(trunc " << *Op->getType() << " " << Op << " to "
360 << *Trunc->getType() << ")";
361 return;
362 }
363 case scZeroExtend: {
365 SCEVUse Op = ZExt->getOperand();
366 OS << "(zext " << *Op->getType() << " " << Op << " to " << *ZExt->getType()
367 << ")";
368 return;
369 }
370 case scSignExtend: {
372 SCEVUse Op = SExt->getOperand();
373 OS << "(sext " << *Op->getType() << " " << Op << " to " << *SExt->getType()
374 << ")";
375 return;
376 }
377 case scAddRecExpr: {
378 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
379 OS << "{" << AR->getOperand(0);
380 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
381 OS << ",+," << AR->getOperand(i);
382 OS << "}<";
383 if (AR->hasNoUnsignedWrap())
384 OS << "nuw><";
385 if (AR->hasNoSignedWrap())
386 OS << "nsw><";
387 if (AR->hasNoSelfWrap() && !AR->hasNoUnsignedWrap() &&
388 !AR->hasNoSignedWrap())
389 OS << "nw><";
390 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
391 OS << ">";
392 return;
393 }
394 case scAddExpr:
395 case scMulExpr:
396 case scUMaxExpr:
397 case scSMaxExpr:
398 case scUMinExpr:
399 case scSMinExpr:
401 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
402 const char *OpStr = nullptr;
403 switch (NAry->getSCEVType()) {
404 case scAddExpr: OpStr = " + "; break;
405 case scMulExpr: OpStr = " * "; break;
406 case scUMaxExpr: OpStr = " umax "; break;
407 case scSMaxExpr: OpStr = " smax "; break;
408 case scUMinExpr:
409 OpStr = " umin ";
410 break;
411 case scSMinExpr:
412 OpStr = " smin ";
413 break;
415 OpStr = " umin_seq ";
416 break;
417 default:
418 llvm_unreachable("There are no other nary expression types.");
419 }
420 OS << "(" << llvm::interleaved(NAry->operands(), OpStr) << ")";
421 switch (NAry->getSCEVType()) {
422 case scAddExpr:
423 case scMulExpr:
424 if (NAry->hasNoUnsignedWrap())
425 OS << "<nuw>";
426 if (NAry->hasNoSignedWrap())
427 OS << "<nsw>";
428 break;
429 default:
430 // Nothing to print for other nary expressions.
431 break;
432 }
433 return;
434 }
435 case scUDivExpr: {
436 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
437 OS << "(" << UDiv->getLHS() << " /u " << UDiv->getRHS() << ")";
438 return;
439 }
440 case scUnknown:
441 cast<SCEVUnknown>(this)->getValue()->printAsOperand(OS, false);
442 return;
444 OS << "***COULDNOTCOMPUTE***";
445 return;
446 }
447 llvm_unreachable("Unknown SCEV kind!");
448}
449
451 switch (getSCEVType()) {
452 case scConstant:
453 case scVScale:
454 case scUnknown:
455 return {};
456 case scPtrToAddr:
457 case scTruncate:
458 case scZeroExtend:
459 case scSignExtend:
460 return cast<SCEVCastExpr>(this)->operands();
461 case scAddRecExpr:
462 case scAddExpr:
463 case scMulExpr:
464 case scUMaxExpr:
465 case scSMaxExpr:
466 case scUMinExpr:
467 case scSMinExpr:
469 return cast<SCEVNAryExpr>(this)->operands();
470 case scUDivExpr:
471 return cast<SCEVUDivExpr>(this)->operands();
473 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
474 }
475 llvm_unreachable("Unknown SCEV kind!");
476}
477
478bool SCEV::isZero() const { return match(this, m_scev_Zero()); }
479
480bool SCEV::isOne() const { return match(this, m_scev_One()); }
481
482bool SCEV::isAllOnesValue() const { return match(this, m_scev_AllOnes()); }
483
486 if (!Mul) return false;
487
488 // If there is a constant factor, it will be first.
489 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
490 if (!SC) return false;
491
492 // Return true if the value is negative, this matches things like (-42 * V).
493 return SC->getAPInt().isNegative();
494}
495
498
500 return S->getSCEVType() == scCouldNotCompute;
501}
502
504 auto &Entry = ConstantSCEVs[V];
505 if (Entry)
506 return Entry;
507
510 ID.AddPointer(V);
511 void *IP = nullptr;
512 if (SCEVConstant *S =
513 static_cast<SCEVConstant *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)))
514 return Entry = S;
515 SCEVConstant *S =
516 new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
517 UniqueSCEVs.InsertNode(S, IP);
518 S->computeAndSetCanonical(*this);
519 return Entry = S;
520}
521
523 return getConstant(ConstantInt::get(getContext(), Val));
524}
525
526const SCEV *
529 // TODO: Avoid implicit trunc?
530 // See https://github.com/llvm/llvm-project/issues/112510.
531 return getConstant(
532 ConstantInt::get(ITy, V, isSigned, /*ImplicitTrunc=*/true));
533}
534
538 ID.AddPointer(Ty);
539 void *IP = nullptr;
540 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
541 return S;
542 SCEV *S = new (SCEVAllocator) SCEVVScale(ID.Intern(SCEVAllocator), Ty);
543 UniqueSCEVs.InsertNode(S, IP);
544 S->computeAndSetCanonical(*this);
545 return S;
546}
547
549 SCEV::NoWrapFlags Flags) {
550 const SCEV *Res = getConstant(Ty, EC.getKnownMinValue());
551 if (EC.isScalable())
552 Res = getMulExpr(Res, getVScale(Ty), Flags);
553 return Res;
554}
555
557 SCEVUse op, Type *ty)
558 : SCEV(ID, SCEVTy, computeExpressionSize(op), ty), Op(op) {}
559
560SCEVPtrToAddrExpr::SCEVPtrToAddrExpr(const FoldingSetNodeIDRef ID,
561 const SCEV *Op, Type *ITy)
562 : SCEVCastExpr(ID, scPtrToAddr, Op, ITy) {
563 assert(getOperand()->getType()->isPointerTy() && getType()->isIntegerTy() &&
564 "Must be a non-bit-width-changing pointer-to-integer cast!");
565}
566
571
572SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
573 Type *ty)
575 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
576 "Cannot truncate non-integer value!");
577}
578
579SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
580 Type *ty)
582 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
583 "Cannot zero extend non-integer value!");
584}
585
586SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
587 Type *ty)
589 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
590 "Cannot sign extend non-integer value!");
591}
592
594 // Clear this SCEVUnknown from various maps.
595 SE->forgetMemoizedResults({this});
596
597 // Remove this SCEVUnknown from the uniquing map.
598 SE->UniqueSCEVs.RemoveNode(this);
599
600 // Release the value.
601 setValPtr(nullptr);
602}
603
604void SCEVUnknown::allUsesReplacedWith(Value *New) {
605 // Clear this SCEVUnknown from various maps.
606 SE->forgetMemoizedResults({this});
607
608 // Remove this SCEVUnknown from the uniquing map.
609 SE->UniqueSCEVs.RemoveNode(this);
610
611 // Replace the value pointer in case someone is still using this SCEVUnknown.
612 setValPtr(New);
613}
614
615//===----------------------------------------------------------------------===//
616// SCEV Utilities
617//===----------------------------------------------------------------------===//
618
619/// Compare the two values \p LV and \p RV in terms of their "complexity" where
620/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
621/// operands in SCEV expressions.
622static int CompareValueComplexity(const LoopInfo *const LI, Value *LV,
623 Value *RV, unsigned Depth) {
625 return 0;
626
627 // Order pointer values after integer values. This helps SCEVExpander form
628 // GEPs.
629 bool LIsPointer = LV->getType()->isPointerTy(),
630 RIsPointer = RV->getType()->isPointerTy();
631 if (LIsPointer != RIsPointer)
632 return (int)LIsPointer - (int)RIsPointer;
633
634 // Compare getValueID values.
635 unsigned LID = LV->getValueID(), RID = RV->getValueID();
636 if (LID != RID)
637 return (int)LID - (int)RID;
638
639 // Sort arguments by their position.
640 if (const auto *LA = dyn_cast<Argument>(LV)) {
641 const auto *RA = cast<Argument>(RV);
642 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
643 return (int)LArgNo - (int)RArgNo;
644 }
645
646 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
647 const auto *RGV = cast<GlobalValue>(RV);
648
649 if (auto L = LGV->getLinkage() - RGV->getLinkage())
650 return L;
651
652 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
653 auto LT = GV->getLinkage();
654 return !(GlobalValue::isPrivateLinkage(LT) ||
656 };
657
658 // Use the names to distinguish the two values, but only if the
659 // names are semantically important.
660 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
661 return LGV->getName().compare(RGV->getName());
662 }
663
664 // For instructions, compare their loop depth, and their operand count. This
665 // is pretty loose.
666 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
667 const auto *RInst = cast<Instruction>(RV);
668
669 // Compare loop depths.
670 const BasicBlock *LParent = LInst->getParent(),
671 *RParent = RInst->getParent();
672 if (LParent != RParent) {
673 unsigned LDepth = LI->getLoopDepth(LParent),
674 RDepth = LI->getLoopDepth(RParent);
675 if (LDepth != RDepth)
676 return (int)LDepth - (int)RDepth;
677 }
678
679 // Compare the number of operands.
680 unsigned LNumOps = LInst->getNumOperands(),
681 RNumOps = RInst->getNumOperands();
682 if (LNumOps != RNumOps)
683 return (int)LNumOps - (int)RNumOps;
684
685 for (unsigned Idx : seq(LNumOps)) {
686 int Result = CompareValueComplexity(LI, LInst->getOperand(Idx),
687 RInst->getOperand(Idx), Depth + 1);
688 if (Result != 0)
689 return Result;
690 }
691 }
692
693 return 0;
694}
695
696// Return negative, zero, or positive, if LHS is less than, equal to, or greater
697// than RHS, respectively. A three-way result allows recursive comparisons to be
698// more efficient.
699// If the max analysis depth was reached, return std::nullopt, assuming we do
700// not know if they are equivalent for sure.
701static std::optional<int>
702CompareSCEVComplexity(const LoopInfo *const LI, const SCEV *LHS,
703 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
704 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
705 if (LHS == RHS)
706 return 0;
707
708 // Primarily, sort the SCEVs by their getSCEVType().
709 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
710 if (LType != RType)
711 return (int)LType - (int)RType;
712
714 return std::nullopt;
715
716 // Aside from the getSCEVType() ordering, the particular ordering
717 // isn't very important except that it's beneficial to be consistent,
718 // so that (a + b) and (b + a) don't end up as different expressions.
719 switch (LType) {
720 case scUnknown: {
721 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
722 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
723
724 int X =
725 CompareValueComplexity(LI, LU->getValue(), RU->getValue(), Depth + 1);
726 return X;
727 }
728
729 case scConstant: {
732
733 // Compare constant values.
734 const APInt &LA = LC->getAPInt();
735 const APInt &RA = RC->getAPInt();
736 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
737 if (LBitWidth != RBitWidth)
738 return (int)LBitWidth - (int)RBitWidth;
739 return LA.ult(RA) ? -1 : 1;
740 }
741
742 case scVScale: {
743 const auto *LTy = cast<IntegerType>(cast<SCEVVScale>(LHS)->getType());
744 const auto *RTy = cast<IntegerType>(cast<SCEVVScale>(RHS)->getType());
745 return LTy->getBitWidth() - RTy->getBitWidth();
746 }
747
748 case scAddRecExpr: {
751
752 // There is always a dominance between two recs that are used by one SCEV,
753 // so we can safely sort recs by loop header dominance. We require such
754 // order in getAddExpr.
755 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
756 if (LLoop != RLoop) {
757 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
758 assert(LHead != RHead && "Two loops share the same header?");
759 if (DT.dominates(LHead, RHead))
760 return 1;
761 assert(DT.dominates(RHead, LHead) &&
762 "No dominance between recurrences used by one SCEV?");
763 return -1;
764 }
765
766 [[fallthrough]];
767 }
768
769 case scTruncate:
770 case scZeroExtend:
771 case scSignExtend:
772 case scPtrToAddr:
773 case scAddExpr:
774 case scMulExpr:
775 case scUDivExpr:
776 case scSMaxExpr:
777 case scUMaxExpr:
778 case scSMinExpr:
779 case scUMinExpr:
781 ArrayRef<SCEVUse> LOps = LHS->operands();
782 ArrayRef<SCEVUse> ROps = RHS->operands();
783
784 // Lexicographically compare n-ary-like expressions.
785 unsigned LNumOps = LOps.size(), RNumOps = ROps.size();
786 if (LNumOps != RNumOps)
787 return (int)LNumOps - (int)RNumOps;
788
789 for (unsigned i = 0; i != LNumOps; ++i) {
790 auto X = CompareSCEVComplexity(LI, LOps[i].getPointer(),
791 ROps[i].getPointer(), DT, Depth + 1);
792 if (X != 0)
793 return X;
794 }
795 return 0;
796 }
797
799 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
800 }
801 llvm_unreachable("Unknown SCEV kind!");
802}
803
804/// Given a list of SCEV objects, order them by their complexity, and group
805/// objects of the same complexity together by value. When this routine is
806/// finished, we know that any duplicates in the vector are consecutive and that
807/// complexity is monotonically increasing.
808///
809/// Note that we go take special precautions to ensure that we get deterministic
810/// results from this routine. In other words, we don't want the results of
811/// this to depend on where the addresses of various SCEV objects happened to
812/// land in memory.
814 DominatorTree &DT) {
815 if (Ops.size() < 2) return; // Noop
816
817 // Whether LHS has provably less complexity than RHS.
818 auto IsLessComplex = [&](SCEVUse LHS, SCEVUse RHS) {
819 auto Complexity = CompareSCEVComplexity(LI, LHS, RHS, DT);
820 return Complexity && *Complexity < 0;
821 };
822 if (Ops.size() == 2) {
823 // This is the common case, which also happens to be trivially simple.
824 // Special case it.
825 SCEVUse &LHS = Ops[0], &RHS = Ops[1];
826 if (IsLessComplex(RHS, LHS))
827 std::swap(LHS, RHS);
828 return;
829 }
830
831 // Do the rough sort by complexity.
833 Ops, [&](SCEVUse LHS, SCEVUse RHS) { return IsLessComplex(LHS, RHS); });
834
835 // Now that we are sorted by complexity, group elements of the same
836 // complexity. Note that this is, at worst, N^2, but the vector is likely to
837 // be extremely short in practice. Note that we take this approach because we
838 // do not want to depend on the addresses of the objects we are grouping.
839 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
840 const SCEV *S = Ops[i];
841 unsigned Complexity = S->getSCEVType();
842
843 // If there are any objects of the same complexity and same value as this
844 // one, group them.
845 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
846 if (Ops[j] == S) { // Found a duplicate.
847 // Move it to immediately after i'th element.
848 std::swap(Ops[i+1], Ops[j]);
849 ++i; // no need to rescan it.
850 if (i == e-2) return; // Done!
851 }
852 }
853 }
854}
855
856/// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
857/// least HugeExprThreshold nodes).
859 return any_of(Ops, [](const SCEV *S) {
861 });
862}
863
864/// Performs a number of common optimizations on the passed \p Ops. If the
865/// whole expression reduces down to a single operand, it will be returned.
866///
867/// The following optimizations are performed:
868/// * Fold constants using the \p Fold function.
869/// * Remove identity constants satisfying \p IsIdentity.
870/// * If a constant satisfies \p IsAbsorber, return it.
871/// * Sort operands by complexity.
872template <typename FoldT, typename IsIdentityT, typename IsAbsorberT>
873static const SCEV *
875 SmallVectorImpl<SCEVUse> &Ops, FoldT Fold,
876 IsIdentityT IsIdentity, IsAbsorberT IsAbsorber) {
877 const SCEVConstant *Folded = nullptr;
878 for (unsigned Idx = 0; Idx < Ops.size();) {
879 const SCEV *Op = Ops[Idx];
880 if (const auto *C = dyn_cast<SCEVConstant>(Op)) {
881 if (!Folded)
882 Folded = C;
883 else
884 Folded = cast<SCEVConstant>(
885 SE.getConstant(Fold(Folded->getAPInt(), C->getAPInt())));
886 Ops.erase(Ops.begin() + Idx);
887 continue;
888 }
889 ++Idx;
890 }
891
892 if (Ops.empty()) {
893 assert(Folded && "Must have folded value");
894 return Folded;
895 }
896
897 if (Folded && IsAbsorber(Folded->getAPInt()))
898 return Folded;
899
900 GroupByComplexity(Ops, &LI, DT);
901 if (Folded && !IsIdentity(Folded->getAPInt()))
902 Ops.insert(Ops.begin(), Folded);
903
904 return Ops.size() == 1 ? Ops[0] : nullptr;
905}
906
907//===----------------------------------------------------------------------===//
908// Simple SCEV method implementations
909//===----------------------------------------------------------------------===//
910
911/// Compute BC(It, K). The result has width W. Assume, K > 0.
912static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
913 ScalarEvolution &SE,
914 Type *ResultTy) {
915 // Handle the simplest case efficiently.
916 if (K == 1)
917 return SE.getTruncateOrZeroExtend(It, ResultTy);
918
919 // We are using the following formula for BC(It, K):
920 //
921 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
922 //
923 // Suppose, W is the bitwidth of the return value. We must be prepared for
924 // overflow. Hence, we must assure that the result of our computation is
925 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
926 // safe in modular arithmetic.
927 //
928 // However, this code doesn't use exactly that formula; the formula it uses
929 // is something like the following, where T is the number of factors of 2 in
930 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
931 // exponentiation:
932 //
933 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
934 //
935 // This formula is trivially equivalent to the previous formula. However,
936 // this formula can be implemented much more efficiently. The trick is that
937 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
938 // arithmetic. To do exact division in modular arithmetic, all we have
939 // to do is multiply by the inverse. Therefore, this step can be done at
940 // width W.
941 //
942 // The next issue is how to safely do the division by 2^T. The way this
943 // is done is by doing the multiplication step at a width of at least W + T
944 // bits. This way, the bottom W+T bits of the product are accurate. Then,
945 // when we perform the division by 2^T (which is equivalent to a right shift
946 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
947 // truncated out after the division by 2^T.
948 //
949 // In comparison to just directly using the first formula, this technique
950 // is much more efficient; using the first formula requires W * K bits,
951 // but this formula less than W + K bits. Also, the first formula requires
952 // a division step, whereas this formula only requires multiplies and shifts.
953 //
954 // It doesn't matter whether the subtraction step is done in the calculation
955 // width or the input iteration count's width; if the subtraction overflows,
956 // the result must be zero anyway. We prefer here to do it in the width of
957 // the induction variable because it helps a lot for certain cases; CodeGen
958 // isn't smart enough to ignore the overflow, which leads to much less
959 // efficient code if the width of the subtraction is wider than the native
960 // register width.
961 //
962 // (It's possible to not widen at all by pulling out factors of 2 before
963 // the multiplication; for example, K=2 can be calculated as
964 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
965 // extra arithmetic, so it's not an obvious win, and it gets
966 // much more complicated for K > 3.)
967
968 // Protection from insane SCEVs; this bound is conservative,
969 // but it probably doesn't matter.
970 if (K > 1000)
971 return SE.getCouldNotCompute();
972
973 unsigned W = SE.getTypeSizeInBits(ResultTy);
974
975 // Calculate K! / 2^T and T; we divide out the factors of two before
976 // multiplying for calculating K! / 2^T to avoid overflow.
977 // Other overflow doesn't matter because we only care about the bottom
978 // W bits of the result.
979 APInt OddFactorial(W, 1);
980 unsigned T = 1;
981 for (unsigned i = 3; i <= K; ++i) {
982 unsigned TwoFactors = countr_zero(i);
983 T += TwoFactors;
984 OddFactorial *= (i >> TwoFactors);
985 }
986
987 // We need at least W + T bits for the multiplication step
988 unsigned CalculationBits = W + T;
989
990 // Calculate 2^T, at width T+W.
991 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
992
993 // Calculate the multiplicative inverse of K! / 2^T;
994 // this multiplication factor will perform the exact division by
995 // K! / 2^T.
996 APInt MultiplyFactor = OddFactorial.multiplicativeInverse();
997
998 // Calculate the product, at width T+W
999 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1000 CalculationBits);
1001 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1002 for (unsigned i = 1; i != K; ++i) {
1003 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1004 Dividend = SE.getMulExpr(Dividend,
1005 SE.getTruncateOrZeroExtend(S, CalculationTy));
1006 }
1007
1008 // Divide by 2^T
1009 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1010
1011 // Truncate the result, and divide by K! / 2^T.
1012
1013 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1014 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1015}
1016
1017/// Return the value of this chain of recurrences at the specified iteration
1018/// number. We can evaluate this recurrence by multiplying each element in the
1019/// chain by the binomial coefficient corresponding to it. In other words, we
1020/// can evaluate {A,+,B,+,C,+,D} as:
1021///
1022/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1023///
1024/// where BC(It, k) stands for binomial coefficient.
1026 ScalarEvolution &SE) const {
1027 return evaluateAtIteration(operands(), It, SE);
1028}
1029
1031 const SCEV *It,
1032 ScalarEvolution &SE) {
1033 assert(Operands.size() > 0);
1034 const SCEV *Result = Operands[0].getPointer();
1035 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1036 // The computation is correct in the face of overflow provided that the
1037 // multiplication is performed _after_ the evaluation of the binomial
1038 // coefficient.
1039 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
1040 if (isa<SCEVCouldNotCompute>(Coeff))
1041 return Coeff;
1042
1043 Result =
1044 SE.getAddExpr(Result, SE.getMulExpr(Operands[i].getPointer(), Coeff));
1045 }
1046 return Result;
1047}
1048
1049//===----------------------------------------------------------------------===//
1050// SCEV Expression folder implementations
1051//===----------------------------------------------------------------------===//
1052
1053/// The SCEVCastSinkingRewriter takes a scalar evolution expression,
1054/// which computes a pointer-typed value, and rewrites the whole expression
1055/// tree so that *all* the computations are done on integers, and the only
1056/// pointer-typed operands in the expression are SCEVUnknown.
1057/// The CreatePtrCast callback is invoked to create the actual conversion
1058/// (ptrtoint or ptrtoaddr) at the SCEVUnknown leaves.
1060 : public SCEVRewriteVisitor<SCEVCastSinkingRewriter> {
1062 using ConversionFn = function_ref<const SCEV *(const SCEVUnknown *)>;
1063 Type *TargetTy;
1064 ConversionFn CreatePtrCast;
1065
1066public:
1068 ConversionFn CreatePtrCast)
1069 : Base(SE), TargetTy(TargetTy), CreatePtrCast(std::move(CreatePtrCast)) {}
1070
1071 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
1072 Type *TargetTy, ConversionFn CreatePtrCast) {
1073 SCEVCastSinkingRewriter Rewriter(SE, TargetTy, std::move(CreatePtrCast));
1074 return Rewriter.visit(Scev);
1075 }
1076
1077 const SCEV *visit(const SCEV *S) {
1078 Type *STy = S->getType();
1079 // If the expression is not pointer-typed, just keep it as-is.
1080 if (!STy->isPointerTy())
1081 return S;
1082 // Else, recursively sink the cast down into it.
1083 return Base::visit(S);
1084 }
1085
1086 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1087 // Preserve wrap flags on rewritten SCEVAddExpr, which the default
1088 // implementation drops.
1090 bool Changed = false;
1091 for (SCEVUse Op : Expr->operands()) {
1092 Operands.push_back(visit(Op.getPointer()));
1093 Changed |= Op.getPointer() != Operands.back();
1094 }
1095 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1096 }
1097
1098 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1100 bool Changed = false;
1101 for (SCEVUse Op : Expr->operands()) {
1102 Operands.push_back(visit(Op.getPointer()));
1103 Changed |= Op.getPointer() != Operands.back();
1104 }
1105 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1106 }
1107
1108 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1109 assert(Expr->getType()->isPointerTy() &&
1110 "Should only reach pointer-typed SCEVUnknown's.");
1111 // Perform some basic constant folding. If the operand of the cast is a
1112 // null pointer, don't create a cast SCEV expression (that will be left
1113 // as-is), but produce a zero constant.
1115 return SE.getZero(TargetTy);
1116 return CreatePtrCast(Expr);
1117 }
1118};
1119
1121 assert(Op->getType()->isPointerTy() && "Op must be a pointer");
1122
1123 // Treat pointers with unstable representation conservatively, since the
1124 // address bits may change.
1125 if (DL.hasUnstableRepresentation(Op->getType()))
1126 return getCouldNotCompute();
1127
1128 Type *Ty = DL.getAddressType(Op->getType());
1129
1130 // Use the rewriter to sink the cast down to SCEVUnknown leaves.
1131 // The rewriter handles null pointer constant folding.
1133 Op, *this, Ty, [this, Ty](const SCEVUnknown *U) {
1136 ID.AddPointer(U);
1137 ID.AddPointer(Ty);
1138 void *IP = nullptr;
1139 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1140 return S;
1141 SCEV *S = new (SCEVAllocator)
1142 SCEVPtrToAddrExpr(ID.Intern(SCEVAllocator), U, Ty);
1143 UniqueSCEVs.InsertNode(S, IP);
1144 S->computeAndSetCanonical(*this);
1145 registerUser(S, U);
1146 return static_cast<const SCEV *>(S);
1147 });
1148 assert(IntOp->getType()->isIntegerTy() &&
1149 "We must have succeeded in sinking the cast, "
1150 "and ending up with an integer-typed expression!");
1151 return IntOp;
1152}
1153
1155 unsigned Depth) {
1156 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1157 "This is not a truncating conversion!");
1158 assert(isSCEVable(Ty) &&
1159 "This is not a conversion to a SCEVable type!");
1160 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1161 Ty = getEffectiveSCEVType(Ty);
1162
1165 ID.AddPointer(Op.getOpaqueValue());
1166 ID.AddPointer(Ty);
1167 void *IP = nullptr;
1168 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1169
1170 // Fold if the operand is constant.
1171 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1172 return getConstant(
1173 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1174
1175 // trunc(trunc(x)) --> trunc(x)
1177 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1178
1179 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1181 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1182
1183 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1185 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1186
1187 if (Depth > MaxCastDepth) {
1188 SCEV *S =
1189 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1190 UniqueSCEVs.InsertNode(S, IP);
1191 S->computeAndSetCanonical(*this);
1192 registerUser(S, Op);
1193 return S;
1194 }
1195
1196 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1197 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1198 // if after transforming we have at most one truncate, not counting truncates
1199 // that replace other casts.
1201 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1203 unsigned numTruncs = 0;
1204 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1205 ++i) {
1206 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1207 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1209 numTruncs++;
1210 Operands.push_back(S);
1211 }
1212 if (numTruncs < 2) {
1213 if (isa<SCEVAddExpr>(Op))
1214 return getAddExpr(Operands);
1215 if (isa<SCEVMulExpr>(Op))
1216 return getMulExpr(Operands);
1217 llvm_unreachable("Unexpected SCEV type for Op.");
1218 }
1219 // Although we checked in the beginning that ID is not in the cache, it is
1220 // possible that during recursion and different modification ID was inserted
1221 // into the cache. So if we find it, just return it.
1222 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1223 return S;
1224 }
1225
1226 // If the input value is a chrec scev, truncate the chrec's operands.
1227 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1229 for (const SCEV *Op : AddRec->operands())
1230 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1231 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1232 }
1233
1234 // Return zero if truncating to known zeros.
1235 uint32_t MinTrailingZeros = getMinTrailingZeros(Op);
1236 if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1237 return getZero(Ty);
1238
1239 // The cast wasn't folded; create an explicit cast node. We can reuse
1240 // the existing insert position since if we get here, we won't have
1241 // made any changes which would invalidate it.
1242 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1243 Op, Ty);
1244 UniqueSCEVs.InsertNode(S, IP);
1245 S->computeAndSetCanonical(*this);
1246 registerUser(S, Op);
1247 return S;
1248}
1249
1250// Get the limit of a recurrence such that incrementing by Step cannot cause
1251// signed overflow as long as the value of the recurrence within the
1252// loop does not exceed this limit before incrementing.
1253static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1254 ICmpInst::Predicate *Pred,
1255 ScalarEvolution *SE) {
1256 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1257 if (SE->isKnownPositive(Step)) {
1258 *Pred = ICmpInst::ICMP_SLT;
1260 SE->getSignedRangeMax(Step));
1261 }
1262 if (SE->isKnownNegative(Step)) {
1263 *Pred = ICmpInst::ICMP_SGT;
1265 SE->getSignedRangeMin(Step));
1266 }
1267 return nullptr;
1268}
1269
1270// Get the limit of a recurrence such that incrementing by Step cannot cause
1271// unsigned overflow as long as the value of the recurrence within the loop does
1272// not exceed this limit before incrementing.
1274 ICmpInst::Predicate *Pred,
1275 ScalarEvolution *SE) {
1276 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1277 *Pred = ICmpInst::ICMP_ULT;
1278
1280 SE->getUnsignedRangeMax(Step));
1281}
1282
1283namespace {
1284
1285struct ExtendOpTraitsBase {
1286 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(SCEVUse, Type *,
1287 unsigned);
1288};
1289
1290// Used to make code generic over signed and unsigned overflow.
1291template <typename ExtendOp> struct ExtendOpTraits {
1292 // Members present:
1293 //
1294 // static const SCEV::NoWrapFlags WrapType;
1295 //
1296 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1297 //
1298 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1299 // ICmpInst::Predicate *Pred,
1300 // ScalarEvolution *SE);
1301};
1302
1303template <>
1304struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1305 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1306
1307 static const GetExtendExprTy GetExtendExpr;
1308
1309 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1310 ICmpInst::Predicate *Pred,
1311 ScalarEvolution *SE) {
1312 return getSignedOverflowLimitForStep(Step, Pred, SE);
1313 }
1314};
1315
1316const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1318
1319template <>
1320struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1321 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1322
1323 static const GetExtendExprTy GetExtendExpr;
1324
1325 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1326 ICmpInst::Predicate *Pred,
1327 ScalarEvolution *SE) {
1328 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1329 }
1330};
1331
1332const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1334
1335} // end anonymous namespace
1336
1337// The recurrence AR has been shown to have no signed/unsigned wrap or something
1338// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1339// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1340// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1341// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1342// expression "Step + sext/zext(PreIncAR)" is congruent with
1343// "sext/zext(PostIncAR)"
1344template <typename ExtendOpTy>
1345static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1346 ScalarEvolution *SE, unsigned Depth) {
1347 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1348 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1349
1350 const Loop *L = AR->getLoop();
1351 const SCEV *Start = AR->getStart();
1352 const SCEV *Step = AR->getStepRecurrence(*SE);
1353
1354 // Check for a simple looking step prior to loop entry.
1355 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1356 if (!SA)
1357 return nullptr;
1358
1359 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1360 // subtraction is expensive. For this purpose, perform a quick and dirty
1361 // difference, by checking for Step in the operand list. Note, that
1362 // SA might have repeated ops, like %a + %a + ..., so only remove one.
1363 SmallVector<SCEVUse, 4> DiffOps(SA->operands());
1364 for (auto It = DiffOps.begin(); It != DiffOps.end(); ++It)
1365 if (*It == Step) {
1366 DiffOps.erase(It);
1367 break;
1368 }
1369
1370 if (DiffOps.size() == SA->getNumOperands())
1371 return nullptr;
1372
1373 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1374 // `Step`:
1375
1376 // 1. NSW/NUW flags on the step increment.
1377 auto PreStartFlags =
1379 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1381 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1382
1383 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1384 // "S+X does not sign/unsign-overflow".
1385 //
1386
1387 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1388 if (PreAR && any(PreAR->getNoWrapFlags(WrapType)) &&
1389 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1390 return PreStart;
1391
1392 // 2. Direct overflow check on the step operation's expression.
1393 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1394 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1395 const SCEV *OperandExtendedStart =
1396 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1397 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1398 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1399 if (PreAR && any(AR->getNoWrapFlags(WrapType))) {
1400 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1401 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1402 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1403 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1404 }
1405 return PreStart;
1406 }
1407
1408 // 3. Loop precondition.
1410 const SCEV *OverflowLimit =
1411 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1412
1413 if (OverflowLimit &&
1414 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1415 return PreStart;
1416
1417 return nullptr;
1418}
1419
1420// Get the normalized zero or sign extended expression for this AddRec's Start.
1421template <typename ExtendOpTy>
1422static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1423 ScalarEvolution *SE,
1424 unsigned Depth) {
1425 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1426
1427 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1428 if (!PreStart)
1429 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1430
1431 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1432 Depth),
1433 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1434}
1435
1436// Try to prove away overflow by looking at "nearby" add recurrences. A
1437// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1438// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1439//
1440// Formally:
1441//
1442// {S,+,X} == {S-T,+,X} + T
1443// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1444//
1445// If ({S-T,+,X} + T) does not overflow ... (1)
1446//
1447// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1448//
1449// If {S-T,+,X} does not overflow ... (2)
1450//
1451// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1452// == {Ext(S-T)+Ext(T),+,Ext(X)}
1453//
1454// If (S-T)+T does not overflow ... (3)
1455//
1456// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1457// == {Ext(S),+,Ext(X)} == LHS
1458//
1459// Thus, if (1), (2) and (3) are true for some T, then
1460// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1461//
1462// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1463// does not overflow" restricted to the 0th iteration. Therefore we only need
1464// to check for (1) and (2).
1465//
1466// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1467// is `Delta` (defined below).
1468template <typename ExtendOpTy>
1469bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1470 const SCEV *Step,
1471 const Loop *L) {
1472 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1473
1474 // We restrict `Start` to a constant to prevent SCEV from spending too much
1475 // time here. It is correct (but more expensive) to continue with a
1476 // non-constant `Start` and do a general SCEV subtraction to compute
1477 // `PreStart` below.
1478 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1479 if (!StartC)
1480 return false;
1481
1482 APInt StartAI = StartC->getAPInt();
1483
1484 for (unsigned Delta : {-2, -1, 1, 2}) {
1485 const SCEV *PreStart = getConstant(StartAI - Delta);
1486
1487 FoldingSetNodeID ID;
1488 ID.AddInteger(scAddRecExpr);
1489 ID.AddPointer(PreStart);
1490 ID.AddPointer(Step);
1491 ID.AddPointer(L);
1492 void *IP = nullptr;
1493 const auto *PreAR =
1494 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1495
1496 // Give up if we don't already have the add recurrence we need because
1497 // actually constructing an add recurrence is relatively expensive.
1498 if (PreAR && any(PreAR->getNoWrapFlags(WrapType))) { // proves (2)
1499 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1501 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1502 DeltaS, &Pred, this);
1503 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1504 return true;
1505 }
1506 }
1507
1508 return false;
1509}
1510
1511// Finds an integer D for an expression (C + x + y + ...) such that the top
1512// level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1513// unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1514// maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1515// the (C + x + y + ...) expression is \p WholeAddExpr.
1517 const SCEVConstant *ConstantTerm,
1518 const SCEVAddExpr *WholeAddExpr) {
1519 const APInt &C = ConstantTerm->getAPInt();
1520 const unsigned BitWidth = C.getBitWidth();
1521 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1522 uint32_t TZ = BitWidth;
1523 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1524 TZ = std::min(TZ, SE.getMinTrailingZeros(WholeAddExpr->getOperand(I)));
1525 if (TZ) {
1526 // Set D to be as many least significant bits of C as possible while still
1527 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1528 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1529 }
1530 return APInt(BitWidth, 0);
1531}
1532
1533// Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1534// level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1535// number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1536// ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1538 const APInt &ConstantStart,
1539 const SCEV *Step) {
1540 const unsigned BitWidth = ConstantStart.getBitWidth();
1541 const uint32_t TZ = SE.getMinTrailingZeros(Step);
1542 if (TZ)
1543 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1544 : ConstantStart;
1545 return APInt(BitWidth, 0);
1546}
1547
1549 const ScalarEvolution::FoldID &ID, const SCEV *S,
1552 &FoldCacheUser) {
1553 auto I = FoldCache.insert({ID, S});
1554 if (!I.second) {
1555 // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1556 // entry.
1557 auto &UserIDs = FoldCacheUser[I.first->second];
1558 assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
1559 for (unsigned I = 0; I != UserIDs.size(); ++I)
1560 if (UserIDs[I] == ID) {
1561 std::swap(UserIDs[I], UserIDs.back());
1562 break;
1563 }
1564 UserIDs.pop_back();
1565 I.first->second = S;
1566 }
1567 FoldCacheUser[S].push_back(ID);
1568}
1569
1571 unsigned Depth) {
1572 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1573 "This is not an extending conversion!");
1574 assert(isSCEVable(Ty) &&
1575 "This is not a conversion to a SCEVable type!");
1576 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1577 Ty = getEffectiveSCEVType(Ty);
1578
1579 FoldID ID(scZeroExtend, Op, Ty);
1580 if (const SCEV *S = FoldCache.lookup(ID))
1581 return S;
1582
1583 const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1585 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1586 return S;
1587}
1588
1590 unsigned Depth) {
1591 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1592 "This is not an extending conversion!");
1593 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1594 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1595
1596 // Fold if the operand is constant.
1597 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1598 return getConstant(SC->getAPInt().zext(getTypeSizeInBits(Ty)));
1599
1600 // zext(zext(x)) --> zext(x)
1602 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1603
1604 // If the operand is an affine AddRec with the no-unsigned-wrap flag, the
1605 // zero-extension distributes over the recurrence.
1606 const SCEV *Start, *Step;
1607 const Loop *L;
1608 if (Depth <= MaxCastDepth &&
1609 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1610 const auto *AR = cast<SCEVAddRecExpr>(Op);
1611 if (AR->hasNoUnsignedWrap()) {
1612 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1613 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1614 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1615 }
1616 }
1617
1618 // Before doing any expensive analysis, check to see if we've already
1619 // computed a SCEV for this Op and Ty.
1622 ID.AddPointer(Op.getOpaqueValue());
1623 ID.AddPointer(Ty);
1624 void *IP = nullptr;
1625 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1626 if (Depth > MaxCastDepth) {
1627 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1628 Op, Ty);
1629 UniqueSCEVs.InsertNode(S, IP);
1630 S->computeAndSetCanonical(*this);
1631 registerUser(S, Op);
1632 return S;
1633 }
1634
1635 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1637 // It's possible the bits taken off by the truncate were all zero bits. If
1638 // so, we should be able to simplify this further.
1639 const SCEV *X = ST->getOperand();
1641 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1642 unsigned NewBits = getTypeSizeInBits(Ty);
1643 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1644 CR.zextOrTrunc(NewBits)))
1645 return getTruncateOrZeroExtend(X, Ty, Depth);
1646 }
1647
1648 // If the input value is a chrec scev, and we can prove that the value
1649 // did not overflow the old, smaller, value, we can zero extend all of the
1650 // operands (often constants). This allows analysis of something like
1651 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1652 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1653 const auto *AR = cast<SCEVAddRecExpr>(Op);
1654 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1655
1656 // The no-unsigned-wrap case is handled before the uniquing lookup above.
1657
1658 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1659 // Note that this serves two purposes: It filters out loops that are
1660 // simply not analyzable, and it covers the case where this code is
1661 // being called from within backedge-taken count analysis, such that
1662 // attempting to ask for the backedge-taken count would likely result
1663 // in infinite recursion. In the later case, the analysis code will
1664 // cope with a conservative value, and it will take care to purge
1665 // that value once it has finished.
1666 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1667 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1668 // Manually compute the final value for AR, checking for overflow.
1669
1670 // Check whether the backedge-taken count can be losslessly casted to
1671 // the addrec's type. The count is always unsigned.
1672 const SCEV *CastedMaxBECount =
1673 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1674 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1675 CastedMaxBECount, MaxBECount->getType(), Depth);
1676 if (MaxBECount == RecastedMaxBECount) {
1677 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1678 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1679 const SCEV *ZMul =
1680 getMulExpr(CastedMaxBECount, Step, SCEV::FlagAnyWrap, Depth + 1);
1681 const SCEV *ZAdd = getZeroExtendExpr(
1682 getAddExpr(Start, ZMul, SCEV::FlagAnyWrap, Depth + 1), WideTy,
1683 Depth + 1);
1684 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1685 const SCEV *WideMaxBECount =
1686 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1687 const SCEV *OperandExtendedAdd =
1688 getAddExpr(WideStart,
1689 getMulExpr(WideMaxBECount,
1690 getZeroExtendExpr(Step, WideTy, Depth + 1),
1693 if (ZAdd == OperandExtendedAdd) {
1694 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1695 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1696 // Return the expression with the addrec on the outside.
1697 Start =
1699 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1700 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1701 }
1702 // Similar to above, only this time treat the step value as signed.
1703 // This covers loops that count down.
1704 OperandExtendedAdd =
1705 getAddExpr(WideStart,
1706 getMulExpr(WideMaxBECount,
1707 getSignExtendExpr(Step, WideTy, Depth + 1),
1710 if (ZAdd == OperandExtendedAdd) {
1711 // Cache knowledge of AR NW, which is propagated to this AddRec.
1712 // Negative step causes unsigned wrap, but it still can't self-wrap.
1713 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1714 // Return the expression with the addrec on the outside.
1715 Start =
1717 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1718 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1719 }
1720 }
1721 }
1722
1723 // Normally, in the cases we can prove no-overflow via a
1724 // backedge guarding condition, we can also compute a backedge
1725 // taken count for the loop. The exceptions are assumptions and
1726 // guards present in the loop -- SCEV is not great at exploiting
1727 // these to compute max backedge taken counts, but can still use
1728 // these to prove lack of overflow. Use this fact to avoid
1729 // doing extra work that may not pay off.
1730 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1731 !AC.assumptions().empty()) {
1732
1733 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1734 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1735 if (AR->hasNoUnsignedWrap()) {
1736 // Same as nuw case above - duplicated here to avoid a compile time
1737 // issue. It's not clear that the order of checks does matter, but
1738 // it's one of two issue possible causes for a change which was
1739 // reverted. Be conservative for the moment.
1740 Start =
1742 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1743 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1744 }
1745
1746 // For a negative step, we can extend the operands iff doing so only
1747 // traverses values in the range zext([0,UINT_MAX]).
1748 if (isKnownNegative(Step)) {
1749 const SCEV *N =
1753 // Cache knowledge of AR NW, which is propagated to this
1754 // AddRec. Negative step causes unsigned wrap, but it
1755 // still can't self-wrap.
1756 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1757 // Return the expression with the addrec on the outside.
1758 Start =
1760 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1761 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1762 }
1763 }
1764 }
1765
1766 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1767 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1768 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1769 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1770 const APInt &C = SC->getAPInt();
1771 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1772 if (D != 0) {
1773 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1774 const SCEV *SResidual =
1775 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1776 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1777 return getAddExpr(SZExtD, SZExtR, SCEV::FlagNSW | SCEV::FlagNUW,
1778 Depth + 1);
1779 }
1780 }
1781
1782 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1783 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1784 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1785 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1786 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1787 }
1788 }
1789
1790 // zext(A % B) --> zext(A) % zext(B)
1791 {
1792 const SCEV *LHS;
1793 const SCEV *RHS;
1794 if (match(Op, m_scev_URem(m_SCEV(LHS), m_SCEV(RHS), *this)))
1795 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1796 getZeroExtendExpr(RHS, Ty, Depth + 1));
1797 }
1798
1799 // zext(A / B) --> zext(A) / zext(B).
1800 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1801 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1802 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1803
1804 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1805 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1806 if (SA->hasNoUnsignedWrap()) {
1807 // If the addition does not unsign overflow then we can, by definition,
1808 // commute the zero extension with the addition operation.
1810 for (SCEVUse Op : SA->operands())
1811 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1812 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1813 }
1814
1815 const APInt *C, *C2;
1816 // zext (C + A)<nsw> -> (sext(C) + sext(A))<nsw> if zext (C + A)<nsw> >=s 0.
1817 // Currently the non-negative check is done manually, as isKnownNonNegative
1818 // is too expensive.
1819 if (SA->hasNoSignedWrap() &&
1821 m_scev_SMax(m_scev_APInt(C2), m_SCEV()))) &&
1822 C->isNegative() && !C->isMinSignedValue() && C2->sge(C->abs())) {
1823 assert(isKnownNonNegative(SA) && "incorrectly determined non-negative");
1824 return getAddExpr(getSignExtendExpr(SA->getOperand(0), Ty, Depth + 1),
1825 getSignExtendExpr(SA->getOperand(1), Ty, Depth + 1),
1826 SCEV::FlagNSW, Depth + 1);
1827 }
1828
1829 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1830 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1831 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1832 //
1833 // Often address arithmetics contain expressions like
1834 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1835 // This transformation is useful while proving that such expressions are
1836 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1837 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1838 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1839 if (D != 0) {
1840 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1841 const SCEV *SResidual =
1843 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1844 return getAddExpr(SZExtD, SZExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1845 Depth + 1);
1846 }
1847 }
1848 }
1849
1850 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1851 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1852 if (SM->hasNoUnsignedWrap()) {
1853 // If the multiply does not unsign overflow then we can, by definition,
1854 // commute the zero extension with the multiply operation.
1856 for (SCEVUse Op : SM->operands())
1857 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1858 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1859 }
1860
1861 // zext(2^K * (trunc X to iN)) to iM ->
1862 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1863 //
1864 // Proof:
1865 //
1866 // zext(2^K * (trunc X to iN)) to iM
1867 // = zext((trunc X to iN) << K) to iM
1868 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1869 // (because shl removes the top K bits)
1870 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1871 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1872 //
1873 const APInt *C;
1874 const SCEV *TruncRHS;
1875 if (match(SM,
1876 m_scev_Mul(m_scev_APInt(C), m_scev_Trunc(m_SCEV(TruncRHS)))) &&
1877 C->isPowerOf2()) {
1878 int NewTruncBits =
1879 getTypeSizeInBits(SM->getOperand(1)->getType()) - C->logBase2();
1880 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1881 return getMulExpr(
1882 getZeroExtendExpr(SM->getOperand(0), Ty),
1883 getZeroExtendExpr(getTruncateExpr(TruncRHS, NewTruncTy), Ty),
1884 SCEV::FlagNUW, Depth + 1);
1885 }
1886 }
1887
1888 // zext(umin(x, y)) -> umin(zext(x), zext(y))
1889 // zext(umax(x, y)) -> umax(zext(x), zext(y))
1893 for (SCEVUse Operand : MinMax->operands())
1894 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1896 return getUMinExpr(Operands);
1897 return getUMaxExpr(Operands);
1898 }
1899
1900 // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
1902 assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!");
1904 for (SCEVUse Operand : MinMax->operands())
1905 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1906 return getUMinExpr(Operands, /*Sequential*/ true);
1907 }
1908
1909 // The cast wasn't folded; create an explicit cast node.
1910 // Recompute the insert position, as it may have been invalidated.
1911 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1912 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1913 Op, Ty);
1914 UniqueSCEVs.InsertNode(S, IP);
1915 S->computeAndSetCanonical(*this);
1916 registerUser(S, Op);
1917 return S;
1918}
1919
1921 unsigned Depth) {
1922 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1923 "This is not an extending conversion!");
1924 assert(isSCEVable(Ty) &&
1925 "This is not a conversion to a SCEVable type!");
1926 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1927 Ty = getEffectiveSCEVType(Ty);
1928
1929 FoldID ID(scSignExtend, Op, Ty);
1930 if (const SCEV *S = FoldCache.lookup(ID))
1931 return S;
1932
1933 const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
1935 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1936 return S;
1937}
1938
1940 unsigned Depth) {
1941 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1942 "This is not an extending conversion!");
1943 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1944 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1945 Ty = getEffectiveSCEVType(Ty);
1946
1947 // Fold if the operand is constant.
1948 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1949 return getConstant(SC->getAPInt().sext(getTypeSizeInBits(Ty)));
1950
1951 // sext(sext(x)) --> sext(x)
1953 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1954
1955 // sext(zext(x)) --> zext(x)
1957 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1958
1959 // If the operand is an affine AddRec with the no-signed-wrap flag, the
1960 // sign-extension distributes over the recurrence.
1961 const SCEV *Start, *Step;
1962 const Loop *L;
1963 if (Depth <= MaxCastDepth &&
1964 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1965 const auto *AR = cast<SCEVAddRecExpr>(Op);
1966 if (AR->hasNoSignedWrap()) {
1967 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
1968 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1969 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1970 }
1971 }
1972
1973 // Before doing any expensive analysis, check to see if we've already
1974 // computed a SCEV for this Op and Ty.
1977 ID.AddPointer(Op.getOpaqueValue());
1978 ID.AddPointer(Ty);
1979 void *IP = nullptr;
1980 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1981 // Limit recursion depth.
1982 if (Depth > MaxCastDepth) {
1983 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1984 Op, Ty);
1985 UniqueSCEVs.InsertNode(S, IP);
1986 S->computeAndSetCanonical(*this);
1987 registerUser(S, Op);
1988 return S;
1989 }
1990
1991 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1993 // It's possible the bits taken off by the truncate were all sign bits. If
1994 // so, we should be able to simplify this further.
1995 const SCEV *X = ST->getOperand();
1997 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1998 unsigned NewBits = getTypeSizeInBits(Ty);
1999 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
2000 CR.sextOrTrunc(NewBits)))
2001 return getTruncateOrSignExtend(X, Ty, Depth);
2002 }
2003
2004 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
2005 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
2006 if (SA->hasNoSignedWrap()) {
2007 // If the addition does not sign overflow then we can, by definition,
2008 // commute the sign extension with the addition operation.
2010 for (SCEVUse Op : SA->operands())
2011 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
2012 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
2013 }
2014
2015 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
2016 // if D + (C - D + x + y + ...) could be proven to not signed wrap
2017 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
2018 //
2019 // For instance, this will bring two seemingly different expressions:
2020 // 1 + sext(5 + 20 * %x + 24 * %y) and
2021 // sext(6 + 20 * %x + 24 * %y)
2022 // to the same form:
2023 // 2 + sext(4 + 20 * %x + 24 * %y)
2024 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
2025 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
2026 if (D != 0) {
2027 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2028 const SCEV *SResidual =
2030 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2031 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
2032 Depth + 1);
2033 }
2034 }
2035 }
2036 // If the input value is a chrec scev, and we can prove that the value
2037 // did not overflow the old, smaller, value, we can sign extend all of the
2038 // operands (often constants). This allows analysis of something like
2039 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
2040 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
2041 const auto *AR = cast<SCEVAddRecExpr>(Op);
2042 unsigned BitWidth = getTypeSizeInBits(AR->getType());
2043
2044 // The no-signed-wrap case is handled before the uniquing lookup above.
2045
2046 // Check whether the backedge-taken count is SCEVCouldNotCompute.
2047 // Note that this serves two purposes: It filters out loops that are
2048 // simply not analyzable, and it covers the case where this code is
2049 // being called from within backedge-taken count analysis, such that
2050 // attempting to ask for the backedge-taken count would likely result
2051 // in infinite recursion. In the later case, the analysis code will
2052 // cope with a conservative value, and it will take care to purge
2053 // that value once it has finished.
2054 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2055 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2056 // Manually compute the final value for AR, checking for
2057 // overflow.
2058
2059 // Check whether the backedge-taken count can be losslessly casted to
2060 // the addrec's type. The count is always unsigned.
2061 const SCEV *CastedMaxBECount =
2062 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2063 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2064 CastedMaxBECount, MaxBECount->getType(), Depth);
2065 if (MaxBECount == RecastedMaxBECount) {
2066 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2067 // Check whether Start+Step*MaxBECount has no signed overflow.
2068 const SCEV *SMul =
2069 getMulExpr(CastedMaxBECount, Step, SCEV::FlagAnyWrap, Depth + 1);
2070 const SCEV *SAdd = getSignExtendExpr(
2071 getAddExpr(Start, SMul, SCEV::FlagAnyWrap, Depth + 1), WideTy,
2072 Depth + 1);
2073 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2074 const SCEV *WideMaxBECount =
2075 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2076 const SCEV *OperandExtendedAdd =
2077 getAddExpr(WideStart,
2078 getMulExpr(WideMaxBECount,
2079 getSignExtendExpr(Step, WideTy, Depth + 1),
2082 if (SAdd == OperandExtendedAdd) {
2083 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2084 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2085 // Return the expression with the addrec on the outside.
2086 Start =
2088 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2089 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2090 }
2091 // Similar to above, only this time treat the step value as unsigned.
2092 // This covers loops that count up with an unsigned step.
2093 OperandExtendedAdd =
2094 getAddExpr(WideStart,
2095 getMulExpr(WideMaxBECount,
2096 getZeroExtendExpr(Step, WideTy, Depth + 1),
2099 if (SAdd == OperandExtendedAdd) {
2100 // If AR wraps around then
2101 //
2102 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2103 // => SAdd != OperandExtendedAdd
2104 //
2105 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2106 // (SAdd == OperandExtendedAdd => AR is NW)
2107
2108 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2109
2110 // Return the expression with the addrec on the outside.
2111 Start =
2113 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
2114 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2115 }
2116 }
2117 }
2118
2119 auto NewFlags = proveNoSignedWrapViaInduction(AR);
2120 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2121 if (AR->hasNoSignedWrap()) {
2122 // Same as nsw case above - duplicated here to avoid a compile time
2123 // issue. It's not clear that the order of checks does matter, but
2124 // it's one of two issue possible causes for a change which was
2125 // reverted. Be conservative for the moment.
2126 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2127 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2128 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2129 }
2130
2131 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2132 // if D + (C - D + Step * n) could be proven to not signed wrap
2133 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2134 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2135 const APInt &C = SC->getAPInt();
2136 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2137 if (D != 0) {
2138 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2139 const SCEV *SResidual =
2140 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2141 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2142 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
2143 Depth + 1);
2144 }
2145 }
2146
2147 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2148 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2149 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2150 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2151 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2152 }
2153 }
2154
2155 // If the input value is provably positive and we could not simplify
2156 // away the sext build a zext instead.
2158 return getZeroExtendExpr(Op, Ty, Depth + 1);
2159
2160 // sext(smin(x, y)) -> smin(sext(x), sext(y))
2161 // sext(smax(x, y)) -> smax(sext(x), sext(y))
2165 for (SCEVUse Operand : MinMax->operands())
2166 Operands.push_back(getSignExtendExpr(Operand, Ty));
2168 return getSMinExpr(Operands);
2169 return getSMaxExpr(Operands);
2170 }
2171
2172 // The cast wasn't folded; create an explicit cast node.
2173 // Recompute the insert position, as it may have been invalidated.
2174 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2175 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2176 Op, Ty);
2177 UniqueSCEVs.InsertNode(S, IP);
2178 S->computeAndSetCanonical(*this);
2179 registerUser(S, Op);
2180 return S;
2181}
2182
2184 switch (Kind) {
2185 case scTruncate:
2186 return getTruncateExpr(Op, Ty);
2187 case scZeroExtend:
2188 return getZeroExtendExpr(Op, Ty);
2189 case scSignExtend:
2190 return getSignExtendExpr(Op, Ty);
2191 case scPtrToAddr: {
2192 const SCEV *Expr = getPtrToAddrExpr(Op);
2193 assert(Expr->getType() == Ty && "requested type must match");
2194 return Expr;
2195 }
2196 default:
2197 llvm_unreachable("Not a SCEV cast expression!");
2198 }
2199}
2200
2201/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2202/// unspecified bits out to the given type.
2204 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2205 "This is not an extending conversion!");
2206 assert(isSCEVable(Ty) &&
2207 "This is not a conversion to a SCEVable type!");
2208 Ty = getEffectiveSCEVType(Ty);
2209
2210 // Sign-extend negative constants.
2211 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2212 if (SC->getAPInt().isNegative())
2213 return getSignExtendExpr(Op, Ty);
2214
2215 // Peel off a truncate cast.
2217 const SCEV *NewOp = T->getOperand();
2218 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2219 return getAnyExtendExpr(NewOp, Ty);
2220 return getTruncateOrNoop(NewOp, Ty);
2221 }
2222
2223 // Next try a zext cast. If the cast is folded, use it.
2224 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2225 if (!isa<SCEVZeroExtendExpr>(ZExt))
2226 return ZExt;
2227
2228 // Next try a sext cast. If the cast is folded, use it.
2229 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2230 if (!isa<SCEVSignExtendExpr>(SExt))
2231 return SExt;
2232
2233 // Force the cast to be folded into the operands of an addrec.
2234 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2236 for (const SCEV *Op : AR->operands())
2237 Ops.push_back(getAnyExtendExpr(Op, Ty));
2238 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2239 }
2240
2241 // If the expression is obviously signed, use the sext cast value.
2242 if (isa<SCEVSMaxExpr>(Op))
2243 return SExt;
2244
2245 // Absent any other information, use the zext cast value.
2246 return ZExt;
2247}
2248
2249/// Process the given Ops list, which is a list of operands to be added under
2250/// the given scale, update the given map. This is a helper function for
2251/// getAddRecExpr. As an example of what it does, given a sequence of operands
2252/// that would form an add expression like this:
2253///
2254/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2255///
2256/// where A and B are constants, update the map with these values:
2257///
2258/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2259///
2260/// and add 13 + A*B*29 to AccumulatedConstant.
2261/// This will allow getAddRecExpr to produce this:
2262///
2263/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2264///
2265/// This form often exposes folding opportunities that are hidden in
2266/// the original operand list.
2267///
2268/// Return true iff it appears that any interesting folding opportunities
2269/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2270/// the common case where no interesting opportunities are present, and
2271/// is also used as a check to avoid infinite recursion.
2274 APInt &AccumulatedConstant,
2276 const APInt &Scale,
2277 ScalarEvolution &SE) {
2278 bool Interesting = false;
2279
2280 // Iterate over the add operands. They are sorted, with constants first.
2281 unsigned i = 0;
2282 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2283 ++i;
2284 // Pull a buried constant out to the outside.
2285 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2286 Interesting = true;
2287 AccumulatedConstant += Scale * C->getAPInt();
2288 }
2289
2290 // Next comes everything else. We're especially interested in multiplies
2291 // here, but they're in the middle, so just visit the rest with one loop.
2292 for (; i != Ops.size(); ++i) {
2294 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2295 APInt NewScale =
2296 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2297 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2298 // A multiplication of a constant with another add; recurse.
2299 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2300 Interesting |= CollectAddOperandsWithScales(
2301 M, NewOps, AccumulatedConstant, Add->operands(), NewScale, SE);
2302 } else {
2303 // A multiplication of a constant with some other value. Update
2304 // the map.
2305 SmallVector<SCEVUse, 4> MulOps(drop_begin(Mul->operands()));
2306 const SCEV *Key = SE.getMulExpr(MulOps);
2307 auto Pair = M.insert({Key, NewScale});
2308 if (Pair.second) {
2309 NewOps.push_back(Pair.first->first);
2310 } else {
2311 Pair.first->second += NewScale;
2312 // The map already had an entry for this value, which may indicate
2313 // a folding opportunity.
2314 Interesting = true;
2315 }
2316 }
2317 } else {
2318 // An ordinary operand. Update the map.
2319 auto Pair = M.insert({Ops[i], Scale});
2320 if (Pair.second) {
2321 NewOps.push_back(Pair.first->first);
2322 } else {
2323 Pair.first->second += Scale;
2324 // The map already had an entry for this value, which may indicate
2325 // a folding opportunity.
2326 Interesting = true;
2327 }
2328 }
2329 }
2330
2331 return Interesting;
2332}
2333
2335 const SCEV *LHS, const SCEV *RHS,
2336 const Instruction *CtxI) {
2338 unsigned);
2339 switch (BinOp) {
2340 default:
2341 llvm_unreachable("Unsupported binary op");
2342 case Instruction::Add:
2344 break;
2345 case Instruction::Sub:
2347 break;
2348 case Instruction::Mul:
2350 break;
2351 }
2352
2353 const SCEV *(ScalarEvolution::*Extension)(SCEVUse, Type *, unsigned) =
2356
2357 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2358 auto *NarrowTy = cast<IntegerType>(LHS->getType());
2359 auto *WideTy =
2360 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2361
2362 const SCEV *A = (this->*Extension)(
2363 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2364 const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2365 const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2366 const SCEV *B = (this->*Operation)(LHSB, RHSB, SCEV::FlagAnyWrap, 0);
2367 if (A == B)
2368 return true;
2369 // Can we use context to prove the fact we need?
2370 if (!CtxI)
2371 return false;
2372 // TODO: Support mul.
2373 if (BinOp == Instruction::Mul)
2374 return false;
2375 auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2376 // TODO: Lift this limitation.
2377 if (!RHSC)
2378 return false;
2379 APInt C = RHSC->getAPInt();
2380 unsigned NumBits = C.getBitWidth();
2381 bool IsSub = (BinOp == Instruction::Sub);
2382 bool IsNegativeConst = (Signed && C.isNegative());
2383 // Compute the direction and magnitude by which we need to check overflow.
2384 bool OverflowDown = IsSub ^ IsNegativeConst;
2385 APInt Magnitude = C;
2386 if (IsNegativeConst) {
2387 if (C == APInt::getSignedMinValue(NumBits))
2388 // TODO: SINT_MIN on inversion gives the same negative value, we don't
2389 // want to deal with that.
2390 return false;
2391 Magnitude = -C;
2392 }
2393
2395 if (OverflowDown) {
2396 // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2397 APInt Min = Signed ? APInt::getSignedMinValue(NumBits)
2398 : APInt::getMinValue(NumBits);
2399 APInt Limit = Min + Magnitude;
2400 return isKnownPredicateAt(Pred, getConstant(Limit), LHS, CtxI);
2401 } else {
2402 // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2403 APInt Max = Signed ? APInt::getSignedMaxValue(NumBits)
2404 : APInt::getMaxValue(NumBits);
2405 APInt Limit = Max - Magnitude;
2406 return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2407 }
2408}
2409
2410std::optional<SCEV::NoWrapFlags>
2412 const OverflowingBinaryOperator *OBO) {
2413 // It cannot be done any better.
2414 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2415 return std::nullopt;
2416
2417 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2418
2419 if (OBO->hasNoUnsignedWrap())
2421 if (OBO->hasNoSignedWrap())
2423
2424 bool Deduced = false;
2425
2427 const SCEV *LHS = getSCEV(OBO->getOperand(0));
2428 const SCEV *RHS = getSCEV(OBO->getOperand(1));
2429
2430 bool CanUseNSW = true;
2431 const APInt *ShiftAmt;
2432 // Treat `shl %a, C` as `mul %a, 1 << C`.
2433 if (match(OBO, m_Shl(m_Value(), m_APInt(ShiftAmt)))) {
2434 unsigned BitWidth = ShiftAmt->getBitWidth();
2435 if (ShiftAmt->uge(BitWidth))
2436 return std::nullopt;
2437 // NSW only transfers if the shift amount is < BitWidth - 1, as INT_MIN * -1
2438 // overflows.
2439 CanUseNSW = ShiftAmt->ult(BitWidth - 1);
2440 Opcode = Instruction::Mul;
2442 } else if (Opcode != Instruction::Add && Opcode != Instruction::Sub &&
2443 Opcode != Instruction::Mul) {
2444 return std::nullopt;
2445 }
2446
2447 const Instruction *CtxI =
2449 if (!OBO->hasNoUnsignedWrap() &&
2450 willNotOverflow(Opcode, /* Signed */ false, LHS, RHS, CtxI)) {
2452 Deduced = true;
2453 }
2454
2455 if (CanUseNSW && !OBO->hasNoSignedWrap() &&
2456 willNotOverflow(Opcode, /* Signed */ true, LHS, RHS, CtxI)) {
2458 Deduced = true;
2459 }
2460
2461 if (Deduced)
2462 return Flags;
2463 return std::nullopt;
2464}
2465
2466// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2467// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2468// can't-overflow flags for the operation if possible.
2472 SCEV::NoWrapFlags Flags) {
2473 using namespace std::placeholders;
2474
2475 using OBO = OverflowingBinaryOperator;
2476
2477 bool CanAnalyze =
2479 (void)CanAnalyze;
2480 assert(CanAnalyze && "don't call from other places!");
2481
2482 SCEV::NoWrapFlags SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2483 SCEV::NoWrapFlags SignOrUnsignWrap =
2484 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2485
2486 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2487 auto IsKnownNonNegative = [&](SCEVUse U) {
2488 return SE->isKnownNonNegative(U);
2489 };
2490
2491 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2492 Flags = ScalarEvolution::setFlags(Flags, SignOrUnsignMask);
2493
2494 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2495
2496 if (SignOrUnsignWrap != SignOrUnsignMask &&
2497 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2498 isa<SCEVConstant>(Ops[0])) {
2499
2500 auto Opcode = [&] {
2501 switch (Type) {
2502 case scAddExpr:
2503 return Instruction::Add;
2504 case scMulExpr:
2505 return Instruction::Mul;
2506 default:
2507 llvm_unreachable("Unexpected SCEV op.");
2508 }
2509 }();
2510
2511 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2512
2513 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2514 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2516 Opcode, C, OBO::NoSignedWrap);
2517 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2519 }
2520
2521 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2522 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2524 Opcode, C, OBO::NoUnsignedWrap);
2525 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2527 }
2528 }
2529
2530 // <0,+,nonnegative><nw> is also nuw
2531 // TODO: Add corresponding nsw case
2533 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2534 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2536
2537 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2539 Ops.size() == 2) {
2540 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2541 if (UDiv->getOperand(1) == Ops[1])
2543 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2544 if (UDiv->getOperand(1) == Ops[0])
2546 }
2547
2548 return Flags;
2549}
2550
2552 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2553}
2554
2555/// Get a canonical add expression, or something simpler if possible.
2557 SCEV::NoWrapFlags OrigFlags,
2558 unsigned Depth) {
2559 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2560 "only nuw or nsw allowed");
2561 assert(!Ops.empty() && "Cannot get empty add!");
2562 if (Ops.size() == 1) return Ops[0];
2563#ifndef NDEBUG
2564 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2565 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2566 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2567 "SCEVAddExpr operand types don't match!");
2568 unsigned NumPtrs = count_if(
2569 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2570 assert(NumPtrs <= 1 && "add has at most one pointer operand");
2571#endif
2572
2573 const SCEV *Folded = constantFoldAndGroupOps(
2574 *this, LI, DT, Ops,
2575 [](const APInt &C1, const APInt &C2) { return C1 + C2; },
2576 [](const APInt &C) { return C.isZero(); }, // identity
2577 [](const APInt &C) { return false; }); // absorber
2578 if (Folded)
2579 return Folded;
2580
2581 unsigned Idx = isa<SCEVConstant>(Ops[0]) ? 1 : 0;
2582
2583 // Delay expensive flag strengthening until necessary.
2584 auto ComputeFlags = [this, OrigFlags](ArrayRef<SCEVUse> Ops) {
2585 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2586 };
2587
2588 // Limit recursion calls depth.
2590 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2591
2592 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2593 // Don't strengthen flags if we have no new information.
2594 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2595 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2596 Add->setNoWrapFlags(ComputeFlags(Ops));
2597 return S;
2598 }
2599
2600 // Okay, check to see if the same value occurs in the operand list more than
2601 // once. If so, merge them together into an multiply expression. Since we
2602 // sorted the list, these values are required to be adjacent.
2603 Type *Ty = Ops[0]->getType();
2604 bool FoundMatch = false;
2605 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2606 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2607 // Scan ahead to count how many equal operands there are.
2608 unsigned Count = 2;
2609 while (i+Count != e && Ops[i+Count] == Ops[i])
2610 ++Count;
2611 // Merge the values into a multiply.
2612 SCEVUse Scale = getConstant(Ty, Count);
2613 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2614 if (Ops.size() == Count)
2615 return Mul;
2616 Ops[i] = Mul;
2617 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2618 --i; e -= Count - 1;
2619 FoundMatch = true;
2620 }
2621 if (FoundMatch)
2622 return getAddExpr(Ops, OrigFlags, Depth + 1);
2623
2624 // Check for truncates. If all the operands are truncated from the same
2625 // type, see if factoring out the truncate would permit the result to be
2626 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2627 // if the contents of the resulting outer trunc fold to something simple.
2628 auto FindTruncSrcType = [&]() -> Type * {
2629 // We're ultimately looking to fold an addrec of truncs and muls of only
2630 // constants and truncs, so if we find any other types of SCEV
2631 // as operands of the addrec then we bail and return nullptr here.
2632 // Otherwise, we return the type of the operand of a trunc that we find.
2633 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2634 return T->getOperand()->getType();
2635 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2636 SCEVUse LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2637 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2638 return T->getOperand()->getType();
2639 }
2640 return nullptr;
2641 };
2642 if (auto *SrcType = FindTruncSrcType()) {
2643 SmallVector<SCEVUse, 8> LargeOps;
2644 bool Ok = true;
2645 // Check all the operands to see if they can be represented in the
2646 // source type of the truncate.
2647 for (const SCEV *Op : Ops) {
2649 if (T->getOperand()->getType() != SrcType) {
2650 Ok = false;
2651 break;
2652 }
2653 LargeOps.push_back(T->getOperand());
2654 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Op)) {
2655 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2656 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Op)) {
2657 SmallVector<SCEVUse, 8> LargeMulOps;
2658 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2659 if (const SCEVTruncateExpr *T =
2660 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2661 if (T->getOperand()->getType() != SrcType) {
2662 Ok = false;
2663 break;
2664 }
2665 LargeMulOps.push_back(T->getOperand());
2666 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2667 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2668 } else {
2669 Ok = false;
2670 break;
2671 }
2672 }
2673 if (Ok)
2674 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2675 } else {
2676 Ok = false;
2677 break;
2678 }
2679 }
2680 if (Ok) {
2681 // Evaluate the expression in the larger type.
2682 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2683 // If it folds to something simple, use it. Otherwise, don't.
2684 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2685 return getTruncateExpr(Fold, Ty);
2686 }
2687 }
2688
2689 if (Ops.size() == 2) {
2690 // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2691 // C2 can be folded in a way that allows retaining wrapping flags of (X +
2692 // C1).
2693 const SCEV *A = Ops[0];
2694 const SCEV *B = Ops[1];
2695 auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2696 auto *C = dyn_cast<SCEVConstant>(A);
2697 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2698 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2699 auto C2 = C->getAPInt();
2700 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2701
2702 APInt ConstAdd = C1 + C2;
2703 auto AddFlags = AddExpr->getNoWrapFlags();
2704 // Adding a smaller constant is NUW if the original AddExpr was NUW.
2706 ConstAdd.ule(C1)) {
2707 PreservedFlags =
2709 }
2710
2711 // Adding a constant with the same sign and small magnitude is NSW, if the
2712 // original AddExpr was NSW.
2714 C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2715 ConstAdd.abs().ule(C1.abs())) {
2716 PreservedFlags =
2718 }
2719
2720 if (PreservedFlags != SCEV::FlagAnyWrap) {
2721 SmallVector<SCEVUse, 4> NewOps(AddExpr->operands());
2722 NewOps[0] = getConstant(ConstAdd);
2723 return getAddExpr(NewOps, PreservedFlags);
2724 }
2725 }
2726
2727 // Try to push the constant operand into a ZExt: A + zext (-A + B) -> zext
2728 // (B), if trunc (A) + -A + B does not unsigned-wrap.
2729 const SCEVAddExpr *InnerAdd;
2730 if (match(B, m_scev_ZExt(m_scev_Add(InnerAdd)))) {
2731 const SCEV *NarrowA = getTruncateExpr(A, InnerAdd->getType());
2732 if (NarrowA == getNegativeSCEV(InnerAdd->getOperand(0)) &&
2733 getZeroExtendExpr(NarrowA, B->getType()) == A &&
2734 hasFlags(StrengthenNoWrapFlags(this, scAddExpr, {NarrowA, InnerAdd},
2736 SCEV::FlagNUW)) {
2737 return getZeroExtendExpr(getAddExpr(NarrowA, InnerAdd), B->getType());
2738 }
2739 }
2740 }
2741
2742 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2743 const SCEV *Y;
2744 if (Ops.size() == 2 &&
2745 match(Ops[0],
2747 m_scev_URem(m_scev_Specific(Ops[1]), m_SCEV(Y), *this))))
2748 return getMulExpr(Y, getUDivExpr(Ops[1], Y));
2749
2750 // Skip past any other cast SCEVs.
2751 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2752 ++Idx;
2753
2754 // If there are add operands they would be next.
2755 if (Idx < Ops.size()) {
2756 bool DeletedAdd = false;
2757 // If the original flags and all inlined SCEVAddExprs are NUW, use the
2758 // common NUW flag for expression after inlining. Other flags cannot be
2759 // preserved, because they may depend on the original order of operations.
2760 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2761 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2762 if (Ops.size() > AddOpsInlineThreshold ||
2763 Add->getNumOperands() > AddOpsInlineThreshold)
2764 break;
2765 // If we have an add, expand the add operands onto the end of the operands
2766 // list.
2767 Ops.erase(Ops.begin()+Idx);
2768 append_range(Ops, Add->operands());
2769 DeletedAdd = true;
2770 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2771 }
2772
2773 // If we deleted at least one add, we added operands to the end of the list,
2774 // and they are not necessarily sorted. Recurse to resort and resimplify
2775 // any operands we just acquired.
2776 if (DeletedAdd)
2777 return getAddExpr(Ops, CommonFlags, Depth + 1);
2778 }
2779
2780 // Skip over the add expression until we get to a multiply.
2781 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2782 ++Idx;
2783
2784 // Check to see if there are any folding opportunities present with
2785 // operands multiplied by constant values.
2786 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2787 uint64_t BitWidth = getTypeSizeInBits(Ty);
2790 APInt AccumulatedConstant(BitWidth, 0);
2791 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2792 Ops, APInt(BitWidth, 1), *this)) {
2793 struct APIntCompare {
2794 bool operator()(const APInt &LHS, const APInt &RHS) const {
2795 return LHS.ult(RHS);
2796 }
2797 };
2798
2799 // Some interesting folding opportunity is present, so its worthwhile to
2800 // re-generate the operands list. Group the operands by constant scale,
2801 // to avoid multiplying by the same constant scale multiple times.
2802 std::map<APInt, SmallVector<SCEVUse, 4>, APIntCompare> MulOpLists;
2803 for (const SCEV *NewOp : NewOps)
2804 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2805 // Re-generate the operands list.
2806 Ops.clear();
2807 if (AccumulatedConstant != 0)
2808 Ops.push_back(getConstant(AccumulatedConstant));
2809 for (auto &MulOp : MulOpLists) {
2810 if (MulOp.first == 1) {
2811 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2812 } else if (MulOp.first != 0) {
2813 Ops.push_back(getMulExpr(
2814 getConstant(MulOp.first),
2815 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2816 SCEV::FlagAnyWrap, Depth + 1));
2817 }
2818 }
2819 if (Ops.empty())
2820 return getZero(Ty);
2821 if (Ops.size() == 1)
2822 return Ops[0];
2823 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2824 }
2825 }
2826
2827 // Given a SCEVMulExpr and an operand index, return the product of all
2828 // operands except the one at OpIdx.
2829 auto StripFactor = [&](const SCEVMulExpr *M, unsigned OpIdx) -> SCEVUse {
2830 if (M->getNumOperands() == 2)
2831 return M->getOperand(OpIdx == 0);
2832 SmallVector<SCEVUse, 4> Remaining(M->operands().take_front(OpIdx));
2833 append_range(Remaining, M->operands().drop_front(OpIdx + 1));
2834 return getMulExpr(Remaining, SCEV::FlagAnyWrap, Depth + 1);
2835 };
2836
2837 // If we are adding something to a multiply expression, make sure the
2838 // something is not already an operand of the multiply. If so, merge it into
2839 // the multiply.
2840 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2841 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2842 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2843 // Scan all terms to find every occurrence of common factor MulOpSCEV
2844 // and fold them in one shot:
2845 // A1*X + A2*X + ... + An*X --> X * (A1 + A2 + ... + An)
2846 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2847 if (isa<SCEVConstant>(MulOpSCEV))
2848 continue;
2849
2850 // Cofactors: 1 for bare addends matching MulOpSCEV, or the
2851 // remaining product for multiply terms containing MulOpSCEV.
2852 SmallVector<SCEVUse, 4> Cofactors;
2853 SmallVector<unsigned, 4> DeadIndices;
2854 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) {
2855 if (MulOpSCEV == Ops[AddOp]) {
2856 // W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2857 Cofactors.push_back(getOne(Ty));
2858 DeadIndices.push_back(AddOp);
2859 continue;
2860 }
2861
2862 if (AddOp <= Idx || !isa<SCEVMulExpr>(Ops[AddOp]))
2863 continue;
2864
2865 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[AddOp]);
2866 for (unsigned OMulOp = 0, OE = OtherMul->getNumOperands(); OMulOp != OE;
2867 ++OMulOp) {
2868 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2869 // (A*B*C) + (A*D*E) --> A * (B*C + D*E)
2870 Cofactors.push_back(StripFactor(OtherMul, OMulOp));
2871 DeadIndices.push_back(AddOp);
2872 break;
2873 }
2874 }
2875 }
2876
2877 // Fold all collected cofactors with the anchor multiply's cofactor:
2878 // MulOpSCEV * (Cofactor_1 + ... + Cofactor_n + AnchorCofactor)
2879 if (!Cofactors.empty()) {
2880 Cofactors.push_back(StripFactor(Mul, MulOp));
2881
2882 SCEVUse InnerSum = getAddExpr(Cofactors, SCEV::FlagAnyWrap, Depth + 1);
2883 SCEVUse OuterMul =
2884 getMulExpr(MulOpSCEV, InnerSum, SCEV::FlagAnyWrap, Depth + 1);
2885
2886 // DeadIndices does not include Idx (the anchor), hence +1.
2887 if (Ops.size() == DeadIndices.size() + 1)
2888 return OuterMul;
2889
2890 // Erase Ops[Idx] first, then erase DeadIndices in reverse order.
2891 // The -1 adjustment accounts for the shift from removing Idx;
2892 // reverse order means each erasure only shifts later positions,
2893 // which have already been processed.
2894 Ops.erase(Ops.begin() + Idx);
2895 for (unsigned Dead : reverse(DeadIndices))
2896 Ops.erase(Ops.begin() + (Dead > Idx ? Dead - 1 : Dead));
2897
2898 Ops.push_back(OuterMul);
2899 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2900 }
2901 }
2902 }
2903
2904 // If there are any add recurrences in the operands list, see if any other
2905 // added values are loop invariant. If so, we can fold them into the
2906 // recurrence.
2907 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2908 ++Idx;
2909
2910 // Scan over all recurrences, trying to fold loop invariants into them.
2911 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2912 // Scan all of the other operands to this add and add them to the vector if
2913 // they are loop invariant w.r.t. the recurrence.
2915 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2916 const Loop *AddRecLoop = AddRec->getLoop();
2917 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2918 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2919 LIOps.push_back(Ops[i]);
2920 Ops.erase(Ops.begin()+i);
2921 --i; --e;
2922 }
2923
2924 // If we found some loop invariants, fold them into the recurrence.
2925 if (!LIOps.empty()) {
2926 // Compute nowrap flags for the addition of the loop-invariant ops and
2927 // the addrec. Temporarily push it as an operand for that purpose. These
2928 // flags are valid in the scope of the addrec only.
2929 LIOps.push_back(AddRec);
2930 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2931 LIOps.pop_back();
2932
2933 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2934 LIOps.push_back(AddRec->getStart());
2935
2936 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2937
2938 // It is not in general safe to propagate flags valid on an add within
2939 // the addrec scope to one outside it. We must prove that the inner
2940 // scope is guaranteed to execute if the outer one does to be able to
2941 // safely propagate. We know the program is undefined if poison is
2942 // produced on the inner scoped addrec. We also know that *for this use*
2943 // the outer scoped add can't overflow (because of the flags we just
2944 // computed for the inner scoped add) without the program being undefined.
2945 // Proving that entry to the outer scope neccesitates entry to the inner
2946 // scope, thus proves the program undefined if the flags would be violated
2947 // in the outer scope.
2948 SCEV::NoWrapFlags AddFlags = Flags;
2949 if (AddFlags != SCEV::FlagAnyWrap) {
2950 auto *DefI = getDefiningScopeBound(LIOps);
2951 auto *ReachI = &*AddRecLoop->getHeader()->begin();
2952 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2953 AddFlags = SCEV::FlagAnyWrap;
2954 }
2955 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2956
2957 // Build the new addrec. Propagate the NUW and NSW flags if both the
2958 // outer add and the inner addrec are guaranteed to have no overflow.
2959 // Always propagate NW.
2960 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2961 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2962
2963 // If all of the other operands were loop invariant, we are done.
2964 if (Ops.size() == 1) return NewRec;
2965
2966 // Otherwise, add the folded AddRec by the non-invariant parts.
2967 for (unsigned i = 0;; ++i)
2968 if (Ops[i] == AddRec) {
2969 Ops[i] = NewRec;
2970 break;
2971 }
2972 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2973 }
2974
2975 // Okay, if there weren't any loop invariants to be folded, check to see if
2976 // there are multiple AddRec's with the same loop induction variable being
2977 // added together. If so, we can fold them.
2978 for (unsigned OtherIdx = Idx+1;
2979 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2980 ++OtherIdx) {
2981 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2982 // so that the 1st found AddRecExpr is dominated by all others.
2983 assert(DT.dominates(
2984 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2985 AddRec->getLoop()->getHeader()) &&
2986 "AddRecExprs are not sorted in reverse dominance order?");
2987 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2988 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2989 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2990 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2991 ++OtherIdx) {
2992 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2993 if (OtherAddRec->getLoop() == AddRecLoop) {
2994 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2995 i != e; ++i) {
2996 if (i >= AddRecOps.size()) {
2997 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
2998 break;
2999 }
3000 AddRecOps[i] =
3001 getAddExpr(AddRecOps[i], OtherAddRec->getOperand(i),
3003 }
3004 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3005 }
3006 }
3007 // Step size has changed, so we cannot guarantee no self-wraparound.
3008 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
3009 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3010 }
3011 }
3012
3013 // Otherwise couldn't fold anything into this recurrence. Move onto the
3014 // next one.
3015 }
3016
3017 // Okay, it looks like we really DO need an add expr. Check to see if we
3018 // already have one, otherwise create a new one.
3019 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
3020}
3021
3022const SCEV *ScalarEvolution::getOrCreateAddExpr(ArrayRef<SCEVUse> Ops,
3023 SCEV::NoWrapFlags Flags) {
3026 for (SCEVUse Op : Ops)
3027 ID.AddPointer(Op.getOpaqueValue());
3028 void *IP = nullptr;
3029 SCEVAddExpr *S =
3030 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3031 if (!S) {
3032 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3034 S = new (SCEVAllocator)
3035 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
3036 UniqueSCEVs.InsertNode(S, IP);
3037 S->computeAndSetCanonical(*this);
3038 registerUser(S, Ops);
3039 }
3040 S->setNoWrapFlags(Flags);
3041 return S;
3042}
3043
3044const SCEV *ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<SCEVUse> Ops,
3045 const Loop *L,
3046 SCEV::NoWrapFlags Flags) {
3047 FoldingSetNodeID ID;
3048 ID.AddInteger(scAddRecExpr);
3049 for (SCEVUse Op : Ops)
3050 ID.AddPointer(Op.getOpaqueValue());
3051 ID.AddPointer(L);
3052 void *IP = nullptr;
3053 SCEVAddRecExpr *S =
3054 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3055 if (!S) {
3056 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3058 S = new (SCEVAllocator)
3059 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
3060 UniqueSCEVs.InsertNode(S, IP);
3061 S->computeAndSetCanonical(*this);
3062 LoopUsers[L].push_back(S);
3063 registerUser(S, Ops);
3064 }
3065 setNoWrapFlags(S, Flags);
3066 return S;
3067}
3068
3069const SCEV *ScalarEvolution::getOrCreateMulExpr(ArrayRef<SCEVUse> Ops,
3070 SCEV::NoWrapFlags Flags) {
3071 FoldingSetNodeID ID;
3072 ID.AddInteger(scMulExpr);
3073 for (SCEVUse Op : Ops)
3074 ID.AddPointer(Op.getOpaqueValue());
3075 void *IP = nullptr;
3076 SCEVMulExpr *S =
3077 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3078 if (!S) {
3079 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3081 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
3082 O, Ops.size());
3083 UniqueSCEVs.InsertNode(S, IP);
3084 S->computeAndSetCanonical(*this);
3085 registerUser(S, Ops);
3086 }
3087 S->setNoWrapFlags(Flags);
3088 return S;
3089}
3090
3091const SCEV *ScalarEvolution::getOrCreateUDivExpr(SCEVUse LHS, SCEVUse RHS) {
3092 FoldingSetNodeID ID;
3093 ID.AddInteger(scUDivExpr);
3094 ID.AddPointer(LHS.getOpaqueValue());
3095 ID.AddPointer(RHS.getOpaqueValue());
3096 void *IP = nullptr;
3097 SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3098 if (!S) {
3099 S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), LHS, RHS);
3100 UniqueSCEVs.InsertNode(S, IP);
3101 S->computeAndSetCanonical(*this);
3103 }
3104 return S;
3105}
3106
3107static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
3108 uint64_t k = i*j;
3109 if (j > 1 && k / j != i) Overflow = true;
3110 return k;
3111}
3112
3113/// Compute the result of "n choose k", the binomial coefficient. If an
3114/// intermediate computation overflows, Overflow will be set and the return will
3115/// be garbage. Overflow is not cleared on absence of overflow.
3116static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3117 // We use the multiplicative formula:
3118 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3119 // At each iteration, we take the n-th term of the numeral and divide by the
3120 // (k-n)th term of the denominator. This division will always produce an
3121 // integral result, and helps reduce the chance of overflow in the
3122 // intermediate computations. However, we can still overflow even when the
3123 // final result would fit.
3124
3125 if (n == 0 || n == k) return 1;
3126 if (k > n) return 0;
3127
3128 if (k > n/2)
3129 k = n-k;
3130
3131 uint64_t r = 1;
3132 for (uint64_t i = 1; i <= k; ++i) {
3133 r = umul_ov(r, n-(i-1), Overflow);
3134 r /= i;
3135 }
3136 return r;
3137}
3138
3139/// Determine if any of the operands in this SCEV are a constant or if
3140/// any of the add or multiply expressions in this SCEV contain a constant.
3141static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3142 struct FindConstantInAddMulChain {
3143 bool FoundConstant = false;
3144
3145 bool follow(const SCEV *S) {
3146 FoundConstant |= isa<SCEVConstant>(S);
3147 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3148 }
3149
3150 bool isDone() const {
3151 return FoundConstant;
3152 }
3153 };
3154
3155 FindConstantInAddMulChain F;
3157 ST.visitAll(StartExpr);
3158 return F.FoundConstant;
3159}
3160
3161/// Get a canonical multiply expression, or something simpler if possible.
3163 SCEV::NoWrapFlags OrigFlags,
3164 unsigned Depth) {
3165 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3166 "only nuw or nsw allowed");
3167 assert(!Ops.empty() && "Cannot get empty mul!");
3168 if (Ops.size() == 1) return Ops[0];
3169#ifndef NDEBUG
3170 Type *ETy = Ops[0]->getType();
3171 assert(!ETy->isPointerTy());
3172 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3173 assert(Ops[i]->getType() == ETy &&
3174 "SCEVMulExpr operand types don't match!");
3175#endif
3176
3177 const SCEV *Folded = constantFoldAndGroupOps(
3178 *this, LI, DT, Ops,
3179 [](const APInt &C1, const APInt &C2) { return C1 * C2; },
3180 [](const APInt &C) { return C.isOne(); }, // identity
3181 [](const APInt &C) { return C.isZero(); }); // absorber
3182 if (Folded)
3183 return Folded;
3184
3185 // Delay expensive flag strengthening until necessary.
3186 auto ComputeFlags = [this, OrigFlags](const ArrayRef<SCEVUse> Ops) {
3187 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3188 };
3189
3190 // Limit recursion calls depth.
3192 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3193
3194 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3195 // Don't strengthen flags if we have no new information.
3196 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3197 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3198 Mul->setNoWrapFlags(ComputeFlags(Ops));
3199 return S;
3200 }
3201
3202 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3203 if (Ops.size() == 2) {
3204 // C1*(C2+V) -> C1*C2 + C1*V
3205 // If any of Add's ops are Adds or Muls with a constant, apply this
3206 // transformation as well.
3207 //
3208 // TODO: There are some cases where this transformation is not
3209 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
3210 // this transformation should be narrowed down.
3211 const SCEV *Op0, *Op1;
3212 if (match(Ops[1], m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))) &&
3214 const SCEV *LHS = getMulExpr(LHSC, Op0, SCEV::FlagAnyWrap, Depth + 1);
3215 const SCEV *RHS = getMulExpr(LHSC, Op1, SCEV::FlagAnyWrap, Depth + 1);
3216 return getAddExpr(LHS, RHS, SCEV::FlagAnyWrap, Depth + 1);
3217 }
3218
3219 if (Ops[0]->isAllOnesValue()) {
3220 // If we have a mul by -1 of an add, try distributing the -1 among the
3221 // add operands.
3222 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3224 bool AnyFolded = false;
3225 for (const SCEV *AddOp : Add->operands()) {
3226 const SCEV *Mul = getMulExpr(Ops[0], SCEVUse(AddOp),
3228 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3229 NewOps.push_back(Mul);
3230 }
3231 if (AnyFolded)
3232 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3233 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3234 // Negation preserves a recurrence's no self-wrap property.
3236 for (const SCEV *AddRecOp : AddRec->operands())
3237 Operands.push_back(getMulExpr(Ops[0], SCEVUse(AddRecOp),
3238 SCEV::FlagAnyWrap, Depth + 1));
3239 // Let M be the minimum representable signed value. AddRec with nsw
3240 // multiplied by -1 can have signed overflow if and only if it takes a
3241 // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3242 // maximum signed value. In all other cases signed overflow is
3243 // impossible.
3244 auto FlagsMask = SCEV::FlagNW;
3245 if (AddRec->hasNoSignedWrap()) {
3246 auto MinInt =
3247 APInt::getSignedMinValue(getTypeSizeInBits(AddRec->getType()));
3248 if (getSignedRangeMin(AddRec) != MinInt)
3249 FlagsMask = setFlags(FlagsMask, SCEV::FlagNSW);
3250 }
3251 return getAddRecExpr(Operands, AddRec->getLoop(),
3252 AddRec->getNoWrapFlags(FlagsMask));
3253 }
3254 }
3255
3256 // Try to push the constant operand into a ZExt: C * zext (A + B) ->
3257 // zext (C*A + C*B) if trunc (C) * (A + B) does not unsigned-wrap.
3258 const SCEVAddExpr *InnerAdd;
3259 if (match(Ops[1], m_scev_ZExt(m_scev_Add(InnerAdd)))) {
3260 const SCEV *NarrowC = getTruncateExpr(LHSC, InnerAdd->getType());
3261 if (isa<SCEVConstant>(InnerAdd->getOperand(0)) &&
3262 getZeroExtendExpr(NarrowC, Ops[1]->getType()) == LHSC &&
3263 hasFlags(StrengthenNoWrapFlags(this, scMulExpr, {NarrowC, InnerAdd},
3265 SCEV::FlagNUW)) {
3266 auto *Res = getMulExpr(NarrowC, InnerAdd, SCEV::FlagNUW, Depth + 1);
3267 return getZeroExtendExpr(Res, Ops[1]->getType(), Depth + 1);
3268 };
3269 }
3270
3271 // Try to fold (C1 * D /u C2) -> C1/C2 * D, if C1 and C2 are powers-of-2,
3272 // D is a multiple of C2, and C1 is a multiple of C2. If C2 is a multiple
3273 // of C1, fold to (D /u (C2 /u C1)).
3274 const SCEV *D;
3275 APInt C1V = LHSC->getAPInt();
3276 // (C1 * D /u C2) == -1 * -C1 * D /u C2 when C1 != INT_MIN. Don't treat -1
3277 // as -1 * 1, as it won't enable additional folds.
3278 if (C1V.isNegative() && !C1V.isMinSignedValue() && !C1V.isAllOnes())
3279 C1V = C1V.abs();
3280 const SCEVConstant *C2;
3281 if (C1V.isPowerOf2() &&
3283 C2->getAPInt().isPowerOf2() &&
3284 C1V.logBase2() <= getMinTrailingZeros(D)) {
3285 const SCEV *NewMul = nullptr;
3286 if (C1V.uge(C2->getAPInt())) {
3287 NewMul = getMulExpr(getUDivExpr(getConstant(C1V), C2), D);
3288 } else if (C2->getAPInt().logBase2() <= getMinTrailingZeros(D)) {
3289 assert(C1V.ugt(1) && "C1 <= 1 should have been folded earlier");
3290 NewMul = getUDivExpr(D, getUDivExpr(C2, getConstant(C1V)));
3291 }
3292 if (NewMul)
3293 return C1V == LHSC->getAPInt() ? NewMul : getNegativeSCEV(NewMul);
3294 }
3295 }
3296 }
3297
3298 // Skip over the add expression until we get to a multiply.
3299 unsigned Idx = 0;
3300 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3301 ++Idx;
3302
3303 // If there are mul operands inline them all into this expression.
3304 if (Idx < Ops.size()) {
3305 bool DeletedMul = false;
3306 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3307 if (Ops.size() > MulOpsInlineThreshold)
3308 break;
3309 // If we have an mul, expand the mul operands onto the end of the
3310 // operands list.
3311 Ops.erase(Ops.begin()+Idx);
3312 append_range(Ops, Mul->operands());
3313 DeletedMul = true;
3314 }
3315
3316 // If we deleted at least one mul, we added operands to the end of the
3317 // list, and they are not necessarily sorted. Recurse to resort and
3318 // resimplify any operands we just acquired.
3319 if (DeletedMul)
3320 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3321 }
3322
3323 // If there are any add recurrences in the operands list, see if any other
3324 // added values are loop invariant. If so, we can fold them into the
3325 // recurrence.
3326 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3327 ++Idx;
3328
3329 // Scan over all recurrences, trying to fold loop invariants into them.
3330 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3331 // Scan all of the other operands to this mul and add them to the vector
3332 // if they are loop invariant w.r.t. the recurrence.
3334 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3335 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3336 if (isAvailableAtLoopEntry(Ops[i], AddRec->getLoop())) {
3337 LIOps.push_back(Ops[i]);
3338 Ops.erase(Ops.begin()+i);
3339 --i; --e;
3340 }
3341
3342 // If we found some loop invariants, fold them into the recurrence.
3343 if (!LIOps.empty()) {
3344 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3346 NewOps.reserve(AddRec->getNumOperands());
3347 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3348
3349 // If both the mul and addrec are nuw, we can preserve nuw.
3350 // If both the mul and addrec are nsw, we can only preserve nsw if either
3351 // a) they are also nuw, or
3352 // b) all multiplications of addrec operands with scale are nsw.
3353 SCEV::NoWrapFlags Flags =
3354 AddRec->getNoWrapFlags(ComputeFlags({Scale, AddRec}));
3355
3356 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3357 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3358 SCEV::FlagAnyWrap, Depth + 1));
3359
3360 if (hasFlags(Flags, SCEV::FlagNSW) && !hasFlags(Flags, SCEV::FlagNUW)) {
3362 Instruction::Mul, getSignedRange(Scale),
3364 if (!NSWRegion.contains(getSignedRange(AddRec->getOperand(i))))
3365 Flags = clearFlags(Flags, SCEV::FlagNSW);
3366 }
3367 }
3368
3369 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(), Flags);
3370
3371 // If all of the other operands were loop invariant, we are done.
3372 if (Ops.size() == 1) return NewRec;
3373
3374 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3375 for (unsigned i = 0;; ++i)
3376 if (Ops[i] == AddRec) {
3377 Ops[i] = NewRec;
3378 break;
3379 }
3380 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3381 }
3382
3383 // Okay, if there weren't any loop invariants to be folded, check to see
3384 // if there are multiple AddRec's with the same loop induction variable
3385 // being multiplied together. If so, we can fold them.
3386
3387 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3388 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3389 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3390 // ]]],+,...up to x=2n}.
3391 // Note that the arguments to choose() are always integers with values
3392 // known at compile time, never SCEV objects.
3393 //
3394 // The implementation avoids pointless extra computations when the two
3395 // addrec's are of different length (mathematically, it's equivalent to
3396 // an infinite stream of zeros on the right).
3397 bool OpsModified = false;
3398 for (unsigned OtherIdx = Idx+1;
3399 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3400 ++OtherIdx) {
3401 const SCEVAddRecExpr *OtherAddRec =
3402 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3403 if (!OtherAddRec || OtherAddRec->getLoop() != AddRec->getLoop())
3404 continue;
3405
3406 // Limit max number of arguments to avoid creation of unreasonably big
3407 // SCEVAddRecs with very complex operands.
3408 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3409 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3410 continue;
3411
3412 bool Overflow = false;
3413 Type *Ty = AddRec->getType();
3414 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3415 SmallVector<SCEVUse, 7> AddRecOps;
3416 for (int x = 0, xe = AddRec->getNumOperands() +
3417 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3419 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3420 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3421 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3422 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3423 z < ze && !Overflow; ++z) {
3424 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3425 uint64_t Coeff;
3426 if (LargerThan64Bits)
3427 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3428 else
3429 Coeff = Coeff1*Coeff2;
3430 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3431 const SCEV *Term1 = AddRec->getOperand(y-z);
3432 const SCEV *Term2 = OtherAddRec->getOperand(z);
3433 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3434 SCEV::FlagAnyWrap, Depth + 1));
3435 }
3436 }
3437 if (SumOps.empty())
3438 SumOps.push_back(getZero(Ty));
3439 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3440 }
3441 if (!Overflow) {
3442 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
3444 if (Ops.size() == 2) return NewAddRec;
3445 Ops[Idx] = NewAddRec;
3446 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3447 OpsModified = true;
3448 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3449 if (!AddRec)
3450 break;
3451 }
3452 }
3453 if (OpsModified)
3454 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3455
3456 // Otherwise couldn't fold anything into this recurrence. Move onto the
3457 // next one.
3458 }
3459
3460 // Okay, it looks like we really DO need an mul expr. Check to see if we
3461 // already have one, otherwise create a new one.
3462 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3463}
3464
3465/// Represents an unsigned remainder expression based on unsigned division.
3467 assert(getEffectiveSCEVType(LHS->getType()) ==
3468 getEffectiveSCEVType(RHS->getType()) &&
3469 "SCEVURemExpr operand types don't match!");
3470
3471 // Short-circuit easy cases
3472 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3473 // If constant is one, the result is trivial
3474 if (RHSC->getValue()->isOne())
3475 return getZero(LHS->getType()); // X urem 1 --> 0
3476
3477 // If constant is a power of two, fold into a zext(trunc(LHS)).
3478 if (RHSC->getAPInt().isPowerOf2()) {
3479 Type *FullTy = LHS->getType();
3480 Type *TruncTy =
3481 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3482 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3483 }
3484 }
3485
3486 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3487 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3488 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3489 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3490}
3491
3492/// Get a canonical unsigned division expression, or something simpler if
3493/// possible.
3495 assert(!LHS->getType()->isPointerTy() &&
3496 "SCEVUDivExpr operand can't be pointer!");
3497 assert(LHS->getType() == RHS->getType() &&
3498 "SCEVUDivExpr operand types don't match!");
3499
3500 if (SCEV *S =
3501 findExistingSCEVInCache(scUDivExpr, ArrayRef<SCEVUse>({LHS, RHS})))
3502 return S;
3503
3504 // 0 udiv Y == 0
3505 if (match(LHS, m_scev_Zero()))
3506 return LHS;
3507
3508 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3509 if (RHSC->getValue()->isOne())
3510 return LHS; // X udiv 1 --> x
3511 // If the denominator is zero, the result of the udiv is undefined. Don't
3512 // try to analyze it, because the resolution chosen here may differ from
3513 // the resolution chosen in other parts of the compiler.
3514 if (!RHSC->getValue()->isZero()) {
3515 // Determine if the division can be folded into the operands of
3516 // its operands.
3517 // TODO: Generalize this to non-constants by using known-bits information.
3518 Type *Ty = LHS->getType();
3519 unsigned LZ = RHSC->getAPInt().countl_zero();
3520 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3521 // For non-power-of-two values, effectively round the value up to the
3522 // nearest power of two.
3523 if (!RHSC->getAPInt().isPowerOf2())
3524 ++MaxShiftAmt;
3525 IntegerType *ExtTy =
3526 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3527 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3528 if (const SCEVConstant *Step =
3529 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3530 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3531 const APInt &StepInt = Step->getAPInt();
3532 const APInt &DivInt = RHSC->getAPInt();
3533 if (!StepInt.urem(DivInt) &&
3534 getZeroExtendExpr(AR, ExtTy) ==
3535 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3536 getZeroExtendExpr(Step, ExtTy),
3537 AR->getLoop(), SCEV::FlagAnyWrap)) {
3539 for (const SCEV *Op : AR->operands())
3540 Operands.push_back(getUDivExpr(Op, RHS));
3541 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3542 }
3543 /// Get a canonical UDivExpr for a recurrence.
3544 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3545 const APInt *StartRem;
3546 if (!DivInt.urem(StepInt) && match(getURemExpr(AR->getStart(), Step),
3547 m_scev_APInt(StartRem))) {
3548 bool NoWrap =
3549 getZeroExtendExpr(AR, ExtTy) ==
3550 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3551 getZeroExtendExpr(Step, ExtTy), AR->getLoop(),
3553
3554 // With N <= C and both N, C as powers-of-2, the transformation
3555 // {X,+,N}/C => {(X - X%N),+,N}/C preserves division results even
3556 // if wrapping occurs, as the division results remain equivalent for
3557 // all offsets in [[(X - X%N), X).
3558 bool CanFoldWithWrap = StepInt.ule(DivInt) && // N <= C
3559 StepInt.isPowerOf2() && DivInt.isPowerOf2();
3560 // Only fold if the subtraction can be folded in the start
3561 // expression.
3562 const SCEV *NewStart =
3563 getMinusSCEV(AR->getStart(), getConstant(*StartRem));
3564 if (*StartRem != 0 && (NoWrap || CanFoldWithWrap) &&
3565 !isa<SCEVAddExpr>(NewStart)) {
3566 const SCEV *NewLHS =
3567 getAddRecExpr(NewStart, Step, AR->getLoop(),
3568 NoWrap ? SCEV::FlagNW : SCEV::FlagAnyWrap);
3569 if (LHS != NewLHS)
3570 return getUDivExpr(NewLHS, RHS);
3571 }
3572 }
3573 }
3574 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3575 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3576 if (M->hasNoUnsignedWrap()) {
3577 // Find an operand that's safely divisible.
3578 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3579 const SCEV *Op = M->getOperand(i);
3580 const SCEV *Div = getUDivExpr(Op, RHSC);
3581 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3582 SmallVector<SCEVUse, 4> Operands(M->operands());
3583 Operands[i] = Div;
3584 return getMulExpr(Operands);
3585 }
3586 }
3587
3588 // Even if it's not divisible, try to remove a common factor.
3589 if (const auto *LHSC = dyn_cast<SCEVConstant>(M->getOperand(0))) {
3590 APInt Factor = APIntOps::GreatestCommonDivisor(LHSC->getAPInt(),
3591 RHSC->getAPInt());
3592 if (!Factor.isIntN(1)) {
3593 SmallVector<SCEVUse, 2> NewOperands;
3594 NewOperands.push_back(getConstant(LHSC->getAPInt().udiv(Factor)));
3595 append_range(NewOperands, M->operands().drop_front());
3596 const SCEV *NewMul = getMulExpr(NewOperands);
3597 return getUDivExpr(NewMul,
3598 getConstant(RHSC->getAPInt().udiv(Factor)));
3599 }
3600 }
3601 }
3602 }
3603
3604 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3605 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3606 if (auto *DivisorConstant =
3607 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3608 bool Overflow = false;
3609 APInt NewRHS =
3610 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3611 if (Overflow) {
3612 return getConstant(RHSC->getType(), 0, false);
3613 }
3614 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3615 }
3616 }
3617
3618 // (A+B)/C --> (A/C + B/C) if the add does not unsigned wrap and A/C and
3619 // B/C can be folded.
3620 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3621 if (A->hasNoUnsignedWrap()) {
3623 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3624 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3625 if (isa<SCEVUDivExpr>(Op) ||
3626 getMulExpr(Op, RHS) != A->getOperand(i))
3627 break;
3628 Operands.push_back(Op);
3629 }
3630 if (Operands.size() == A->getNumOperands())
3631 return getAddExpr(Operands);
3632 }
3633 }
3634
3635 // ((N - M) + (M * A)) / N --> ((N - 1) + (M * A)) / N
3636 // This is an idiom for rounding A up to the next multiple of N, where A
3637 // is aready known to be a multiple of M. In this case, instcombine can
3638 // see that some low bits of the added constant are unused, so can clear
3639 // them, but we want to canonicalise to set the low bits. This makes the
3640 // pattern easier to match, without needing to check for known bits in
3641 // A*M.
3642 const APInt &N = RHSC->getAPInt();
3643 const APInt *NMinusM, *M;
3644 const SCEV *A;
3645 if (match(LHS, m_scev_Add(m_scev_APInt(NMinusM),
3646 m_scev_Mul(m_scev_APInt(M), m_SCEV(A))))) {
3647 if (N.isPowerOf2() && M->isPowerOf2() && M->ult(N) &&
3648 *NMinusM == N - *M) {
3649 return getUDivExpr(
3651 RHS);
3652 }
3653 }
3654
3655 // Fold if both operands are constant.
3656 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3657 return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3658 }
3659 }
3660
3661 // ((-C + (C smax %x)) /u %x) evaluates to zero, for any positive constant C.
3662 const APInt *NegC, *C;
3663 if (match(LHS,
3666 NegC->isNegative() && !NegC->isMinSignedValue() && *C == -*NegC)
3667 return getZero(LHS->getType());
3668
3669 // (%a * %b)<nuw> / %b -> %a
3670 const auto *Mul = dyn_cast<SCEVMulExpr>(LHS);
3671 if (Mul && Mul->hasNoUnsignedWrap()) {
3672 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3673 if (Mul->getOperand(i) == RHS) {
3675 append_range(Operands, Mul->operands().take_front(i));
3676 append_range(Operands, Mul->operands().drop_front(i + 1));
3677 return getMulExpr(Operands);
3678 }
3679 }
3680 }
3681
3682 // TODO: Generalize to handle any common factors.
3683 // udiv (mul nuw a, vscale), (mul nuw b, vscale) --> udiv a, b
3684 const SCEV *NewLHS, *NewRHS;
3685 if (match(LHS, m_scev_c_NUWMul(m_SCEV(NewLHS), m_SCEVVScale())) &&
3686 match(RHS, m_scev_c_NUWMul(m_SCEV(NewRHS), m_SCEVVScale())))
3687 return getUDivExpr(NewLHS, NewRHS);
3688
3689 return getOrCreateUDivExpr(LHS, RHS);
3690}
3691
3692/// Get a canonical unsigned division expression, or something simpler if
3693/// possible. There is no representation for an exact udiv in SCEV IR, but we
3694/// can attempt to optimize it prior to construction.
3696 // Currently there is no exact specific logic.
3697
3698 return getUDivExpr(LHS, RHS);
3699}
3700
3701/// Get an add recurrence expression for the specified loop. Simplify the
3702/// expression as much as possible.
3704 const Loop *L,
3705 SCEV::NoWrapFlags Flags) {
3707 Operands.push_back(Start);
3708 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3709 if (StepChrec->getLoop() == L) {
3710 append_range(Operands, StepChrec->operands());
3711 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3712 }
3713
3714 Operands.push_back(Step);
3715 return getAddRecExpr(Operands, L, Flags);
3716}
3717
3718/// Get an add recurrence expression for the specified loop. Simplify the
3719/// expression as much as possible.
3721 const Loop *L,
3722 SCEV::NoWrapFlags Flags) {
3723 if (Operands.size() == 1) return Operands[0];
3724#ifndef NDEBUG
3726 for (const SCEV *Op : llvm::drop_begin(Operands)) {
3727 assert(getEffectiveSCEVType(Op->getType()) == ETy &&
3728 "SCEVAddRecExpr operand types don't match!");
3729 assert(!Op->getType()->isPointerTy() && "Step must be integer");
3730 }
3731 for (const SCEV *Op : Operands)
3733 "SCEVAddRecExpr operand is not available at loop entry!");
3734#endif
3735
3736 if (Operands.back()->isZero()) {
3737 Operands.pop_back();
3738 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3739 }
3740
3741 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3742 // use that information to infer NUW and NSW flags. However, computing a
3743 // BE count requires calling getAddRecExpr, so we may not yet have a
3744 // meaningful BE count at this point (and if we don't, we'd be stuck
3745 // with a SCEVCouldNotCompute as the cached BE count).
3746
3747 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3748
3749 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3750 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3751 const Loop *NestedLoop = NestedAR->getLoop();
3752 if (L->contains(NestedLoop)
3753 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3754 : (!NestedLoop->contains(L) &&
3755 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3756 SmallVector<SCEVUse, 4> NestedOperands(NestedAR->operands());
3757 Operands[0] = NestedAR->getStart();
3758 // AddRecs require their operands be loop-invariant with respect to their
3759 // loops. Don't perform this transformation if it would break this
3760 // requirement.
3761 bool AllInvariant = all_of(
3762 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3763
3764 if (AllInvariant) {
3765 // Create a recurrence for the outer loop with the same step size.
3766 //
3767 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3768 // inner recurrence has the same property.
3769 SCEV::NoWrapFlags OuterFlags =
3770 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3771
3772 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3773 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3774 return isLoopInvariant(Op, NestedLoop);
3775 });
3776
3777 if (AllInvariant) {
3778 // Ok, both add recurrences are valid after the transformation.
3779 //
3780 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3781 // the outer recurrence has the same property.
3782 SCEV::NoWrapFlags InnerFlags =
3783 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3784 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3785 }
3786 }
3787 // Reset Operands to its original state.
3788 Operands[0] = NestedAR;
3789 }
3790 }
3791
3792 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3793 // already have one, otherwise create a new one.
3794 return getOrCreateAddRecExpr(Operands, L, Flags);
3795}
3796
3798 ArrayRef<SCEVUse> IndexExprs) {
3799 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3800 // getSCEV(Base)->getType() has the same address space as Base->getType()
3801 // because SCEV::getType() preserves the address space.
3802 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
3803 if (NW != GEPNoWrapFlags::none()) {
3804 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3805 // but to do that, we have to ensure that said flag is valid in the entire
3806 // defined scope of the SCEV.
3807 // TODO: non-instructions have global scope. We might be able to prove
3808 // some global scope cases
3809 auto *GEPI = dyn_cast<Instruction>(GEP);
3810 if (!GEPI || !isSCEVExprNeverPoison(GEPI))
3811 NW = GEPNoWrapFlags::none();
3812 }
3813
3814 return getGEPExpr(BaseExpr, IndexExprs, GEP->getSourceElementType(), NW);
3815}
3816
3818 ArrayRef<SCEVUse> IndexExprs,
3819 Type *SrcElementTy, GEPNoWrapFlags NW) {
3821 if (NW.hasNoUnsignedSignedWrap())
3822 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNSW);
3823 if (NW.hasNoUnsignedWrap())
3824 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNUW);
3825
3826 Type *CurTy = BaseExpr->getType();
3827 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3828 bool FirstIter = true;
3830 for (SCEVUse IndexExpr : IndexExprs) {
3831 // Compute the (potentially symbolic) offset in bytes for this index.
3832 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3833 // For a struct, add the member offset.
3834 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3835 unsigned FieldNo = Index->getZExtValue();
3836 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3837 Offsets.push_back(FieldOffset);
3838
3839 // Update CurTy to the type of the field at Index.
3840 CurTy = STy->getTypeAtIndex(Index);
3841 } else {
3842 // Update CurTy to its element type.
3843 if (FirstIter) {
3844 assert(isa<PointerType>(CurTy) &&
3845 "The first index of a GEP indexes a pointer");
3846 CurTy = SrcElementTy;
3847 FirstIter = false;
3848 } else {
3849 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3850 }
3851 // For an array, add the element offset, explicitly scaled.
3852 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3853 // Getelementptr indices are signed.
3854 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3855
3856 // Multiply the index by the element size to compute the element offset.
3857 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3858 Offsets.push_back(LocalOffset);
3859 }
3860 }
3861
3862 // Handle degenerate case of GEP without offsets.
3863 if (Offsets.empty())
3864 return BaseExpr;
3865
3866 // Add the offsets together, assuming nsw if inbounds.
3867 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3868 // Add the base address and the offset. We cannot use the nsw flag, as the
3869 // base address is unsigned. However, if we know that the offset is
3870 // non-negative, we can use nuw.
3871 bool NUW = NW.hasNoUnsignedWrap() ||
3874 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3875 assert(BaseExpr->getType() == GEPExpr->getType() &&
3876 "GEP should not change type mid-flight.");
3877 return GEPExpr;
3878}
3879
3880SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3883 ID.AddInteger(SCEVType);
3884 for (SCEVUse Op : Ops)
3885 ID.AddPointer(Op.getOpaqueValue());
3886 void *IP = nullptr;
3887 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3888}
3889
3890const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3892 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3893}
3894
3897 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3898 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3899 if (Ops.size() == 1) return Ops[0];
3900#ifndef NDEBUG
3901 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3902 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3903 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3904 "Operand types don't match!");
3905 assert(Ops[0]->getType()->isPointerTy() ==
3906 Ops[i]->getType()->isPointerTy() &&
3907 "min/max should be consistently pointerish");
3908 }
3909#endif
3910
3911 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3912 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3913
3914 const SCEV *Folded = constantFoldAndGroupOps(
3915 *this, LI, DT, Ops,
3916 [&](const APInt &C1, const APInt &C2) {
3917 switch (Kind) {
3918 case scSMaxExpr:
3919 return APIntOps::smax(C1, C2);
3920 case scSMinExpr:
3921 return APIntOps::smin(C1, C2);
3922 case scUMaxExpr:
3923 return APIntOps::umax(C1, C2);
3924 case scUMinExpr:
3925 return APIntOps::umin(C1, C2);
3926 default:
3927 llvm_unreachable("Unknown SCEV min/max opcode");
3928 }
3929 },
3930 [&](const APInt &C) {
3931 // identity
3932 if (IsMax)
3933 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3934 else
3935 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3936 },
3937 [&](const APInt &C) {
3938 // absorber
3939 if (IsMax)
3940 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3941 else
3942 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3943 });
3944 if (Folded)
3945 return Folded;
3946
3947 // Check if we have created the same expression before.
3948 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3949 return S;
3950 }
3951
3952 // Find the first operation of the same kind
3953 unsigned Idx = 0;
3954 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3955 ++Idx;
3956
3957 // Check to see if one of the operands is of the same kind. If so, expand its
3958 // operands onto our operand list, and recurse to simplify.
3959 if (Idx < Ops.size()) {
3960 bool DeletedAny = false;
3961 while (Ops[Idx]->getSCEVType() == Kind) {
3962 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3963 Ops.erase(Ops.begin()+Idx);
3964 append_range(Ops, SMME->operands());
3965 DeletedAny = true;
3966 }
3967
3968 if (DeletedAny)
3969 return getMinMaxExpr(Kind, Ops);
3970 }
3971
3972 // Okay, check to see if the same value occurs in the operand list twice. If
3973 // so, delete one. Since we sorted the list, these values are required to
3974 // be adjacent.
3979 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3980 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3981 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3982 if (Ops[i] == Ops[i + 1] ||
3983 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3984 // X op Y op Y --> X op Y
3985 // X op Y --> X, if we know X, Y are ordered appropriately
3986 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3987 --i;
3988 --e;
3989 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3990 Ops[i + 1])) {
3991 // X op Y --> Y, if we know X, Y are ordered appropriately
3992 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3993 --i;
3994 --e;
3995 }
3996 }
3997
3998 if (Ops.size() == 1) return Ops[0];
3999
4000 assert(!Ops.empty() && "Reduced smax down to nothing!");
4001
4002 // Okay, it looks like we really DO need an expr. Check to see if we
4003 // already have one, otherwise create a new one.
4005 ID.AddInteger(Kind);
4006 for (SCEVUse Op : Ops)
4007 ID.AddPointer(Op.getOpaqueValue());
4008 void *IP = nullptr;
4009 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4010 if (ExistingSCEV)
4011 return ExistingSCEV;
4012 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4014 SCEV *S = new (SCEVAllocator)
4015 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4016
4017 UniqueSCEVs.InsertNode(S, IP);
4018 S->computeAndSetCanonical(*this);
4019 registerUser(S, Ops);
4020 return S;
4021}
4022
4023namespace {
4024
4025class SCEVSequentialMinMaxDeduplicatingVisitor final
4026 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
4027 std::optional<const SCEV *>> {
4028 using RetVal = std::optional<const SCEV *>;
4030
4031 ScalarEvolution &SE;
4032 const SCEVTypes RootKind; // Must be a sequential min/max expression.
4033 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
4035
4036 bool canRecurseInto(SCEVTypes Kind) const {
4037 // We can only recurse into the SCEV expression of the same effective type
4038 // as the type of our root SCEV expression.
4039 return RootKind == Kind || NonSequentialRootKind == Kind;
4040 };
4041
4042 RetVal visitAnyMinMaxExpr(const SCEV *S) {
4044 "Only for min/max expressions.");
4045 SCEVTypes Kind = S->getSCEVType();
4046
4047 if (!canRecurseInto(Kind))
4048 return S;
4049
4050 auto *NAry = cast<SCEVNAryExpr>(S);
4051 SmallVector<SCEVUse> NewOps;
4052 bool Changed = visit(Kind, NAry->operands(), NewOps);
4053
4054 if (!Changed)
4055 return S;
4056 if (NewOps.empty())
4057 return std::nullopt;
4058
4060 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
4061 : SE.getMinMaxExpr(Kind, NewOps);
4062 }
4063
4064 RetVal visit(const SCEV *S) {
4065 // Has the whole operand been seen already?
4066 if (!SeenOps.insert(S).second)
4067 return std::nullopt;
4068 return Base::visit(S);
4069 }
4070
4071public:
4072 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
4073 SCEVTypes RootKind)
4074 : SE(SE), RootKind(RootKind),
4075 NonSequentialRootKind(
4076 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4077 RootKind)) {}
4078
4079 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<SCEVUse> OrigOps,
4080 SmallVectorImpl<SCEVUse> &NewOps) {
4081 bool Changed = false;
4083 Ops.reserve(OrigOps.size());
4084
4085 for (const SCEV *Op : OrigOps) {
4086 RetVal NewOp = visit(Op);
4087 if (NewOp != Op)
4088 Changed = true;
4089 if (NewOp)
4090 Ops.emplace_back(*NewOp);
4091 }
4092
4093 if (Changed)
4094 NewOps = std::move(Ops);
4095 return Changed;
4096 }
4097
4098 RetVal visitConstant(const SCEVConstant *Constant) { return Constant; }
4099
4100 RetVal visitVScale(const SCEVVScale *VScale) { return VScale; }
4101
4102 RetVal visitPtrToAddrExpr(const SCEVPtrToAddrExpr *Expr) { return Expr; }
4103
4104 RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
4105
4106 RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; }
4107
4108 RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; }
4109
4110 RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; }
4111
4112 RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; }
4113
4114 RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
4115
4116 RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
4117
4118 RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) {
4119 return visitAnyMinMaxExpr(Expr);
4120 }
4121
4122 RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) {
4123 return visitAnyMinMaxExpr(Expr);
4124 }
4125
4126 RetVal visitSMinExpr(const SCEVSMinExpr *Expr) {
4127 return visitAnyMinMaxExpr(Expr);
4128 }
4129
4130 RetVal visitUMinExpr(const SCEVUMinExpr *Expr) {
4131 return visitAnyMinMaxExpr(Expr);
4132 }
4133
4134 RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
4135 return visitAnyMinMaxExpr(Expr);
4136 }
4137
4138 RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; }
4139
4140 RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; }
4141};
4142
4143} // namespace
4144
4146 switch (Kind) {
4147 case scConstant:
4148 case scVScale:
4149 case scTruncate:
4150 case scZeroExtend:
4151 case scSignExtend:
4152 case scPtrToAddr:
4153 case scAddExpr:
4154 case scMulExpr:
4155 case scUDivExpr:
4156 case scAddRecExpr:
4157 case scUMaxExpr:
4158 case scSMaxExpr:
4159 case scUMinExpr:
4160 case scSMinExpr:
4161 case scUnknown:
4162 // If any operand is poison, the whole expression is poison.
4163 return true;
4165 // FIXME: if the *first* operand is poison, the whole expression is poison.
4166 return false; // Pessimistically, say that it does not propagate poison.
4167 case scCouldNotCompute:
4168 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4169 }
4170 llvm_unreachable("Unknown SCEV kind!");
4171}
4172
4173namespace {
4174// The only way poison may be introduced in a SCEV expression is from a
4175// poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4176// not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not*
4177// introduce poison -- they encode guaranteed, non-speculated knowledge.
4178//
4179// Additionally, all SCEV nodes propagate poison from inputs to outputs,
4180// with the notable exception of umin_seq, where only poison from the first
4181// operand is (unconditionally) propagated.
4182struct SCEVPoisonCollector {
4183 bool LookThroughMaybePoisonBlocking;
4184 SmallPtrSet<const SCEVUnknown *, 4> MaybePoison;
4185 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4186 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4187
4188 bool follow(const SCEV *S) {
4189 if (!LookThroughMaybePoisonBlocking &&
4191 return false;
4192
4193 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4194 if (!isGuaranteedNotToBePoison(SU->getValue()))
4195 MaybePoison.insert(SU);
4196 }
4197 return true;
4198 }
4199 bool isDone() const { return false; }
4200};
4201} // namespace
4202
4203/// Return true if V is poison given that AssumedPoison is already poison.
4204static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4205 // First collect all SCEVs that might result in AssumedPoison to be poison.
4206 // We need to look through potentially poison-blocking operations here,
4207 // because we want to find all SCEVs that *might* result in poison, not only
4208 // those that are *required* to.
4209 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4210 visitAll(AssumedPoison, PC1);
4211
4212 // AssumedPoison is never poison. As the assumption is false, the implication
4213 // is true. Don't bother walking the other SCEV in this case.
4214 if (PC1.MaybePoison.empty())
4215 return true;
4216
4217 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4218 // as well. We cannot look through potentially poison-blocking operations
4219 // here, as their arguments only *may* make the result poison.
4220 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4221 visitAll(S, PC2);
4222
4223 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4224 // it will also make S poison by being part of PC2.MaybePoison.
4225 return llvm::set_is_subset(PC1.MaybePoison, PC2.MaybePoison);
4226}
4227
4229 SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4230 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4231 visitAll(S, PC);
4232 for (const SCEVUnknown *SU : PC.MaybePoison)
4233 Result.insert(SU->getValue());
4234}
4235
4237 const SCEV *S, Instruction *I,
4238 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
4239 // If the instruction cannot be poison, it's always safe to reuse.
4241 return true;
4242
4243 // Otherwise, it is possible that I is more poisonous that S. Collect the
4244 // poison-contributors of S, and then check whether I has any additional
4245 // poison-contributors. Poison that is contributed through poison-generating
4246 // flags is handled by dropping those flags instead.
4248 getPoisonGeneratingValues(PoisonVals, S);
4249
4250 SmallVector<Value *> Worklist;
4252 Worklist.push_back(I);
4253 while (!Worklist.empty()) {
4254 Value *V = Worklist.pop_back_val();
4255 if (!Visited.insert(V).second)
4256 continue;
4257
4258 // Avoid walking large instruction graphs.
4259 if (Visited.size() > 16)
4260 return false;
4261
4262 // Either the value can't be poison, or the S would also be poison if it
4263 // is.
4264 if (PoisonVals.contains(V) || ::isGuaranteedNotToBePoison(V))
4265 continue;
4266
4267 auto *I = dyn_cast<Instruction>(V);
4268 if (!I)
4269 return false;
4270
4271 // Disjoint or instructions are interpreted as adds by SCEV. However, we
4272 // can't replace an arbitrary add with disjoint or, even if we drop the
4273 // flag. We would need to convert the or into an add.
4274 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
4275 if (PDI->isDisjoint())
4276 return false;
4277
4278 // FIXME: Ignore vscale, even though it technically could be poison. Do this
4279 // because SCEV currently assumes it can't be poison. Remove this special
4280 // case once we proper model when vscale can be poison.
4281 if (auto *II = dyn_cast<IntrinsicInst>(I);
4282 II && II->getIntrinsicID() == Intrinsic::vscale)
4283 continue;
4284
4285 if (canCreatePoison(cast<Operator>(I), /*ConsiderFlagsAndMetadata*/ false))
4286 return false;
4287
4288 // If the instruction can't create poison, we can recurse to its operands.
4289 if (I->hasPoisonGeneratingAnnotations())
4290 DropPoisonGeneratingInsts.push_back(I);
4291
4292 llvm::append_range(Worklist, I->operands());
4293 }
4294 return true;
4295}
4296
4297const SCEV *
4300 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4301 "Not a SCEVSequentialMinMaxExpr!");
4302 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4303 if (Ops.size() == 1)
4304 return Ops[0];
4305#ifndef NDEBUG
4306 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4307 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4308 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4309 "Operand types don't match!");
4310 assert(Ops[0]->getType()->isPointerTy() ==
4311 Ops[i]->getType()->isPointerTy() &&
4312 "min/max should be consistently pointerish");
4313 }
4314#endif
4315
4316 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4317 // so we can *NOT* do any kind of sorting of the expressions!
4318
4319 // Check if we have created the same expression before.
4320 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4321 return S;
4322
4323 // FIXME: there are *some* simplifications that we can do here.
4324
4325 // Keep only the first instance of an operand.
4326 {
4327 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4328 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4329 if (Changed)
4330 return getSequentialMinMaxExpr(Kind, Ops);
4331 }
4332
4333 // Check to see if one of the operands is of the same kind. If so, expand its
4334 // operands onto our operand list, and recurse to simplify.
4335 {
4336 unsigned Idx = 0;
4337 bool DeletedAny = false;
4338 while (Idx < Ops.size()) {
4339 if (Ops[Idx]->getSCEVType() != Kind) {
4340 ++Idx;
4341 continue;
4342 }
4343 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4344 Ops.erase(Ops.begin() + Idx);
4345 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4346 SMME->operands().end());
4347 DeletedAny = true;
4348 }
4349
4350 if (DeletedAny)
4351 return getSequentialMinMaxExpr(Kind, Ops);
4352 }
4353
4354 const SCEV *SaturationPoint;
4356 switch (Kind) {
4358 SaturationPoint = getZero(Ops[0]->getType());
4359 Pred = ICmpInst::ICMP_ULE;
4360 break;
4361 default:
4362 llvm_unreachable("Not a sequential min/max type.");
4363 }
4364
4365 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4366 if (!isGuaranteedNotToCauseUB(Ops[i]))
4367 continue;
4368 // We can replace %x umin_seq %y with %x umin %y if either:
4369 // * %y being poison implies %x is also poison.
4370 // * %x cannot be the saturating value (e.g. zero for umin).
4371 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4372 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4373 SaturationPoint)) {
4374 SmallVector<SCEVUse, 2> SeqOps = {Ops[i - 1], Ops[i]};
4375 Ops[i - 1] = getMinMaxExpr(
4377 SeqOps);
4378 Ops.erase(Ops.begin() + i);
4379 return getSequentialMinMaxExpr(Kind, Ops);
4380 }
4381 // Fold %x umin_seq %y to %x if %x ule %y.
4382 // TODO: We might be able to prove the predicate for a later operand.
4383 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4384 Ops.erase(Ops.begin() + i);
4385 return getSequentialMinMaxExpr(Kind, Ops);
4386 }
4387 }
4388
4389 // Okay, it looks like we really DO need an expr. Check to see if we
4390 // already have one, otherwise create a new one.
4392 ID.AddInteger(Kind);
4393 for (SCEVUse Op : Ops)
4394 ID.AddPointer(Op.getOpaqueValue());
4395 void *IP = nullptr;
4396 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4397 if (ExistingSCEV)
4398 return ExistingSCEV;
4399
4400 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4402 SCEV *S = new (SCEVAllocator)
4403 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4404
4405 UniqueSCEVs.InsertNode(S, IP);
4406 S->computeAndSetCanonical(*this);
4407 registerUser(S, Ops);
4408 return S;
4409}
4410
4415
4419
4424
4428
4433
4437
4439 bool Sequential) {
4440 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4441 return getUMinExpr(Ops, Sequential);
4442}
4443
4449
4450const SCEV *
4452 const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4453 if (Size.isScalable())
4454 Res = getMulExpr(Res, getVScale(IntTy));
4455 return Res;
4456}
4457
4459 return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4460}
4461
4463 return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4464}
4465
4467 StructType *STy,
4468 unsigned FieldNo) {
4469 // We can bypass creating a target-independent constant expression and then
4470 // folding it back into a ConstantInt. This is just a compile-time
4471 // optimization.
4472 const StructLayout *SL = getDataLayout().getStructLayout(STy);
4473 assert(!SL->getSizeInBits().isScalable() &&
4474 "Cannot get offset for structure containing scalable vector types");
4475 return getConstant(IntTy, SL->getElementOffset(FieldNo));
4476}
4477
4479 // Don't attempt to do anything other than create a SCEVUnknown object
4480 // here. createSCEV only calls getUnknown after checking for all other
4481 // interesting possibilities, and any other code that calls getUnknown
4482 // is doing so in order to hide a value from SCEV canonicalization.
4483
4486 ID.AddPointer(V);
4487 void *IP = nullptr;
4488 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
4489 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4490 "Stale SCEVUnknown in uniquing map!");
4491 return S;
4492 }
4493 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4494 FirstUnknown);
4495 FirstUnknown = cast<SCEVUnknown>(S);
4496 UniqueSCEVs.InsertNode(S, IP);
4497 S->computeAndSetCanonical(*this);
4498 return S;
4499}
4500
4501//===----------------------------------------------------------------------===//
4502// Basic SCEV Analysis and PHI Idiom Recognition Code
4503//
4504
4505/// Test if values of the given type are analyzable within the SCEV
4506/// framework. This primarily includes integer types, and it can optionally
4507/// include pointer types if the ScalarEvolution class has access to
4508/// target-specific information.
4510 // Integers and pointers are always SCEVable.
4511 return Ty->isIntOrPtrTy();
4512}
4513
4514/// Return the size in bits of the specified type, for which isSCEVable must
4515/// return true.
4517 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4518 if (Ty->isPointerTy())
4520 return getDataLayout().getTypeSizeInBits(Ty);
4521}
4522
4523/// Return a type with the same bitwidth as the given type and which represents
4524/// how SCEV will treat the given type, for which isSCEVable must return
4525/// true. For pointer types, this is the pointer index sized integer type.
4527 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4528
4529 if (Ty->isIntegerTy())
4530 return Ty;
4531
4532 // The only other support type is pointer.
4533 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4534 return getDataLayout().getIndexType(Ty);
4535}
4536
4538 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4539}
4540
4542 const SCEV *B) {
4543 /// For a valid use point to exist, the defining scope of one operand
4544 /// must dominate the other.
4545 bool PreciseA, PreciseB;
4546 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4547 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4548 if (!PreciseA || !PreciseB)
4549 // Can't tell.
4550 return false;
4551 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4552 DT.dominates(ScopeB, ScopeA);
4553}
4554
4556 return CouldNotCompute.get();
4557}
4558
4559bool ScalarEvolution::checkValidity(const SCEV *S) const {
4560 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4561 auto *SU = dyn_cast<SCEVUnknown>(S);
4562 return SU && SU->getValue() == nullptr;
4563 });
4564
4565 return !ContainsNulls;
4566}
4567
4569 HasRecMapType::iterator I = HasRecMap.find(S);
4570 if (I != HasRecMap.end())
4571 return I->second;
4572
4573 bool FoundAddRec =
4574 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4575 HasRecMap.insert({S, FoundAddRec});
4576 return FoundAddRec;
4577}
4578
4579/// Return the ValueOffsetPair set for \p S. \p S can be represented
4580/// by the value and offset from any ValueOffsetPair in the set.
4581ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4582 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4583 if (SI == ExprValueMap.end())
4584 return {};
4585 return SI->second.getArrayRef();
4586}
4587
4588/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4589/// cannot be used separately. eraseValueFromMap should be used to remove
4590/// V from ValueExprMap and ExprValueMap at the same time.
4591void ScalarEvolution::eraseValueFromMap(Value *V) {
4592 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4593 if (I != ValueExprMap.end()) {
4594 auto EVIt = ExprValueMap.find(I->second);
4595 bool Removed = EVIt->second.remove(V);
4596 (void) Removed;
4597 assert(Removed && "Value not in ExprValueMap?");
4598 ValueExprMap.erase(I);
4599 }
4600}
4601
4602void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4603 // A recursive query may have already computed the SCEV. It should be
4604 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4605 // inferred nowrap flags.
4606 auto It = ValueExprMap.find_as(V);
4607 if (It == ValueExprMap.end()) {
4608 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4609 ExprValueMap[S].insert(V);
4610 }
4611}
4612
4613/// Return an existing SCEV if it exists, otherwise analyze the expression and
4614/// create a new one.
4616 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4617
4618 if (const SCEV *S = getExistingSCEV(V))
4619 return S;
4620 return createSCEVIter(V);
4621}
4622
4624 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4625
4626 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4627 if (I != ValueExprMap.end()) {
4628 const SCEV *S = I->second;
4629 assert(checkValidity(S) &&
4630 "existing SCEV has not been properly invalidated");
4631 return S;
4632 }
4633 return nullptr;
4634}
4635
4636/// Return a SCEV corresponding to -V = -1*V
4638 SCEV::NoWrapFlags Flags) {
4639 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4640 return getConstant(
4641 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4642
4643 Type *Ty = V->getType();
4644 Ty = getEffectiveSCEVType(Ty);
4645 return getMulExpr(V, getMinusOne(Ty), Flags);
4646}
4647
4648/// If Expr computes ~A, return A else return nullptr
4649static const SCEV *MatchNotExpr(const SCEV *Expr) {
4650 const SCEV *MulOp;
4651 if (match(Expr, m_scev_Add(m_scev_AllOnes(),
4652 m_scev_Mul(m_scev_AllOnes(), m_SCEV(MulOp)))))
4653 return MulOp;
4654 return nullptr;
4655}
4656
4657/// Return a SCEV corresponding to ~V = -1-V
4659 assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4660
4661 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4662 return getConstant(
4663 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4664
4665 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4666 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4667 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4668 SmallVector<SCEVUse, 2> MatchedOperands;
4669 for (const SCEV *Operand : MME->operands()) {
4670 const SCEV *Matched = MatchNotExpr(Operand);
4671 if (!Matched)
4672 return (const SCEV *)nullptr;
4673 MatchedOperands.push_back(Matched);
4674 }
4675 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4676 MatchedOperands);
4677 };
4678 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4679 return Replaced;
4680 }
4681
4682 Type *Ty = V->getType();
4683 Ty = getEffectiveSCEVType(Ty);
4684 return getMinusSCEV(getMinusOne(Ty), V);
4685}
4686
4688 assert(P->getType()->isPointerTy());
4689
4690 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4691 // The base of an AddRec is the first operand.
4692 SmallVector<SCEVUse> Ops{AddRec->operands()};
4693 Ops[0] = removePointerBase(Ops[0]);
4694 // Don't try to transfer nowrap flags for now. We could in some cases
4695 // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4696 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
4697 }
4698 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4699 // The base of an Add is the pointer operand.
4700 SmallVector<SCEVUse> Ops{Add->operands()};
4701 SCEVUse *PtrOp = nullptr;
4702 for (SCEVUse &AddOp : Ops) {
4703 if (AddOp->getType()->isPointerTy()) {
4704 assert(!PtrOp && "Cannot have multiple pointer ops");
4705 PtrOp = &AddOp;
4706 }
4707 }
4708 *PtrOp = removePointerBase(*PtrOp);
4709 // Don't try to transfer nowrap flags for now. We could in some cases
4710 // (for example, if the pointer operand of the Add is a SCEVUnknown).
4711 return getAddExpr(Ops);
4712 }
4713 // Any other expression must be a pointer base.
4714 return getZero(P->getType());
4715}
4716
4718 SCEV::NoWrapFlags Flags,
4719 unsigned Depth) {
4720 // Fast path: X - X --> 0.
4721 if (LHS == RHS)
4722 return getZero(LHS->getType());
4723
4724 // If we subtract two pointers with different pointer bases, bail.
4725 // Eventually, we're going to add an assertion to getMulExpr that we
4726 // can't multiply by a pointer.
4727 if (RHS->getType()->isPointerTy()) {
4728 if (!LHS->getType()->isPointerTy() ||
4729 getPointerBase(LHS) != getPointerBase(RHS))
4730 return getCouldNotCompute();
4731 LHS = removePointerBase(LHS);
4732 RHS = removePointerBase(RHS);
4733 }
4734
4735 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4736 // makes it so that we cannot make much use of NUW.
4737 auto AddFlags = SCEV::FlagAnyWrap;
4738 const bool RHSIsNotMinSigned =
4740 if (hasFlags(Flags, SCEV::FlagNSW)) {
4741 // Let M be the minimum representable signed value. Then (-1)*RHS
4742 // signed-wraps if and only if RHS is M. That can happen even for
4743 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4744 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4745 // (-1)*RHS, we need to prove that RHS != M.
4746 //
4747 // If LHS is non-negative and we know that LHS - RHS does not
4748 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4749 // either by proving that RHS > M or that LHS >= 0.
4750 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4751 AddFlags = SCEV::FlagNSW;
4752 }
4753 }
4754
4755 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4756 // RHS is NSW and LHS >= 0.
4757 //
4758 // The difficulty here is that the NSW flag may have been proven
4759 // relative to a loop that is to be found in a recurrence in LHS and
4760 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4761 // larger scope than intended.
4762 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4763
4764 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4765}
4766
4768 unsigned Depth) {
4769 Type *SrcTy = V->getType();
4770 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4771 "Cannot truncate or zero extend with non-integer arguments!");
4772 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4773 return V; // No conversion
4774 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4775 return getTruncateExpr(V, Ty, Depth);
4776 return getZeroExtendExpr(V, Ty, Depth);
4777}
4778
4780 unsigned Depth) {
4781 Type *SrcTy = V->getType();
4782 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4783 "Cannot truncate or zero extend with non-integer arguments!");
4784 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4785 return V; // No conversion
4786 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4787 return getTruncateExpr(V, Ty, Depth);
4788 return getSignExtendExpr(V, Ty, Depth);
4789}
4790
4792 Type *SrcTy = V->getType();
4793 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4794 "Cannot noop or zero extend with non-integer arguments!");
4796 "getNoopOrZeroExtend cannot truncate!");
4797 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4798 return V; // No conversion
4799 return getZeroExtendExpr(V, Ty);
4800}
4801
4803 Type *SrcTy = V->getType();
4804 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4805 "Cannot noop or sign extend with non-integer arguments!");
4807 "getNoopOrSignExtend cannot truncate!");
4808 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4809 return V; // No conversion
4810 return getSignExtendExpr(V, Ty);
4811}
4812
4814 Type *SrcTy = V->getType();
4815 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4816 "Cannot noop or any extend with non-integer arguments!");
4818 "getNoopOrAnyExtend cannot truncate!");
4819 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4820 return V; // No conversion
4821 return getAnyExtendExpr(V, Ty);
4822}
4823
4825 Type *SrcTy = V->getType();
4826 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4827 "Cannot truncate or noop with non-integer arguments!");
4829 "getTruncateOrNoop cannot extend!");
4830 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4831 return V; // No conversion
4832 return getTruncateExpr(V, Ty);
4833}
4834
4836 const SCEV *RHS) {
4837 const SCEV *PromotedLHS = LHS;
4838 const SCEV *PromotedRHS = RHS;
4839
4840 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4841 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4842 else
4843 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4844
4845 return getUMaxExpr(PromotedLHS, PromotedRHS);
4846}
4847
4849 const SCEV *RHS,
4850 bool Sequential) {
4851 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4852 return getUMinFromMismatchedTypes(Ops, Sequential);
4853}
4854
4855const SCEV *
4857 bool Sequential) {
4858 assert(!Ops.empty() && "At least one operand must be!");
4859 // Trivial case.
4860 if (Ops.size() == 1)
4861 return Ops[0];
4862
4863 // Find the max type first.
4864 Type *MaxType = nullptr;
4865 for (SCEVUse S : Ops)
4866 if (MaxType)
4867 MaxType = getWiderType(MaxType, S->getType());
4868 else
4869 MaxType = S->getType();
4870 assert(MaxType && "Failed to find maximum type!");
4871
4872 // Extend all ops to max type.
4873 SmallVector<SCEVUse, 2> PromotedOps;
4874 for (SCEVUse S : Ops)
4875 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4876
4877 // Generate umin.
4878 return getUMinExpr(PromotedOps, Sequential);
4879}
4880
4882 // A pointer operand may evaluate to a nonpointer expression, such as null.
4883 if (!V->getType()->isPointerTy())
4884 return V;
4885
4886 while (true) {
4887 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4888 V = AddRec->getStart();
4889 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4890 const SCEV *PtrOp = nullptr;
4891 for (const SCEV *AddOp : Add->operands()) {
4892 if (AddOp->getType()->isPointerTy()) {
4893 assert(!PtrOp && "Cannot have multiple pointer ops");
4894 PtrOp = AddOp;
4895 }
4896 }
4897 assert(PtrOp && "Must have pointer op");
4898 V = PtrOp;
4899 } else // Not something we can look further into.
4900 return V;
4901 }
4902}
4903
4904/// Push users of the given Instruction onto the given Worklist.
4908 // Push the def-use children onto the Worklist stack.
4909 for (User *U : I->users()) {
4910 auto *UserInsn = cast<Instruction>(U);
4911 if (Visited.insert(UserInsn).second)
4912 Worklist.push_back(UserInsn);
4913 }
4914}
4915
4916namespace {
4917
4918/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4919/// expression in case its Loop is L. If it is not L then
4920/// if IgnoreOtherLoops is true then use AddRec itself
4921/// otherwise rewrite cannot be done.
4922/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4923class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4924public:
4925 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4926 bool IgnoreOtherLoops = true) {
4927 SCEVInitRewriter Rewriter(L, SE);
4928 const SCEV *Result = Rewriter.visit(S);
4929 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4930 return SE.getCouldNotCompute();
4931 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4932 ? SE.getCouldNotCompute()
4933 : Result;
4934 }
4935
4936 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4937 if (!SE.isLoopInvariant(Expr, L))
4938 SeenLoopVariantSCEVUnknown = true;
4939 return Expr;
4940 }
4941
4942 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4943 // Only re-write AddRecExprs for this loop.
4944 if (Expr->getLoop() == L)
4945 return Expr->getStart();
4946 SeenOtherLoops = true;
4947 return Expr;
4948 }
4949
4950 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4951
4952 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4953
4954private:
4955 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4956 : SCEVRewriteVisitor(SE), L(L) {}
4957
4958 const Loop *L;
4959 bool SeenLoopVariantSCEVUnknown = false;
4960 bool SeenOtherLoops = false;
4961};
4962
4963/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4964/// increment expression in case its Loop is L. If it is not L then
4965/// use AddRec itself.
4966/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4967class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4968public:
4969 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4970 SCEVPostIncRewriter Rewriter(L, SE);
4971 const SCEV *Result = Rewriter.visit(S);
4972 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4973 ? SE.getCouldNotCompute()
4974 : Result;
4975 }
4976
4977 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4978 if (!SE.isLoopInvariant(Expr, L))
4979 SeenLoopVariantSCEVUnknown = true;
4980 return Expr;
4981 }
4982
4983 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4984 // Only re-write AddRecExprs for this loop.
4985 if (Expr->getLoop() == L)
4986 return Expr->getPostIncExpr(SE);
4987 SeenOtherLoops = true;
4988 return Expr;
4989 }
4990
4991 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4992
4993 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4994
4995private:
4996 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4997 : SCEVRewriteVisitor(SE), L(L) {}
4998
4999 const Loop *L;
5000 bool SeenLoopVariantSCEVUnknown = false;
5001 bool SeenOtherLoops = false;
5002};
5003
5004/// This class evaluates the compare condition by matching it against the
5005/// condition of loop latch. If there is a match we assume a true value
5006/// for the condition while building SCEV nodes.
5007class SCEVBackedgeConditionFolder
5008 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
5009public:
5010 static const SCEV *rewrite(const SCEV *S, const Loop *L,
5011 ScalarEvolution &SE) {
5012 bool IsPosBECond = false;
5013 Value *BECond = nullptr;
5014 if (BasicBlock *Latch = L->getLoopLatch()) {
5015 if (CondBrInst *BI = dyn_cast<CondBrInst>(Latch->getTerminator())) {
5016 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
5017 "Both outgoing branches should not target same header!");
5018 BECond = BI->getCondition();
5019 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
5020 } else {
5021 return S;
5022 }
5023 }
5024 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
5025 return Rewriter.visit(S);
5026 }
5027
5028 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5029 const SCEV *Result = Expr;
5030 bool InvariantF = SE.isLoopInvariant(Expr, L);
5031
5032 if (!InvariantF) {
5034 switch (I->getOpcode()) {
5035 case Instruction::Select: {
5036 SelectInst *SI = cast<SelectInst>(I);
5037 std::optional<const SCEV *> Res =
5038 compareWithBackedgeCondition(SI->getCondition());
5039 if (Res) {
5040 bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
5041 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
5042 }
5043 break;
5044 }
5045 default: {
5046 std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
5047 if (Res)
5048 Result = *Res;
5049 break;
5050 }
5051 }
5052 }
5053 return Result;
5054 }
5055
5056private:
5057 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
5058 bool IsPosBECond, ScalarEvolution &SE)
5059 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
5060 IsPositiveBECond(IsPosBECond) {}
5061
5062 std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
5063
5064 const Loop *L;
5065 /// Loop back condition.
5066 Value *BackedgeCond = nullptr;
5067 /// Set to true if loop back is on positive branch condition.
5068 bool IsPositiveBECond;
5069};
5070
5071std::optional<const SCEV *>
5072SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
5073
5074 // If value matches the backedge condition for loop latch,
5075 // then return a constant evolution node based on loopback
5076 // branch taken.
5077 if (BackedgeCond == IC)
5078 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
5080 return std::nullopt;
5081}
5082
5083class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
5084public:
5085 static const SCEV *rewrite(const SCEV *S, const Loop *L,
5086 ScalarEvolution &SE) {
5087 SCEVShiftRewriter Rewriter(L, SE);
5088 const SCEV *Result = Rewriter.visit(S);
5089 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
5090 }
5091
5092 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5093 // Only allow AddRecExprs for this loop.
5094 if (!SE.isLoopInvariant(Expr, L))
5095 Valid = false;
5096 return Expr;
5097 }
5098
5099 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5100 if (Expr->getLoop() == L && Expr->isAffine())
5101 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
5102 Valid = false;
5103 return Expr;
5104 }
5105
5106 bool isValid() { return Valid; }
5107
5108private:
5109 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
5110 : SCEVRewriteVisitor(SE), L(L) {}
5111
5112 const Loop *L;
5113 bool Valid = true;
5114};
5115
5116} // end anonymous namespace
5117
5118void ScalarEvolution::inferNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
5119 if (!AR->isAffine())
5120 return;
5121
5122 // Force computation of ranges, which will also perform range-based flag
5123 // inference.
5124 if (!AR->hasNoSignedWrap())
5125 (void)getSignedRange(AR);
5126
5127 if (!AR->hasNoUnsignedWrap())
5128 (void)getUnsignedRange(AR);
5129
5130 if (!AR->hasNoSelfWrap()) {
5131 const SCEV *BECount = getConstantMaxBackedgeTakenCount(AR->getLoop());
5132 if (const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(BECount)) {
5133 ConstantRange StepCR = getSignedRange(AR->getStepRecurrence(*this));
5134 const APInt &BECountAP = BECountMax->getAPInt();
5135 unsigned NoOverflowBitWidth =
5136 BECountAP.getActiveBits() + StepCR.getMinSignedBits();
5137 if (NoOverflowBitWidth <= getTypeSizeInBits(AR->getType()))
5138 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
5139 }
5140 }
5141}
5142
5144ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5146
5147 if (AR->hasNoSignedWrap())
5148 return Result;
5149
5150 if (!AR->isAffine())
5151 return Result;
5152
5153 // This function can be expensive, only try to prove NSW once per AddRec.
5154 if (!SignedWrapViaInductionTried.insert(AR).second)
5155 return Result;
5156
5157 const SCEV *Step = AR->getStepRecurrence(*this);
5158 const Loop *L = AR->getLoop();
5159
5160 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5161 // Note that this serves two purposes: It filters out loops that are
5162 // simply not analyzable, and it covers the case where this code is
5163 // being called from within backedge-taken count analysis, such that
5164 // attempting to ask for the backedge-taken count would likely result
5165 // in infinite recursion. In the later case, the analysis code will
5166 // cope with a conservative value, and it will take care to purge
5167 // that value once it has finished.
5168 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5169
5170 // Normally, in the cases we can prove no-overflow via a
5171 // backedge guarding condition, we can also compute a backedge
5172 // taken count for the loop. The exceptions are assumptions and
5173 // guards present in the loop -- SCEV is not great at exploiting
5174 // these to compute max backedge taken counts, but can still use
5175 // these to prove lack of overflow. Use this fact to avoid
5176 // doing extra work that may not pay off.
5177
5178 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5179 AC.assumptions().empty())
5180 return Result;
5181
5182 // If the backedge is guarded by a comparison with the pre-inc value the
5183 // addrec is safe. Also, if the entry is guarded by a comparison with the
5184 // start value and the backedge is guarded by a comparison with the post-inc
5185 // value, the addrec is safe.
5187 const SCEV *OverflowLimit =
5188 getSignedOverflowLimitForStep(Step, &Pred, this);
5189 if (OverflowLimit &&
5190 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5191 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
5192 Result = setFlags(Result, SCEV::FlagNSW);
5193 }
5194 return Result;
5195}
5197ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5199
5200 if (AR->hasNoUnsignedWrap())
5201 return Result;
5202
5203 if (!AR->isAffine())
5204 return Result;
5205
5206 // This function can be expensive, only try to prove NUW once per AddRec.
5207 if (!UnsignedWrapViaInductionTried.insert(AR).second)
5208 return Result;
5209
5210 const SCEV *Step = AR->getStepRecurrence(*this);
5211 const Loop *L = AR->getLoop();
5212
5213 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5214 // Note that this serves two purposes: It filters out loops that are
5215 // simply not analyzable, and it covers the case where this code is
5216 // being called from within backedge-taken count analysis, such that
5217 // attempting to ask for the backedge-taken count would likely result
5218 // in infinite recursion. In the later case, the analysis code will
5219 // cope with a conservative value, and it will take care to purge
5220 // that value once it has finished.
5221 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5222
5223 // Normally, in the cases we can prove no-overflow via a
5224 // backedge guarding condition, we can also compute a backedge
5225 // taken count for the loop. The exceptions are assumptions and
5226 // guards present in the loop -- SCEV is not great at exploiting
5227 // these to compute max backedge taken counts, but can still use
5228 // these to prove lack of overflow. Use this fact to avoid
5229 // doing extra work that may not pay off.
5230
5231 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5232 AC.assumptions().empty())
5233 return Result;
5234
5235 // If the backedge is guarded by a comparison with the pre-inc value the
5236 // addrec is safe. Also, if the entry is guarded by a comparison with the
5237 // start value and the backedge is guarded by a comparison with the post-inc
5238 // value, the addrec is safe.
5239 if (isKnownPositive(Step)) {
5241 const SCEV *OverflowLimit =
5242 getUnsignedOverflowLimitForStep(Step, &Pred, this);
5243 if (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5244 isKnownOnEveryIteration(Pred, AR, OverflowLimit))
5245 Result = setFlags(Result, SCEV::FlagNUW);
5246 }
5247 return Result;
5248}
5249
5250namespace {
5251
5252/// Represents an abstract binary operation. This may exist as a
5253/// normal instruction or constant expression, or may have been
5254/// derived from an expression tree.
5255struct BinaryOp {
5256 unsigned Opcode;
5257 Value *LHS;
5258 Value *RHS;
5259 bool IsNSW = false;
5260 bool IsNUW = false;
5261
5262 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5263 /// constant expression.
5264 Operator *Op = nullptr;
5265
5266 explicit BinaryOp(Operator *Op)
5267 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5268 Op(Op) {
5269 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5270 IsNSW = OBO->hasNoSignedWrap();
5271 IsNUW = OBO->hasNoUnsignedWrap();
5272 }
5273 }
5274
5275 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5276 bool IsNUW = false)
5277 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5278};
5279
5280} // end anonymous namespace
5281
5282/// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
5283static std::optional<BinaryOp> MatchBinaryOp(Value *V, const DataLayout &DL,
5284 AssumptionCache &AC,
5285 const DominatorTree &DT,
5286 const Instruction *CxtI) {
5287 auto *Op = dyn_cast<Operator>(V);
5288 if (!Op)
5289 return std::nullopt;
5290
5291 // Implementation detail: all the cleverness here should happen without
5292 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5293 // SCEV expressions when possible, and we should not break that.
5294
5295 switch (Op->getOpcode()) {
5296 case Instruction::Add:
5297 case Instruction::Sub:
5298 case Instruction::Mul:
5299 case Instruction::UDiv:
5300 case Instruction::URem:
5301 case Instruction::And:
5302 case Instruction::AShr:
5303 case Instruction::Shl:
5304 return BinaryOp(Op);
5305
5306 case Instruction::Or: {
5307 // Convert or disjoint into add nuw nsw.
5308 if (cast<PossiblyDisjointInst>(Op)->isDisjoint()) {
5309 BinaryOp BinOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
5310 /*IsNSW=*/true, /*IsNUW=*/true);
5311 // Keep the reference to the original instruction so that we can later
5312 // check whether it can produce poison value or not.
5313 BinOp.Op = Op;
5314 return BinOp;
5315 }
5316 return BinaryOp(Op);
5317 }
5318
5319 case Instruction::Xor:
5320 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5321 // If the RHS of the xor is a signmask, then this is just an add.
5322 // Instcombine turns add of signmask into xor as a strength reduction step.
5323 if (RHSC->getValue().isSignMask())
5324 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5325 // Binary `xor` is a bit-wise `add`.
5326 if (V->getType()->isIntegerTy(1))
5327 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5328 return BinaryOp(Op);
5329
5330 case Instruction::LShr:
5331 // Turn logical shift right of a constant into a unsigned divide.
5332 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5333 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5334
5335 // If the shift count is not less than the bitwidth, the result of
5336 // the shift is undefined. Don't try to analyze it, because the
5337 // resolution chosen here may differ from the resolution chosen in
5338 // other parts of the compiler.
5339 if (SA->getValue().ult(BitWidth)) {
5340 Constant *X =
5341 ConstantInt::get(SA->getContext(),
5342 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5343 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5344 }
5345 }
5346 return BinaryOp(Op);
5347
5348 case Instruction::ExtractValue: {
5349 auto *EVI = cast<ExtractValueInst>(Op);
5350 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5351 break;
5352
5353 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5354 if (!WO)
5355 break;
5356
5357 Instruction::BinaryOps BinOp = WO->getBinaryOp();
5358 bool Signed = WO->isSigned();
5359 // TODO: Should add nuw/nsw flags for mul as well.
5360 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5361 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5362
5363 // Now that we know that all uses of the arithmetic-result component of
5364 // CI are guarded by the overflow check, we can go ahead and pretend
5365 // that the arithmetic is non-overflowing.
5366 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5367 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5368 }
5369
5370 default:
5371 break;
5372 }
5373
5374 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5375 // semantics as a Sub, return a binary sub expression.
5376 if (auto *II = dyn_cast<IntrinsicInst>(V))
5377 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5378 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5379
5380 return std::nullopt;
5381}
5382
5383/// Helper function to createAddRecFromPHIWithCasts. We have a phi
5384/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5385/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5386/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5387/// follows one of the following patterns:
5388/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5389/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5390/// If the SCEV expression of \p Op conforms with one of the expected patterns
5391/// we return the type of the truncation operation, and indicate whether the
5392/// truncated type should be treated as signed/unsigned by setting
5393/// \p Signed to true/false, respectively.
5394static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5395 bool &Signed, ScalarEvolution &SE) {
5396 // The case where Op == SymbolicPHI (that is, with no type conversions on
5397 // the way) is handled by the regular add recurrence creating logic and
5398 // would have already been triggered in createAddRecForPHI. Reaching it here
5399 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5400 // because one of the other operands of the SCEVAddExpr updating this PHI is
5401 // not invariant).
5402 //
5403 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5404 // this case predicates that allow us to prove that Op == SymbolicPHI will
5405 // be added.
5406 if (Op == SymbolicPHI)
5407 return nullptr;
5408
5409 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5410 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5411 if (SourceBits != NewBits)
5412 return nullptr;
5413
5414 if (match(Op, m_scev_SExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5415 Signed = true;
5416 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5417 }
5418 if (match(Op, m_scev_ZExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5419 Signed = false;
5420 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5421 }
5422 return nullptr;
5423}
5424
5425static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5426 if (!PN->getType()->isIntegerTy())
5427 return nullptr;
5428 const Loop *L = LI.getLoopFor(PN->getParent());
5429 if (!L || L->getHeader() != PN->getParent())
5430 return nullptr;
5431 return L;
5432}
5433
5434// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5435// computation that updates the phi follows the following pattern:
5436// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5437// which correspond to a phi->trunc->sext/zext->add->phi update chain.
5438// If so, try to see if it can be rewritten as an AddRecExpr under some
5439// Predicates. If successful, return them as a pair. Also cache the results
5440// of the analysis.
5441//
5442// Example usage scenario:
5443// Say the Rewriter is called for the following SCEV:
5444// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5445// where:
5446// %X = phi i64 (%Start, %BEValue)
5447// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5448// and call this function with %SymbolicPHI = %X.
5449//
5450// The analysis will find that the value coming around the backedge has
5451// the following SCEV:
5452// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5453// Upon concluding that this matches the desired pattern, the function
5454// will return the pair {NewAddRec, SmallPredsVec} where:
5455// NewAddRec = {%Start,+,%Step}
5456// SmallPredsVec = {P1, P2, P3} as follows:
5457// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5458// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5459// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5460// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5461// under the predicates {P1,P2,P3}.
5462// This predicated rewrite will be cached in PredicatedSCEVRewrites:
5463// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5464//
5465// TODO's:
5466//
5467// 1) Extend the Induction descriptor to also support inductions that involve
5468// casts: When needed (namely, when we are called in the context of the
5469// vectorizer induction analysis), a Set of cast instructions will be
5470// populated by this method, and provided back to isInductionPHI. This is
5471// needed to allow the vectorizer to properly record them to be ignored by
5472// the cost model and to avoid vectorizing them (otherwise these casts,
5473// which are redundant under the runtime overflow checks, will be
5474// vectorized, which can be costly).
5475//
5476// 2) Support additional induction/PHISCEV patterns: We also want to support
5477// inductions where the sext-trunc / zext-trunc operations (partly) occur
5478// after the induction update operation (the induction increment):
5479//
5480// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5481// which correspond to a phi->add->trunc->sext/zext->phi update chain.
5482//
5483// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5484// which correspond to a phi->trunc->add->sext/zext->phi update chain.
5485//
5486// 3) Outline common code with createAddRecFromPHI to avoid duplication.
5487std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5488ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5490
5491 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5492 // return an AddRec expression under some predicate.
5493
5494 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5495 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5496 assert(L && "Expecting an integer loop header phi");
5497
5498 // The loop may have multiple entrances or multiple exits; we can analyze
5499 // this phi as an addrec if it has a unique entry value and a unique
5500 // backedge value.
5501 Value *BEValueV = nullptr, *StartValueV = nullptr;
5502 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5503 Value *V = PN->getIncomingValue(i);
5504 if (L->contains(PN->getIncomingBlock(i))) {
5505 if (!BEValueV) {
5506 BEValueV = V;
5507 } else if (BEValueV != V) {
5508 BEValueV = nullptr;
5509 break;
5510 }
5511 } else if (!StartValueV) {
5512 StartValueV = V;
5513 } else if (StartValueV != V) {
5514 StartValueV = nullptr;
5515 break;
5516 }
5517 }
5518 if (!BEValueV || !StartValueV)
5519 return std::nullopt;
5520
5521 const SCEV *BEValue = getSCEV(BEValueV);
5522
5523 // If the value coming around the backedge is an add with the symbolic
5524 // value we just inserted, possibly with casts that we can ignore under
5525 // an appropriate runtime guard, then we found a simple induction variable!
5526 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5527 if (!Add)
5528 return std::nullopt;
5529
5530 // If there is a single occurrence of the symbolic value, possibly
5531 // casted, replace it with a recurrence.
5532 unsigned FoundIndex = Add->getNumOperands();
5533 Type *TruncTy = nullptr;
5534 bool Signed;
5535 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5536 if ((TruncTy =
5537 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5538 if (FoundIndex == e) {
5539 FoundIndex = i;
5540 break;
5541 }
5542
5543 if (FoundIndex == Add->getNumOperands())
5544 return std::nullopt;
5545
5546 // Create an add with everything but the specified operand.
5548 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5549 if (i != FoundIndex)
5550 Ops.push_back(Add->getOperand(i));
5551 const SCEV *Accum = getAddExpr(Ops);
5552
5553 // The runtime checks will not be valid if the step amount is
5554 // varying inside the loop.
5555 if (!isLoopInvariant(Accum, L))
5556 return std::nullopt;
5557
5558 // *** Part2: Create the predicates
5559
5560 // Analysis was successful: we have a phi-with-cast pattern for which we
5561 // can return an AddRec expression under the following predicates:
5562 //
5563 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5564 // fits within the truncated type (does not overflow) for i = 0 to n-1.
5565 // P2: An Equal predicate that guarantees that
5566 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5567 // P3: An Equal predicate that guarantees that
5568 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5569 //
5570 // As we next prove, the above predicates guarantee that:
5571 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5572 //
5573 //
5574 // More formally, we want to prove that:
5575 // Expr(i+1) = Start + (i+1) * Accum
5576 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5577 //
5578 // Given that:
5579 // 1) Expr(0) = Start
5580 // 2) Expr(1) = Start + Accum
5581 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5582 // 3) Induction hypothesis (step i):
5583 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5584 //
5585 // Proof:
5586 // Expr(i+1) =
5587 // = Start + (i+1)*Accum
5588 // = (Start + i*Accum) + Accum
5589 // = Expr(i) + Accum
5590 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5591 // :: from step i
5592 //
5593 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5594 //
5595 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5596 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
5597 // + Accum :: from P3
5598 //
5599 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5600 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5601 //
5602 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5603 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5604 //
5605 // By induction, the same applies to all iterations 1<=i<n:
5606 //
5607
5608 // Create a truncated addrec for which we will add a no overflow check (P1).
5609 const SCEV *StartVal = getSCEV(StartValueV);
5610 const SCEV *PHISCEV =
5611 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5612 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5613
5614 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5615 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5616 // will be constant.
5617 //
5618 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5619 // add P1.
5620 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5624 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5625 Predicates.push_back(AddRecPred);
5626 }
5627
5628 // Create the Equal Predicates P2,P3:
5629
5630 // It is possible that the predicates P2 and/or P3 are computable at
5631 // compile time due to StartVal and/or Accum being constants.
5632 // If either one is, then we can check that now and escape if either P2
5633 // or P3 is false.
5634
5635 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5636 // for each of StartVal and Accum
5637 auto getExtendedExpr = [&](const SCEV *Expr,
5638 bool CreateSignExtend) -> const SCEV * {
5639 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5640 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5641 const SCEV *ExtendedExpr =
5642 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5643 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5644 return ExtendedExpr;
5645 };
5646
5647 // Given:
5648 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5649 // = getExtendedExpr(Expr)
5650 // Determine whether the predicate P: Expr == ExtendedExpr
5651 // is known to be false at compile time
5652 auto PredIsKnownFalse = [&](const SCEV *Expr,
5653 const SCEV *ExtendedExpr) -> bool {
5654 return Expr != ExtendedExpr &&
5655 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5656 };
5657
5658 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5659 if (PredIsKnownFalse(StartVal, StartExtended)) {
5660 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5661 return std::nullopt;
5662 }
5663
5664 // The Step is always Signed (because the overflow checks are either
5665 // NSSW or NUSW)
5666 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5667 if (PredIsKnownFalse(Accum, AccumExtended)) {
5668 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5669 return std::nullopt;
5670 }
5671
5672 auto AppendPredicate = [&](const SCEV *Expr,
5673 const SCEV *ExtendedExpr) -> void {
5674 if (Expr != ExtendedExpr &&
5675 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5676 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5677 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5678 Predicates.push_back(Pred);
5679 }
5680 };
5681
5682 AppendPredicate(StartVal, StartExtended);
5683 AppendPredicate(Accum, AccumExtended);
5684
5685 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5686 // which the casts had been folded away. The caller can rewrite SymbolicPHI
5687 // into NewAR if it will also add the runtime overflow checks specified in
5688 // Predicates.
5689 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5690
5691 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5692 std::make_pair(NewAR, Predicates);
5693 // Remember the result of the analysis for this SCEV at this locayyytion.
5694 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5695 return PredRewrite;
5696}
5697
5698std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5700 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5701 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5702 if (!L)
5703 return std::nullopt;
5704
5705 // Check to see if we already analyzed this PHI.
5706 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5707 if (I != PredicatedSCEVRewrites.end()) {
5708 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5709 I->second;
5710 // Analysis was done before and failed to create an AddRec:
5711 if (Rewrite.first == SymbolicPHI)
5712 return std::nullopt;
5713 // Analysis was done before and succeeded to create an AddRec under
5714 // a predicate:
5715 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5716 assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5717 return Rewrite;
5718 }
5719
5720 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5721 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5722
5723 // Record in the cache that the analysis failed
5724 if (!Rewrite) {
5726 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5727 return std::nullopt;
5728 }
5729
5730 return Rewrite;
5731}
5732
5733// FIXME: This utility is currently required because the Rewriter currently
5734// does not rewrite this expression:
5735// {0, +, (sext ix (trunc iy to ix) to iy)}
5736// into {0, +, %step},
5737// even when the following Equal predicate exists:
5738// "%step == (sext ix (trunc iy to ix) to iy)".
5740 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2,
5741 ArrayRef<const SCEVPredicate *> NoWrapPreds) const {
5742 if (AR1 == AR2)
5743 return true;
5744
5745 SCEVUnionPredicate NoWrapUnionPred(NoWrapPreds, SE);
5746 SCEVUnionPredicate AllPreds = Preds->getUnionWith(&NoWrapUnionPred, SE);
5747 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5748 if (Expr1 != Expr2 &&
5749 !AllPreds.implies(SE.getEqualPredicate(Expr1, Expr2), SE) &&
5750 !AllPreds.implies(SE.getEqualPredicate(Expr2, Expr1), SE))
5751 return false;
5752 return true;
5753 };
5754
5755 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5756 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5757 return false;
5758 return true;
5759}
5760
5761/// A helper function for createAddRecFromPHI to handle simple cases.
5762///
5763/// This function tries to find an AddRec expression for the simplest (yet most
5764/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5765/// If it fails, createAddRecFromPHI will use a more general, but slow,
5766/// technique for finding the AddRec expression.
5767const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5768 Value *BEValueV,
5769 Value *StartValueV) {
5770 const Loop *L = LI.getLoopFor(PN->getParent());
5771 assert(L && L->getHeader() == PN->getParent());
5772 assert(BEValueV && StartValueV);
5773
5774 auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN);
5775 if (!BO)
5776 return nullptr;
5777
5778 if (BO->Opcode != Instruction::Add)
5779 return nullptr;
5780
5781 const SCEV *Accum = nullptr;
5782 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5783 Accum = getSCEV(BO->RHS);
5784 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5785 Accum = getSCEV(BO->LHS);
5786
5787 if (!Accum)
5788 return nullptr;
5789
5791 if (BO->IsNUW)
5792 Flags = setFlags(Flags, SCEV::FlagNUW);
5793 if (BO->IsNSW)
5794 Flags = setFlags(Flags, SCEV::FlagNSW);
5795
5796 const SCEV *StartVal = getSCEV(StartValueV);
5797 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5798 insertValueToMap(PN, PHISCEV);
5799
5800 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5801 inferNoWrapViaConstantRanges(AR);
5802
5803 // We can add Flags to the post-inc expression only if we
5804 // know that it is *undefined behavior* for BEValueV to
5805 // overflow.
5806 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5807 assert(isLoopInvariant(Accum, L) &&
5808 "Accum is defined outside L, but is not invariant?");
5809 if (isAddRecNeverPoison(BEInst, L))
5810 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5811 }
5812
5813 return PHISCEV;
5814}
5815
5816const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5817 const Loop *L = LI.getLoopFor(PN->getParent());
5818 if (!L || L->getHeader() != PN->getParent())
5819 return nullptr;
5820
5821 // The loop may have multiple entrances or multiple exits; we can analyze
5822 // this phi as an addrec if it has a unique entry value and a unique
5823 // backedge value.
5824 Value *BEValueV = nullptr, *StartValueV = nullptr;
5825 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5826 Value *V = PN->getIncomingValue(i);
5827 if (L->contains(PN->getIncomingBlock(i))) {
5828 if (!BEValueV) {
5829 BEValueV = V;
5830 } else if (BEValueV != V) {
5831 BEValueV = nullptr;
5832 break;
5833 }
5834 } else if (!StartValueV) {
5835 StartValueV = V;
5836 } else if (StartValueV != V) {
5837 StartValueV = nullptr;
5838 break;
5839 }
5840 }
5841 if (!BEValueV || !StartValueV)
5842 return nullptr;
5843
5844 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5845 "PHI node already processed?");
5846
5847 // First, try to find AddRec expression without creating a fictituos symbolic
5848 // value for PN.
5849 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5850 return S;
5851
5852 // Handle PHI node value symbolically.
5853 const SCEV *SymbolicName = getUnknown(PN);
5854 insertValueToMap(PN, SymbolicName);
5855
5856 // Using this symbolic name for the PHI, analyze the value coming around
5857 // the back-edge.
5858 const SCEV *BEValue = getSCEV(BEValueV);
5859
5860 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5861 // has a special value for the first iteration of the loop.
5862
5863 // If the value coming around the backedge is an add with the symbolic
5864 // value we just inserted, then we found a simple induction variable!
5865 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5866 // If there is a single occurrence of the symbolic value, replace it
5867 // with a recurrence.
5868 unsigned FoundIndex = Add->getNumOperands();
5869 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5870 if (Add->getOperand(i) == SymbolicName)
5871 if (FoundIndex == e) {
5872 FoundIndex = i;
5873 break;
5874 }
5875
5876 if (FoundIndex != Add->getNumOperands()) {
5877 // Create an add with everything but the specified operand.
5879 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5880 if (i != FoundIndex)
5881 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5882 L, *this));
5883 const SCEV *Accum = getAddExpr(Ops);
5884
5885 // This is not a valid addrec if the step amount is varying each
5886 // loop iteration, but is not itself an addrec in this loop.
5887 if (isLoopInvariant(Accum, L) ||
5888 (isa<SCEVAddRecExpr>(Accum) &&
5889 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5891
5892 if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
5893 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5894 if (BO->IsNUW)
5895 Flags = setFlags(Flags, SCEV::FlagNUW);
5896 if (BO->IsNSW)
5897 Flags = setFlags(Flags, SCEV::FlagNSW);
5898 }
5899 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5900 if (GEP->getOperand(0) == PN) {
5901 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
5902 // If the increment has any nowrap flags, then we know the address
5903 // space cannot be wrapped around.
5904 if (NW != GEPNoWrapFlags::none())
5905 Flags = setFlags(Flags, SCEV::FlagNW);
5906 // If the GEP is nuw or nusw with non-negative offset, we know that
5907 // no unsigned wrap occurs. We cannot set the nsw flag as only the
5908 // offset is treated as signed, while the base is unsigned.
5909 if (NW.hasNoUnsignedWrap() ||
5911 Flags = setFlags(Flags, SCEV::FlagNUW);
5912 }
5913
5914 // We cannot transfer nuw and nsw flags from subtraction
5915 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5916 // for instance.
5917 }
5918
5919 const SCEV *StartVal = getSCEV(StartValueV);
5920 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5921
5922 // Okay, for the entire analysis of this edge we assumed the PHI
5923 // to be symbolic. We now need to go back and purge all of the
5924 // entries for the scalars that use the symbolic expression.
5925 forgetMemoizedResults({SymbolicName});
5926 insertValueToMap(PN, PHISCEV);
5927
5928 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5929 inferNoWrapViaConstantRanges(AR);
5930
5931 // We can add Flags to the post-inc expression only if we
5932 // know that it is *undefined behavior* for BEValueV to
5933 // overflow.
5934 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5935 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5936 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5937
5938 return PHISCEV;
5939 }
5940 }
5941 } else {
5942 // Otherwise, this could be a loop like this:
5943 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5944 // In this case, j = {1,+,1} and BEValue is j.
5945 // Because the other in-value of i (0) fits the evolution of BEValue
5946 // i really is an addrec evolution.
5947 //
5948 // We can generalize this saying that i is the shifted value of BEValue
5949 // by one iteration:
5950 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5951
5952 // Do not allow refinement in rewriting of BEValue.
5953 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5954 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5955 if (Shifted != getCouldNotCompute() && Start != getCouldNotCompute() &&
5956 isGuaranteedNotToCauseUB(Shifted) && ::impliesPoison(Shifted, Start)) {
5957 const SCEV *StartVal = getSCEV(StartValueV);
5958 if (Start == StartVal) {
5959 // Okay, for the entire analysis of this edge we assumed the PHI
5960 // to be symbolic. We now need to go back and purge all of the
5961 // entries for the scalars that use the symbolic expression.
5962 forgetMemoizedResults({SymbolicName});
5963 insertValueToMap(PN, Shifted);
5964 return Shifted;
5965 }
5966 }
5967 }
5968
5969 // Remove the temporary PHI node SCEV that has been inserted while intending
5970 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5971 // as it will prevent later (possibly simpler) SCEV expressions to be added
5972 // to the ValueExprMap.
5973 eraseValueFromMap(PN);
5974
5975 return nullptr;
5976}
5977
5978// Try to match a control flow sequence that branches out at BI and merges back
5979// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5980// match.
5982 Value *&C, Value *&LHS, Value *&RHS) {
5983 C = BI->getCondition();
5984
5985 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5986 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5987
5988 Use &LeftUse = Merge->getOperandUse(0);
5989 Use &RightUse = Merge->getOperandUse(1);
5990
5991 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5992 LHS = LeftUse;
5993 RHS = RightUse;
5994 return true;
5995 }
5996
5997 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5998 LHS = RightUse;
5999 RHS = LeftUse;
6000 return true;
6001 }
6002
6003 return false;
6004}
6005
6007 Value *&Cond, Value *&LHS,
6008 Value *&RHS) {
6009 auto IsReachable =
6010 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
6011 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
6012 // Try to match
6013 //
6014 // br %cond, label %left, label %right
6015 // left:
6016 // br label %merge
6017 // right:
6018 // br label %merge
6019 // merge:
6020 // V = phi [ %x, %left ], [ %y, %right ]
6021 //
6022 // as "select %cond, %x, %y"
6023
6024 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
6025 assert(IDom && "At least the entry block should dominate PN");
6026
6027 auto *BI = dyn_cast<CondBrInst>(IDom->getTerminator());
6028 return BI && BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS);
6029 }
6030 return false;
6031}
6032
6033const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
6034 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6035 if (getOperandsForSelectLikePHI(DT, PN, Cond, LHS, RHS) &&
6038 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
6039
6040 return nullptr;
6041}
6042
6044 BinaryOperator *CommonInst = nullptr;
6045 // Check if instructions are identical.
6046 for (Value *Incoming : PN->incoming_values()) {
6047 auto *IncomingInst = dyn_cast<BinaryOperator>(Incoming);
6048 if (!IncomingInst)
6049 return nullptr;
6050 if (CommonInst) {
6051 if (!CommonInst->isIdenticalToWhenDefined(IncomingInst))
6052 return nullptr; // Not identical, give up
6053 } else {
6054 // Remember binary operator
6055 CommonInst = IncomingInst;
6056 }
6057 }
6058 return CommonInst;
6059}
6060
6061/// Returns SCEV for the first operand of a phi if all phi operands have
6062/// identical opcodes and operands
6063/// eg.
6064/// a: %add = %a + %b
6065/// br %c
6066/// b: %add1 = %a + %b
6067/// br %c
6068/// c: %phi = phi [%add, a], [%add1, b]
6069/// scev(%phi) => scev(%add)
6070const SCEV *
6071ScalarEvolution::createNodeForPHIWithIdenticalOperands(PHINode *PN) {
6072 BinaryOperator *CommonInst = getCommonInstForPHI(PN);
6073 if (!CommonInst)
6074 return nullptr;
6075
6076 // Check if SCEV exprs for instructions are identical.
6077 const SCEV *CommonSCEV = getSCEV(CommonInst);
6078 bool SCEVExprsIdentical =
6080 [this, CommonSCEV](Value *V) { return CommonSCEV == getSCEV(V); });
6081 return SCEVExprsIdentical ? CommonSCEV : nullptr;
6082}
6083
6084const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
6085 if (const SCEV *S = createAddRecFromPHI(PN))
6086 return S;
6087
6088 // We do not allow simplifying phi (undef, X) to X here, to avoid reusing the
6089 // phi node for X.
6090 if (Value *V = simplifyInstruction(
6091 PN, {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
6092 /*UseInstrInfo=*/true, /*CanUseUndef=*/false}))
6093 return getSCEV(V);
6094
6095 if (const SCEV *S = createNodeForPHIWithIdenticalOperands(PN))
6096 return S;
6097
6098 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
6099 return S;
6100
6101 // If it's not a loop phi, we can't handle it yet.
6102 return getUnknown(PN);
6103}
6104
6105bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
6106 SCEVTypes RootKind) {
6107 struct FindClosure {
6108 const SCEV *OperandToFind;
6109 const SCEVTypes RootKind; // Must be a sequential min/max expression.
6110 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
6111
6112 bool Found = false;
6113
6114 bool canRecurseInto(SCEVTypes Kind) const {
6115 // We can only recurse into the SCEV expression of the same effective type
6116 // as the type of our root SCEV expression, and into zero-extensions.
6117 return RootKind == Kind || NonSequentialRootKind == Kind ||
6118 scZeroExtend == Kind;
6119 };
6120
6121 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
6122 : OperandToFind(OperandToFind), RootKind(RootKind),
6123 NonSequentialRootKind(
6125 RootKind)) {}
6126
6127 bool follow(const SCEV *S) {
6128 Found = S == OperandToFind;
6129
6130 return !isDone() && canRecurseInto(S->getSCEVType());
6131 }
6132
6133 bool isDone() const { return Found; }
6134 };
6135
6136 FindClosure FC(OperandToFind, RootKind);
6137 visitAll(Root, FC);
6138 return FC.Found;
6139}
6140
6141std::optional<const SCEV *>
6142ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
6143 ICmpInst *Cond,
6144 Value *TrueVal,
6145 Value *FalseVal) {
6146 // Try to match some simple smax or umax patterns.
6147 auto *ICI = Cond;
6148
6149 Value *LHS = ICI->getOperand(0);
6150 Value *RHS = ICI->getOperand(1);
6151
6152 switch (ICI->getPredicate()) {
6153 case ICmpInst::ICMP_SLT:
6154 case ICmpInst::ICMP_SLE:
6155 case ICmpInst::ICMP_ULT:
6156 case ICmpInst::ICMP_ULE:
6157 std::swap(LHS, RHS);
6158 [[fallthrough]];
6159 case ICmpInst::ICMP_SGT:
6160 case ICmpInst::ICMP_SGE:
6161 case ICmpInst::ICMP_UGT:
6162 case ICmpInst::ICMP_UGE:
6163 // a > b ? a+x : b+x -> max(a, b)+x
6164 // a > b ? b+x : a+x -> min(a, b)+x
6166 bool Signed = ICI->isSigned();
6167 const SCEV *LA = getSCEV(TrueVal);
6168 const SCEV *RA = getSCEV(FalseVal);
6169 const SCEV *LS = getSCEV(LHS);
6170 const SCEV *RS = getSCEV(RHS);
6171 if (LA->getType()->isPointerTy()) {
6172 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6173 // Need to make sure we can't produce weird expressions involving
6174 // negated pointers.
6175 if (LA == LS && RA == RS)
6176 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6177 if (LA == RS && RA == LS)
6178 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6179 }
6180 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6181 if (Op->getType()->isPointerTy()) {
6184 return Op;
6185 }
6186 if (Signed)
6187 Op = getNoopOrSignExtend(Op, Ty);
6188 else
6189 Op = getNoopOrZeroExtend(Op, Ty);
6190 return Op;
6191 };
6192 LS = CoerceOperand(LS);
6193 RS = CoerceOperand(RS);
6195 break;
6196 const SCEV *LDiff = getMinusSCEV(LA, LS);
6197 const SCEV *RDiff = getMinusSCEV(RA, RS);
6198 if (LDiff == RDiff)
6199 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6200 LDiff);
6201 LDiff = getMinusSCEV(LA, RS);
6202 RDiff = getMinusSCEV(RA, LS);
6203 if (LDiff == RDiff)
6204 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6205 LDiff);
6206 }
6207 break;
6208 case ICmpInst::ICMP_NE:
6209 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
6210 std::swap(TrueVal, FalseVal);
6211 [[fallthrough]];
6212 case ICmpInst::ICMP_EQ:
6213 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
6216 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6217 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y
6218 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y
6219 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6220 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y
6221 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6222 return getAddExpr(getUMaxExpr(X, C), Y);
6223 }
6224 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
6225 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
6226 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
6227 // -> umin_seq(x, umin (..., umin_seq(...), ...))
6229 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6230 const SCEV *X = getSCEV(LHS);
6231 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6232 X = ZExt->getOperand();
6233 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6234 const SCEV *FalseValExpr = getSCEV(FalseVal);
6235 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6236 return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6237 /*Sequential=*/true);
6238 }
6239 }
6240 break;
6241 default:
6242 break;
6243 }
6244
6245 return std::nullopt;
6246}
6247
6248static std::optional<const SCEV *>
6250 const SCEV *TrueExpr, const SCEV *FalseExpr) {
6251 assert(CondExpr->getType()->isIntegerTy(1) &&
6252 TrueExpr->getType() == FalseExpr->getType() &&
6253 TrueExpr->getType()->isIntegerTy(1) &&
6254 "Unexpected operands of a select.");
6255
6256 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
6257 // --> C + (umin_seq cond, x - C)
6258 //
6259 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
6260 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6261 // --> C + (umin_seq ~cond, x - C)
6262
6263 // FIXME: while we can't legally model the case where both of the hands
6264 // are fully variable, we only require that the *difference* is constant.
6265 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6266 return std::nullopt;
6267
6268 const SCEV *X, *C;
6269 if (isa<SCEVConstant>(TrueExpr)) {
6270 CondExpr = SE->getNotSCEV(CondExpr);
6271 X = FalseExpr;
6272 C = TrueExpr;
6273 } else {
6274 X = TrueExpr;
6275 C = FalseExpr;
6276 }
6277 return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6278 /*Sequential=*/true));
6279}
6280
6281static std::optional<const SCEV *>
6283 Value *FalseVal) {
6284 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6285 return std::nullopt;
6286
6287 const auto *SECond = SE->getSCEV(Cond);
6288 const auto *SETrue = SE->getSCEV(TrueVal);
6289 const auto *SEFalse = SE->getSCEV(FalseVal);
6290 return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6291}
6292
6293const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6294 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6295 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6296 assert(TrueVal->getType() == FalseVal->getType() &&
6297 V->getType() == TrueVal->getType() &&
6298 "Types of select hands and of the result must match.");
6299
6300 // For now, only deal with i1-typed `select`s.
6301 if (!V->getType()->isIntegerTy(1))
6302 return getUnknown(V);
6303
6304 if (std::optional<const SCEV *> S =
6305 createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6306 return *S;
6307
6308 return getUnknown(V);
6309}
6310
6311const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6312 Value *TrueVal,
6313 Value *FalseVal) {
6314 // Handle "constant" branch or select. This can occur for instance when a
6315 // loop pass transforms an inner loop and moves on to process the outer loop.
6316 if (auto *CI = dyn_cast<ConstantInt>(Cond))
6317 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6318
6319 if (auto *I = dyn_cast<Instruction>(V)) {
6320 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6321 if (std::optional<const SCEV *> S =
6322 createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6323 TrueVal, FalseVal))
6324 return *S;
6325 }
6326 }
6327
6328 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6329}
6330
6331/// Expand GEP instructions into add and multiply operations. This allows them
6332/// to be analyzed by regular SCEV code.
6333const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6334 assert(GEP->getSourceElementType()->isSized() &&
6335 "GEP source element type must be sized");
6336
6337 SmallVector<SCEVUse, 4> IndexExprs;
6338 for (Value *Index : GEP->indices())
6339 IndexExprs.push_back(getSCEV(Index));
6340 return getGEPExpr(GEP, IndexExprs);
6341}
6342
6343APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S,
6344 const Instruction *CtxI) {
6346 auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6347 return TrailingZeros >= BitWidth
6349 : APInt::getOneBitSet(BitWidth, TrailingZeros);
6350 };
6351 auto GetGCDMultiple = [this, CtxI](const SCEVNAryExpr *N) {
6352 // The result is GCD of all operands results.
6353 APInt Res = getConstantMultiple(N->getOperand(0), CtxI);
6354 for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6356 Res, getConstantMultiple(N->getOperand(I), CtxI));
6357 return Res;
6358 };
6359
6360 switch (S->getSCEVType()) {
6361 case scConstant:
6362 return cast<SCEVConstant>(S)->getAPInt();
6363 case scPtrToAddr:
6364 return getConstantMultiple(cast<SCEVCastExpr>(S)->getOperand());
6365 case scUDivExpr:
6366 case scVScale:
6367 return APInt(BitWidth, 1);
6368 case scTruncate: {
6369 // Only multiples that are a power of 2 will hold after truncation.
6370 const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6371 uint32_t TZ = getMinTrailingZeros(T->getOperand(), CtxI);
6372 return GetShiftedByZeros(TZ);
6373 }
6374 case scZeroExtend: {
6375 const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(S);
6376 return getConstantMultiple(Z->getOperand(), CtxI).zext(BitWidth);
6377 }
6378 case scSignExtend: {
6379 // Only multiples that are a power of 2 will hold after sext.
6380 const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6381 uint32_t TZ = getMinTrailingZeros(E->getOperand(), CtxI);
6382 return GetShiftedByZeros(TZ);
6383 }
6384 case scMulExpr: {
6385 const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6386 if (M->hasNoUnsignedWrap()) {
6387 // The result is the product of all operand results.
6388 APInt Res = getConstantMultiple(M->getOperand(0), CtxI);
6389 for (const SCEV *Operand : M->operands().drop_front())
6390 Res = Res * getConstantMultiple(Operand, CtxI);
6391 return Res;
6392 }
6393
6394 // If there are no wrap guarentees, find the trailing zeros, which is the
6395 // sum of trailing zeros for all its operands.
6396 uint32_t TZ = 0;
6397 for (const SCEV *Operand : M->operands())
6398 TZ += getMinTrailingZeros(Operand, CtxI);
6399 return GetShiftedByZeros(TZ);
6400 }
6401 case scAddExpr:
6402 case scAddRecExpr: {
6403 const SCEVNAryExpr *N = cast<SCEVNAryExpr>(S);
6404 if (N->hasNoUnsignedWrap())
6405 return GetGCDMultiple(N);
6406 // Find the trailing bits, which is the minimum of its operands.
6407 uint32_t TZ = getMinTrailingZeros(N->getOperand(0), CtxI);
6408 for (const SCEV *Operand : N->operands().drop_front())
6409 TZ = std::min(TZ, getMinTrailingZeros(Operand, CtxI));
6410 return GetShiftedByZeros(TZ);
6411 }
6412 case scUMaxExpr:
6413 case scSMaxExpr:
6414 case scUMinExpr:
6415 case scSMinExpr:
6417 return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6418 case scUnknown: {
6419 // Ask ValueTracking for known bits. SCEVUnknown only become available at
6420 // the point their underlying IR instruction has been defined. If CtxI was
6421 // not provided, use:
6422 // * the first instruction in the entry block if it is an argument
6423 // * the instruction itself otherwise.
6424 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6425 if (!CtxI) {
6426 if (isa<Argument>(U->getValue()))
6427 CtxI = &*F.getEntryBlock().begin();
6428 else if (auto *I = dyn_cast<Instruction>(U->getValue()))
6429 CtxI = I;
6430 }
6431 unsigned Known =
6432 computeKnownBits(U->getValue(),
6433 SimplifyQuery(getDataLayout(), &DT, &AC, CtxI)
6434 .allowEphemerals(true))
6435 .countMinTrailingZeros();
6436 return GetShiftedByZeros(Known);
6437 }
6438 case scCouldNotCompute:
6439 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6440 }
6441 llvm_unreachable("Unknown SCEV kind!");
6442}
6443
6445 const Instruction *CtxI) {
6446 // Skip looking up and updating the cache if there is a context instruction,
6447 // as the result will only be valid in the specified context.
6448 if (CtxI)
6449 return getConstantMultipleImpl(S, CtxI);
6450
6451 auto I = ConstantMultipleCache.find(S);
6452 if (I != ConstantMultipleCache.end())
6453 return I->second;
6454
6455 APInt Result = getConstantMultipleImpl(S, CtxI);
6456 auto InsertPair = ConstantMultipleCache.insert({S, Result});
6457 assert(InsertPair.second && "Should insert a new key");
6458 return InsertPair.first->second;
6459}
6460
6462 APInt Multiple = getConstantMultiple(S);
6463 return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6464}
6465
6467 const Instruction *CtxI) {
6468 return std::min(getConstantMultiple(S, CtxI).countTrailingZeros(),
6469 (unsigned)getTypeSizeInBits(S->getType()));
6470}
6471
6472/// Helper method to assign a range to V from metadata present in the IR.
6473static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6475 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6476 return getConstantRangeFromMetadata(*MD);
6477 if (const auto *CB = dyn_cast<CallBase>(V))
6478 if (std::optional<ConstantRange> Range = CB->getRange())
6479 return Range;
6480 }
6481 if (auto *A = dyn_cast<Argument>(V))
6482 if (std::optional<ConstantRange> Range = A->getRange())
6483 return Range;
6484
6485 return std::nullopt;
6486}
6487
6489 SCEV::NoWrapFlags Flags) {
6490 if (AddRec->getNoWrapFlags(Flags) != Flags) {
6491 AddRec->setNoWrapFlags(Flags);
6492 UnsignedRanges.erase(AddRec);
6493 SignedRanges.erase(AddRec);
6494 ConstantMultipleCache.erase(AddRec);
6495 }
6496}
6497
6498ConstantRange ScalarEvolution::
6499getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6500 const DataLayout &DL = getDataLayout();
6501
6502 unsigned BitWidth = getTypeSizeInBits(U->getType());
6503 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6504
6505 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6506 // use information about the trip count to improve our available range. Note
6507 // that the trip count independent cases are already handled by known bits.
6508 // WARNING: The definition of recurrence used here is subtly different than
6509 // the one used by AddRec (and thus most of this file). Step is allowed to
6510 // be arbitrarily loop varying here, where AddRec allows only loop invariant
6511 // and other addrecs in the same loop (for non-affine addrecs). The code
6512 // below intentionally handles the case where step is not loop invariant.
6513 auto *P = dyn_cast<PHINode>(U->getValue());
6514 if (!P)
6515 return FullSet;
6516
6517 // Make sure that no Phi input comes from an unreachable block. Otherwise,
6518 // even the values that are not available in these blocks may come from them,
6519 // and this leads to false-positive recurrence test.
6520 for (auto *Pred : predecessors(P->getParent()))
6521 if (!DT.isReachableFromEntry(Pred))
6522 return FullSet;
6523
6524 BinaryOperator *BO;
6525 Value *Start, *Step;
6526 if (!matchSimpleRecurrence(P, BO, Start, Step))
6527 return FullSet;
6528
6529 // If we found a recurrence in reachable code, we must be in a loop. Note
6530 // that BO might be in some subloop of L, and that's completely okay.
6531 auto *L = LI.getLoopFor(P->getParent());
6532 assert(L && L->getHeader() == P->getParent());
6533 if (!L->contains(BO->getParent()))
6534 // NOTE: This bailout should be an assert instead. However, asserting
6535 // the condition here exposes a case where LoopFusion is querying SCEV
6536 // with malformed loop information during the midst of the transform.
6537 // There doesn't appear to be an obvious fix, so for the moment bailout
6538 // until the caller issue can be fixed. PR49566 tracks the bug.
6539 return FullSet;
6540
6541 // TODO: Extend to other opcodes such as mul, and div
6542 switch (BO->getOpcode()) {
6543 default:
6544 return FullSet;
6545 case Instruction::AShr:
6546 case Instruction::LShr:
6547 case Instruction::Shl:
6548 break;
6549 };
6550
6551 if (BO->getOperand(0) != P)
6552 // TODO: Handle the power function forms some day.
6553 return FullSet;
6554
6555 unsigned TC = getSmallConstantMaxTripCount(L);
6556 if (!TC || TC >= BitWidth)
6557 return FullSet;
6558
6559 auto KnownStart = computeKnownBits(Start, DL, &AC, nullptr, &DT);
6560 auto KnownStep = computeKnownBits(Step, DL, &AC, nullptr, &DT);
6561 assert(KnownStart.getBitWidth() == BitWidth &&
6562 KnownStep.getBitWidth() == BitWidth);
6563
6564 // Compute total shift amount, being careful of overflow and bitwidths.
6565 auto MaxShiftAmt = KnownStep.getMaxValue();
6566 APInt TCAP(BitWidth, TC-1);
6567 bool Overflow = false;
6568 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6569 if (Overflow)
6570 return FullSet;
6571
6572 switch (BO->getOpcode()) {
6573 default:
6574 llvm_unreachable("filtered out above");
6575 case Instruction::AShr: {
6576 // For each ashr, three cases:
6577 // shift = 0 => unchanged value
6578 // saturation => 0 or -1
6579 // other => a value closer to zero (of the same sign)
6580 // Thus, the end value is closer to zero than the start.
6581 auto KnownEnd = KnownBits::ashr(KnownStart,
6582 KnownBits::makeConstant(TotalShift));
6583 if (KnownStart.isNonNegative())
6584 // Analogous to lshr (simply not yet canonicalized)
6585 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6586 KnownStart.getMaxValue() + 1);
6587 if (KnownStart.isNegative())
6588 // End >=u Start && End <=s Start
6589 return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6590 KnownEnd.getMaxValue() + 1);
6591 break;
6592 }
6593 case Instruction::LShr: {
6594 // For each lshr, three cases:
6595 // shift = 0 => unchanged value
6596 // saturation => 0
6597 // other => a smaller positive number
6598 // Thus, the low end of the unsigned range is the last value produced.
6599 auto KnownEnd = KnownBits::lshr(KnownStart,
6600 KnownBits::makeConstant(TotalShift));
6601 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6602 KnownStart.getMaxValue() + 1);
6603 }
6604 case Instruction::Shl: {
6605 // Iff no bits are shifted out, value increases on every shift.
6606 auto KnownEnd = KnownBits::shl(KnownStart,
6607 KnownBits::makeConstant(TotalShift));
6608 if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6609 return ConstantRange(KnownStart.getMinValue(),
6610 KnownEnd.getMaxValue() + 1);
6611 break;
6612 }
6613 };
6614 return FullSet;
6615}
6616
6617// The goal of this function is to check if recursively visiting the operands
6618// of this PHI might lead to an infinite loop. If we do see such a loop,
6619// there's no good way to break it, so we avoid analyzing such cases.
6620//
6621// getRangeRef previously used a visited set to avoid infinite loops, but this
6622// caused other issues: the result was dependent on the order of getRangeRef
6623// calls, and the interaction with createSCEVIter could cause a stack overflow
6624// in some cases (see issue #148253).
6625//
6626// FIXME: The way this is implemented is overly conservative; this checks
6627// for a few obviously safe patterns, but anything that doesn't lead to
6628// recursion is fine.
6630 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6632 return true;
6633
6634 if (all_of(PHI->operands(),
6635 [&](Value *Operand) { return DT.dominates(Operand, PHI); }))
6636 return true;
6637
6638 return false;
6639}
6640
6641const ConstantRange &
6642ScalarEvolution::getRangeRefIter(const SCEV *S,
6643 ScalarEvolution::RangeSignHint SignHint) {
6644 DenseMap<const SCEV *, ConstantRange> &Cache =
6645 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6646 : SignedRanges;
6647 SmallVector<SCEVUse> WorkList;
6648 SmallPtrSet<const SCEV *, 8> Seen;
6649
6650 // Add Expr to the worklist, if Expr is either an N-ary expression or a
6651 // SCEVUnknown PHI node.
6652 auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6653 if (!Seen.insert(Expr).second)
6654 return;
6655 if (Cache.contains(Expr))
6656 return;
6657 switch (Expr->getSCEVType()) {
6658 case scUnknown:
6660 break;
6661 [[fallthrough]];
6662 case scConstant:
6663 case scVScale:
6664 case scTruncate:
6665 case scZeroExtend:
6666 case scSignExtend:
6667 case scPtrToAddr:
6668 case scAddExpr:
6669 case scMulExpr:
6670 case scUDivExpr:
6671 case scAddRecExpr:
6672 case scUMaxExpr:
6673 case scSMaxExpr:
6674 case scUMinExpr:
6675 case scSMinExpr:
6677 WorkList.push_back(Expr);
6678 break;
6679 case scCouldNotCompute:
6680 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6681 }
6682 };
6683 AddToWorklist(S);
6684
6685 // Build worklist by queuing operands of N-ary expressions and phi nodes.
6686 for (unsigned I = 0; I != WorkList.size(); ++I) {
6687 const SCEV *P = WorkList[I];
6688 auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6689 // If it is not a `SCEVUnknown`, just recurse into operands.
6690 if (!UnknownS) {
6691 for (const SCEV *Op : P->operands())
6692 AddToWorklist(Op);
6693 continue;
6694 }
6695 // `SCEVUnknown`'s require special treatment.
6696 if (PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6697 if (!RangeRefPHIAllowedOperands(DT, P))
6698 continue;
6699 for (auto &Op : reverse(P->operands()))
6700 AddToWorklist(getSCEV(Op));
6701 }
6702 }
6703
6704 if (!WorkList.empty()) {
6705 // Use getRangeRef to compute ranges for items in the worklist in reverse
6706 // order. This will force ranges for earlier operands to be computed before
6707 // their users in most cases.
6708 for (const SCEV *P : reverse(drop_begin(WorkList))) {
6709 getRangeRef(P, SignHint);
6710 }
6711 }
6712
6713 return getRangeRef(S, SignHint, 0);
6714}
6715
6716const APInt *ScalarEvolution::getConstantAPIntOrNull(const SCEV *S) {
6717 if (const auto *C = dyn_cast<SCEVConstant>(S))
6718 return &C->getAPInt();
6719 return nullptr;
6720}
6721
6722/// Determine the range for a particular SCEV. If SignHint is
6723/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6724/// with a "cleaner" unsigned (resp. signed) representation.
6725const ConstantRange &ScalarEvolution::getRangeRef(
6726 const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6727 DenseMap<const SCEV *, ConstantRange> &Cache =
6728 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6729 : SignedRanges;
6731 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6733
6734 // See if we've computed this range already.
6735 auto I = Cache.find(S);
6736 if (I != Cache.end())
6737 return I->second;
6738
6739 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6740 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6741
6742 // Switch to iteratively computing the range for S, if it is part of a deeply
6743 // nested expression.
6745 return getRangeRefIter(S, SignHint);
6746
6747 unsigned BitWidth = getTypeSizeInBits(S->getType());
6748 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6749 using OBO = OverflowingBinaryOperator;
6750
6751 // If the value has known zeros, the maximum value will have those known zeros
6752 // as well.
6753 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6754 APInt Multiple = getNonZeroConstantMultiple(S);
6755 APInt Remainder = APInt::getMaxValue(BitWidth).urem(Multiple);
6756 if (!Remainder.isZero())
6757 ConservativeResult =
6758 ConstantRange(APInt::getMinValue(BitWidth),
6759 APInt::getMaxValue(BitWidth) - Remainder + 1);
6760 }
6761 else {
6762 uint32_t TZ = getMinTrailingZeros(S);
6763 if (TZ != 0) {
6764 ConservativeResult = ConstantRange(
6766 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6767 }
6768 }
6769
6770 switch (S->getSCEVType()) {
6771 case scConstant:
6772 llvm_unreachable("Already handled above.");
6773 case scVScale:
6774 return setRange(S, SignHint, getVScaleRange(&F, BitWidth));
6775 case scTruncate: {
6776 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6777 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6778 return setRange(
6779 Trunc, SignHint,
6780 ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6781 }
6782 case scZeroExtend: {
6783 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6784 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6785 return setRange(
6786 ZExt, SignHint,
6787 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6788 }
6789 case scSignExtend: {
6790 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6791 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6792 return setRange(
6793 SExt, SignHint,
6794 ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6795 }
6796 case scPtrToAddr: {
6797 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6798 ConstantRange X = getRangeRef(Cast->getOperand(), SignHint, Depth + 1);
6799 return setRange(Cast, SignHint, X);
6800 }
6801 case scAddExpr: {
6802 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6803 // Check if this is a URem pattern: A - (A / B) * B, which is always < B.
6804 const SCEV *URemLHS = nullptr, *URemRHS = nullptr;
6805 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED &&
6806 match(S, m_scev_URem(m_SCEV(URemLHS), m_SCEV(URemRHS), *this))) {
6807 ConstantRange LHSRange = getRangeRef(URemLHS, SignHint, Depth + 1);
6808 ConstantRange RHSRange = getRangeRef(URemRHS, SignHint, Depth + 1);
6809 ConservativeResult =
6810 ConservativeResult.intersectWith(LHSRange.urem(RHSRange), RangeType);
6811 }
6812 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6813 unsigned WrapType = OBO::AnyWrap;
6814 if (Add->hasNoSignedWrap())
6815 WrapType |= OBO::NoSignedWrap;
6816 if (Add->hasNoUnsignedWrap())
6817 WrapType |= OBO::NoUnsignedWrap;
6818 for (const SCEV *Op : drop_begin(Add->operands()))
6819 X = X.addWithNoWrap(getRangeRef(Op, SignHint, Depth + 1), WrapType,
6820 RangeType);
6821 return setRange(Add, SignHint,
6822 ConservativeResult.intersectWith(X, RangeType));
6823 }
6824 case scMulExpr: {
6825 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6826 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6827 for (const SCEV *Op : drop_begin(Mul->operands()))
6828 X = X.multiply(getRangeRef(Op, SignHint, Depth + 1));
6829 return setRange(Mul, SignHint,
6830 ConservativeResult.intersectWith(X, RangeType));
6831 }
6832 case scUDivExpr: {
6833 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6834 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6835 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6836 return setRange(UDiv, SignHint,
6837 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6838 }
6839 case scAddRecExpr: {
6840 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6841 // If there's no unsigned wrap, the value will never be less than its
6842 // initial value.
6843 if (AddRec->hasNoUnsignedWrap()) {
6844 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6845 if (!UnsignedMinValue.isZero())
6846 ConservativeResult = ConservativeResult.intersectWith(
6847 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6848 }
6849
6850 // If there's no signed wrap, and all the operands except initial value have
6851 // the same sign or zero, the value won't ever be:
6852 // 1: smaller than initial value if operands are non negative,
6853 // 2: bigger than initial value if operands are non positive.
6854 // For both cases, value can not cross signed min/max boundary.
6855 if (AddRec->hasNoSignedWrap()) {
6856 bool AllNonNeg = true;
6857 bool AllNonPos = true;
6858 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6859 if (!isKnownNonNegative(AddRec->getOperand(i)))
6860 AllNonNeg = false;
6861 if (!isKnownNonPositive(AddRec->getOperand(i)))
6862 AllNonPos = false;
6863 }
6864 if (AllNonNeg)
6865 ConservativeResult = ConservativeResult.intersectWith(
6868 RangeType);
6869 else if (AllNonPos)
6870 ConservativeResult = ConservativeResult.intersectWith(
6872 getSignedRangeMax(AddRec->getStart()) +
6873 1),
6874 RangeType);
6875 }
6876
6877 // TODO: non-affine addrec
6878 if (AddRec->isAffine()) {
6879 const SCEV *MaxBEScev =
6881 if (!isa<SCEVCouldNotCompute>(MaxBEScev)) {
6882 APInt MaxBECount = cast<SCEVConstant>(MaxBEScev)->getAPInt();
6883
6884 // Adjust MaxBECount to the same bitwidth as AddRec. We can truncate if
6885 // MaxBECount's active bits are all <= AddRec's bit width.
6886 if (MaxBECount.getBitWidth() > BitWidth &&
6887 MaxBECount.getActiveBits() <= BitWidth)
6888 MaxBECount = MaxBECount.trunc(BitWidth);
6889 else if (MaxBECount.getBitWidth() < BitWidth)
6890 MaxBECount = MaxBECount.zext(BitWidth);
6891
6892 if (MaxBECount.getBitWidth() == BitWidth) {
6893 auto [RangeFromAffine, Flags] = getRangeForAffineAR(
6894 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6895 ConservativeResult =
6896 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6897 const_cast<SCEVAddRecExpr *>(AddRec)->setNoWrapFlags(Flags);
6898
6899 auto RangeFromFactoring = getRangeViaFactoring(
6900 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6901 ConservativeResult =
6902 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6903 }
6904 }
6905
6906 // Now try symbolic BE count and more powerful methods.
6908 const SCEV *SymbolicMaxBECount =
6910 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6911 getTypeSizeInBits(MaxBEScev->getType()) <= BitWidth &&
6912 AddRec->hasNoSelfWrap()) {
6913 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6914 AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6915 ConservativeResult =
6916 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6917 }
6918 }
6919 }
6920
6921 return setRange(AddRec, SignHint, std::move(ConservativeResult));
6922 }
6923 case scUMaxExpr:
6924 case scSMaxExpr:
6925 case scUMinExpr:
6926 case scSMinExpr:
6927 case scSequentialUMinExpr: {
6929 switch (S->getSCEVType()) {
6930 case scUMaxExpr:
6931 ID = Intrinsic::umax;
6932 break;
6933 case scSMaxExpr:
6934 ID = Intrinsic::smax;
6935 break;
6936 case scUMinExpr:
6938 ID = Intrinsic::umin;
6939 break;
6940 case scSMinExpr:
6941 ID = Intrinsic::smin;
6942 break;
6943 default:
6944 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6945 }
6946
6947 const auto *NAry = cast<SCEVNAryExpr>(S);
6948 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
6949 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6950 X = X.intrinsic(
6951 ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
6952 return setRange(S, SignHint,
6953 ConservativeResult.intersectWith(X, RangeType));
6954 }
6955 case scUnknown: {
6956 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6957 Value *V = U->getValue();
6958
6959 // Check if the IR explicitly contains !range metadata.
6960 std::optional<ConstantRange> MDRange = GetRangeFromMetadata(V);
6961 if (MDRange)
6962 ConservativeResult =
6963 ConservativeResult.intersectWith(*MDRange, RangeType);
6964
6965 // Use facts about recurrences in the underlying IR. Note that add
6966 // recurrences are AddRecExprs and thus don't hit this path. This
6967 // primarily handles shift recurrences.
6968 auto CR = getRangeForUnknownRecurrence(U);
6969 ConservativeResult = ConservativeResult.intersectWith(CR);
6970
6971 // See if ValueTracking can give us a useful range.
6972 const DataLayout &DL = getDataLayout();
6973 KnownBits Known = computeKnownBits(V, DL, &AC, nullptr, &DT);
6974 if (Known.getBitWidth() != BitWidth)
6975 Known = Known.zextOrTrunc(BitWidth);
6976
6977 // ValueTracking may be able to compute a tighter result for the number of
6978 // sign bits than for the value of those sign bits.
6979 unsigned NS = ComputeNumSignBits(V, DL, &AC, nullptr, &DT);
6980 if (U->getType()->isPointerTy()) {
6981 // If the pointer size is larger than the index size type, this can cause
6982 // NS to be larger than BitWidth. So compensate for this.
6983 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
6984 int ptrIdxDiff = ptrSize - BitWidth;
6985 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
6986 NS -= ptrIdxDiff;
6987 }
6988
6989 if (NS > 1) {
6990 // If we know any of the sign bits, we know all of the sign bits.
6991 if (!Known.Zero.getHiBits(NS).isZero())
6992 Known.Zero.setHighBits(NS);
6993 if (!Known.One.getHiBits(NS).isZero())
6994 Known.One.setHighBits(NS);
6995 }
6996
6997 if (Known.getMinValue() != Known.getMaxValue() + 1)
6998 ConservativeResult = ConservativeResult.intersectWith(
6999 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
7000 RangeType);
7001 if (NS > 1)
7002 ConservativeResult = ConservativeResult.intersectWith(
7003 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
7004 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
7005 RangeType);
7006
7007 if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
7008 // Strengthen the range if the underlying IR value is a
7009 // global/alloca/heap allocation using the size of the object.
7010 bool CanBeNull;
7011 uint64_t DerefBytes = V->getPointerDereferenceableBytes(
7012 DL, CanBeNull, /*CanBeFreed=*/nullptr);
7013 if (DerefBytes > 1 && isUIntN(BitWidth, DerefBytes)) {
7014 // The highest address the object can start is DerefBytes bytes before
7015 // the end (unsigned max value). If this value is not a multiple of the
7016 // alignment, the last possible start value is the next lowest multiple
7017 // of the alignment. Note: The computations below cannot overflow,
7018 // because if they would there's no possible start address for the
7019 // object.
7020 APInt MaxVal =
7021 APInt::getMaxValue(BitWidth) - APInt(BitWidth, DerefBytes);
7022 uint64_t Align = U->getValue()->getPointerAlignment(DL).value();
7023 uint64_t Rem = MaxVal.urem(Align);
7024 MaxVal -= APInt(BitWidth, Rem);
7025 APInt MinVal = APInt::getZero(BitWidth);
7026 if (llvm::isKnownNonZero(V, DL))
7027 MinVal = Align;
7028 ConservativeResult = ConservativeResult.intersectWith(
7029 ConstantRange::getNonEmpty(MinVal, MaxVal + 1), RangeType);
7030 }
7031 }
7032
7033 // A range of Phi is a subset of union of all ranges of its input.
7034 if (PHINode *Phi = dyn_cast<PHINode>(V)) {
7035 // SCEVExpander sometimes creates SCEVUnknowns that are secretly
7036 // AddRecs; return the range for the corresponding AddRec.
7037 if (auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V)))
7038 return getRangeRef(AR, SignHint, Depth + 1);
7039
7040 // Make sure that we do not run over cycled Phis.
7041 if (RangeRefPHIAllowedOperands(DT, Phi)) {
7042 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
7043
7044 for (const auto &Op : Phi->operands()) {
7045 auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
7046 RangeFromOps = RangeFromOps.unionWith(OpRange);
7047 // No point to continue if we already have a full set.
7048 if (RangeFromOps.isFullSet())
7049 break;
7050 }
7051 ConservativeResult =
7052 ConservativeResult.intersectWith(RangeFromOps, RangeType);
7053 }
7054 }
7055
7056 // vscale can't be equal to zero
7057 if (const auto *II = dyn_cast<IntrinsicInst>(V))
7058 if (II->getIntrinsicID() == Intrinsic::vscale) {
7059 ConstantRange Disallowed = APInt::getZero(BitWidth);
7060 ConservativeResult = ConservativeResult.difference(Disallowed);
7061 }
7062
7063 return setRange(U, SignHint, std::move(ConservativeResult));
7064 }
7065 case scCouldNotCompute:
7066 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
7067 }
7068
7069 return setRange(S, SignHint, std::move(ConservativeResult));
7070}
7071
7072// Given a StartRange, Step and MaxBECount for an expression compute a range of
7073// values that the expression can take. Initially, the expression has a value
7074// from StartRange and then is changed by Step up to MaxBECount times. Signed
7075// argument defines if we treat Step as signed or unsigned. The second return
7076// value indicates that no wrapping occurred.
7077static std::pair<ConstantRange, bool>
7079 const APInt &MaxBECount, bool Signed) {
7080 unsigned BitWidth = Step.getBitWidth();
7081 assert(BitWidth == StartRange.getBitWidth() &&
7082 BitWidth == MaxBECount.getBitWidth() && "mismatched bit widths");
7083 // If either Step or MaxBECount is 0, then the expression won't change, and we
7084 // just need to return the initial range.
7085 if (Step == 0 || MaxBECount == 0)
7086 return {StartRange, true};
7087
7088 // If we don't know anything about the initial value (i.e. StartRange is
7089 // FullRange), then we don't know anything about the final range either.
7090 // Return FullRange.
7091 if (StartRange.isFullSet())
7092 return {ConstantRange::getFull(BitWidth), false};
7093
7094 // If Step is signed and negative, then we use its absolute value, but we also
7095 // note that we're moving in the opposite direction.
7096 bool Descending = Signed && Step.isNegative();
7097
7098 if (Signed)
7099 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
7100 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
7101 // This equations hold true due to the well-defined wrap-around behavior of
7102 // APInt.
7103 Step = Step.abs();
7104
7105 // Check if Offset is more than full span of BitWidth. If it is, the
7106 // expression is guaranteed to overflow.
7107 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
7108 return {ConstantRange::getFull(BitWidth), false};
7109
7110 // Offset is by how much the expression can change. Checks above guarantee no
7111 // overflow here.
7112 APInt Offset = Step * MaxBECount;
7113
7114 // Minimum value of the final range will match the minimal value of StartRange
7115 // if the expression is increasing and will be decreased by Offset otherwise.
7116 // Maximum value of the final range will match the maximal value of StartRange
7117 // if the expression is decreasing and will be increased by Offset otherwise.
7118 APInt StartLower = StartRange.getLower();
7119 APInt StartUpper = StartRange.getUpper() - 1;
7120 bool Overflow;
7121 APInt MovedBoundary;
7122 if (Signed) {
7123 // This does not use sadd_ov, as we want to check overflow for a signed
7124 // start with an unsigned offset.
7125 if (Descending) {
7126 MovedBoundary = StartLower - std::move(Offset);
7127 Overflow = MovedBoundary.sgt(StartLower) || StartRange.isSignWrappedSet();
7128 } else {
7129 MovedBoundary = StartUpper + std::move(Offset);
7130 Overflow = MovedBoundary.slt(StartUpper) || StartRange.isSignWrappedSet();
7131 }
7132 } else {
7133 MovedBoundary = StartUpper.uadd_ov(std::move(Offset), Overflow);
7134 Overflow |= StartRange.isWrappedSet();
7135 }
7136
7137 // It's possible that the new minimum/maximum value will fall into the initial
7138 // range (due to wrap around). This means that the expression can take any
7139 // value in this bitwidth, and we have to return full range.
7140 if (StartRange.contains(MovedBoundary))
7141 return {ConstantRange::getFull(BitWidth), false};
7142
7143 APInt NewLower =
7144 Descending ? std::move(MovedBoundary) : std::move(StartLower);
7145 APInt NewUpper =
7146 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
7147 NewUpper += 1;
7148
7149 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
7150 return {ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)),
7151 !Overflow};
7152}
7153
7154std::pair<ConstantRange, SCEV::NoWrapFlags>
7155ScalarEvolution::getRangeForAffineAR(const SCEV *Start, const SCEV *Step,
7156 const APInt &MaxBECount) {
7157 assert(getTypeSizeInBits(Start->getType()) ==
7158 getTypeSizeInBits(Step->getType()) &&
7159 getTypeSizeInBits(Start->getType()) == MaxBECount.getBitWidth() &&
7160 "mismatched bit widths");
7161
7162 // First, consider step signed.
7163 ConstantRange StartSRange = getSignedRange(Start);
7164 ConstantRange StepSRange = getSignedRange(Step);
7165
7166 // If Step can be both positive and negative, we need to find ranges for the
7167 // maximum absolute step values in both directions and union them.
7168 auto [SR1, NSW1] = getRangeForAffineARHelper(
7169 StepSRange.getSignedMin(), StartSRange, MaxBECount, /*Signed=*/true);
7170 auto [SR2, NSW2] = getRangeForAffineARHelper(StepSRange.getSignedMax(),
7171 StartSRange, MaxBECount,
7172 /*Signed=*/true);
7173 ConstantRange SR = SR1.unionWith(SR2);
7174
7175 // Next, consider step unsigned.
7176 auto [UR, NUW] = getRangeForAffineARHelper(
7177 getUnsignedRangeMax(Step), getUnsignedRange(Start), MaxBECount,
7178 /*Signed=*/false);
7179
7181 if (NUW)
7183 if (NSW1 && NSW2)
7185
7186 // Finally, intersect signed and unsigned ranges.
7188}
7189
7190ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
7191 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
7192 ScalarEvolution::RangeSignHint SignHint) {
7193 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
7194 assert(AddRec->hasNoSelfWrap() &&
7195 "This only works for non-self-wrapping AddRecs!");
7196 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
7197 const SCEV *Step = AddRec->getStepRecurrence(*this);
7198 // Only deal with constant step to save compile time.
7199 if (!isa<SCEVConstant>(Step))
7200 return ConstantRange::getFull(BitWidth);
7201 // Let's make sure that we can prove that we do not self-wrap during
7202 // MaxBECount iterations. We need this because MaxBECount is a maximum
7203 // iteration count estimate, and we might infer nw from some exit for which we
7204 // do not know max exit count (or any other side reasoning).
7205 // TODO: Turn into assert at some point.
7206 if (getTypeSizeInBits(MaxBECount->getType()) >
7207 getTypeSizeInBits(AddRec->getType()))
7208 return ConstantRange::getFull(BitWidth);
7209 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
7210 const SCEV *RangeWidth = getMinusOne(AddRec->getType());
7211 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
7212 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
7213 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
7214 MaxItersWithoutWrap))
7215 return ConstantRange::getFull(BitWidth);
7216
7217 ICmpInst::Predicate LEPred =
7219 ICmpInst::Predicate GEPred =
7221 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7222
7223 // We know that there is no self-wrap. Let's take Start and End values and
7224 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7225 // the iteration. They either lie inside the range [Min(Start, End),
7226 // Max(Start, End)] or outside it:
7227 //
7228 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
7229 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
7230 //
7231 // No self wrap flag guarantees that the intermediate values cannot be BOTH
7232 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7233 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7234 // Start <= End and step is positive, or Start >= End and step is negative.
7235 const SCEV *Start = applyLoopGuards(AddRec->getStart(), AddRec->getLoop());
7236 ConstantRange StartRange = getRangeRef(Start, SignHint);
7237 ConstantRange EndRange = getRangeRef(End, SignHint);
7238 ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7239 // If they already cover full iteration space, we will know nothing useful
7240 // even if we prove what we want to prove.
7241 if (RangeBetween.isFullSet())
7242 return RangeBetween;
7243 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7244 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7245 : RangeBetween.isWrappedSet();
7246 if (IsWrappedSet)
7247 return ConstantRange::getFull(BitWidth);
7248
7249 if (isKnownPositive(Step) &&
7250 isKnownPredicateViaConstantRanges(LEPred, Start, End))
7251 return RangeBetween;
7252 if (isKnownNegative(Step) &&
7253 isKnownPredicateViaConstantRanges(GEPred, Start, End))
7254 return RangeBetween;
7255 return ConstantRange::getFull(BitWidth);
7256}
7257
7258ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7259 const SCEV *Step,
7260 const APInt &MaxBECount) {
7261 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7262 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7263
7264 unsigned BitWidth = MaxBECount.getBitWidth();
7265 assert(getTypeSizeInBits(Start->getType()) == BitWidth &&
7266 getTypeSizeInBits(Step->getType()) == BitWidth &&
7267 "mismatched bit widths");
7268
7269 struct SelectPattern {
7270 Value *Condition = nullptr;
7271 APInt TrueValue;
7272 APInt FalseValue;
7273
7274 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7275 const SCEV *S) {
7276 std::optional<unsigned> CastOp;
7277 APInt Offset(BitWidth, 0);
7278
7280 "Should be!");
7281
7282 // Peel off a constant offset. In the future we could consider being
7283 // smarter here and handle {Start+Step,+,Step} too.
7284 const APInt *Off;
7285 if (match(S, m_scev_Add(m_scev_APInt(Off), m_SCEV(S))))
7286 Offset = *Off;
7287
7288 // Peel off a cast operation
7289 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7290 CastOp = SCast->getSCEVType();
7291 S = SCast->getOperand();
7292 }
7293
7294 using namespace llvm::PatternMatch;
7295
7296 auto *SU = dyn_cast<SCEVUnknown>(S);
7297 const APInt *TrueVal, *FalseVal;
7298 if (!SU ||
7299 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7300 m_APInt(FalseVal)))) {
7301 Condition = nullptr;
7302 return;
7303 }
7304
7305 TrueValue = *TrueVal;
7306 FalseValue = *FalseVal;
7307
7308 // Re-apply the cast we peeled off earlier
7309 if (CastOp)
7310 switch (*CastOp) {
7311 default:
7312 llvm_unreachable("Unknown SCEV cast type!");
7313
7314 case scTruncate:
7315 TrueValue = TrueValue.trunc(BitWidth);
7316 FalseValue = FalseValue.trunc(BitWidth);
7317 break;
7318 case scZeroExtend:
7319 TrueValue = TrueValue.zext(BitWidth);
7320 FalseValue = FalseValue.zext(BitWidth);
7321 break;
7322 case scSignExtend:
7323 TrueValue = TrueValue.sext(BitWidth);
7324 FalseValue = FalseValue.sext(BitWidth);
7325 break;
7326 }
7327
7328 // Re-apply the constant offset we peeled off earlier
7329 TrueValue += Offset;
7330 FalseValue += Offset;
7331 }
7332
7333 bool isRecognized() { return Condition != nullptr; }
7334 };
7335
7336 SelectPattern StartPattern(*this, BitWidth, Start);
7337 if (!StartPattern.isRecognized())
7338 return ConstantRange::getFull(BitWidth);
7339
7340 SelectPattern StepPattern(*this, BitWidth, Step);
7341 if (!StepPattern.isRecognized())
7342 return ConstantRange::getFull(BitWidth);
7343
7344 if (StartPattern.Condition != StepPattern.Condition) {
7345 // We don't handle this case today; but we could, by considering four
7346 // possibilities below instead of two. I'm not sure if there are cases where
7347 // that will help over what getRange already does, though.
7348 return ConstantRange::getFull(BitWidth);
7349 }
7350
7351 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7352 // construct arbitrary general SCEV expressions here. This function is called
7353 // from deep in the call stack, and calling getSCEV (on a sext instruction,
7354 // say) can end up caching a suboptimal value.
7355
7356 // FIXME: without the explicit `this` receiver below, MSVC errors out with
7357 // C2352 and C2512 (otherwise it isn't needed).
7358
7359 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7360 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7361 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7362 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7363
7364 ConstantRange TrueRange =
7365 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount).first;
7366 ConstantRange FalseRange =
7367 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount).first;
7368
7369 return TrueRange.unionWith(FalseRange);
7370}
7371
7372SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7373 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
7374 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7375
7376 // Return early if there are no flags to propagate to the SCEV.
7378 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(BinOp);
7379 PDI && PDI->isDisjoint()) {
7381 } else {
7382 if (BinOp->hasNoUnsignedWrap())
7384 if (BinOp->hasNoSignedWrap())
7386 }
7387 if (Flags == SCEV::FlagAnyWrap)
7388 return SCEV::FlagAnyWrap;
7389
7390 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
7391}
7392
7393const Instruction *
7394ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7395 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7396 return &*AddRec->getLoop()->getHeader()->begin();
7397 if (auto *U = dyn_cast<SCEVUnknown>(S))
7398 if (auto *I = dyn_cast<Instruction>(U->getValue()))
7399 return I;
7400 return nullptr;
7401}
7402
7403const Instruction *ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops,
7404 bool &Precise) {
7405 Precise = true;
7406 // Do a bounded search of the def relation of the requested SCEVs.
7407 SmallPtrSet<const SCEV *, 16> Visited;
7408 SmallVector<SCEVUse> Worklist;
7409 auto pushOp = [&](const SCEV *S) {
7410 if (!Visited.insert(S).second)
7411 return;
7412 // Threshold of 30 here is arbitrary.
7413 if (Visited.size() > 30) {
7414 Precise = false;
7415 return;
7416 }
7417 Worklist.push_back(S);
7418 };
7419
7420 for (SCEVUse S : Ops)
7421 pushOp(S);
7422
7423 const Instruction *Bound = nullptr;
7424 while (!Worklist.empty()) {
7425 SCEVUse S = Worklist.pop_back_val();
7426 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7427 if (!Bound || DT.dominates(Bound, DefI))
7428 Bound = DefI;
7429 } else {
7430 for (SCEVUse Op : S->operands())
7431 pushOp(Op);
7432 }
7433 }
7434 return Bound ? Bound : &*F.getEntryBlock().begin();
7435}
7436
7437const Instruction *
7438ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops) {
7439 bool Discard;
7440 return getDefiningScopeBound(Ops, Discard);
7441}
7442
7443bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7444 const Instruction *B) {
7445 if (A->getParent() == B->getParent() &&
7447 B->getIterator()))
7448 return true;
7449
7450 auto *BLoop = LI.getLoopFor(B->getParent());
7451 if (BLoop && BLoop->getHeader() == B->getParent() &&
7452 BLoop->getLoopPreheader() == A->getParent() &&
7454 A->getParent()->end()) &&
7455 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7456 B->getIterator()))
7457 return true;
7458 return false;
7459}
7460
7462 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ true);
7463 visitAll(Op, PC);
7464 return PC.MaybePoison.empty();
7465}
7466
7467bool ScalarEvolution::isGuaranteedNotToCauseUB(const SCEV *Op) {
7468 return !SCEVExprContains(Op, [this](const SCEV *S) {
7469 const SCEV *Op1;
7470 bool M = match(S, m_scev_UDiv(m_SCEV(), m_SCEV(Op1)));
7471 // The UDiv may be UB if the divisor is poison or zero. Unless the divisor
7472 // is a non-zero constant, we have to assume the UDiv may be UB.
7473 return M && (!isKnownNonZero(Op1) || !isGuaranteedNotToBePoison(Op1));
7474 });
7475}
7476
7477bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7478 // Only proceed if we can prove that I does not yield poison.
7480 return false;
7481
7482 // At this point we know that if I is executed, then it does not wrap
7483 // according to at least one of NSW or NUW. If I is not executed, then we do
7484 // not know if the calculation that I represents would wrap. Multiple
7485 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7486 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7487 // derived from other instructions that map to the same SCEV. We cannot make
7488 // that guarantee for cases where I is not executed. So we need to find a
7489 // upper bound on the defining scope for the SCEV, and prove that I is
7490 // executed every time we enter that scope. When the bounding scope is a
7491 // loop (the common case), this is equivalent to proving I executes on every
7492 // iteration of that loop.
7493 SmallVector<SCEVUse> SCEVOps;
7494 for (const Use &Op : I->operands()) {
7495 // I could be an extractvalue from a call to an overflow intrinsic.
7496 // TODO: We can do better here in some cases.
7497 if (isSCEVable(Op->getType()))
7498 SCEVOps.push_back(getSCEV(Op));
7499 }
7500 auto *DefI = getDefiningScopeBound(SCEVOps);
7501 return isGuaranteedToTransferExecutionTo(DefI, I);
7502}
7503
7504bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7505 // If we know that \c I can never be poison period, then that's enough.
7506 if (isSCEVExprNeverPoison(I))
7507 return true;
7508
7509 // If the loop only has one exit, then we know that, if the loop is entered,
7510 // any instruction dominating that exit will be executed. If any such
7511 // instruction would result in UB, the addrec cannot be poison.
7512 //
7513 // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7514 // also handles uses outside the loop header (they just need to dominate the
7515 // single exit).
7516
7517 auto *ExitingBB = L->getExitingBlock();
7518 if (!ExitingBB || !loopHasNoAbnormalExits(L))
7519 return false;
7520
7521 SmallPtrSet<const Value *, 16> KnownPoison;
7523
7524 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
7525 // things that are known to be poison under that assumption go on the
7526 // Worklist.
7527 KnownPoison.insert(I);
7528 Worklist.push_back(I);
7529
7530 while (!Worklist.empty()) {
7531 const Instruction *Poison = Worklist.pop_back_val();
7532
7533 for (const Use &U : Poison->uses()) {
7534 const Instruction *PoisonUser = cast<Instruction>(U.getUser());
7535 if (mustTriggerUB(PoisonUser, KnownPoison) &&
7536 DT.dominates(PoisonUser->getParent(), ExitingBB))
7537 return true;
7538
7539 if (propagatesPoison(U) && L->contains(PoisonUser))
7540 if (KnownPoison.insert(PoisonUser).second)
7541 Worklist.push_back(PoisonUser);
7542 }
7543 }
7544
7545 return false;
7546}
7547
7548ScalarEvolution::LoopProperties
7549ScalarEvolution::getLoopProperties(const Loop *L) {
7550 using LoopProperties = ScalarEvolution::LoopProperties;
7551
7552 auto Itr = LoopPropertiesCache.find(L);
7553 if (Itr == LoopPropertiesCache.end()) {
7554 auto HasSideEffects = [](Instruction *I) {
7555 if (auto *SI = dyn_cast<StoreInst>(I))
7556 return !SI->isSimple();
7557
7558 if (I->mayThrow())
7559 return true;
7560
7561 // Non-volatile memset / memcpy do not count as side-effect for forward
7562 // progress.
7563 if (isa<MemIntrinsic>(I) && !I->isVolatile())
7564 return false;
7565
7566 return I->mayWriteToMemory();
7567 };
7568
7569 LoopProperties LP = {/* HasNoAbnormalExits */ true,
7570 /*HasNoSideEffects*/ true};
7571
7572 for (auto *BB : L->getBlocks())
7573 for (auto &I : *BB) {
7575 LP.HasNoAbnormalExits = false;
7576 if (HasSideEffects(&I))
7577 LP.HasNoSideEffects = false;
7578 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7579 break; // We're already as pessimistic as we can get.
7580 }
7581
7582 auto InsertPair = LoopPropertiesCache.insert({L, LP});
7583 assert(InsertPair.second && "We just checked!");
7584 Itr = InsertPair.first;
7585 }
7586
7587 return Itr->second;
7588}
7589
7591 // A mustprogress loop without side effects must be finite.
7592 // TODO: The check used here is very conservative. It's only *specific*
7593 // side effects which are well defined in infinite loops.
7594 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7595}
7596
7597const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7598 // Worklist item with a Value and a bool indicating whether all operands have
7599 // been visited already.
7602
7603 Stack.emplace_back(V, false);
7604 while (!Stack.empty()) {
7605 auto E = Stack.back();
7606 Value *CurV = E.getPointer();
7607
7608 if (getExistingSCEV(CurV)) {
7609 Stack.pop_back();
7610 continue;
7611 }
7612
7614 const SCEV *CreatedSCEV = nullptr;
7615 // If all operands have been visited already, create the SCEV.
7616 if (E.getInt()) {
7617 CreatedSCEV = createSCEV(CurV);
7618 } else {
7619 // Otherwise get the operands we need to create SCEV's for before creating
7620 // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7621 // just use it.
7622 CreatedSCEV = getOperandsToCreate(CurV, Ops);
7623 }
7624
7625 if (CreatedSCEV) {
7626 insertValueToMap(CurV, CreatedSCEV);
7627 Stack.pop_back();
7628 } else {
7629 Stack.back().setInt(true);
7630 // Queue its operands which need to be constructed.
7631 for (Value *Op : Ops)
7632 Stack.emplace_back(Op, false);
7633 }
7634 }
7635
7636 return getExistingSCEV(V);
7637}
7638
7639const SCEV *
7640ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7641 if (!isSCEVable(V->getType()))
7642 return getUnknown(V);
7643
7644 if (Instruction *I = dyn_cast<Instruction>(V)) {
7645 // Don't attempt to analyze instructions in blocks that aren't
7646 // reachable. Such instructions don't matter, and they aren't required
7647 // to obey basic rules for definitions dominating uses which this
7648 // analysis depends on.
7649 if (!DT.isReachableFromEntry(I->getParent()))
7650 return getUnknown(PoisonValue::get(V->getType()));
7651 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7652 return getConstant(CI);
7653 else if (isa<GlobalAlias>(V))
7654 return getUnknown(V);
7655 else if (!isa<ConstantExpr>(V))
7656 return getUnknown(V);
7657
7659 if (auto BO =
7661 bool IsConstArg = isa<ConstantInt>(BO->RHS);
7662 switch (BO->Opcode) {
7663 case Instruction::Add:
7664 case Instruction::Mul: {
7665 // For additions and multiplications, traverse add/mul chains for which we
7666 // can potentially create a single SCEV, to reduce the number of
7667 // get{Add,Mul}Expr calls.
7668 do {
7669 if (BO->Op) {
7670 if (BO->Op != V && getExistingSCEV(BO->Op)) {
7671 Ops.push_back(BO->Op);
7672 break;
7673 }
7674 }
7675 Ops.push_back(BO->RHS);
7676 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7678 if (!NewBO ||
7679 (BO->Opcode == Instruction::Add &&
7680 (NewBO->Opcode != Instruction::Add &&
7681 NewBO->Opcode != Instruction::Sub)) ||
7682 (BO->Opcode == Instruction::Mul &&
7683 NewBO->Opcode != Instruction::Mul)) {
7684 Ops.push_back(BO->LHS);
7685 break;
7686 }
7687 // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7688 // requires a SCEV for the LHS.
7689 if (BO->Op && (BO->IsNSW || BO->IsNUW)) {
7690 auto *I = dyn_cast<Instruction>(BO->Op);
7691 if (I && programUndefinedIfPoison(I)) {
7692 Ops.push_back(BO->LHS);
7693 break;
7694 }
7695 }
7696 BO = NewBO;
7697 } while (true);
7698 return nullptr;
7699 }
7700 case Instruction::Sub:
7701 case Instruction::UDiv:
7702 case Instruction::URem:
7703 break;
7704 case Instruction::AShr:
7705 case Instruction::Shl:
7706 case Instruction::Xor:
7707 if (!IsConstArg)
7708 return nullptr;
7709 break;
7710 case Instruction::And:
7711 case Instruction::Or:
7712 if (!IsConstArg && !BO->LHS->getType()->isIntegerTy(1))
7713 return nullptr;
7714 break;
7715 case Instruction::LShr:
7716 return getUnknown(V);
7717 default:
7718 llvm_unreachable("Unhandled binop");
7719 break;
7720 }
7721
7722 Ops.push_back(BO->LHS);
7723 Ops.push_back(BO->RHS);
7724 return nullptr;
7725 }
7726
7727 switch (U->getOpcode()) {
7728 case Instruction::Trunc:
7729 case Instruction::ZExt:
7730 case Instruction::SExt:
7731 case Instruction::PtrToAddr:
7732 case Instruction::PtrToInt:
7733 Ops.push_back(U->getOperand(0));
7734 return nullptr;
7735
7736 case Instruction::BitCast:
7737 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
7738 Ops.push_back(U->getOperand(0));
7739 return nullptr;
7740 }
7741 return getUnknown(V);
7742
7743 case Instruction::SDiv:
7744 case Instruction::SRem:
7745 Ops.push_back(U->getOperand(0));
7746 Ops.push_back(U->getOperand(1));
7747 return nullptr;
7748
7749 case Instruction::GetElementPtr:
7750 assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7751 "GEP source element type must be sized");
7752 llvm::append_range(Ops, U->operands());
7753 return nullptr;
7754
7755 case Instruction::IntToPtr:
7756 return getUnknown(V);
7757
7758 case Instruction::PHI:
7759 // getNodeForPHI has four ways to turn a PHI into a SCEV; retrieve the
7760 // relevant nodes for each of them.
7761 //
7762 // The first is just to call simplifyInstruction, and get something back
7763 // that isn't a PHI.
7764 if (Value *V = simplifyInstruction(
7765 cast<PHINode>(U),
7766 {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
7767 /*UseInstrInfo=*/true, /*CanUseUndef=*/false})) {
7768 assert(V);
7769 Ops.push_back(V);
7770 return nullptr;
7771 }
7772 // The second is createNodeForPHIWithIdenticalOperands: this looks for
7773 // operands which all perform the same operation, but haven't been
7774 // CSE'ed for whatever reason.
7775 if (BinaryOperator *BO = getCommonInstForPHI(cast<PHINode>(U))) {
7776 assert(BO);
7777 Ops.push_back(BO);
7778 return nullptr;
7779 }
7780 // The third is createNodeFromSelectLikePHI; this takes a PHI which
7781 // is equivalent to a select, and analyzes it like a select.
7782 {
7783 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
7785 assert(Cond);
7786 assert(LHS);
7787 assert(RHS);
7788 if (auto *CondICmp = dyn_cast<ICmpInst>(Cond)) {
7789 Ops.push_back(CondICmp->getOperand(0));
7790 Ops.push_back(CondICmp->getOperand(1));
7791 }
7792 Ops.push_back(Cond);
7793 Ops.push_back(LHS);
7794 Ops.push_back(RHS);
7795 return nullptr;
7796 }
7797 }
7798 // The fourth way is createAddRecFromPHI. It's complicated to handle here,
7799 // so just construct it recursively.
7800 //
7801 // In addition to getNodeForPHI, also construct nodes which might be needed
7802 // by getRangeRef.
7804 for (Value *V : cast<PHINode>(U)->operands())
7805 Ops.push_back(V);
7806 return nullptr;
7807 }
7808 return nullptr;
7809
7810 case Instruction::Select: {
7811 // Check if U is a select that can be simplified to a SCEVUnknown.
7812 auto CanSimplifyToUnknown = [this, U]() {
7813 if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
7814 return false;
7815
7816 auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
7817 if (!ICI)
7818 return false;
7819 Value *LHS = ICI->getOperand(0);
7820 Value *RHS = ICI->getOperand(1);
7821 if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7822 ICI->getPredicate() == CmpInst::ICMP_NE) {
7824 return true;
7825 } else if (getTypeSizeInBits(LHS->getType()) >
7826 getTypeSizeInBits(U->getType()))
7827 return true;
7828 return false;
7829 };
7830 if (CanSimplifyToUnknown())
7831 return getUnknown(U);
7832
7833 llvm::append_range(Ops, U->operands());
7834 return nullptr;
7835 break;
7836 }
7837 case Instruction::Call:
7838 case Instruction::Invoke:
7839 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7840 Ops.push_back(RV);
7841 return nullptr;
7842 }
7843
7844 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7845 switch (II->getIntrinsicID()) {
7846 case Intrinsic::abs:
7847 Ops.push_back(II->getArgOperand(0));
7848 return nullptr;
7849 case Intrinsic::umax:
7850 case Intrinsic::umin:
7851 case Intrinsic::smax:
7852 case Intrinsic::smin:
7853 case Intrinsic::usub_sat:
7854 case Intrinsic::uadd_sat:
7855 Ops.push_back(II->getArgOperand(0));
7856 Ops.push_back(II->getArgOperand(1));
7857 return nullptr;
7858 case Intrinsic::start_loop_iterations:
7859 case Intrinsic::annotation:
7860 case Intrinsic::ptr_annotation:
7861 Ops.push_back(II->getArgOperand(0));
7862 return nullptr;
7863 default:
7864 break;
7865 }
7866 }
7867 break;
7868 }
7869
7870 return nullptr;
7871}
7872
7873const SCEV *ScalarEvolution::createSCEV(Value *V) {
7874 if (!isSCEVable(V->getType()))
7875 return getUnknown(V);
7876
7877 if (Instruction *I = dyn_cast<Instruction>(V)) {
7878 // Don't attempt to analyze instructions in blocks that aren't
7879 // reachable. Such instructions don't matter, and they aren't required
7880 // to obey basic rules for definitions dominating uses which this
7881 // analysis depends on.
7882 if (!DT.isReachableFromEntry(I->getParent()))
7883 return getUnknown(PoisonValue::get(V->getType()));
7884 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7885 return getConstant(CI);
7886 else if (isa<GlobalAlias>(V))
7887 return getUnknown(V);
7888 else if (!isa<ConstantExpr>(V))
7889 return getUnknown(V);
7890
7891 const SCEV *LHS;
7892 const SCEV *RHS;
7893
7895 if (auto BO =
7897 switch (BO->Opcode) {
7898 case Instruction::Add: {
7899 // The simple thing to do would be to just call getSCEV on both operands
7900 // and call getAddExpr with the result. However if we're looking at a
7901 // bunch of things all added together, this can be quite inefficient,
7902 // because it leads to N-1 getAddExpr calls for N ultimate operands.
7903 // Instead, gather up all the operands and make a single getAddExpr call.
7904 // LLVM IR canonical form means we need only traverse the left operands.
7906 do {
7907 if (BO->Op) {
7908 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7909 AddOps.push_back(OpSCEV);
7910 break;
7911 }
7912
7913 // If a NUW or NSW flag can be applied to the SCEV for this
7914 // addition, then compute the SCEV for this addition by itself
7915 // with a separate call to getAddExpr. We need to do that
7916 // instead of pushing the operands of the addition onto AddOps,
7917 // since the flags are only known to apply to this particular
7918 // addition - they may not apply to other additions that can be
7919 // formed with operands from AddOps.
7920 const SCEV *RHS = getSCEV(BO->RHS);
7921 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7922 if (Flags != SCEV::FlagAnyWrap) {
7923 const SCEV *LHS = getSCEV(BO->LHS);
7924 if (BO->Opcode == Instruction::Sub)
7925 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7926 else
7927 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7928 break;
7929 }
7930 }
7931
7932 if (BO->Opcode == Instruction::Sub)
7933 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7934 else
7935 AddOps.push_back(getSCEV(BO->RHS));
7936
7937 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7939 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7940 NewBO->Opcode != Instruction::Sub)) {
7941 AddOps.push_back(getSCEV(BO->LHS));
7942 break;
7943 }
7944 BO = NewBO;
7945 } while (true);
7946
7947 return getAddExpr(AddOps);
7948 }
7949
7950 case Instruction::Mul: {
7952 do {
7953 if (BO->Op) {
7954 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7955 MulOps.push_back(OpSCEV);
7956 break;
7957 }
7958
7959 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7960 if (Flags != SCEV::FlagAnyWrap) {
7961 LHS = getSCEV(BO->LHS);
7962 RHS = getSCEV(BO->RHS);
7963 MulOps.push_back(getMulExpr(LHS, RHS, Flags));
7964 break;
7965 }
7966 }
7967
7968 MulOps.push_back(getSCEV(BO->RHS));
7969 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7971 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7972 MulOps.push_back(getSCEV(BO->LHS));
7973 break;
7974 }
7975 BO = NewBO;
7976 } while (true);
7977
7978 return getMulExpr(MulOps);
7979 }
7980 case Instruction::UDiv:
7981 LHS = getSCEV(BO->LHS);
7982 RHS = getSCEV(BO->RHS);
7983 return getUDivExpr(LHS, RHS);
7984 case Instruction::URem:
7985 LHS = getSCEV(BO->LHS);
7986 RHS = getSCEV(BO->RHS);
7987 return getURemExpr(LHS, RHS);
7988 case Instruction::Sub: {
7990 if (BO->Op)
7991 Flags = getNoWrapFlagsFromUB(BO->Op);
7992
7993 // Try to use ptrtoaddr for subtracts with at least one ptrtoint
7994 // operand. While we don't model ptrtoint directly in SCEV, the
7995 // difference between two pointer addresses is well-defined.
7996 Value *PtrLHS = nullptr, *PtrRHS = nullptr;
7997 bool HasPtrLHS = match(BO->LHS, m_PtrToInt(m_Value(PtrLHS)));
7998 bool HasPtrRHS = match(BO->RHS, m_PtrToInt(m_Value(PtrRHS)));
7999 if (HasPtrLHS || HasPtrRHS) {
8000 // Convert a ptrtoint operand (OrigOp) to ptrtoaddr of its pointer
8001 // PtrOp. When only one side is ptrtoint (BothPtr is false), skip
8002 // SCEVUnknown pointers since wrapping them in ptrtoaddr adds no
8003 // useful structure.
8004 auto GetOp = [&](bool HasPtr, Value *PtrOp, Value *OrigOp,
8005 bool BothPtr) -> const SCEV * {
8006 if (!HasPtr)
8007 return getSCEV(OrigOp);
8008 const SCEV *PtrSCEV = getSCEV(PtrOp);
8009 if (BothPtr || !isa<SCEVUnknown>(PtrSCEV)) {
8010 const SCEV *Addr = getPtrToAddrExpr(PtrSCEV);
8011 if (!isa<SCEVCouldNotCompute>(Addr) &&
8012 getTypeSizeInBits(OrigOp->getType()) <=
8013 getTypeSizeInBits(Addr->getType()))
8014 return getTruncateOrNoop(Addr, OrigOp->getType());
8015 }
8016 return getSCEV(OrigOp);
8017 };
8018 const SCEV *L = GetOp(HasPtrLHS, PtrLHS, BO->LHS, HasPtrRHS);
8019 const SCEV *R = GetOp(HasPtrRHS, PtrRHS, BO->RHS, HasPtrLHS);
8020 return getMinusSCEV(L, R, Flags);
8021 }
8022
8023 LHS = getSCEV(BO->LHS);
8024 RHS = getSCEV(BO->RHS);
8025 return getMinusSCEV(LHS, RHS, Flags);
8026 }
8027 case Instruction::And:
8028 // For an expression like x&255 that merely masks off the high bits,
8029 // use zext(trunc(x)) as the SCEV expression.
8030 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
8031 if (CI->isZero())
8032 return getSCEV(BO->RHS);
8033 if (CI->isMinusOne())
8034 return getSCEV(BO->LHS);
8035 const APInt &A = CI->getValue();
8036
8037 // Instcombine's ShrinkDemandedConstant may strip bits out of
8038 // constants, obscuring what would otherwise be a low-bits mask.
8039 // Use computeKnownBits to compute what ShrinkDemandedConstant
8040 // knew about to reconstruct a low-bits mask value.
8041 unsigned LZ = A.countl_zero();
8042 unsigned TZ = A.countr_zero();
8043 unsigned BitWidth = A.getBitWidth();
8044 KnownBits Known(BitWidth);
8045 computeKnownBits(BO->LHS, Known, getDataLayout(), &AC, nullptr, &DT);
8046
8047 APInt EffectiveMask =
8048 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
8049 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
8050 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
8051 const SCEV *LHS = getSCEV(BO->LHS);
8052 const SCEV *ShiftedLHS = nullptr;
8053 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
8054 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
8055 // For an expression like (x * 8) & 8, simplify the multiply.
8056 unsigned MulZeros = OpC->getAPInt().countr_zero();
8057 unsigned GCD = std::min(MulZeros, TZ);
8058 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
8060 MulOps.push_back(getConstant(OpC->getAPInt().ashr(GCD)));
8061 append_range(MulOps, LHSMul->operands().drop_front());
8062 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
8063 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
8064 }
8065 }
8066 if (!ShiftedLHS)
8067 ShiftedLHS = getUDivExpr(LHS, MulCount);
8068 return getMulExpr(
8070 getTruncateExpr(ShiftedLHS,
8071 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
8072 BO->LHS->getType()),
8073 MulCount);
8074 }
8075 }
8076 // Binary `and` is a bit-wise `umin`.
8077 if (BO->LHS->getType()->isIntegerTy(1)) {
8078 LHS = getSCEV(BO->LHS);
8079 RHS = getSCEV(BO->RHS);
8080 return getUMinExpr(LHS, RHS);
8081 }
8082 break;
8083
8084 case Instruction::Or:
8085 // Binary `or` is a bit-wise `umax`.
8086 if (BO->LHS->getType()->isIntegerTy(1)) {
8087 LHS = getSCEV(BO->LHS);
8088 RHS = getSCEV(BO->RHS);
8089 return getUMaxExpr(LHS, RHS);
8090 }
8091 break;
8092
8093 case Instruction::Xor:
8094 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
8095 // If the RHS of xor is -1, then this is a not operation.
8096 if (CI->isMinusOne())
8097 return getNotSCEV(getSCEV(BO->LHS));
8098
8099 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
8100 // This is a variant of the check for xor with -1, and it handles
8101 // the case where instcombine has trimmed non-demanded bits out
8102 // of an xor with -1.
8103 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
8104 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
8105 if (LBO->getOpcode() == Instruction::And &&
8106 LCI->getValue() == CI->getValue())
8107 if (const SCEVZeroExtendExpr *Z =
8109 Type *UTy = BO->LHS->getType();
8110 const SCEV *Z0 = Z->getOperand();
8111 Type *Z0Ty = Z0->getType();
8112 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
8113
8114 // If C is a low-bits mask, the zero extend is serving to
8115 // mask off the high bits. Complement the operand and
8116 // re-apply the zext.
8117 if (CI->getValue().isMask(Z0TySize))
8118 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
8119
8120 // If C is a single bit, it may be in the sign-bit position
8121 // before the zero-extend. In this case, represent the xor
8122 // using an add, which is equivalent, and re-apply the zext.
8123 APInt Trunc = CI->getValue().trunc(Z0TySize);
8124 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
8125 Trunc.isSignMask())
8126 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
8127 UTy);
8128 }
8129 }
8130 break;
8131
8132 case Instruction::Shl:
8133 // Turn shift left of a constant amount into a multiply.
8134 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
8135 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
8136
8137 // If the shift count is not less than the bitwidth, the result of
8138 // the shift is undefined. Don't try to analyze it, because the
8139 // resolution chosen here may differ from the resolution chosen in
8140 // other parts of the compiler.
8141 if (SA->getValue().uge(BitWidth))
8142 break;
8143
8144 // We can safely preserve the nuw flag in all cases. It's also safe to
8145 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
8146 // requires special handling. It can be preserved as long as we're not
8147 // left shifting by bitwidth - 1.
8148 auto Flags = SCEV::FlagAnyWrap;
8149 if (BO->Op) {
8150 auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
8151 if (any(MulFlags & SCEV::FlagNSW) &&
8152 (any(MulFlags & SCEV::FlagNUW) ||
8153 SA->getValue().ult(BitWidth - 1)))
8155 if (any(MulFlags & SCEV::FlagNUW))
8157 }
8158
8159 ConstantInt *X = ConstantInt::get(
8160 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
8161 return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
8162 }
8163 break;
8164
8165 case Instruction::AShr:
8166 // AShr X, C, where C is a constant.
8167 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
8168 if (!CI)
8169 break;
8170
8171 Type *OuterTy = BO->LHS->getType();
8173 // If the shift count is not less than the bitwidth, the result of
8174 // the shift is undefined. Don't try to analyze it, because the
8175 // resolution chosen here may differ from the resolution chosen in
8176 // other parts of the compiler.
8177 if (CI->getValue().uge(BitWidth))
8178 break;
8179
8180 if (CI->isZero())
8181 return getSCEV(BO->LHS); // shift by zero --> noop
8182
8183 uint64_t AShrAmt = CI->getZExtValue();
8184 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
8185
8186 Operator *L = dyn_cast<Operator>(BO->LHS);
8187 const SCEV *AddTruncateExpr = nullptr;
8188 ConstantInt *ShlAmtCI = nullptr;
8189 const SCEV *AddConstant = nullptr;
8190
8191 if (L && L->getOpcode() == Instruction::Add) {
8192 // X = Shl A, n
8193 // Y = Add X, c
8194 // Z = AShr Y, m
8195 // n, c and m are constants.
8196
8197 Operator *LShift = dyn_cast<Operator>(L->getOperand(0));
8198 ConstantInt *AddOperandCI = dyn_cast<ConstantInt>(L->getOperand(1));
8199 if (LShift && LShift->getOpcode() == Instruction::Shl) {
8200 if (AddOperandCI) {
8201 const SCEV *ShlOp0SCEV = getSCEV(LShift->getOperand(0));
8202 ShlAmtCI = dyn_cast<ConstantInt>(LShift->getOperand(1));
8203 // since we truncate to TruncTy, the AddConstant should be of the
8204 // same type, so create a new Constant with type same as TruncTy.
8205 // Also, the Add constant should be shifted right by AShr amount.
8206 APInt AddOperand = AddOperandCI->getValue().ashr(AShrAmt);
8207 AddConstant = getConstant(AddOperand.trunc(BitWidth - AShrAmt));
8208 // we model the expression as sext(add(trunc(A), c << n)), since the
8209 // sext(trunc) part is already handled below, we create a
8210 // AddExpr(TruncExp) which will be used later.
8211 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8212 }
8213 }
8214 } else if (L && L->getOpcode() == Instruction::Shl) {
8215 // X = Shl A, n
8216 // Y = AShr X, m
8217 // Both n and m are constant.
8218
8219 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
8220 ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
8221 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8222 }
8223
8224 if (AddTruncateExpr && ShlAmtCI) {
8225 // We can merge the two given cases into a single SCEV statement,
8226 // incase n = m, the mul expression will be 2^0, so it gets resolved to
8227 // a simpler case. The following code handles the two cases:
8228 //
8229 // 1) For a two-shift sext-inreg, i.e. n = m,
8230 // use sext(trunc(x)) as the SCEV expression.
8231 //
8232 // 2) When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
8233 // expression. We already checked that ShlAmt < BitWidth, so
8234 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
8235 // ShlAmt - AShrAmt < Amt.
8236 const APInt &ShlAmt = ShlAmtCI->getValue();
8237 if (ShlAmt.ult(BitWidth) && ShlAmt.uge(AShrAmt)) {
8238 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
8239 ShlAmtCI->getZExtValue() - AShrAmt);
8240 const SCEV *CompositeExpr =
8241 getMulExpr(AddTruncateExpr, getConstant(Mul));
8242 if (L->getOpcode() != Instruction::Shl)
8243 CompositeExpr = getAddExpr(CompositeExpr, AddConstant);
8244
8245 return getSignExtendExpr(CompositeExpr, OuterTy);
8246 }
8247 }
8248 break;
8249 }
8250 }
8251
8252 switch (U->getOpcode()) {
8253 case Instruction::Trunc:
8254 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
8255
8256 case Instruction::ZExt:
8257 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8258
8259 case Instruction::SExt:
8260 if (auto BO = MatchBinaryOp(U->getOperand(0), getDataLayout(), AC, DT,
8262 // The NSW flag of a subtract does not always survive the conversion to
8263 // A + (-1)*B. By pushing sign extension onto its operands we are much
8264 // more likely to preserve NSW and allow later AddRec optimisations.
8265 //
8266 // NOTE: This is effectively duplicating this logic from getSignExtend:
8267 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
8268 // but by that point the NSW information has potentially been lost.
8269 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
8270 Type *Ty = U->getType();
8271 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
8272 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
8273 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
8274 }
8275 }
8276 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8277
8278 case Instruction::BitCast:
8279 // BitCasts are no-op casts so we just eliminate the cast.
8280 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
8281 return getSCEV(U->getOperand(0));
8282 break;
8283
8284 case Instruction::PtrToAddr: {
8285 const SCEV *IntOp = getPtrToAddrExpr(getSCEV(U->getOperand(0)));
8286 if (isa<SCEVCouldNotCompute>(IntOp))
8287 return getUnknown(V);
8288 return IntOp;
8289 }
8290
8291 case Instruction::PtrToInt: {
8292 // Keep ptrtoint as SCEVUnknown, except when the pointer operand has SCEV
8293 // structure (e.g. a pointer add-rec or an offset from a known base). In
8294 // that case model it via ptrtoaddr to preserve the integer structure
8295 // (induction, constant folding). A bare SCEVUnknown pointer gains no
8296 // structure from wrapping it in ptrtoaddr, so leave it opaque.
8297 const SCEV *PtrSCEV = getSCEV(U->getOperand(0));
8298 if (!isa<SCEVUnknown>(PtrSCEV)) {
8299 const SCEV *Addr = getPtrToAddrExpr(PtrSCEV);
8300 if (!isa<SCEVCouldNotCompute>(Addr) &&
8301 getTypeSizeInBits(V->getType()) <= getTypeSizeInBits(Addr->getType()))
8302 return getTruncateOrNoop(Addr, V->getType());
8303 }
8304 return getUnknown(V);
8305 }
8306 case Instruction::IntToPtr:
8307 // Just don't deal with inttoptr casts.
8308 return getUnknown(V);
8309
8310 case Instruction::SDiv:
8311 // If both operands are non-negative, this is just an udiv.
8312 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8313 isKnownNonNegative(getSCEV(U->getOperand(1))))
8314 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8315 break;
8316
8317 case Instruction::SRem:
8318 // If both operands are non-negative, this is just an urem.
8319 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8320 isKnownNonNegative(getSCEV(U->getOperand(1))))
8321 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8322 break;
8323
8324 case Instruction::GetElementPtr:
8325 return createNodeForGEP(cast<GEPOperator>(U));
8326
8327 case Instruction::PHI:
8328 return createNodeForPHI(cast<PHINode>(U));
8329
8330 case Instruction::Select:
8331 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
8332 U->getOperand(2));
8333
8334 case Instruction::Call:
8335 case Instruction::Invoke:
8336 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
8337 return getSCEV(RV);
8338
8339 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
8340 switch (II->getIntrinsicID()) {
8341 case Intrinsic::abs:
8342 return getAbsExpr(
8343 getSCEV(II->getArgOperand(0)),
8344 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
8345 case Intrinsic::umax:
8346 LHS = getSCEV(II->getArgOperand(0));
8347 RHS = getSCEV(II->getArgOperand(1));
8348 return getUMaxExpr(LHS, RHS);
8349 case Intrinsic::umin:
8350 LHS = getSCEV(II->getArgOperand(0));
8351 RHS = getSCEV(II->getArgOperand(1));
8352 return getUMinExpr(LHS, RHS);
8353 case Intrinsic::smax:
8354 LHS = getSCEV(II->getArgOperand(0));
8355 RHS = getSCEV(II->getArgOperand(1));
8356 return getSMaxExpr(LHS, RHS);
8357 case Intrinsic::smin:
8358 LHS = getSCEV(II->getArgOperand(0));
8359 RHS = getSCEV(II->getArgOperand(1));
8360 return getSMinExpr(LHS, RHS);
8361 case Intrinsic::usub_sat: {
8362 const SCEV *X = getSCEV(II->getArgOperand(0));
8363 const SCEV *Y = getSCEV(II->getArgOperand(1));
8364 const SCEV *ClampedY = getUMinExpr(X, Y);
8365 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
8366 }
8367 case Intrinsic::uadd_sat: {
8368 const SCEV *X = getSCEV(II->getArgOperand(0));
8369 const SCEV *Y = getSCEV(II->getArgOperand(1));
8370 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
8371 return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
8372 }
8373 case Intrinsic::start_loop_iterations:
8374 case Intrinsic::annotation:
8375 case Intrinsic::ptr_annotation:
8376 // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8377 // just eqivalent to the first operand for SCEV purposes.
8378 return getSCEV(II->getArgOperand(0));
8379 case Intrinsic::vscale:
8380 return getVScale(II->getType());
8381 default:
8382 break;
8383 }
8384 }
8385 break;
8386 }
8387
8388 return getUnknown(V);
8389}
8390
8391//===----------------------------------------------------------------------===//
8392// Iteration Count Computation Code
8393//
8394
8396 if (isa<SCEVCouldNotCompute>(ExitCount))
8397 return getCouldNotCompute();
8398
8399 auto *ExitCountType = ExitCount->getType();
8400 assert(ExitCountType->isIntegerTy());
8401 auto *EvalTy = Type::getIntNTy(ExitCountType->getContext(),
8402 1 + ExitCountType->getScalarSizeInBits());
8403 return getTripCountFromExitCount(ExitCount, EvalTy, nullptr);
8404}
8405
8407 Type *EvalTy,
8408 const Loop *L) {
8409 if (isa<SCEVCouldNotCompute>(ExitCount))
8410 return getCouldNotCompute();
8411
8412 unsigned ExitCountSize = getTypeSizeInBits(ExitCount->getType());
8413 unsigned EvalSize = EvalTy->getPrimitiveSizeInBits();
8414
8415 auto CanAddOneWithoutOverflow = [&]() {
8416 ConstantRange ExitCountRange =
8417 getRangeRef(ExitCount, RangeSignHint::HINT_RANGE_UNSIGNED);
8418 if (!ExitCountRange.contains(APInt::getMaxValue(ExitCountSize)))
8419 return true;
8420
8421 return L && isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
8422 getMinusOne(ExitCount->getType()));
8423 };
8424
8425 // If we need to zero extend the backedge count, check if we can add one to
8426 // it prior to zero extending without overflow. Provided this is safe, it
8427 // allows better simplification of the +1.
8428 if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8429 return getZeroExtendExpr(
8430 getAddExpr(ExitCount, getOne(ExitCount->getType())), EvalTy);
8431
8432 // Get the total trip count from the count by adding 1. This may wrap.
8433 return getAddExpr(getTruncateOrZeroExtend(ExitCount, EvalTy), getOne(EvalTy));
8434}
8435
8436static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8437 if (!ExitCount)
8438 return 0;
8439
8440 ConstantInt *ExitConst = ExitCount->getValue();
8441
8442 // Guard against huge trip counts.
8443 if (ExitConst->getValue().getActiveBits() > 32)
8444 return 0;
8445
8446 // In case of integer overflow, this returns 0, which is correct.
8447 return ((unsigned)ExitConst->getZExtValue()) + 1;
8448}
8449
8451 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
8452 return getConstantTripCount(ExitCount);
8453}
8454
8455unsigned
8457 const BasicBlock *ExitingBlock) {
8458 assert(ExitingBlock && "Must pass a non-null exiting block!");
8459 assert(L->isLoopExiting(ExitingBlock) &&
8460 "Exiting block must actually branch out of the loop!");
8461 const SCEVConstant *ExitCount =
8462 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
8463 return getConstantTripCount(ExitCount);
8464}
8465
8467 const Loop *L, SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8468
8469 const auto *MaxExitCount =
8470 Predicates ? getPredicatedConstantMaxBackedgeTakenCount(L, *Predicates)
8472 return getConstantTripCount(dyn_cast<SCEVConstant>(MaxExitCount));
8473}
8474
8476 SmallVector<BasicBlock *, 8> ExitingBlocks;
8477 L->getExitingBlocks(ExitingBlocks);
8478
8479 std::optional<unsigned> Res;
8480 for (auto *ExitingBB : ExitingBlocks) {
8481 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
8482 if (!Res)
8483 Res = Multiple;
8484 Res = std::gcd(*Res, Multiple);
8485 }
8486 return Res.value_or(1);
8487}
8488
8490 const SCEV *ExitCount) {
8491 if (isa<SCEVCouldNotCompute>(ExitCount))
8492 return 1;
8493
8494 // Get the trip count
8495 const SCEV *TCExpr = getTripCountFromExitCount(applyLoopGuards(ExitCount, L));
8496
8497 APInt Multiple = getNonZeroConstantMultiple(TCExpr);
8498 // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8499 // the greatest power of 2 divisor less than 2^32.
8500 return Multiple.getActiveBits() > 32
8501 ? 1U << std::min(31U, Multiple.countTrailingZeros())
8502 : (unsigned)Multiple.getZExtValue();
8503}
8504
8505/// Returns the largest constant divisor of the trip count of this loop as a
8506/// normal unsigned value, if possible. This means that the actual trip count is
8507/// always a multiple of the returned value (don't forget the trip count could
8508/// very well be zero as well!).
8509///
8510/// Returns 1 if the trip count is unknown or not guaranteed to be the
8511/// multiple of a constant (which is also the case if the trip count is simply
8512/// constant, use getSmallConstantTripCount for that case), Will also return 1
8513/// if the trip count is very large (>= 2^32).
8514///
8515/// As explained in the comments for getSmallConstantTripCount, this assumes
8516/// that control exits the loop via ExitingBlock.
8517unsigned
8519 const BasicBlock *ExitingBlock) {
8520 assert(ExitingBlock && "Must pass a non-null exiting block!");
8521 assert(L->isLoopExiting(ExitingBlock) &&
8522 "Exiting block must actually branch out of the loop!");
8523 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8524 return getSmallConstantTripMultiple(L, ExitCount);
8525}
8526
8528 const BasicBlock *ExitingBlock,
8529 ExitCountKind Kind) {
8530 switch (Kind) {
8531 case Exact:
8532 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8533 case SymbolicMaximum:
8534 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8535 case ConstantMaximum:
8536 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8537 };
8538 llvm_unreachable("Invalid ExitCountKind!");
8539}
8540
8542 const Loop *L, const BasicBlock *ExitingBlock,
8544 switch (Kind) {
8545 case Exact:
8546 return getPredicatedBackedgeTakenInfo(L).getExact(ExitingBlock, this,
8547 Predicates);
8548 case SymbolicMaximum:
8549 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this,
8550 Predicates);
8551 case ConstantMaximum:
8552 return getPredicatedBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this,
8553 Predicates);
8554 };
8555 llvm_unreachable("Invalid ExitCountKind!");
8556}
8557
8560 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8561}
8562
8564 ExitCountKind Kind) {
8565 switch (Kind) {
8566 case Exact:
8567 return getBackedgeTakenInfo(L).getExact(L, this);
8568 case ConstantMaximum:
8569 return getBackedgeTakenInfo(L).getConstantMax(this);
8570 case SymbolicMaximum:
8571 return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8572 };
8573 llvm_unreachable("Invalid ExitCountKind!");
8574}
8575
8578 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(L, this, &Preds);
8579}
8580
8583 return getPredicatedBackedgeTakenInfo(L).getConstantMax(this, &Preds);
8584}
8585
8587 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8588}
8589
8590/// Push PHI nodes in the header of the given loop onto the given Worklist.
8591static void PushLoopPHIs(const Loop *L,
8594 BasicBlock *Header = L->getHeader();
8595
8596 // Push all Loop-header PHIs onto the Worklist stack.
8597 for (PHINode &PN : Header->phis())
8598 if (Visited.insert(&PN).second)
8599 Worklist.push_back(&PN);
8600}
8601
8602ScalarEvolution::BackedgeTakenInfo &
8603ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8604 auto &BTI = getBackedgeTakenInfo(L);
8605 if (BTI.hasFullInfo())
8606 return BTI;
8607
8608 auto Pair = PredicatedBackedgeTakenCounts.try_emplace(L);
8609
8610 if (!Pair.second)
8611 return Pair.first->second;
8612
8613 BackedgeTakenInfo Result =
8614 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8615
8616 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8617}
8618
8619ScalarEvolution::BackedgeTakenInfo &
8620ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8621 // Initially insert an invalid entry for this loop. If the insertion
8622 // succeeds, proceed to actually compute a backedge-taken count and
8623 // update the value. The temporary CouldNotCompute value tells SCEV
8624 // code elsewhere that it shouldn't attempt to request a new
8625 // backedge-taken count, which could result in infinite recursion.
8626 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8627 BackedgeTakenCounts.try_emplace(L);
8628 if (!Pair.second)
8629 return Pair.first->second;
8630
8631 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8632 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8633 // must be cleared in this scope.
8634 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8635
8636 // Now that we know more about the trip count for this loop, forget any
8637 // existing SCEV values for PHI nodes in this loop since they are only
8638 // conservative estimates made without the benefit of trip count
8639 // information. This invalidation is not necessary for correctness, and is
8640 // only done to produce more precise results.
8641 if (Result.hasAnyInfo()) {
8642 // Invalidate any expression using an addrec in this loop.
8643 SmallVector<SCEVUse, 8> ToForget;
8644 auto LoopUsersIt = LoopUsers.find(L);
8645 if (LoopUsersIt != LoopUsers.end())
8646 append_range(ToForget, LoopUsersIt->second);
8647 forgetMemoizedResults(ToForget);
8648
8649 // Invalidate constant-evolved loop header phis.
8650 for (PHINode &PN : L->getHeader()->phis())
8651 ConstantEvolutionLoopExitValue.erase(&PN);
8652 }
8653
8654 // Re-lookup the insert position, since the call to
8655 // computeBackedgeTakenCount above could result in a
8656 // recusive call to getBackedgeTakenInfo (on a different
8657 // loop), which would invalidate the iterator computed
8658 // earlier.
8659 return BackedgeTakenCounts.find(L)->second = std::move(Result);
8660}
8661
8663 // This method is intended to forget all info about loops. It should
8664 // invalidate caches as if the following happened:
8665 // - The trip counts of all loops have changed arbitrarily
8666 // - Every llvm::Value has been updated in place to produce a different
8667 // result.
8668 BackedgeTakenCounts.clear();
8669 PredicatedBackedgeTakenCounts.clear();
8670 BECountUsers.clear();
8671 LoopPropertiesCache.clear();
8672 ConstantEvolutionLoopExitValue.clear();
8673 ValueExprMap.clear();
8674 ValuesAtScopes.clear();
8675 ValuesAtScopesUsers.clear();
8676 LoopDispositions.clear();
8677 BlockDispositions.clear();
8678 UnsignedRanges.clear();
8679 SignedRanges.clear();
8680 ExprValueMap.clear();
8681 HasRecMap.clear();
8682 ConstantMultipleCache.clear();
8683 PredicatedSCEVRewrites.clear();
8684 FoldCache.clear();
8685 FoldCacheUser.clear();
8686}
8687void ScalarEvolution::visitAndClearUsers(
8690 SmallVectorImpl<SCEVUse> &ToForget) {
8691 while (!Worklist.empty()) {
8692 Instruction *I = Worklist.pop_back_val();
8693 if (!isSCEVable(I->getType()) && !isa<WithOverflowInst>(I))
8694 continue;
8695
8697 ValueExprMap.find_as(static_cast<Value *>(I));
8698 if (It != ValueExprMap.end()) {
8699 ToForget.push_back(It->second);
8700 eraseValueFromMap(It->first);
8701 if (PHINode *PN = dyn_cast<PHINode>(I))
8702 ConstantEvolutionLoopExitValue.erase(PN);
8703 }
8704
8705 PushDefUseChildren(I, Worklist, Visited);
8706 }
8707}
8708
8710 SmallVector<const Loop *, 16> LoopWorklist(1, L);
8713 SmallVector<SCEVUse, 16> ToForget;
8714
8715 // Iterate over all the loops and sub-loops to drop SCEV information.
8716 while (!LoopWorklist.empty()) {
8717 auto *CurrL = LoopWorklist.pop_back_val();
8718
8719 // Drop any stored trip count value.
8720 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8721 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8722
8723 // Drop information about predicated SCEV rewrites for this loop.
8724 PredicatedSCEVRewrites.remove_if(
8725 [&](const auto &Entry) { return Entry.first.second == CurrL; });
8726
8727 auto LoopUsersItr = LoopUsers.find(CurrL);
8728 if (LoopUsersItr != LoopUsers.end())
8729 llvm::append_range(ToForget, LoopUsersItr->second);
8730
8731 // Drop information about expressions based on loop-header PHIs.
8732 PushLoopPHIs(CurrL, Worklist, Visited);
8733 visitAndClearUsers(Worklist, Visited, ToForget);
8734
8735 LoopPropertiesCache.erase(CurrL);
8736 // Forget all contained loops too, to avoid dangling entries in the
8737 // ValuesAtScopes map.
8738 LoopWorklist.append(CurrL->begin(), CurrL->end());
8739 }
8740 forgetMemoizedResults(ToForget);
8741}
8742
8744 forgetLoop(L->getOutermostLoop());
8745}
8746
8749 if (!I) return;
8750
8751 // Drop information about expressions based on loop-header PHIs.
8754 SmallVector<SCEVUse, 8> ToForget;
8755 Worklist.push_back(I);
8756 Visited.insert(I);
8757 visitAndClearUsers(Worklist, Visited, ToForget);
8758
8759 forgetMemoizedResults(ToForget);
8760}
8761
8763 // If SCEV looked through a trivial LCSSA phi node, we might have SCEV's
8764 // directly using a SCEVUnknown/SCEVAddRec defined in the loop. After an
8765 // extra predecessor is added, this is no longer valid. Find all Unknowns and
8766 // AddRecs defined in the loop and invalidate any SCEV's making use of them.
8767 auto InvalidateValue = [&](Value *Val) {
8768 if (!isSCEVable(Val->getType()))
8769 return;
8770 if (const SCEV *S = getExistingSCEV(Val)) {
8771 struct InvalidationRootCollector {
8772 Loop *L;
8774
8775 InvalidationRootCollector(Loop *L) : L(L) {}
8776
8777 bool follow(const SCEV *S) {
8778 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
8779 if (auto *I = dyn_cast<Instruction>(SU->getValue()))
8780 if (L->contains(I))
8781 Roots.push_back(S);
8782 } else if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
8783 if (L->contains(AddRec->getLoop()))
8784 Roots.push_back(S);
8785 }
8786 return true;
8787 }
8788 bool isDone() const { return false; }
8789 };
8790
8791 InvalidationRootCollector C(L);
8792 visitAll(S, C);
8793 forgetMemoizedResults(C.Roots);
8794 }
8795 };
8796
8797 InvalidateValue(V);
8798
8799 // If V has a non-SCEV-able type (e.g. {i64, i1} from a with.overflow
8800 // intrinsic), its users (e.g. extractvalue) may have stale SCEV
8801 // expressions referencing loop-internal values.
8802 if (!isSCEVable(V->getType()) && any_of(V->incoming_values(), [](Value *Inc) {
8803 return isa<WithOverflowInst>(Inc);
8804 }))
8805 for (User *U : V->users())
8806 InvalidateValue(U);
8807 // Also perform the normal invalidation.
8808 forgetValue(V);
8809}
8810
8811void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8812
8814 // Unless a specific value is passed to invalidation, completely clear both
8815 // caches.
8816 if (!V) {
8817 BlockDispositions.clear();
8818 LoopDispositions.clear();
8819 return;
8820 }
8821
8822 if (!isSCEVable(V->getType()))
8823 return;
8824
8825 const SCEV *S = getExistingSCEV(V);
8826 if (!S)
8827 return;
8828
8829 // Invalidate the block and loop dispositions cached for S. Dispositions of
8830 // S's users may change if S's disposition changes (i.e. a user may change to
8831 // loop-invariant, if S changes to loop invariant), so also invalidate
8832 // dispositions of S's users recursively.
8833 SmallVector<SCEVUse, 8> Worklist = {S};
8835 while (!Worklist.empty()) {
8836 const SCEV *Curr = Worklist.pop_back_val();
8837 bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8838 bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8839 if (!LoopDispoRemoved && !BlockDispoRemoved)
8840 continue;
8841 auto Users = SCEVUsers.find(Curr);
8842 if (Users != SCEVUsers.end())
8843 for (const auto *User : Users->second)
8844 if (Seen.insert(User).second)
8845 Worklist.push_back(User);
8846 }
8847}
8848
8849/// Get the exact loop backedge taken count considering all loop exits. A
8850/// computable result can only be returned for loops with all exiting blocks
8851/// dominating the latch. howFarToZero assumes that the limit of each loop test
8852/// is never skipped. This is a valid assumption as long as the loop exits via
8853/// that test. For precise results, it is the caller's responsibility to specify
8854/// the relevant loop exiting block using getExact(ExitingBlock, SE).
8855const SCEV *ScalarEvolution::BackedgeTakenInfo::getExact(
8856 const Loop *L, ScalarEvolution *SE,
8858 // If any exits were not computable, the loop is not computable.
8859 if (!isComplete() || ExitNotTaken.empty())
8860 return SE->getCouldNotCompute();
8861
8862 const BasicBlock *Latch = L->getLoopLatch();
8863 // All exiting blocks we have collected must dominate the only backedge.
8864 if (!Latch)
8865 return SE->getCouldNotCompute();
8866
8867 // All exiting blocks we have gathered dominate loop's latch, so exact trip
8868 // count is simply a minimum out of all these calculated exit counts.
8870 for (const auto &ENT : ExitNotTaken) {
8871 const SCEV *BECount = ENT.ExactNotTaken;
8872 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8873 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8874 "We should only have known counts for exiting blocks that dominate "
8875 "latch!");
8876
8877 Ops.push_back(BECount);
8878
8879 if (Preds)
8880 append_range(*Preds, ENT.Predicates);
8881
8882 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8883 "Predicate should be always true!");
8884 }
8885
8886 // If an earlier exit exits on the first iteration (exit count zero), then
8887 // a later poison exit count should not propagate into the result. This are
8888 // exactly the semantics provided by umin_seq.
8889 return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8890}
8891
8892const ScalarEvolution::ExitNotTakenInfo *
8893ScalarEvolution::BackedgeTakenInfo::getExitNotTaken(
8894 const BasicBlock *ExitingBlock,
8895 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8896 for (const auto &ENT : ExitNotTaken)
8897 if (ENT.ExitingBlock == ExitingBlock) {
8898 if (ENT.hasAlwaysTruePredicate())
8899 return &ENT;
8900 else if (Predicates) {
8901 append_range(*Predicates, ENT.Predicates);
8902 return &ENT;
8903 }
8904 }
8905
8906 return nullptr;
8907}
8908
8909/// getConstantMax - Get the constant max backedge taken count for the loop.
8910const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8911 ScalarEvolution *SE,
8912 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8913 if (!getConstantMax())
8914 return SE->getCouldNotCompute();
8915
8916 for (const auto &ENT : ExitNotTaken)
8917 if (!ENT.hasAlwaysTruePredicate()) {
8918 if (!Predicates)
8919 return SE->getCouldNotCompute();
8920 append_range(*Predicates, ENT.Predicates);
8921 }
8922
8923 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8924 isa<SCEVConstant>(getConstantMax())) &&
8925 "No point in having a non-constant max backedge taken count!");
8926 return getConstantMax();
8927}
8928
8929const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8930 const Loop *L, ScalarEvolution *SE,
8931 SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8932 if (!SymbolicMax) {
8933 // Form an expression for the maximum exit count possible for this loop. We
8934 // merge the max and exact information to approximate a version of
8935 // getConstantMaxBackedgeTakenCount which isn't restricted to just
8936 // constants.
8937 SmallVector<SCEVUse, 4> ExitCounts;
8938
8939 for (const auto &ENT : ExitNotTaken) {
8940 const SCEV *ExitCount = ENT.SymbolicMaxNotTaken;
8941 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
8942 assert(SE->DT.dominates(ENT.ExitingBlock, L->getLoopLatch()) &&
8943 "We should only have known counts for exiting blocks that "
8944 "dominate latch!");
8945 ExitCounts.push_back(ExitCount);
8946 if (Predicates)
8947 append_range(*Predicates, ENT.Predicates);
8948
8949 assert((Predicates || ENT.hasAlwaysTruePredicate()) &&
8950 "Predicate should be always true!");
8951 }
8952 }
8953 if (ExitCounts.empty())
8954 SymbolicMax = SE->getCouldNotCompute();
8955 else
8956 SymbolicMax =
8957 SE->getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
8958 }
8959 return SymbolicMax;
8960}
8961
8962bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8963 ScalarEvolution *SE) const {
8964 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8965 return !ENT.hasAlwaysTruePredicate();
8966 };
8967 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8968}
8969
8972
8974 const SCEV *E, const SCEV *ConstantMaxNotTaken,
8975 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8979 // If we prove the max count is zero, so is the symbolic bound. This happens
8980 // in practice due to differences in a) how context sensitive we've chosen
8981 // to be and b) how we reason about bounds implied by UB.
8982 if (ConstantMaxNotTaken->isZero()) {
8983 this->ExactNotTaken = E = ConstantMaxNotTaken;
8984 this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
8985 }
8986
8989 "Exact is not allowed to be less precise than Constant Max");
8992 "Exact is not allowed to be less precise than Symbolic Max");
8995 "Symbolic Max is not allowed to be less precise than Constant Max");
8998 "No point in having a non-constant max backedge taken count!");
9000 for (const auto PredList : PredLists)
9001 for (const auto *P : PredList) {
9002 if (SeenPreds.contains(P))
9003 continue;
9004 assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!");
9005 SeenPreds.insert(P);
9006 Predicates.push_back(P);
9007 }
9008 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
9009 "Backedge count should be int");
9011 !ConstantMaxNotTaken->getType()->isPointerTy()) &&
9012 "Max backedge count should be int");
9013}
9014
9022
9023/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
9024/// computable exit into a persistent ExitNotTakenInfo array.
9025ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
9027 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
9028 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
9029 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
9030
9031 ExitNotTaken.reserve(ExitCounts.size());
9032 std::transform(ExitCounts.begin(), ExitCounts.end(),
9033 std::back_inserter(ExitNotTaken),
9034 [&](const EdgeExitInfo &EEI) {
9035 BasicBlock *ExitBB = EEI.first;
9036 const ExitLimit &EL = EEI.second;
9037 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
9038 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
9039 EL.Predicates);
9040 });
9041 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
9042 isa<SCEVConstant>(ConstantMax)) &&
9043 "No point in having a non-constant max backedge taken count!");
9044}
9045
9046/// Compute the number of times the backedge of the specified loop will execute.
9047ScalarEvolution::BackedgeTakenInfo
9048ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
9049 bool AllowPredicates) {
9050 SmallVector<BasicBlock *, 8> ExitingBlocks;
9051 L->getExitingBlocks(ExitingBlocks);
9052
9053 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
9054
9056 bool CouldComputeBECount = true;
9057 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
9058 const SCEV *MustExitMaxBECount = nullptr;
9059 const SCEV *MayExitMaxBECount = nullptr;
9060 bool MustExitMaxOrZero = false;
9061 bool IsOnlyExit = ExitingBlocks.size() == 1;
9062
9063 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
9064 // and compute maxBECount.
9065 // Do a union of all the predicates here.
9066 for (BasicBlock *ExitBB : ExitingBlocks) {
9067 // We canonicalize untaken exits to br (constant), ignore them so that
9068 // proving an exit untaken doesn't negatively impact our ability to reason
9069 // about the loop as whole.
9070 if (auto *BI = dyn_cast<CondBrInst>(ExitBB->getTerminator()))
9071 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
9072 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9073 if (ExitIfTrue == CI->isZero())
9074 continue;
9075 }
9076
9077 ExitLimit EL = computeExitLimit(L, ExitBB, IsOnlyExit, AllowPredicates);
9078
9079 assert((AllowPredicates || EL.Predicates.empty()) &&
9080 "Predicated exit limit when predicates are not allowed!");
9081
9082 // 1. For each exit that can be computed, add an entry to ExitCounts.
9083 // CouldComputeBECount is true only if all exits can be computed.
9084 if (EL.ExactNotTaken != getCouldNotCompute())
9085 ++NumExitCountsComputed;
9086 else
9087 // We couldn't compute an exact value for this exit, so
9088 // we won't be able to compute an exact value for the loop.
9089 CouldComputeBECount = false;
9090 // Remember exit count if either exact or symbolic is known. Because
9091 // Exact always implies symbolic, only check symbolic.
9092 if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
9093 ExitCounts.emplace_back(ExitBB, EL);
9094 else {
9095 assert(EL.ExactNotTaken == getCouldNotCompute() &&
9096 "Exact is known but symbolic isn't?");
9097 ++NumExitCountsNotComputed;
9098 }
9099
9100 // 2. Derive the loop's MaxBECount from each exit's max number of
9101 // non-exiting iterations. Partition the loop exits into two kinds:
9102 // LoopMustExits and LoopMayExits.
9103 //
9104 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
9105 // is a LoopMayExit. If any computable LoopMustExit is found, then
9106 // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
9107 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
9108 // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
9109 // any
9110 // computable EL.ConstantMaxNotTaken.
9111 if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
9112 DT.dominates(ExitBB, Latch)) {
9113 if (!MustExitMaxBECount) {
9114 MustExitMaxBECount = EL.ConstantMaxNotTaken;
9115 MustExitMaxOrZero = EL.MaxOrZero;
9116 } else {
9117 MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
9118 EL.ConstantMaxNotTaken);
9119 }
9120 } else if (MayExitMaxBECount != getCouldNotCompute()) {
9121 if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
9122 MayExitMaxBECount = EL.ConstantMaxNotTaken;
9123 else {
9124 MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
9125 EL.ConstantMaxNotTaken);
9126 }
9127 }
9128 }
9129 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
9130 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
9131 // The loop backedge will be taken the maximum or zero times if there's
9132 // a single exit that must be taken the maximum or zero times.
9133 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
9134
9135 // Remember which SCEVs are used in exit limits for invalidation purposes.
9136 // We only care about non-constant SCEVs here, so we can ignore
9137 // EL.ConstantMaxNotTaken
9138 // and MaxBECount, which must be SCEVConstant.
9139 for (const auto &Pair : ExitCounts) {
9140 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
9141 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
9142 if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
9143 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
9144 {L, AllowPredicates});
9145 }
9146 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
9147 MaxBECount, MaxOrZero);
9148}
9149
9150ScalarEvolution::ExitLimit
9151ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
9152 bool IsOnlyExit, bool AllowPredicates) {
9153 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
9154 // If our exiting block does not dominate the latch, then its connection with
9155 // loop's exit limit may be far from trivial.
9156 const BasicBlock *Latch = L->getLoopLatch();
9157 if (!Latch || !DT.dominates(ExitingBlock, Latch))
9158 return getCouldNotCompute();
9159
9160 Instruction *Term = ExitingBlock->getTerminator();
9161 if (CondBrInst *BI = dyn_cast<CondBrInst>(Term)) {
9162 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9163 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
9164 "It should have one successor in loop and one exit block!");
9165 // Proceed to the next level to examine the exit condition expression.
9166 return computeExitLimitFromCond(L, BI->getCondition(), ExitIfTrue,
9167 /*ControlsOnlyExit=*/IsOnlyExit,
9168 AllowPredicates);
9169 }
9170
9171 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
9172 // For switch, make sure that there is a single exit from the loop.
9173 BasicBlock *Exit = nullptr;
9174 for (auto *SBB : successors(ExitingBlock))
9175 if (!L->contains(SBB)) {
9176 if (Exit) // Multiple exit successors.
9177 return getCouldNotCompute();
9178 Exit = SBB;
9179 }
9180 assert(Exit && "Exiting block must have at least one exit");
9181 return computeExitLimitFromSingleExitSwitch(
9182 L, SI, Exit, /*ControlsOnlyExit=*/IsOnlyExit);
9183 }
9184
9185 return getCouldNotCompute();
9186}
9187
9189 const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9190 bool AllowPredicates) {
9191 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
9192 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
9193 ControlsOnlyExit, AllowPredicates);
9194}
9195
9196std::optional<ScalarEvolution::ExitLimit>
9197ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
9198 bool ExitIfTrue, bool ControlsOnlyExit,
9199 bool AllowPredicates) {
9200 (void)this->L;
9201 (void)this->ExitIfTrue;
9202 (void)this->AllowPredicates;
9203
9204 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9205 this->AllowPredicates == AllowPredicates &&
9206 "Variance in assumed invariant key components!");
9207 auto Itr = TripCountMap.find({ExitCond, ControlsOnlyExit});
9208 if (Itr == TripCountMap.end())
9209 return std::nullopt;
9210 return Itr->second;
9211}
9212
9213void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
9214 bool ExitIfTrue,
9215 bool ControlsOnlyExit,
9216 bool AllowPredicates,
9217 const ExitLimit &EL) {
9218 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9219 this->AllowPredicates == AllowPredicates &&
9220 "Variance in assumed invariant key components!");
9221
9222 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsOnlyExit}, EL});
9223 assert(InsertResult.second && "Expected successful insertion!");
9224 (void)InsertResult;
9225 (void)ExitIfTrue;
9226}
9227
9228ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
9229 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9230 bool ControlsOnlyExit, bool AllowPredicates) {
9231
9232 if (auto MaybeEL = Cache.find(L, ExitCond, ExitIfTrue, ControlsOnlyExit,
9233 AllowPredicates))
9234 return *MaybeEL;
9235
9236 ExitLimit EL = computeExitLimitFromCondImpl(
9237 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates);
9238 Cache.insert(L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates, EL);
9239 return EL;
9240}
9241
9242ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
9243 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9244 bool ControlsOnlyExit, bool AllowPredicates) {
9245 // Handle BinOp conditions (And, Or).
9246 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
9247 Cache, L, ExitCond, ExitIfTrue, AllowPredicates))
9248 return *LimitFromBinOp;
9249
9250 // With an icmp, it may be feasible to compute an exact backedge-taken count.
9251 // Proceed to the next level to examine the icmp.
9252 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
9253 ExitLimit EL =
9254 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsOnlyExit);
9255 if (EL.hasFullInfo() || !AllowPredicates)
9256 return EL;
9257
9258 // Try again, but use SCEV predicates this time.
9259 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue,
9260 ControlsOnlyExit,
9261 /*AllowPredicates=*/true);
9262 }
9263
9264 // Check for a constant condition. These are normally stripped out by
9265 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
9266 // preserve the CFG and is temporarily leaving constant conditions
9267 // in place.
9268 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
9269 if (ExitIfTrue == !CI->getZExtValue())
9270 // The backedge is always taken.
9271 return getCouldNotCompute();
9272 // The backedge is never taken.
9273 return getZero(CI->getType());
9274 }
9275
9276 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
9277 // with a constant step, we can form an equivalent icmp predicate and figure
9278 // out how many iterations will be taken before we exit.
9279 const WithOverflowInst *WO;
9280 const APInt *C;
9281 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
9282 match(WO->getRHS(), m_APInt(C))) {
9283 ConstantRange NWR =
9285 WO->getNoWrapKind());
9286 CmpInst::Predicate Pred;
9287 APInt NewRHSC, Offset;
9288 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
9289 if (!ExitIfTrue)
9290 Pred = ICmpInst::getInversePredicate(Pred);
9291 auto *LHS = getSCEV(WO->getLHS());
9292 if (Offset != 0)
9294 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
9295 ControlsOnlyExit, AllowPredicates);
9296 if (EL.hasAnyInfo())
9297 return EL;
9298 }
9299
9300 // If it's not an integer or pointer comparison then compute it the hard way.
9301 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9302}
9303
9304std::optional<ScalarEvolution::ExitLimit>
9305ScalarEvolution::computeExitLimitFromCondFromBinOp(ExitLimitCacheTy &Cache,
9306 const Loop *L,
9307 Value *ExitCond,
9308 bool ExitIfTrue,
9309 bool AllowPredicates) {
9310 // Check if the controlling expression for this loop is an And or Or.
9311 Value *Op0, *Op1;
9312 bool IsAnd;
9313 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
9314 IsAnd = true;
9315 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
9316 IsAnd = false;
9317 else
9318 return std::nullopt;
9319
9320 // A sub-condition of a non-trivial binop never solely controls the exit,
9321 // whether we exit always depends on both conditions.
9322 ExitLimit EL0 = computeExitLimitFromCondCached(
9323 Cache, L, Op0, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9324 ExitLimit EL1 = computeExitLimitFromCondCached(
9325 Cache, L, Op1, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9326
9327 // EitherMayExit is true in these two cases:
9328 // br (and Op0 Op1), loop, exit
9329 // br (or Op0 Op1), exit, loop
9330 bool EitherMayExit = IsAnd ^ ExitIfTrue;
9331
9332 const SCEV *BECount = getCouldNotCompute();
9333 const SCEV *ConstantMaxBECount = getCouldNotCompute();
9334 const SCEV *SymbolicMaxBECount = getCouldNotCompute();
9335 if (EitherMayExit) {
9336 bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
9337 // Both conditions must be same for the loop to continue executing.
9338 // Choose the less conservative count.
9339 if (EL0.ExactNotTaken != getCouldNotCompute() &&
9340 EL1.ExactNotTaken != getCouldNotCompute()) {
9341 BECount = getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken,
9342 UseSequentialUMin);
9343 }
9344 if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
9345 ConstantMaxBECount = EL1.ConstantMaxNotTaken;
9346 else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
9347 ConstantMaxBECount = EL0.ConstantMaxNotTaken;
9348 else
9349 ConstantMaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
9350 EL1.ConstantMaxNotTaken);
9351 if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
9352 SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
9353 else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
9354 SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
9355 else
9356 SymbolicMaxBECount = getUMinFromMismatchedTypes(
9357 EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
9358 } else {
9359 // Both conditions must be same at the same time for the loop to exit.
9360 // For now, be conservative.
9361 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
9362 BECount = EL0.ExactNotTaken;
9363 }
9364
9365 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
9366 // to be more aggressive when computing BECount than when computing
9367 // ConstantMaxBECount. In these cases it is possible for EL0.ExactNotTaken
9368 // and
9369 // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
9370 // EL1.ConstantMaxNotTaken to not.
9371 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
9372 !isa<SCEVCouldNotCompute>(BECount))
9373 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
9374 if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
9375 SymbolicMaxBECount =
9376 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
9377 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
9378 {ArrayRef(EL0.Predicates), ArrayRef(EL1.Predicates)});
9379}
9380
9381ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9382 const Loop *L, ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9383 bool AllowPredicates) {
9384 // If the condition was exit on true, convert the condition to exit on false
9385 CmpPredicate Pred;
9386 if (!ExitIfTrue)
9387 Pred = ExitCond->getCmpPredicate();
9388 else
9389 Pred = ExitCond->getInverseCmpPredicate();
9390 const ICmpInst::Predicate OriginalPred = Pred;
9391
9392 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
9393 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
9394
9395 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsOnlyExit,
9396 AllowPredicates);
9397 if (EL.hasAnyInfo())
9398 return EL;
9399
9400 auto *ExhaustiveCount =
9401 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9402
9403 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
9404 return ExhaustiveCount;
9405
9406 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
9407 ExitCond->getOperand(1), L, OriginalPred);
9408}
9409ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9410 const Loop *L, CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS,
9411 bool ControlsOnlyExit, bool AllowPredicates) {
9412
9413 // Try to evaluate any dependencies out of the loop.
9414 LHS = getSCEVAtScope(LHS, L);
9415 RHS = getSCEVAtScope(RHS, L);
9416
9417 // At this point, we would like to compute how many iterations of the
9418 // loop the predicate will return true for these inputs.
9419 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
9420 // If there is a loop-invariant, force it into the RHS.
9421 std::swap(LHS, RHS);
9423 }
9424
9425 bool ControllingFiniteLoop = ControlsOnlyExit && loopHasNoAbnormalExits(L) &&
9427 // Simplify the operands before analyzing them.
9428 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0);
9429
9430 // If we have a comparison of a chrec against a constant, try to use value
9431 // ranges to answer this query.
9432 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
9433 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
9434 if (AddRec->getLoop() == L) {
9435 // Form the constant range.
9436 ConstantRange CompRange =
9437 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
9438
9439 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
9440 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
9441 }
9442
9443 // If this loop must exit based on this condition (or execute undefined
9444 // behaviour), see if we can improve wrap flags. This is essentially
9445 // a must execute style proof.
9446 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
9447 // If we can prove the test sequence produced must repeat the same values
9448 // on self-wrap of the IV, then we can infer that IV doesn't self wrap
9449 // because if it did, we'd have an infinite (undefined) loop.
9450 // TODO: We can peel off any functions which are invertible *in L*. Loop
9451 // invariant terms are effectively constants for our purposes here.
9452 SCEVUse InnerLHS = LHS;
9453 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
9454 InnerLHS = ZExt->getOperand();
9455 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS);
9456 AR && !AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
9457 isKnownToBeAPowerOfTwo(AR->getStepRecurrence(*this), /*OrZero=*/true,
9458 /*OrNegative=*/true)) {
9459 auto Flags = AR->getNoWrapFlags();
9460 Flags = setFlags(Flags, SCEV::FlagNW);
9463 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9464 }
9465
9466 // For a slt/ult condition with a positive step, can we prove nsw/nuw?
9467 // From no-self-wrap, this follows trivially from the fact that every
9468 // (un)signed-wrapped, but not self-wrapped value must be LT than the
9469 // last value before (un)signed wrap. Since we know that last value
9470 // didn't exit, nor will any smaller one.
9471 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT) {
9472 auto WrapType = Pred == ICmpInst::ICMP_SLT ? SCEV::FlagNSW : SCEV::FlagNUW;
9473 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9474 AR && AR->getLoop() == L && AR->isAffine() &&
9475 !AR->getNoWrapFlags(WrapType) && AR->hasNoSelfWrap() &&
9476 isKnownPositive(AR->getStepRecurrence(*this))) {
9477 auto Flags = AR->getNoWrapFlags();
9478 Flags = setFlags(Flags, WrapType);
9481 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9482 }
9483 }
9484 }
9485
9486 switch (Pred) {
9487 case ICmpInst::ICMP_NE: { // while (X != Y)
9488 // Convert to: while (X-Y != 0)
9489 if (LHS->getType()->isPointerTy()) {
9492 return LHS;
9493 }
9494 if (RHS->getType()->isPointerTy()) {
9497 return RHS;
9498 }
9499 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit,
9500 AllowPredicates);
9501 if (EL.hasAnyInfo())
9502 return EL;
9503 break;
9504 }
9505 case ICmpInst::ICMP_EQ: { // while (X == Y)
9506 // Convert to: while (X-Y == 0)
9507 if (LHS->getType()->isPointerTy()) {
9510 return LHS;
9511 }
9512 if (RHS->getType()->isPointerTy()) {
9515 return RHS;
9516 }
9517 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
9518 if (EL.hasAnyInfo()) return EL;
9519 break;
9520 }
9521 case ICmpInst::ICMP_SLE:
9522 case ICmpInst::ICMP_ULE:
9523 // Since the loop is finite, an invariant RHS cannot include the boundary
9524 // value, otherwise it would loop forever.
9525 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9526 !isLoopInvariant(RHS, L)) {
9527 // Otherwise, perform the addition in a wider type, to avoid overflow.
9528 // If the LHS is an addrec with the appropriate nowrap flag, the
9529 // extension will be sunk into it and the exit count can be analyzed.
9530 auto *OldType = dyn_cast<IntegerType>(LHS->getType());
9531 if (!OldType)
9532 break;
9533 // Prefer doubling the bitwidth over adding a single bit to make it more
9534 // likely that we use a legal type.
9535 auto *NewType =
9536 Type::getIntNTy(OldType->getContext(), OldType->getBitWidth() * 2);
9537 if (ICmpInst::isSigned(Pred)) {
9538 LHS = getSignExtendExpr(LHS, NewType);
9539 RHS = getSignExtendExpr(RHS, NewType);
9540 } else {
9541 LHS = getZeroExtendExpr(LHS, NewType);
9542 RHS = getZeroExtendExpr(RHS, NewType);
9543 }
9544 }
9546 [[fallthrough]];
9547 case ICmpInst::ICMP_SLT:
9548 case ICmpInst::ICMP_ULT: { // while (X < Y)
9549 bool IsSigned = ICmpInst::isSigned(Pred);
9550 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9551 AllowPredicates);
9552 if (EL.hasAnyInfo())
9553 return EL;
9554 break;
9555 }
9556 case ICmpInst::ICMP_SGE:
9557 case ICmpInst::ICMP_UGE:
9558 // Since the loop is finite, an invariant RHS cannot include the boundary
9559 // value, otherwise it would loop forever.
9560 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9561 !isLoopInvariant(RHS, L))
9562 break;
9564 [[fallthrough]];
9565 case ICmpInst::ICMP_SGT:
9566 case ICmpInst::ICMP_UGT: { // while (X > Y)
9567 bool IsSigned = ICmpInst::isSigned(Pred);
9568 ExitLimit EL = howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9569 AllowPredicates);
9570 if (EL.hasAnyInfo())
9571 return EL;
9572 break;
9573 }
9574 default:
9575 break;
9576 }
9577
9578 return getCouldNotCompute();
9579}
9580
9581ScalarEvolution::ExitLimit
9582ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
9583 SwitchInst *Switch,
9584 BasicBlock *ExitingBlock,
9585 bool ControlsOnlyExit) {
9586 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
9587
9588 // Give up if the exit is the default dest of a switch.
9589 if (Switch->getDefaultDest() == ExitingBlock)
9590 return getCouldNotCompute();
9591
9592 assert(L->contains(Switch->getDefaultDest()) &&
9593 "Default case must not exit the loop!");
9594 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
9595 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
9596
9597 // while (X != Y) --> while (X-Y != 0)
9598 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit);
9599 if (EL.hasAnyInfo())
9600 return EL;
9601
9602 return getCouldNotCompute();
9603}
9604
9605static ConstantInt *
9607 ScalarEvolution &SE) {
9608 const SCEV *InVal = SE.getConstant(C);
9609 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
9611 "Evaluation of SCEV at constant didn't fold correctly?");
9612 return cast<SCEVConstant>(Val)->getValue();
9613}
9614
9615ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
9616 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
9617 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
9618 if (!RHS)
9619 return getCouldNotCompute();
9620
9621 const BasicBlock *Latch = L->getLoopLatch();
9622 if (!Latch)
9623 return getCouldNotCompute();
9624
9625 const BasicBlock *Predecessor = L->getLoopPredecessor();
9626 if (!Predecessor)
9627 return getCouldNotCompute();
9628
9629 // Return true if V is of the form "LHS `shift_op` <positive constant>".
9630 // Return LHS in OutLHS, shift_op in OutOpCode, and the shift amount in
9631 // OutShiftAmt.
9632 auto MatchPositiveShift = [](Value *V, Value *&OutLHS,
9633 Instruction::BinaryOps &OutOpCode,
9634 unsigned &OutShiftAmt) {
9635 using namespace PatternMatch;
9636
9637 ConstantInt *ShiftAmt;
9638 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9639 OutOpCode = Instruction::LShr;
9640 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9641 OutOpCode = Instruction::AShr;
9642 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9643 OutOpCode = Instruction::Shl;
9644 else
9645 return false;
9646
9647 uint64_t Amt = ShiftAmt->getValue().getLimitedValue();
9648 if (Amt == 0 || Amt >= OutLHS->getType()->getScalarSizeInBits())
9649 return false;
9650 OutShiftAmt = Amt;
9651 return true;
9652 };
9653
9654 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
9655 //
9656 // loop:
9657 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
9658 // %iv.shifted = lshr i32 %iv, <positive constant>
9659 //
9660 // Return true on a successful match. Return the corresponding PHI node (%iv
9661 // above) in PNOut, the opcode of the shift operation in OpCodeOut, and the
9662 // shift amount in ShiftAmtOut.
9663 auto MatchShiftRecurrence = [&](Value *V, PHINode *&PNOut,
9664 Instruction::BinaryOps &OpCodeOut,
9665 unsigned &ShiftAmtOut) {
9666 std::optional<Instruction::BinaryOps> PostShiftOpCode;
9667
9668 {
9670 Value *V;
9671 unsigned Amt;
9672
9673 // If we encounter a shift instruction, "peel off" the shift operation,
9674 // and remember that we did so. Later when we inspect %iv's backedge
9675 // value, we will make sure that the backedge value uses the same
9676 // operation.
9677 //
9678 // Note: the peeled shift operation does not have to be the same
9679 // instruction as the one feeding into the PHI's backedge value. We only
9680 // really care about it being the same *kind* of shift instruction --
9681 // that's all that is required for our later inferences to hold.
9682 if (MatchPositiveShift(LHS, V, OpC, Amt)) {
9683 PostShiftOpCode = OpC;
9684 LHS = V;
9685 }
9686 }
9687
9688 PNOut = dyn_cast<PHINode>(LHS);
9689 if (!PNOut || PNOut->getParent() != L->getHeader())
9690 return false;
9691
9692 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
9693 Value *OpLHS;
9694
9695 return
9696 // The backedge value for the PHI node must be a shift by a positive
9697 // amount
9698 MatchPositiveShift(BEValue, OpLHS, OpCodeOut, ShiftAmtOut) &&
9699
9700 // of the PHI node itself
9701 OpLHS == PNOut &&
9702
9703 // and the kind of shift should be match the kind of shift we peeled
9704 // off, if any.
9705 (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9706 };
9707
9708 PHINode *PN;
9710 unsigned ShiftAmt;
9711 if (!MatchShiftRecurrence(LHS, PN, OpCode, ShiftAmt))
9712 return getCouldNotCompute();
9713
9714 const DataLayout &DL = getDataLayout();
9715
9716 // The key rationale for this optimization is that for some kinds of shift
9717 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
9718 // within a finite number of iterations. If the condition guarding the
9719 // backedge (in the sense that the backedge is taken if the condition is true)
9720 // is false for the value the shift recurrence stabilizes to, then we know
9721 // that the backedge is taken only a finite number of times.
9722
9723 ConstantInt *StableValue = nullptr;
9724 switch (OpCode) {
9725 default:
9726 llvm_unreachable("Impossible case!");
9727
9728 case Instruction::AShr: {
9729 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
9730 // bitwidth(K) iterations.
9731 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
9732 KnownBits Known = computeKnownBits(FirstValue, DL, &AC,
9733 Predecessor->getTerminator(), &DT);
9734 auto *Ty = cast<IntegerType>(RHS->getType());
9735 if (Known.isNonNegative())
9736 StableValue = ConstantInt::get(Ty, 0);
9737 else if (Known.isNegative())
9738 StableValue = ConstantInt::get(Ty, -1, true);
9739 else
9740 return getCouldNotCompute();
9741
9742 break;
9743 }
9744 case Instruction::LShr:
9745 case Instruction::Shl:
9746 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
9747 // stabilize to 0 in at most bitwidth(K) iterations.
9748 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
9749 break;
9750 }
9751
9752 auto *Result =
9753 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
9754 assert(Result->getType()->isIntegerTy(1) &&
9755 "Otherwise cannot be an operand to a branch instruction");
9756
9757 if (Result->isNullValue()) {
9758 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9759 unsigned MaxBTC = BitWidth;
9760
9761 // For right-shift recurrences (lshr/ashr with non-negative start), we can
9762 // compute a tighter max backedge-taken count from the range of the start
9763 // value. After k shifts of ShiftAmt, value = start >> (k * ShiftAmt).
9764 // The value reaches 0 (the stable value) when k * ShiftAmt >=
9765 // activeBits(start), so max BTC = ceil(activeBits(maxStart) / ShiftAmt).
9766 if (OpCode == Instruction::LShr || OpCode == Instruction::AShr) {
9767 Value *StartValue = PN->getIncomingValueForBlock(Predecessor);
9768 const SCEV *StartSCEV = getSCEV(StartValue);
9769 APInt MaxStart = getUnsignedRangeMax(StartSCEV);
9770 if (MaxStart.isStrictlyPositive()) {
9771 unsigned ActiveBits = MaxStart.getActiveBits();
9772 unsigned RangeBTC = divideCeil(ActiveBits, ShiftAmt);
9773 MaxBTC = std::min(MaxBTC, RangeBTC);
9774 }
9775 }
9776
9777 const SCEV *UpperBound =
9779 return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
9780 }
9781
9782 return getCouldNotCompute();
9783}
9784
9785/// Return true if we can constant fold an instruction of the specified type,
9786/// assuming that all operands were constants.
9787static bool CanConstantFold(const Instruction *I) {
9791 return true;
9792
9793 if (const CallInst *CI = dyn_cast<CallInst>(I))
9794 if (const Function *F = CI->getCalledFunction())
9795 return canConstantFoldCallTo(CI, F);
9796 return false;
9797}
9798
9799/// Determine whether this instruction can constant evolve within this loop
9800/// assuming its operands can all constant evolve.
9801static bool canConstantEvolve(Instruction *I, const Loop *L) {
9802 // An instruction outside of the loop can't be derived from a loop PHI.
9803 if (!L->contains(I)) return false;
9804
9805 if (isa<PHINode>(I)) {
9806 // We don't currently keep track of the control flow needed to evaluate
9807 // PHIs, so we cannot handle PHIs inside of loops.
9808 return L->getHeader() == I->getParent();
9809 }
9810
9811 // If we won't be able to constant fold this expression even if the operands
9812 // are constants, bail early.
9813 return CanConstantFold(I);
9814}
9815
9816/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
9817/// recursing through each instruction operand until reaching a loop header phi.
9818static PHINode *
9821 unsigned Depth) {
9823 return nullptr;
9824
9825 // Otherwise, we can evaluate this instruction if all of its operands are
9826 // constant or derived from a PHI node themselves.
9827 PHINode *PHI = nullptr;
9828 for (Value *Op : UseInst->operands()) {
9829 if (isa<Constant>(Op)) continue;
9830
9832 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
9833
9834 PHINode *P = dyn_cast<PHINode>(OpInst);
9835 if (!P)
9836 // If this operand is already visited, reuse the prior result.
9837 // We may have P != PHI if this is the deepest point at which the
9838 // inconsistent paths meet.
9839 P = PHIMap.lookup(OpInst);
9840 if (!P) {
9841 // Recurse and memoize the results, whether a phi is found or not.
9842 // This recursive call invalidates pointers into PHIMap.
9843 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
9844 PHIMap[OpInst] = P;
9845 }
9846 if (!P)
9847 return nullptr; // Not evolving from PHI
9848 if (PHI && PHI != P)
9849 return nullptr; // Evolving from multiple different PHIs.
9850 PHI = P;
9851 }
9852 // This is a expression evolving from a constant PHI!
9853 return PHI;
9854}
9855
9856/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9857/// in the loop that V is derived from. We allow arbitrary operations along the
9858/// way, but the operands of an operation must either be constants or a value
9859/// derived from a constant PHI. If this expression does not fit with these
9860/// constraints, return null.
9863 if (!I || !canConstantEvolve(I, L)) return nullptr;
9864
9865 if (PHINode *PN = dyn_cast<PHINode>(I))
9866 return PN;
9867
9868 // Record non-constant instructions contained by the loop.
9870 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
9871}
9872
9873/// EvaluateExpression - Given an expression that passes the
9874/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9875/// in the loop has the value PHIVal. If we can't fold this expression for some
9876/// reason, return null.
9879 const DataLayout &DL,
9880 const TargetLibraryInfo *TLI) {
9881 // Convenient constant check, but redundant for recursive calls.
9882 if (Constant *C = dyn_cast<Constant>(V)) return C;
9884 if (!I) return nullptr;
9885
9886 if (Constant *C = Vals.lookup(I)) return C;
9887
9888 // An instruction inside the loop depends on a value outside the loop that we
9889 // weren't given a mapping for, or a value such as a call inside the loop.
9890 if (!canConstantEvolve(I, L)) return nullptr;
9891
9892 // An unmapped PHI can be due to a branch or another loop inside this loop,
9893 // or due to this not being the initial iteration through a loop where we
9894 // couldn't compute the evolution of this particular PHI last time.
9895 if (isa<PHINode>(I)) return nullptr;
9896
9897 std::vector<Constant*> Operands(I->getNumOperands());
9898
9899 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9900 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9901 if (!Operand) {
9902 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9903 if (!Operands[i]) return nullptr;
9904 continue;
9905 }
9906 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9907 Vals[Operand] = C;
9908 if (!C) return nullptr;
9909 Operands[i] = C;
9910 }
9911
9912 return ConstantFoldInstOperands(I, Operands, DL, TLI,
9913 /*AllowNonDeterministic=*/false);
9914}
9915
9916
9917// If every incoming value to PN except the one for BB is a specific Constant,
9918// return that, else return nullptr.
9920 Constant *IncomingVal = nullptr;
9921
9922 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9923 if (PN->getIncomingBlock(i) == BB)
9924 continue;
9925
9926 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
9927 if (!CurrentVal)
9928 return nullptr;
9929
9930 if (IncomingVal != CurrentVal) {
9931 if (IncomingVal)
9932 return nullptr;
9933 IncomingVal = CurrentVal;
9934 }
9935 }
9936
9937 return IncomingVal;
9938}
9939
9940/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9941/// in the header of its containing loop, we know the loop executes a
9942/// constant number of times, and the PHI node is just a recurrence
9943/// involving constants, fold it.
9944Constant *
9945ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9946 const APInt &BEs,
9947 const Loop *L) {
9948 auto [I, Inserted] = ConstantEvolutionLoopExitValue.try_emplace(PN);
9949 if (!Inserted)
9950 return I->second;
9951
9953 return nullptr; // Not going to evaluate it.
9954
9955 Constant *&RetVal = I->second;
9956
9957 DenseMap<Instruction *, Constant *> CurrentIterVals;
9958 BasicBlock *Header = L->getHeader();
9959 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9960
9961 BasicBlock *Latch = L->getLoopLatch();
9962 if (!Latch)
9963 return nullptr;
9964
9965 for (PHINode &PHI : Header->phis()) {
9966 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9967 CurrentIterVals[&PHI] = StartCST;
9968 }
9969 if (!CurrentIterVals.count(PN))
9970 return RetVal = nullptr;
9971
9972 Value *BEValue = PN->getIncomingValueForBlock(Latch);
9973
9974 // Execute the loop symbolically to determine the exit value.
9975 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
9976 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
9977
9978 unsigned NumIterations = BEs.getZExtValue(); // must be in range
9979 unsigned IterationNum = 0;
9980 const DataLayout &DL = getDataLayout();
9981 for (; ; ++IterationNum) {
9982 if (IterationNum == NumIterations)
9983 return RetVal = CurrentIterVals[PN]; // Got exit value!
9984
9985 // Compute the value of the PHIs for the next iteration.
9986 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9987 DenseMap<Instruction *, Constant *> NextIterVals;
9988 Constant *NextPHI =
9989 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9990 if (!NextPHI)
9991 return nullptr; // Couldn't evaluate!
9992 NextIterVals[PN] = NextPHI;
9993
9994 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9995
9996 // Also evaluate the other PHI nodes. However, we don't get to stop if we
9997 // cease to be able to evaluate one of them or if they stop evolving,
9998 // because that doesn't necessarily prevent us from computing PN.
10000 for (const auto &I : CurrentIterVals) {
10001 PHINode *PHI = dyn_cast<PHINode>(I.first);
10002 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
10003 PHIsToCompute.emplace_back(PHI, I.second);
10004 }
10005 // We use two distinct loops because EvaluateExpression may invalidate any
10006 // iterators into CurrentIterVals.
10007 for (const auto &I : PHIsToCompute) {
10008 PHINode *PHI = I.first;
10009 Constant *&NextPHI = NextIterVals[PHI];
10010 if (!NextPHI) { // Not already computed.
10011 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
10012 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
10013 }
10014 if (NextPHI != I.second)
10015 StoppedEvolving = false;
10016 }
10017
10018 // If all entries in CurrentIterVals == NextIterVals then we can stop
10019 // iterating, the loop can't continue to change.
10020 if (StoppedEvolving)
10021 return RetVal = CurrentIterVals[PN];
10022
10023 CurrentIterVals.swap(NextIterVals);
10024 }
10025}
10026
10027const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
10028 Value *Cond,
10029 bool ExitWhen) {
10030 PHINode *PN = getConstantEvolvingPHI(Cond, L);
10031 if (!PN) return getCouldNotCompute();
10032
10033 // If the loop is canonicalized, the PHI will have exactly two entries.
10034 // That's the only form we support here.
10035 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
10036
10037 DenseMap<Instruction *, Constant *> CurrentIterVals;
10038 BasicBlock *Header = L->getHeader();
10039 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
10040
10041 BasicBlock *Latch = L->getLoopLatch();
10042 assert(Latch && "Should follow from NumIncomingValues == 2!");
10043
10044 for (PHINode &PHI : Header->phis()) {
10045 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
10046 CurrentIterVals[&PHI] = StartCST;
10047 }
10048 if (!CurrentIterVals.count(PN))
10049 return getCouldNotCompute();
10050
10051 // Okay, we find a PHI node that defines the trip count of this loop. Execute
10052 // the loop symbolically to determine when the condition gets a value of
10053 // "ExitWhen".
10054 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
10055 const DataLayout &DL = getDataLayout();
10056 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
10057 auto *CondVal = dyn_cast_or_null<ConstantInt>(
10058 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
10059
10060 // Couldn't symbolically evaluate.
10061 if (!CondVal) return getCouldNotCompute();
10062
10063 if (CondVal->getValue() == uint64_t(ExitWhen)) {
10064 ++NumBruteForceTripCountsComputed;
10065 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
10066 }
10067
10068 // Update all the PHI nodes for the next iteration.
10069 DenseMap<Instruction *, Constant *> NextIterVals;
10070
10071 // Create a list of which PHIs we need to compute. We want to do this before
10072 // calling EvaluateExpression on them because that may invalidate iterators
10073 // into CurrentIterVals.
10074 SmallVector<PHINode *, 8> PHIsToCompute;
10075 for (const auto &I : CurrentIterVals) {
10076 PHINode *PHI = dyn_cast<PHINode>(I.first);
10077 if (!PHI || PHI->getParent() != Header) continue;
10078 PHIsToCompute.push_back(PHI);
10079 }
10080 for (PHINode *PHI : PHIsToCompute) {
10081 Constant *&NextPHI = NextIterVals[PHI];
10082 if (NextPHI) continue; // Already computed!
10083
10084 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
10085 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
10086 }
10087 CurrentIterVals.swap(NextIterVals);
10088 }
10089
10090 // Too many iterations were needed to evaluate.
10091 return getCouldNotCompute();
10092}
10093
10094const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
10096 ValuesAtScopes[V];
10097 // Check to see if we've folded this expression at this loop before.
10098 for (auto &LS : Values)
10099 if (LS.first == L)
10100 return LS.second ? LS.second : V;
10101
10102 Values.emplace_back(L, nullptr);
10103
10104 // Otherwise compute it.
10105 const SCEV *C = computeSCEVAtScope(V, L);
10106 for (auto &LS : reverse(ValuesAtScopes[V]))
10107 if (LS.first == L) {
10108 LS.second = C;
10109 if (!isa<SCEVConstant>(C))
10110 ValuesAtScopesUsers[C].push_back({L, V});
10111 break;
10112 }
10113 return C;
10114}
10115
10116/// This builds up a Constant using the ConstantExpr interface. That way, we
10117/// will return Constants for objects which aren't represented by a
10118/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
10119/// Returns NULL if the SCEV isn't representable as a Constant.
10121 switch (V->getSCEVType()) {
10122 case scCouldNotCompute:
10123 case scAddRecExpr:
10124 case scVScale:
10125 return nullptr;
10126 case scConstant:
10127 return cast<SCEVConstant>(V)->getValue();
10128 case scUnknown:
10130 case scPtrToAddr: {
10132 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
10133 return ConstantExpr::getPtrToAddr(CastOp, P2I->getType());
10134
10135 return nullptr;
10136 }
10137 case scTruncate: {
10139 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
10140 return ConstantExpr::getTrunc(CastOp, ST->getType());
10141 return nullptr;
10142 }
10143 case scAddExpr: {
10144 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
10145 Constant *C = nullptr;
10146 for (const SCEV *Op : SA->operands()) {
10148 if (!OpC)
10149 return nullptr;
10150 if (!C) {
10151 C = OpC;
10152 continue;
10153 }
10154 assert(!C->getType()->isPointerTy() &&
10155 "Can only have one pointer, and it must be last");
10156 if (OpC->getType()->isPointerTy()) {
10157 // The offsets have been converted to bytes. We can add bytes using
10158 // an i8 GEP.
10159 C = ConstantExpr::getPtrAdd(OpC, C);
10160 } else {
10161 C = ConstantExpr::getAdd(C, OpC);
10162 }
10163 }
10164 return C;
10165 }
10166 case scMulExpr:
10167 case scSignExtend:
10168 case scZeroExtend:
10169 case scUDivExpr:
10170 case scSMaxExpr:
10171 case scUMaxExpr:
10172 case scSMinExpr:
10173 case scUMinExpr:
10175 return nullptr;
10176 }
10177 llvm_unreachable("Unknown SCEV kind!");
10178}
10179
10180const SCEV *ScalarEvolution::getWithOperands(const SCEV *S,
10181 SmallVectorImpl<SCEVUse> &NewOps) {
10182 switch (S->getSCEVType()) {
10183 case scTruncate:
10184 case scZeroExtend:
10185 case scSignExtend:
10186 case scPtrToAddr:
10187 return getCastExpr(S->getSCEVType(), NewOps[0], S->getType());
10188 case scAddRecExpr: {
10189 auto *AddRec = cast<SCEVAddRecExpr>(S);
10190 return getAddRecExpr(NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags());
10191 }
10192 case scAddExpr:
10193 return getAddExpr(NewOps, cast<SCEVAddExpr>(S)->getNoWrapFlags());
10194 case scMulExpr:
10195 return getMulExpr(NewOps, cast<SCEVMulExpr>(S)->getNoWrapFlags());
10196 case scUDivExpr:
10197 return getUDivExpr(NewOps[0], NewOps[1]);
10198 case scUMaxExpr:
10199 case scSMaxExpr:
10200 case scUMinExpr:
10201 case scSMinExpr:
10202 return getMinMaxExpr(S->getSCEVType(), NewOps);
10204 return getSequentialMinMaxExpr(S->getSCEVType(), NewOps);
10205 case scConstant:
10206 case scVScale:
10207 case scUnknown:
10208 return S;
10209 case scCouldNotCompute:
10210 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10211 }
10212 llvm_unreachable("Unknown SCEV kind!");
10213}
10214
10215const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
10216 switch (V->getSCEVType()) {
10217 case scConstant:
10218 case scVScale:
10219 return V;
10220 case scAddRecExpr: {
10221 // If this is a loop recurrence for a loop that does not contain L, then we
10222 // are dealing with the final value computed by the loop.
10223 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(V);
10224 // First, attempt to evaluate each operand.
10225 // Avoid performing the look-up in the common case where the specified
10226 // expression has no loop-variant portions.
10227 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
10228 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
10229 if (OpAtScope == AddRec->getOperand(i))
10230 continue;
10231
10232 // Okay, at least one of these operands is loop variant but might be
10233 // foldable. Build a new instance of the folded commutative expression.
10235 NewOps.reserve(AddRec->getNumOperands());
10236 append_range(NewOps, AddRec->operands().take_front(i));
10237 NewOps.push_back(OpAtScope);
10238 for (++i; i != e; ++i)
10239 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
10240
10241 const SCEV *FoldedRec = getAddRecExpr(
10242 NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags(SCEV::FlagNW));
10243 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
10244 // The addrec may be folded to a nonrecurrence, for example, if the
10245 // induction variable is multiplied by zero after constant folding. Go
10246 // ahead and return the folded value.
10247 if (!AddRec)
10248 return FoldedRec;
10249 break;
10250 }
10251
10252 // If the scope is outside the addrec's loop, evaluate it by using the
10253 // loop exit value of the addrec.
10254 if (!AddRec->getLoop()->contains(L)) {
10255 // To evaluate this recurrence, we need to know how many times the AddRec
10256 // loop iterates. Compute this now.
10257 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
10258 if (BackedgeTakenCount == getCouldNotCompute())
10259 return AddRec;
10260
10261 // Then, evaluate the AddRec.
10262 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
10263 }
10264
10265 return AddRec;
10266 }
10267 case scTruncate:
10268 case scZeroExtend:
10269 case scSignExtend:
10270 case scPtrToAddr:
10271 case scAddExpr:
10272 case scMulExpr:
10273 case scUDivExpr:
10274 case scUMaxExpr:
10275 case scSMaxExpr:
10276 case scUMinExpr:
10277 case scSMinExpr:
10278 case scSequentialUMinExpr: {
10279 ArrayRef<SCEVUse> Ops = V->operands();
10280 // Avoid performing the look-up in the common case where the specified
10281 // expression has no loop-variant portions.
10282 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
10283 const SCEV *OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10284 if (OpAtScope != Ops[i].getPointer()) {
10285 // Okay, at least one of these operands is loop variant but might be
10286 // foldable. Build a new instance of the folded commutative expression.
10288 NewOps.reserve(Ops.size());
10289 append_range(NewOps, Ops.take_front(i));
10290 NewOps.push_back(OpAtScope);
10291
10292 for (++i; i != e; ++i) {
10293 OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10294 NewOps.push_back(OpAtScope);
10295 }
10296
10297 return getWithOperands(V, NewOps);
10298 }
10299 }
10300 // If we got here, all operands are loop invariant.
10301 return V;
10302 }
10303 case scUnknown: {
10304 // If this instruction is evolved from a constant-evolving PHI, compute the
10305 // exit value from the loop without using SCEVs.
10306 const SCEVUnknown *SU = cast<SCEVUnknown>(V);
10308 if (!I)
10309 return V; // This is some other type of SCEVUnknown, just return it.
10310
10311 if (PHINode *PN = dyn_cast<PHINode>(I)) {
10312 const Loop *CurrLoop = this->LI[I->getParent()];
10313 // Looking for loop exit value.
10314 if (CurrLoop && CurrLoop->getParentLoop() == L &&
10315 PN->getParent() == CurrLoop->getHeader()) {
10316 // Okay, there is no closed form solution for the PHI node. Check
10317 // to see if the loop that contains it has a known backedge-taken
10318 // count. If so, we may be able to force computation of the exit
10319 // value.
10320 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
10321 // This trivial case can show up in some degenerate cases where
10322 // the incoming IR has not yet been fully simplified.
10323 if (BackedgeTakenCount->isZero()) {
10324 Value *InitValue = nullptr;
10325 bool MultipleInitValues = false;
10326 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
10327 if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
10328 if (!InitValue)
10329 InitValue = PN->getIncomingValue(i);
10330 else if (InitValue != PN->getIncomingValue(i)) {
10331 MultipleInitValues = true;
10332 break;
10333 }
10334 }
10335 }
10336 if (!MultipleInitValues && InitValue)
10337 return getSCEV(InitValue);
10338 }
10339 // Do we have a loop invariant value flowing around the backedge
10340 // for a loop which must execute the backedge?
10341 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
10342 isKnownNonZero(BackedgeTakenCount) &&
10343 PN->getNumIncomingValues() == 2) {
10344
10345 unsigned InLoopPred =
10346 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
10347 Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
10348 if (CurrLoop->isLoopInvariant(BackedgeVal))
10349 return getSCEV(BackedgeVal);
10350 }
10351 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
10352 // Okay, we know how many times the containing loop executes. If
10353 // this is a constant evolving PHI node, get the final value at
10354 // the specified iteration number.
10355 Constant *RV =
10356 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
10357 if (RV)
10358 return getSCEV(RV);
10359 }
10360 }
10361 }
10362
10363 // Okay, this is an expression that we cannot symbolically evaluate
10364 // into a SCEV. Check to see if it's possible to symbolically evaluate
10365 // the arguments into constants, and if so, try to constant propagate the
10366 // result. This is particularly useful for computing loop exit values.
10367 if (!CanConstantFold(I))
10368 return V; // This is some other type of SCEVUnknown, just return it.
10369
10370 SmallVector<Constant *, 4> Operands;
10371 Operands.reserve(I->getNumOperands());
10372 bool MadeImprovement = false;
10373 for (Value *Op : I->operands()) {
10374 if (Constant *C = dyn_cast<Constant>(Op)) {
10375 Operands.push_back(C);
10376 continue;
10377 }
10378
10379 // If any of the operands is non-constant and if they are
10380 // non-integer and non-pointer, don't even try to analyze them
10381 // with scev techniques.
10382 if (!isSCEVable(Op->getType()))
10383 return V;
10384
10385 const SCEV *OrigV = getSCEV(Op);
10386 const SCEV *OpV = getSCEVAtScope(OrigV, L);
10387 MadeImprovement |= OrigV != OpV;
10388
10390 if (!C)
10391 return V;
10392 assert(C->getType() == Op->getType() && "Type mismatch");
10393 Operands.push_back(C);
10394 }
10395
10396 // Check to see if getSCEVAtScope actually made an improvement.
10397 if (!MadeImprovement)
10398 return V; // This is some other type of SCEVUnknown, just return it.
10399
10400 Constant *C = nullptr;
10401 const DataLayout &DL = getDataLayout();
10402 C = ConstantFoldInstOperands(I, Operands, DL, &TLI,
10403 /*AllowNonDeterministic=*/false);
10404 if (!C)
10405 return V;
10406 return getSCEV(C);
10407 }
10408 case scCouldNotCompute:
10409 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10410 }
10411 llvm_unreachable("Unknown SCEV type!");
10412}
10413
10415 return getSCEVAtScope(getSCEV(V), L);
10416}
10417
10418const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
10420 return stripInjectiveFunctions(ZExt->getOperand());
10422 return stripInjectiveFunctions(SExt->getOperand());
10423 return S;
10424}
10425
10426/// Finds the minimum unsigned root of the following equation:
10427///
10428/// A * X = B (mod N)
10429///
10430/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
10431/// A and B isn't important.
10432///
10433/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
10434static const SCEV *
10437 ScalarEvolution &SE, const Loop *L) {
10438 uint32_t BW = A.getBitWidth();
10439 assert(BW == SE.getTypeSizeInBits(B->getType()));
10440 assert(A != 0 && "A must be non-zero.");
10441
10442 // 1. D = gcd(A, N)
10443 //
10444 // The gcd of A and N may have only one prime factor: 2. The number of
10445 // trailing zeros in A is its multiplicity
10446 uint32_t Mult2 = A.countr_zero();
10447 // D = 2^Mult2
10448
10449 // 2. Check if B is divisible by D.
10450 //
10451 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
10452 // is not less than multiplicity of this prime factor for D.
10453 unsigned MinTZ = SE.getMinTrailingZeros(B);
10454 // Try again with the terminator of the loop predecessor for context-specific
10455 // result, if MinTZ s too small.
10456 if (MinTZ < Mult2 && L->getLoopPredecessor())
10457 MinTZ = SE.getMinTrailingZeros(B, L->getLoopPredecessor()->getTerminator());
10458 if (MinTZ < Mult2) {
10459 // Check if we can prove there's no remainder using URem.
10460 const SCEV *URem =
10461 SE.getURemExpr(B, SE.getConstant(APInt::getOneBitSet(BW, Mult2)));
10462 const SCEV *Zero = SE.getZero(B->getType());
10463 if (!SE.isKnownPredicate(CmpInst::ICMP_EQ, URem, Zero)) {
10464 // Try to add a predicate ensuring B is a multiple of 1 << Mult2.
10465 if (!Predicates)
10466 return SE.getCouldNotCompute();
10467
10468 // Avoid adding a predicate that is known to be false.
10469 if (SE.isKnownPredicate(CmpInst::ICMP_NE, URem, Zero))
10470 return SE.getCouldNotCompute();
10471 Predicates->push_back(SE.getEqualPredicate(URem, Zero));
10472 }
10473 }
10474
10475 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
10476 // modulo (N / D).
10477 //
10478 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
10479 // (N / D) in general. The inverse itself always fits into BW bits, though,
10480 // so we immediately truncate it.
10481 APInt AD = A.lshr(Mult2).trunc(BW - Mult2); // AD = A / D
10482 APInt I = AD.multiplicativeInverse().zext(BW);
10483
10484 // 4. Compute the minimum unsigned root of the equation:
10485 // I * (B / D) mod (N / D)
10486 // To simplify the computation, we factor out the divide by D:
10487 // (I * B mod N) / D
10488 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
10489 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
10490}
10491
10492/// For a given quadratic addrec, generate coefficients of the corresponding
10493/// quadratic equation, multiplied by a common value to ensure that they are
10494/// integers.
10495/// The returned value is a tuple { A, B, C, M, BitWidth }, where
10496/// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
10497/// were multiplied by, and BitWidth is the bit width of the original addrec
10498/// coefficients.
10499/// This function returns std::nullopt if the addrec coefficients are not
10500/// compile- time constants.
10501static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
10503 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
10504 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
10505 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
10506 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
10507 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
10508 << *AddRec << '\n');
10509
10510 // We currently can only solve this if the coefficients are constants.
10511 if (!LC || !MC || !NC) {
10512 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
10513 return std::nullopt;
10514 }
10515
10516 APInt L = LC->getAPInt();
10517 APInt M = MC->getAPInt();
10518 APInt N = NC->getAPInt();
10519 assert(!N.isZero() && "This is not a quadratic addrec");
10520
10521 unsigned BitWidth = LC->getAPInt().getBitWidth();
10522 unsigned NewWidth = BitWidth + 1;
10523 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
10524 << BitWidth << '\n');
10525 // The sign-extension (as opposed to a zero-extension) here matches the
10526 // extension used in SolveQuadraticEquationWrap (with the same motivation).
10527 N = N.sext(NewWidth);
10528 M = M.sext(NewWidth);
10529 L = L.sext(NewWidth);
10530
10531 // The increments are M, M+N, M+2N, ..., so the accumulated values are
10532 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
10533 // L+M, L+2M+N, L+3M+3N, ...
10534 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
10535 //
10536 // The equation Acc = 0 is then
10537 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
10538 // In a quadratic form it becomes:
10539 // N n^2 + (2M-N) n + 2L = 0.
10540
10541 APInt A = N;
10542 APInt B = 2 * M - A;
10543 APInt C = 2 * L;
10544 APInt T = APInt(NewWidth, 2);
10545 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
10546 << "x + " << C << ", coeff bw: " << NewWidth
10547 << ", multiplied by " << T << '\n');
10548 return std::make_tuple(A, B, C, T, BitWidth);
10549}
10550
10551/// Helper function to compare optional APInts:
10552/// (a) if X and Y both exist, return min(X, Y),
10553/// (b) if neither X nor Y exist, return std::nullopt,
10554/// (c) if exactly one of X and Y exists, return that value.
10555static std::optional<APInt> MinOptional(std::optional<APInt> X,
10556 std::optional<APInt> Y) {
10557 if (X && Y) {
10558 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
10559 APInt XW = X->sext(W);
10560 APInt YW = Y->sext(W);
10561 return XW.slt(YW) ? *X : *Y;
10562 }
10563 if (!X && !Y)
10564 return std::nullopt;
10565 return X ? *X : *Y;
10566}
10567
10568/// Helper function to truncate an optional APInt to a given BitWidth.
10569/// When solving addrec-related equations, it is preferable to return a value
10570/// that has the same bit width as the original addrec's coefficients. If the
10571/// solution fits in the original bit width, truncate it (except for i1).
10572/// Returning a value of a different bit width may inhibit some optimizations.
10573///
10574/// In general, a solution to a quadratic equation generated from an addrec
10575/// may require BW+1 bits, where BW is the bit width of the addrec's
10576/// coefficients. The reason is that the coefficients of the quadratic
10577/// equation are BW+1 bits wide (to avoid truncation when converting from
10578/// the addrec to the equation).
10579static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
10580 unsigned BitWidth) {
10581 if (!X)
10582 return std::nullopt;
10583 unsigned W = X->getBitWidth();
10585 return X->trunc(BitWidth);
10586 return X;
10587}
10588
10589/// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
10590/// iterations. The values L, M, N are assumed to be signed, and they
10591/// should all have the same bit widths.
10592/// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
10593/// where BW is the bit width of the addrec's coefficients.
10594/// If the calculated value is a BW-bit integer (for BW > 1), it will be
10595/// returned as such, otherwise the bit width of the returned value may
10596/// be greater than BW.
10597///
10598/// This function returns std::nullopt if
10599/// (a) the addrec coefficients are not constant, or
10600/// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
10601/// like x^2 = 5, no integer solutions exist, in other cases an integer
10602/// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
10603static std::optional<APInt>
10605 APInt A, B, C, M;
10606 unsigned BitWidth;
10607 auto T = GetQuadraticEquation(AddRec);
10608 if (!T)
10609 return std::nullopt;
10610
10611 std::tie(A, B, C, M, BitWidth) = *T;
10612 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
10613 std::optional<APInt> X =
10615 if (!X)
10616 return std::nullopt;
10617
10618 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
10619 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
10620 if (!V->isZero())
10621 return std::nullopt;
10622
10623 return TruncIfPossible(X, BitWidth);
10624}
10625
10626/// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
10627/// iterations. The values M, N are assumed to be signed, and they
10628/// should all have the same bit widths.
10629/// Find the least n such that c(n) does not belong to the given range,
10630/// while c(n-1) does.
10631///
10632/// This function returns std::nullopt if
10633/// (a) the addrec coefficients are not constant, or
10634/// (b) SolveQuadraticEquationWrap was unable to find a solution for the
10635/// bounds of the range.
10636static std::optional<APInt>
10638 const ConstantRange &Range, ScalarEvolution &SE) {
10639 assert(AddRec->getOperand(0)->isZero() &&
10640 "Starting value of addrec should be 0");
10641 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
10642 << Range << ", addrec " << *AddRec << '\n');
10643 // This case is handled in getNumIterationsInRange. Here we can assume that
10644 // we start in the range.
10645 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
10646 "Addrec's initial value should be in range");
10647
10648 APInt A, B, C, M;
10649 unsigned BitWidth;
10650 auto T = GetQuadraticEquation(AddRec);
10651 if (!T)
10652 return std::nullopt;
10653
10654 // Be careful about the return value: there can be two reasons for not
10655 // returning an actual number. First, if no solutions to the equations
10656 // were found, and second, if the solutions don't leave the given range.
10657 // The first case means that the actual solution is "unknown", the second
10658 // means that it's known, but not valid. If the solution is unknown, we
10659 // cannot make any conclusions.
10660 // Return a pair: the optional solution and a flag indicating if the
10661 // solution was found.
10662 auto SolveForBoundary =
10663 [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
10664 // Solve for signed overflow and unsigned overflow, pick the lower
10665 // solution.
10666 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
10667 << Bound << " (before multiplying by " << M << ")\n");
10668 Bound *= M; // The quadratic equation multiplier.
10669
10670 std::optional<APInt> SO;
10671 if (BitWidth > 1) {
10672 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10673 "signed overflow\n");
10675 }
10676 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10677 "unsigned overflow\n");
10678 std::optional<APInt> UO =
10680
10681 auto LeavesRange = [&] (const APInt &X) {
10682 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
10683 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
10684 if (Range.contains(V0->getValue()))
10685 return false;
10686 // X should be at least 1, so X-1 is non-negative.
10687 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
10689 if (Range.contains(V1->getValue()))
10690 return true;
10691 return false;
10692 };
10693
10694 // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
10695 // can be a solution, but the function failed to find it. We cannot treat it
10696 // as "no solution".
10697 if (!SO || !UO)
10698 return {std::nullopt, false};
10699
10700 // Check the smaller value first to see if it leaves the range.
10701 // At this point, both SO and UO must have values.
10702 std::optional<APInt> Min = MinOptional(SO, UO);
10703 if (LeavesRange(*Min))
10704 return { Min, true };
10705 std::optional<APInt> Max = Min == SO ? UO : SO;
10706 if (LeavesRange(*Max))
10707 return { Max, true };
10708
10709 // Solutions were found, but were eliminated, hence the "true".
10710 return {std::nullopt, true};
10711 };
10712
10713 std::tie(A, B, C, M, BitWidth) = *T;
10714 // Lower bound is inclusive, subtract 1 to represent the exiting value.
10715 APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
10716 APInt Upper = Range.getUpper().sext(A.getBitWidth());
10717 auto SL = SolveForBoundary(Lower);
10718 auto SU = SolveForBoundary(Upper);
10719 // If any of the solutions was unknown, no meaninigful conclusions can
10720 // be made.
10721 if (!SL.second || !SU.second)
10722 return std::nullopt;
10723
10724 // Claim: The correct solution is not some value between Min and Max.
10725 //
10726 // Justification: Assuming that Min and Max are different values, one of
10727 // them is when the first signed overflow happens, the other is when the
10728 // first unsigned overflow happens. Crossing the range boundary is only
10729 // possible via an overflow (treating 0 as a special case of it, modeling
10730 // an overflow as crossing k*2^W for some k).
10731 //
10732 // The interesting case here is when Min was eliminated as an invalid
10733 // solution, but Max was not. The argument is that if there was another
10734 // overflow between Min and Max, it would also have been eliminated if
10735 // it was considered.
10736 //
10737 // For a given boundary, it is possible to have two overflows of the same
10738 // type (signed/unsigned) without having the other type in between: this
10739 // can happen when the vertex of the parabola is between the iterations
10740 // corresponding to the overflows. This is only possible when the two
10741 // overflows cross k*2^W for the same k. In such case, if the second one
10742 // left the range (and was the first one to do so), the first overflow
10743 // would have to enter the range, which would mean that either we had left
10744 // the range before or that we started outside of it. Both of these cases
10745 // are contradictions.
10746 //
10747 // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
10748 // solution is not some value between the Max for this boundary and the
10749 // Min of the other boundary.
10750 //
10751 // Justification: Assume that we had such Max_A and Min_B corresponding
10752 // to range boundaries A and B and such that Max_A < Min_B. If there was
10753 // a solution between Max_A and Min_B, it would have to be caused by an
10754 // overflow corresponding to either A or B. It cannot correspond to B,
10755 // since Min_B is the first occurrence of such an overflow. If it
10756 // corresponded to A, it would have to be either a signed or an unsigned
10757 // overflow that is larger than both eliminated overflows for A. But
10758 // between the eliminated overflows and this overflow, the values would
10759 // cover the entire value space, thus crossing the other boundary, which
10760 // is a contradiction.
10761
10762 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
10763}
10764
10765ScalarEvolution::ExitLimit ScalarEvolution::howFarToZero(const SCEV *V,
10766 const Loop *L,
10767 bool ControlsOnlyExit,
10768 bool AllowPredicates) {
10769
10770 // This is only used for loops with a "x != y" exit test. The exit condition
10771 // is now expressed as a single expression, V = x-y. So the exit test is
10772 // effectively V != 0. We know and take advantage of the fact that this
10773 // expression only being used in a comparison by zero context.
10774
10776 // If the value is a constant
10777 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10778 // If the value is already zero, the branch will execute zero times.
10779 if (C->getValue()->isZero()) return C;
10780 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10781 }
10782
10783 const SCEVAddRecExpr *AddRec =
10784 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
10785
10786 if (!AddRec && AllowPredicates)
10787 // Try to make this an AddRec using runtime tests, in the first X
10788 // iterations of this loop, where X is the SCEV expression found by the
10789 // algorithm below.
10790 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
10791
10792 if (!AddRec || AddRec->getLoop() != L)
10793 return getCouldNotCompute();
10794
10795 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
10796 // the quadratic equation to solve it.
10797 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
10798 // We can only use this value if the chrec ends up with an exact zero
10799 // value at this index. When solving for "X*X != 5", for example, we
10800 // should not accept a root of 2.
10801 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
10802 const auto *R = cast<SCEVConstant>(getConstant(*S));
10803 return ExitLimit(R, R, R, false, Predicates);
10804 }
10805 return getCouldNotCompute();
10806 }
10807
10808 // Otherwise we can only handle this if it is affine.
10809 if (!AddRec->isAffine())
10810 return getCouldNotCompute();
10811
10812 // If this is an affine expression, the execution count of this branch is
10813 // the minimum unsigned root of the following equation:
10814 //
10815 // Start + Step*N = 0 (mod 2^BW)
10816 //
10817 // equivalent to:
10818 //
10819 // Step*N = -Start (mod 2^BW)
10820 //
10821 // where BW is the common bit width of Start and Step.
10822
10823 // Get the initial value for the loop.
10824 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
10825 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
10826
10827 if (!isLoopInvariant(Step, L))
10828 return getCouldNotCompute();
10829
10830 LoopGuards Guards = LoopGuards::collect(L, *this);
10831 // Specialize step for this loop so we get context sensitive facts below.
10832 const SCEV *StepWLG = applyLoopGuards(Step, Guards);
10833
10834 // For positive steps (counting up until unsigned overflow):
10835 // N = -Start/Step (as unsigned)
10836 // For negative steps (counting down to zero):
10837 // N = Start/-Step
10838 // First compute the unsigned distance from zero in the direction of Step.
10839 bool CountDown = isKnownNegative(StepWLG);
10840 if (!CountDown && !isKnownNonNegative(StepWLG))
10841 return getCouldNotCompute();
10842
10843 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
10844 // Handle unitary steps, which cannot wraparound.
10845 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10846 // N = Distance (as unsigned)
10847
10848 if (match(Step, m_CombineOr(m_scev_One(), m_scev_AllOnes()))) {
10849 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, Guards));
10850 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
10851
10852 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10853 // we end up with a loop whose backedge-taken count is n - 1. Detect this
10854 // case, and see if we can improve the bound.
10855 //
10856 // Explicitly handling this here is necessary because getUnsignedRange
10857 // isn't context-sensitive; it doesn't know that we only care about the
10858 // range inside the loop.
10859 const SCEV *Zero = getZero(Distance->getType());
10860 const SCEV *One = getOne(Distance->getType());
10861 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
10862 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
10863 // If Distance + 1 doesn't overflow, we can compute the maximum distance
10864 // as "unsigned_max(Distance + 1) - 1".
10865 ConstantRange CR = getUnsignedRange(DistancePlusOne);
10866 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
10867 }
10868 return ExitLimit(Distance, getConstant(MaxBECount), Distance, false,
10869 Predicates);
10870 }
10871
10872 // If the condition controls loop exit (the loop exits only if the expression
10873 // is true) and the addition is no-wrap we can use unsigned divide to
10874 // compute the backedge count. In this case, the step may not divide the
10875 // distance, but we don't care because if the condition is "missed" the loop
10876 // will have undefined behavior due to wrapping.
10877 if (ControlsOnlyExit && AddRec->hasNoSelfWrap() &&
10878 loopHasNoAbnormalExits(AddRec->getLoop())) {
10879
10880 // If the stride is zero and the start is non-zero, the loop must be
10881 // infinite. In C++, most loops are finite by assumption, in which case the
10882 // step being zero implies UB must execute if the loop is entered.
10883 if (!(loopIsFiniteByAssumption(L) && isKnownNonZero(Start)) &&
10884 !isKnownNonZero(StepWLG))
10885 return getCouldNotCompute();
10886
10887 const SCEV *Exact =
10888 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10889 const SCEV *ConstantMax = getCouldNotCompute();
10890 if (Exact != getCouldNotCompute()) {
10891 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, Guards));
10892 ConstantMax =
10894 }
10895 const SCEV *SymbolicMax =
10896 isa<SCEVCouldNotCompute>(Exact) ? ConstantMax : Exact;
10897 return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
10898 }
10899
10900 // Solve the general equation.
10901 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
10902 if (!StepC || StepC->getValue()->isZero())
10903 return getCouldNotCompute();
10904 const SCEV *E = SolveLinEquationWithOverflow(
10905 StepC->getAPInt(), getNegativeSCEV(Start),
10906 AllowPredicates ? &Predicates : nullptr, *this, L);
10907
10908 const SCEV *M = E;
10909 if (E != getCouldNotCompute()) {
10910 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, Guards));
10911 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
10912 }
10913 auto *S = isa<SCEVCouldNotCompute>(E) ? M : E;
10914 return ExitLimit(E, M, S, false, Predicates);
10915}
10916
10917ScalarEvolution::ExitLimit
10918ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10919 // Loops that look like: while (X == 0) are very strange indeed. We don't
10920 // handle them yet except for the trivial case. This could be expanded in the
10921 // future as needed.
10922
10923 // If the value is a constant, check to see if it is known to be non-zero
10924 // already. If so, the backedge will execute zero times.
10925 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10926 if (!C->getValue()->isZero())
10927 return getZero(C->getType());
10928 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10929 }
10930
10931 // We could implement others, but I really doubt anyone writes loops like
10932 // this, and if they did, they would already be constant folded.
10933 return getCouldNotCompute();
10934}
10935
10936std::pair<const BasicBlock *, const BasicBlock *>
10937ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10938 const {
10939 // If the block has a unique predecessor, then there is no path from the
10940 // predecessor to the block that does not go through the direct edge
10941 // from the predecessor to the block.
10942 if (const BasicBlock *Pred = BB->getSinglePredecessor())
10943 return {Pred, BB};
10944
10945 // A loop's header is defined to be a block that dominates the loop.
10946 // If the header has a unique predecessor outside the loop, it must be
10947 // a block that has exactly one successor that can reach the loop.
10948 if (const Loop *L = LI.getLoopFor(BB))
10949 return {L->getLoopPredecessor(), L->getHeader()};
10950
10951 return {nullptr, BB};
10952}
10953
10954/// SCEV structural equivalence is usually sufficient for testing whether two
10955/// expressions are equal, however for the purposes of looking for a condition
10956/// guarding a loop, it can be useful to be a little more general, since a
10957/// front-end may have replicated the controlling expression.
10958static bool HasSameValue(const SCEV *A, const SCEV *B) {
10959 // Quick check to see if they are the same SCEV.
10960 if (A == B) return true;
10961
10962 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10963 // Not all instructions that are "identical" compute the same value. For
10964 // instance, two distinct alloca instructions allocating the same type are
10965 // identical and do not read memory; but compute distinct values.
10966 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
10967 };
10968
10969 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10970 // two different instructions with the same value. Check for this case.
10971 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
10972 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
10973 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
10974 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
10975 if (ComputesEqualValues(AI, BI))
10976 return true;
10977
10978 // Otherwise assume they may have a different value.
10979 return false;
10980}
10981
10982static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS) {
10983 const SCEV *Op0, *Op1;
10984 if (!match(S, m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))))
10985 return false;
10986 if (match(Op0, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10987 LHS = Op1;
10988 return true;
10989 }
10990 if (match(Op1, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10991 LHS = Op0;
10992 return true;
10993 }
10994 return false;
10995}
10996
10998 SCEVUse &RHS, unsigned Depth) {
10999 bool Changed = false;
11000 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
11001 // '0 != 0'.
11002 auto TrivialCase = [&](bool TriviallyTrue) {
11004 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
11005 return true;
11006 };
11007 // If we hit the max recursion limit bail out.
11008 if (Depth >= 3)
11009 return false;
11010
11011 const SCEV *NewLHS, *NewRHS;
11012 if (match(LHS, m_scev_c_Mul(m_SCEV(NewLHS), m_SCEVVScale())) &&
11013 match(RHS, m_scev_c_Mul(m_SCEV(NewRHS), m_SCEVVScale()))) {
11014 const SCEVMulExpr *LMul = cast<SCEVMulExpr>(LHS);
11015 const SCEVMulExpr *RMul = cast<SCEVMulExpr>(RHS);
11016
11017 // (X * vscale) pred (Y * vscale) ==> X pred Y
11018 // when both multiples are NSW.
11019 // (X * vscale) uicmp/eq/ne (Y * vscale) ==> X uicmp/eq/ne Y
11020 // when both multiples are NUW.
11021 if ((LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap()) ||
11022 (LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap() &&
11023 !ICmpInst::isSigned(Pred))) {
11024 LHS = NewLHS;
11025 RHS = NewRHS;
11026 Changed = true;
11027 }
11028 }
11029
11030 // Canonicalize a constant to the right side.
11031 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
11032 // Check for both operands constant.
11033 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
11034 if (!ICmpInst::compare(LHSC->getAPInt(), RHSC->getAPInt(), Pred))
11035 return TrivialCase(false);
11036 return TrivialCase(true);
11037 }
11038 // Otherwise swap the operands to put the constant on the right.
11039 std::swap(LHS, RHS);
11041 Changed = true;
11042 }
11043
11044 // (K + A) pred (K + B) --> A pred B
11045 // For equality, no flags are needed.
11046 // For signed, both adds must be NSW. For unsigned, both must be NUW.
11047 {
11048 const SCEVConstant *C = nullptr;
11049 if (match(LHS, m_scev_Add(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11050 match(RHS, m_scev_Add(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11051 const auto *LAdd = cast<SCEVAddExpr>(LHS);
11052 const auto *RAdd = cast<SCEVAddExpr>(RHS);
11053 if (ICmpInst::isEquality(Pred) ||
11054 (ICmpInst::isSigned(Pred) && LAdd->hasNoSignedWrap() &&
11055 RAdd->hasNoSignedWrap()) ||
11056 (ICmpInst::isUnsigned(Pred) && LAdd->hasNoUnsignedWrap() &&
11057 RAdd->hasNoUnsignedWrap())) {
11058 LHS = NewLHS;
11059 RHS = NewRHS;
11060 Changed = true;
11061 }
11062 }
11063 }
11064
11065 // (C * A) pred (C * B) --> A pred B
11066 // For equality predicates, both muls must be NUW or both must be NSW
11067 // (either suffices to make multiplication by C injective; C == 0 is
11068 // impossible because SCEV folds 0 * X to 0).
11069 // For signed ordering, C must be positive and both muls must be NSW.
11070 // For unsigned ordering, both muls must be NUW.
11071 {
11072 const SCEVConstant *C = nullptr;
11073 if (match(LHS, m_scev_Mul(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11074 match(RHS, m_scev_Mul(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11075 const auto *LMul = cast<SCEVMulExpr>(LHS);
11076 const auto *RMul = cast<SCEVMulExpr>(RHS);
11077 bool BothNUW = LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap();
11078 bool BothNSW = LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap();
11079 if ((ICmpInst::isEquality(Pred) && (BothNUW || BothNSW)) ||
11080 (ICmpInst::isSigned(Pred) && BothNSW &&
11081 C->getAPInt().isStrictlyPositive()) ||
11082 (ICmpInst::isUnsigned(Pred) && BothNUW)) {
11083 LHS = NewLHS;
11084 RHS = NewRHS;
11085 Changed = true;
11086 }
11087 }
11088 }
11089
11090 // If we're comparing an addrec with a value which is loop-invariant in the
11091 // addrec's loop, put the addrec on the left. Also make a dominance check,
11092 // as both operands could be addrecs loop-invariant in each other's loop.
11093 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
11094 const Loop *L = AR->getLoop();
11095 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
11096 std::swap(LHS, RHS);
11098 Changed = true;
11099 }
11100 }
11101
11102 // If there's a constant operand, canonicalize comparisons with boundary
11103 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
11104 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
11105 const APInt &RA = RC->getAPInt();
11106
11107 bool SimplifiedByConstantRange = false;
11108
11109 if (!ICmpInst::isEquality(Pred)) {
11111 if (ExactCR.isFullSet())
11112 return TrivialCase(true);
11113 if (ExactCR.isEmptySet())
11114 return TrivialCase(false);
11115
11116 APInt NewRHS;
11117 CmpInst::Predicate NewPred;
11118 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
11119 ICmpInst::isEquality(NewPred)) {
11120 // We were able to convert an inequality to an equality.
11121 Pred = NewPred;
11122 RHS = getConstant(NewRHS);
11123 Changed = SimplifiedByConstantRange = true;
11124 }
11125 }
11126
11127 if (!SimplifiedByConstantRange) {
11128 switch (Pred) {
11129 default:
11130 break;
11131 case ICmpInst::ICMP_EQ:
11132 case ICmpInst::ICMP_NE:
11133 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
11134 if (RA.isZero() && MatchBinarySub(LHS, LHS, RHS))
11135 Changed = true;
11136 break;
11137
11138 // The "Should have been caught earlier!" messages refer to the fact
11139 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
11140 // should have fired on the corresponding cases, and canonicalized the
11141 // check to trivial case.
11142
11143 case ICmpInst::ICMP_UGE:
11144 assert(!RA.isMinValue() && "Should have been caught earlier!");
11145 Pred = ICmpInst::ICMP_UGT;
11146 RHS = getConstant(RA - 1);
11147 Changed = true;
11148 break;
11149 case ICmpInst::ICMP_ULE:
11150 assert(!RA.isMaxValue() && "Should have been caught earlier!");
11151 Pred = ICmpInst::ICMP_ULT;
11152 RHS = getConstant(RA + 1);
11153 Changed = true;
11154 break;
11155 case ICmpInst::ICMP_SGE:
11156 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
11157 Pred = ICmpInst::ICMP_SGT;
11158 RHS = getConstant(RA - 1);
11159 Changed = true;
11160 break;
11161 case ICmpInst::ICMP_SLE:
11162 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
11163 Pred = ICmpInst::ICMP_SLT;
11164 RHS = getConstant(RA + 1);
11165 Changed = true;
11166 break;
11167 }
11168 }
11169 }
11170
11171 // Check for obvious equality.
11172 if (HasSameValue(LHS, RHS)) {
11173 if (ICmpInst::isTrueWhenEqual(Pred))
11174 return TrivialCase(true);
11176 return TrivialCase(false);
11177 }
11178
11179 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
11180 // adding or subtracting 1 from one of the operands.
11181 switch (Pred) {
11182 case ICmpInst::ICMP_SLE:
11183 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
11184 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11186 Pred = ICmpInst::ICMP_SLT;
11187 Changed = true;
11188 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
11189 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
11191 Pred = ICmpInst::ICMP_SLT;
11192 Changed = true;
11193 }
11194 break;
11195 case ICmpInst::ICMP_SGE:
11196 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
11197 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
11199 Pred = ICmpInst::ICMP_SGT;
11200 Changed = true;
11201 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
11202 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11204 Pred = ICmpInst::ICMP_SGT;
11205 Changed = true;
11206 }
11207 break;
11208 case ICmpInst::ICMP_ULE:
11209 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
11210 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11212 Pred = ICmpInst::ICMP_ULT;
11213 Changed = true;
11214 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
11215 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
11216 Pred = ICmpInst::ICMP_ULT;
11217 Changed = true;
11218 }
11219 break;
11220 case ICmpInst::ICMP_UGE:
11221 // If RHS is an op we can fold the -1, try that first.
11222 // Otherwise prefer LHS to preserve the nuw flag.
11223 if ((isa<SCEVConstant>(RHS) ||
11225 isa<SCEVConstant>(cast<SCEVNAryExpr>(RHS)->getOperand(0)))) &&
11226 !getUnsignedRangeMin(RHS).isMinValue()) {
11227 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11228 Pred = ICmpInst::ICMP_UGT;
11229 Changed = true;
11230 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
11231 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11233 Pred = ICmpInst::ICMP_UGT;
11234 Changed = true;
11235 } else if (!getUnsignedRangeMin(RHS).isMinValue()) {
11236 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11237 Pred = ICmpInst::ICMP_UGT;
11238 Changed = true;
11239 }
11240 break;
11241 default:
11242 break;
11243 }
11244
11245 // TODO: More simplifications are possible here.
11246
11247 // Recursively simplify until we either hit a recursion limit or nothing
11248 // changes.
11249 if (Changed)
11250 (void)SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1);
11251
11252 return Changed;
11253}
11254
11256 return getSignedRangeMax(S).isNegative();
11257}
11258
11262
11264 return !getSignedRangeMin(S).isNegative();
11265}
11266
11270
11272 // Query push down for cases where the unsigned range is
11273 // less than sufficient.
11274 if (const auto *SExt = dyn_cast<SCEVSignExtendExpr>(S))
11275 return isKnownNonZero(SExt->getOperand(0));
11276 return getUnsignedRangeMin(S) != 0;
11277}
11278
11280 bool OrNegative) {
11281 auto NonRecursive = [OrNegative](const SCEV *S) {
11282 if (auto *C = dyn_cast<SCEVConstant>(S))
11283 return C->getAPInt().isPowerOf2() ||
11284 (OrNegative && C->getAPInt().isNegatedPowerOf2());
11285
11286 // vscale is a power-of-two.
11287 return isa<SCEVVScale>(S);
11288 };
11289
11290 if (NonRecursive(S))
11291 return true;
11292
11293 auto *Mul = dyn_cast<SCEVMulExpr>(S);
11294 if (!Mul)
11295 return false;
11296 return all_of(Mul->operands(), NonRecursive) && (OrZero || isKnownNonZero(S));
11297}
11298
11300 const SCEV *S, uint64_t M,
11302 if (M == 0)
11303 return false;
11304 if (M == 1)
11305 return true;
11306
11307 // Recursively check AddRec operands. An AddRecExpr S is a multiple of M if S
11308 // starts with a multiple of M and at every iteration step S only adds
11309 // multiples of M.
11310 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
11311 return isKnownMultipleOf(AddRec->getStart(), M, Assumptions) &&
11312 isKnownMultipleOf(AddRec->getStepRecurrence(*this), M, Assumptions);
11313
11314 // For a constant, check that "S % M == 0".
11315 if (auto *Cst = dyn_cast<SCEVConstant>(S)) {
11316 APInt C = Cst->getAPInt();
11317 return C.urem(M) == 0;
11318 }
11319
11320 // TODO: Also check other SCEV expressions, i.e., SCEVAddRecExpr, etc.
11321
11322 // Basic tests have failed.
11323 // Check "S % M == 0" at compile time and record runtime Assumptions.
11324 auto *STy = dyn_cast<IntegerType>(S->getType());
11325 const SCEV *SmodM =
11326 getURemExpr(S, getConstant(ConstantInt::get(STy, M, false)));
11327 const SCEV *Zero = getZero(STy);
11328
11329 // Check whether "S % M == 0" is known at compile time.
11330 if (isKnownPredicate(ICmpInst::ICMP_EQ, SmodM, Zero))
11331 return true;
11332
11333 // Check whether "S % M != 0" is known at compile time.
11334 if (isKnownPredicate(ICmpInst::ICMP_NE, SmodM, Zero))
11335 return false;
11336
11338
11339 // Detect redundant predicates.
11340 for (auto *A : Assumptions)
11341 if (A->implies(P, *this))
11342 return true;
11343
11344 // Only record non-redundant predicates.
11345 Assumptions.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 if (isKnownViaInduction(Pred, LHS, RHS))
11422 return true;
11423
11424 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
11425 return true;
11426
11427 // Otherwise see what can be done with some simple reasoning.
11428 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
11429}
11430
11432 const SCEV *LHS,
11433 const SCEV *RHS) {
11434 if (isKnownPredicate(Pred, LHS, RHS))
11435 return true;
11437 return false;
11438 return std::nullopt;
11439}
11440
11442 const SCEV *RHS,
11443 const Instruction *CtxI) {
11444 // TODO: Analyze guards and assumes from Context's block.
11445 return isKnownPredicate(Pred, LHS, RHS) ||
11446 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
11447}
11448
11449std::optional<bool>
11451 const SCEV *RHS, const Instruction *CtxI) {
11452 std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
11453 if (KnownWithoutContext)
11454 return KnownWithoutContext;
11455
11456 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
11457 return true;
11459 CtxI->getParent(), ICmpInst::getInverseCmpPredicate(Pred), LHS, RHS))
11460 return false;
11461 return std::nullopt;
11462}
11463
11465 const SCEVAddRecExpr *LHS,
11466 const SCEV *RHS) {
11467 const Loop *L = LHS->getLoop();
11468 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
11469 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
11470}
11471
11472std::optional<ScalarEvolution::MonotonicPredicateType>
11474 ICmpInst::Predicate Pred) {
11475 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
11476
11477#ifndef NDEBUG
11478 // Verify an invariant: inverting the predicate should turn a monotonically
11479 // increasing change to a monotonically decreasing one, and vice versa.
11480 if (Result) {
11481 auto ResultSwapped =
11482 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
11483
11484 assert(*ResultSwapped != *Result &&
11485 "monotonicity should flip as we flip the predicate");
11486 }
11487#endif
11488
11489 return Result;
11490}
11491
11492std::optional<ScalarEvolution::MonotonicPredicateType>
11493ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
11494 ICmpInst::Predicate Pred) {
11495 // A zero step value for LHS means the induction variable is essentially a
11496 // loop invariant value. We don't really depend on the predicate actually
11497 // flipping from false to true (for increasing predicates, and the other way
11498 // around for decreasing predicates), all we care about is that *if* the
11499 // predicate changes then it only changes from false to true.
11500 //
11501 // A zero step value in itself is not very useful, but there may be places
11502 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
11503 // as general as possible.
11504
11505 // Only handle LE/LT/GE/GT predicates.
11506 if (!ICmpInst::isRelational(Pred))
11507 return std::nullopt;
11508
11509 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
11510 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
11511 "Should be greater or less!");
11512
11513 // Check that AR does not wrap.
11514 if (ICmpInst::isUnsigned(Pred)) {
11515 if (!LHS->hasNoUnsignedWrap())
11516 return std::nullopt;
11518 }
11519 assert(ICmpInst::isSigned(Pred) &&
11520 "Relational predicate is either signed or unsigned!");
11521 if (!LHS->hasNoSignedWrap())
11522 return std::nullopt;
11523
11524 const SCEV *Step = LHS->getStepRecurrence(*this);
11525
11526 if (isKnownNonNegative(Step))
11528
11529 if (isKnownNonPositive(Step))
11531
11532 return std::nullopt;
11533}
11534
11535std::optional<ScalarEvolution::LoopInvariantPredicate>
11537 const SCEV *RHS, const Loop *L,
11538 const Instruction *CtxI) {
11539 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11540 if (!isLoopInvariant(RHS, L)) {
11541 if (!isLoopInvariant(LHS, L))
11542 return std::nullopt;
11543
11544 std::swap(LHS, RHS);
11546 }
11547
11548 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11549 if (!ArLHS || ArLHS->getLoop() != L)
11550 return std::nullopt;
11551
11552 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
11553 if (!MonotonicType)
11554 return std::nullopt;
11555 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
11556 // true as the loop iterates, and the backedge is control dependent on
11557 // "ArLHS `Pred` RHS" == true then we can reason as follows:
11558 //
11559 // * if the predicate was false in the first iteration then the predicate
11560 // is never evaluated again, since the loop exits without taking the
11561 // backedge.
11562 // * if the predicate was true in the first iteration then it will
11563 // continue to be true for all future iterations since it is
11564 // monotonically increasing.
11565 //
11566 // For both the above possibilities, we can replace the loop varying
11567 // predicate with its value on the first iteration of the loop (which is
11568 // loop invariant).
11569 //
11570 // A similar reasoning applies for a monotonically decreasing predicate, by
11571 // replacing true with false and false with true in the above two bullets.
11573 auto P = Increasing ? Pred : ICmpInst::getInverseCmpPredicate(Pred);
11574
11575 if (isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
11577 RHS);
11578
11579 if (!CtxI)
11580 return std::nullopt;
11581 // Try to prove via context.
11582 // TODO: Support other cases.
11583 switch (Pred) {
11584 default:
11585 break;
11586 case ICmpInst::ICMP_ULE:
11587 case ICmpInst::ICMP_ULT: {
11588 assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!");
11589 // Given preconditions
11590 // (1) ArLHS does not cross the border of positive and negative parts of
11591 // range because of:
11592 // - Positive step; (TODO: lift this limitation)
11593 // - nuw - does not cross zero boundary;
11594 // - nsw - does not cross SINT_MAX boundary;
11595 // (2) ArLHS <s RHS
11596 // (3) RHS >=s 0
11597 // we can replace the loop variant ArLHS <u RHS condition with loop
11598 // invariant Start(ArLHS) <u RHS.
11599 //
11600 // Because of (1) there are two options:
11601 // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
11602 // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
11603 // It means that ArLHS <s RHS <=> ArLHS <u RHS.
11604 // Because of (2) ArLHS <u RHS is trivially true.
11605 // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
11606 // We can strengthen this to Start(ArLHS) <u RHS.
11607 auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
11608 if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
11609 isKnownPositive(ArLHS->getStepRecurrence(*this)) &&
11610 isKnownNonNegative(RHS) &&
11611 isKnownPredicateAt(SignFlippedPred, ArLHS, RHS, CtxI))
11613 RHS);
11614 }
11615 }
11616
11617 return std::nullopt;
11618}
11619
11620std::optional<ScalarEvolution::LoopInvariantPredicate>
11622 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11623 const Instruction *CtxI, const SCEV *MaxIter) {
11625 Pred, LHS, RHS, L, CtxI, MaxIter))
11626 return LIP;
11627 if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
11628 // Number of iterations expressed as UMIN isn't always great for expressing
11629 // the value on the last iteration. If the straightforward approach didn't
11630 // work, try the following trick: if the a predicate is invariant for X, it
11631 // is also invariant for umin(X, ...). So try to find something that works
11632 // among subexpressions of MaxIter expressed as umin.
11633 for (SCEVUse Op : UMin->operands())
11635 Pred, LHS, RHS, L, CtxI, Op))
11636 return LIP;
11637 return std::nullopt;
11638}
11639
11640std::optional<ScalarEvolution::LoopInvariantPredicate>
11642 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11643 const Instruction *CtxI, const SCEV *MaxIter) {
11644 // Try to prove the following set of facts:
11645 // - The predicate is monotonic in the iteration space.
11646 // - If the check does not fail on the 1st iteration:
11647 // - No overflow will happen during first MaxIter iterations;
11648 // - It will not fail on the MaxIter'th iteration.
11649 // If the check does fail on the 1st iteration, we leave the loop and no
11650 // other checks matter.
11651
11652 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11653 if (!isLoopInvariant(RHS, L)) {
11654 if (!isLoopInvariant(LHS, L))
11655 return std::nullopt;
11656
11657 std::swap(LHS, RHS);
11659 }
11660
11661 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
11662 if (!AR || AR->getLoop() != L)
11663 return std::nullopt;
11664
11665 // Even if both are valid, we need to consistently chose the unsigned or the
11666 // signed predicate below, not mixtures of both. For now, prefer the unsigned
11667 // predicate.
11668 Pred = Pred.dropSameSign();
11669
11670 // The predicate must be relational (i.e. <, <=, >=, >).
11671 if (!ICmpInst::isRelational(Pred))
11672 return std::nullopt;
11673
11674 // TODO: Support steps other than +/- 1.
11675 const SCEV *Step = AR->getStepRecurrence(*this);
11676 auto *One = getOne(Step->getType());
11677 auto *MinusOne = getNegativeSCEV(One);
11678 if (Step != One && Step != MinusOne)
11679 return std::nullopt;
11680
11681 // Type mismatch here means that MaxIter is potentially larger than max
11682 // unsigned value in start type, which mean we cannot prove no wrap for the
11683 // indvar.
11684 if (AR->getType() != MaxIter->getType())
11685 return std::nullopt;
11686
11687 // Value of IV on suggested last iteration.
11688 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
11689 // Does it still meet the requirement?
11690 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
11691 return std::nullopt;
11692 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
11693 // not exceed max unsigned value of this type), this effectively proves
11694 // that there is no wrap during the iteration. To prove that there is no
11695 // signed/unsigned wrap, we need to check that
11696 // Start <= Last for step = 1 or Start >= Last for step = -1.
11697 ICmpInst::Predicate NoOverflowPred =
11699 if (Step == MinusOne)
11700 NoOverflowPred = ICmpInst::getSwappedPredicate(NoOverflowPred);
11701 const SCEV *Start = AR->getStart();
11702 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
11703 return std::nullopt;
11704
11705 // Everything is fine.
11706 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
11707}
11708
11709bool ScalarEvolution::isKnownPredicateViaConstantRanges(CmpPredicate Pred,
11710 SCEVUse LHS,
11711 SCEVUse RHS) {
11712 if (HasSameValue(LHS, RHS))
11713 return ICmpInst::isTrueWhenEqual(Pred);
11714
11715 auto CheckRange = [&](bool IsSigned) {
11716 auto RangeLHS = IsSigned ? getSignedRange(LHS) : getUnsignedRange(LHS);
11717 auto RangeRHS = IsSigned ? getSignedRange(RHS) : getUnsignedRange(RHS);
11718 return RangeLHS.icmp(Pred, RangeRHS);
11719 };
11720
11721 // The check at the top of the function catches the case where the values are
11722 // known to be equal.
11723 if (Pred == CmpInst::ICMP_EQ)
11724 return false;
11725
11726 if (Pred == CmpInst::ICMP_NE) {
11727 if (CheckRange(true) || CheckRange(false))
11728 return true;
11729 auto *Diff = getMinusSCEV(LHS, RHS);
11730 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
11731 }
11732
11733 return CheckRange(CmpInst::isSigned(Pred));
11734}
11735
11736bool ScalarEvolution::isKnownPredicateViaNoOverflow(CmpPredicate Pred,
11738 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
11739 // C1 and C2 are constant integers. If either X or Y are not add expressions,
11740 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
11741 // OutC1 and OutC2.
11742 auto MatchBinaryAddToConst = [this](SCEVUse X, SCEVUse Y, APInt &OutC1,
11743 APInt &OutC2,
11744 SCEV::NoWrapFlags ExpectedFlags) {
11745 SCEVUse XNonConstOp, XConstOp;
11746 SCEVUse YNonConstOp, YConstOp;
11747 SCEV::NoWrapFlags XFlagsPresent;
11748 SCEV::NoWrapFlags YFlagsPresent;
11749
11750 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
11751 XConstOp = getZero(X->getType());
11752 XNonConstOp = X;
11753 XFlagsPresent = ExpectedFlags;
11754 }
11755 if (!isa<SCEVConstant>(XConstOp))
11756 return false;
11757
11758 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
11759 YConstOp = getZero(Y->getType());
11760 YNonConstOp = Y;
11761 YFlagsPresent = ExpectedFlags;
11762 }
11763
11764 if (YNonConstOp != XNonConstOp)
11765 return false;
11766
11767 if (!isa<SCEVConstant>(YConstOp))
11768 return false;
11769
11770 // When matching ADDs with NUW flags (and unsigned predicates), only the
11771 // second ADD (with the larger constant) requires NUW.
11772 if ((YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11773 return false;
11774 if (ExpectedFlags != SCEV::FlagNUW &&
11775 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) {
11776 return false;
11777 }
11778
11779 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
11780 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
11781
11782 return true;
11783 };
11784
11785 APInt C1;
11786 APInt C2;
11787
11788 switch (Pred) {
11789 default:
11790 break;
11791
11792 case ICmpInst::ICMP_SGE:
11793 std::swap(LHS, RHS);
11794 [[fallthrough]];
11795 case ICmpInst::ICMP_SLE:
11796 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
11797 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
11798 return true;
11799
11800 break;
11801
11802 case ICmpInst::ICMP_SGT:
11803 std::swap(LHS, RHS);
11804 [[fallthrough]];
11805 case ICmpInst::ICMP_SLT:
11806 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
11807 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
11808 return true;
11809
11810 break;
11811
11812 case ICmpInst::ICMP_UGE:
11813 std::swap(LHS, RHS);
11814 [[fallthrough]];
11815 case ICmpInst::ICMP_ULE:
11816 // (X + C1) u<= (X + C2)<nuw> for C1 u<= C2.
11817 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ule(C2))
11818 return true;
11819
11820 break;
11821
11822 case ICmpInst::ICMP_UGT:
11823 std::swap(LHS, RHS);
11824 [[fallthrough]];
11825 case ICmpInst::ICMP_ULT:
11826 // (X + C1) u< (X + C2)<nuw> if C1 u< C2.
11827 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ult(C2))
11828 return true;
11829 break;
11830 }
11831
11832 return false;
11833}
11834
11835bool ScalarEvolution::isKnownPredicateViaSplitting(CmpPredicate Pred,
11837 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
11838 return false;
11839
11840 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
11841 // the stack can result in exponential time complexity.
11842 SaveAndRestore Restore(ProvingSplitPredicate, true);
11843
11844 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
11845 //
11846 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
11847 // isKnownPredicate. isKnownPredicate is more powerful, but also more
11848 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
11849 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
11850 // use isKnownPredicate later if needed.
11851 return isKnownNonNegative(RHS) &&
11854}
11855
11856bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, CmpPredicate Pred,
11857 const SCEV *LHS, const SCEV *RHS) {
11858 // No need to even try if we know the module has no guards.
11859 if (!HasGuards)
11860 return false;
11861
11862 return any_of(*BB, [&](const Instruction &I) {
11863 using namespace llvm::PatternMatch;
11864
11865 Value *Condition;
11867 m_Value(Condition))) &&
11868 isImpliedCond(Pred, LHS, RHS, Condition, false);
11869 });
11870}
11871
11872/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
11873/// protected by a conditional between LHS and RHS. This is used to
11874/// to eliminate casts.
11876 CmpPredicate Pred,
11877 const SCEV *LHS,
11878 const SCEV *RHS) {
11879 // Interpret a null as meaning no loop, where there is obviously no guard
11880 // (interprocedural conditions notwithstanding). Do not bother about
11881 // unreachable loops.
11882 if (!L || !DT.isReachableFromEntry(L->getHeader()))
11883 return true;
11884
11885 if (VerifyIR)
11886 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
11887 "This cannot be done on broken IR!");
11888
11889
11890 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11891 return true;
11892
11893 BasicBlock *Latch = L->getLoopLatch();
11894 if (!Latch)
11895 return false;
11896
11897 CondBrInst *LoopContinuePredicate =
11899 if (LoopContinuePredicate &&
11900 isImpliedCond(Pred, LHS, RHS, LoopContinuePredicate->getCondition(),
11901 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
11902 return true;
11903
11904 // We don't want more than one activation of the following loops on the stack
11905 // -- that can lead to O(n!) time complexity.
11906 if (WalkingBEDominatingConds)
11907 return false;
11908
11909 SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
11910
11911 // See if we can exploit a trip count to prove the predicate.
11912 const auto &BETakenInfo = getBackedgeTakenInfo(L);
11913 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
11914 if (LatchBECount != getCouldNotCompute()) {
11915 // We know that Latch branches back to the loop header exactly
11916 // LatchBECount times. This means the backdege condition at Latch is
11917 // equivalent to "{0,+,1} u< LatchBECount".
11918 Type *Ty = LatchBECount->getType();
11919 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
11920 const SCEV *LoopCounter =
11921 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
11922 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
11923 LatchBECount))
11924 return true;
11925 }
11926
11927 // Check conditions due to any @llvm.assume intrinsics.
11928 for (auto &AssumeVH : AC.assumptions()) {
11929 if (!AssumeVH)
11930 continue;
11931 auto *CI = cast<CallInst>(AssumeVH);
11932 if (!DT.dominates(CI, Latch->getTerminator()))
11933 continue;
11934
11935 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
11936 return true;
11937 }
11938
11939 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
11940 return true;
11941
11942 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
11943 DTN != HeaderDTN; DTN = DTN->getIDom()) {
11944 assert(DTN && "should reach the loop header before reaching the root!");
11945
11946 BasicBlock *BB = DTN->getBlock();
11947 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
11948 return true;
11949
11950 BasicBlock *PBB = BB->getSinglePredecessor();
11951 if (!PBB)
11952 continue;
11953
11955 if (!ContBr || ContBr->getSuccessor(0) == ContBr->getSuccessor(1))
11956 continue;
11957
11958 // If we have an edge `E` within the loop body that dominates the only
11959 // latch, the condition guarding `E` also guards the backedge. This
11960 // reasoning works only for loops with a single latch.
11961 // We're constructively (and conservatively) enumerating edges within the
11962 // loop body that dominate the latch. The dominator tree better agree
11963 // with us on this:
11964 assert(DT.dominates(BasicBlockEdge(PBB, BB), Latch) && "should be!");
11965 if (isImpliedCond(Pred, LHS, RHS, ContBr->getCondition(),
11966 BB != ContBr->getSuccessor(0)))
11967 return true;
11968 }
11969
11970 return false;
11971}
11972
11974 CmpPredicate Pred,
11975 const SCEV *LHS,
11976 const SCEV *RHS) {
11977 // Do not bother proving facts for unreachable code.
11978 if (!DT.isReachableFromEntry(BB))
11979 return true;
11980 if (VerifyIR)
11981 assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
11982 "This cannot be done on broken IR!");
11983
11984 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
11985 // the facts (a >= b && a != b) separately. A typical situation is when the
11986 // non-strict comparison is known from ranges and non-equality is known from
11987 // dominating predicates. If we are proving strict comparison, we always try
11988 // to prove non-equality and non-strict comparison separately.
11989 CmpPredicate NonStrictPredicate = ICmpInst::getNonStrictCmpPredicate(Pred);
11990 const bool ProvingStrictComparison =
11991 Pred != NonStrictPredicate.dropSameSign();
11992 bool ProvedNonStrictComparison = false;
11993 bool ProvedNonEquality = false;
11994
11995 auto SplitAndProve = [&](std::function<bool(CmpPredicate)> Fn) -> bool {
11996 if (!ProvedNonStrictComparison)
11997 ProvedNonStrictComparison = Fn(NonStrictPredicate);
11998 if (!ProvedNonEquality)
11999 ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
12000 if (ProvedNonStrictComparison && ProvedNonEquality)
12001 return true;
12002 return false;
12003 };
12004
12005 if (ProvingStrictComparison) {
12006 auto ProofFn = [&](CmpPredicate P) {
12007 return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
12008 };
12009 if (SplitAndProve(ProofFn))
12010 return true;
12011 }
12012
12013 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
12014 auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
12015 const Instruction *CtxI = &BB->front();
12016 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
12017 return true;
12018 if (ProvingStrictComparison) {
12019 auto ProofFn = [&](CmpPredicate P) {
12020 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
12021 };
12022 if (SplitAndProve(ProofFn))
12023 return true;
12024 }
12025 return false;
12026 };
12027
12028 // Starting at the block's predecessor, climb up the predecessor chain, as long
12029 // as there are predecessors that can be found that have unique successors
12030 // leading to the original block.
12031 const Loop *ContainingLoop = LI.getLoopFor(BB);
12032 const BasicBlock *PredBB;
12033 if (ContainingLoop && ContainingLoop->getHeader() == BB)
12034 PredBB = ContainingLoop->getLoopPredecessor();
12035 else
12036 PredBB = BB->getSinglePredecessor();
12037 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
12038 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
12039 const CondBrInst *BlockEntryPredicate =
12040 dyn_cast<CondBrInst>(Pair.first->getTerminator());
12041 if (!BlockEntryPredicate)
12042 continue;
12043
12044 if (ProveViaCond(BlockEntryPredicate->getCondition(),
12045 BlockEntryPredicate->getSuccessor(0) != Pair.second))
12046 return true;
12047 }
12048
12049 // Check conditions due to any @llvm.assume intrinsics.
12050 for (auto &AssumeVH : AC.assumptions()) {
12051 if (!AssumeVH)
12052 continue;
12053 auto *CI = cast<CallInst>(AssumeVH);
12054 if (!DT.dominates(CI, BB))
12055 continue;
12056
12057 if (ProveViaCond(CI->getArgOperand(0), false))
12058 return true;
12059 }
12060
12061 // Check conditions due to any @llvm.experimental.guard intrinsics.
12062 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
12063 F.getParent(), Intrinsic::experimental_guard);
12064 if (GuardDecl)
12065 for (const auto *GU : GuardDecl->users())
12066 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
12067 if (Guard->getFunction() == BB->getParent() && DT.dominates(Guard, BB))
12068 if (ProveViaCond(Guard->getArgOperand(0), false))
12069 return true;
12070 return false;
12071}
12072
12074 const SCEV *LHS,
12075 const SCEV *RHS) {
12076 // Interpret a null as meaning no loop, where there is obviously no guard
12077 // (interprocedural conditions notwithstanding).
12078 if (!L)
12079 return false;
12080
12081 // Both LHS and RHS must be available at loop entry.
12083 "LHS is not available at Loop Entry");
12085 "RHS is not available at Loop Entry");
12086
12087 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
12088 return true;
12089
12090 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
12091}
12092
12093bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12094 const SCEV *RHS,
12095 const Value *FoundCondValue, bool Inverse,
12096 const Instruction *CtxI) {
12097 // False conditions implies anything. Do not bother analyzing it further.
12098 if (FoundCondValue ==
12099 ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
12100 return true;
12101
12102 if (!PendingLoopPredicates.insert(FoundCondValue).second)
12103 return false;
12104
12105 llvm::scope_exit ClearOnExit(
12106 [&]() { PendingLoopPredicates.erase(FoundCondValue); });
12107
12108 // Recursively handle And and Or conditions.
12109 const Value *Op0, *Op1;
12110 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
12111 if (!Inverse)
12112 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12113 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12114 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
12115 if (Inverse)
12116 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12117 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12118 }
12119
12120 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
12121 if (!ICI) return false;
12122
12123 // Now that we found a conditional branch that dominates the loop or controls
12124 // the loop latch. Check to see if it is the comparison we are looking for.
12125 CmpPredicate FoundPred;
12126 if (Inverse)
12127 FoundPred = ICI->getInverseCmpPredicate();
12128 else
12129 FoundPred = ICI->getCmpPredicate();
12130
12131 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
12132 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
12133
12134 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
12135}
12136
12137bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12138 const SCEV *RHS, CmpPredicate FoundPred,
12139 const SCEV *FoundLHS, const SCEV *FoundRHS,
12140 const Instruction *CtxI) {
12141 // Balance the types.
12142 if (getTypeSizeInBits(LHS->getType()) <
12143 getTypeSizeInBits(FoundLHS->getType())) {
12144 // For unsigned and equality predicates, try to prove that both found
12145 // operands fit into narrow unsigned range. If so, try to prove facts in
12146 // narrow types.
12147 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
12148 !FoundRHS->getType()->isPointerTy()) {
12149 auto *NarrowType = LHS->getType();
12150 auto *WideType = FoundLHS->getType();
12151 auto BitWidth = getTypeSizeInBits(NarrowType);
12152 const SCEV *MaxValue = getZeroExtendExpr(
12154 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
12155 MaxValue) &&
12156 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
12157 MaxValue)) {
12158 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
12159 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
12160 // We cannot preserve samesign after truncation.
12161 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred.dropSameSign(),
12162 TruncFoundLHS, TruncFoundRHS, CtxI))
12163 return true;
12164 }
12165 }
12166
12167 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
12168 return false;
12169 if (CmpInst::isSigned(Pred)) {
12170 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
12171 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
12172 } else {
12173 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
12174 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
12175 }
12176 } else if (getTypeSizeInBits(LHS->getType()) >
12177 getTypeSizeInBits(FoundLHS->getType())) {
12178 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
12179 return false;
12180 if (CmpInst::isSigned(FoundPred)) {
12181 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
12182 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
12183 } else {
12184 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
12185 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
12186 }
12187 }
12188 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
12189 FoundRHS, CtxI);
12190}
12191
12192bool ScalarEvolution::isImpliedCondBalancedTypes(
12193 CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, CmpPredicate FoundPred,
12194 SCEVUse FoundLHS, SCEVUse FoundRHS, const Instruction *CtxI) {
12196 getTypeSizeInBits(FoundLHS->getType()) &&
12197 "Types should be balanced!");
12198 // Canonicalize the query to match the way instcombine will have
12199 // canonicalized the comparison.
12200 if (SimplifyICmpOperands(Pred, LHS, RHS))
12201 if (LHS == RHS)
12202 return CmpInst::isTrueWhenEqual(Pred);
12203 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
12204 if (FoundLHS == FoundRHS)
12205 return CmpInst::isFalseWhenEqual(FoundPred);
12206
12207 // Check to see if we can make the LHS or RHS match.
12208 if (LHS == FoundRHS || RHS == FoundLHS) {
12209 if (isa<SCEVConstant>(RHS)) {
12210 std::swap(FoundLHS, FoundRHS);
12211 FoundPred = ICmpInst::getSwappedCmpPredicate(FoundPred);
12212 } else {
12213 std::swap(LHS, RHS);
12215 }
12216 }
12217
12218 // Check whether the found predicate is the same as the desired predicate.
12219 if (auto P = CmpPredicate::getMatching(FoundPred, Pred))
12220 return isImpliedCondOperands(*P, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12221
12222 // Check whether swapping the found predicate makes it the same as the
12223 // desired predicate.
12224 if (auto P = CmpPredicate::getMatching(
12225 ICmpInst::getSwappedCmpPredicate(FoundPred), Pred)) {
12226 // We can write the implication
12227 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS
12228 // using one of the following ways:
12229 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS
12230 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS
12231 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS
12232 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS
12233 // Forms 1. and 2. require swapping the operands of one condition. Don't
12234 // do this if it would break canonical constant/addrec ordering.
12236 return isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P), RHS,
12237 LHS, FoundLHS, FoundRHS, CtxI);
12238 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
12239 return isImpliedCondOperands(*P, LHS, RHS, FoundRHS, FoundLHS, CtxI);
12240
12241 // There's no clear preference between forms 3. and 4., try both. Avoid
12242 // forming getNotSCEV of pointer values as the resulting subtract is
12243 // not legal.
12244 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() &&
12245 isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P),
12246 getNotSCEV(LHS), getNotSCEV(RHS), FoundLHS,
12247 FoundRHS, CtxI))
12248 return true;
12249
12250 if (!FoundLHS->getType()->isPointerTy() &&
12251 !FoundRHS->getType()->isPointerTy() &&
12252 isImpliedCondOperands(*P, LHS, RHS, getNotSCEV(FoundLHS),
12253 getNotSCEV(FoundRHS), CtxI))
12254 return true;
12255
12256 return false;
12257 }
12258
12259 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
12261 assert(P1 != P2 && "Handled earlier!");
12262 return CmpInst::isRelational(P2) &&
12264 };
12265 if (IsSignFlippedPredicate(Pred, FoundPred)) {
12266 // Unsigned comparison is the same as signed comparison when both the
12267 // operands are non-negative or negative.
12268 if (haveSameSign(FoundLHS, FoundRHS))
12269 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12270 // Create local copies that we can freely swap and canonicalize our
12271 // conditions to "le/lt".
12272 CmpPredicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
12273 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
12274 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
12275 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
12276 CanonicalPred = ICmpInst::getSwappedCmpPredicate(CanonicalPred);
12277 CanonicalFoundPred = ICmpInst::getSwappedCmpPredicate(CanonicalFoundPred);
12278 std::swap(CanonicalLHS, CanonicalRHS);
12279 std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
12280 }
12281 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
12282 "Must be!");
12283 assert((ICmpInst::isLT(CanonicalFoundPred) ||
12284 ICmpInst::isLE(CanonicalFoundPred)) &&
12285 "Must be!");
12286 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
12287 // Use implication:
12288 // x <u y && y >=s 0 --> x <s y.
12289 // If we can prove the left part, the right part is also proven.
12290 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
12291 CanonicalRHS, CanonicalFoundLHS,
12292 CanonicalFoundRHS);
12293 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
12294 // Use implication:
12295 // x <s y && y <s 0 --> x <u y.
12296 // If we can prove the left part, the right part is also proven.
12297 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
12298 CanonicalRHS, CanonicalFoundLHS,
12299 CanonicalFoundRHS);
12300 }
12301
12302 // Check if we can make progress by sharpening ranges.
12303 if (FoundPred == ICmpInst::ICMP_NE &&
12304 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
12305
12306 const SCEVConstant *C = nullptr;
12307 const SCEV *V = nullptr;
12308
12309 if (isa<SCEVConstant>(FoundLHS)) {
12310 C = cast<SCEVConstant>(FoundLHS);
12311 V = FoundRHS;
12312 } else {
12313 C = cast<SCEVConstant>(FoundRHS);
12314 V = FoundLHS;
12315 }
12316
12317 // The guarding predicate tells us that C != V. If the known range
12318 // of V is [C, t), we can sharpen the range to [C + 1, t). The
12319 // range we consider has to correspond to same signedness as the
12320 // predicate we're interested in folding.
12321
12322 APInt Min = ICmpInst::isSigned(Pred) ?
12324
12325 if (Min == C->getAPInt()) {
12326 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
12327 // This is true even if (Min + 1) wraps around -- in case of
12328 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
12329
12330 APInt SharperMin = Min + 1;
12331
12332 switch (Pred) {
12333 case ICmpInst::ICMP_SGE:
12334 case ICmpInst::ICMP_UGE:
12335 // We know V `Pred` SharperMin. If this implies LHS `Pred`
12336 // RHS, we're done.
12337 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
12338 CtxI))
12339 return true;
12340 [[fallthrough]];
12341
12342 case ICmpInst::ICMP_SGT:
12343 case ICmpInst::ICMP_UGT:
12344 // We know from the range information that (V `Pred` Min ||
12345 // V == Min). We know from the guarding condition that !(V
12346 // == Min). This gives us
12347 //
12348 // V `Pred` Min || V == Min && !(V == Min)
12349 // => V `Pred` Min
12350 //
12351 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
12352
12353 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
12354 return true;
12355 break;
12356
12357 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
12358 case ICmpInst::ICMP_SLE:
12359 case ICmpInst::ICMP_ULE:
12360 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12361 LHS, V, getConstant(SharperMin), CtxI))
12362 return true;
12363 [[fallthrough]];
12364
12365 case ICmpInst::ICMP_SLT:
12366 case ICmpInst::ICMP_ULT:
12367 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12368 LHS, V, getConstant(Min), CtxI))
12369 return true;
12370 break;
12371
12372 default:
12373 // No change
12374 break;
12375 }
12376 }
12377 }
12378
12379 // Check whether the actual condition is beyond sufficient.
12380 if (FoundPred == ICmpInst::ICMP_EQ)
12381 if (ICmpInst::isTrueWhenEqual(Pred))
12382 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12383 return true;
12384 if (Pred == ICmpInst::ICMP_NE)
12385 if (!ICmpInst::isTrueWhenEqual(FoundPred))
12386 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12387 return true;
12388
12389 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS))
12390 return true;
12391
12392 // Otherwise assume the worst.
12393 return false;
12394}
12395
12396bool ScalarEvolution::splitBinaryAdd(SCEVUse Expr, SCEVUse &L, SCEVUse &R,
12397 SCEV::NoWrapFlags &Flags) {
12398 if (!match(Expr, m_scev_Add(m_SCEV(L), m_SCEV(R))))
12399 return false;
12400
12401 Flags = cast<SCEVAddExpr>(Expr)->getNoWrapFlags();
12402 return true;
12403}
12404
12405std::optional<APInt>
12407 // We avoid subtracting expressions here because this function is usually
12408 // fairly deep in the call stack (i.e. is called many times).
12409
12410 unsigned BW = getTypeSizeInBits(More->getType());
12411 APInt Diff(BW, 0);
12412 APInt DiffMul(BW, 1);
12413 // Try various simplifications to reduce the difference to a constant. Limit
12414 // the number of allowed simplifications to keep compile-time low.
12415 for (unsigned I = 0; I < 8; ++I) {
12416 if (More == Less)
12417 return Diff;
12418
12419 // Reduce addrecs with identical steps to their start value.
12421 const auto *LAR = cast<SCEVAddRecExpr>(Less);
12422 const auto *MAR = cast<SCEVAddRecExpr>(More);
12423
12424 if (LAR->getLoop() != MAR->getLoop())
12425 return std::nullopt;
12426
12427 // We look at affine expressions only; not for correctness but to keep
12428 // getStepRecurrence cheap.
12429 if (!LAR->isAffine() || !MAR->isAffine())
12430 return std::nullopt;
12431
12432 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
12433 return std::nullopt;
12434
12435 Less = LAR->getStart();
12436 More = MAR->getStart();
12437 continue;
12438 }
12439
12440 // Try to match a common constant multiply.
12441 auto MatchConstMul =
12442 [](const SCEV *S) -> std::optional<std::pair<const SCEV *, APInt>> {
12443 const APInt *C;
12444 const SCEV *Op;
12445 if (match(S, m_scev_Mul(m_scev_APInt(C), m_SCEV(Op))))
12446 return {{Op, *C}};
12447 return std::nullopt;
12448 };
12449 if (auto MatchedMore = MatchConstMul(More)) {
12450 if (auto MatchedLess = MatchConstMul(Less)) {
12451 if (MatchedMore->second == MatchedLess->second) {
12452 More = MatchedMore->first;
12453 Less = MatchedLess->first;
12454 DiffMul *= MatchedMore->second;
12455 continue;
12456 }
12457 }
12458 }
12459
12460 // Try to cancel out common factors in two add expressions.
12462 auto Add = [&](const SCEV *S, int Mul) {
12463 if (auto *C = dyn_cast<SCEVConstant>(S)) {
12464 if (Mul == 1) {
12465 Diff += C->getAPInt() * DiffMul;
12466 } else {
12467 assert(Mul == -1);
12468 Diff -= C->getAPInt() * DiffMul;
12469 }
12470 } else
12471 Multiplicity[S] += Mul;
12472 };
12473 auto Decompose = [&](const SCEV *S, int Mul) {
12474 if (isa<SCEVAddExpr>(S)) {
12475 for (const SCEV *Op : S->operands())
12476 Add(Op, Mul);
12477 } else
12478 Add(S, Mul);
12479 };
12480 Decompose(More, 1);
12481 Decompose(Less, -1);
12482
12483 // Check whether all the non-constants cancel out, or reduce to new
12484 // More/Less values.
12485 const SCEV *NewMore = nullptr, *NewLess = nullptr;
12486 for (const auto &[S, Mul] : Multiplicity) {
12487 if (Mul == 0)
12488 continue;
12489 if (Mul == 1) {
12490 if (NewMore)
12491 return std::nullopt;
12492 NewMore = S;
12493 } else if (Mul == -1) {
12494 if (NewLess)
12495 return std::nullopt;
12496 NewLess = S;
12497 } else
12498 return std::nullopt;
12499 }
12500
12501 // Values stayed the same, no point in trying further.
12502 if (NewMore == More || NewLess == Less)
12503 return std::nullopt;
12504
12505 More = NewMore;
12506 Less = NewLess;
12507
12508 // Reduced to constant.
12509 if (!More && !Less)
12510 return Diff;
12511
12512 // Left with variable on only one side, bail out.
12513 if (!More || !Less)
12514 return std::nullopt;
12515 }
12516
12517 // Did not reduce to constant.
12518 return std::nullopt;
12519}
12520
12521bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
12522 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12523 const SCEV *FoundRHS, const Instruction *CtxI) {
12524 // Try to recognize the following pattern:
12525 //
12526 // FoundRHS = ...
12527 // ...
12528 // loop:
12529 // FoundLHS = {Start,+,W}
12530 // context_bb: // Basic block from the same loop
12531 // known(Pred, FoundLHS, FoundRHS)
12532 //
12533 // If some predicate is known in the context of a loop, it is also known on
12534 // each iteration of this loop, including the first iteration. Therefore, in
12535 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
12536 // prove the original pred using this fact.
12537 if (!CtxI)
12538 return false;
12539 const BasicBlock *ContextBB = CtxI->getParent();
12540 // Make sure AR varies in the context block.
12541 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
12542 const Loop *L = AR->getLoop();
12543 const auto *Latch = L->getLoopLatch();
12544 // Make sure that context belongs to the loop and executes on 1st iteration
12545 // (if it ever executes at all).
12546 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12547 return false;
12548 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
12549 return false;
12550 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
12551 }
12552
12553 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
12554 const Loop *L = AR->getLoop();
12555 const auto *Latch = L->getLoopLatch();
12556 // Make sure that context belongs to the loop and executes on 1st iteration
12557 // (if it ever executes at all).
12558 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12559 return false;
12560 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
12561 return false;
12562 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
12563 }
12564
12565 return false;
12566}
12567
12568bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(CmpPredicate Pred,
12569 const SCEV *LHS,
12570 const SCEV *RHS,
12571 const SCEV *FoundLHS,
12572 const SCEV *FoundRHS) {
12573 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
12574 return false;
12575
12576 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
12577 if (!AddRecLHS)
12578 return false;
12579
12580 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12581 if (!AddRecFoundLHS)
12582 return false;
12583
12584 // We'd like to let SCEV reason about control dependencies, so we constrain
12585 // both the inequalities to be about add recurrences on the same loop. This
12586 // way we can use isLoopEntryGuardedByCond later.
12587
12588 const Loop *L = AddRecFoundLHS->getLoop();
12589 if (L != AddRecLHS->getLoop())
12590 return false;
12591
12592 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
12593 //
12594 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
12595 // ... (2)
12596 //
12597 // Informal proof for (2), assuming (1) [*]:
12598 //
12599 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
12600 //
12601 // Then
12602 //
12603 // FoundLHS s< FoundRHS s< INT_MIN - C
12604 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
12605 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
12606 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
12607 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
12608 // <=> FoundLHS + C s< FoundRHS + C
12609 //
12610 // [*]: (1) can be proved by ruling out overflow.
12611 //
12612 // [**]: This can be proved by analyzing all the four possibilities:
12613 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
12614 // (A s>= 0, B s>= 0).
12615 //
12616 // Note:
12617 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
12618 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
12619 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
12620 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
12621 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
12622 // C)".
12623
12624 std::optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
12625 if (!LDiff)
12626 return false;
12627 std::optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
12628 if (!RDiff || *LDiff != *RDiff)
12629 return false;
12630
12631 if (LDiff->isMinValue())
12632 return true;
12633
12634 APInt FoundRHSLimit;
12635
12636 if (Pred == CmpInst::ICMP_ULT) {
12637 FoundRHSLimit = -(*RDiff);
12638 } else {
12639 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
12640 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
12641 }
12642
12643 // Try to prove (1) or (2), as needed.
12644 return isAvailableAtLoopEntry(FoundRHS, L) &&
12645 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
12646 getConstant(FoundRHSLimit));
12647}
12648
12649bool ScalarEvolution::isImpliedViaMerge(CmpPredicate Pred, const SCEV *LHS,
12650 const SCEV *RHS, const SCEV *FoundLHS,
12651 const SCEV *FoundRHS, unsigned Depth) {
12652 const PHINode *LPhi = nullptr, *RPhi = nullptr;
12653
12654 llvm::scope_exit ClearOnExit([&]() {
12655 if (LPhi) {
12656 bool Erased = PendingMerges.erase(LPhi);
12657 assert(Erased && "Failed to erase LPhi!");
12658 (void)Erased;
12659 }
12660 if (RPhi) {
12661 bool Erased = PendingMerges.erase(RPhi);
12662 assert(Erased && "Failed to erase RPhi!");
12663 (void)Erased;
12664 }
12665 });
12666
12667 // Find respective Phis and check that they are not being pending.
12668 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
12669 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
12670 if (!PendingMerges.insert(Phi).second)
12671 return false;
12672 LPhi = Phi;
12673 }
12674 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
12675 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
12676 // If we detect a loop of Phi nodes being processed by this method, for
12677 // example:
12678 //
12679 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
12680 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
12681 //
12682 // we don't want to deal with a case that complex, so return conservative
12683 // answer false.
12684 if (!PendingMerges.insert(Phi).second)
12685 return false;
12686 RPhi = Phi;
12687 }
12688
12689 // If none of LHS, RHS is a Phi, nothing to do here.
12690 if (!LPhi && !RPhi)
12691 return false;
12692
12693 // If there is a SCEVUnknown Phi we are interested in, make it left.
12694 if (!LPhi) {
12695 std::swap(LHS, RHS);
12696 std::swap(FoundLHS, FoundRHS);
12697 std::swap(LPhi, RPhi);
12699 }
12700
12701 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
12702 const BasicBlock *LBB = LPhi->getParent();
12703 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12704
12705 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
12706 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
12707 isImpliedCondOperandsViaRanges(Pred, S1, S2, Pred, FoundLHS, FoundRHS) ||
12708 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
12709 };
12710
12711 if (RPhi && RPhi->getParent() == LBB) {
12712 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
12713 // If we compare two Phis from the same block, and for each entry block
12714 // the predicate is true for incoming values from this block, then the
12715 // predicate is also true for the Phis.
12716 for (const BasicBlock *IncBB : predecessors(LBB)) {
12717 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12718 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
12719 if (!ProvedEasily(L, R))
12720 return false;
12721 }
12722 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
12723 // Case two: RHS is also a Phi from the same basic block, and it is an
12724 // AddRec. It means that there is a loop which has both AddRec and Unknown
12725 // PHIs, for it we can compare incoming values of AddRec from above the loop
12726 // and latch with their respective incoming values of LPhi.
12727 // TODO: Generalize to handle loops with many inputs in a header.
12728 if (LPhi->getNumIncomingValues() != 2) return false;
12729
12730 auto *RLoop = RAR->getLoop();
12731 auto *Predecessor = RLoop->getLoopPredecessor();
12732 assert(Predecessor && "Loop with AddRec with no predecessor?");
12733 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
12734 if (!ProvedEasily(L1, RAR->getStart()))
12735 return false;
12736 auto *Latch = RLoop->getLoopLatch();
12737 assert(Latch && "Loop with AddRec with no latch?");
12738 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
12739 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
12740 return false;
12741 } else {
12742 // In all other cases go over inputs of LHS and compare each of them to RHS,
12743 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
12744 // At this point RHS is either a non-Phi, or it is a Phi from some block
12745 // different from LBB.
12746 for (const BasicBlock *IncBB : predecessors(LBB)) {
12747 // Check that RHS is available in this block.
12748 if (!dominates(RHS, IncBB))
12749 return false;
12750 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12751 // Make sure L does not refer to a value from a potentially previous
12752 // iteration of a loop.
12753 if (!properlyDominates(L, LBB))
12754 return false;
12755 // Addrecs are considered to properly dominate their loop, so are missed
12756 // by the previous check. Discard any values that have computable
12757 // evolution in this loop.
12758 if (auto *Loop = LI.getLoopFor(LBB))
12760 return false;
12761 if (!ProvedEasily(L, RHS))
12762 return false;
12763 }
12764 }
12765 return true;
12766}
12767
12768bool ScalarEvolution::isImpliedCondOperandsViaShift(CmpPredicate Pred,
12769 const SCEV *LHS,
12770 const SCEV *RHS,
12771 const SCEV *FoundLHS,
12772 const SCEV *FoundRHS) {
12773 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make
12774 // sure that we are dealing with same LHS.
12775 if (RHS == FoundRHS) {
12776 std::swap(LHS, RHS);
12777 std::swap(FoundLHS, FoundRHS);
12779 }
12780 if (LHS != FoundLHS)
12781 return false;
12782
12783 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
12784 if (!SUFoundRHS)
12785 return false;
12786
12787 Value *Shiftee, *ShiftValue;
12788
12789 using namespace PatternMatch;
12790 if (match(SUFoundRHS->getValue(),
12791 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
12792 auto *ShifteeS = getSCEV(Shiftee);
12793 // Prove one of the following:
12794 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
12795 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
12796 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12797 // ---> LHS <s RHS
12798 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12799 // ---> LHS <=s RHS
12800 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
12801 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
12802 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
12803 if (isKnownNonNegative(ShifteeS))
12804 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
12805 }
12806
12807 return false;
12808}
12809
12810bool ScalarEvolution::isImpliedCondOperandsViaMatchingDiff(
12811 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12812 const SCEV *FoundRHS) {
12813 // Only valid for equality predicates: (A == B) implies (C == D) when
12814 // the SCEV difference A - B equals C - D (they check the same
12815 // underlying relationship at every iteration).
12816 if (!ICmpInst::isEquality(Pred))
12817 return false;
12818
12819 // Restrict to cases involving loop recurrences - that's where this
12820 // pattern arises (correlated IV comparisons). This avoids calling
12821 // getMinusSCEV on arbitrary non-loop expressions.
12823 (!isa<SCEVAddRecExpr>(FoundLHS) && !isa<SCEVAddRecExpr>(FoundRHS)))
12824 return false;
12825
12826 // AddRecs from different loops can never produce matching differences.
12827 const SCEVAddRecExpr *QueryAddRec = dyn_cast<SCEVAddRecExpr>(LHS);
12828 if (!QueryAddRec)
12829 QueryAddRec = cast<SCEVAddRecExpr>(RHS);
12830 const SCEVAddRecExpr *FoundAddRec = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12831 if (!FoundAddRec)
12832 FoundAddRec = cast<SCEVAddRecExpr>(FoundRHS);
12833 if (QueryAddRec->getLoop() != FoundAddRec->getLoop())
12834 return false;
12835
12836 // If the strides differ, the differences can never match.
12837 if (QueryAddRec->getStepRecurrence(*this) !=
12838 FoundAddRec->getStepRecurrence(*this))
12839 return false;
12840
12841 // Compute differences. For pointer-typed operands sharing the same base,
12842 // getMinusSCEV strips the common base and returns an integer SCEV.
12843 // For example, {base,+,8} - (base+8*n) = {-8n,+,8}
12844 const SCEV *FoundDiff = getMinusSCEV(FoundLHS, FoundRHS);
12845 if (isa<SCEVCouldNotCompute>(FoundDiff))
12846 return false;
12847
12848 const SCEV *Diff = getMinusSCEV(LHS, RHS);
12849 if (isa<SCEVCouldNotCompute>(Diff))
12850 return false;
12851
12852 return Diff == FoundDiff;
12853}
12854
12855bool ScalarEvolution::isImpliedCondOperands(CmpPredicate Pred, const SCEV *LHS,
12856 const SCEV *RHS,
12857 const SCEV *FoundLHS,
12858 const SCEV *FoundRHS,
12859 const Instruction *CtxI) {
12860 return isImpliedCondOperandsViaRanges(Pred, LHS, RHS, Pred, FoundLHS,
12861 FoundRHS) ||
12862 isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS,
12863 FoundRHS) ||
12864 isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS) ||
12865 isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12866 CtxI) ||
12867 isImpliedCondOperandsViaMatchingDiff(Pred, LHS, RHS, FoundLHS,
12868 FoundRHS) ||
12869 isImpliedCondOperandsHelper(Pred, LHS, RHS, FoundLHS, FoundRHS);
12870}
12871
12872/// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
12873template <typename MinMaxExprType>
12874static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
12875 const SCEV *Candidate) {
12876 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12877 if (!MinMaxExpr)
12878 return false;
12879
12880 return is_contained(MinMaxExpr->operands(), Candidate);
12881}
12882
12884 CmpPredicate Pred, const SCEV *LHS,
12885 const SCEV *RHS) {
12886 // If both sides are affine addrecs for the same loop, with equal
12887 // steps, and we know the recurrences don't wrap, then we only
12888 // need to check the predicate on the starting values.
12889
12890 if (!ICmpInst::isRelational(Pred))
12891 return false;
12892
12893 const SCEV *LStart, *RStart, *Step;
12894 const Loop *L;
12895 if (!match(LHS,
12896 m_scev_AffineAddRec(m_SCEV(LStart), m_SCEV(Step), m_Loop(L))) ||
12898 m_SpecificLoop(L))))
12899 return false;
12904 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
12905 return false;
12906
12907 return SE.isKnownPredicate(Pred, LStart, RStart);
12908}
12909
12910/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
12911/// expression?
12913 const SCEV *LHS, const SCEV *RHS) {
12914 switch (Pred) {
12915 default:
12916 return false;
12917
12918 case ICmpInst::ICMP_SGE:
12919 std::swap(LHS, RHS);
12920 [[fallthrough]];
12921 case ICmpInst::ICMP_SLE:
12922 return
12923 // min(A, ...) <= A
12925 // A <= max(A, ...)
12927
12928 case ICmpInst::ICMP_UGE:
12929 std::swap(LHS, RHS);
12930 [[fallthrough]];
12931 case ICmpInst::ICMP_ULE:
12932 return
12933 // min(A, ...) <= A
12934 // FIXME: what about umin_seq?
12936 // A <= max(A, ...)
12938
12939 case ICmpInst::ICMP_UGT:
12940 std::swap(LHS, RHS);
12941 [[fallthrough]];
12942 case ICmpInst::ICMP_ULT:
12943 // umin(Ops) u<= each Op, so proving Op u< RHS for any Op proves
12944 // umin(Ops) u< RHS.
12945 //
12946 // Use computeConstantDifference instead of the more powerful
12947 // isKnownPredicate to keep this check cheap: isKnownPredicateViaMinOrMax
12948 // is called from isKnownViaNonRecursiveReasoning, so recursing into
12949 // the full predicate prover would be expensive.
12950 if (const auto *Min = dyn_cast<SCEVUMinExpr>(LHS)) {
12951 for (SCEVUse Op : Min->operands()) {
12952 std::optional<APInt> Diff = SE.computeConstantDifference(RHS, Op);
12953 // When Op and RHS share a common base differing by a
12954 // constant offset D (RHS - Op = D), Op u< RHS holds iff D != 0 and
12955 // RHS >= D (unsigned), i.e. the subtraction doesn't underflow.
12956 if (Diff && !Diff->isZero() && SE.getUnsignedRangeMin(RHS).uge(*Diff))
12957 return true;
12958 }
12959 }
12960 return false;
12961 }
12962
12963 llvm_unreachable("covered switch fell through?!");
12964}
12965
12966bool ScalarEvolution::isImpliedViaOperations(CmpPredicate Pred, const SCEV *LHS,
12967 const SCEV *RHS,
12968 const SCEV *FoundLHS,
12969 const SCEV *FoundRHS,
12970 unsigned Depth) {
12973 "LHS and RHS have different sizes?");
12974 assert(getTypeSizeInBits(FoundLHS->getType()) ==
12975 getTypeSizeInBits(FoundRHS->getType()) &&
12976 "FoundLHS and FoundRHS have different sizes?");
12977 // We want to avoid hurting the compile time with analysis of too big trees.
12979 return false;
12980
12981 // We only want to work with GT comparison so far.
12982 if (ICmpInst::isLT(Pred)) {
12984 std::swap(LHS, RHS);
12985 std::swap(FoundLHS, FoundRHS);
12986 }
12987
12989
12990 // For unsigned, try to reduce it to corresponding signed comparison.
12991 if (P == ICmpInst::ICMP_UGT)
12992 // We can replace unsigned predicate with its signed counterpart if all
12993 // involved values are non-negative.
12994 // TODO: We could have better support for unsigned.
12995 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
12996 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
12997 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
12998 // use this fact to prove that LHS and RHS are non-negative.
12999 const SCEV *MinusOne = getMinusOne(LHS->getType());
13000 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
13001 FoundRHS) &&
13002 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
13003 FoundRHS))
13005 }
13006
13007 if (P != ICmpInst::ICMP_SGT)
13008 return false;
13009
13010 auto GetOpFromSExt = [&](const SCEV *S) -> const SCEV * {
13011 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
13012 return Ext->getOperand();
13013 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
13014 // the constant in some cases.
13015 return S;
13016 };
13017
13018 // Acquire values from extensions.
13019 auto *OrigLHS = LHS;
13020 auto *OrigFoundLHS = FoundLHS;
13021 LHS = GetOpFromSExt(LHS);
13022 FoundLHS = GetOpFromSExt(FoundLHS);
13023
13024 // Is the SGT predicate can be proved trivially or using the found context.
13025 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
13026 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
13027 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
13028 FoundRHS, Depth + 1);
13029 };
13030
13031 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
13032 // We want to avoid creation of any new non-constant SCEV. Since we are
13033 // going to compare the operands to RHS, we should be certain that we don't
13034 // need any size extensions for this. So let's decline all cases when the
13035 // sizes of types of LHS and RHS do not match.
13036 // TODO: Maybe try to get RHS from sext to catch more cases?
13038 return false;
13039
13040 // Should not overflow.
13041 if (!LHSAddExpr->hasNoSignedWrap())
13042 return false;
13043
13044 SCEVUse LL = LHSAddExpr->getOperand(0);
13045 SCEVUse LR = LHSAddExpr->getOperand(1);
13046 auto *MinusOne = getMinusOne(RHS->getType());
13047
13048 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
13049 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
13050 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
13051 };
13052 // Try to prove the following rule:
13053 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
13054 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
13055 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
13056 return true;
13057 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
13058 Value *LL, *LR;
13059 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
13060
13061 using namespace llvm::PatternMatch;
13062
13063 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
13064 // Rules for division.
13065 // We are going to perform some comparisons with Denominator and its
13066 // derivative expressions. In general case, creating a SCEV for it may
13067 // lead to a complex analysis of the entire graph, and in particular it
13068 // can request trip count recalculation for the same loop. This would
13069 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
13070 // this, we only want to create SCEVs that are constants in this section.
13071 // So we bail if Denominator is not a constant.
13072 if (!isa<ConstantInt>(LR))
13073 return false;
13074
13075 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
13076
13077 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
13078 // then a SCEV for the numerator already exists and matches with FoundLHS.
13079 auto *Numerator = getExistingSCEV(LL);
13080 if (!Numerator || Numerator->getType() != FoundLHS->getType())
13081 return false;
13082
13083 // Make sure that the numerator matches with FoundLHS and the denominator
13084 // is positive.
13085 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
13086 return false;
13087
13088 auto *DTy = Denominator->getType();
13089 auto *FRHSTy = FoundRHS->getType();
13090 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
13091 // One of types is a pointer and another one is not. We cannot extend
13092 // them properly to a wider type, so let us just reject this case.
13093 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
13094 // to avoid this check.
13095 return false;
13096
13097 // Given that:
13098 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
13099 auto *WTy = getWiderType(DTy, FRHSTy);
13100 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
13101 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
13102
13103 // Try to prove the following rule:
13104 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
13105 // For example, given that FoundLHS > 2. It means that FoundLHS is at
13106 // least 3. If we divide it by Denominator < 4, we will have at least 1.
13107 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
13108 if (isKnownNonPositive(RHS) &&
13109 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
13110 return true;
13111
13112 // Try to prove the following rule:
13113 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
13114 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
13115 // If we divide it by Denominator > 2, then:
13116 // 1. If FoundLHS is negative, then the result is 0.
13117 // 2. If FoundLHS is non-negative, then the result is non-negative.
13118 // Anyways, the result is non-negative.
13119 auto *MinusOne = getMinusOne(WTy);
13120 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
13121 if (isKnownNegative(RHS) &&
13122 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
13123 return true;
13124 }
13125 }
13126
13127 // If our expression contained SCEVUnknown Phis, and we split it down and now
13128 // need to prove something for them, try to prove the predicate for every
13129 // possible incoming values of those Phis.
13130 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
13131 return true;
13132
13133 return false;
13134}
13135
13137 const SCEV *RHS) {
13138 // zext x u<= sext x, sext x s<= zext x
13139 const SCEV *Op;
13140 switch (Pred) {
13141 case ICmpInst::ICMP_SGE:
13142 std::swap(LHS, RHS);
13143 [[fallthrough]];
13144 case ICmpInst::ICMP_SLE: {
13145 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt.
13146 return match(LHS, m_scev_SExt(m_SCEV(Op))) &&
13148 }
13149 case ICmpInst::ICMP_UGE:
13150 std::swap(LHS, RHS);
13151 [[fallthrough]];
13152 case ICmpInst::ICMP_ULE: {
13153 // If operand >=u 0 then ZExt == SExt. If operand <u 0 then ZExt <u SExt.
13154 return match(LHS, m_scev_ZExt(m_SCEV(Op))) &&
13156 }
13157 default:
13158 return false;
13159 };
13160 llvm_unreachable("unhandled case");
13161}
13162
13163bool ScalarEvolution::isKnownViaNonRecursiveReasoning(CmpPredicate Pred,
13164 SCEVUse LHS,
13165 SCEVUse RHS) {
13166 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
13167 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
13168 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
13169 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
13170 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
13171}
13172
13173bool ScalarEvolution::isImpliedCondOperandsHelper(CmpPredicate Pred,
13174 const SCEV *LHS,
13175 const SCEV *RHS,
13176 const SCEV *FoundLHS,
13177 const SCEV *FoundRHS) {
13178 switch (Pred) {
13179 default:
13180 llvm_unreachable("Unexpected CmpPredicate value!");
13181 case ICmpInst::ICMP_EQ:
13182 case ICmpInst::ICMP_NE:
13183 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
13184 return true;
13185 break;
13186 case ICmpInst::ICMP_SLT:
13187 case ICmpInst::ICMP_SLE:
13188 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
13189 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
13190 return true;
13191 break;
13192 case ICmpInst::ICMP_SGT:
13193 case ICmpInst::ICMP_SGE:
13194 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
13195 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
13196 return true;
13197 break;
13198 case ICmpInst::ICMP_ULT:
13199 case ICmpInst::ICMP_ULE:
13200 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
13201 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
13202 return true;
13203 break;
13204 case ICmpInst::ICMP_UGT:
13205 case ICmpInst::ICMP_UGE:
13206 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
13207 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
13208 return true;
13209 break;
13210 }
13211
13212 // Maybe it can be proved via operations?
13213 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
13214 return true;
13215
13216 return false;
13217}
13218
13219bool ScalarEvolution::isImpliedCondOperandsViaRanges(
13220 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, CmpPredicate FoundPred,
13221 const SCEV *FoundLHS, const SCEV *FoundRHS) {
13222 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
13223 // The restriction on `FoundRHS` be lifted easily -- it exists only to
13224 // reduce the compile time impact of this optimization.
13225 return false;
13226
13227 std::optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
13228 if (!Addend)
13229 return false;
13230
13231 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
13232
13233 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
13234 // antecedent "`FoundLHS` `FoundPred` `FoundRHS`".
13235 ConstantRange FoundLHSRange =
13236 ConstantRange::makeExactICmpRegion(FoundPred, ConstFoundRHS);
13237
13238 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
13239 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
13240
13241 // We can also compute the range of values for `LHS` that satisfy the
13242 // consequent, "`LHS` `Pred` `RHS`":
13243 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
13244 // The antecedent implies the consequent if every value of `LHS` that
13245 // satisfies the antecedent also satisfies the consequent.
13246 return LHSRange.icmp(Pred, ConstRHS);
13247}
13248
13249bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
13250 bool IsSigned) {
13251 assert(isKnownPositive(Stride) && "Positive stride expected!");
13252
13253 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13254 const SCEV *One = getOne(Stride->getType());
13255
13256 if (IsSigned) {
13257 APInt MaxRHS = getSignedRangeMax(RHS);
13258 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
13259 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13260
13261 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
13262 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
13263 }
13264
13265 APInt MaxRHS = getUnsignedRangeMax(RHS);
13266 APInt MaxValue = APInt::getMaxValue(BitWidth);
13267 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13268
13269 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
13270 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
13271}
13272
13273bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
13274 bool IsSigned) {
13275
13276 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13277 const SCEV *One = getOne(Stride->getType());
13278
13279 if (IsSigned) {
13280 APInt MinRHS = getSignedRangeMin(RHS);
13281 APInt MinValue = APInt::getSignedMinValue(BitWidth);
13282 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13283
13284 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
13285 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
13286 }
13287
13288 APInt MinRHS = getUnsignedRangeMin(RHS);
13289 APInt MinValue = APInt::getMinValue(BitWidth);
13290 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13291
13292 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
13293 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
13294}
13295
13297 // umin(N, 1) + floor((N - umin(N, 1)) / D)
13298 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
13299 // expression fixes the case of N=0.
13300 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
13301 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
13302 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
13303}
13304
13305const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
13306 const SCEV *Stride,
13307 const SCEV *End,
13308 unsigned BitWidth,
13309 bool IsSigned) {
13310 // The logic in this function assumes we can represent a positive stride.
13311 // If we can't, the backedge-taken count must be zero.
13312 if (IsSigned && BitWidth == 1)
13313 return getZero(Stride->getType());
13314
13315 // This code below only been closely audited for negative strides in the
13316 // unsigned comparison case, it may be correct for signed comparison, but
13317 // that needs to be established.
13318 if (IsSigned && isKnownNegative(Stride))
13319 return getCouldNotCompute();
13320
13321 // Calculate the maximum backedge count based on the range of values
13322 // permitted by Start, End, and Stride.
13323 APInt MinStart =
13324 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
13325
13326 APInt MinStride =
13327 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
13328
13329 // We assume either the stride is positive, or the backedge-taken count
13330 // is zero. So force StrideForMaxBECount to be at least one.
13331 APInt One(BitWidth, 1);
13332 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
13333 : APIntOps::umax(One, MinStride);
13334
13335 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
13336 : APInt::getMaxValue(BitWidth);
13337 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
13338
13339 // Although End can be a MAX expression we estimate MaxEnd considering only
13340 // the case End = RHS of the loop termination condition. This is safe because
13341 // in the other case (End - Start) is zero, leading to a zero maximum backedge
13342 // taken count.
13343 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
13344 : APIntOps::umin(getUnsignedRangeMax(End), Limit);
13345
13346 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
13347 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
13348 : APIntOps::umax(MaxEnd, MinStart);
13349
13350 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */,
13351 getConstant(StrideForMaxBECount) /* Step */);
13352}
13353
13355ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
13356 const Loop *L, bool IsSigned,
13357 bool ControlsOnlyExit, bool AllowPredicates) {
13359
13361 bool PredicatedIV = false;
13362 if (!IV) {
13363 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
13364 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
13365 if (AR && AR->getLoop() == L && AR->isAffine()) {
13366 auto canProveNUW = [&]() {
13367 // We can use the comparison to infer no-wrap flags only if it fully
13368 // controls the loop exit.
13369 if (!ControlsOnlyExit)
13370 return false;
13371
13372 if (!isLoopInvariant(RHS, L))
13373 return false;
13374
13375 if (!isKnownNonZero(AR->getStepRecurrence(*this)))
13376 // We need the sequence defined by AR to strictly increase in the
13377 // unsigned integer domain for the logic below to hold.
13378 return false;
13379
13380 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
13381 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
13382 // If RHS <=u Limit, then there must exist a value V in the sequence
13383 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
13384 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned
13385 // overflow occurs. This limit also implies that a signed comparison
13386 // (in the wide bitwidth) is equivalent to an unsigned comparison as
13387 // the high bits on both sides must be zero.
13388 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
13389 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
13390 Limit = Limit.zext(OuterBitWidth);
13391 return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit);
13392 };
13393 auto Flags = AR->getNoWrapFlags();
13394 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
13395 Flags = setFlags(Flags, SCEV::FlagNUW);
13396
13397 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
13398 if (AR->hasNoUnsignedWrap()) {
13399 // Emulate what getZeroExtendExpr would have done during construction
13400 // if we'd been able to infer the fact just above at that time.
13401 const SCEV *Step = AR->getStepRecurrence(*this);
13402 Type *Ty = ZExt->getType();
13403 auto *S = getAddRecExpr(
13405 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
13407 }
13408 }
13409 }
13410 }
13411
13412
13413 if (!IV && AllowPredicates) {
13414 // Try to make this an AddRec using runtime tests, in the first X
13415 // iterations of this loop, where X is the SCEV expression found by the
13416 // algorithm below.
13417 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13418 PredicatedIV = true;
13419 }
13420
13421 // Avoid weird loops
13422 if (!IV || IV->getLoop() != L || !IV->isAffine())
13423 return getCouldNotCompute();
13424
13425 // A precondition of this method is that the condition being analyzed
13426 // reaches an exiting branch which dominates the latch. Given that, we can
13427 // assume that an increment which violates the nowrap specification and
13428 // produces poison must cause undefined behavior when the resulting poison
13429 // value is branched upon and thus we can conclude that the backedge is
13430 // taken no more often than would be required to produce that poison value.
13431 // Note that a well defined loop can exit on the iteration which violates
13432 // the nowrap specification if there is another exit (either explicit or
13433 // implicit/exceptional) which causes the loop to execute before the
13434 // exiting instruction we're analyzing would trigger UB.
13435 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13436 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13438
13439 const SCEV *Stride = IV->getStepRecurrence(*this);
13440
13441 bool PositiveStride = isKnownPositive(Stride);
13442
13443 // Avoid negative or zero stride values.
13444 if (!PositiveStride) {
13445 // We can compute the correct backedge taken count for loops with unknown
13446 // strides if we can prove that the loop is not an infinite loop with side
13447 // effects. Here's the loop structure we are trying to handle -
13448 //
13449 // i = start
13450 // do {
13451 // A[i] = i;
13452 // i += s;
13453 // } while (i < end);
13454 //
13455 // The backedge taken count for such loops is evaluated as -
13456 // (max(end, start + stride) - start - 1) /u stride
13457 //
13458 // The additional preconditions that we need to check to prove correctness
13459 // of the above formula is as follows -
13460 //
13461 // a) IV is either nuw or nsw depending upon signedness (indicated by the
13462 // NoWrap flag).
13463 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13464 // no side effects within the loop)
13465 // c) loop has a single static exit (with no abnormal exits)
13466 //
13467 // Precondition a) implies that if the stride is negative, this is a single
13468 // trip loop. The backedge taken count formula reduces to zero in this case.
13469 //
13470 // Precondition b) and c) combine to imply that if rhs is invariant in L,
13471 // then a zero stride means the backedge can't be taken without executing
13472 // undefined behavior.
13473 //
13474 // The positive stride case is the same as isKnownPositive(Stride) returning
13475 // true (original behavior of the function).
13476 //
13477 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
13479 return getCouldNotCompute();
13480
13481 if (!isKnownNonZero(Stride)) {
13482 // If we have a step of zero, and RHS isn't invariant in L, we don't know
13483 // if it might eventually be greater than start and if so, on which
13484 // iteration. We can't even produce a useful upper bound.
13485 if (!isLoopInvariant(RHS, L))
13486 return getCouldNotCompute();
13487
13488 // We allow a potentially zero stride, but we need to divide by stride
13489 // below. Since the loop can't be infinite and this check must control
13490 // the sole exit, we can infer the exit must be taken on the first
13491 // iteration (e.g. backedge count = 0) if the stride is zero. Given that,
13492 // we know the numerator in the divides below must be zero, so we can
13493 // pick an arbitrary non-zero value for the denominator (e.g. stride)
13494 // and produce the right result.
13495 // FIXME: Handle the case where Stride is poison?
13496 auto wouldZeroStrideBeUB = [&]() {
13497 // Proof by contradiction. Suppose the stride were zero. If we can
13498 // prove that the backedge *is* taken on the first iteration, then since
13499 // we know this condition controls the sole exit, we must have an
13500 // infinite loop. We can't have a (well defined) infinite loop per
13501 // check just above.
13502 // Note: The (Start - Stride) term is used to get the start' term from
13503 // (start' + stride,+,stride). Remember that we only care about the
13504 // result of this expression when stride == 0 at runtime.
13505 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
13506 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
13507 };
13508 if (!wouldZeroStrideBeUB()) {
13509 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13510 }
13511 }
13512 } else if (!NoWrap) {
13513 // Avoid proven overflow cases: this will ensure that the backedge taken
13514 // count will not generate any unsigned overflow.
13515 if (canIVOverflowOnLT(RHS, Stride, IsSigned))
13516 return getCouldNotCompute();
13517 }
13518
13519 // On all paths just preceeding, we established the following invariant:
13520 // IV can be assumed not to overflow up to and including the exiting
13521 // iteration. We proved this in one of two ways:
13522 // 1) We can show overflow doesn't occur before the exiting iteration
13523 // 1a) canIVOverflowOnLT, and b) step of one
13524 // 2) We can show that if overflow occurs, the loop must execute UB
13525 // before any possible exit.
13526 // Note that we have not yet proved RHS invariant (in general).
13527
13528 const SCEV *Start = IV->getStart();
13529
13530 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
13531 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
13532 // Use integer-typed versions for actual computation; we can't subtract
13533 // pointers in general.
13534 const SCEV *OrigStart = Start;
13535 const SCEV *OrigRHS = RHS;
13536 if (Start->getType()->isPointerTy()) {
13537 Start = getPtrToAddrExpr(Start);
13538 if (isa<SCEVCouldNotCompute>(Start))
13539 return Start;
13540 }
13541 if (RHS->getType()->isPointerTy()) {
13544 return RHS;
13545 }
13546
13547 const SCEV *End = nullptr, *BECount = nullptr,
13548 *BECountIfBackedgeTaken = nullptr;
13549 if (!isLoopInvariant(RHS, L)) {
13550 const auto *RHSAddRec = dyn_cast<SCEVAddRecExpr>(RHS);
13551 if (PositiveStride && RHSAddRec != nullptr && RHSAddRec->getLoop() == L &&
13552 any(RHSAddRec->getNoWrapFlags())) {
13553 // The structure of loop we are trying to calculate backedge count of:
13554 //
13555 // left = left_start
13556 // right = right_start
13557 //
13558 // while(left < right){
13559 // ... do something here ...
13560 // left += s1; // stride of left is s1 (s1 > 0)
13561 // right += s2; // stride of right is s2 (s2 < 0)
13562 // }
13563 //
13564
13565 const SCEV *RHSStart = RHSAddRec->getStart();
13566 const SCEV *RHSStride = RHSAddRec->getStepRecurrence(*this);
13567
13568 // If Stride - RHSStride is positive and does not overflow, we can write
13569 // backedge count as ->
13570 // ceil((End - Start) /u (Stride - RHSStride))
13571 // Where, End = max(RHSStart, Start)
13572
13573 // Check if RHSStride < 0 and Stride - RHSStride will not overflow.
13574 if (isKnownNegative(RHSStride) &&
13575 willNotOverflow(Instruction::Sub, /*Signed=*/true, Stride,
13576 RHSStride)) {
13577
13578 const SCEV *Denominator = getMinusSCEV(Stride, RHSStride);
13579 if (isKnownPositive(Denominator)) {
13580 End = IsSigned ? getSMaxExpr(RHSStart, Start)
13581 : getUMaxExpr(RHSStart, Start);
13582
13583 // We can do this because End >= Start, as End = max(RHSStart, Start)
13584 const SCEV *Delta = getMinusSCEV(End, Start);
13585
13586 BECount = getUDivCeilSCEV(Delta, Denominator);
13587 BECountIfBackedgeTaken =
13588 getUDivCeilSCEV(getMinusSCEV(RHSStart, Start), Denominator);
13589 }
13590 }
13591 }
13592 if (BECount == nullptr) {
13593 // If we cannot calculate ExactBECount, we can calculate the MaxBECount,
13594 // given the start, stride and max value for the end bound of the
13595 // loop (RHS), and the fact that IV does not overflow (which is
13596 // checked above).
13597 const SCEV *MaxBECount = computeMaxBECountForLT(
13598 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
13599 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
13600 MaxBECount, false /*MaxOrZero*/, Predicates);
13601 }
13602 } else {
13603 // We use the expression (max(End,Start)-Start)/Stride to describe the
13604 // backedge count, as if the backedge is taken at least once
13605 // max(End,Start) is End and so the result is as above, and if not
13606 // max(End,Start) is Start so we get a backedge count of zero.
13607 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
13608 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!");
13609 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
13610 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
13611 // Can we prove (max(RHS,Start) > Start - Stride?
13612 if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) &&
13613 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
13614 // In this case, we can use a refined formula for computing backedge
13615 // taken count. The general formula remains:
13616 // "End-Start /uceiling Stride" where "End = max(RHS,Start)"
13617 // We want to use the alternate formula:
13618 // "((End - 1) - (Start - Stride)) /u Stride"
13619 // Let's do a quick case analysis to show these are equivalent under
13620 // our precondition that max(RHS,Start) > Start - Stride.
13621 // * For RHS <= Start, the backedge-taken count must be zero.
13622 // "((End - 1) - (Start - Stride)) /u Stride" reduces to
13623 // "((Start - 1) - (Start - Stride)) /u Stride" which simplies to
13624 // "Stride - 1 /u Stride" which is indeed zero for all non-zero values
13625 // of Stride. For 0 stride, we've use umin(1,Stride) above,
13626 // reducing this to the stride of 1 case.
13627 // * For RHS >= Start, the backedge count must be "RHS-Start /uceil
13628 // Stride".
13629 // "((End - 1) - (Start - Stride)) /u Stride" reduces to
13630 // "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to
13631 // "((RHS - (Start - Stride) - 1) /u Stride".
13632 // Our preconditions trivially imply no overflow in that form.
13633 const SCEV *MinusOne = getMinusOne(Stride->getType());
13634 const SCEV *Numerator =
13635 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
13636 BECount = getUDivExpr(Numerator, Stride);
13637 }
13638
13639 if (!BECount) {
13640 auto canProveRHSGreaterThanEqualStart = [&]() {
13641 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
13642 const SCEV *GuardedRHS = applyLoopGuards(OrigRHS, L);
13643 const SCEV *GuardedStart = applyLoopGuards(OrigStart, L);
13644
13645 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart) ||
13646 isKnownPredicate(CondGE, GuardedRHS, GuardedStart))
13647 return true;
13648
13649 // (RHS > Start - 1) implies RHS >= Start.
13650 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
13651 // "Start - 1" doesn't overflow.
13652 // * For signed comparison, if Start - 1 does overflow, it's equal
13653 // to INT_MAX, and "RHS >s INT_MAX" is trivially false.
13654 // * For unsigned comparison, if Start - 1 does overflow, it's equal
13655 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
13656 //
13657 // FIXME: Should isLoopEntryGuardedByCond do this for us?
13658 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13659 auto *StartMinusOne =
13660 getAddExpr(OrigStart, getMinusOne(OrigStart->getType()));
13661 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
13662 };
13663
13664 // If we know that RHS >= Start in the context of loop, then we know
13665 // that max(RHS, Start) = RHS at this point.
13666 if (canProveRHSGreaterThanEqualStart()) {
13667 End = RHS;
13668 } else {
13669 // If RHS < Start, the backedge will be taken zero times. So in
13670 // general, we can write the backedge-taken count as:
13671 //
13672 // RHS >= Start ? ceil(RHS - Start) / Stride : 0
13673 //
13674 // We convert it to the following to make it more convenient for SCEV:
13675 //
13676 // ceil(max(RHS, Start) - Start) / Stride
13677 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
13678
13679 // See what would happen if we assume the backedge is taken. This is
13680 // used to compute MaxBECount.
13681 BECountIfBackedgeTaken =
13682 getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
13683 }
13684
13685 // At this point, we know:
13686 //
13687 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
13688 // 2. The index variable doesn't overflow.
13689 //
13690 // Therefore, we know N exists such that
13691 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
13692 // doesn't overflow.
13693 //
13694 // Using this information, try to prove whether the addition in
13695 // "(Start - End) + (Stride - 1)" has unsigned overflow.
13696 const SCEV *One = getOne(Stride->getType());
13697 bool MayAddOverflow = [&] {
13698 if (isKnownToBeAPowerOfTwo(Stride)) {
13699 // Suppose Stride is a power of two, and Start/End are unsigned
13700 // integers. Let UMAX be the largest representable unsigned
13701 // integer.
13702 //
13703 // By the preconditions of this function, we know
13704 // "(Start + Stride * N) >= End", and this doesn't overflow.
13705 // As a formula:
13706 //
13707 // End <= (Start + Stride * N) <= UMAX
13708 //
13709 // Subtracting Start from all the terms:
13710 //
13711 // End - Start <= Stride * N <= UMAX - Start
13712 //
13713 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore:
13714 //
13715 // End - Start <= Stride * N <= UMAX
13716 //
13717 // Stride * N is a multiple of Stride. Therefore,
13718 //
13719 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
13720 //
13721 // Since Stride is a power of two, UMAX + 1 is divisible by
13722 // Stride. Therefore, UMAX mod Stride == Stride - 1. So we can
13723 // write:
13724 //
13725 // End - Start <= Stride * N <= UMAX - Stride - 1
13726 //
13727 // Dropping the middle term:
13728 //
13729 // End - Start <= UMAX - Stride - 1
13730 //
13731 // Adding Stride - 1 to both sides:
13732 //
13733 // (End - Start) + (Stride - 1) <= UMAX
13734 //
13735 // In other words, the addition doesn't have unsigned overflow.
13736 //
13737 // A similar proof works if we treat Start/End as signed values.
13738 // Just rewrite steps before "End - Start <= Stride * N <= UMAX"
13739 // to use signed max instead of unsigned max. Note that we're
13740 // trying to prove a lack of unsigned overflow in either case.
13741 return false;
13742 }
13743 if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
13744 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End
13745 // - 1. If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1
13746 // <u End. If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End -
13747 // 1 <s End.
13748 //
13749 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 ==
13750 // End.
13751 return false;
13752 }
13753 return true;
13754 }();
13755
13756 const SCEV *Delta = getMinusSCEV(End, Start);
13757 if (!MayAddOverflow) {
13758 // floor((D + (S - 1)) / S)
13759 // We prefer this formulation if it's legal because it's fewer
13760 // operations.
13761 BECount =
13762 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13763 } else {
13764 BECount = getUDivCeilSCEV(Delta, Stride);
13765 }
13766 }
13767 }
13768
13769 const SCEV *ConstantMaxBECount;
13770 bool MaxOrZero = false;
13771 if (isa<SCEVConstant>(BECount)) {
13772 ConstantMaxBECount = BECount;
13773 } else if (BECountIfBackedgeTaken &&
13774 isa<SCEVConstant>(BECountIfBackedgeTaken)) {
13775 // If we know exactly how many times the backedge will be taken if it's
13776 // taken at least once, then the backedge count will either be that or
13777 // zero.
13778 ConstantMaxBECount = BECountIfBackedgeTaken;
13779 MaxOrZero = true;
13780 } else {
13781 ConstantMaxBECount = computeMaxBECountForLT(
13782 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
13783 }
13784
13785 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
13786 !isa<SCEVCouldNotCompute>(BECount))
13787 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
13788
13789 const SCEV *SymbolicMaxBECount =
13790 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13791 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
13792 Predicates);
13793}
13794
13795ScalarEvolution::ExitLimit ScalarEvolution::howManyGreaterThans(
13796 const SCEV *LHS, const SCEV *RHS, const Loop *L, bool IsSigned,
13797 bool ControlsOnlyExit, bool AllowPredicates) {
13799 // We handle only IV > Invariant
13800 if (!isLoopInvariant(RHS, L))
13801 return getCouldNotCompute();
13802
13803 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
13804 if (!IV && AllowPredicates)
13805 // Try to make this an AddRec using runtime tests, in the first X
13806 // iterations of this loop, where X is the SCEV expression found by the
13807 // algorithm below.
13808 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13809
13810 // Avoid weird loops
13811 if (!IV || IV->getLoop() != L || !IV->isAffine())
13812 return getCouldNotCompute();
13813
13814 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13815 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13817
13818 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
13819
13820 // Avoid negative or zero stride values
13821 if (!isKnownPositive(Stride))
13822 return getCouldNotCompute();
13823
13824 // Avoid proven overflow cases: this will ensure that the backedge taken count
13825 // will not generate any unsigned overflow. Relaxed no-overflow conditions
13826 // exploit NoWrapFlags, allowing to optimize in presence of undefined
13827 // behaviors like the case of C language.
13828 bool MayAddOverflow = false;
13829 const SCEV *Start = IV->getStart();
13830 const SCEV *End = RHS;
13831 if (!Stride->isOne() && canIVOverflowOnGT(RHS, Stride, IsSigned)) {
13832 if (!NoWrap)
13833 return getCouldNotCompute();
13834 MayAddOverflow = true;
13835 }
13836
13837 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
13838 // If we know that Start >= RHS in the context of loop, then we know that
13839 // min(RHS, Start) = RHS at this point.
13841 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
13842 End = RHS;
13843 else
13844 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
13845 }
13846
13847 if (Start->getType()->isPointerTy()) {
13848 Start = getPtrToAddrExpr(Start);
13849 if (isa<SCEVCouldNotCompute>(Start))
13850 return Start;
13851 }
13852 if (End->getType()->isPointerTy()) {
13853 End = getPtrToAddrExpr(End);
13854 if (isa<SCEVCouldNotCompute>(End))
13855 return End;
13856 }
13857
13858 const SCEV *Delta = getMinusSCEV(Start, End);
13859 const SCEV *BECount;
13860 if (MayAddOverflow) {
13861 // The ceiling division instead needs Start >= End, so that (Start - End) is
13862 // the exact unsigned distance between them.
13864 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, End))
13865 return getCouldNotCompute();
13866 BECount = getUDivCeilSCEV(Delta, Stride);
13867 } else {
13868 // Compute ((Start - End) + (Stride - 1)) / Stride, if the IV cannot
13869 // overflow as it requires fewer operations.
13870 const SCEV *One = getOne(Stride->getType());
13871 BECount = getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13872 }
13873
13874 APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
13876
13877 APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
13878 : getUnsignedRangeMin(Stride);
13879
13880 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
13881 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
13882 : APInt::getMinValue(BitWidth) + (MinStride - 1);
13883
13884 // Although End can be a MIN expression we estimate MinEnd considering only
13885 // the case End = RHS. This is safe because in the other case (Start - End)
13886 // is zero, leading to a zero maximum backedge taken count.
13887 APInt MinEnd =
13888 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
13889 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
13890
13891 const SCEV *ConstantMaxBECount =
13892 isa<SCEVConstant>(BECount)
13893 ? BECount
13894 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd),
13895 getConstant(MinStride));
13896
13897 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount))
13898 ConstantMaxBECount = BECount;
13899 const SCEV *SymbolicMaxBECount =
13900 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13901
13902 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
13903 Predicates);
13904}
13905
13907 ScalarEvolution &SE) const {
13908 if (Range.isFullSet()) // Infinite loop.
13909 return SE.getCouldNotCompute();
13910
13911 // If the start is a non-zero constant, shift the range to simplify things.
13912 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
13913 if (!SC->getValue()->isZero()) {
13915 Operands[0] = SE.getZero(SC->getType());
13916 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
13918 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
13919 return ShiftedAddRec->getNumIterationsInRange(
13920 Range.subtract(SC->getAPInt()), SE);
13921 // This is strange and shouldn't happen.
13922 return SE.getCouldNotCompute();
13923 }
13924
13925 // The only time we can solve this is when we have all constant indices.
13926 // Otherwise, we cannot determine the overflow conditions.
13927 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
13928 return SE.getCouldNotCompute();
13929
13930 // Okay at this point we know that all elements of the chrec are constants and
13931 // that the start element is zero.
13932
13933 // First check to see if the range contains zero. If not, the first
13934 // iteration exits.
13935 unsigned BitWidth = SE.getTypeSizeInBits(getType());
13936 if (!Range.contains(APInt(BitWidth, 0)))
13937 return SE.getZero(getType());
13938
13939 if (isAffine()) {
13940 // If this is an affine expression then we have this situation:
13941 // Solve {0,+,A} in Range === Ax in Range
13942
13943 // We know that zero is in the range. If A is positive then we know that
13944 // the upper value of the range must be the first possible exit value.
13945 // If A is negative then the lower of the range is the last possible loop
13946 // value. Also note that we already checked for a full range.
13947 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
13948 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
13949
13950 // The exit value should be (End+A)/A.
13951 APInt ExitVal = (End + A).udiv(A);
13952 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
13953
13954 // Evaluate at the exit value. If we really did fall out of the valid
13955 // range, then we computed our trip count, otherwise wrap around or other
13956 // things must have happened.
13957 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
13958 if (Range.contains(Val->getValue()))
13959 return SE.getCouldNotCompute(); // Something strange happened
13960
13961 // Ensure that the previous value is in the range.
13962 assert(Range.contains(
13964 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
13965 "Linear scev computation is off in a bad way!");
13966 return SE.getConstant(ExitValue);
13967 }
13968
13969 if (isQuadratic()) {
13970 if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
13971 return SE.getConstant(*S);
13972 }
13973
13974 return SE.getCouldNotCompute();
13975}
13976
13977const SCEVAddRecExpr *
13979 assert(getNumOperands() > 1 && "AddRec with zero step?");
13980 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
13981 // but in this case we cannot guarantee that the value returned will be an
13982 // AddRec because SCEV does not have a fixed point where it stops
13983 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
13984 // may happen if we reach arithmetic depth limit while simplifying. So we
13985 // construct the returned value explicitly.
13987 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
13988 // (this + Step) is {A+B,+,B+C,+...,+,N}.
13989 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
13990 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
13991 // We know that the last operand is not a constant zero (otherwise it would
13992 // have been popped out earlier). This guarantees us that if the result has
13993 // the same last operand, then it will also not be popped out, meaning that
13994 // the returned value will be an AddRec.
13995 const SCEV *Last = getOperand(getNumOperands() - 1);
13996 assert(!Last->isZero() && "Recurrency with zero step?");
13997 Ops.push_back(Last);
14000}
14001
14002// Return true when S contains at least an undef value.
14004 return SCEVExprContains(
14005 S, [](const SCEV *S) { return match(S, m_scev_UndefOrPoison()); });
14006}
14007
14008// Return true when S contains a value that is a nullptr.
14010 return SCEVExprContains(S, [](const SCEV *S) {
14011 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
14012 return SU->getValue() == nullptr;
14013 return false;
14014 });
14015}
14016
14017/// Return the size of an element read or written by Inst.
14019 Type *Ty;
14020 Type *PtrTy;
14021 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
14022 Ty = Store->getValueOperand()->getType();
14023 PtrTy = Store->getPointerOperandType();
14024 } else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
14025 Ty = Load->getType();
14026 PtrTy = Load->getPointerOperandType();
14027 } else {
14028 return nullptr;
14029 }
14030
14031 Type *ETy = getEffectiveSCEVType(PtrTy);
14032 return getSizeOfExpr(ETy, Ty);
14033}
14034
14035//===----------------------------------------------------------------------===//
14036// SCEVCallbackVH Class Implementation
14037//===----------------------------------------------------------------------===//
14038
14040 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14041 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
14042 SE->ConstantEvolutionLoopExitValue.erase(PN);
14043 SE->eraseValueFromMap(getValPtr());
14044 // this now dangles!
14045}
14046
14047void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
14048 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14049
14050 // Forget all the expressions associated with users of the old value,
14051 // so that future queries will recompute the expressions using the new
14052 // value.
14053 SE->forgetValue(getValPtr());
14054 // this now dangles!
14055}
14056
14057ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
14058 : CallbackVH(V), SE(se) {}
14059
14060//===----------------------------------------------------------------------===//
14061// ScalarEvolution Class Implementation
14062//===----------------------------------------------------------------------===//
14063
14066 LoopInfo &LI)
14067 : F(F), DL(F.getDataLayout()), TLI(TLI), AC(AC), DT(DT), LI(LI),
14068 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
14069 LoopDispositions(64), BlockDispositions(64) {
14070 // To use guards for proving predicates, we need to scan every instruction in
14071 // relevant basic blocks, and not just terminators. Doing this is a waste of
14072 // time if the IR does not actually contain any calls to
14073 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
14074 //
14075 // This pessimizes the case where a pass that preserves ScalarEvolution wants
14076 // to _add_ guards to the module when there weren't any before, and wants
14077 // ScalarEvolution to optimize based on those guards. For now we prefer to be
14078 // efficient in lieu of being smart in that rather obscure case.
14079
14080 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
14081 F.getParent(), Intrinsic::experimental_guard);
14082 HasGuards = GuardDecl && !GuardDecl->use_empty();
14083}
14084
14086 : F(Arg.F), DL(Arg.DL), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC),
14087 DT(Arg.DT), LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
14088 ValueExprMap(std::move(Arg.ValueExprMap)),
14089 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
14090 PendingMerges(std::move(Arg.PendingMerges)),
14091 ConstantMultipleCache(std::move(Arg.ConstantMultipleCache)),
14092 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
14093 PredicatedBackedgeTakenCounts(
14094 std::move(Arg.PredicatedBackedgeTakenCounts)),
14095 BECountUsers(std::move(Arg.BECountUsers)),
14096 ConstantEvolutionLoopExitValue(
14097 std::move(Arg.ConstantEvolutionLoopExitValue)),
14098 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
14099 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
14100 LoopDispositions(std::move(Arg.LoopDispositions)),
14101 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
14102 BlockDispositions(std::move(Arg.BlockDispositions)),
14103 SCEVUsers(std::move(Arg.SCEVUsers)),
14104 UnsignedRanges(std::move(Arg.UnsignedRanges)),
14105 SignedRanges(std::move(Arg.SignedRanges)),
14106 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
14107 UniquePreds(std::move(Arg.UniquePreds)),
14108 SCEVAllocator(std::move(Arg.SCEVAllocator)),
14109 ConstantSCEVs(std::move(Arg.ConstantSCEVs)),
14110 LoopUsers(std::move(Arg.LoopUsers)),
14111 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
14112 FirstUnknown(Arg.FirstUnknown) {
14113 Arg.FirstUnknown = nullptr;
14114}
14115
14117 // Iterate through all the SCEVUnknown instances and call their
14118 // destructors, so that they release their references to their values.
14119 for (SCEVUnknown *U = FirstUnknown; U;) {
14120 SCEVUnknown *Tmp = U;
14121 U = U->Next;
14122 Tmp->~SCEVUnknown();
14123 }
14124 FirstUnknown = nullptr;
14125
14126 ExprValueMap.clear();
14127 ValueExprMap.clear();
14128 HasRecMap.clear();
14129 BackedgeTakenCounts.clear();
14130 PredicatedBackedgeTakenCounts.clear();
14131
14132 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
14133 assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
14134 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
14135 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
14136}
14137
14141
14142/// When printing a top-level SCEV for trip counts, it's helpful to include
14143/// a type for constants which are otherwise hard to disambiguate.
14144static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV* S) {
14145 if (isa<SCEVConstant>(S))
14146 OS << *S->getType() << " ";
14147 OS << *S;
14148}
14149
14151 const Loop *L) {
14152 // Print all inner loops first
14153 for (Loop *I : *L)
14154 PrintLoopInfo(OS, SE, I);
14155
14156 OS << "Loop ";
14157 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14158 OS << ": ";
14159
14160 SmallVector<BasicBlock *, 8> ExitingBlocks;
14161 L->getExitingBlocks(ExitingBlocks);
14162 if (ExitingBlocks.size() != 1)
14163 OS << "<multiple exits> ";
14164
14165 auto *BTC = SE->getBackedgeTakenCount(L);
14166 if (!isa<SCEVCouldNotCompute>(BTC)) {
14167 OS << "backedge-taken count is ";
14168 PrintSCEVWithTypeHint(OS, BTC);
14169 } else
14170 OS << "Unpredictable backedge-taken count.";
14171 OS << "\n";
14172
14173 if (ExitingBlocks.size() > 1)
14174 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14175 OS << " exit count for " << ExitingBlock->getName() << ": ";
14176 const SCEV *EC = SE->getExitCount(L, ExitingBlock);
14177 PrintSCEVWithTypeHint(OS, EC);
14178 if (isa<SCEVCouldNotCompute>(EC)) {
14179 // Retry with predicates.
14181 EC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates);
14182 if (!isa<SCEVCouldNotCompute>(EC)) {
14183 OS << "\n predicated exit count for " << ExitingBlock->getName()
14184 << ": ";
14185 PrintSCEVWithTypeHint(OS, EC);
14186 OS << "\n Predicates:\n";
14187 for (const auto *P : Predicates)
14188 P->print(OS, 4);
14189 }
14190 }
14191 OS << "\n";
14192 }
14193
14194 OS << "Loop ";
14195 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14196 OS << ": ";
14197
14198 auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
14199 if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
14200 OS << "constant max backedge-taken count is ";
14201 PrintSCEVWithTypeHint(OS, ConstantBTC);
14203 OS << ", actual taken count either this or zero.";
14204 } else {
14205 OS << "Unpredictable constant max backedge-taken count. ";
14206 }
14207
14208 OS << "\n"
14209 "Loop ";
14210 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14211 OS << ": ";
14212
14213 auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
14214 if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
14215 OS << "symbolic max backedge-taken count is ";
14216 PrintSCEVWithTypeHint(OS, SymbolicBTC);
14218 OS << ", actual taken count either this or zero.";
14219 } else {
14220 OS << "Unpredictable symbolic max backedge-taken count. ";
14221 }
14222 OS << "\n";
14223
14224 if (ExitingBlocks.size() > 1)
14225 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14226 OS << " symbolic max exit count for " << ExitingBlock->getName() << ": ";
14227 auto *ExitBTC = SE->getExitCount(L, ExitingBlock,
14229 PrintSCEVWithTypeHint(OS, ExitBTC);
14230 if (isa<SCEVCouldNotCompute>(ExitBTC)) {
14231 // Retry with predicates.
14233 ExitBTC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates,
14235 if (!isa<SCEVCouldNotCompute>(ExitBTC)) {
14236 OS << "\n predicated symbolic max exit count for "
14237 << ExitingBlock->getName() << ": ";
14238 PrintSCEVWithTypeHint(OS, ExitBTC);
14239 OS << "\n Predicates:\n";
14240 for (const auto *P : Predicates)
14241 P->print(OS, 4);
14242 }
14243 }
14244 OS << "\n";
14245 }
14246
14248 auto *PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
14249 if (PBT != BTC) {
14250 OS << "Loop ";
14251 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14252 OS << ": ";
14253 if (!isa<SCEVCouldNotCompute>(PBT)) {
14254 OS << "Predicated backedge-taken count is ";
14255 PrintSCEVWithTypeHint(OS, PBT);
14256 } else
14257 OS << "Unpredictable predicated backedge-taken count.";
14258 OS << "\n";
14259 OS << " Predicates:\n";
14260 for (const auto *P : Preds)
14261 P->print(OS, 4);
14262 }
14263 Preds.clear();
14264
14265 auto *PredConstantMax =
14267 if (PredConstantMax != ConstantBTC) {
14268 OS << "Loop ";
14269 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14270 OS << ": ";
14271 if (!isa<SCEVCouldNotCompute>(PredConstantMax)) {
14272 OS << "Predicated constant max backedge-taken count is ";
14273 PrintSCEVWithTypeHint(OS, PredConstantMax);
14274 } else
14275 OS << "Unpredictable predicated constant max backedge-taken count.";
14276 OS << "\n";
14277 OS << " Predicates:\n";
14278 for (const auto *P : Preds)
14279 P->print(OS, 4);
14280 }
14281 Preds.clear();
14282
14283 auto *PredSymbolicMax =
14285 if (SymbolicBTC != PredSymbolicMax) {
14286 OS << "Loop ";
14287 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14288 OS << ": ";
14289 if (!isa<SCEVCouldNotCompute>(PredSymbolicMax)) {
14290 OS << "Predicated symbolic max backedge-taken count is ";
14291 PrintSCEVWithTypeHint(OS, PredSymbolicMax);
14292 } else
14293 OS << "Unpredictable predicated symbolic max backedge-taken count.";
14294 OS << "\n";
14295 OS << " Predicates:\n";
14296 for (const auto *P : Preds)
14297 P->print(OS, 4);
14298 }
14299
14301 OS << "Loop ";
14302 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14303 OS << ": ";
14304 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
14305 }
14306}
14307
14308namespace llvm {
14309// Note: these overloaded operators need to be in the llvm namespace for them
14310// to be resolved correctly. If we put them outside the llvm namespace, the
14311//
14312// OS << ": " << SE.getLoopDisposition(SV, InnerL);
14313//
14314// code below "breaks" and start printing raw enum values as opposed to the
14315// string values.
14318 switch (LD) {
14320 OS << "Variant";
14321 break;
14323 OS << "Invariant";
14324 break;
14326 OS << "Uniform";
14327 break;
14329 OS << "Computable";
14330 break;
14331 }
14332 return OS;
14333}
14334
14337 switch (BD) {
14339 OS << "DoesNotDominate";
14340 break;
14342 OS << "Dominates";
14343 break;
14345 OS << "ProperlyDominates";
14346 break;
14347 }
14348 return OS;
14349}
14350} // namespace llvm
14351
14353 // ScalarEvolution's implementation of the print method is to print
14354 // out SCEV values of all instructions that are interesting. Doing
14355 // this potentially causes it to create new SCEV objects though,
14356 // which technically conflicts with the const qualifier. This isn't
14357 // observable from outside the class though, so casting away the
14358 // const isn't dangerous.
14359 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14360
14361 if (ClassifyExpressions) {
14362 OS << "Classifying expressions for: ";
14363 F.printAsOperand(OS, /*PrintType=*/false);
14364 OS << "\n";
14365 for (Instruction &I : instructions(F))
14366 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
14367 OS << I << '\n';
14368 OS << " --> ";
14369 const SCEV *SV = SE.getSCEV(&I);
14370 SV->print(OS);
14371 if (!isa<SCEVCouldNotCompute>(SV)) {
14372 OS << " U: ";
14373 SE.getUnsignedRange(SV).print(OS);
14374 OS << " S: ";
14375 SE.getSignedRange(SV).print(OS);
14376 }
14377
14378 const Loop *L = LI.getLoopFor(I.getParent());
14379
14380 SCEVUse AtUse = SE.getSCEVAtScope(SV, L);
14381 if (AtUse != SV) {
14382 OS << " --> ";
14383 OS << AtUse;
14384 if (!isa<SCEVCouldNotCompute>(AtUse)) {
14385 OS << " U: ";
14386 SE.getUnsignedRange(AtUse).print(OS);
14387 OS << " S: ";
14388 SE.getSignedRange(AtUse).print(OS);
14389 }
14390 }
14391
14392 if (L) {
14393 OS << "\t\t" "Exits: ";
14394 SCEVUse ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
14395 if (!SE.isLoopInvariant(ExitValue, L)) {
14396 OS << "<<Unknown>>";
14397 } else {
14398 OS << ExitValue;
14399 }
14400
14401 ListSeparator LS(", ", "\t\tLoopDispositions: { ");
14402 for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
14403 OS << LS;
14404 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14405 OS << ": " << SE.getLoopDisposition(SV, Iter);
14406 }
14407
14408 for (const auto *InnerL : depth_first(L)) {
14409 if (InnerL == L)
14410 continue;
14411 OS << LS;
14412 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14413 OS << ": " << SE.getLoopDisposition(SV, InnerL);
14414 }
14415
14416 OS << " }";
14417 }
14418
14419 OS << "\n";
14420 }
14421 }
14422
14423 OS << "Determining loop execution counts for: ";
14424 F.printAsOperand(OS, /*PrintType=*/false);
14425 OS << "\n";
14426 for (Loop *I : LI)
14427 PrintLoopInfo(OS, &SE, I);
14428}
14429
14432 auto &Values = LoopDispositions[S];
14433 for (auto &V : Values) {
14434 if (V.getPointer() == L)
14435 return V.getInt();
14436 }
14437 Values.emplace_back(L, LoopVariant);
14438 LoopDisposition D = computeLoopDisposition(S, L);
14439 auto &Values2 = LoopDispositions[S];
14440 for (auto &V : llvm::reverse(Values2)) {
14441 if (V.getPointer() == L) {
14442 V.setInt(D);
14443 break;
14444 }
14445 }
14446 return D;
14447}
14448
14450ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
14451 switch (S->getSCEVType()) {
14452 case scConstant:
14453 case scVScale:
14454 return LoopInvariant;
14455 case scAddRecExpr: {
14456 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14457
14458 // If L is the addrec's loop, it's computable.
14459 if (AR->getLoop() == L)
14460 return LoopComputable;
14461
14462 // Add recurrences are never invariant in the function-body (null loop).
14463 if (!L)
14464 return LoopVariant;
14465
14466 // Everything that is not defined at loop entry is variant.
14467 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) {
14468 if (L->contains(AR->getLoop()) &&
14469 llvm::all_of(AR->operands(),
14470 [&](const SCEV *Op) { return isLoopUniform(Op, L); }))
14471 return LoopUniform;
14472
14473 return LoopVariant;
14474 }
14475 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
14476 " dominate the contained loop's header?");
14477
14478 // This recurrence is invariant w.r.t. L if AR's loop contains L.
14479 if (AR->getLoop()->contains(L))
14480 return LoopInvariant;
14481
14482 // This recurrence is variant w.r.t. L if any of its operands
14483 // are variant.
14484 for (SCEVUse Op : AR->operands())
14485 if (!isLoopInvariant(Op, L))
14486 return LoopVariant;
14487
14488 // Otherwise it's loop-invariant.
14489 return LoopInvariant;
14490 }
14491 case scTruncate:
14492 case scZeroExtend:
14493 case scSignExtend:
14494 case scPtrToAddr:
14495 case scAddExpr:
14496 case scMulExpr:
14497 case scUDivExpr:
14498 case scUMaxExpr:
14499 case scSMaxExpr:
14500 case scUMinExpr:
14501 case scSMinExpr:
14502 case scSequentialUMinExpr: {
14503 bool HasVarying = false;
14504 bool HasUniform = false;
14505 for (SCEVUse Op : S->operands()) {
14507 if (D == LoopVariant)
14508 return LoopVariant;
14509 if (D == LoopComputable)
14510 HasVarying = true;
14511 if (D == LoopUniform)
14512 HasUniform = true;
14513 }
14514 return HasVarying ? (HasUniform ? LoopVariant : LoopComputable)
14515 : (HasUniform ? LoopUniform : LoopInvariant);
14516 }
14517 case scUnknown:
14518 // All non-instruction values are loop invariant. All instructions are loop
14519 // invariant if they are not contained in the specified loop.
14520 // Instructions are never considered invariant in the function body
14521 // (null loop) because they are defined within the "loop".
14523 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
14524 return LoopInvariant;
14525 case scCouldNotCompute:
14526 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14527 }
14528 llvm_unreachable("Unknown SCEV kind!");
14529}
14530
14531bool ScalarEvolution::isLoopUniform(const SCEV *S, const Loop *L) {
14533 return D == LoopUniform || D == LoopInvariant;
14534}
14535
14537 return getLoopDisposition(S, L) == LoopInvariant;
14538}
14539
14541 return getLoopDisposition(S, L) == LoopComputable;
14542}
14543
14546 auto &Values = BlockDispositions[S];
14547 for (auto &V : Values) {
14548 if (V.getPointer() == BB)
14549 return V.getInt();
14550 }
14551 Values.emplace_back(BB, DoesNotDominateBlock);
14552 BlockDisposition D = computeBlockDisposition(S, BB);
14553 auto &Values2 = BlockDispositions[S];
14554 for (auto &V : llvm::reverse(Values2)) {
14555 if (V.getPointer() == BB) {
14556 V.setInt(D);
14557 break;
14558 }
14559 }
14560 return D;
14561}
14562
14564ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
14565 switch (S->getSCEVType()) {
14566 case scConstant:
14567 case scVScale:
14569 case scAddRecExpr: {
14570 // This uses a "dominates" query instead of "properly dominates" query
14571 // to test for proper dominance too, because the instruction which
14572 // produces the addrec's value is a PHI, and a PHI effectively properly
14573 // dominates its entire containing block.
14574 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14575 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
14576 return DoesNotDominateBlock;
14577
14578 // Fall through into SCEVNAryExpr handling.
14579 [[fallthrough]];
14580 }
14581 case scTruncate:
14582 case scZeroExtend:
14583 case scSignExtend:
14584 case scPtrToAddr:
14585 case scAddExpr:
14586 case scMulExpr:
14587 case scUDivExpr:
14588 case scUMaxExpr:
14589 case scSMaxExpr:
14590 case scUMinExpr:
14591 case scSMinExpr:
14592 case scSequentialUMinExpr: {
14593 bool Proper = true;
14594 for (const SCEV *NAryOp : S->operands()) {
14596 if (D == DoesNotDominateBlock)
14597 return DoesNotDominateBlock;
14598 if (D == DominatesBlock)
14599 Proper = false;
14600 }
14601 return Proper ? ProperlyDominatesBlock : DominatesBlock;
14602 }
14603 case scUnknown:
14604 if (Instruction *I =
14606 if (I->getParent() == BB)
14607 return DominatesBlock;
14608 if (DT.properlyDominates(I->getParent(), BB))
14610 return DoesNotDominateBlock;
14611 }
14613 case scCouldNotCompute:
14614 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14615 }
14616 llvm_unreachable("Unknown SCEV kind!");
14617}
14618
14619bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
14620 return getBlockDisposition(S, BB) >= DominatesBlock;
14621}
14622
14625}
14626
14627bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
14628 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
14629}
14630
14631void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
14632 bool Predicated) {
14633 auto &BECounts =
14634 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14635 auto It = BECounts.find(L);
14636 if (It != BECounts.end()) {
14637 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
14638 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14639 if (!isa<SCEVConstant>(S)) {
14640 auto UserIt = BECountUsers.find(S);
14641 assert(UserIt != BECountUsers.end());
14642 UserIt->second.erase({L, Predicated});
14643 }
14644 }
14645 }
14646 BECounts.erase(It);
14647 }
14648}
14649
14650void ScalarEvolution::forgetMemoizedResults(ArrayRef<SCEVUse> SCEVs) {
14651 SmallPtrSet<const SCEV *, 8> ToForget(llvm::from_range, SCEVs);
14652 SmallVector<SCEVUse, 8> Worklist(ToForget.begin(), ToForget.end());
14653
14654 while (!Worklist.empty()) {
14655 const SCEV *Curr = Worklist.pop_back_val();
14656 auto Users = SCEVUsers.find(Curr);
14657 if (Users != SCEVUsers.end())
14658 for (const auto *User : Users->second)
14659 if (ToForget.insert(User).second)
14660 Worklist.push_back(User);
14661 }
14662
14663 for (const auto *S : ToForget)
14664 forgetMemoizedResultsImpl(S);
14665
14666 PredicatedSCEVRewrites.remove_if(
14667 [&](const auto &Entry) { return ToForget.count(Entry.first.first); });
14668}
14669
14670void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
14671 LoopDispositions.erase(S);
14672 BlockDispositions.erase(S);
14673 UnsignedRanges.erase(S);
14674 SignedRanges.erase(S);
14675 HasRecMap.erase(S);
14676 ConstantMultipleCache.erase(S);
14677
14678 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
14679 UnsignedWrapViaInductionTried.erase(AR);
14680 SignedWrapViaInductionTried.erase(AR);
14681 }
14682
14683 auto ExprIt = ExprValueMap.find(S);
14684 if (ExprIt != ExprValueMap.end()) {
14685 for (Value *V : ExprIt->second) {
14686 auto ValueIt = ValueExprMap.find_as(V);
14687 if (ValueIt != ValueExprMap.end())
14688 ValueExprMap.erase(ValueIt);
14689 }
14690 ExprValueMap.erase(ExprIt);
14691 }
14692
14693 auto ScopeIt = ValuesAtScopes.find(S);
14694 if (ScopeIt != ValuesAtScopes.end()) {
14695 for (const auto &Pair : ScopeIt->second)
14696 if (!isa_and_nonnull<SCEVConstant>(Pair.second))
14697 llvm::erase(ValuesAtScopesUsers[Pair.second],
14698 std::make_pair(Pair.first, S));
14699 ValuesAtScopes.erase(ScopeIt);
14700 }
14701
14702 auto ScopeUserIt = ValuesAtScopesUsers.find(S);
14703 if (ScopeUserIt != ValuesAtScopesUsers.end()) {
14704 for (const auto &Pair : ScopeUserIt->second)
14705 llvm::erase(ValuesAtScopes[Pair.second], std::make_pair(Pair.first, S));
14706 ValuesAtScopesUsers.erase(ScopeUserIt);
14707 }
14708
14709 auto BEUsersIt = BECountUsers.find(S);
14710 if (BEUsersIt != BECountUsers.end()) {
14711 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
14712 auto Copy = BEUsersIt->second;
14713 for (const auto &Pair : Copy)
14714 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
14715 BECountUsers.erase(BEUsersIt);
14716 }
14717
14718 auto FoldUser = FoldCacheUser.find(S);
14719 if (FoldUser != FoldCacheUser.end())
14720 for (auto &KV : FoldUser->second)
14721 FoldCache.erase(KV);
14722 FoldCacheUser.erase(S);
14723}
14724
14725void
14726ScalarEvolution::getUsedLoops(const SCEV *S,
14727 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
14728 struct FindUsedLoops {
14729 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
14730 : LoopsUsed(LoopsUsed) {}
14731 SmallPtrSetImpl<const Loop *> &LoopsUsed;
14732 bool follow(const SCEV *S) {
14733 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
14734 LoopsUsed.insert(AR->getLoop());
14735 return true;
14736 }
14737
14738 bool isDone() const { return false; }
14739 };
14740
14741 FindUsedLoops F(LoopsUsed);
14742 SCEVTraversal<FindUsedLoops>(F).visitAll(S);
14743}
14744
14745void ScalarEvolution::getReachableBlocks(
14748 Worklist.push_back(&F.getEntryBlock());
14749 while (!Worklist.empty()) {
14750 BasicBlock *BB = Worklist.pop_back_val();
14751 if (!Reachable.insert(BB).second)
14752 continue;
14753
14754 Value *Cond;
14755 BasicBlock *TrueBB, *FalseBB;
14756 if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
14757 m_BasicBlock(FalseBB)))) {
14758 if (auto *C = dyn_cast<ConstantInt>(Cond)) {
14759 Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
14760 continue;
14761 }
14762
14763 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14764 const SCEV *L = getSCEV(Cmp->getOperand(0));
14765 const SCEV *R = getSCEV(Cmp->getOperand(1));
14766 if (isKnownPredicateViaConstantRanges(Cmp->getCmpPredicate(), L, R)) {
14767 Worklist.push_back(TrueBB);
14768 continue;
14769 }
14770 if (isKnownPredicateViaConstantRanges(Cmp->getInverseCmpPredicate(), L,
14771 R)) {
14772 Worklist.push_back(FalseBB);
14773 continue;
14774 }
14775 }
14776 }
14777
14778 append_range(Worklist, successors(BB));
14779 }
14780}
14781
14783 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14784 ScalarEvolution SE2(F, TLI, AC, DT, LI);
14785
14786 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
14787
14788 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
14789 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
14790 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
14791
14792 const SCEV *visitConstant(const SCEVConstant *Constant) {
14793 return SE.getConstant(Constant->getAPInt());
14794 }
14795
14796 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14797 return SE.getUnknown(Expr->getValue());
14798 }
14799
14800 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
14801 return SE.getCouldNotCompute();
14802 }
14803 };
14804
14805 SCEVMapper SCM(SE2);
14806 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
14807 SE2.getReachableBlocks(ReachableBlocks, F);
14808
14809 auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
14810 if (containsUndefs(Old) || containsUndefs(New)) {
14811 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
14812 // not propagate undef aggressively). This means we can (and do) fail
14813 // verification in cases where a transform makes a value go from "undef"
14814 // to "undef+1" (say). The transform is fine, since in both cases the
14815 // result is "undef", but SCEV thinks the value increased by 1.
14816 return nullptr;
14817 }
14818
14819 // Unless VerifySCEVStrict is set, we only compare constant deltas.
14820 const SCEV *Delta = SE2.getMinusSCEV(Old, New);
14821 if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
14822 return nullptr;
14823
14824 return Delta;
14825 };
14826
14827 while (!LoopStack.empty()) {
14828 auto *L = LoopStack.pop_back_val();
14829 llvm::append_range(LoopStack, *L);
14830
14831 // Only verify BECounts in reachable loops. For an unreachable loop,
14832 // any BECount is legal.
14833 if (!ReachableBlocks.contains(L->getHeader()))
14834 continue;
14835
14836 // Only verify cached BECounts. Computing new BECounts may change the
14837 // results of subsequent SCEV uses.
14838 auto It = BackedgeTakenCounts.find(L);
14839 if (It == BackedgeTakenCounts.end())
14840 continue;
14841
14842 auto *CurBECount =
14843 SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
14844 auto *NewBECount = SE2.getBackedgeTakenCount(L);
14845
14846 if (CurBECount == SE2.getCouldNotCompute() ||
14847 NewBECount == SE2.getCouldNotCompute()) {
14848 // NB! This situation is legal, but is very suspicious -- whatever pass
14849 // change the loop to make a trip count go from could not compute to
14850 // computable or vice-versa *should have* invalidated SCEV. However, we
14851 // choose not to assert here (for now) since we don't want false
14852 // positives.
14853 continue;
14854 }
14855
14856 if (SE.getTypeSizeInBits(CurBECount->getType()) >
14857 SE.getTypeSizeInBits(NewBECount->getType()))
14858 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
14859 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
14860 SE.getTypeSizeInBits(NewBECount->getType()))
14861 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
14862
14863 const SCEV *Delta = GetDelta(CurBECount, NewBECount);
14864 if (Delta && !Delta->isZero()) {
14865 dbgs() << "Trip Count for " << *L << " Changed!\n";
14866 dbgs() << "Old: " << *CurBECount << "\n";
14867 dbgs() << "New: " << *NewBECount << "\n";
14868 dbgs() << "Delta: " << *Delta << "\n";
14869 std::abort();
14870 }
14871 }
14872
14873 // Collect all valid loops currently in LoopInfo.
14874 SmallPtrSet<Loop *, 32> ValidLoops;
14875 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
14876 while (!Worklist.empty()) {
14877 Loop *L = Worklist.pop_back_val();
14878 if (ValidLoops.insert(L).second)
14879 Worklist.append(L->begin(), L->end());
14880 }
14881 for (const auto &KV : ValueExprMap) {
14882#ifndef NDEBUG
14883 // Check for SCEV expressions referencing invalid/deleted loops.
14884 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14885 assert(ValidLoops.contains(AR->getLoop()) &&
14886 "AddRec references invalid loop");
14887 }
14888#endif
14889
14890 // Check that the value is also part of the reverse map.
14891 auto It = ExprValueMap.find(KV.second);
14892 if (It == ExprValueMap.end() || !It->second.contains(KV.first)) {
14893 dbgs() << "Value " << *KV.first
14894 << " is in ValueExprMap but not in ExprValueMap\n";
14895 std::abort();
14896 }
14897
14898 if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
14899 if (!ReachableBlocks.contains(I->getParent()))
14900 continue;
14901 const SCEV *OldSCEV = SCM.visit(KV.second);
14902 const SCEV *NewSCEV = SE2.getSCEV(I);
14903 const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14904 if (Delta && !Delta->isZero()) {
14905 dbgs() << "SCEV for value " << *I << " changed!\n"
14906 << "Old: " << *OldSCEV << "\n"
14907 << "New: " << *NewSCEV << "\n"
14908 << "Delta: " << *Delta << "\n";
14909 std::abort();
14910 }
14911 }
14912 }
14913
14914 for (const auto &KV : ExprValueMap) {
14915 for (Value *V : KV.second) {
14916 const SCEV *S = ValueExprMap.lookup(V);
14917 if (!S) {
14918 dbgs() << "Value " << *V
14919 << " is in ExprValueMap but not in ValueExprMap\n";
14920 std::abort();
14921 }
14922 if (S != KV.first) {
14923 dbgs() << "Value " << *V << " mapped to " << *S << " rather than "
14924 << *KV.first << "\n";
14925 std::abort();
14926 }
14927 }
14928 }
14929
14930 // Verify integrity of SCEV users.
14931 for (const auto &S : UniqueSCEVs) {
14932 for (SCEVUse Op : S.operands()) {
14933 // We do not store dependencies of constants.
14934 if (isa<SCEVConstant>(Op))
14935 continue;
14936 auto It = SCEVUsers.find(Op);
14937 if (It != SCEVUsers.end() && It->second.count(&S))
14938 continue;
14939 dbgs() << "Use of operand " << *Op << " by user " << S
14940 << " is not being tracked!\n";
14941 std::abort();
14942 }
14943 }
14944
14945 // Verify integrity of ValuesAtScopes users.
14946 for (const auto &ValueAndVec : ValuesAtScopes) {
14947 const SCEV *Value = ValueAndVec.first;
14948 for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
14949 const Loop *L = LoopAndValueAtScope.first;
14950 const SCEV *ValueAtScope = LoopAndValueAtScope.second;
14951 if (!isa<SCEVConstant>(ValueAtScope)) {
14952 auto It = ValuesAtScopesUsers.find(ValueAtScope);
14953 if (It != ValuesAtScopesUsers.end() &&
14954 is_contained(It->second, std::make_pair(L, Value)))
14955 continue;
14956 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14957 << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
14958 std::abort();
14959 }
14960 }
14961 }
14962
14963 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
14964 const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
14965 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
14966 const Loop *L = LoopAndValue.first;
14967 const SCEV *Value = LoopAndValue.second;
14969 auto It = ValuesAtScopes.find(Value);
14970 if (It != ValuesAtScopes.end() &&
14971 is_contained(It->second, std::make_pair(L, ValueAtScope)))
14972 continue;
14973 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14974 << *ValueAtScope << " missing in ValuesAtScopes\n";
14975 std::abort();
14976 }
14977 }
14978
14979 // Verify integrity of BECountUsers.
14980 auto VerifyBECountUsers = [&](bool Predicated) {
14981 auto &BECounts =
14982 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14983 for (const auto &LoopAndBEInfo : BECounts) {
14984 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
14985 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14986 if (!isa<SCEVConstant>(S)) {
14987 auto UserIt = BECountUsers.find(S);
14988 if (UserIt != BECountUsers.end() &&
14989 UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
14990 continue;
14991 dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
14992 << " missing from BECountUsers\n";
14993 std::abort();
14994 }
14995 }
14996 }
14997 }
14998 };
14999 VerifyBECountUsers(/* Predicated */ false);
15000 VerifyBECountUsers(/* Predicated */ true);
15001
15002 // Verify intergity of loop disposition cache.
15003 for (auto &[S, Values] : LoopDispositions) {
15004 for (auto [Loop, CachedDisposition] : Values) {
15005 const auto RecomputedDisposition = SE2.getLoopDisposition(S, Loop);
15006 if (CachedDisposition != RecomputedDisposition) {
15007 dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
15008 << " is incorrect: cached " << CachedDisposition << ", actual "
15009 << RecomputedDisposition << "\n";
15010 std::abort();
15011 }
15012 }
15013 }
15014
15015 // Verify integrity of the block disposition cache.
15016 for (auto &[S, Values] : BlockDispositions) {
15017 for (auto [BB, CachedDisposition] : Values) {
15018 const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
15019 if (CachedDisposition != RecomputedDisposition) {
15020 dbgs() << "Cached disposition of " << *S << " for block %"
15021 << BB->getName() << " is incorrect: cached " << CachedDisposition
15022 << ", actual " << RecomputedDisposition << "\n";
15023 std::abort();
15024 }
15025 }
15026 }
15027
15028 // Verify FoldCache/FoldCacheUser caches.
15029 for (auto [FoldID, Expr] : FoldCache) {
15030 auto I = FoldCacheUser.find(Expr);
15031 if (I == FoldCacheUser.end()) {
15032 dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
15033 << "!\n";
15034 std::abort();
15035 }
15036 if (!is_contained(I->second, FoldID)) {
15037 dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
15038 std::abort();
15039 }
15040 }
15041 for (auto [Expr, IDs] : FoldCacheUser) {
15042 for (auto &FoldID : IDs) {
15043 const SCEV *S = FoldCache.lookup(FoldID);
15044 if (!S) {
15045 dbgs() << "Missing entry in FoldCache for expression " << *Expr
15046 << "!\n";
15047 std::abort();
15048 }
15049 if (S != Expr) {
15050 dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: " << *S
15051 << " != " << *Expr << "!\n";
15052 std::abort();
15053 }
15054 }
15055 }
15056
15057 // Verify that ConstantMultipleCache computations are correct. We check that
15058 // cached multiples and recomputed multiples are multiples of each other to
15059 // verify correctness. It is possible that a recomputed multiple is different
15060 // from the cached multiple due to strengthened no wrap flags or changes in
15061 // KnownBits computations.
15062 for (auto [S, Multiple] : ConstantMultipleCache) {
15063 APInt RecomputedMultiple = SE2.getConstantMultiple(S);
15064 if ((Multiple != 0 && RecomputedMultiple != 0 &&
15065 Multiple.urem(RecomputedMultiple) != 0 &&
15066 RecomputedMultiple.urem(Multiple) != 0)) {
15067 dbgs() << "Incorrect cached computation in ConstantMultipleCache for "
15068 << *S << " : Computed " << RecomputedMultiple
15069 << " but cache contains " << Multiple << "!\n";
15070 std::abort();
15071 }
15072 }
15073}
15074
15076 Function &F, const PreservedAnalyses &PA,
15077 FunctionAnalysisManager::Invalidator &Inv) {
15078 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
15079 // of its dependencies is invalidated.
15080 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
15081 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
15082 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
15083 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
15084 Inv.invalidate<LoopAnalysis>(F, PA);
15085}
15086
15087AnalysisKey ScalarEvolutionAnalysis::Key;
15088
15091 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
15092 auto &AC = AM.getResult<AssumptionAnalysis>(F);
15093 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
15094 auto &LI = AM.getResult<LoopAnalysis>(F);
15095 return ScalarEvolution(F, TLI, AC, DT, LI);
15096}
15097
15103
15106 // For compatibility with opt's -analyze feature under legacy pass manager
15107 // which was not ported to NPM. This keeps tests using
15108 // update_analyze_test_checks.py working.
15109 OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
15110 << F.getName() << "':\n";
15112 return PreservedAnalyses::all();
15113}
15114
15116 "Scalar Evolution Analysis", false, true)
15122 "Scalar Evolution Analysis", false, true)
15123
15124char ScalarEvolutionWrapperPass::ID = 0;
15125
15127
15129 SE.reset(new ScalarEvolution(
15131 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
15133 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
15134 return false;
15135}
15136
15138
15140 SE->print(OS);
15141}
15142
15144 if (!VerifySCEV)
15145 return;
15146
15147 SE->verify();
15148}
15149
15157
15159 const SCEV *RHS) {
15160 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
15161}
15162
15163const SCEVPredicate *
15165 const SCEV *LHS, const SCEV *RHS) {
15167 assert(LHS->getType() == RHS->getType() &&
15168 "Type mismatch between LHS and RHS");
15169 // Unique this node based on the arguments
15170 ID.AddInteger(SCEVPredicate::P_Compare);
15171 ID.AddInteger(Pred);
15172 ID.AddPointer(LHS);
15173 ID.AddPointer(RHS);
15174 void *IP = nullptr;
15175 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
15176 return S;
15177 SCEVComparePredicate *Eq = new (SCEVAllocator)
15178 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
15179 UniquePreds.InsertNode(Eq, IP);
15180 return Eq;
15181}
15182
15184 const SCEVAddRecExpr *AR,
15187 // Unique this node based on the arguments
15189 ID.AddPointer(AR);
15190 ID.AddInteger(AddedFlags);
15191 void *IP = nullptr;
15192 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
15193 return S;
15194 auto *OF = new (SCEVAllocator)
15195 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
15196 UniquePreds.InsertNode(OF, IP);
15197 return OF;
15198}
15199
15200namespace {
15201
15202class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
15203public:
15204
15205 /// Rewrites \p S in the context of a loop L and the SCEV predication
15206 /// infrastructure.
15207 ///
15208 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
15209 /// equivalences present in \p Pred.
15210 ///
15211 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
15212 /// \p NewPreds such that the result will be an AddRecExpr.
15213 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
15215 const SCEVPredicate *Pred) {
15216 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
15217 return Rewriter.visit(S);
15218 }
15219
15220 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
15221 if (Pred) {
15222 if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
15223 for (const auto *Pred : U->getPredicates())
15224 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
15225 if (IPred->getLHS() == Expr &&
15226 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15227 return IPred->getRHS();
15228 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
15229 if (IPred->getLHS() == Expr &&
15230 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15231 return IPred->getRHS();
15232 }
15233 }
15234 return convertToAddRecWithPreds(Expr);
15235 }
15236
15237 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
15238 const SCEV *Operand = visit(Expr->getOperand());
15239 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15240 if (AR && AR->getLoop() == L && AR->isAffine()) {
15241 // This couldn't be folded because the operand didn't have the nuw
15242 // flag. Add the nusw flag as an assumption that we could make.
15243 const SCEV *Step = AR->getStepRecurrence(SE);
15244 Type *Ty = Expr->getType();
15245 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
15246 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
15247 SE.getSignExtendExpr(Step, Ty), L,
15248 AR->getNoWrapFlags());
15249 }
15250 return SE.getZeroExtendExpr(Operand, Expr->getType());
15251 }
15252
15253 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
15254 const SCEV *Operand = visit(Expr->getOperand());
15255 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15256 if (AR && AR->getLoop() == L && AR->isAffine()) {
15257 // This couldn't be folded because the operand didn't have the nsw
15258 // flag. Add the nssw flag as an assumption that we could make.
15259 const SCEV *Step = AR->getStepRecurrence(SE);
15260 Type *Ty = Expr->getType();
15261 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
15262 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
15263 SE.getSignExtendExpr(Step, Ty), L,
15264 AR->getNoWrapFlags());
15265 }
15266 return SE.getSignExtendExpr(Operand, Expr->getType());
15267 }
15268
15269private:
15270 explicit SCEVPredicateRewriter(
15271 const Loop *L, ScalarEvolution &SE,
15272 SmallVectorImpl<const SCEVPredicate *> *NewPreds,
15273 const SCEVPredicate *Pred)
15274 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
15275
15276 bool addOverflowAssumption(const SCEVPredicate *P) {
15277 if (!NewPreds) {
15278 // Check if we've already made this assumption.
15279 return Pred && Pred->implies(P, SE);
15280 }
15281 NewPreds->push_back(P);
15282 return true;
15283 }
15284
15285 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
15287 auto *A = SE.getWrapPredicate(AR, AddedFlags);
15288 return addOverflowAssumption(A);
15289 }
15290
15291 // If \p Expr represents a PHINode, we try to see if it can be represented
15292 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
15293 // to add this predicate as a runtime overflow check, we return the AddRec.
15294 // If \p Expr does not meet these conditions (is not a PHI node, or we
15295 // couldn't create an AddRec for it, or couldn't add the predicate), we just
15296 // return \p Expr.
15297 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
15298 if (!isa<PHINode>(Expr->getValue()))
15299 return Expr;
15300 std::optional<
15301 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
15302 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
15303 if (!PredicatedRewrite)
15304 return Expr;
15305 for (const auto *P : PredicatedRewrite->second){
15306 // Wrap predicates from outer loops are not supported.
15307 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
15308 if (L != WP->getExpr()->getLoop())
15309 return Expr;
15310 }
15311 if (!addOverflowAssumption(P))
15312 return Expr;
15313 }
15314 return PredicatedRewrite->first;
15315 }
15316
15317 SmallVectorImpl<const SCEVPredicate *> *NewPreds;
15318 const SCEVPredicate *Pred;
15319 const Loop *L;
15320};
15321
15322} // end anonymous namespace
15323
15324const SCEV *
15326 const SCEVPredicate &Preds) {
15327 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
15328}
15329
15331 const SCEV *S, const Loop *L,
15334 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
15335 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
15336
15337 if (!AddRec)
15338 return nullptr;
15339
15340 // Check if any of the transformed predicates is known to be false. In that
15341 // case, it doesn't make sense to convert to a predicated AddRec, as the
15342 // versioned loop will never execute.
15343 for (const SCEVPredicate *Pred : TransformPreds) {
15344 auto *WrapPred = dyn_cast<SCEVWrapPredicate>(Pred);
15345 if (!WrapPred || WrapPred->getFlags() != SCEVWrapPredicate::IncrementNSSW)
15346 continue;
15347
15348 const SCEVAddRecExpr *AddRecToCheck = WrapPred->getExpr();
15349 const SCEV *ExitCount = getBackedgeTakenCount(AddRecToCheck->getLoop());
15350 if (isa<SCEVCouldNotCompute>(ExitCount))
15351 continue;
15352
15353 const SCEV *Step = AddRecToCheck->getStepRecurrence(*this);
15354 if (!Step->isOne())
15355 continue;
15356
15357 ExitCount = getTruncateOrSignExtend(ExitCount, Step->getType());
15358 const SCEV *Add = getAddExpr(AddRecToCheck->getStart(), ExitCount);
15359 if (isKnownPredicate(CmpInst::ICMP_SLT, Add, AddRecToCheck->getStart()))
15360 return nullptr;
15361 }
15362
15363 // Since the transformation was successful, we can now transfer the SCEV
15364 // predicates.
15365 Preds.append(TransformPreds.begin(), TransformPreds.end());
15366
15367 return AddRec;
15368}
15369
15370/// SCEV predicates
15374
15376 const ICmpInst::Predicate Pred,
15377 const SCEV *LHS, const SCEV *RHS)
15378 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
15379 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
15380 assert(LHS != RHS && "LHS and RHS are the same SCEV");
15381}
15382
15384 ScalarEvolution &SE) const {
15385 const auto *Op = dyn_cast<SCEVComparePredicate>(N);
15386
15387 if (!Op)
15388 return false;
15389
15390 if (Pred != ICmpInst::ICMP_EQ)
15391 return false;
15392
15393 return Op->LHS == LHS && Op->RHS == RHS;
15394}
15395
15396bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
15397
15399 if (Pred == ICmpInst::ICMP_EQ)
15400 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
15401 else
15402 OS.indent(Depth) << "Compare predicate: " << *LHS << " " << Pred << ") "
15403 << *RHS << "\n";
15404
15405}
15406
15408 const SCEVAddRecExpr *AR,
15409 IncrementWrapFlags Flags)
15410 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
15411
15412const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
15413
15415 ScalarEvolution &SE) const {
15416 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
15417 if (!Op || setFlags(Flags, Op->Flags) != Flags)
15418 return false;
15419
15420 if (Op->AR == AR)
15421 return true;
15422
15423 if (Flags != SCEVWrapPredicate::IncrementNSSW &&
15425 return false;
15426
15427 const SCEV *Start = AR->getStart();
15428 const SCEV *OpStart = Op->AR->getStart();
15429 if (Start->getType()->isPointerTy() != OpStart->getType()->isPointerTy())
15430 return false;
15431
15432 // Reject pointers to different address spaces.
15433 if (Start->getType()->isPointerTy() && Start->getType() != OpStart->getType())
15434 return false;
15435
15436 // NUSW/NSSW on a wider-type AddRec does not imply the same on a
15437 // narrower-type AddRec.
15438 if (SE.getTypeSizeInBits(AR->getType()) >
15439 SE.getTypeSizeInBits(Op->AR->getType()))
15440 return false;
15441
15442 const SCEV *Step = AR->getStepRecurrence(SE);
15443 const SCEV *OpStep = Op->AR->getStepRecurrence(SE);
15444 if (!SE.isKnownPositive(Step) || !SE.isKnownPositive(OpStep))
15445 return false;
15446
15447 // If both steps are positive, this implies N, if N's start and step are
15448 // ULE/SLE (for NSUW/NSSW) than this'.
15449 Type *WiderTy = SE.getWiderType(Step->getType(), OpStep->getType());
15450 Step = SE.getNoopOrZeroExtend(Step, WiderTy);
15451 OpStep = SE.getNoopOrZeroExtend(OpStep, WiderTy);
15452
15453 bool IsNUW = Flags == SCEVWrapPredicate::IncrementNUSW;
15454 OpStart = IsNUW ? SE.getNoopOrZeroExtend(OpStart, WiderTy)
15455 : SE.getNoopOrSignExtend(OpStart, WiderTy);
15456 Start = IsNUW ? SE.getNoopOrZeroExtend(Start, WiderTy)
15457 : SE.getNoopOrSignExtend(Start, WiderTy);
15459 return SE.isKnownPredicate(Pred, OpStep, Step) &&
15460 SE.isKnownPredicate(Pred, OpStart, Start);
15461}
15462
15464 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
15465 IncrementWrapFlags IFlags = Flags;
15466
15467 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
15468 IFlags = clearFlags(IFlags, IncrementNSSW);
15469
15470 return IFlags == IncrementAnyWrap;
15471}
15472
15473void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
15474 OS.indent(Depth) << *getExpr() << " Added Flags: ";
15476 OS << "<nusw>";
15478 OS << "<nssw>";
15479 OS << "\n";
15480}
15481
15484 ScalarEvolution &SE) {
15485 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
15486 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
15487
15488 // We can safely transfer the NSW flag as NSSW.
15489 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
15490 ImpliedFlags = IncrementNSSW;
15491
15492 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
15493 // If the increment is positive, the SCEV NUW flag will also imply the
15494 // WrapPredicate NUSW flag.
15495 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
15496 if (Step->getValue()->getValue().isNonNegative())
15497 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
15498 }
15499
15500 return ImpliedFlags;
15501}
15502
15503/// Union predicates don't get cached so create a dummy set ID for it.
15505 ScalarEvolution &SE)
15506 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {
15507 for (const auto *P : Preds)
15508 add(P, SE);
15509}
15510
15512 return all_of(Preds,
15513 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
15514}
15515
15517 ScalarEvolution &SE) const {
15518 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
15519 return all_of(Set->Preds, [this, &SE](const SCEVPredicate *I) {
15520 return this->implies(I, SE);
15521 });
15522
15523 if (any_of(Preds,
15524 [N, &SE](const SCEVPredicate *I) { return I->implies(N, SE); }))
15525 return true;
15526
15527 // A wrap predicate may be implied by a wrap predicate in Preds after applying
15528 // equal predicates.
15529 const auto *NWrap = dyn_cast<SCEVWrapPredicate>(N);
15530 if (!NWrap)
15531 return false;
15532 const Loop *L = NWrap->getExpr()->getLoop();
15533 return any_of(Preds, [&](const SCEVPredicate *I) {
15534 const auto *IWrap = dyn_cast<SCEVWrapPredicate>(I);
15535 if (!IWrap)
15536 return false;
15537 const auto *RewrittenAR = dyn_cast<SCEVAddRecExpr>(
15538 SE.rewriteUsingPredicate(IWrap->getExpr(), L, *this));
15539 return RewrittenAR &&
15540 SE.getWrapPredicate(RewrittenAR, IWrap->getFlags())->implies(N, SE);
15541 });
15542}
15543
15545 for (const auto *Pred : Preds)
15546 Pred->print(OS, Depth);
15547}
15548
15549void SCEVUnionPredicate::add(const SCEVPredicate *N, ScalarEvolution &SE) {
15550 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
15551 for (const auto *Pred : Set->Preds)
15552 add(Pred, SE);
15553 return;
15554 }
15555
15556 // Implication checks are quadratic in the number of predicates. Stop doing
15557 // them if there are many predicates, as they should be too expensive to use
15558 // anyway at that point.
15559 bool CheckImplies = Preds.size() < 16;
15560
15561 // Only add predicate if it is not already implied by this union predicate.
15562 if (CheckImplies && implies(N, SE))
15563 return;
15564
15565 // Build a new vector containing the current predicates, except the ones that
15566 // are implied by the new predicate N.
15568 for (auto *P : Preds) {
15569 if (CheckImplies && N->implies(P, SE))
15570 continue;
15571 PrunedPreds.push_back(P);
15572 }
15573 Preds = std::move(PrunedPreds);
15574 Preds.push_back(N);
15575}
15576
15578 Loop &L)
15579 : SE(SE), L(L) {
15581 Preds = std::make_unique<SCEVUnionPredicate>(Empty, SE);
15582}
15583
15586 for (const auto *Op : Ops)
15587 // We do not expect that forgetting cached data for SCEVConstants will ever
15588 // open any prospects for sharpening or introduce any correctness issues,
15589 // so we don't bother storing their dependencies.
15590 if (!isa<SCEVConstant>(Op))
15591 SCEVUsers[Op].insert(User);
15592}
15593
15595 for (const SCEV *Op : Ops)
15596 // We do not expect that forgetting cached data for SCEVConstants will ever
15597 // open any prospects for sharpening or introduce any correctness issues,
15598 // so we don't bother storing their dependencies.
15599 if (!isa<SCEVConstant>(Op))
15600 SCEVUsers[Op].insert(User);
15601}
15602
15604 const SCEV *Expr = SE.getSCEV(V);
15605 return getPredicatedSCEV(Expr);
15606}
15607
15609 RewriteEntry &Entry = RewriteMap[Expr];
15610
15611 // If we already have an entry and the version matches, return it.
15612 if (Entry.second && Generation == Entry.first)
15613 return Entry.second;
15614
15615 // We found an entry but it's stale. Rewrite the stale entry
15616 // according to the current predicate.
15617 if (Entry.second)
15618 Expr = Entry.second;
15619
15620 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
15621 Entry = {Generation, NewSCEV};
15622
15623 return NewSCEV;
15624}
15625
15627 if (!BackedgeCount) {
15629 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
15630 for (const auto *P : Preds)
15631 addPredicate(*P);
15632 }
15633 return BackedgeCount;
15634}
15635
15637 if (!SymbolicMaxBackedgeCount) {
15639 SymbolicMaxBackedgeCount =
15640 SE.getPredicatedSymbolicMaxBackedgeTakenCount(&L, Preds);
15641 for (const auto *P : Preds)
15642 addPredicate(*P);
15643 }
15644 return SymbolicMaxBackedgeCount;
15645}
15646
15648 if (!SmallConstantMaxTripCount) {
15650 SmallConstantMaxTripCount = SE.getSmallConstantMaxTripCount(&L, &Preds);
15651 for (const auto *P : Preds)
15652 addPredicate(*P);
15653 }
15654 return *SmallConstantMaxTripCount;
15655}
15656
15658 if (Preds->implies(&Pred, SE))
15659 return;
15660
15661 SmallVector<const SCEVPredicate *, 4> NewPreds(Preds->getPredicates());
15662 NewPreds.push_back(&Pred);
15663 Preds = std::make_unique<SCEVUnionPredicate>(NewPreds, SE);
15664 updateGeneration();
15665}
15666
15669 for (const SCEVPredicate *P : Preds)
15670 addPredicate(*P);
15671}
15672
15674 return *Preds;
15675}
15676
15677void PredicatedScalarEvolution::updateGeneration() {
15678 // If the generation number wrapped recompute everything.
15679 if (++Generation == 0) {
15680 for (auto &II : RewriteMap) {
15681 const SCEV *Rewritten = II.second.second;
15682 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
15683 }
15684 }
15685}
15686
15689 const auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V));
15690 if (!AR)
15691 return false;
15692
15694 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
15695
15697}
15698
15701 const SCEV *Expr = this->getSCEV(V);
15703 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
15704
15705 if (!New)
15706 return nullptr;
15707
15708 if (ExtraPreds) {
15709 ExtraPreds->append(NewPreds);
15710 return New;
15711 }
15712
15713 addPredicates(NewPreds);
15714
15715 RewriteMap[SE.getSCEV(V)] = {Generation, New};
15716 return New;
15717}
15718
15721 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
15722 Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates(),
15723 SE)),
15724 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {}
15725
15727 // For each block.
15728 for (auto *BB : L.getBlocks())
15729 for (auto &I : *BB) {
15730 if (!SE.isSCEVable(I.getType()))
15731 continue;
15732
15733 auto *Expr = SE.getSCEV(&I);
15734 auto II = RewriteMap.find(Expr);
15735
15736 if (II == RewriteMap.end())
15737 continue;
15738
15739 // Don't print things that are not interesting.
15740 if (II->second.second == Expr)
15741 continue;
15742
15743 OS.indent(Depth) << "[PSE]" << I << ":\n";
15744 OS.indent(Depth + 2) << *Expr << "\n";
15745 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
15746 }
15747}
15748
15751 BasicBlock *Header = L->getHeader();
15752 BasicBlock *Pred = L->getLoopPredecessor();
15753 LoopGuards Guards(SE);
15754 if (!Pred)
15755 return Guards;
15757 collectFromBlock(SE, Guards, Header, Pred, VisitedBlocks);
15758 return Guards;
15759}
15760
15761void ScalarEvolution::LoopGuards::collectFromPHI(
15765 unsigned Depth) {
15766 if (!SE.isSCEVable(Phi.getType()))
15767 return;
15768
15769 using MinMaxPattern = std::pair<const SCEVConstant *, SCEVTypes>;
15770 auto GetMinMaxConst = [&](unsigned IncomingIdx) -> MinMaxPattern {
15771 const BasicBlock *InBlock = Phi.getIncomingBlock(IncomingIdx);
15772 if (!VisitedBlocks.insert(InBlock).second)
15773 return {nullptr, scCouldNotCompute};
15774
15775 // Avoid analyzing unreachable blocks so that we don't get trapped
15776 // traversing cycles with ill-formed dominance or infinite cycles
15777 if (!SE.DT.isReachableFromEntry(InBlock))
15778 return {nullptr, scCouldNotCompute};
15779
15780 auto [G, Inserted] = IncomingGuards.try_emplace(InBlock, LoopGuards(SE));
15781 if (Inserted)
15782 collectFromBlock(SE, G->second, Phi.getParent(), InBlock, VisitedBlocks,
15783 Depth + 1);
15784 auto &RewriteMap = G->second.RewriteMap;
15785 if (RewriteMap.empty())
15786 return {nullptr, scCouldNotCompute};
15787 auto S = RewriteMap.find(SE.getSCEV(Phi.getIncomingValue(IncomingIdx)));
15788 if (S == RewriteMap.end())
15789 return {nullptr, scCouldNotCompute};
15790 auto *SM = dyn_cast_if_present<SCEVMinMaxExpr>(S->second);
15791 if (!SM)
15792 return {nullptr, scCouldNotCompute};
15793 if (const SCEVConstant *C0 = dyn_cast<SCEVConstant>(SM->getOperand(0)))
15794 return {C0, SM->getSCEVType()};
15795 return {nullptr, scCouldNotCompute};
15796 };
15797 auto MergeMinMaxConst = [](MinMaxPattern P1,
15798 MinMaxPattern P2) -> MinMaxPattern {
15799 auto [C1, T1] = P1;
15800 auto [C2, T2] = P2;
15801 if (!C1 || !C2 || T1 != T2)
15802 return {nullptr, scCouldNotCompute};
15803 switch (T1) {
15804 case scUMaxExpr:
15805 return {C1->getAPInt().ult(C2->getAPInt()) ? C1 : C2, T1};
15806 case scSMaxExpr:
15807 return {C1->getAPInt().slt(C2->getAPInt()) ? C1 : C2, T1};
15808 case scUMinExpr:
15809 return {C1->getAPInt().ugt(C2->getAPInt()) ? C1 : C2, T1};
15810 case scSMinExpr:
15811 return {C1->getAPInt().sgt(C2->getAPInt()) ? C1 : C2, T1};
15812 default:
15813 llvm_unreachable("Trying to merge non-MinMaxExpr SCEVs.");
15814 }
15815 };
15816 auto P = GetMinMaxConst(0);
15817 for (unsigned int In = 1; In < Phi.getNumIncomingValues(); In++) {
15818 if (!P.first)
15819 break;
15820 P = MergeMinMaxConst(P, GetMinMaxConst(In));
15821 }
15822 if (P.first) {
15823 const SCEV *LHS = SE.getSCEV(const_cast<PHINode *>(&Phi));
15824 SmallVector<SCEVUse, 2> Ops({P.first, LHS});
15825 const SCEV *RHS = SE.getMinMaxExpr(P.second, Ops);
15826 Guards.RewriteMap.insert({LHS, RHS});
15827 }
15828}
15829
15830// Return a new SCEV that modifies \p Expr to the closest number divides by
15831// \p Divisor and less or equal than Expr. For now, only handle constant
15832// Expr.
15834 const APInt &DivisorVal,
15835 ScalarEvolution &SE) {
15836 const APInt *ExprVal;
15837 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15838 DivisorVal.isNonPositive())
15839 return Expr;
15840 APInt Rem = ExprVal->urem(DivisorVal);
15841 // return the SCEV: Expr - Expr % Divisor
15842 return SE.getConstant(*ExprVal - Rem);
15843}
15844
15845// Return a new SCEV that modifies \p Expr to the closest number divides by
15846// \p Divisor and greater or equal than Expr. For now, only handle constant
15847// Expr.
15848static const SCEV *getNextSCEVDivisibleByDivisor(const SCEV *Expr,
15849 const APInt &DivisorVal,
15850 ScalarEvolution &SE) {
15851 const APInt *ExprVal;
15852 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15853 DivisorVal.isNonPositive())
15854 return Expr;
15855 APInt Rem = ExprVal->urem(DivisorVal);
15856 if (Rem.isZero())
15857 return Expr;
15858 // return the SCEV: Expr + Divisor - Expr % Divisor
15859 return SE.getConstant(*ExprVal + DivisorVal - Rem);
15860}
15861
15863 ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS,
15866 // If we have LHS == 0, check if LHS is computing a property of some unknown
15867 // SCEV %v which we can rewrite %v to express explicitly.
15869 return false;
15870 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
15871 // explicitly express that.
15872 const SCEVUnknown *URemLHS = nullptr;
15873 const SCEV *URemRHS = nullptr;
15874 if (!match(LHS, m_scev_URem(m_SCEVUnknown(URemLHS), m_SCEV(URemRHS), SE)))
15875 return false;
15876
15877 const SCEV *Multiple =
15878 SE.getMulExpr(SE.getUDivExpr(URemLHS, URemRHS), URemRHS);
15879 DivInfo[URemLHS] = Multiple;
15880 if (auto *C = dyn_cast<SCEVConstant>(URemRHS))
15881 Multiples[URemLHS] = C->getAPInt();
15882 return true;
15883}
15884
15885// Check if the condition is a divisibility guard (A % B == 0).
15886static bool isDivisibilityGuard(const SCEV *LHS, const SCEV *RHS,
15887 ScalarEvolution &SE) {
15888 const SCEV *X, *Y;
15889 return match(LHS, m_scev_URem(m_SCEV(X), m_SCEV(Y), SE)) && RHS->isZero();
15890}
15891
15892// Apply divisibility by \p Divisor on MinMaxExpr with constant values,
15893// recursively. This is done by aligning up/down the constant value to the
15894// Divisor.
15895static const SCEV *applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr,
15896 APInt Divisor,
15897 ScalarEvolution &SE) {
15898 // Return true if \p Expr is a MinMax SCEV expression with a non-negative
15899 // constant operand. If so, return in \p SCTy the SCEV type and in \p RHS
15900 // the non-constant operand and in \p LHS the constant operand.
15901 auto IsMinMaxSCEVWithNonNegativeConstant =
15902 [&](const SCEV *Expr, SCEVTypes &SCTy, const SCEV *&LHS,
15903 const SCEV *&RHS) {
15904 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr)) {
15905 if (MinMax->getNumOperands() != 2)
15906 return false;
15907 if (auto *C = dyn_cast<SCEVConstant>(MinMax->getOperand(0))) {
15908 if (C->getAPInt().isNegative())
15909 return false;
15910 SCTy = MinMax->getSCEVType();
15911 LHS = MinMax->getOperand(0);
15912 RHS = MinMax->getOperand(1);
15913 return true;
15914 }
15915 }
15916 return false;
15917 };
15918
15919 const SCEV *MinMaxLHS = nullptr, *MinMaxRHS = nullptr;
15920 SCEVTypes SCTy;
15921 if (!IsMinMaxSCEVWithNonNegativeConstant(MinMaxExpr, SCTy, MinMaxLHS,
15922 MinMaxRHS))
15923 return MinMaxExpr;
15924 auto IsMin = isa<SCEVSMinExpr>(MinMaxExpr) || isa<SCEVUMinExpr>(MinMaxExpr);
15925 assert(SE.isKnownNonNegative(MinMaxLHS) && "Expected non-negative operand!");
15926 auto *DivisibleExpr =
15927 IsMin ? getPreviousSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE)
15928 : getNextSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE);
15930 applyDivisibilityOnMinMaxExpr(MinMaxRHS, Divisor, SE), DivisibleExpr};
15931 return SE.getMinMaxExpr(SCTy, Ops);
15932}
15933
15934void ScalarEvolution::LoopGuards::collectFromBlock(
15935 ScalarEvolution &SE, ScalarEvolution::LoopGuards &Guards,
15936 const BasicBlock *Block, const BasicBlock *Pred,
15937 SmallPtrSetImpl<const BasicBlock *> &VisitedBlocks, unsigned Depth) {
15938
15940
15941 SmallVector<SCEVUse> ExprsToRewrite;
15942 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
15943 const SCEV *RHS,
15944 DenseMap<const SCEV *, const SCEV *> &RewriteMap,
15945 const LoopGuards &DivGuards) {
15946 // WARNING: It is generally unsound to apply any wrap flags to the proposed
15947 // replacement SCEV which isn't directly implied by the structure of that
15948 // SCEV. In particular, using contextual facts to imply flags is *NOT*
15949 // legal. See the scoping rules for flags in the header to understand why.
15950
15951 // Puts rewrite rule \p From -> \p To into the rewrite map. Also if \p From
15952 // and \p FromRewritten are the same (i.e. there has been no rewrite
15953 // registered for \p From), then puts this value in the list of rewritten
15954 // expressions.
15955 auto AddRewrite = [&](const SCEV *From, const SCEV *FromRewritten,
15956 const SCEV *To) {
15957 if (From == FromRewritten)
15958 ExprsToRewrite.push_back(From);
15959 RewriteMap[From] = To;
15960 };
15961
15962 // Checks whether \p S has already been rewritten. In that case returns the
15963 // existing rewrite because we want to chain further rewrites onto the
15964 // already rewritten value. Otherwise returns \p S.
15965 auto GetMaybeRewritten = [&](const SCEV *S) {
15966 return RewriteMap.lookup_or(S, S);
15967 };
15968
15969 // Check for a condition of the form (-C1 + X < C2). InstCombine will
15970 // create this form when combining two checks of the form (X u< C2 + C1) and
15971 // (X >=u C1).
15972 auto MatchRangeCheckIdiom = [&](ICmpInst::Predicate Pred,
15973 const SCEV *MatchLHS,
15974 const SCEV *MatchRHS) {
15975 const SCEVConstant *C1;
15976 const SCEVUnknown *LHSUnknown;
15977 auto *C2 = dyn_cast<SCEVConstant>(MatchRHS);
15978 if (!match(MatchLHS,
15979 m_scev_Add(m_SCEVConstant(C1), m_SCEVUnknown(LHSUnknown))) ||
15980 !C2)
15981 return false;
15982
15983 auto ExactRegion =
15984 ConstantRange::makeExactICmpRegion(Pred, C2->getAPInt())
15985 .sub(C1->getAPInt());
15986
15987 // Tighten the raw range with what we already know about LHSUnknown
15988 // from prior guards recorded in RewriteMap, or from SCEV's own range
15989 // analysis.
15990 const SCEV *RewrittenLHS = GetMaybeRewritten(LHSUnknown);
15991 ExactRegion = ExactRegion.intersectWith(SE.getUnsignedRange(RewrittenLHS),
15993
15994 // Bail if the guard is inconsistent with prior facts, or if the range
15995 // is still not a monotonic non-wrapping interval after tightening.
15996 if (ExactRegion.isEmptySet() || ExactRegion.isWrappedSet() ||
15997 ExactRegion.isFullSet())
15998 return false;
15999
16000 const SCEV *RegionMin = SE.getConstant(ExactRegion.getUnsignedMin());
16001 const SCEV *RegionMax = SE.getConstant(ExactRegion.getUnsignedMax());
16002 const SCEV *ClampedLHS =
16003 SE.getUMaxExpr(RegionMin, SE.getUMinExpr(RewrittenLHS, RegionMax));
16004 AddRewrite(LHSUnknown, RewrittenLHS, ClampedLHS);
16005 return true;
16006 };
16007 if (MatchRangeCheckIdiom(Predicate, LHS, RHS))
16008 return;
16009
16010 // Do not apply information for constants or if RHS contains an AddRec.
16012 return;
16013
16014 // If RHS is SCEVUnknown, make sure the information is applied to it.
16016 std::swap(LHS, RHS);
16018 }
16019
16020 const SCEV *RewrittenLHS = GetMaybeRewritten(LHS);
16021 // Apply divisibility information when computing the constant multiple.
16022 const APInt &DividesBy =
16023 SE.getConstantMultiple(DivGuards.rewrite(RewrittenLHS));
16024
16025 // Collect rewrites for LHS and its transitive operands based on the
16026 // condition.
16027 // For min/max expressions, also apply the guard to its operands:
16028 // 'min(a, b) >= c' -> '(a >= c) and (b >= c)',
16029 // 'min(a, b) > c' -> '(a > c) and (b > c)',
16030 // 'max(a, b) <= c' -> '(a <= c) and (b <= c)',
16031 // 'max(a, b) < c' -> '(a < c) and (b < c)'.
16032
16033 // We cannot express strict predicates in SCEV, so instead we replace them
16034 // with non-strict ones against plus or minus one of RHS depending on the
16035 // predicate.
16036 const SCEV *One = SE.getOne(RHS->getType());
16037 switch (Predicate) {
16038 case CmpInst::ICMP_ULT:
16039 if (RHS->getType()->isPointerTy())
16040 return;
16041 RHS = SE.getUMaxExpr(RHS, One);
16042 [[fallthrough]];
16043 case CmpInst::ICMP_SLT: {
16044 RHS = SE.getMinusSCEV(RHS, One);
16045 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16046 break;
16047 }
16048 case CmpInst::ICMP_UGT:
16049 case CmpInst::ICMP_SGT:
16050 RHS = SE.getAddExpr(RHS, One);
16051 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16052 break;
16053 case CmpInst::ICMP_ULE:
16054 case CmpInst::ICMP_SLE:
16055 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16056 break;
16057 case CmpInst::ICMP_UGE:
16058 case CmpInst::ICMP_SGE:
16059 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16060 break;
16061 default:
16062 break;
16063 }
16064
16065 SmallVector<SCEVUse, 16> Worklist(1, LHS);
16066 SmallPtrSet<const SCEV *, 16> Visited;
16067
16068 auto EnqueueOperands = [&Worklist](const SCEVNAryExpr *S) {
16069 append_range(Worklist, S->operands());
16070 };
16071
16072 while (!Worklist.empty()) {
16073 const SCEV *From = Worklist.pop_back_val();
16074 if (isa<SCEVConstant>(From))
16075 continue;
16076 if (!Visited.insert(From).second)
16077 continue;
16078 const SCEV *FromRewritten = GetMaybeRewritten(From);
16079 const SCEV *To = nullptr;
16080
16081 switch (Predicate) {
16082 case CmpInst::ICMP_ULT:
16083 case CmpInst::ICMP_ULE:
16084 To = SE.getUMinExpr(FromRewritten, RHS);
16085 if (auto *UMax = dyn_cast<SCEVUMaxExpr>(FromRewritten))
16086 EnqueueOperands(UMax);
16087 break;
16088 case CmpInst::ICMP_SLT:
16089 case CmpInst::ICMP_SLE:
16090 To = SE.getSMinExpr(FromRewritten, RHS);
16091 if (auto *SMax = dyn_cast<SCEVSMaxExpr>(FromRewritten))
16092 EnqueueOperands(SMax);
16093 break;
16094 case CmpInst::ICMP_UGT:
16095 case CmpInst::ICMP_UGE:
16096 To = SE.getUMaxExpr(FromRewritten, RHS);
16097 if (auto *UMin = dyn_cast<SCEVUMinExpr>(FromRewritten))
16098 EnqueueOperands(UMin);
16099 break;
16100 case CmpInst::ICMP_SGT:
16101 case CmpInst::ICMP_SGE:
16102 To = SE.getSMaxExpr(FromRewritten, RHS);
16103 if (auto *SMin = dyn_cast<SCEVSMinExpr>(FromRewritten))
16104 EnqueueOperands(SMin);
16105 break;
16106 case CmpInst::ICMP_EQ:
16108 To = RHS;
16109 break;
16110 case CmpInst::ICMP_NE:
16111 if (match(RHS, m_scev_Zero())) {
16112 const SCEV *OneAlignedUp =
16113 getNextSCEVDivisibleByDivisor(One, DividesBy, SE);
16114 To = SE.getUMaxExpr(FromRewritten, OneAlignedUp);
16115 } else {
16116 // LHS != RHS can be rewritten as (LHS - RHS) = UMax(1, LHS - RHS),
16117 // but creating the subtraction eagerly is expensive. Track the
16118 // inequalities in a separate map, and materialize the rewrite lazily
16119 // when encountering a suitable subtraction while re-writing.
16120 if (LHS->getType()->isPointerTy()) {
16121 LHS = SE.getPtrToAddrExpr(LHS);
16122 RHS = SE.getPtrToAddrExpr(RHS);
16124 break;
16125 }
16126 const SCEVConstant *C;
16127 const SCEV *A, *B;
16130 RHS = A;
16131 LHS = B;
16132 }
16133 if (LHS > RHS)
16134 std::swap(LHS, RHS);
16135 Guards.NotEqual.insert({LHS, RHS});
16136 continue;
16137 }
16138 break;
16139 default:
16140 break;
16141 }
16142
16143 if (To)
16144 AddRewrite(From, FromRewritten, To);
16145 }
16146 };
16147
16149 // First, collect information from assumptions dominating the loop.
16150 for (auto &AssumeVH : SE.AC.assumptions()) {
16151 if (!AssumeVH)
16152 continue;
16153 auto *AssumeI = cast<CallInst>(AssumeVH);
16154 if (!SE.DT.dominates(AssumeI, Block))
16155 continue;
16156 Terms.emplace_back(AssumeI->getOperand(0), true);
16157 }
16158
16159 // Second, collect information from llvm.experimental.guards dominating the loop.
16160 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
16161 SE.F.getParent(), Intrinsic::experimental_guard);
16162 if (GuardDecl)
16163 for (const auto *GU : GuardDecl->users())
16164 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
16165 if (Guard->getFunction() == Block->getParent() &&
16166 SE.DT.dominates(Guard, Block))
16167 Terms.emplace_back(Guard->getArgOperand(0), true);
16168
16169 // Third, collect conditions from dominating branches. Starting at the loop
16170 // predecessor, climb up the predecessor chain, as long as there are
16171 // predecessors that can be found that have unique successors leading to the
16172 // original header.
16173 // TODO: share this logic with isLoopEntryGuardedByCond.
16174 unsigned NumCollectedConditions = 0;
16176 std::pair<const BasicBlock *, const BasicBlock *> Pair(Pred, Block);
16177 for (; Pair.first;
16178 Pair = SE.getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
16179 VisitedBlocks.insert(Pair.second);
16180 const CondBrInst *LoopEntryPredicate =
16181 dyn_cast<CondBrInst>(Pair.first->getTerminator());
16182 if (!LoopEntryPredicate)
16183 continue;
16184
16185 Terms.emplace_back(LoopEntryPredicate->getCondition(),
16186 LoopEntryPredicate->getSuccessor(0) == Pair.second);
16187 NumCollectedConditions++;
16188
16189 // If we are recursively collecting guards stop after 2
16190 // conditions to limit compile-time impact for now.
16191 if (Depth > 0 && NumCollectedConditions == 2)
16192 break;
16193 }
16194 // Finally, if we stopped climbing the predecessor chain because
16195 // there wasn't a unique one to continue, try to collect conditions
16196 // for PHINodes by recursively following all of their incoming
16197 // blocks and try to merge the found conditions to build a new one
16198 // for the Phi.
16199 if (Pair.second->hasNPredecessorsOrMore(2) &&
16201 SmallDenseMap<const BasicBlock *, LoopGuards> IncomingGuards;
16202 for (auto &Phi : Pair.second->phis())
16203 collectFromPHI(SE, Guards, Phi, VisitedBlocks, IncomingGuards, Depth);
16204 }
16205
16206 // Now apply the information from the collected conditions to
16207 // Guards.RewriteMap. Conditions are processed in reverse order, so the
16208 // earliest conditions is processed first, except guards with divisibility
16209 // information, which are moved to the back. This ensures the SCEVs with the
16210 // shortest dependency chains are constructed first.
16212 GuardsToProcess;
16213 for (auto [Term, EnterIfTrue] : reverse(Terms)) {
16214 SmallVector<Value *, 8> Worklist;
16215 SmallPtrSet<Value *, 8> Visited;
16216 Worklist.push_back(Term);
16217 while (!Worklist.empty()) {
16218 Value *Cond = Worklist.pop_back_val();
16219 if (!Visited.insert(Cond).second)
16220 continue;
16221
16222 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
16223 auto Predicate =
16224 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
16225 const auto *LHS = SE.getSCEV(Cmp->getOperand(0));
16226 const auto *RHS = SE.getSCEV(Cmp->getOperand(1));
16227 // If LHS is a constant, apply information to the other expression.
16228 // TODO: If LHS is not a constant, check if using CompareSCEVComplexity
16229 // can improve results.
16230 if (isa<SCEVConstant>(LHS)) {
16231 std::swap(LHS, RHS);
16233 }
16234 GuardsToProcess.emplace_back(Predicate, LHS, RHS);
16235 continue;
16236 }
16237
16238 Value *L, *R;
16239 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
16240 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
16241 Worklist.push_back(L);
16242 Worklist.push_back(R);
16243 }
16244 }
16245 }
16246
16247 // Process divisibility guards in reverse order to populate DivGuards early.
16248 DenseMap<const SCEV *, APInt> Multiples;
16249 LoopGuards DivGuards(SE);
16250 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess) {
16251 if (!isDivisibilityGuard(LHS, RHS, SE))
16252 continue;
16253 collectDivisibilityInformation(Predicate, LHS, RHS, DivGuards.RewriteMap,
16254 Multiples, SE);
16255 }
16256
16257 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess)
16258 CollectCondition(Predicate, LHS, RHS, Guards.RewriteMap, DivGuards);
16259
16260 // Apply divisibility information last. This ensures it is applied to the
16261 // outermost expression after other rewrites for the given value.
16262 for (const auto &[K, Divisor] : Multiples) {
16263 const SCEV *DivisorSCEV = SE.getConstant(Divisor);
16264 Guards.RewriteMap[K] =
16266 Guards.rewrite(K), Divisor, SE),
16267 DivisorSCEV),
16268 DivisorSCEV);
16269 ExprsToRewrite.push_back(K);
16270 }
16271
16272 // Let the rewriter preserve NUW/NSW flags if the unsigned/signed ranges of
16273 // the replacement expressions are contained in the ranges of the replaced
16274 // expressions.
16275 Guards.PreserveNUW = true;
16276 Guards.PreserveNSW = true;
16277 for (const SCEV *Expr : ExprsToRewrite) {
16278 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16279 Guards.PreserveNUW &=
16280 SE.getUnsignedRange(Expr).contains(SE.getUnsignedRange(RewriteTo));
16281 Guards.PreserveNSW &=
16282 SE.getSignedRange(Expr).contains(SE.getSignedRange(RewriteTo));
16283 }
16284
16285 // Now that all rewrite information is collect, rewrite the collected
16286 // expressions with the information in the map. This applies information to
16287 // sub-expressions.
16288 if (ExprsToRewrite.size() > 1) {
16289 for (const SCEV *Expr : ExprsToRewrite) {
16290 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16291 Guards.RewriteMap.erase(Expr);
16292 Guards.RewriteMap.insert({Expr, Guards.rewrite(RewriteTo)});
16293 }
16294 }
16295}
16296
16298 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
16299 /// in the map. It skips AddRecExpr because we cannot guarantee that the
16300 /// replacement is loop invariant in the loop of the AddRec.
16301 class SCEVLoopGuardRewriter
16302 : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
16305
16307
16308 public:
16309 SCEVLoopGuardRewriter(ScalarEvolution &SE,
16310 const ScalarEvolution::LoopGuards &Guards)
16311 : SCEVRewriteVisitor(SE), Map(Guards.RewriteMap),
16312 NotEqual(Guards.NotEqual) {
16313 if (Guards.PreserveNUW)
16314 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNUW);
16315 if (Guards.PreserveNSW)
16316 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNSW);
16317 }
16318
16319 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
16320
16321 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
16322 return Map.lookup_or(Expr, Expr);
16323 }
16324
16325 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
16326 if (const SCEV *S = Map.lookup(Expr))
16327 return S;
16328
16329 // If we didn't find the extact ZExt expr in the map, check if there's
16330 // an entry for a smaller ZExt we can use instead.
16331 Type *Ty = Expr->getType();
16332 const SCEV *Op = Expr->getOperand(0);
16333 unsigned Bitwidth = Ty->getScalarSizeInBits() / 2;
16334 while (Bitwidth % 8 == 0 && Bitwidth >= 8 &&
16335 Bitwidth > Op->getType()->getScalarSizeInBits()) {
16336 Type *NarrowTy = IntegerType::get(SE.getContext(), Bitwidth);
16337 auto *NarrowExt = SE.getZeroExtendExpr(Op, NarrowTy);
16338 if (const SCEV *S = Map.lookup(NarrowExt))
16339 return SE.getZeroExtendExpr(S, Ty);
16340 Bitwidth = Bitwidth / 2;
16341 }
16342
16344 Expr);
16345 }
16346
16347 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
16348 if (const SCEV *S = Map.lookup(Expr))
16349 return S;
16351 Expr);
16352 }
16353
16354 const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
16355 if (const SCEV *S = Map.lookup(Expr))
16356 return S;
16358 }
16359
16360 const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
16361 if (const SCEV *S = Map.lookup(Expr))
16362 return S;
16364 }
16365
16366 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
16367 if (const SCEV *S = Map.lookup(Expr))
16368 return S;
16369
16370 // Helper to check if S is a subtraction (A - B) where A != B, and if so,
16371 // return UMax(S, 1).
16372 auto RewriteSubtraction = [&](const SCEV *S) -> const SCEV * {
16373 SCEVUse LHS, RHS;
16374 if (MatchBinarySub(S, LHS, RHS)) {
16375 if (LHS > RHS)
16376 std::swap(LHS, RHS);
16377 if (NotEqual.contains({LHS, RHS})) {
16378 const SCEV *OneAlignedUp = getNextSCEVDivisibleByDivisor(
16379 SE.getOne(S->getType()), SE.getConstantMultiple(S), SE);
16380 return SE.getUMaxExpr(OneAlignedUp, S);
16381 }
16382 }
16383 return nullptr;
16384 };
16385
16386 // Check if Expr itself is a subtraction pattern with guard info.
16387 if (const SCEV *Rewritten = RewriteSubtraction(Expr))
16388 return Rewritten;
16389
16390 // Trip count expressions sometimes consist of adding 3 operands, i.e.
16391 // (Const + A + B). There may be guard info for A + B, and if so, apply
16392 // it.
16393 // TODO: Could more generally apply guards to Add sub-expressions.
16394 if (isa<SCEVConstant>(Expr->getOperand(0))) {
16395 if (Expr->getNumOperands() == 3) {
16396 const SCEV *Add =
16397 SE.getAddExpr(Expr->getOperand(1), Expr->getOperand(2));
16398 if (const SCEV *Rewritten = RewriteSubtraction(Add))
16399 return SE.getAddExpr(
16400 Expr->getOperand(0), Rewritten,
16401 ScalarEvolution::maskFlags(Expr->getNoWrapFlags(), FlagMask));
16402 if (const SCEV *S = Map.lookup(Add))
16403 return SE.getAddExpr(Expr->getOperand(0), S);
16404 }
16405
16406 // For expressions of the form (Const + A), check if we have guard info
16407 // for (Const + 1 + A), and rewrite to ((Const + 1 + A) - 1). This makes
16408 // sure we don't lose information when rewriting expressions based on
16409 // back-edge taken counts in some cases.
16410 if (Expr->getNumOperands() == 2) {
16411 const SCEV *S = nullptr;
16412 // Handle (-1 + 1 + A) without constructing SCEVs.
16413 if (match(Expr->getOperand(0), m_scev_AllOnes())) {
16414 S = Map.lookup(Expr->getOperand(1));
16415 } else {
16416 const SCEV *NewC =
16417 SE.getAddExpr(Expr->getOperand(0), SE.getOne(Expr->getType()));
16418 S = Map.lookup(SE.getAddExpr(NewC, Expr->getOperand(1)));
16419 }
16420 if (S)
16421 return SE.getAddExpr(S, SE.getMinusOne(Expr->getType()));
16422 }
16423 }
16425 bool Changed = false;
16426 for (SCEVUse Op : Expr->operands()) {
16427 Operands.push_back(
16429 Changed |= Op != Operands.back();
16430 }
16431 // We are only replacing operands with equivalent values, so transfer the
16432 // flags from the original expression.
16433 return !Changed ? Expr
16434 : SE.getAddExpr(Operands,
16436 Expr->getNoWrapFlags(), FlagMask));
16437 }
16438
16439 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
16441 bool Changed = false;
16442 for (SCEVUse Op : Expr->operands()) {
16443 Operands.push_back(
16445 Changed |= Op != Operands.back();
16446 }
16447 // We are only replacing operands with equivalent values, so transfer the
16448 // flags from the original expression.
16449 return !Changed ? Expr
16450 : SE.getMulExpr(Operands,
16452 Expr->getNoWrapFlags(), FlagMask));
16453 }
16454 };
16455
16456 if (RewriteMap.empty() && NotEqual.empty())
16457 return Expr;
16458
16459 SCEVLoopGuardRewriter Rewriter(SE, *this);
16460 return Rewriter.visit(Expr);
16461}
16462
16463const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
16464 return applyLoopGuards(Expr, LoopGuards::collect(L, *this));
16465}
16466
16468 const LoopGuards &Guards) {
16469 return Guards.rewrite(Expr);
16470}
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:856
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:678
This file contains the declarations for the subclasses of Constant, which represent the different fla...
SmallPtrSet< const BasicBlock *, 8 > VisitedBlocks
This file defines the DenseMap class.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
static bool isSigned(unsigned Opcode)
This file defines a hash set that can be used to remove duplication of nodes in a graph.
#define op(i)
Hexagon Common GEP
Value * getPointer(Value *Ptr)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This defines the Use class.
iv Induction Variable Users
Definition IVUsers.cpp:48
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:539
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define T
#define T1
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
ppc ctr loops verify
PowerPC Reduce CR logical Operation
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
R600 Clause Merge
const SmallVectorImpl< MachineOperand > & Cond
static DominatorTree getDomTree(Function &F)
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
SI Fold Operands
SI optimize exec mask operations pre RA
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
This file contains some templates that are useful if you are working with the STL at all.
This file provides utility classes that use RAII to save and restore values.
bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind, SCEVTypes RootKind)
static cl::opt< unsigned > MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, cl::desc("Max coefficients in AddRec during evolving"), cl::init(8))
static cl::opt< unsigned > RangeIterThreshold("scev-range-iter-threshold", cl::Hidden, cl::desc("Threshold for switching to iteratively computing SCEV ranges"), cl::init(32))
static const Loop * isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI)
static unsigned getConstantTripCount(const SCEVConstant *ExitCount)
static int CompareValueComplexity(const LoopInfo *const LI, Value *LV, Value *RV, unsigned Depth)
Compare the two values LV and RV in terms of their "complexity" where "complexity" is a partial (and ...
static const SCEV * getNextSCEVDivisibleByDivisor(const SCEV *Expr, const APInt &DivisorVal, ScalarEvolution &SE)
static void PushLoopPHIs(const Loop *L, SmallVectorImpl< Instruction * > &Worklist, SmallPtrSetImpl< Instruction * > &Visited)
Push PHI nodes in the header of the given loop onto the given Worklist.
static void insertFoldCacheEntry(const ScalarEvolution::FoldID &ID, const SCEV *S, DenseMap< ScalarEvolution::FoldID, const SCEV * > &FoldCache, DenseMap< const SCEV *, SmallVector< ScalarEvolution::FoldID, 2 > > &FoldCacheUser)
static cl::opt< bool > ClassifyExpressions("scalar-evolution-classify-expressions", cl::Hidden, cl::init(true), cl::desc("When printing analysis, include information on every instruction"))
static bool hasHugeExpression(ArrayRef< SCEVUse > Ops)
Returns true if Ops contains a huge SCEV (the subtree of S contains at least HugeExprThreshold nodes)...
static bool CanConstantFold(const Instruction *I)
Return true if we can constant fold an instruction of the specified type, assuming that all operands ...
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 const SCEV * getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, ScalarEvolution *SE, unsigned Depth)
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 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 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 PHINode * getConstantEvolvingPHI(Value *V, const Loop *L)
getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node in the loop that V is deri...
static const SCEV * SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, SmallVectorImpl< const SCEVPredicate * > *Predicates, ScalarEvolution &SE, const Loop *L)
Finds the minimum unsigned root of the following equation:
static cl::opt< unsigned > MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, cl::desc("Maximum number of iterations SCEV will " "symbolically execute a constant " "derived loop"), cl::init(100))
static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow)
static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV *S)
When printing a top-level SCEV for trip counts, it's helpful to include a type for constants which ar...
static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, const Loop *L)
static SCEV::NoWrapFlags StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, ArrayRef< SCEVUse > Ops, SCEV::NoWrapFlags Flags)
static bool containsConstantInAddMulChain(const SCEV *StartExpr)
Determine if any of the operands in this SCEV are a constant or if any of the add or multiply express...
static const SCEV * getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, ScalarEvolution *SE, unsigned Depth)
static bool CollectAddOperandsWithScales(SmallDenseMap< SCEVUse, APInt, 16 > &M, SmallVectorImpl< SCEVUse > &NewOps, APInt &AccumulatedConstant, ArrayRef< SCEVUse > Ops, const APInt &Scale, ScalarEvolution &SE)
Process the given Ops list, which is a list of operands to be added under the given scale,...
static const SCEV * constantFoldAndGroupOps(ScalarEvolution &SE, LoopInfo &LI, DominatorTree &DT, SmallVectorImpl< SCEVUse > &Ops, FoldT Fold, IsIdentityT IsIdentity, IsAbsorberT IsAbsorber)
Performs a number of common optimizations on the passed Ops.
static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
static void GroupByComplexity(SmallVectorImpl< SCEVUse > &Ops, LoopInfo *LI, DominatorTree &DT)
Given a list of SCEV objects, order them by their complexity, and group objects of the same complexit...
static bool collectDivisibilityInformation(ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS, DenseMap< const SCEV *, const SCEV * > &DivInfo, DenseMap< const SCEV *, APInt > &Multiples, ScalarEvolution &SE)
static cl::opt< unsigned > MaxSCEVOperationsImplicationDepth("scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, cl::desc("Maximum depth of recursive SCEV operations implication analysis"), cl::init(2))
static void PushDefUseChildren(Instruction *I, SmallVectorImpl< Instruction * > &Worklist, SmallPtrSetImpl< Instruction * > &Visited)
Push users of the given Instruction onto the given Worklist.
static std::optional< APInt > SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, const ConstantRange &Range, ScalarEvolution &SE)
Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n iterations.
static cl::opt< bool > UseContextForNoWrapFlagInference("scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden, cl::desc("Infer nuw/nsw flags using context where suitable"), cl::init(true))
static cl::opt< bool > EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden, cl::desc("Handle <= and >= in finite loops"), cl::init(true))
static bool getOperandsForSelectLikePHI(DominatorTree &DT, PHINode *PN, Value *&Cond, Value *&LHS, Value *&RHS)
static std::optional< std::tuple< APInt, APInt, APInt, APInt, unsigned > > GetQuadraticEquation(const SCEVAddRecExpr *AddRec)
For a given quadratic addrec, generate coefficients of the corresponding quadratic equation,...
static bool isKnownPredicateExtendIdiom(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
static std::optional< BinaryOp > MatchBinaryOp(Value *V, const DataLayout &DL, AssumptionCache &AC, const DominatorTree &DT, const Instruction *CxtI)
Try to map V into a BinaryOp, and return std::nullopt on failure.
static std::optional< APInt > SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE)
Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n iterations.
static std::optional< APInt > TruncIfPossible(std::optional< APInt > X, unsigned BitWidth)
Helper function to truncate an optional APInt to a given BitWidth.
static cl::opt< unsigned > MaxSCEVCompareDepth("scalar-evolution-max-scev-compare-depth", cl::Hidden, cl::desc("Maximum depth of recursive SCEV complexity comparisons"), cl::init(32))
static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, const SCEVConstant *ConstantTerm, const SCEVAddExpr *WholeAddExpr)
static cl::opt< unsigned > MaxConstantEvolvingDepth("scalar-evolution-max-constant-evolving-depth", cl::Hidden, cl::desc("Maximum depth of recursive constant evolving"), cl::init(32))
static bool 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 std::optional< int > CompareSCEVComplexity(const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, DominatorTree &DT, unsigned Depth=0)
static bool canConstantEvolve(Instruction *I, const Loop *L)
Determine whether this instruction can constant evolve within this loop assuming its operands can all...
static PHINode * getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, DenseMap< Instruction *, PHINode * > &PHIMap, unsigned Depth)
getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by recursing through each instructi...
static bool scevUnconditionallyPropagatesPoisonFromOperands(SCEVTypes Kind)
static cl::opt< bool > VerifySCEVStrict("verify-scev-strict", cl::Hidden, cl::desc("Enable stricter verification with -verify-scev is passed"))
static Constant * getOtherIncomingValue(PHINode *PN, BasicBlock *BB)
static cl::opt< bool > UseExpensiveRangeSharpening("scalar-evolution-use-expensive-range-sharpening", cl::Hidden, cl::init(false), cl::desc("Use more powerful methods of sharpening expression ranges. May " "be costly in terms of compile time"))
static const SCEV * getUnsignedOverflowLimitForStep(const SCEV *Step, ICmpInst::Predicate *Pred, ScalarEvolution *SE)
static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Is LHS Pred RHS true on the virtue of LHS or RHS being a Min or Max expression?
static bool BrPHIToSelect(DominatorTree &DT, CondBrInst *BI, PHINode *Merge, Value *&C, Value *&LHS, Value *&RHS)
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
static bool InBlock(const Value *V, const BasicBlock *BB)
Provides some synthesis utilities to produce sequences of values.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
static std::optional< bool > isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS, const Value *ARHS, const Value *BLHS, const Value *BRHS)
Return true if "icmp Pred BLHS BRHS" is true whenever "icmp PredALHS ARHS" is true.
Virtual Register Rewriter
Value * RHS
Value * LHS
BinaryOperator * Mul
static const uint32_t IV[8]
Definition blake3_impl.h:83
SCEVCastSinkingRewriter(ScalarEvolution &SE, Type *TargetTy, ConversionFn CreatePtrCast)
static const SCEV * rewrite(const SCEV *Scev, ScalarEvolution &SE, Type *TargetTy, ConversionFn CreatePtrCast)
const SCEV * visitUnknown(const SCEVUnknown *Expr)
const SCEV * visitMulExpr(const SCEVMulExpr *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:2007
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1056
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:420
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1561
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1533
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:969
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:203
APInt abs() const
Get the absolute value.
Definition APInt.h:1816
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1206
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:368
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1187
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:377
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition APInt.h:463
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1693
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1509
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1116
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:206
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:213
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:326
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1171
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1971
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:216
bool isNonPositive() const
Determine if this APInt Value is non-positive (<= 0).
Definition APInt.h:358
unsigned countTrailingZeros() const
Definition APInt.h:1668
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:353
unsigned logBase2() const
Definition APInt.h:1782
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:472
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:830
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1301
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1155
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1029
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:876
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:437
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:303
bool isSignBitSet() const
Determine if sign bit of this APInt is set.
Definition APInt.h:338
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1135
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:197
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition APInt.h:429
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1242
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:236
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1226
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
AnalysisUsage & addRequiredTransitive()
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
MutableArrayRef< WeakVH > assumptions()
Access the list of assumption handles currently tracked for this function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction & front() const
Definition BasicBlock.h:469
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI unsigned getNoWrapKind() const
Returns one of OBO::NoSignedWrap or OBO::NoUnsignedWrap.
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
This class represents a function call, abstracting a target machine's calling convention.
virtual void deleted()
Callback for Value destruction.
void setValPtr(Value *P)
bool isFalseWhenEqual() const
This is just a convenience.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
bool isSigned() const
Definition InstrTypes.h:993
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
bool isUnsigned() const
Definition InstrTypes.h:999
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Definition InstrTypes.h:989
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
LLVM_ABI CmpInst::Predicate getPreferredSignedPredicate() const
Attempts to return a signed CmpInst::Predicate from the CmpPredicate.
CmpInst::Predicate dropSameSign() const
Drops samesign information.
Conditional Branch instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static LLVM_ABI Constant * getNot(Constant *C)
static Constant * getPtrAdd(Constant *Ptr, Constant *Offset, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReduced=nullptr)
Create a getelementptr i8, ptr, offset constant expression.
Definition Constants.h:1497
static LLVM_ABI Constant * getPtrToAddr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
This class represents a range of values.
LLVM_ABI ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
LLVM_ABI ConstantRange zextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
LLVM_ABI bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const
Set up Pred and RHS such that ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.
const APInt & getLower() const
Return the lower value for this range.
LLVM_ABI ConstantRange urem(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned remainder operation of...
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI ConstantRange zeroExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
LLVM_ABI bool isSignWrappedSet() const
Return true if this set wraps around the signed domain.
LLVM_ABI APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
LLVM_ABI bool isWrappedSet() const
Return true if this set wraps around the unsigned domain.
LLVM_ABI void print(raw_ostream &OS) const
Print out the bounds to a stream.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
LLVM_ABI ConstantRange signExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
const APInt & getUpper() const
Return the upper value for this range.
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static LLVM_ABI ConstantRange makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp, const ConstantRange &Other, unsigned NoWrapKind)
Produce the largest range containing all X such that "X BinOp Y" is guaranteed not to wrap (overflow)...
LLVM_ABI unsigned getMinSignedBits() const
Compute the maximal number of bits needed to represent every value in this signed range.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
LLVM_ABI ConstantRange sextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
static LLVM_ABI ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp, const APInt &Other, unsigned NoWrapKind)
Produce the range that contains X if and only if "X BinOp Other" does not wrap.
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
LLVM_ABI IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:791
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:250
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:299
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition DenseMap.h:133
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive,...
Definition DenseMap.h:236
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:219
iterator end()
Definition DenseMap.h:141
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:214
void swap(DerivedT &RHS)
Definition DenseMap.h:437
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This class describes a reference to an interned FoldingSetNodeID, which can be a useful to store node...
Definition FoldingSet.h:175
This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:212
void AddInteger(signed I)
Definition FoldingSet.h:241
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.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI bool isIdenticalToWhenDefined(const Instruction *I, bool IntersectAttrs=false) const LLVM_READONLY
This is like isIdenticalTo, except that it ignores the SubclassOptionalData flags,...
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:348
A helper class to return the specified delimiter string after the first invocation of operator String...
An instruction for reading from memory.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
BlockT * getHeader() const
unsigned getLoopDepth() const
Return the nesting level of this loop.
BlockT * getLoopPredecessor() const
If the given loop's header has exactly one unique predecessor outside the loop, return it.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
unsigned getLoopDepth(const BlockT *BB) const
Return the loop nesting level of the specified block.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:619
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:67
Metadata node.
Definition Metadata.h:1069
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition Operator.h:113
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition Operator.h:107
iterator_range< const_block_iterator > blocks() const
op_range incoming_values()
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
PointerIntPair - This class implements a pair of a pointer and small integer.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
LLVM_ABI void addPredicate(const SCEVPredicate &Pred)
Adds a new predicate.
LLVM_ABI const SCEVPredicate & getPredicate() const
LLVM_ABI const SCEV * getPredicatedSCEV(const SCEV *Expr)
Returns the rewritten SCEV for Expr in the context of the current SCEV predicate.
LLVM_ABI bool areAddRecsEqualWithPreds(const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2, ArrayRef< const SCEVPredicate * > ExtraPreds={}) const
Check if AR1 and AR2 are equal, while taking into account Equal predicates in Preds and ExtraPreds.
LLVM_ABI bool hasNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags)
Returns true if we've statically proved that V doesn't wrap.
LLVM_ABI const SCEVAddRecExpr * getAsAddRec(Value *V, SmallVectorImpl< const SCEVPredicate * > *WrapPredsAdded=nullptr)
Attempts to produce an AddRecExpr for V by adding additional SCEV predicates.
LLVM_ABI void print(raw_ostream &OS, unsigned Depth) const
Print the SCEV mappings done by the Predicated Scalar Evolution.
LLVM_ABI PredicatedScalarEvolution(ScalarEvolution &SE, Loop &L)
LLVM_ABI unsigned getSmallConstantMaxTripCount()
Returns the upper bound of the loop trip count as a normal unsigned value, or 0 if the trip count is ...
LLVM_ABI void addPredicates(ArrayRef< const SCEVPredicate * > Preds)
Adds all predicates in Preds.
LLVM_ABI const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSymbolicMaxBackedgeTakenCount()
Get the (predicated) symbolic max backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
constexpr bool isValid() const
Definition Register.h:112
This node represents an addition of some number of SCEVs.
This node represents a polynomial recurrence on the trip count of the specified loop.
LLVM_ABI const SCEV * evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const
Return the value of this chain of recurrences at the specified iteration number.
void setNoWrapFlags(NoWrapFlags Flags)
Set flags for a recurrence without clearing any previously set flags.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
bool isQuadratic() const
Return true if this represents an expression A + B*x + C*x^2 where A, B and C are loop invariant valu...
LLVM_ABI const SCEV * getNumIterationsInRange(const ConstantRange &Range, ScalarEvolution &SE) const
Return the number of iterations of this loop that produce values in the specified constant range.
LLVM_ABI const SCEVAddRecExpr * getPostIncExpr(ScalarEvolution &SE) const
Return an expression representing the value of this expression one iteration of the loop ahead.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This is the base class for unary cast operator classes.
LLVM_ABI SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, SCEVUse op, Type *ty)
void setNoWrapFlags(NoWrapFlags Flags)
Set flags for a non-recurrence without clearing previously set flags.
This class represents an assumption that the expression LHS Pred RHS evaluates to true,...
SCEVComparePredicate(const FoldingSetNodeIDRef ID, const ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
bool isAlwaysTrue() const override
Returns true if the predicate is always true.
void print(raw_ostream &OS, unsigned Depth=0) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Implementation of the SCEVPredicate interface.
This class represents a constant integer value.
ConstantInt * getValue() const
const APInt & getAPInt() const
This is the base class for unary integral cast operator classes.
LLVM_ABI SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, SCEVUse op, Type *ty)
This node is the base class min/max selections.
static enum SCEVTypes negate(enum SCEVTypes T)
This node represents multiplication of some number of SCEVs.
This node is a base class providing common functionality for n'ary operators.
ArrayRef< SCEVUse > operands() const
NoWrapFlags getNoWrapFlags(NoWrapFlags Mask=NoWrapMask) const
SCEVUse getOperand(unsigned i) const
This class represents an assumption made using SCEV expressions which can be checked at run-time.
SCEVPredicate(const SCEVPredicate &)=default
virtual bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const =0
Returns true if this predicate implies N.
SCEVPredicateKind Kind
This class represents a cast from a pointer to a pointer-sized integer value, without capturing the p...
This visitor recursively visits a SCEV expression and re-writes it.
const SCEV * visitSignExtendExpr(const SCEVSignExtendExpr *Expr)
const SCEV * visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr)
const SCEV * visitSMinExpr(const SCEVSMinExpr *Expr)
const SCEV * visitUMinExpr(const SCEVUMinExpr *Expr)
This class represents a signed minimum selection.
This node is the base class for sequential/in-order min/max selections.
static SCEVTypes getEquivalentNonSequentialSCEVType(SCEVTypes Ty)
This class represents a sign extension of a small integer value to a larger integer value.
Visit all nodes in the expression tree using worklist traversal.
This class represents a truncation of an integer value to a smaller integer value.
This class represents a binary unsigned division operation.
This class represents an unsigned minimum selection.
This class represents a composition of other SCEV predicates, and is the class that most clients will...
void print(raw_ostream &OS, unsigned Depth) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Returns true if this predicate implies N.
SCEVUnionPredicate(ArrayRef< const SCEVPredicate * > Preds, ScalarEvolution &SE)
Union predicates don't get cached so create a dummy set ID for it.
bool isAlwaysTrue() const override
Implementation of the SCEVPredicate interface.
SCEVUnionPredicate getUnionWith(const SCEVPredicate *N, ScalarEvolution &SE) const
Returns a new SCEVUnionPredicate that is the union of this predicate and the given predicate N.
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
This class represents the value of vscale, as used when defining the length of a scalable vector or r...
This class represents an assumption made on an AddRec expression.
IncrementWrapFlags
Similar to SCEV::NoWrapFlags, but with slightly different semantics for FlagNUSW.
SCEVWrapPredicate(const FoldingSetNodeIDRef ID, const SCEVAddRecExpr *AR, IncrementWrapFlags Flags)
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Returns true if this predicate implies N.
static SCEVWrapPredicate::IncrementWrapFlags setFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OnFlags)
void print(raw_ostream &OS, unsigned Depth=0) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool isAlwaysTrue() const override
Returns true if the predicate is always true.
const SCEVAddRecExpr * getExpr() const
Implementation of the SCEVPredicate interface.
static SCEVWrapPredicate::IncrementWrapFlags clearFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OffFlags)
Convenient IncrementWrapFlags manipulation methods.
static SCEVWrapPredicate::IncrementWrapFlags getImpliedFlags(const SCEVAddRecExpr *AR, ScalarEvolution &SE)
Returns the set of SCEVWrapPredicate no wrap flags implied by a SCEVAddRecExpr.
IncrementWrapFlags getFlags() const
Returns the set assumed no overflow flags.
This class represents a zero extension of a small integer value to a larger integer value.
This class represents an analyzed expression in the program.
unsigned short getExpressionSize() const
SCEVNoWrapFlags NoWrapFlags
LLVM_ABI bool isOne() const
Return true if the expression is a constant one.
SCEV(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, unsigned short ExpressionSize, Type *Ty)
static constexpr auto FlagNUW
LLVM_ABI void computeAndSetCanonical(ScalarEvolution &SE)
Compute and set the canonical SCEV, by constructing a SCEV with the same operands,...
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
const SCEV * CanonicalSCEV
Pointer to the canonical version of the SCEV, i.e.
static constexpr auto FlagAnyWrap
LLVM_ABI void dump() const
This method is used for debugging.
LLVM_ABI bool isAllOnesValue() const
Return true if the expression is a constant all-ones value.
LLVM_ABI bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
static constexpr auto FlagNSW
LLVM_ABI ArrayRef< SCEVUse > operands() const
Return operands of this SCEV expression.
Type * getType() const
Return the LLVM type of this SCEV expression.
LLVM_ABI void print(raw_ostream &OS) const
Print out the internal representation of this scalar to the specified stream.
SCEVTypes getSCEVType() const
static constexpr auto FlagNW
Analysis pass that exposes the ScalarEvolution for a function.
LLVM_ABI ScalarEvolution run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void print(raw_ostream &OS, const Module *=nullptr) const override
print - Print out the internal state of the pass.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
static LLVM_ABI LoopGuards collect(const Loop *L, ScalarEvolution &SE)
Collect rewrite map for loop guards for loop L, together with flags indicating if NUW and NSW can be ...
LLVM_ABI const SCEV * rewrite(const SCEV *Expr) const
Try to apply the collected loop guards to Expr.
The main scalar evolution driver.
LLVM_ABI const SCEV * getUDivExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
const SCEV * getConstantMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
static bool hasFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags TestFlags)
const DataLayout & getDataLayout() const
Return the DataLayout associated with the module this SCEV instance is operating on.
LLVM_ABI bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
LLVM_ABI bool isKnownOnEveryIteration(CmpPredicate Pred, const SCEVAddRecExpr *LHS, const SCEV *RHS)
Test if the condition described by Pred, LHS, RHS is known to be true on every iteration of the loop ...
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantExitCondDuringFirstIterationsImpl(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI, const SCEV *MaxIter)
LLVM_ABI const SCEV * getZeroExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getUDivCeilSCEV(const SCEV *N, const SCEV *D)
Compute ceil(N / D).
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantExitCondDuringFirstIterations(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI, const SCEV *MaxIter)
If the result of the predicate LHS Pred RHS is loop invariant with respect to L at given Context duri...
LLVM_ABI Type * getWiderType(Type *Ty1, Type *Ty2) const
LLVM_ABI const SCEV * getAbsExpr(const SCEV *Op, bool IsNSW)
LLVM_ABI bool isKnownNonPositive(const SCEV *S)
Test if the given expression is known to be non-positive.
LLVM_ABI bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
LLVM_ABI const SCEV * getPredicatedConstantMaxBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getConstantMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
LLVM_ABI const SCEV * removePointerBase(const SCEV *S)
Compute an expression equivalent to S - getPointerBase(S).
LLVM_ABI bool isLoopEntryGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the loop is protected by a conditional between LHS and RHS.
LLVM_ABI bool isKnownNonZero(const SCEV *S)
Test if the given expression is known to be non-zero.
LLVM_ABI const SCEV * getURemExpr(SCEVUse LHS, SCEVUse RHS)
Represents an unsigned remainder expression based on unsigned division.
LLVM_ABI const SCEV * getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LLVM_ABI const SCEV * getSMinExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI void setNoWrapFlags(SCEVAddRecExpr *AddRec, SCEV::NoWrapFlags Flags)
Update no-wrap flags of an AddRec.
LLVM_ABI const SCEV * getUMaxFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS)
Promote the operands to the wider of the types using zero-extension, and then perform a umax operatio...
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
LLVM_ABI bool willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI=nullptr)
Is operation BinOp between LHS and RHS provably does not have a signed/unsigned overflow (Signed)?
LLVM_ABI ExitLimit computeExitLimitFromCond(const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit, bool AllowPredicates=false)
Compute the number of times the backedge of the specified loop will execute if its exit condition wer...
LLVM_ABI const SCEV * getMinMaxExpr(SCEVTypes Kind, SmallVectorImpl< SCEVUse > &Operands)
LLVM_ABI const SCEVPredicate * getEqualPredicate(const SCEV *LHS, const SCEV *RHS)
LLVM_ABI unsigned getSmallConstantTripMultiple(const Loop *L, const SCEV *ExitCount)
Returns the largest constant divisor of the trip count as a normal unsigned value,...
LLVM_ABI uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getPredicatedBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getBackedgeTakenCount, except it will add a set of SCEV predicates to Predicates that are ...
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
ConstantRange getSignedRange(const SCEV *S)
Determine the signed range for a particular SCEV.
LLVM_ABI const SCEV * getAddRecExpr(SCEVUse Start, SCEVUse Step, const Loop *L, SCEV::NoWrapFlags Flags)
Get an add recurrence expression for the specified loop.
LLVM_ABI const SCEV * getNoopOrSignExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
static LLVM_ABI bool isGuaranteedNotToBePoison(const SCEV *Op)
Returns true if Op is guaranteed to not be poison.
bool loopHasNoAbnormalExits(const Loop *L)
Return true if the loop has no abnormal exits.
LLVM_ABI const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
LLVM_ABI ScalarEvolution(Function &F, TargetLibraryInfo &TLI, AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI)
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI const SCEV * getTruncateOrNoop(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI const SCEV * getSequentialMinMaxExpr(SCEVTypes Kind, SmallVectorImpl< SCEVUse > &Operands)
LLVM_ABI const SCEV * getCastExpr(SCEVTypes Kind, SCEVUse Op, Type *Ty)
LLVM_ABI std::optional< bool > evaluatePredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Check whether the condition described by Pred, LHS, and RHS is true or false in the given Context.
LLVM_ABI unsigned getSmallConstantMaxTripCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Returns the upper bound of the loop trip count as a normal unsigned value.
LLVM_ABI bool isBackedgeTakenCountMaxOrZero(const Loop *L)
Return true if the backedge taken count is either the value returned by getConstantMaxBackedgeTakenCo...
LLVM_ABI void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI bool isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
LLVM_ABI bool SimplifyICmpOperands(CmpPredicate &Pred, SCEVUse &LHS, SCEVUse &RHS, unsigned Depth=0)
Simplify LHS and RHS in a comparison with predicate Pred.
APInt getUnsignedRangeMin(const SCEV *S)
Determine the min of the unsigned range for a particular SCEV.
LLVM_ABI const SCEV * getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo)
Return an expression for offsetof on the given field with type IntTy.
LLVM_ABI LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L)
Return the "disposition" of the given SCEV with respect to the given loop.
LLVM_ABI bool containsAddRecurrence(const SCEV *S)
Return true if the SCEV is a scAddRecExpr or it contains scAddRecExpr.
LLVM_ABI const SCEV * getTruncateExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool hasOperand(const SCEV *S, const SCEV *Op) const
Test whether the given SCEV has Op as a direct or indirect operand.
LLVM_ABI const SCEV * getZeroExtendExprImpl(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI Type * getEffectiveSCEVType(Type *Ty) const
Return a type with the same bitwidth as the given type and which represents how SCEV will treat the g...
LLVM_ABI const SCEVPredicate * getComparePredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
LLVM_ABI bool haveSameSign(const SCEV *S1, const SCEV *S2)
Return true if we know that S1 and S2 must have the same sign.
LLVM_ABI const SCEV * getNotSCEV(const SCEV *V)
Return the SCEV object corresponding to ~V.
LLVM_ABI const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
LLVM_ABI bool instructionCouldExistWithOperands(const SCEV *A, const SCEV *B)
Return true if there exists a point in the program at which both A and B could be operands to the sam...
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
LLVM_ABI void print(raw_ostream &OS) const
LLVM_ABI const SCEV * getAnyExtendExpr(SCEVUse Op, Type *Ty)
getAnyExtendExpr - Return a SCEV for the given operand extended with unspecified bits out to the give...
LLVM_ABI const SCEV * getPredicatedExitCount(const Loop *L, const BasicBlock *ExitingBlock, SmallVectorImpl< const SCEVPredicate * > *Predicates, ExitCountKind Kind=Exact)
Same as above except this uses the predicated backedge taken info and may require predicates.
static SCEV::NoWrapFlags clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags)
LLVM_ABI void forgetTopmostLoop(const Loop *L)
LLVM_ABI void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
APInt getSignedRangeMin(const SCEV *S)
Determine the min of the signed range for a particular SCEV.
LLVM_ABI bool isLoopUniform(const SCEV *S, const Loop *L)
Returns true if the given SCEV is loop-uniform with respect to the specified loop L.
LLVM_ABI const SCEV * getNoopOrAnyExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
LLVM_ABI const SCEV * getSignExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getUMaxExpr(SCEVUse LHS, SCEVUse RHS)
static SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags Mask)
Convenient NoWrapFlags manipulation.
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantPredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI=nullptr)
If the result of the predicate LHS Pred RHS is loop invariant with respect to L, return a LoopInvaria...
LLVM_ABI const SCEV * getStoreSizeOfExpr(Type *IntTy, Type *StoreTy)
Return an expression for the store size of StoreTy that is type IntTy.
LLVM_ABI const SCEVPredicate * getWrapPredicate(const SCEVAddRecExpr *AR, SCEVWrapPredicate::IncrementWrapFlags AddedFlags)
LLVM_ABI bool isLoopBackedgeGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether the backedge of the loop is protected by a conditional between LHS and RHS.
LLVM_ABI APInt getNonZeroConstantMultiple(const SCEV *S)
const SCEV * getMinusOne(Type *Ty)
Return a SCEV for the constant -1 of a specific type.
static SCEV::NoWrapFlags setFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OnFlags)
LLVM_ABI bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count.
LLVM_ABI BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB)
Return the "disposition" of the given SCEV with respect to the given block.
LLVM_ABI const SCEV * getNoopOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
LLVM_ABI const SCEV * getUMinFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS, bool Sequential=false)
Promote the operands to the wider of the types using zero-extension, and then perform a umin operatio...
LLVM_ABI bool loopIsFiniteByAssumption(const Loop *L)
Return true if this loop is finite by assumption.
LLVM_ABI const SCEV * getExistingSCEV(Value *V)
Return an existing SCEV for V if there is one, otherwise return nullptr.
LLVM_ABI APInt getConstantMultiple(const SCEV *S, const Instruction *CtxI=nullptr)
Returns the max constant multiple of S.
LoopDisposition
An enum describing the relationship between a SCEV and a loop.
@ LoopComputable
The SCEV varies predictably with the loop.
@ LoopVariant
The SCEV is loop-variant (unknown).
@ LoopInvariant
The SCEV is loop-invariant.
@ LoopUniform
The SCEV is loop-uniform.
LLVM_ABI bool isKnownMultipleOf(const SCEV *S, uint64_t M, SmallVectorImpl< const SCEVPredicate * > &Assumptions)
Check that S is a multiple of M.
LLVM_ABI bool isKnownToBeAPowerOfTwo(const SCEV *S, bool OrZero=false, bool OrNegative=false)
Test if the given expression is known to be a power of 2.
LLVM_ABI std::optional< SCEV::NoWrapFlags > getStrengthenedNoWrapFlagsFromBinOp(const OverflowingBinaryOperator *OBO)
Parse NSW/NUW flags from add/sub/mul IR binary operation Op into SCEV no-wrap flags,...
LLVM_ABI void forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V)
Forget LCSSA phi node V of loop L to which a new predecessor was added, such that it may no longer be...
LLVM_ABI bool containsUndefs(const SCEV *S) const
Return true if the SCEV expression contains an undef value.
LLVM_ABI std::optional< MonotonicPredicateType > getMonotonicPredicateType(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred)
If, for all loop invariant X, the predicate "LHS `Pred` X" is monotonically increasing or decreasing,...
LLVM_ABI const SCEV * getCouldNotCompute()
LLVM_ABI const SCEV * getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
LLVM_ABI bool isAvailableAtLoopEntry(const SCEV *S, const Loop *L)
Determine if the SCEV can be evaluated at loop's entry.
LLVM_ABI uint32_t getMinTrailingZeros(const SCEV *S, const Instruction *CtxI=nullptr)
Determine the minimum number of zero bits that S is guaranteed to end in (at every loop iteration).
BlockDisposition
An enum describing the relationship between a SCEV and a basic block.
@ DominatesBlock
The SCEV dominates the block.
@ ProperlyDominatesBlock
The SCEV properly dominates the block.
@ DoesNotDominateBlock
The SCEV does not dominate the block.
LLVM_ABI const SCEV * getExitCount(const Loop *L, const BasicBlock *ExitingBlock, ExitCountKind Kind=Exact)
Return the number of times the backedge executes before the given exit would be taken; if not exactly...
LLVM_ABI void getPoisonGeneratingValues(SmallPtrSetImpl< const Value * > &Result, const SCEV *S)
Return the set of Values that, if poison, will definitively result in S being poison as well.
LLVM_ABI void forgetLoopDispositions()
Called when the client has changed the disposition of values in this loop.
LLVM_ABI const SCEV * getVScale(Type *Ty)
LLVM_ABI unsigned getSmallConstantTripCount(const Loop *L)
Returns the exact trip count of the loop if we can compute it, and the result is a small constant.
LLVM_ABI bool hasComputableLoopEvolution(const SCEV *S, const Loop *L)
Return true if the given SCEV changes value in a known way in the specified loop.
LLVM_ABI const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
LLVM_ABI void forgetAllLoops()
LLVM_ABI const SCEV * getSignExtendExprImpl(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool dominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV dominate the specified basic block.
APInt getUnsignedRangeMax(const SCEV *S)
Determine the max of the unsigned range for a particular SCEV.
LLVM_ABI const SCEV * getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
ExitCountKind
The terms "backedge taken count" and "exit count" are used interchangeably to refer to the number of ...
@ SymbolicMaximum
An expression which provides an upper bound on the exact trip count.
@ ConstantMaximum
A constant which provides an upper bound on the exact trip count.
@ Exact
An expression exactly describing the number of times the backedge has executed when a loop is exited.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
LLVM_ABI const SCEV * getPtrToAddrExpr(const SCEV *Op)
LLVM_ABI const SCEVAddRecExpr * convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Preds)
Tries to convert the S expression to an AddRec expression, adding additional predicates to Preds as r...
LLVM_ABI const SCEV * getSMaxExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI const SCEV * getElementSize(Instruction *Inst)
Return the size of an element read or written by Inst.
LLVM_ABI const SCEV * getSizeOfExpr(Type *IntTy, TypeSize Size)
Return an expression for a TypeSize.
LLVM_ABI std::optional< bool > evaluatePredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Check whether the condition described by Pred, LHS, and RHS is true or false.
LLVM_ABI const SCEV * getUnknown(Value *V)
LLVM_ABI std::optional< std::pair< const SCEV *, SmallVector< const SCEVPredicate *, 3 > > > createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI)
Checks if SymbolicPHI can be rewritten as an AddRecExpr under some Predicates.
LLVM_ABI const SCEV * getTruncateOrZeroExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool isKnownViaInduction(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
We'd like to check the predicate on every iteration of the most dominated loop between loops used in ...
LLVM_ABI std::optional< APInt > computeConstantDifference(const SCEV *LHS, const SCEV *RHS)
Compute LHS - RHS and returns the result as an APInt if it is a constant, and std::nullopt if it isn'...
LLVM_ABI bool properlyDominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV properly dominate the specified basic block.
LLVM_ABI const SCEV * getUDivExactExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
LLVM_ABI const SCEV * rewriteUsingPredicate(const SCEV *S, const Loop *L, const SCEVPredicate &A)
Re-writes the SCEV according to the Predicates in A.
LLVM_ABI std::pair< const SCEV *, const SCEV * > SplitIntoInitAndPostInc(const Loop *L, const SCEV *S)
Splits SCEV expression S into two SCEVs.
LLVM_ABI bool canReuseInstruction(const SCEV *S, Instruction *I, SmallVectorImpl< Instruction * > &DropPoisonGeneratingInsts)
Check whether it is poison-safe to represent the expression S using the instruction I.
LLVM_ABI bool isKnownPredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * getPredicatedSymbolicMaxBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getSymbolicMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
LLVM_ABI const SCEV * getGEPExpr(GEPOperator *GEP, ArrayRef< SCEVUse > IndexExprs)
Returns an expression for a GEP.
LLVM_ABI const SCEV * getUMinExpr(SCEVUse LHS, SCEVUse RHS, bool Sequential=false)
LLVM_ABI void registerUser(const SCEV *User, ArrayRef< const SCEV * > Ops)
Notify this ScalarEvolution that User directly uses SCEVs in Ops.
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
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:293
size_type size() const
Definition SmallPtrSet.h:99
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:743
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
TypeSize getSizeInBits() const
Definition DataLayout.h:754
Class to represent struct types.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:306
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:313
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
Use & Op()
Definition User.h:171
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
iterator_range< user_iterator > users()
Definition Value.h:426
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition Value.h:543
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition APInt.h:2275
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition APInt.h:2280
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition APInt.h:2285
LLVM_ABI std::optional< APInt > SolveQuadraticEquationWrap(APInt A, APInt B, APInt C, unsigned RangeWidth)
Let q(n) = An^2 + Bn + C, and BW = bit width of the value range (e.g.
Definition APInt.cpp:2848
LLVM_ABI APInt GreatestCommonDivisor(APInt A, APInt B, bool IsSigned=false)
Compute GCD of two APInt values.
Definition APInt.cpp:825
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2290
constexpr bool any(E Val)
@ Entry
Definition COFF.h:862
int getMinValue(MCInstrInfo const &MCII, MCInst const &MCI)
Return the minimum value of an extendable operand.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
bind_cst_ty m_scev_APInt(const APInt *&C)
Match an SCEV constant and bind it to an APInt.
cst_pred_ty< is_all_ones > m_scev_AllOnes()
Match an integer with all bits set.
SCEVUnaryExpr_match< SCEVZeroExtendExpr, Op0_t > m_scev_ZExt(const Op0_t &Op0)
is_undef_or_poison m_scev_UndefOrPoison()
Match an SCEVUnknown wrapping undef or poison.
cst_pred_ty< is_one > m_scev_One()
Match an integer 1.
specificloop_ty m_SpecificLoop(const Loop *L)
SCEVUnaryExpr_match< SCEVSignExtendExpr, Op0_t > m_scev_SExt(const Op0_t &Op0)
match_bind< const SCEVMulExpr > m_scev_Mul(const SCEVMulExpr *&V)
cst_pred_ty< is_zero > m_scev_Zero()
Match an integer 0.
SCEVUnaryExpr_match< SCEVTruncateExpr, Op0_t > m_scev_Trunc(const Op0_t &Op0)
bool match(const SCEV *S, const Pattern &P)
SCEVBinaryExpr_match< SCEVUDivExpr, Op0_t, Op1_t > m_scev_UDiv(const Op0_t &Op0, const Op1_t &Op1)
specificscev_ty m_scev_Specific(const SCEV *S)
Match if we have a specific specified SCEV.
SCEVAffineAddRec_match< Op0_t, Op1_t, match_isa< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
match_bind< const SCEVUnknown > m_SCEVUnknown(const SCEVUnknown *&V)
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t, SCEV::FlagNUW, true > m_scev_c_NUWMul(const Op0_t &Op0, const Op1_t &Op1)
match_bind< const SCEVAddExpr > m_scev_Add(const SCEVAddExpr *&V)
SCEVBinaryExpr_match< SCEVSMaxExpr, Op0_t, Op1_t, SCEV::FlagAnyWrap, true > m_scev_SMax(const Op0_t &Op0, const Op1_t &Op1)
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t, SCEV::FlagAnyWrap, true > m_scev_c_Mul(const Op0_t &Op0, const Op1_t &Op1)
SCEVURem_match< Op0_t, Op1_t > m_scev_URem(Op0_t LHS, Op1_t RHS, ScalarEvolution &SE)
Match the mathematical pattern A - (A / B) * B, where A and B can be arbitrary expressions.
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
Definition CoroShape.h:32
constexpr double e
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
void visitAll(const SCEV *Root, SV &Visitor)
Use SCEVTraversal to visit all nodes in the given expression tree.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
@ Offset
Definition DWP.cpp:578
void stable_sort(R &&Range)
Definition STLExtras.h:2116
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
SaveAndRestore(T &) -> SaveAndRestore< T >
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
LLVM_ABI bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
LLVM_ABI bool mustTriggerUB(const Instruction *I, const SmallPtrSetImpl< const Value * > &KnownPoison)
Return true if the given instruction must trigger undefined behavior when I is executed with any oper...
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
@ Known
Known to have no common set bits.
@ Dead
Unused definition.
LLVM_ABI bool canConstantFoldCallTo(const CallBase *Call, const Function *F)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function.
InterleavedRange< Range > interleaved(const Range &R, StringRef Separator=", ", StringRef Prefix="", StringRef Suffix="")
Output range R as a sequence of interleaved elements.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
auto successors(const MachineBasicBlock *BB)
scope_exit(Callable) -> scope_exit< Callable >
@ BinaryOp
One of the operands is a binary op.
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
constexpr from_range_t from_range
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
bool set_is_subset(const S1Ty &S1, const S2Ty &S2)
set_is_subset(A, B) - Return true iff A in B
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Instruction *I=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
void * PointerTy
LLVM_ABI bool VerifySCEV
auto uninitialized_copy(R &&Src, IterTy Dst)
Definition STLExtras.h:2111
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, const DominatorTree &DT)
Returns true if the arithmetic part of the WO 's result is used only along the paths control dependen...
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2200
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
LLVM_ABI bool isMustProgress(const Loop *L)
Return true if this loop can be assumed to make progress.
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
LLVM_ABI bool isFinite(const Loop *L)
Return true if this loop can be assumed to run for a finite number of iterations.
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
unsigned short computeExpressionSize(ArrayRef< SCEVUse > Args)
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:383
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
LLVM_ABI bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ Mul
Product of integers.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ Add
Sum of integers.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2012
DWARFExpression::Operation Op
auto max_element(R &&Range)
Provide wrappers to std::max_element which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2088
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2019
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:249
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
iterator_range< df_iterator< T > > depth_first(const T &G)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
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.
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:
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.