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
242 "scalar-evolution-max-scc-analysis-depth", cl::Hidden,
243 cl::desc("Maximum amount of nodes to process while searching SCEVUnknown "
244 "Phi strongly connected components"),
245 cl::init(8));
246
247static cl::opt<bool>
248 EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
249 cl::desc("Handle <= and >= in finite loops"),
250 cl::init(true));
251
253 "scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden,
254 cl::desc("Infer nuw/nsw flags using context where suitable"),
255 cl::init(true));
256
257//===----------------------------------------------------------------------===//
258// SCEV class definitions
259//===----------------------------------------------------------------------===//
260
262 // Leaf nodes are always their own canonical.
263 switch (getSCEVType()) {
264 case scConstant:
265 case scVScale:
266 case scUnknown:
267 CanonicalSCEV = this;
268 return;
269 default:
270 break;
271 }
272
273 // For all other expressions, check whether any immediate operand has a
274 // different canonical. Since operands are always created before their parent,
275 // their canonical pointers are already set — no recursion needed.
276 bool Changed = false;
278 for (SCEVUse Op : operands()) {
279 CanonOps.push_back(Op->getCanonical());
280 Changed |= CanonOps.back() != Op.getPointer();
281 }
282
283 if (!Changed) {
284 CanonicalSCEV = this;
285 return;
286 }
287
288 auto *NAry = dyn_cast<SCEVNAryExpr>(this);
289 SCEV::NoWrapFlags Flags = NAry ? NAry->getNoWrapFlags() : SCEV::FlagAnyWrap;
290 switch (getSCEVType()) {
291 case scPtrToAddr:
292 CanonicalSCEV = SE.getPtrToAddrExpr(CanonOps[0]);
293 return;
294 case scTruncate:
295 CanonicalSCEV = SE.getTruncateExpr(CanonOps[0], getType());
296 return;
297 case scZeroExtend:
298 CanonicalSCEV = SE.getZeroExtendExpr(CanonOps[0], getType());
299 return;
300 case scSignExtend:
301 CanonicalSCEV = SE.getSignExtendExpr(CanonOps[0], getType());
302 return;
303 case scUDivExpr:
304 CanonicalSCEV = SE.getUDivExpr(CanonOps[0], CanonOps[1]);
305 return;
306 case scAddExpr:
307 CanonicalSCEV = SE.getAddExpr(CanonOps, Flags);
308 return;
309 case scMulExpr:
310 CanonicalSCEV = SE.getMulExpr(CanonOps, Flags);
311 return;
312 case scAddRecExpr:
314 CanonOps, cast<SCEVAddRecExpr>(this)->getLoop(), Flags);
315 return;
316 case scSMaxExpr:
317 CanonicalSCEV = SE.getSMaxExpr(CanonOps);
318 return;
319 case scUMaxExpr:
320 CanonicalSCEV = SE.getUMaxExpr(CanonOps);
321 return;
322 case scSMinExpr:
323 CanonicalSCEV = SE.getSMinExpr(CanonOps);
324 return;
325 case scUMinExpr:
326 CanonicalSCEV = SE.getUMinExpr(CanonOps);
327 return;
329 CanonicalSCEV = SE.getUMinExpr(CanonOps, /*Sequential=*/true);
330 return;
331 default:
332 llvm_unreachable("Unknown SCEV type");
333 }
334}
335
336//===----------------------------------------------------------------------===//
337// Implementation of the SCEV class.
338//
339
340#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
342 print(dbgs());
343 dbgs() << '\n';
344}
345#endif
346
347void SCEV::print(raw_ostream &OS) const {
348 switch (getSCEVType()) {
349 case scConstant:
350 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
351 return;
352 case scVScale:
353 OS << "vscale";
354 return;
355 case scPtrToAddr: {
356 const SCEVCastExpr *PtrCast = cast<SCEVCastExpr>(this);
357 const SCEV *Op = PtrCast->getOperand();
358 OS << "(ptrtoaddr " << *Op->getType() << " " << *Op << " to "
359 << *PtrCast->getType() << ")";
360 return;
361 }
362 case scTruncate: {
363 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
364 const SCEV *Op = Trunc->getOperand();
365 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
366 << *Trunc->getType() << ")";
367 return;
368 }
369 case scZeroExtend: {
371 const SCEV *Op = ZExt->getOperand();
372 OS << "(zext " << *Op->getType() << " " << *Op << " to "
373 << *ZExt->getType() << ")";
374 return;
375 }
376 case scSignExtend: {
378 const SCEV *Op = SExt->getOperand();
379 OS << "(sext " << *Op->getType() << " " << *Op << " to "
380 << *SExt->getType() << ")";
381 return;
382 }
383 case scAddRecExpr: {
384 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
385 OS << "{" << *AR->getOperand(0);
386 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
387 OS << ",+," << *AR->getOperand(i);
388 OS << "}<";
389 if (AR->hasNoUnsignedWrap())
390 OS << "nuw><";
391 if (AR->hasNoSignedWrap())
392 OS << "nsw><";
393 if (AR->hasNoSelfWrap() && !AR->hasNoUnsignedWrap() &&
394 !AR->hasNoSignedWrap())
395 OS << "nw><";
396 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
397 OS << ">";
398 return;
399 }
400 case scAddExpr:
401 case scMulExpr:
402 case scUMaxExpr:
403 case scSMaxExpr:
404 case scUMinExpr:
405 case scSMinExpr:
407 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
408 const char *OpStr = nullptr;
409 switch (NAry->getSCEVType()) {
410 case scAddExpr: OpStr = " + "; break;
411 case scMulExpr: OpStr = " * "; break;
412 case scUMaxExpr: OpStr = " umax "; break;
413 case scSMaxExpr: OpStr = " smax "; break;
414 case scUMinExpr:
415 OpStr = " umin ";
416 break;
417 case scSMinExpr:
418 OpStr = " smin ";
419 break;
421 OpStr = " umin_seq ";
422 break;
423 default:
424 llvm_unreachable("There are no other nary expression types.");
425 }
426 OS << "("
428 << ")";
429 switch (NAry->getSCEVType()) {
430 case scAddExpr:
431 case scMulExpr:
432 if (NAry->hasNoUnsignedWrap())
433 OS << "<nuw>";
434 if (NAry->hasNoSignedWrap())
435 OS << "<nsw>";
436 break;
437 default:
438 // Nothing to print for other nary expressions.
439 break;
440 }
441 return;
442 }
443 case scUDivExpr: {
444 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
445 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
446 return;
447 }
448 case scUnknown:
449 cast<SCEVUnknown>(this)->getValue()->printAsOperand(OS, false);
450 return;
452 OS << "***COULDNOTCOMPUTE***";
453 return;
454 }
455 llvm_unreachable("Unknown SCEV kind!");
456}
457
459 switch (getSCEVType()) {
460 case scConstant:
461 case scVScale:
462 case scUnknown:
463 return {};
464 case scPtrToAddr:
465 case scTruncate:
466 case scZeroExtend:
467 case scSignExtend:
468 return cast<SCEVCastExpr>(this)->operands();
469 case scAddRecExpr:
470 case scAddExpr:
471 case scMulExpr:
472 case scUMaxExpr:
473 case scSMaxExpr:
474 case scUMinExpr:
475 case scSMinExpr:
477 return cast<SCEVNAryExpr>(this)->operands();
478 case scUDivExpr:
479 return cast<SCEVUDivExpr>(this)->operands();
481 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
482 }
483 llvm_unreachable("Unknown SCEV kind!");
484}
485
486bool SCEV::isZero() const { return match(this, m_scev_Zero()); }
487
488bool SCEV::isOne() const { return match(this, m_scev_One()); }
489
490bool SCEV::isAllOnesValue() const { return match(this, m_scev_AllOnes()); }
491
494 if (!Mul) return false;
495
496 // If there is a constant factor, it will be first.
497 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
498 if (!SC) return false;
499
500 // Return true if the value is negative, this matches things like (-42 * V).
501 return SC->getAPInt().isNegative();
502}
503
506
508 return S->getSCEVType() == scCouldNotCompute;
509}
510
512 auto &Entry = ConstantSCEVs[V];
513 if (Entry)
514 return Entry;
515
518 ID.AddPointer(V);
519 void *IP = nullptr;
520 if (SCEVConstant *S =
521 static_cast<SCEVConstant *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)))
522 return Entry = S;
523 SCEVConstant *S =
524 new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
525 UniqueSCEVs.InsertNode(S, IP);
526 S->computeAndSetCanonical(*this);
527 return Entry = S;
528}
529
531 return getConstant(ConstantInt::get(getContext(), Val));
532}
533
534const SCEV *
537 // TODO: Avoid implicit trunc?
538 // See https://github.com/llvm/llvm-project/issues/112510.
539 return getConstant(
540 ConstantInt::get(ITy, V, isSigned, /*ImplicitTrunc=*/true));
541}
542
546 ID.AddPointer(Ty);
547 void *IP = nullptr;
548 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
549 return S;
550 SCEV *S = new (SCEVAllocator) SCEVVScale(ID.Intern(SCEVAllocator), Ty);
551 UniqueSCEVs.InsertNode(S, IP);
552 S->computeAndSetCanonical(*this);
553 return S;
554}
555
557 SCEV::NoWrapFlags Flags) {
558 const SCEV *Res = getConstant(Ty, EC.getKnownMinValue());
559 if (EC.isScalable())
560 Res = getMulExpr(Res, getVScale(Ty), Flags);
561 return Res;
562}
563
565 SCEVUse op, Type *ty)
566 : SCEV(ID, SCEVTy, computeExpressionSize(op), ty), Op(op) {}
567
568SCEVPtrToAddrExpr::SCEVPtrToAddrExpr(const FoldingSetNodeIDRef ID,
569 const SCEV *Op, Type *ITy)
570 : SCEVCastExpr(ID, scPtrToAddr, Op, ITy) {
571 assert(getOperand()->getType()->isPointerTy() && getType()->isIntegerTy() &&
572 "Must be a non-bit-width-changing pointer-to-integer cast!");
573}
574
579
580SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
581 Type *ty)
583 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
584 "Cannot truncate non-integer value!");
585}
586
587SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
588 Type *ty)
590 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
591 "Cannot zero extend non-integer value!");
592}
593
594SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
595 Type *ty)
597 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
598 "Cannot sign extend non-integer value!");
599}
600
602 // Clear this SCEVUnknown from various maps.
603 SE->forgetMemoizedResults({this});
604
605 // Remove this SCEVUnknown from the uniquing map.
606 SE->UniqueSCEVs.RemoveNode(this);
607
608 // Release the value.
609 setValPtr(nullptr);
610}
611
612void SCEVUnknown::allUsesReplacedWith(Value *New) {
613 // Clear this SCEVUnknown from various maps.
614 SE->forgetMemoizedResults({this});
615
616 // Remove this SCEVUnknown from the uniquing map.
617 SE->UniqueSCEVs.RemoveNode(this);
618
619 // Replace the value pointer in case someone is still using this SCEVUnknown.
620 setValPtr(New);
621}
622
623//===----------------------------------------------------------------------===//
624// SCEV Utilities
625//===----------------------------------------------------------------------===//
626
627/// Compare the two values \p LV and \p RV in terms of their "complexity" where
628/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
629/// operands in SCEV expressions.
630static int CompareValueComplexity(const LoopInfo *const LI, Value *LV,
631 Value *RV, unsigned Depth) {
633 return 0;
634
635 // Order pointer values after integer values. This helps SCEVExpander form
636 // GEPs.
637 bool LIsPointer = LV->getType()->isPointerTy(),
638 RIsPointer = RV->getType()->isPointerTy();
639 if (LIsPointer != RIsPointer)
640 return (int)LIsPointer - (int)RIsPointer;
641
642 // Compare getValueID values.
643 unsigned LID = LV->getValueID(), RID = RV->getValueID();
644 if (LID != RID)
645 return (int)LID - (int)RID;
646
647 // Sort arguments by their position.
648 if (const auto *LA = dyn_cast<Argument>(LV)) {
649 const auto *RA = cast<Argument>(RV);
650 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
651 return (int)LArgNo - (int)RArgNo;
652 }
653
654 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
655 const auto *RGV = cast<GlobalValue>(RV);
656
657 if (auto L = LGV->getLinkage() - RGV->getLinkage())
658 return L;
659
660 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
661 auto LT = GV->getLinkage();
662 return !(GlobalValue::isPrivateLinkage(LT) ||
664 };
665
666 // Use the names to distinguish the two values, but only if the
667 // names are semantically important.
668 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
669 return LGV->getName().compare(RGV->getName());
670 }
671
672 // For instructions, compare their loop depth, and their operand count. This
673 // is pretty loose.
674 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
675 const auto *RInst = cast<Instruction>(RV);
676
677 // Compare loop depths.
678 const BasicBlock *LParent = LInst->getParent(),
679 *RParent = RInst->getParent();
680 if (LParent != RParent) {
681 unsigned LDepth = LI->getLoopDepth(LParent),
682 RDepth = LI->getLoopDepth(RParent);
683 if (LDepth != RDepth)
684 return (int)LDepth - (int)RDepth;
685 }
686
687 // Compare the number of operands.
688 unsigned LNumOps = LInst->getNumOperands(),
689 RNumOps = RInst->getNumOperands();
690 if (LNumOps != RNumOps)
691 return (int)LNumOps - (int)RNumOps;
692
693 for (unsigned Idx : seq(LNumOps)) {
694 int Result = CompareValueComplexity(LI, LInst->getOperand(Idx),
695 RInst->getOperand(Idx), Depth + 1);
696 if (Result != 0)
697 return Result;
698 }
699 }
700
701 return 0;
702}
703
704// Return negative, zero, or positive, if LHS is less than, equal to, or greater
705// than RHS, respectively. A three-way result allows recursive comparisons to be
706// more efficient.
707// If the max analysis depth was reached, return std::nullopt, assuming we do
708// not know if they are equivalent for sure.
709static std::optional<int>
710CompareSCEVComplexity(const LoopInfo *const LI, const SCEV *LHS,
711 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
712 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
713 if (LHS == RHS)
714 return 0;
715
716 // Primarily, sort the SCEVs by their getSCEVType().
717 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
718 if (LType != RType)
719 return (int)LType - (int)RType;
720
722 return std::nullopt;
723
724 // Aside from the getSCEVType() ordering, the particular ordering
725 // isn't very important except that it's beneficial to be consistent,
726 // so that (a + b) and (b + a) don't end up as different expressions.
727 switch (LType) {
728 case scUnknown: {
729 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
730 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
731
732 int X =
733 CompareValueComplexity(LI, LU->getValue(), RU->getValue(), Depth + 1);
734 return X;
735 }
736
737 case scConstant: {
740
741 // Compare constant values.
742 const APInt &LA = LC->getAPInt();
743 const APInt &RA = RC->getAPInt();
744 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
745 if (LBitWidth != RBitWidth)
746 return (int)LBitWidth - (int)RBitWidth;
747 return LA.ult(RA) ? -1 : 1;
748 }
749
750 case scVScale: {
751 const auto *LTy = cast<IntegerType>(cast<SCEVVScale>(LHS)->getType());
752 const auto *RTy = cast<IntegerType>(cast<SCEVVScale>(RHS)->getType());
753 return LTy->getBitWidth() - RTy->getBitWidth();
754 }
755
756 case scAddRecExpr: {
759
760 // There is always a dominance between two recs that are used by one SCEV,
761 // so we can safely sort recs by loop header dominance. We require such
762 // order in getAddExpr.
763 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
764 if (LLoop != RLoop) {
765 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
766 assert(LHead != RHead && "Two loops share the same header?");
767 if (DT.dominates(LHead, RHead))
768 return 1;
769 assert(DT.dominates(RHead, LHead) &&
770 "No dominance between recurrences used by one SCEV?");
771 return -1;
772 }
773
774 [[fallthrough]];
775 }
776
777 case scTruncate:
778 case scZeroExtend:
779 case scSignExtend:
780 case scPtrToAddr:
781 case scAddExpr:
782 case scMulExpr:
783 case scUDivExpr:
784 case scSMaxExpr:
785 case scUMaxExpr:
786 case scSMinExpr:
787 case scUMinExpr:
789 ArrayRef<SCEVUse> LOps = LHS->operands();
790 ArrayRef<SCEVUse> ROps = RHS->operands();
791
792 // Lexicographically compare n-ary-like expressions.
793 unsigned LNumOps = LOps.size(), RNumOps = ROps.size();
794 if (LNumOps != RNumOps)
795 return (int)LNumOps - (int)RNumOps;
796
797 for (unsigned i = 0; i != LNumOps; ++i) {
798 auto X = CompareSCEVComplexity(LI, LOps[i].getPointer(),
799 ROps[i].getPointer(), DT, Depth + 1);
800 if (X != 0)
801 return X;
802 }
803 return 0;
804 }
805
807 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
808 }
809 llvm_unreachable("Unknown SCEV kind!");
810}
811
812/// Given a list of SCEV objects, order them by their complexity, and group
813/// objects of the same complexity together by value. When this routine is
814/// finished, we know that any duplicates in the vector are consecutive and that
815/// complexity is monotonically increasing.
816///
817/// Note that we go take special precautions to ensure that we get deterministic
818/// results from this routine. In other words, we don't want the results of
819/// this to depend on where the addresses of various SCEV objects happened to
820/// land in memory.
822 DominatorTree &DT) {
823 if (Ops.size() < 2) return; // Noop
824
825 // Whether LHS has provably less complexity than RHS.
826 auto IsLessComplex = [&](SCEVUse LHS, SCEVUse RHS) {
827 auto Complexity = CompareSCEVComplexity(LI, LHS, RHS, DT);
828 return Complexity && *Complexity < 0;
829 };
830 if (Ops.size() == 2) {
831 // This is the common case, which also happens to be trivially simple.
832 // Special case it.
833 SCEVUse &LHS = Ops[0], &RHS = Ops[1];
834 if (IsLessComplex(RHS, LHS))
835 std::swap(LHS, RHS);
836 return;
837 }
838
839 // Do the rough sort by complexity.
841 Ops, [&](SCEVUse LHS, SCEVUse RHS) { return IsLessComplex(LHS, RHS); });
842
843 // Now that we are sorted by complexity, group elements of the same
844 // complexity. Note that this is, at worst, N^2, but the vector is likely to
845 // be extremely short in practice. Note that we take this approach because we
846 // do not want to depend on the addresses of the objects we are grouping.
847 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
848 const SCEV *S = Ops[i];
849 unsigned Complexity = S->getSCEVType();
850
851 // If there are any objects of the same complexity and same value as this
852 // one, group them.
853 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
854 if (Ops[j] == S) { // Found a duplicate.
855 // Move it to immediately after i'th element.
856 std::swap(Ops[i+1], Ops[j]);
857 ++i; // no need to rescan it.
858 if (i == e-2) return; // Done!
859 }
860 }
861 }
862}
863
864/// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
865/// least HugeExprThreshold nodes).
867 return any_of(Ops, [](const SCEV *S) {
869 });
870}
871
872/// Performs a number of common optimizations on the passed \p Ops. If the
873/// whole expression reduces down to a single operand, it will be returned.
874///
875/// The following optimizations are performed:
876/// * Fold constants using the \p Fold function.
877/// * Remove identity constants satisfying \p IsIdentity.
878/// * If a constant satisfies \p IsAbsorber, return it.
879/// * Sort operands by complexity.
880template <typename FoldT, typename IsIdentityT, typename IsAbsorberT>
881static const SCEV *
883 SmallVectorImpl<SCEVUse> &Ops, FoldT Fold,
884 IsIdentityT IsIdentity, IsAbsorberT IsAbsorber) {
885 const SCEVConstant *Folded = nullptr;
886 for (unsigned Idx = 0; Idx < Ops.size();) {
887 const SCEV *Op = Ops[Idx];
888 if (const auto *C = dyn_cast<SCEVConstant>(Op)) {
889 if (!Folded)
890 Folded = C;
891 else
892 Folded = cast<SCEVConstant>(
893 SE.getConstant(Fold(Folded->getAPInt(), C->getAPInt())));
894 Ops.erase(Ops.begin() + Idx);
895 continue;
896 }
897 ++Idx;
898 }
899
900 if (Ops.empty()) {
901 assert(Folded && "Must have folded value");
902 return Folded;
903 }
904
905 if (Folded && IsAbsorber(Folded->getAPInt()))
906 return Folded;
907
908 GroupByComplexity(Ops, &LI, DT);
909 if (Folded && !IsIdentity(Folded->getAPInt()))
910 Ops.insert(Ops.begin(), Folded);
911
912 return Ops.size() == 1 ? Ops[0] : nullptr;
913}
914
915//===----------------------------------------------------------------------===//
916// Simple SCEV method implementations
917//===----------------------------------------------------------------------===//
918
919/// Compute BC(It, K). The result has width W. Assume, K > 0.
920static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
921 ScalarEvolution &SE,
922 Type *ResultTy) {
923 // Handle the simplest case efficiently.
924 if (K == 1)
925 return SE.getTruncateOrZeroExtend(It, ResultTy);
926
927 // We are using the following formula for BC(It, K):
928 //
929 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
930 //
931 // Suppose, W is the bitwidth of the return value. We must be prepared for
932 // overflow. Hence, we must assure that the result of our computation is
933 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
934 // safe in modular arithmetic.
935 //
936 // However, this code doesn't use exactly that formula; the formula it uses
937 // is something like the following, where T is the number of factors of 2 in
938 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
939 // exponentiation:
940 //
941 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
942 //
943 // This formula is trivially equivalent to the previous formula. However,
944 // this formula can be implemented much more efficiently. The trick is that
945 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
946 // arithmetic. To do exact division in modular arithmetic, all we have
947 // to do is multiply by the inverse. Therefore, this step can be done at
948 // width W.
949 //
950 // The next issue is how to safely do the division by 2^T. The way this
951 // is done is by doing the multiplication step at a width of at least W + T
952 // bits. This way, the bottom W+T bits of the product are accurate. Then,
953 // when we perform the division by 2^T (which is equivalent to a right shift
954 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
955 // truncated out after the division by 2^T.
956 //
957 // In comparison to just directly using the first formula, this technique
958 // is much more efficient; using the first formula requires W * K bits,
959 // but this formula less than W + K bits. Also, the first formula requires
960 // a division step, whereas this formula only requires multiplies and shifts.
961 //
962 // It doesn't matter whether the subtraction step is done in the calculation
963 // width or the input iteration count's width; if the subtraction overflows,
964 // the result must be zero anyway. We prefer here to do it in the width of
965 // the induction variable because it helps a lot for certain cases; CodeGen
966 // isn't smart enough to ignore the overflow, which leads to much less
967 // efficient code if the width of the subtraction is wider than the native
968 // register width.
969 //
970 // (It's possible to not widen at all by pulling out factors of 2 before
971 // the multiplication; for example, K=2 can be calculated as
972 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
973 // extra arithmetic, so it's not an obvious win, and it gets
974 // much more complicated for K > 3.)
975
976 // Protection from insane SCEVs; this bound is conservative,
977 // but it probably doesn't matter.
978 if (K > 1000)
979 return SE.getCouldNotCompute();
980
981 unsigned W = SE.getTypeSizeInBits(ResultTy);
982
983 // Calculate K! / 2^T and T; we divide out the factors of two before
984 // multiplying for calculating K! / 2^T to avoid overflow.
985 // Other overflow doesn't matter because we only care about the bottom
986 // W bits of the result.
987 APInt OddFactorial(W, 1);
988 unsigned T = 1;
989 for (unsigned i = 3; i <= K; ++i) {
990 unsigned TwoFactors = countr_zero(i);
991 T += TwoFactors;
992 OddFactorial *= (i >> TwoFactors);
993 }
994
995 // We need at least W + T bits for the multiplication step
996 unsigned CalculationBits = W + T;
997
998 // Calculate 2^T, at width T+W.
999 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1000
1001 // Calculate the multiplicative inverse of K! / 2^T;
1002 // this multiplication factor will perform the exact division by
1003 // K! / 2^T.
1004 APInt MultiplyFactor = OddFactorial.multiplicativeInverse();
1005
1006 // Calculate the product, at width T+W
1007 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1008 CalculationBits);
1009 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1010 for (unsigned i = 1; i != K; ++i) {
1011 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1012 Dividend = SE.getMulExpr(Dividend,
1013 SE.getTruncateOrZeroExtend(S, CalculationTy));
1014 }
1015
1016 // Divide by 2^T
1017 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1018
1019 // Truncate the result, and divide by K! / 2^T.
1020
1021 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1022 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1023}
1024
1025/// Return the value of this chain of recurrences at the specified iteration
1026/// number. We can evaluate this recurrence by multiplying each element in the
1027/// chain by the binomial coefficient corresponding to it. In other words, we
1028/// can evaluate {A,+,B,+,C,+,D} as:
1029///
1030/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1031///
1032/// where BC(It, k) stands for binomial coefficient.
1034 ScalarEvolution &SE) const {
1035 return evaluateAtIteration(operands(), It, SE);
1036}
1037
1039 const SCEV *It,
1040 ScalarEvolution &SE) {
1041 assert(Operands.size() > 0);
1042 const SCEV *Result = Operands[0].getPointer();
1043 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1044 // The computation is correct in the face of overflow provided that the
1045 // multiplication is performed _after_ the evaluation of the binomial
1046 // coefficient.
1047 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
1048 if (isa<SCEVCouldNotCompute>(Coeff))
1049 return Coeff;
1050
1051 Result =
1052 SE.getAddExpr(Result, SE.getMulExpr(Operands[i].getPointer(), Coeff));
1053 }
1054 return Result;
1055}
1056
1057//===----------------------------------------------------------------------===//
1058// SCEV Expression folder implementations
1059//===----------------------------------------------------------------------===//
1060
1061/// The SCEVCastSinkingRewriter takes a scalar evolution expression,
1062/// which computes a pointer-typed value, and rewrites the whole expression
1063/// tree so that *all* the computations are done on integers, and the only
1064/// pointer-typed operands in the expression are SCEVUnknown.
1065/// The CreatePtrCast callback is invoked to create the actual conversion
1066/// (ptrtoint or ptrtoaddr) at the SCEVUnknown leaves.
1068 : public SCEVRewriteVisitor<SCEVCastSinkingRewriter> {
1070 using ConversionFn = function_ref<const SCEV *(const SCEVUnknown *)>;
1071 Type *TargetTy;
1072 ConversionFn CreatePtrCast;
1073
1074public:
1076 ConversionFn CreatePtrCast)
1077 : Base(SE), TargetTy(TargetTy), CreatePtrCast(std::move(CreatePtrCast)) {}
1078
1079 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
1080 Type *TargetTy, ConversionFn CreatePtrCast) {
1081 SCEVCastSinkingRewriter Rewriter(SE, TargetTy, std::move(CreatePtrCast));
1082 return Rewriter.visit(Scev);
1083 }
1084
1085 const SCEV *visit(const SCEV *S) {
1086 Type *STy = S->getType();
1087 // If the expression is not pointer-typed, just keep it as-is.
1088 if (!STy->isPointerTy())
1089 return S;
1090 // Else, recursively sink the cast down into it.
1091 return Base::visit(S);
1092 }
1093
1094 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1095 // Preserve wrap flags on rewritten SCEVAddExpr, which the default
1096 // implementation drops.
1097 SmallVector<SCEVUse, 2> Operands;
1098 bool Changed = false;
1099 for (SCEVUse Op : Expr->operands()) {
1100 Operands.push_back(visit(Op.getPointer()));
1101 Changed |= Op.getPointer() != Operands.back();
1102 }
1103 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1104 }
1105
1106 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1107 SmallVector<SCEVUse, 2> Operands;
1108 bool Changed = false;
1109 for (SCEVUse Op : Expr->operands()) {
1110 Operands.push_back(visit(Op.getPointer()));
1111 Changed |= Op.getPointer() != Operands.back();
1112 }
1113 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1114 }
1115
1116 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1117 assert(Expr->getType()->isPointerTy() &&
1118 "Should only reach pointer-typed SCEVUnknown's.");
1119 // Perform some basic constant folding. If the operand of the cast is a
1120 // null pointer, don't create a cast SCEV expression (that will be left
1121 // as-is), but produce a zero constant.
1123 return SE.getZero(TargetTy);
1124 return CreatePtrCast(Expr);
1125 }
1126};
1127
1129 assert(Op->getType()->isPointerTy() && "Op must be a pointer");
1130
1131 // Treat pointers with unstable representation conservatively, since the
1132 // address bits may change.
1133 if (DL.hasUnstableRepresentation(Op->getType()))
1134 return getCouldNotCompute();
1135
1136 Type *Ty = DL.getAddressType(Op->getType());
1137
1138 // Use the rewriter to sink the cast down to SCEVUnknown leaves.
1139 // The rewriter handles null pointer constant folding.
1141 Op, *this, Ty, [this, Ty](const SCEVUnknown *U) {
1144 ID.AddPointer(U);
1145 ID.AddPointer(Ty);
1146 void *IP = nullptr;
1147 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1148 return S;
1149 SCEV *S = new (SCEVAllocator)
1150 SCEVPtrToAddrExpr(ID.Intern(SCEVAllocator), U, Ty);
1151 UniqueSCEVs.InsertNode(S, IP);
1152 S->computeAndSetCanonical(*this);
1153 registerUser(S, U);
1154 return static_cast<const SCEV *>(S);
1155 });
1156 assert(IntOp->getType()->isIntegerTy() &&
1157 "We must have succeeded in sinking the cast, "
1158 "and ending up with an integer-typed expression!");
1159 return IntOp;
1160}
1161
1163 unsigned Depth) {
1164 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1165 "This is not a truncating conversion!");
1166 assert(isSCEVable(Ty) &&
1167 "This is not a conversion to a SCEVable type!");
1168 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1169 Ty = getEffectiveSCEVType(Ty);
1170
1173 ID.AddPointer(Op);
1174 ID.AddPointer(Ty);
1175 void *IP = nullptr;
1176 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1177
1178 // Fold if the operand is constant.
1179 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1180 return getConstant(
1181 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1182
1183 // trunc(trunc(x)) --> trunc(x)
1185 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1186
1187 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1189 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1190
1191 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1193 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1194
1195 if (Depth > MaxCastDepth) {
1196 SCEV *S =
1197 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1198 UniqueSCEVs.InsertNode(S, IP);
1199 S->computeAndSetCanonical(*this);
1200 registerUser(S, Op);
1201 return S;
1202 }
1203
1204 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1205 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1206 // if after transforming we have at most one truncate, not counting truncates
1207 // that replace other casts.
1209 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1210 SmallVector<SCEVUse, 4> Operands;
1211 unsigned numTruncs = 0;
1212 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1213 ++i) {
1214 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1215 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1217 numTruncs++;
1218 Operands.push_back(S);
1219 }
1220 if (numTruncs < 2) {
1221 if (isa<SCEVAddExpr>(Op))
1222 return getAddExpr(Operands);
1223 if (isa<SCEVMulExpr>(Op))
1224 return getMulExpr(Operands);
1225 llvm_unreachable("Unexpected SCEV type for Op.");
1226 }
1227 // Although we checked in the beginning that ID is not in the cache, it is
1228 // possible that during recursion and different modification ID was inserted
1229 // into the cache. So if we find it, just return it.
1230 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1231 return S;
1232 }
1233
1234 // If the input value is a chrec scev, truncate the chrec's operands.
1235 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1236 SmallVector<SCEVUse, 4> Operands;
1237 for (const SCEV *Op : AddRec->operands())
1238 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1239 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1240 }
1241
1242 // Return zero if truncating to known zeros.
1243 uint32_t MinTrailingZeros = getMinTrailingZeros(Op);
1244 if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1245 return getZero(Ty);
1246
1247 // The cast wasn't folded; create an explicit cast node. We can reuse
1248 // the existing insert position since if we get here, we won't have
1249 // made any changes which would invalidate it.
1250 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1251 Op, Ty);
1252 UniqueSCEVs.InsertNode(S, IP);
1253 S->computeAndSetCanonical(*this);
1254 registerUser(S, Op);
1255 return S;
1256}
1257
1258// Get the limit of a recurrence such that incrementing by Step cannot cause
1259// signed overflow as long as the value of the recurrence within the
1260// loop does not exceed this limit before incrementing.
1261static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1262 ICmpInst::Predicate *Pred,
1263 ScalarEvolution *SE) {
1264 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1265 if (SE->isKnownPositive(Step)) {
1266 *Pred = ICmpInst::ICMP_SLT;
1268 SE->getSignedRangeMax(Step));
1269 }
1270 if (SE->isKnownNegative(Step)) {
1271 *Pred = ICmpInst::ICMP_SGT;
1273 SE->getSignedRangeMin(Step));
1274 }
1275 return nullptr;
1276}
1277
1278// Get the limit of a recurrence such that incrementing by Step cannot cause
1279// unsigned overflow as long as the value of the recurrence within the loop does
1280// not exceed this limit before incrementing.
1282 ICmpInst::Predicate *Pred,
1283 ScalarEvolution *SE) {
1284 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1285 *Pred = ICmpInst::ICMP_ULT;
1286
1288 SE->getUnsignedRangeMax(Step));
1289}
1290
1291namespace {
1292
1293struct ExtendOpTraitsBase {
1294 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1295 unsigned);
1296};
1297
1298// Used to make code generic over signed and unsigned overflow.
1299template <typename ExtendOp> struct ExtendOpTraits {
1300 // Members present:
1301 //
1302 // static const SCEV::NoWrapFlags WrapType;
1303 //
1304 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1305 //
1306 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1307 // ICmpInst::Predicate *Pred,
1308 // ScalarEvolution *SE);
1309};
1310
1311template <>
1312struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1313 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1314
1315 static const GetExtendExprTy GetExtendExpr;
1316
1317 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1318 ICmpInst::Predicate *Pred,
1319 ScalarEvolution *SE) {
1320 return getSignedOverflowLimitForStep(Step, Pred, SE);
1321 }
1322};
1323
1324const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1326
1327template <>
1328struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1329 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1330
1331 static const GetExtendExprTy GetExtendExpr;
1332
1333 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1334 ICmpInst::Predicate *Pred,
1335 ScalarEvolution *SE) {
1336 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1337 }
1338};
1339
1340const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1342
1343} // end anonymous namespace
1344
1345// The recurrence AR has been shown to have no signed/unsigned wrap or something
1346// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1347// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1348// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1349// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1350// expression "Step + sext/zext(PreIncAR)" is congruent with
1351// "sext/zext(PostIncAR)"
1352template <typename ExtendOpTy>
1353static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1354 ScalarEvolution *SE, unsigned Depth) {
1355 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1356 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1357
1358 const Loop *L = AR->getLoop();
1359 const SCEV *Start = AR->getStart();
1360 const SCEV *Step = AR->getStepRecurrence(*SE);
1361
1362 // Check for a simple looking step prior to loop entry.
1363 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1364 if (!SA)
1365 return nullptr;
1366
1367 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1368 // subtraction is expensive. For this purpose, perform a quick and dirty
1369 // difference, by checking for Step in the operand list. Note, that
1370 // SA might have repeated ops, like %a + %a + ..., so only remove one.
1371 SmallVector<SCEVUse, 4> DiffOps(SA->operands());
1372 for (auto It = DiffOps.begin(); It != DiffOps.end(); ++It)
1373 if (*It == Step) {
1374 DiffOps.erase(It);
1375 break;
1376 }
1377
1378 if (DiffOps.size() == SA->getNumOperands())
1379 return nullptr;
1380
1381 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1382 // `Step`:
1383
1384 // 1. NSW/NUW flags on the step increment.
1385 auto PreStartFlags =
1387 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1389 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1390
1391 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1392 // "S+X does not sign/unsign-overflow".
1393 //
1394
1395 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1396 if (PreAR && any(PreAR->getNoWrapFlags(WrapType)) &&
1397 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1398 return PreStart;
1399
1400 // 2. Direct overflow check on the step operation's expression.
1401 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1402 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1403 const SCEV *OperandExtendedStart =
1404 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1405 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1406 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1407 if (PreAR && any(AR->getNoWrapFlags(WrapType))) {
1408 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1409 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1410 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1411 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1412 }
1413 return PreStart;
1414 }
1415
1416 // 3. Loop precondition.
1418 const SCEV *OverflowLimit =
1419 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1420
1421 if (OverflowLimit &&
1422 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1423 return PreStart;
1424
1425 return nullptr;
1426}
1427
1428// Get the normalized zero or sign extended expression for this AddRec's Start.
1429template <typename ExtendOpTy>
1430static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1431 ScalarEvolution *SE,
1432 unsigned Depth) {
1433 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1434
1435 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1436 if (!PreStart)
1437 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1438
1439 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1440 Depth),
1441 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1442}
1443
1444// Try to prove away overflow by looking at "nearby" add recurrences. A
1445// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1446// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1447//
1448// Formally:
1449//
1450// {S,+,X} == {S-T,+,X} + T
1451// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1452//
1453// If ({S-T,+,X} + T) does not overflow ... (1)
1454//
1455// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1456//
1457// If {S-T,+,X} does not overflow ... (2)
1458//
1459// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1460// == {Ext(S-T)+Ext(T),+,Ext(X)}
1461//
1462// If (S-T)+T does not overflow ... (3)
1463//
1464// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1465// == {Ext(S),+,Ext(X)} == LHS
1466//
1467// Thus, if (1), (2) and (3) are true for some T, then
1468// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1469//
1470// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1471// does not overflow" restricted to the 0th iteration. Therefore we only need
1472// to check for (1) and (2).
1473//
1474// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1475// is `Delta` (defined below).
1476template <typename ExtendOpTy>
1477bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1478 const SCEV *Step,
1479 const Loop *L) {
1480 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1481
1482 // We restrict `Start` to a constant to prevent SCEV from spending too much
1483 // time here. It is correct (but more expensive) to continue with a
1484 // non-constant `Start` and do a general SCEV subtraction to compute
1485 // `PreStart` below.
1486 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1487 if (!StartC)
1488 return false;
1489
1490 APInt StartAI = StartC->getAPInt();
1491
1492 for (unsigned Delta : {-2, -1, 1, 2}) {
1493 const SCEV *PreStart = getConstant(StartAI - Delta);
1494
1495 FoldingSetNodeID ID;
1496 ID.AddInteger(scAddRecExpr);
1497 ID.AddPointer(PreStart);
1498 ID.AddPointer(Step);
1499 ID.AddPointer(L);
1500 void *IP = nullptr;
1501 const auto *PreAR =
1502 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1503
1504 // Give up if we don't already have the add recurrence we need because
1505 // actually constructing an add recurrence is relatively expensive.
1506 if (PreAR && any(PreAR->getNoWrapFlags(WrapType))) { // proves (2)
1507 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1509 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1510 DeltaS, &Pred, this);
1511 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1512 return true;
1513 }
1514 }
1515
1516 return false;
1517}
1518
1519// Finds an integer D for an expression (C + x + y + ...) such that the top
1520// level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1521// unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1522// maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1523// the (C + x + y + ...) expression is \p WholeAddExpr.
1525 const SCEVConstant *ConstantTerm,
1526 const SCEVAddExpr *WholeAddExpr) {
1527 const APInt &C = ConstantTerm->getAPInt();
1528 const unsigned BitWidth = C.getBitWidth();
1529 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1530 uint32_t TZ = BitWidth;
1531 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1532 TZ = std::min(TZ, SE.getMinTrailingZeros(WholeAddExpr->getOperand(I)));
1533 if (TZ) {
1534 // Set D to be as many least significant bits of C as possible while still
1535 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1536 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1537 }
1538 return APInt(BitWidth, 0);
1539}
1540
1541// Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1542// level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1543// number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1544// ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1546 const APInt &ConstantStart,
1547 const SCEV *Step) {
1548 const unsigned BitWidth = ConstantStart.getBitWidth();
1549 const uint32_t TZ = SE.getMinTrailingZeros(Step);
1550 if (TZ)
1551 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1552 : ConstantStart;
1553 return APInt(BitWidth, 0);
1554}
1555
1557 const ScalarEvolution::FoldID &ID, const SCEV *S,
1560 &FoldCacheUser) {
1561 auto I = FoldCache.insert({ID, S});
1562 if (!I.second) {
1563 // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1564 // entry.
1565 auto &UserIDs = FoldCacheUser[I.first->second];
1566 assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
1567 for (unsigned I = 0; I != UserIDs.size(); ++I)
1568 if (UserIDs[I] == ID) {
1569 std::swap(UserIDs[I], UserIDs.back());
1570 break;
1571 }
1572 UserIDs.pop_back();
1573 I.first->second = S;
1574 }
1575 FoldCacheUser[S].push_back(ID);
1576}
1577
1578const SCEV *
1580 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1581 "This is not an extending conversion!");
1582 assert(isSCEVable(Ty) &&
1583 "This is not a conversion to a SCEVable type!");
1584 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1585 Ty = getEffectiveSCEVType(Ty);
1586
1587 FoldID ID(scZeroExtend, Op, Ty);
1588 if (const SCEV *S = FoldCache.lookup(ID))
1589 return S;
1590
1591 const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1593 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1594 return S;
1595}
1596
1598 unsigned Depth) {
1599 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1600 "This is not an extending conversion!");
1601 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1602 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1603
1604 // Fold if the operand is constant.
1605 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1606 return getConstant(SC->getAPInt().zext(getTypeSizeInBits(Ty)));
1607
1608 // zext(zext(x)) --> zext(x)
1610 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1611
1612 // If the operand is an affine AddRec with the no-unsigned-wrap flag, the
1613 // zero-extension distributes over the recurrence.
1614 const SCEV *Start, *Step;
1615 const Loop *L;
1616 if (Depth <= MaxCastDepth &&
1617 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1618 const auto *AR = cast<SCEVAddRecExpr>(Op);
1619 if (AR->hasNoUnsignedWrap()) {
1620 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1621 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1622 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1623 }
1624 }
1625
1626 // Before doing any expensive analysis, check to see if we've already
1627 // computed a SCEV for this Op and Ty.
1630 ID.AddPointer(Op);
1631 ID.AddPointer(Ty);
1632 void *IP = nullptr;
1633 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1634 if (Depth > MaxCastDepth) {
1635 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1636 Op, Ty);
1637 UniqueSCEVs.InsertNode(S, IP);
1638 S->computeAndSetCanonical(*this);
1639 registerUser(S, Op);
1640 return S;
1641 }
1642
1643 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1645 // It's possible the bits taken off by the truncate were all zero bits. If
1646 // so, we should be able to simplify this further.
1647 const SCEV *X = ST->getOperand();
1649 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1650 unsigned NewBits = getTypeSizeInBits(Ty);
1651 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1652 CR.zextOrTrunc(NewBits)))
1653 return getTruncateOrZeroExtend(X, Ty, Depth);
1654 }
1655
1656 // If the input value is a chrec scev, and we can prove that the value
1657 // did not overflow the old, smaller, value, we can zero extend all of the
1658 // operands (often constants). This allows analysis of something like
1659 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1660 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1661 const auto *AR = cast<SCEVAddRecExpr>(Op);
1662 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1663
1664 // The no-unsigned-wrap case is handled before the uniquing lookup above.
1665
1666 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1667 // Note that this serves two purposes: It filters out loops that are
1668 // simply not analyzable, and it covers the case where this code is
1669 // being called from within backedge-taken count analysis, such that
1670 // attempting to ask for the backedge-taken count would likely result
1671 // in infinite recursion. In the later case, the analysis code will
1672 // cope with a conservative value, and it will take care to purge
1673 // that value once it has finished.
1674 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1675 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1676 // Manually compute the final value for AR, checking for overflow.
1677
1678 // Check whether the backedge-taken count can be losslessly casted to
1679 // the addrec's type. The count is always unsigned.
1680 const SCEV *CastedMaxBECount =
1681 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1682 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1683 CastedMaxBECount, MaxBECount->getType(), Depth);
1684 if (MaxBECount == RecastedMaxBECount) {
1685 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1686 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1687 const SCEV *ZMul =
1688 getMulExpr(CastedMaxBECount, Step, SCEV::FlagAnyWrap, Depth + 1);
1689 const SCEV *ZAdd = getZeroExtendExpr(
1690 getAddExpr(Start, ZMul, SCEV::FlagAnyWrap, Depth + 1), WideTy,
1691 Depth + 1);
1692 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1693 const SCEV *WideMaxBECount =
1694 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1695 const SCEV *OperandExtendedAdd =
1696 getAddExpr(WideStart,
1697 getMulExpr(WideMaxBECount,
1698 getZeroExtendExpr(Step, WideTy, Depth + 1),
1701 if (ZAdd == OperandExtendedAdd) {
1702 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1703 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1704 // Return the expression with the addrec on the outside.
1705 Start =
1707 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1708 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1709 }
1710 // Similar to above, only this time treat the step value as signed.
1711 // This covers loops that count down.
1712 OperandExtendedAdd =
1713 getAddExpr(WideStart,
1714 getMulExpr(WideMaxBECount,
1715 getSignExtendExpr(Step, WideTy, Depth + 1),
1718 if (ZAdd == OperandExtendedAdd) {
1719 // Cache knowledge of AR NW, which is propagated to this AddRec.
1720 // Negative step causes unsigned wrap, but it still can't self-wrap.
1721 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1722 // Return the expression with the addrec on the outside.
1723 Start =
1725 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1726 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1727 }
1728 }
1729 }
1730
1731 // Normally, in the cases we can prove no-overflow via a
1732 // backedge guarding condition, we can also compute a backedge
1733 // taken count for the loop. The exceptions are assumptions and
1734 // guards present in the loop -- SCEV is not great at exploiting
1735 // these to compute max backedge taken counts, but can still use
1736 // these to prove lack of overflow. Use this fact to avoid
1737 // doing extra work that may not pay off.
1738 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1739 !AC.assumptions().empty()) {
1740
1741 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1742 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1743 if (AR->hasNoUnsignedWrap()) {
1744 // Same as nuw case above - duplicated here to avoid a compile time
1745 // issue. It's not clear that the order of checks does matter, but
1746 // it's one of two issue possible causes for a change which was
1747 // reverted. Be conservative for the moment.
1748 Start =
1750 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1751 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1752 }
1753
1754 // For a negative step, we can extend the operands iff doing so only
1755 // traverses values in the range zext([0,UINT_MAX]).
1756 if (isKnownNegative(Step)) {
1757 const SCEV *N =
1761 // Cache knowledge of AR NW, which is propagated to this
1762 // AddRec. Negative step causes unsigned wrap, but it
1763 // still can't self-wrap.
1764 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1765 // Return the expression with the addrec on the outside.
1766 Start =
1768 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1769 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1770 }
1771 }
1772 }
1773
1774 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1775 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1776 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1777 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1778 const APInt &C = SC->getAPInt();
1779 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1780 if (D != 0) {
1781 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1782 const SCEV *SResidual =
1783 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1784 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1785 return getAddExpr(SZExtD, SZExtR, SCEV::FlagNSW | SCEV::FlagNUW,
1786 Depth + 1);
1787 }
1788 }
1789
1790 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1791 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1792 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1793 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1794 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1795 }
1796 }
1797
1798 // zext(A % B) --> zext(A) % zext(B)
1799 {
1800 const SCEV *LHS;
1801 const SCEV *RHS;
1802 if (match(Op, m_scev_URem(m_SCEV(LHS), m_SCEV(RHS), *this)))
1803 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1804 getZeroExtendExpr(RHS, Ty, Depth + 1));
1805 }
1806
1807 // zext(A / B) --> zext(A) / zext(B).
1808 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1809 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1810 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1811
1812 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1813 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1814 if (SA->hasNoUnsignedWrap()) {
1815 // If the addition does not unsign overflow then we can, by definition,
1816 // commute the zero extension with the addition operation.
1818 for (SCEVUse Op : SA->operands())
1819 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1820 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1821 }
1822
1823 const APInt *C, *C2;
1824 // zext (C + A)<nsw> -> (sext(C) + sext(A))<nsw> if zext (C + A)<nsw> >=s 0.
1825 // Currently the non-negative check is done manually, as isKnownNonNegative
1826 // is too expensive.
1827 if (SA->hasNoSignedWrap() &&
1829 m_scev_SMax(m_scev_APInt(C2), m_SCEV()))) &&
1830 C->isNegative() && !C->isMinSignedValue() && C2->sge(C->abs())) {
1831 assert(isKnownNonNegative(SA) && "incorrectly determined non-negative");
1832 return getAddExpr(getSignExtendExpr(SA->getOperand(0), Ty, Depth + 1),
1833 getSignExtendExpr(SA->getOperand(1), Ty, Depth + 1),
1834 SCEV::FlagNSW, Depth + 1);
1835 }
1836
1837 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1838 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1839 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1840 //
1841 // Often address arithmetics contain expressions like
1842 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1843 // This transformation is useful while proving that such expressions are
1844 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1845 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1846 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1847 if (D != 0) {
1848 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1849 const SCEV *SResidual =
1851 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1852 return getAddExpr(SZExtD, SZExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1853 Depth + 1);
1854 }
1855 }
1856 }
1857
1858 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1859 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1860 if (SM->hasNoUnsignedWrap()) {
1861 // If the multiply does not unsign overflow then we can, by definition,
1862 // commute the zero extension with the multiply operation.
1864 for (SCEVUse Op : SM->operands())
1865 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1866 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1867 }
1868
1869 // zext(2^K * (trunc X to iN)) to iM ->
1870 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1871 //
1872 // Proof:
1873 //
1874 // zext(2^K * (trunc X to iN)) to iM
1875 // = zext((trunc X to iN) << K) to iM
1876 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1877 // (because shl removes the top K bits)
1878 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1879 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1880 //
1881 const APInt *C;
1882 const SCEV *TruncRHS;
1883 if (match(SM,
1884 m_scev_Mul(m_scev_APInt(C), m_scev_Trunc(m_SCEV(TruncRHS)))) &&
1885 C->isPowerOf2()) {
1886 int NewTruncBits =
1887 getTypeSizeInBits(SM->getOperand(1)->getType()) - C->logBase2();
1888 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1889 return getMulExpr(
1890 getZeroExtendExpr(SM->getOperand(0), Ty),
1891 getZeroExtendExpr(getTruncateExpr(TruncRHS, NewTruncTy), Ty),
1892 SCEV::FlagNUW, Depth + 1);
1893 }
1894 }
1895
1896 // zext(umin(x, y)) -> umin(zext(x), zext(y))
1897 // zext(umax(x, y)) -> umax(zext(x), zext(y))
1900 SmallVector<SCEVUse, 4> Operands;
1901 for (SCEVUse Operand : MinMax->operands())
1902 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1904 return getUMinExpr(Operands);
1905 return getUMaxExpr(Operands);
1906 }
1907
1908 // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
1910 assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!");
1911 SmallVector<SCEVUse, 4> Operands;
1912 for (SCEVUse Operand : MinMax->operands())
1913 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1914 return getUMinExpr(Operands, /*Sequential*/ true);
1915 }
1916
1917 // The cast wasn't folded; create an explicit cast node.
1918 // Recompute the insert position, as it may have been invalidated.
1919 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1920 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1921 Op, Ty);
1922 UniqueSCEVs.InsertNode(S, IP);
1923 S->computeAndSetCanonical(*this);
1924 registerUser(S, Op);
1925 return S;
1926}
1927
1928const SCEV *
1930 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1931 "This is not an extending conversion!");
1932 assert(isSCEVable(Ty) &&
1933 "This is not a conversion to a SCEVable type!");
1934 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1935 Ty = getEffectiveSCEVType(Ty);
1936
1937 FoldID ID(scSignExtend, Op, Ty);
1938 if (const SCEV *S = FoldCache.lookup(ID))
1939 return S;
1940
1941 const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
1943 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1944 return S;
1945}
1946
1948 unsigned Depth) {
1949 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1950 "This is not an extending conversion!");
1951 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1952 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1953 Ty = getEffectiveSCEVType(Ty);
1954
1955 // Fold if the operand is constant.
1956 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1957 return getConstant(SC->getAPInt().sext(getTypeSizeInBits(Ty)));
1958
1959 // sext(sext(x)) --> sext(x)
1961 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1962
1963 // sext(zext(x)) --> zext(x)
1965 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1966
1967 // If the operand is an affine AddRec with the no-signed-wrap flag, the
1968 // sign-extension distributes over the recurrence.
1969 const SCEV *Start, *Step;
1970 const Loop *L;
1971 if (Depth <= MaxCastDepth &&
1972 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1973 const auto *AR = cast<SCEVAddRecExpr>(Op);
1974 if (AR->hasNoSignedWrap()) {
1975 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
1976 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1977 return getAddRecExpr(Start, Step, L, SCEV::FlagNSW);
1978 }
1979 }
1980
1981 // Before doing any expensive analysis, check to see if we've already
1982 // computed a SCEV for this Op and Ty.
1985 ID.AddPointer(Op);
1986 ID.AddPointer(Ty);
1987 void *IP = nullptr;
1988 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1989 // Limit recursion depth.
1990 if (Depth > MaxCastDepth) {
1991 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1992 Op, Ty);
1993 UniqueSCEVs.InsertNode(S, IP);
1994 S->computeAndSetCanonical(*this);
1995 registerUser(S, Op);
1996 return S;
1997 }
1998
1999 // sext(trunc(x)) --> sext(x) or x or trunc(x)
2001 // It's possible the bits taken off by the truncate were all sign bits. If
2002 // so, we should be able to simplify this further.
2003 const SCEV *X = ST->getOperand();
2005 unsigned TruncBits = getTypeSizeInBits(ST->getType());
2006 unsigned NewBits = getTypeSizeInBits(Ty);
2007 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
2008 CR.sextOrTrunc(NewBits)))
2009 return getTruncateOrSignExtend(X, Ty, Depth);
2010 }
2011
2012 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
2013 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
2014 if (SA->hasNoSignedWrap()) {
2015 // If the addition does not sign overflow then we can, by definition,
2016 // commute the sign extension with the addition operation.
2018 for (SCEVUse Op : SA->operands())
2019 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
2020 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
2021 }
2022
2023 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
2024 // if D + (C - D + x + y + ...) could be proven to not signed wrap
2025 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
2026 //
2027 // For instance, this will bring two seemingly different expressions:
2028 // 1 + sext(5 + 20 * %x + 24 * %y) and
2029 // sext(6 + 20 * %x + 24 * %y)
2030 // to the same form:
2031 // 2 + sext(4 + 20 * %x + 24 * %y)
2032 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
2033 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
2034 if (D != 0) {
2035 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2036 const SCEV *SResidual =
2038 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2039 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
2040 Depth + 1);
2041 }
2042 }
2043 }
2044 // If the input value is a chrec scev, and we can prove that the value
2045 // did not overflow the old, smaller, value, we can sign extend all of the
2046 // operands (often constants). This allows analysis of something like
2047 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
2048 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
2049 const auto *AR = cast<SCEVAddRecExpr>(Op);
2050 unsigned BitWidth = getTypeSizeInBits(AR->getType());
2051
2052 // The no-signed-wrap case is handled before the uniquing lookup above.
2053
2054 // Check whether the backedge-taken count is SCEVCouldNotCompute.
2055 // Note that this serves two purposes: It filters out loops that are
2056 // simply not analyzable, and it covers the case where this code is
2057 // being called from within backedge-taken count analysis, such that
2058 // attempting to ask for the backedge-taken count would likely result
2059 // in infinite recursion. In the later case, the analysis code will
2060 // cope with a conservative value, and it will take care to purge
2061 // that value once it has finished.
2062 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2063 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2064 // Manually compute the final value for AR, checking for
2065 // overflow.
2066
2067 // Check whether the backedge-taken count can be losslessly casted to
2068 // the addrec's type. The count is always unsigned.
2069 const SCEV *CastedMaxBECount =
2070 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2071 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2072 CastedMaxBECount, MaxBECount->getType(), Depth);
2073 if (MaxBECount == RecastedMaxBECount) {
2074 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2075 // Check whether Start+Step*MaxBECount has no signed overflow.
2076 const SCEV *SMul =
2077 getMulExpr(CastedMaxBECount, Step, SCEV::FlagAnyWrap, Depth + 1);
2078 const SCEV *SAdd = getSignExtendExpr(
2079 getAddExpr(Start, SMul, SCEV::FlagAnyWrap, Depth + 1), WideTy,
2080 Depth + 1);
2081 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2082 const SCEV *WideMaxBECount =
2083 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2084 const SCEV *OperandExtendedAdd =
2085 getAddExpr(WideStart,
2086 getMulExpr(WideMaxBECount,
2087 getSignExtendExpr(Step, WideTy, Depth + 1),
2090 if (SAdd == OperandExtendedAdd) {
2091 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2092 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2093 // Return the expression with the addrec on the outside.
2094 Start =
2096 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2097 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2098 }
2099 // Similar to above, only this time treat the step value as unsigned.
2100 // This covers loops that count up with an unsigned step.
2101 OperandExtendedAdd =
2102 getAddExpr(WideStart,
2103 getMulExpr(WideMaxBECount,
2104 getZeroExtendExpr(Step, WideTy, Depth + 1),
2107 if (SAdd == OperandExtendedAdd) {
2108 // If AR wraps around then
2109 //
2110 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2111 // => SAdd != OperandExtendedAdd
2112 //
2113 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2114 // (SAdd == OperandExtendedAdd => AR is NW)
2115
2116 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2117
2118 // Return the expression with the addrec on the outside.
2119 Start =
2121 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
2122 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2123 }
2124 }
2125 }
2126
2127 auto NewFlags = proveNoSignedWrapViaInduction(AR);
2128 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2129 if (AR->hasNoSignedWrap()) {
2130 // Same as nsw case above - duplicated here to avoid a compile time
2131 // issue. It's not clear that the order of checks does matter, but
2132 // it's one of two issue possible causes for a change which was
2133 // reverted. Be conservative for the moment.
2134 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2135 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2136 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2137 }
2138
2139 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2140 // if D + (C - D + Step * n) could be proven to not signed wrap
2141 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2142 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2143 const APInt &C = SC->getAPInt();
2144 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2145 if (D != 0) {
2146 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2147 const SCEV *SResidual =
2148 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2149 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2150 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
2151 Depth + 1);
2152 }
2153 }
2154
2155 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2156 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2157 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2158 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2159 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2160 }
2161 }
2162
2163 // If the input value is provably positive and we could not simplify
2164 // away the sext build a zext instead.
2166 return getZeroExtendExpr(Op, Ty, Depth + 1);
2167
2168 // sext(smin(x, y)) -> smin(sext(x), sext(y))
2169 // sext(smax(x, y)) -> smax(sext(x), sext(y))
2172 SmallVector<SCEVUse, 4> Operands;
2173 for (SCEVUse Operand : MinMax->operands())
2174 Operands.push_back(getSignExtendExpr(Operand, Ty));
2176 return getSMinExpr(Operands);
2177 return getSMaxExpr(Operands);
2178 }
2179
2180 // The cast wasn't folded; create an explicit cast node.
2181 // Recompute the insert position, as it may have been invalidated.
2182 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2183 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2184 Op, Ty);
2185 UniqueSCEVs.InsertNode(S, IP);
2186 S->computeAndSetCanonical(*this);
2187 registerUser(S, Op);
2188 return S;
2189}
2190
2192 Type *Ty) {
2193 switch (Kind) {
2194 case scTruncate:
2195 return getTruncateExpr(Op, Ty);
2196 case scZeroExtend:
2197 return getZeroExtendExpr(Op, Ty);
2198 case scSignExtend:
2199 return getSignExtendExpr(Op, Ty);
2200 case scPtrToAddr: {
2201 const SCEV *Expr = getPtrToAddrExpr(Op);
2202 assert(Expr->getType() == Ty && "requested type must match");
2203 return Expr;
2204 }
2205 default:
2206 llvm_unreachable("Not a SCEV cast expression!");
2207 }
2208}
2209
2210/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2211/// unspecified bits out to the given type.
2213 Type *Ty) {
2214 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2215 "This is not an extending conversion!");
2216 assert(isSCEVable(Ty) &&
2217 "This is not a conversion to a SCEVable type!");
2218 Ty = getEffectiveSCEVType(Ty);
2219
2220 // Sign-extend negative constants.
2221 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2222 if (SC->getAPInt().isNegative())
2223 return getSignExtendExpr(Op, Ty);
2224
2225 // Peel off a truncate cast.
2227 const SCEV *NewOp = T->getOperand();
2228 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2229 return getAnyExtendExpr(NewOp, Ty);
2230 return getTruncateOrNoop(NewOp, Ty);
2231 }
2232
2233 // Next try a zext cast. If the cast is folded, use it.
2234 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2235 if (!isa<SCEVZeroExtendExpr>(ZExt))
2236 return ZExt;
2237
2238 // Next try a sext cast. If the cast is folded, use it.
2239 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2240 if (!isa<SCEVSignExtendExpr>(SExt))
2241 return SExt;
2242
2243 // Force the cast to be folded into the operands of an addrec.
2244 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2246 for (const SCEV *Op : AR->operands())
2247 Ops.push_back(getAnyExtendExpr(Op, Ty));
2248 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2249 }
2250
2251 // If the expression is obviously signed, use the sext cast value.
2252 if (isa<SCEVSMaxExpr>(Op))
2253 return SExt;
2254
2255 // Absent any other information, use the zext cast value.
2256 return ZExt;
2257}
2258
2259/// Process the given Ops list, which is a list of operands to be added under
2260/// the given scale, update the given map. This is a helper function for
2261/// getAddRecExpr. As an example of what it does, given a sequence of operands
2262/// that would form an add expression like this:
2263///
2264/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2265///
2266/// where A and B are constants, update the map with these values:
2267///
2268/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2269///
2270/// and add 13 + A*B*29 to AccumulatedConstant.
2271/// This will allow getAddRecExpr to produce this:
2272///
2273/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2274///
2275/// This form often exposes folding opportunities that are hidden in
2276/// the original operand list.
2277///
2278/// Return true iff it appears that any interesting folding opportunities
2279/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2280/// the common case where no interesting opportunities are present, and
2281/// is also used as a check to avoid infinite recursion.
2284 APInt &AccumulatedConstant,
2286 const APInt &Scale,
2287 ScalarEvolution &SE) {
2288 bool Interesting = false;
2289
2290 // Iterate over the add operands. They are sorted, with constants first.
2291 unsigned i = 0;
2292 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2293 ++i;
2294 // Pull a buried constant out to the outside.
2295 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2296 Interesting = true;
2297 AccumulatedConstant += Scale * C->getAPInt();
2298 }
2299
2300 // Next comes everything else. We're especially interested in multiplies
2301 // here, but they're in the middle, so just visit the rest with one loop.
2302 for (; i != Ops.size(); ++i) {
2304 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2305 APInt NewScale =
2306 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2307 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2308 // A multiplication of a constant with another add; recurse.
2309 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2310 Interesting |= CollectAddOperandsWithScales(
2311 M, NewOps, AccumulatedConstant, Add->operands(), NewScale, SE);
2312 } else {
2313 // A multiplication of a constant with some other value. Update
2314 // the map.
2315 SmallVector<SCEVUse, 4> MulOps(drop_begin(Mul->operands()));
2316 const SCEV *Key = SE.getMulExpr(MulOps);
2317 auto Pair = M.insert({Key, NewScale});
2318 if (Pair.second) {
2319 NewOps.push_back(Pair.first->first);
2320 } else {
2321 Pair.first->second += NewScale;
2322 // The map already had an entry for this value, which may indicate
2323 // a folding opportunity.
2324 Interesting = true;
2325 }
2326 }
2327 } else {
2328 // An ordinary operand. Update the map.
2329 auto Pair = M.insert({Ops[i], Scale});
2330 if (Pair.second) {
2331 NewOps.push_back(Pair.first->first);
2332 } else {
2333 Pair.first->second += Scale;
2334 // The map already had an entry for this value, which may indicate
2335 // a folding opportunity.
2336 Interesting = true;
2337 }
2338 }
2339 }
2340
2341 return Interesting;
2342}
2343
2345 const SCEV *LHS, const SCEV *RHS,
2346 const Instruction *CtxI) {
2348 unsigned);
2349 switch (BinOp) {
2350 default:
2351 llvm_unreachable("Unsupported binary op");
2352 case Instruction::Add:
2354 break;
2355 case Instruction::Sub:
2357 break;
2358 case Instruction::Mul:
2360 break;
2361 }
2362
2363 const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
2366
2367 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2368 auto *NarrowTy = cast<IntegerType>(LHS->getType());
2369 auto *WideTy =
2370 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2371
2372 const SCEV *A = (this->*Extension)(
2373 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2374 const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2375 const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2376 const SCEV *B = (this->*Operation)(LHSB, RHSB, SCEV::FlagAnyWrap, 0);
2377 if (A == B)
2378 return true;
2379 // Can we use context to prove the fact we need?
2380 if (!CtxI)
2381 return false;
2382 // TODO: Support mul.
2383 if (BinOp == Instruction::Mul)
2384 return false;
2385 auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2386 // TODO: Lift this limitation.
2387 if (!RHSC)
2388 return false;
2389 APInt C = RHSC->getAPInt();
2390 unsigned NumBits = C.getBitWidth();
2391 bool IsSub = (BinOp == Instruction::Sub);
2392 bool IsNegativeConst = (Signed && C.isNegative());
2393 // Compute the direction and magnitude by which we need to check overflow.
2394 bool OverflowDown = IsSub ^ IsNegativeConst;
2395 APInt Magnitude = C;
2396 if (IsNegativeConst) {
2397 if (C == APInt::getSignedMinValue(NumBits))
2398 // TODO: SINT_MIN on inversion gives the same negative value, we don't
2399 // want to deal with that.
2400 return false;
2401 Magnitude = -C;
2402 }
2403
2405 if (OverflowDown) {
2406 // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2407 APInt Min = Signed ? APInt::getSignedMinValue(NumBits)
2408 : APInt::getMinValue(NumBits);
2409 APInt Limit = Min + Magnitude;
2410 return isKnownPredicateAt(Pred, getConstant(Limit), LHS, CtxI);
2411 } else {
2412 // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2413 APInt Max = Signed ? APInt::getSignedMaxValue(NumBits)
2414 : APInt::getMaxValue(NumBits);
2415 APInt Limit = Max - Magnitude;
2416 return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2417 }
2418}
2419
2420std::optional<SCEV::NoWrapFlags>
2422 const OverflowingBinaryOperator *OBO) {
2423 // It cannot be done any better.
2424 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2425 return std::nullopt;
2426
2427 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2428
2429 if (OBO->hasNoUnsignedWrap())
2431 if (OBO->hasNoSignedWrap())
2433
2434 bool Deduced = false;
2435
2437 const SCEV *LHS = getSCEV(OBO->getOperand(0));
2438 const SCEV *RHS = getSCEV(OBO->getOperand(1));
2439
2440 bool CanUseNSW = true;
2441 const APInt *ShiftAmt;
2442 // Treat `shl %a, C` as `mul %a, 1 << C`.
2443 if (match(OBO, m_Shl(m_Value(), m_APInt(ShiftAmt)))) {
2444 unsigned BitWidth = ShiftAmt->getBitWidth();
2445 if (ShiftAmt->uge(BitWidth))
2446 return std::nullopt;
2447 // NSW only transfers if the shift amount is < BitWidth - 1, as INT_MIN * -1
2448 // overflows.
2449 CanUseNSW = ShiftAmt->ult(BitWidth - 1);
2450 Opcode = Instruction::Mul;
2452 } else if (Opcode != Instruction::Add && Opcode != Instruction::Sub &&
2453 Opcode != Instruction::Mul) {
2454 return std::nullopt;
2455 }
2456
2457 const Instruction *CtxI =
2459 if (!OBO->hasNoUnsignedWrap() &&
2460 willNotOverflow(Opcode, /* Signed */ false, LHS, RHS, CtxI)) {
2462 Deduced = true;
2463 }
2464
2465 if (CanUseNSW && !OBO->hasNoSignedWrap() &&
2466 willNotOverflow(Opcode, /* Signed */ true, LHS, RHS, CtxI)) {
2468 Deduced = true;
2469 }
2470
2471 if (Deduced)
2472 return Flags;
2473 return std::nullopt;
2474}
2475
2476// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2477// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2478// can't-overflow flags for the operation if possible.
2482 SCEV::NoWrapFlags Flags) {
2483 using namespace std::placeholders;
2484
2485 using OBO = OverflowingBinaryOperator;
2486
2487 bool CanAnalyze =
2489 (void)CanAnalyze;
2490 assert(CanAnalyze && "don't call from other places!");
2491
2492 SCEV::NoWrapFlags SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2493 SCEV::NoWrapFlags SignOrUnsignWrap =
2494 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2495
2496 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2497 auto IsKnownNonNegative = [&](SCEVUse U) {
2498 return SE->isKnownNonNegative(U);
2499 };
2500
2501 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2502 Flags = ScalarEvolution::setFlags(Flags, SignOrUnsignMask);
2503
2504 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2505
2506 if (SignOrUnsignWrap != SignOrUnsignMask &&
2507 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2508 isa<SCEVConstant>(Ops[0])) {
2509
2510 auto Opcode = [&] {
2511 switch (Type) {
2512 case scAddExpr:
2513 return Instruction::Add;
2514 case scMulExpr:
2515 return Instruction::Mul;
2516 default:
2517 llvm_unreachable("Unexpected SCEV op.");
2518 }
2519 }();
2520
2521 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2522
2523 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2524 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2526 Opcode, C, OBO::NoSignedWrap);
2527 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2529 }
2530
2531 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2532 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2534 Opcode, C, OBO::NoUnsignedWrap);
2535 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2537 }
2538 }
2539
2540 // <0,+,nonnegative><nw> is also nuw
2541 // TODO: Add corresponding nsw case
2543 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2544 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2546
2547 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2549 Ops.size() == 2) {
2550 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2551 if (UDiv->getOperand(1) == Ops[1])
2553 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2554 if (UDiv->getOperand(1) == Ops[0])
2556 }
2557
2558 return Flags;
2559}
2560
2562 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2563}
2564
2565/// Get a canonical add expression, or something simpler if possible.
2567 SCEV::NoWrapFlags OrigFlags,
2568 unsigned Depth) {
2569 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2570 "only nuw or nsw allowed");
2571 assert(!Ops.empty() && "Cannot get empty add!");
2572 if (Ops.size() == 1) return Ops[0];
2573#ifndef NDEBUG
2574 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2575 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2576 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2577 "SCEVAddExpr operand types don't match!");
2578 unsigned NumPtrs = count_if(
2579 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2580 assert(NumPtrs <= 1 && "add has at most one pointer operand");
2581#endif
2582
2583 const SCEV *Folded = constantFoldAndGroupOps(
2584 *this, LI, DT, Ops,
2585 [](const APInt &C1, const APInt &C2) { return C1 + C2; },
2586 [](const APInt &C) { return C.isZero(); }, // identity
2587 [](const APInt &C) { return false; }); // absorber
2588 if (Folded)
2589 return Folded;
2590
2591 unsigned Idx = isa<SCEVConstant>(Ops[0]) ? 1 : 0;
2592
2593 // Delay expensive flag strengthening until necessary.
2594 auto ComputeFlags = [this, OrigFlags](ArrayRef<SCEVUse> Ops) {
2595 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2596 };
2597
2598 // Limit recursion calls depth.
2600 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2601
2602 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2603 // Don't strengthen flags if we have no new information.
2604 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2605 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2606 Add->setNoWrapFlags(ComputeFlags(Ops));
2607 return S;
2608 }
2609
2610 // Okay, check to see if the same value occurs in the operand list more than
2611 // once. If so, merge them together into an multiply expression. Since we
2612 // sorted the list, these values are required to be adjacent.
2613 Type *Ty = Ops[0]->getType();
2614 bool FoundMatch = false;
2615 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2616 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2617 // Scan ahead to count how many equal operands there are.
2618 unsigned Count = 2;
2619 while (i+Count != e && Ops[i+Count] == Ops[i])
2620 ++Count;
2621 // Merge the values into a multiply.
2622 SCEVUse Scale = getConstant(Ty, Count);
2623 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2624 if (Ops.size() == Count)
2625 return Mul;
2626 Ops[i] = Mul;
2627 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2628 --i; e -= Count - 1;
2629 FoundMatch = true;
2630 }
2631 if (FoundMatch)
2632 return getAddExpr(Ops, OrigFlags, Depth + 1);
2633
2634 // Check for truncates. If all the operands are truncated from the same
2635 // type, see if factoring out the truncate would permit the result to be
2636 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2637 // if the contents of the resulting outer trunc fold to something simple.
2638 auto FindTruncSrcType = [&]() -> Type * {
2639 // We're ultimately looking to fold an addrec of truncs and muls of only
2640 // constants and truncs, so if we find any other types of SCEV
2641 // as operands of the addrec then we bail and return nullptr here.
2642 // Otherwise, we return the type of the operand of a trunc that we find.
2643 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2644 return T->getOperand()->getType();
2645 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2646 SCEVUse LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2647 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2648 return T->getOperand()->getType();
2649 }
2650 return nullptr;
2651 };
2652 if (auto *SrcType = FindTruncSrcType()) {
2653 SmallVector<SCEVUse, 8> LargeOps;
2654 bool Ok = true;
2655 // Check all the operands to see if they can be represented in the
2656 // source type of the truncate.
2657 for (const SCEV *Op : Ops) {
2659 if (T->getOperand()->getType() != SrcType) {
2660 Ok = false;
2661 break;
2662 }
2663 LargeOps.push_back(T->getOperand());
2664 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Op)) {
2665 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2666 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Op)) {
2667 SmallVector<SCEVUse, 8> LargeMulOps;
2668 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2669 if (const SCEVTruncateExpr *T =
2670 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2671 if (T->getOperand()->getType() != SrcType) {
2672 Ok = false;
2673 break;
2674 }
2675 LargeMulOps.push_back(T->getOperand());
2676 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2677 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2678 } else {
2679 Ok = false;
2680 break;
2681 }
2682 }
2683 if (Ok)
2684 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2685 } else {
2686 Ok = false;
2687 break;
2688 }
2689 }
2690 if (Ok) {
2691 // Evaluate the expression in the larger type.
2692 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2693 // If it folds to something simple, use it. Otherwise, don't.
2694 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2695 return getTruncateExpr(Fold, Ty);
2696 }
2697 }
2698
2699 if (Ops.size() == 2) {
2700 // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2701 // C2 can be folded in a way that allows retaining wrapping flags of (X +
2702 // C1).
2703 const SCEV *A = Ops[0];
2704 const SCEV *B = Ops[1];
2705 auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2706 auto *C = dyn_cast<SCEVConstant>(A);
2707 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2708 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2709 auto C2 = C->getAPInt();
2710 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2711
2712 APInt ConstAdd = C1 + C2;
2713 auto AddFlags = AddExpr->getNoWrapFlags();
2714 // Adding a smaller constant is NUW if the original AddExpr was NUW.
2716 ConstAdd.ule(C1)) {
2717 PreservedFlags =
2719 }
2720
2721 // Adding a constant with the same sign and small magnitude is NSW, if the
2722 // original AddExpr was NSW.
2724 C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2725 ConstAdd.abs().ule(C1.abs())) {
2726 PreservedFlags =
2728 }
2729
2730 if (PreservedFlags != SCEV::FlagAnyWrap) {
2731 SmallVector<SCEVUse, 4> NewOps(AddExpr->operands());
2732 NewOps[0] = getConstant(ConstAdd);
2733 return getAddExpr(NewOps, PreservedFlags);
2734 }
2735 }
2736
2737 // Try to push the constant operand into a ZExt: A + zext (-A + B) -> zext
2738 // (B), if trunc (A) + -A + B does not unsigned-wrap.
2739 const SCEVAddExpr *InnerAdd;
2740 if (match(B, m_scev_ZExt(m_scev_Add(InnerAdd)))) {
2741 const SCEV *NarrowA = getTruncateExpr(A, InnerAdd->getType());
2742 if (NarrowA == getNegativeSCEV(InnerAdd->getOperand(0)) &&
2743 getZeroExtendExpr(NarrowA, B->getType()) == A &&
2744 hasFlags(StrengthenNoWrapFlags(this, scAddExpr, {NarrowA, InnerAdd},
2746 SCEV::FlagNUW)) {
2747 return getZeroExtendExpr(getAddExpr(NarrowA, InnerAdd), B->getType());
2748 }
2749 }
2750 }
2751
2752 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2753 const SCEV *Y;
2754 if (Ops.size() == 2 &&
2755 match(Ops[0],
2757 m_scev_URem(m_scev_Specific(Ops[1]), m_SCEV(Y), *this))))
2758 return getMulExpr(Y, getUDivExpr(Ops[1], Y));
2759
2760 // Skip past any other cast SCEVs.
2761 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2762 ++Idx;
2763
2764 // If there are add operands they would be next.
2765 if (Idx < Ops.size()) {
2766 bool DeletedAdd = false;
2767 // If the original flags and all inlined SCEVAddExprs are NUW, use the
2768 // common NUW flag for expression after inlining. Other flags cannot be
2769 // preserved, because they may depend on the original order of operations.
2770 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2771 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2772 if (Ops.size() > AddOpsInlineThreshold ||
2773 Add->getNumOperands() > AddOpsInlineThreshold)
2774 break;
2775 // If we have an add, expand the add operands onto the end of the operands
2776 // list.
2777 Ops.erase(Ops.begin()+Idx);
2778 append_range(Ops, Add->operands());
2779 DeletedAdd = true;
2780 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2781 }
2782
2783 // If we deleted at least one add, we added operands to the end of the list,
2784 // and they are not necessarily sorted. Recurse to resort and resimplify
2785 // any operands we just acquired.
2786 if (DeletedAdd)
2787 return getAddExpr(Ops, CommonFlags, Depth + 1);
2788 }
2789
2790 // Skip over the add expression until we get to a multiply.
2791 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2792 ++Idx;
2793
2794 // Check to see if there are any folding opportunities present with
2795 // operands multiplied by constant values.
2796 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2800 APInt AccumulatedConstant(BitWidth, 0);
2801 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2802 Ops, APInt(BitWidth, 1), *this)) {
2803 struct APIntCompare {
2804 bool operator()(const APInt &LHS, const APInt &RHS) const {
2805 return LHS.ult(RHS);
2806 }
2807 };
2808
2809 // Some interesting folding opportunity is present, so its worthwhile to
2810 // re-generate the operands list. Group the operands by constant scale,
2811 // to avoid multiplying by the same constant scale multiple times.
2812 std::map<APInt, SmallVector<SCEVUse, 4>, APIntCompare> MulOpLists;
2813 for (const SCEV *NewOp : NewOps)
2814 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2815 // Re-generate the operands list.
2816 Ops.clear();
2817 if (AccumulatedConstant != 0)
2818 Ops.push_back(getConstant(AccumulatedConstant));
2819 for (auto &MulOp : MulOpLists) {
2820 if (MulOp.first == 1) {
2821 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2822 } else if (MulOp.first != 0) {
2823 Ops.push_back(getMulExpr(
2824 getConstant(MulOp.first),
2825 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2826 SCEV::FlagAnyWrap, Depth + 1));
2827 }
2828 }
2829 if (Ops.empty())
2830 return getZero(Ty);
2831 if (Ops.size() == 1)
2832 return Ops[0];
2833 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2834 }
2835 }
2836
2837 // Given a SCEVMulExpr and an operand index, return the product of all
2838 // operands except the one at OpIdx.
2839 auto StripFactor = [&](const SCEVMulExpr *M, unsigned OpIdx) -> SCEVUse {
2840 if (M->getNumOperands() == 2)
2841 return M->getOperand(OpIdx == 0);
2842 SmallVector<SCEVUse, 4> Remaining(M->operands().take_front(OpIdx));
2843 append_range(Remaining, M->operands().drop_front(OpIdx + 1));
2844 return getMulExpr(Remaining, SCEV::FlagAnyWrap, Depth + 1);
2845 };
2846
2847 // If we are adding something to a multiply expression, make sure the
2848 // something is not already an operand of the multiply. If so, merge it into
2849 // the multiply.
2850 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2851 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2852 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2853 // Scan all terms to find every occurrence of common factor MulOpSCEV
2854 // and fold them in one shot:
2855 // A1*X + A2*X + ... + An*X --> X * (A1 + A2 + ... + An)
2856 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2857 if (isa<SCEVConstant>(MulOpSCEV))
2858 continue;
2859
2860 // Cofactors: 1 for bare addends matching MulOpSCEV, or the
2861 // remaining product for multiply terms containing MulOpSCEV.
2862 SmallVector<SCEVUse, 4> Cofactors;
2863 SmallVector<unsigned, 4> DeadIndices;
2864 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) {
2865 if (MulOpSCEV == Ops[AddOp]) {
2866 // W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2867 Cofactors.push_back(getOne(Ty));
2868 DeadIndices.push_back(AddOp);
2869 continue;
2870 }
2871
2872 if (AddOp <= Idx || !isa<SCEVMulExpr>(Ops[AddOp]))
2873 continue;
2874
2875 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[AddOp]);
2876 for (unsigned OMulOp = 0, OE = OtherMul->getNumOperands(); OMulOp != OE;
2877 ++OMulOp) {
2878 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2879 // (A*B*C) + (A*D*E) --> A * (B*C + D*E)
2880 Cofactors.push_back(StripFactor(OtherMul, OMulOp));
2881 DeadIndices.push_back(AddOp);
2882 break;
2883 }
2884 }
2885 }
2886
2887 // Fold all collected cofactors with the anchor multiply's cofactor:
2888 // MulOpSCEV * (Cofactor_1 + ... + Cofactor_n + AnchorCofactor)
2889 if (!Cofactors.empty()) {
2890 Cofactors.push_back(StripFactor(Mul, MulOp));
2891
2892 SCEVUse InnerSum = getAddExpr(Cofactors, SCEV::FlagAnyWrap, Depth + 1);
2893 SCEVUse OuterMul =
2894 getMulExpr(MulOpSCEV, InnerSum, SCEV::FlagAnyWrap, Depth + 1);
2895
2896 // DeadIndices does not include Idx (the anchor), hence +1.
2897 if (Ops.size() == DeadIndices.size() + 1)
2898 return OuterMul;
2899
2900 // Erase Ops[Idx] first, then erase DeadIndices in reverse order.
2901 // The -1 adjustment accounts for the shift from removing Idx;
2902 // reverse order means each erasure only shifts later positions,
2903 // which have already been processed.
2904 Ops.erase(Ops.begin() + Idx);
2905 for (unsigned Dead : reverse(DeadIndices))
2906 Ops.erase(Ops.begin() + (Dead > Idx ? Dead - 1 : Dead));
2907
2908 Ops.push_back(OuterMul);
2909 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2910 }
2911 }
2912 }
2913
2914 // If there are any add recurrences in the operands list, see if any other
2915 // added values are loop invariant. If so, we can fold them into the
2916 // recurrence.
2917 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2918 ++Idx;
2919
2920 // Scan over all recurrences, trying to fold loop invariants into them.
2921 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2922 // Scan all of the other operands to this add and add them to the vector if
2923 // they are loop invariant w.r.t. the recurrence.
2925 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2926 const Loop *AddRecLoop = AddRec->getLoop();
2927 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2928 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2929 LIOps.push_back(Ops[i]);
2930 Ops.erase(Ops.begin()+i);
2931 --i; --e;
2932 }
2933
2934 // If we found some loop invariants, fold them into the recurrence.
2935 if (!LIOps.empty()) {
2936 // Compute nowrap flags for the addition of the loop-invariant ops and
2937 // the addrec. Temporarily push it as an operand for that purpose. These
2938 // flags are valid in the scope of the addrec only.
2939 LIOps.push_back(AddRec);
2940 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2941 LIOps.pop_back();
2942
2943 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2944 LIOps.push_back(AddRec->getStart());
2945
2946 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2947
2948 // It is not in general safe to propagate flags valid on an add within
2949 // the addrec scope to one outside it. We must prove that the inner
2950 // scope is guaranteed to execute if the outer one does to be able to
2951 // safely propagate. We know the program is undefined if poison is
2952 // produced on the inner scoped addrec. We also know that *for this use*
2953 // the outer scoped add can't overflow (because of the flags we just
2954 // computed for the inner scoped add) without the program being undefined.
2955 // Proving that entry to the outer scope neccesitates entry to the inner
2956 // scope, thus proves the program undefined if the flags would be violated
2957 // in the outer scope.
2958 SCEV::NoWrapFlags AddFlags = Flags;
2959 if (AddFlags != SCEV::FlagAnyWrap) {
2960 auto *DefI = getDefiningScopeBound(LIOps);
2961 auto *ReachI = &*AddRecLoop->getHeader()->begin();
2962 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2963 AddFlags = SCEV::FlagAnyWrap;
2964 }
2965 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2966
2967 // Build the new addrec. Propagate the NUW and NSW flags if both the
2968 // outer add and the inner addrec are guaranteed to have no overflow.
2969 // Always propagate NW.
2970 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2971 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2972
2973 // If all of the other operands were loop invariant, we are done.
2974 if (Ops.size() == 1) return NewRec;
2975
2976 // Otherwise, add the folded AddRec by the non-invariant parts.
2977 for (unsigned i = 0;; ++i)
2978 if (Ops[i] == AddRec) {
2979 Ops[i] = NewRec;
2980 break;
2981 }
2982 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2983 }
2984
2985 // Okay, if there weren't any loop invariants to be folded, check to see if
2986 // there are multiple AddRec's with the same loop induction variable being
2987 // added together. If so, we can fold them.
2988 for (unsigned OtherIdx = Idx+1;
2989 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2990 ++OtherIdx) {
2991 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2992 // so that the 1st found AddRecExpr is dominated by all others.
2993 assert(DT.dominates(
2994 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2995 AddRec->getLoop()->getHeader()) &&
2996 "AddRecExprs are not sorted in reverse dominance order?");
2997 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2998 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2999 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
3000 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3001 ++OtherIdx) {
3002 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3003 if (OtherAddRec->getLoop() == AddRecLoop) {
3004 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
3005 i != e; ++i) {
3006 if (i >= AddRecOps.size()) {
3007 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
3008 break;
3009 }
3010 AddRecOps[i] =
3011 getAddExpr(AddRecOps[i], OtherAddRec->getOperand(i),
3013 }
3014 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3015 }
3016 }
3017 // Step size has changed, so we cannot guarantee no self-wraparound.
3018 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
3019 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3020 }
3021 }
3022
3023 // Otherwise couldn't fold anything into this recurrence. Move onto the
3024 // next one.
3025 }
3026
3027 // Okay, it looks like we really DO need an add expr. Check to see if we
3028 // already have one, otherwise create a new one.
3029 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
3030}
3031
3032const SCEV *ScalarEvolution::getOrCreateAddExpr(ArrayRef<SCEVUse> Ops,
3033 SCEV::NoWrapFlags Flags) {
3036 for (const SCEV *Op : Ops)
3037 ID.AddPointer(Op);
3038 void *IP = nullptr;
3039 SCEVAddExpr *S =
3040 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3041 if (!S) {
3042 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3044 S = new (SCEVAllocator)
3045 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
3046 UniqueSCEVs.InsertNode(S, IP);
3047 S->computeAndSetCanonical(*this);
3048 registerUser(S, Ops);
3049 }
3050 S->setNoWrapFlags(Flags);
3051 return S;
3052}
3053
3054const SCEV *ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<SCEVUse> Ops,
3055 const Loop *L,
3056 SCEV::NoWrapFlags Flags) {
3057 FoldingSetNodeID ID;
3058 ID.AddInteger(scAddRecExpr);
3059 for (const SCEV *Op : Ops)
3060 ID.AddPointer(Op);
3061 ID.AddPointer(L);
3062 void *IP = nullptr;
3063 SCEVAddRecExpr *S =
3064 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3065 if (!S) {
3066 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3068 S = new (SCEVAllocator)
3069 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
3070 UniqueSCEVs.InsertNode(S, IP);
3071 S->computeAndSetCanonical(*this);
3072 LoopUsers[L].push_back(S);
3073 registerUser(S, Ops);
3074 }
3075 setNoWrapFlags(S, Flags);
3076 return S;
3077}
3078
3079const SCEV *ScalarEvolution::getOrCreateMulExpr(ArrayRef<SCEVUse> Ops,
3080 SCEV::NoWrapFlags Flags) {
3081 FoldingSetNodeID ID;
3082 ID.AddInteger(scMulExpr);
3083 for (const SCEV *Op : Ops)
3084 ID.AddPointer(Op);
3085 void *IP = nullptr;
3086 SCEVMulExpr *S =
3087 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3088 if (!S) {
3089 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3091 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
3092 O, Ops.size());
3093 UniqueSCEVs.InsertNode(S, IP);
3094 S->computeAndSetCanonical(*this);
3095 registerUser(S, Ops);
3096 }
3097 S->setNoWrapFlags(Flags);
3098 return S;
3099}
3100
3101static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
3102 uint64_t k = i*j;
3103 if (j > 1 && k / j != i) Overflow = true;
3104 return k;
3105}
3106
3107/// Compute the result of "n choose k", the binomial coefficient. If an
3108/// intermediate computation overflows, Overflow will be set and the return will
3109/// be garbage. Overflow is not cleared on absence of overflow.
3110static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3111 // We use the multiplicative formula:
3112 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3113 // At each iteration, we take the n-th term of the numeral and divide by the
3114 // (k-n)th term of the denominator. This division will always produce an
3115 // integral result, and helps reduce the chance of overflow in the
3116 // intermediate computations. However, we can still overflow even when the
3117 // final result would fit.
3118
3119 if (n == 0 || n == k) return 1;
3120 if (k > n) return 0;
3121
3122 if (k > n/2)
3123 k = n-k;
3124
3125 uint64_t r = 1;
3126 for (uint64_t i = 1; i <= k; ++i) {
3127 r = umul_ov(r, n-(i-1), Overflow);
3128 r /= i;
3129 }
3130 return r;
3131}
3132
3133/// Determine if any of the operands in this SCEV are a constant or if
3134/// any of the add or multiply expressions in this SCEV contain a constant.
3135static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3136 struct FindConstantInAddMulChain {
3137 bool FoundConstant = false;
3138
3139 bool follow(const SCEV *S) {
3140 FoundConstant |= isa<SCEVConstant>(S);
3141 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3142 }
3143
3144 bool isDone() const {
3145 return FoundConstant;
3146 }
3147 };
3148
3149 FindConstantInAddMulChain F;
3151 ST.visitAll(StartExpr);
3152 return F.FoundConstant;
3153}
3154
3155/// Get a canonical multiply expression, or something simpler if possible.
3157 SCEV::NoWrapFlags OrigFlags,
3158 unsigned Depth) {
3159 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3160 "only nuw or nsw allowed");
3161 assert(!Ops.empty() && "Cannot get empty mul!");
3162 if (Ops.size() == 1) return Ops[0];
3163#ifndef NDEBUG
3164 Type *ETy = Ops[0]->getType();
3165 assert(!ETy->isPointerTy());
3166 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3167 assert(Ops[i]->getType() == ETy &&
3168 "SCEVMulExpr operand types don't match!");
3169#endif
3170
3171 const SCEV *Folded = constantFoldAndGroupOps(
3172 *this, LI, DT, Ops,
3173 [](const APInt &C1, const APInt &C2) { return C1 * C2; },
3174 [](const APInt &C) { return C.isOne(); }, // identity
3175 [](const APInt &C) { return C.isZero(); }); // absorber
3176 if (Folded)
3177 return Folded;
3178
3179 // Delay expensive flag strengthening until necessary.
3180 auto ComputeFlags = [this, OrigFlags](const ArrayRef<SCEVUse> Ops) {
3181 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3182 };
3183
3184 // Limit recursion calls depth.
3186 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3187
3188 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3189 // Don't strengthen flags if we have no new information.
3190 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3191 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3192 Mul->setNoWrapFlags(ComputeFlags(Ops));
3193 return S;
3194 }
3195
3196 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3197 if (Ops.size() == 2) {
3198 // C1*(C2+V) -> C1*C2 + C1*V
3199 // If any of Add's ops are Adds or Muls with a constant, apply this
3200 // transformation as well.
3201 //
3202 // TODO: There are some cases where this transformation is not
3203 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
3204 // this transformation should be narrowed down.
3205 const SCEV *Op0, *Op1;
3206 if (match(Ops[1], m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))) &&
3208 const SCEV *LHS = getMulExpr(LHSC, Op0, SCEV::FlagAnyWrap, Depth + 1);
3209 const SCEV *RHS = getMulExpr(LHSC, Op1, SCEV::FlagAnyWrap, Depth + 1);
3210 return getAddExpr(LHS, RHS, SCEV::FlagAnyWrap, Depth + 1);
3211 }
3212
3213 if (Ops[0]->isAllOnesValue()) {
3214 // If we have a mul by -1 of an add, try distributing the -1 among the
3215 // add operands.
3216 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3218 bool AnyFolded = false;
3219 for (const SCEV *AddOp : Add->operands()) {
3220 const SCEV *Mul = getMulExpr(Ops[0], SCEVUse(AddOp),
3222 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3223 NewOps.push_back(Mul);
3224 }
3225 if (AnyFolded)
3226 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3227 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3228 // Negation preserves a recurrence's no self-wrap property.
3229 SmallVector<SCEVUse, 4> Operands;
3230 for (const SCEV *AddRecOp : AddRec->operands())
3231 Operands.push_back(getMulExpr(Ops[0], SCEVUse(AddRecOp),
3232 SCEV::FlagAnyWrap, Depth + 1));
3233 // Let M be the minimum representable signed value. AddRec with nsw
3234 // multiplied by -1 can have signed overflow if and only if it takes a
3235 // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3236 // maximum signed value. In all other cases signed overflow is
3237 // impossible.
3238 auto FlagsMask = SCEV::FlagNW;
3239 if (AddRec->hasNoSignedWrap()) {
3240 auto MinInt =
3241 APInt::getSignedMinValue(getTypeSizeInBits(AddRec->getType()));
3242 if (getSignedRangeMin(AddRec) != MinInt)
3243 FlagsMask = setFlags(FlagsMask, SCEV::FlagNSW);
3244 }
3245 return getAddRecExpr(Operands, AddRec->getLoop(),
3246 AddRec->getNoWrapFlags(FlagsMask));
3247 }
3248 }
3249
3250 // Try to push the constant operand into a ZExt: C * zext (A + B) ->
3251 // zext (C*A + C*B) if trunc (C) * (A + B) does not unsigned-wrap.
3252 const SCEVAddExpr *InnerAdd;
3253 if (match(Ops[1], m_scev_ZExt(m_scev_Add(InnerAdd)))) {
3254 const SCEV *NarrowC = getTruncateExpr(LHSC, InnerAdd->getType());
3255 if (isa<SCEVConstant>(InnerAdd->getOperand(0)) &&
3256 getZeroExtendExpr(NarrowC, Ops[1]->getType()) == LHSC &&
3257 hasFlags(StrengthenNoWrapFlags(this, scMulExpr, {NarrowC, InnerAdd},
3259 SCEV::FlagNUW)) {
3260 auto *Res = getMulExpr(NarrowC, InnerAdd, SCEV::FlagNUW, Depth + 1);
3261 return getZeroExtendExpr(Res, Ops[1]->getType(), Depth + 1);
3262 };
3263 }
3264
3265 // Try to fold (C1 * D /u C2) -> C1/C2 * D, if C1 and C2 are powers-of-2,
3266 // D is a multiple of C2, and C1 is a multiple of C2. If C2 is a multiple
3267 // of C1, fold to (D /u (C2 /u C1)).
3268 const SCEV *D;
3269 APInt C1V = LHSC->getAPInt();
3270 // (C1 * D /u C2) == -1 * -C1 * D /u C2 when C1 != INT_MIN. Don't treat -1
3271 // as -1 * 1, as it won't enable additional folds.
3272 if (C1V.isNegative() && !C1V.isMinSignedValue() && !C1V.isAllOnes())
3273 C1V = C1V.abs();
3274 const SCEVConstant *C2;
3275 if (C1V.isPowerOf2() &&
3277 C2->getAPInt().isPowerOf2() &&
3278 C1V.logBase2() <= getMinTrailingZeros(D)) {
3279 const SCEV *NewMul = nullptr;
3280 if (C1V.uge(C2->getAPInt())) {
3281 NewMul = getMulExpr(getUDivExpr(getConstant(C1V), C2), D);
3282 } else if (C2->getAPInt().logBase2() <= getMinTrailingZeros(D)) {
3283 assert(C1V.ugt(1) && "C1 <= 1 should have been folded earlier");
3284 NewMul = getUDivExpr(D, getUDivExpr(C2, getConstant(C1V)));
3285 }
3286 if (NewMul)
3287 return C1V == LHSC->getAPInt() ? NewMul : getNegativeSCEV(NewMul);
3288 }
3289 }
3290 }
3291
3292 // Skip over the add expression until we get to a multiply.
3293 unsigned Idx = 0;
3294 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3295 ++Idx;
3296
3297 // If there are mul operands inline them all into this expression.
3298 if (Idx < Ops.size()) {
3299 bool DeletedMul = false;
3300 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3301 if (Ops.size() > MulOpsInlineThreshold)
3302 break;
3303 // If we have an mul, expand the mul operands onto the end of the
3304 // operands list.
3305 Ops.erase(Ops.begin()+Idx);
3306 append_range(Ops, Mul->operands());
3307 DeletedMul = true;
3308 }
3309
3310 // If we deleted at least one mul, we added operands to the end of the
3311 // list, and they are not necessarily sorted. Recurse to resort and
3312 // resimplify any operands we just acquired.
3313 if (DeletedMul)
3314 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3315 }
3316
3317 // If there are any add recurrences in the operands list, see if any other
3318 // added values are loop invariant. If so, we can fold them into the
3319 // recurrence.
3320 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3321 ++Idx;
3322
3323 // Scan over all recurrences, trying to fold loop invariants into them.
3324 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3325 // Scan all of the other operands to this mul and add them to the vector
3326 // if they are loop invariant w.r.t. the recurrence.
3328 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3329 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3330 if (isAvailableAtLoopEntry(Ops[i], AddRec->getLoop())) {
3331 LIOps.push_back(Ops[i]);
3332 Ops.erase(Ops.begin()+i);
3333 --i; --e;
3334 }
3335
3336 // If we found some loop invariants, fold them into the recurrence.
3337 if (!LIOps.empty()) {
3338 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3340 NewOps.reserve(AddRec->getNumOperands());
3341 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3342
3343 // If both the mul and addrec are nuw, we can preserve nuw.
3344 // If both the mul and addrec are nsw, we can only preserve nsw if either
3345 // a) they are also nuw, or
3346 // b) all multiplications of addrec operands with scale are nsw.
3347 SCEV::NoWrapFlags Flags =
3348 AddRec->getNoWrapFlags(ComputeFlags({Scale, AddRec}));
3349
3350 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3351 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3352 SCEV::FlagAnyWrap, Depth + 1));
3353
3354 if (hasFlags(Flags, SCEV::FlagNSW) && !hasFlags(Flags, SCEV::FlagNUW)) {
3356 Instruction::Mul, getSignedRange(Scale),
3358 if (!NSWRegion.contains(getSignedRange(AddRec->getOperand(i))))
3359 Flags = clearFlags(Flags, SCEV::FlagNSW);
3360 }
3361 }
3362
3363 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(), Flags);
3364
3365 // If all of the other operands were loop invariant, we are done.
3366 if (Ops.size() == 1) return NewRec;
3367
3368 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3369 for (unsigned i = 0;; ++i)
3370 if (Ops[i] == AddRec) {
3371 Ops[i] = NewRec;
3372 break;
3373 }
3374 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3375 }
3376
3377 // Okay, if there weren't any loop invariants to be folded, check to see
3378 // if there are multiple AddRec's with the same loop induction variable
3379 // being multiplied together. If so, we can fold them.
3380
3381 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3382 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3383 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3384 // ]]],+,...up to x=2n}.
3385 // Note that the arguments to choose() are always integers with values
3386 // known at compile time, never SCEV objects.
3387 //
3388 // The implementation avoids pointless extra computations when the two
3389 // addrec's are of different length (mathematically, it's equivalent to
3390 // an infinite stream of zeros on the right).
3391 bool OpsModified = false;
3392 for (unsigned OtherIdx = Idx+1;
3393 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3394 ++OtherIdx) {
3395 const SCEVAddRecExpr *OtherAddRec =
3396 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3397 if (!OtherAddRec || OtherAddRec->getLoop() != AddRec->getLoop())
3398 continue;
3399
3400 // Limit max number of arguments to avoid creation of unreasonably big
3401 // SCEVAddRecs with very complex operands.
3402 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3403 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3404 continue;
3405
3406 bool Overflow = false;
3407 Type *Ty = AddRec->getType();
3408 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3409 SmallVector<SCEVUse, 7> AddRecOps;
3410 for (int x = 0, xe = AddRec->getNumOperands() +
3411 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3413 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3414 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3415 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3416 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3417 z < ze && !Overflow; ++z) {
3418 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3419 uint64_t Coeff;
3420 if (LargerThan64Bits)
3421 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3422 else
3423 Coeff = Coeff1*Coeff2;
3424 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3425 const SCEV *Term1 = AddRec->getOperand(y-z);
3426 const SCEV *Term2 = OtherAddRec->getOperand(z);
3427 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3428 SCEV::FlagAnyWrap, Depth + 1));
3429 }
3430 }
3431 if (SumOps.empty())
3432 SumOps.push_back(getZero(Ty));
3433 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3434 }
3435 if (!Overflow) {
3436 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
3438 if (Ops.size() == 2) return NewAddRec;
3439 Ops[Idx] = NewAddRec;
3440 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3441 OpsModified = true;
3442 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3443 if (!AddRec)
3444 break;
3445 }
3446 }
3447 if (OpsModified)
3448 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3449
3450 // Otherwise couldn't fold anything into this recurrence. Move onto the
3451 // next one.
3452 }
3453
3454 // Okay, it looks like we really DO need an mul expr. Check to see if we
3455 // already have one, otherwise create a new one.
3456 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3457}
3458
3459/// Represents an unsigned remainder expression based on unsigned division.
3461 assert(getEffectiveSCEVType(LHS->getType()) ==
3462 getEffectiveSCEVType(RHS->getType()) &&
3463 "SCEVURemExpr operand types don't match!");
3464
3465 // Short-circuit easy cases
3466 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3467 // If constant is one, the result is trivial
3468 if (RHSC->getValue()->isOne())
3469 return getZero(LHS->getType()); // X urem 1 --> 0
3470
3471 // If constant is a power of two, fold into a zext(trunc(LHS)).
3472 if (RHSC->getAPInt().isPowerOf2()) {
3473 Type *FullTy = LHS->getType();
3474 Type *TruncTy =
3475 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3476 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3477 }
3478 }
3479
3480 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3481 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3482 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3483 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3484}
3485
3486/// Get a canonical unsigned division expression, or something simpler if
3487/// possible.
3489 assert(!LHS->getType()->isPointerTy() &&
3490 "SCEVUDivExpr operand can't be pointer!");
3491 assert(LHS->getType() == RHS->getType() &&
3492 "SCEVUDivExpr operand types don't match!");
3493
3496 ID.AddPointer(LHS);
3497 ID.AddPointer(RHS);
3498 void *IP = nullptr;
3499 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3500 return S;
3501
3502 // 0 udiv Y == 0
3503 if (match(LHS, m_scev_Zero()))
3504 return LHS;
3505
3506 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3507 if (RHSC->getValue()->isOne())
3508 return LHS; // X udiv 1 --> x
3509 // If the denominator is zero, the result of the udiv is undefined. Don't
3510 // try to analyze it, because the resolution chosen here may differ from
3511 // the resolution chosen in other parts of the compiler.
3512 if (!RHSC->getValue()->isZero()) {
3513 // Determine if the division can be folded into the operands of
3514 // its operands.
3515 // TODO: Generalize this to non-constants by using known-bits information.
3516 Type *Ty = LHS->getType();
3517 unsigned LZ = RHSC->getAPInt().countl_zero();
3518 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3519 // For non-power-of-two values, effectively round the value up to the
3520 // nearest power of two.
3521 if (!RHSC->getAPInt().isPowerOf2())
3522 ++MaxShiftAmt;
3523 IntegerType *ExtTy =
3524 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3525 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3526 if (const SCEVConstant *Step =
3527 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3528 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3529 const APInt &StepInt = Step->getAPInt();
3530 const APInt &DivInt = RHSC->getAPInt();
3531 if (!StepInt.urem(DivInt) &&
3532 getZeroExtendExpr(AR, ExtTy) ==
3533 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3534 getZeroExtendExpr(Step, ExtTy),
3535 AR->getLoop(), SCEV::FlagAnyWrap)) {
3536 SmallVector<SCEVUse, 4> Operands;
3537 for (const SCEV *Op : AR->operands())
3538 Operands.push_back(getUDivExpr(Op, RHS));
3539 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3540 }
3541 /// Get a canonical UDivExpr for a recurrence.
3542 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3543 const APInt *StartRem;
3544 if (!DivInt.urem(StepInt) && match(getURemExpr(AR->getStart(), Step),
3545 m_scev_APInt(StartRem))) {
3546 bool NoWrap =
3547 getZeroExtendExpr(AR, ExtTy) ==
3548 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3549 getZeroExtendExpr(Step, ExtTy), AR->getLoop(),
3551
3552 // With N <= C and both N, C as powers-of-2, the transformation
3553 // {X,+,N}/C => {(X - X%N),+,N}/C preserves division results even
3554 // if wrapping occurs, as the division results remain equivalent for
3555 // all offsets in [[(X - X%N), X).
3556 bool CanFoldWithWrap = StepInt.ule(DivInt) && // N <= C
3557 StepInt.isPowerOf2() && DivInt.isPowerOf2();
3558 // Only fold if the subtraction can be folded in the start
3559 // expression.
3560 const SCEV *NewStart =
3561 getMinusSCEV(AR->getStart(), getConstant(*StartRem));
3562 if (*StartRem != 0 && (NoWrap || CanFoldWithWrap) &&
3563 !isa<SCEVAddExpr>(NewStart)) {
3564 const SCEV *NewLHS =
3565 getAddRecExpr(NewStart, Step, AR->getLoop(),
3566 NoWrap ? SCEV::FlagNW : SCEV::FlagAnyWrap);
3567 if (LHS != NewLHS) {
3568 LHS = NewLHS;
3569
3570 // Reset the ID to include the new LHS, and check if it is
3571 // already cached.
3572 ID.clear();
3573 ID.AddInteger(scUDivExpr);
3574 ID.AddPointer(LHS);
3575 ID.AddPointer(RHS);
3576 IP = nullptr;
3577 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3578 return S;
3579 }
3580 }
3581 }
3582 }
3583 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3584 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3585 SmallVector<SCEVUse, 4> Operands;
3586 for (const SCEV *Op : M->operands())
3587 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3588 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) {
3589 // Find an operand that's safely divisible.
3590 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3591 const SCEV *Op = M->getOperand(i);
3592 const SCEV *Div = getUDivExpr(Op, RHSC);
3593 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3594 Operands = SmallVector<SCEVUse, 4>(M->operands());
3595 Operands[i] = Div;
3596 return getMulExpr(Operands);
3597 }
3598 }
3599
3600 // Even if it's not divisible, try to remove a common factor.
3601 if (const auto *LHSC = dyn_cast<SCEVConstant>(M->getOperand(0))) {
3602 APInt Factor = APIntOps::GreatestCommonDivisor(LHSC->getAPInt(),
3603 RHSC->getAPInt());
3604 if (!Factor.isIntN(1)) {
3605 SmallVector<SCEVUse, 2> NewOperands;
3606 NewOperands.push_back(getConstant(LHSC->getAPInt().udiv(Factor)));
3607 append_range(NewOperands, M->operands().drop_front());
3608 const SCEV *NewMul = getMulExpr(NewOperands);
3609 return getUDivExpr(NewMul,
3610 getConstant(RHSC->getAPInt().udiv(Factor)));
3611 }
3612 }
3613 }
3614 }
3615
3616 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3617 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3618 if (auto *DivisorConstant =
3619 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3620 bool Overflow = false;
3621 APInt NewRHS =
3622 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3623 if (Overflow) {
3624 return getConstant(RHSC->getType(), 0, false);
3625 }
3626 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3627 }
3628 }
3629
3630 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3631 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3632 SmallVector<SCEVUse, 4> Operands;
3633 for (const SCEV *Op : A->operands())
3634 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3635 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3636 Operands.clear();
3637 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3638 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3639 if (isa<SCEVUDivExpr>(Op) ||
3640 getMulExpr(Op, RHS) != A->getOperand(i))
3641 break;
3642 Operands.push_back(Op);
3643 }
3644 if (Operands.size() == A->getNumOperands())
3645 return getAddExpr(Operands);
3646 }
3647 }
3648
3649 // ((N - M) + (M * A)) / N --> ((N - 1) + (M * A)) / N
3650 // This is an idiom for rounding A up to the next multiple of N, where A
3651 // is aready known to be a multiple of M. In this case, instcombine can
3652 // see that some low bits of the added constant are unused, so can clear
3653 // them, but we want to canonicalise to set the low bits. This makes the
3654 // pattern easier to match, without needing to check for known bits in
3655 // A*M.
3656 const APInt &N = RHSC->getAPInt();
3657 const APInt *NMinusM, *M;
3658 const SCEV *A;
3659 if (match(LHS, m_scev_Add(m_scev_APInt(NMinusM),
3660 m_scev_Mul(m_scev_APInt(M), m_SCEV(A))))) {
3661 if (N.isPowerOf2() && M->isPowerOf2() && M->ult(N) &&
3662 *NMinusM == N - *M) {
3663 return getUDivExpr(
3665 RHS);
3666 }
3667 }
3668
3669 // Fold if both operands are constant.
3670 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3671 return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3672 }
3673 }
3674
3675 // ((-C + (C smax %x)) /u %x) evaluates to zero, for any positive constant C.
3676 const APInt *NegC, *C;
3677 if (match(LHS,
3680 NegC->isNegative() && !NegC->isMinSignedValue() && *C == -*NegC)
3681 return getZero(LHS->getType());
3682
3683 // (%a * %b)<nuw> / %b -> %a
3684 const auto *Mul = dyn_cast<SCEVMulExpr>(LHS);
3685 if (Mul && Mul->hasNoUnsignedWrap()) {
3686 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3687 if (Mul->getOperand(i) == RHS) {
3688 SmallVector<SCEVUse, 2> Operands;
3689 append_range(Operands, Mul->operands().take_front(i));
3690 append_range(Operands, Mul->operands().drop_front(i + 1));
3691 return getMulExpr(Operands);
3692 }
3693 }
3694 }
3695
3696 // TODO: Generalize to handle any common factors.
3697 // udiv (mul nuw a, vscale), (mul nuw b, vscale) --> udiv a, b
3698 const SCEV *NewLHS, *NewRHS;
3699 if (match(LHS, m_scev_c_NUWMul(m_SCEV(NewLHS), m_SCEVVScale())) &&
3700 match(RHS, m_scev_c_NUWMul(m_SCEV(NewRHS), m_SCEVVScale())))
3701 return getUDivExpr(NewLHS, NewRHS);
3702
3703 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3704 // changes). Make sure we get a new one.
3705 IP = nullptr;
3706 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3707 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3708 LHS, RHS);
3709 UniqueSCEVs.InsertNode(S, IP);
3710 S->computeAndSetCanonical(*this);
3711 registerUser(S, ArrayRef<SCEVUse>({LHS, RHS}));
3712 return S;
3713}
3714
3715APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3716 APInt A = C1->getAPInt().abs();
3717 APInt B = C2->getAPInt().abs();
3718 uint32_t ABW = A.getBitWidth();
3719 uint32_t BBW = B.getBitWidth();
3720
3721 if (ABW > BBW)
3722 B = B.zext(ABW);
3723 else if (ABW < BBW)
3724 A = A.zext(BBW);
3725
3726 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3727}
3728
3729/// Get a canonical unsigned division expression, or something simpler if
3730/// possible. There is no representation for an exact udiv in SCEV IR, but we
3731/// can attempt to optimize it prior to construction.
3733 // Currently there is no exact specific logic.
3734
3735 return getUDivExpr(LHS, RHS);
3736}
3737
3738/// Get an add recurrence expression for the specified loop. Simplify the
3739/// expression as much as possible.
3741 const Loop *L,
3742 SCEV::NoWrapFlags Flags) {
3743 SmallVector<SCEVUse, 4> Operands;
3744 Operands.push_back(Start);
3745 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3746 if (StepChrec->getLoop() == L) {
3747 append_range(Operands, StepChrec->operands());
3748 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3749 }
3750
3751 Operands.push_back(Step);
3752 return getAddRecExpr(Operands, L, Flags);
3753}
3754
3755/// Get an add recurrence expression for the specified loop. Simplify the
3756/// expression as much as possible.
3758 const Loop *L,
3759 SCEV::NoWrapFlags Flags) {
3760 if (Operands.size() == 1) return Operands[0];
3761#ifndef NDEBUG
3762 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3763 for (const SCEV *Op : llvm::drop_begin(Operands)) {
3764 assert(getEffectiveSCEVType(Op->getType()) == ETy &&
3765 "SCEVAddRecExpr operand types don't match!");
3766 assert(!Op->getType()->isPointerTy() && "Step must be integer");
3767 }
3768 for (const SCEV *Op : Operands)
3770 "SCEVAddRecExpr operand is not available at loop entry!");
3771#endif
3772
3773 if (Operands.back()->isZero()) {
3774 Operands.pop_back();
3775 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3776 }
3777
3778 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3779 // use that information to infer NUW and NSW flags. However, computing a
3780 // BE count requires calling getAddRecExpr, so we may not yet have a
3781 // meaningful BE count at this point (and if we don't, we'd be stuck
3782 // with a SCEVCouldNotCompute as the cached BE count).
3783
3784 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3785
3786 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3787 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3788 const Loop *NestedLoop = NestedAR->getLoop();
3789 if (L->contains(NestedLoop)
3790 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3791 : (!NestedLoop->contains(L) &&
3792 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3793 SmallVector<SCEVUse, 4> NestedOperands(NestedAR->operands());
3794 Operands[0] = NestedAR->getStart();
3795 // AddRecs require their operands be loop-invariant with respect to their
3796 // loops. Don't perform this transformation if it would break this
3797 // requirement.
3798 bool AllInvariant = all_of(
3799 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3800
3801 if (AllInvariant) {
3802 // Create a recurrence for the outer loop with the same step size.
3803 //
3804 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3805 // inner recurrence has the same property.
3806 SCEV::NoWrapFlags OuterFlags =
3807 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3808
3809 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3810 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3811 return isLoopInvariant(Op, NestedLoop);
3812 });
3813
3814 if (AllInvariant) {
3815 // Ok, both add recurrences are valid after the transformation.
3816 //
3817 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3818 // the outer recurrence has the same property.
3819 SCEV::NoWrapFlags InnerFlags =
3820 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3821 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3822 }
3823 }
3824 // Reset Operands to its original state.
3825 Operands[0] = NestedAR;
3826 }
3827 }
3828
3829 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3830 // already have one, otherwise create a new one.
3831 return getOrCreateAddRecExpr(Operands, L, Flags);
3832}
3833
3835 ArrayRef<SCEVUse> IndexExprs) {
3836 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3837 // getSCEV(Base)->getType() has the same address space as Base->getType()
3838 // because SCEV::getType() preserves the address space.
3839 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
3840 if (NW != GEPNoWrapFlags::none()) {
3841 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3842 // but to do that, we have to ensure that said flag is valid in the entire
3843 // defined scope of the SCEV.
3844 // TODO: non-instructions have global scope. We might be able to prove
3845 // some global scope cases
3846 auto *GEPI = dyn_cast<Instruction>(GEP);
3847 if (!GEPI || !isSCEVExprNeverPoison(GEPI))
3848 NW = GEPNoWrapFlags::none();
3849 }
3850
3851 return getGEPExpr(BaseExpr, IndexExprs, GEP->getSourceElementType(), NW);
3852}
3853
3855 ArrayRef<SCEVUse> IndexExprs,
3856 Type *SrcElementTy, GEPNoWrapFlags NW) {
3858 if (NW.hasNoUnsignedSignedWrap())
3859 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNSW);
3860 if (NW.hasNoUnsignedWrap())
3861 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNUW);
3862
3863 Type *CurTy = BaseExpr->getType();
3864 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3865 bool FirstIter = true;
3867 for (SCEVUse IndexExpr : IndexExprs) {
3868 // Compute the (potentially symbolic) offset in bytes for this index.
3869 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3870 // For a struct, add the member offset.
3871 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3872 unsigned FieldNo = Index->getZExtValue();
3873 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3874 Offsets.push_back(FieldOffset);
3875
3876 // Update CurTy to the type of the field at Index.
3877 CurTy = STy->getTypeAtIndex(Index);
3878 } else {
3879 // Update CurTy to its element type.
3880 if (FirstIter) {
3881 assert(isa<PointerType>(CurTy) &&
3882 "The first index of a GEP indexes a pointer");
3883 CurTy = SrcElementTy;
3884 FirstIter = false;
3885 } else {
3887 }
3888 // For an array, add the element offset, explicitly scaled.
3889 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3890 // Getelementptr indices are signed.
3891 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3892
3893 // Multiply the index by the element size to compute the element offset.
3894 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3895 Offsets.push_back(LocalOffset);
3896 }
3897 }
3898
3899 // Handle degenerate case of GEP without offsets.
3900 if (Offsets.empty())
3901 return BaseExpr;
3902
3903 // Add the offsets together, assuming nsw if inbounds.
3904 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3905 // Add the base address and the offset. We cannot use the nsw flag, as the
3906 // base address is unsigned. However, if we know that the offset is
3907 // non-negative, we can use nuw.
3908 bool NUW = NW.hasNoUnsignedWrap() ||
3911 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3912 assert(BaseExpr->getType() == GEPExpr->getType() &&
3913 "GEP should not change type mid-flight.");
3914 return GEPExpr;
3915}
3916
3917SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3920 ID.AddInteger(SCEVType);
3921 for (const SCEV *Op : Ops)
3922 ID.AddPointer(Op);
3923 void *IP = nullptr;
3924 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3925}
3926
3927SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3930 ID.AddInteger(SCEVType);
3931 for (const SCEV *Op : Ops)
3932 ID.AddPointer(Op);
3933 void *IP = nullptr;
3934 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3935}
3936
3937const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3939 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3940}
3941
3944 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3945 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3946 if (Ops.size() == 1) return Ops[0];
3947#ifndef NDEBUG
3948 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3949 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3950 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3951 "Operand types don't match!");
3952 assert(Ops[0]->getType()->isPointerTy() ==
3953 Ops[i]->getType()->isPointerTy() &&
3954 "min/max should be consistently pointerish");
3955 }
3956#endif
3957
3958 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3959 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3960
3961 const SCEV *Folded = constantFoldAndGroupOps(
3962 *this, LI, DT, Ops,
3963 [&](const APInt &C1, const APInt &C2) {
3964 switch (Kind) {
3965 case scSMaxExpr:
3966 return APIntOps::smax(C1, C2);
3967 case scSMinExpr:
3968 return APIntOps::smin(C1, C2);
3969 case scUMaxExpr:
3970 return APIntOps::umax(C1, C2);
3971 case scUMinExpr:
3972 return APIntOps::umin(C1, C2);
3973 default:
3974 llvm_unreachable("Unknown SCEV min/max opcode");
3975 }
3976 },
3977 [&](const APInt &C) {
3978 // identity
3979 if (IsMax)
3980 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3981 else
3982 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3983 },
3984 [&](const APInt &C) {
3985 // absorber
3986 if (IsMax)
3987 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3988 else
3989 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3990 });
3991 if (Folded)
3992 return Folded;
3993
3994 // Check if we have created the same expression before.
3995 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3996 return S;
3997 }
3998
3999 // Find the first operation of the same kind
4000 unsigned Idx = 0;
4001 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
4002 ++Idx;
4003
4004 // Check to see if one of the operands is of the same kind. If so, expand its
4005 // operands onto our operand list, and recurse to simplify.
4006 if (Idx < Ops.size()) {
4007 bool DeletedAny = false;
4008 while (Ops[Idx]->getSCEVType() == Kind) {
4009 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
4010 Ops.erase(Ops.begin()+Idx);
4011 append_range(Ops, SMME->operands());
4012 DeletedAny = true;
4013 }
4014
4015 if (DeletedAny)
4016 return getMinMaxExpr(Kind, Ops);
4017 }
4018
4019 // Okay, check to see if the same value occurs in the operand list twice. If
4020 // so, delete one. Since we sorted the list, these values are required to
4021 // be adjacent.
4026 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
4027 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
4028 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
4029 if (Ops[i] == Ops[i + 1] ||
4030 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
4031 // X op Y op Y --> X op Y
4032 // X op Y --> X, if we know X, Y are ordered appropriately
4033 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
4034 --i;
4035 --e;
4036 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
4037 Ops[i + 1])) {
4038 // X op Y --> Y, if we know X, Y are ordered appropriately
4039 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
4040 --i;
4041 --e;
4042 }
4043 }
4044
4045 if (Ops.size() == 1) return Ops[0];
4046
4047 assert(!Ops.empty() && "Reduced smax down to nothing!");
4048
4049 // Okay, it looks like we really DO need an expr. Check to see if we
4050 // already have one, otherwise create a new one.
4052 ID.AddInteger(Kind);
4053 for (const SCEV *Op : Ops)
4054 ID.AddPointer(Op);
4055 void *IP = nullptr;
4056 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4057 if (ExistingSCEV)
4058 return ExistingSCEV;
4059 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4061 SCEV *S = new (SCEVAllocator)
4062 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4063
4064 UniqueSCEVs.InsertNode(S, IP);
4065 S->computeAndSetCanonical(*this);
4066 registerUser(S, Ops);
4067 return S;
4068}
4069
4070namespace {
4071
4072class SCEVSequentialMinMaxDeduplicatingVisitor final
4073 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
4074 std::optional<const SCEV *>> {
4075 using RetVal = std::optional<const SCEV *>;
4077
4078 ScalarEvolution &SE;
4079 const SCEVTypes RootKind; // Must be a sequential min/max expression.
4080 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
4082
4083 bool canRecurseInto(SCEVTypes Kind) const {
4084 // We can only recurse into the SCEV expression of the same effective type
4085 // as the type of our root SCEV expression.
4086 return RootKind == Kind || NonSequentialRootKind == Kind;
4087 };
4088
4089 RetVal visitAnyMinMaxExpr(const SCEV *S) {
4091 "Only for min/max expressions.");
4092 SCEVTypes Kind = S->getSCEVType();
4093
4094 if (!canRecurseInto(Kind))
4095 return S;
4096
4097 auto *NAry = cast<SCEVNAryExpr>(S);
4098 SmallVector<SCEVUse> NewOps;
4099 bool Changed = visit(Kind, NAry->operands(), NewOps);
4100
4101 if (!Changed)
4102 return S;
4103 if (NewOps.empty())
4104 return std::nullopt;
4105
4107 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
4108 : SE.getMinMaxExpr(Kind, NewOps);
4109 }
4110
4111 RetVal visit(const SCEV *S) {
4112 // Has the whole operand been seen already?
4113 if (!SeenOps.insert(S).second)
4114 return std::nullopt;
4115 return Base::visit(S);
4116 }
4117
4118public:
4119 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
4120 SCEVTypes RootKind)
4121 : SE(SE), RootKind(RootKind),
4122 NonSequentialRootKind(
4123 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4124 RootKind)) {}
4125
4126 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<SCEVUse> OrigOps,
4127 SmallVectorImpl<SCEVUse> &NewOps) {
4128 bool Changed = false;
4130 Ops.reserve(OrigOps.size());
4131
4132 for (const SCEV *Op : OrigOps) {
4133 RetVal NewOp = visit(Op);
4134 if (NewOp != Op)
4135 Changed = true;
4136 if (NewOp)
4137 Ops.emplace_back(*NewOp);
4138 }
4139
4140 if (Changed)
4141 NewOps = std::move(Ops);
4142 return Changed;
4143 }
4144
4145 RetVal visitConstant(const SCEVConstant *Constant) { return Constant; }
4146
4147 RetVal visitVScale(const SCEVVScale *VScale) { return VScale; }
4148
4149 RetVal visitPtrToAddrExpr(const SCEVPtrToAddrExpr *Expr) { return Expr; }
4150
4151 RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
4152
4153 RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; }
4154
4155 RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; }
4156
4157 RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; }
4158
4159 RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; }
4160
4161 RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
4162
4163 RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
4164
4165 RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) {
4166 return visitAnyMinMaxExpr(Expr);
4167 }
4168
4169 RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) {
4170 return visitAnyMinMaxExpr(Expr);
4171 }
4172
4173 RetVal visitSMinExpr(const SCEVSMinExpr *Expr) {
4174 return visitAnyMinMaxExpr(Expr);
4175 }
4176
4177 RetVal visitUMinExpr(const SCEVUMinExpr *Expr) {
4178 return visitAnyMinMaxExpr(Expr);
4179 }
4180
4181 RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
4182 return visitAnyMinMaxExpr(Expr);
4183 }
4184
4185 RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; }
4186
4187 RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; }
4188};
4189
4190} // namespace
4191
4193 switch (Kind) {
4194 case scConstant:
4195 case scVScale:
4196 case scTruncate:
4197 case scZeroExtend:
4198 case scSignExtend:
4199 case scPtrToAddr:
4200 case scAddExpr:
4201 case scMulExpr:
4202 case scUDivExpr:
4203 case scAddRecExpr:
4204 case scUMaxExpr:
4205 case scSMaxExpr:
4206 case scUMinExpr:
4207 case scSMinExpr:
4208 case scUnknown:
4209 // If any operand is poison, the whole expression is poison.
4210 return true;
4212 // FIXME: if the *first* operand is poison, the whole expression is poison.
4213 return false; // Pessimistically, say that it does not propagate poison.
4214 case scCouldNotCompute:
4215 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4216 }
4217 llvm_unreachable("Unknown SCEV kind!");
4218}
4219
4220namespace {
4221// The only way poison may be introduced in a SCEV expression is from a
4222// poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4223// not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not*
4224// introduce poison -- they encode guaranteed, non-speculated knowledge.
4225//
4226// Additionally, all SCEV nodes propagate poison from inputs to outputs,
4227// with the notable exception of umin_seq, where only poison from the first
4228// operand is (unconditionally) propagated.
4229struct SCEVPoisonCollector {
4230 bool LookThroughMaybePoisonBlocking;
4231 SmallPtrSet<const SCEVUnknown *, 4> MaybePoison;
4232 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4233 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4234
4235 bool follow(const SCEV *S) {
4236 if (!LookThroughMaybePoisonBlocking &&
4238 return false;
4239
4240 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4241 if (!isGuaranteedNotToBePoison(SU->getValue()))
4242 MaybePoison.insert(SU);
4243 }
4244 return true;
4245 }
4246 bool isDone() const { return false; }
4247};
4248} // namespace
4249
4250/// Return true if V is poison given that AssumedPoison is already poison.
4251static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4252 // First collect all SCEVs that might result in AssumedPoison to be poison.
4253 // We need to look through potentially poison-blocking operations here,
4254 // because we want to find all SCEVs that *might* result in poison, not only
4255 // those that are *required* to.
4256 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4257 visitAll(AssumedPoison, PC1);
4258
4259 // AssumedPoison is never poison. As the assumption is false, the implication
4260 // is true. Don't bother walking the other SCEV in this case.
4261 if (PC1.MaybePoison.empty())
4262 return true;
4263
4264 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4265 // as well. We cannot look through potentially poison-blocking operations
4266 // here, as their arguments only *may* make the result poison.
4267 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4268 visitAll(S, PC2);
4269
4270 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4271 // it will also make S poison by being part of PC2.MaybePoison.
4272 return llvm::set_is_subset(PC1.MaybePoison, PC2.MaybePoison);
4273}
4274
4276 SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4277 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4278 visitAll(S, PC);
4279 for (const SCEVUnknown *SU : PC.MaybePoison)
4280 Result.insert(SU->getValue());
4281}
4282
4284 const SCEV *S, Instruction *I,
4285 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
4286 // If the instruction cannot be poison, it's always safe to reuse.
4288 return true;
4289
4290 // Otherwise, it is possible that I is more poisonous that S. Collect the
4291 // poison-contributors of S, and then check whether I has any additional
4292 // poison-contributors. Poison that is contributed through poison-generating
4293 // flags is handled by dropping those flags instead.
4295 getPoisonGeneratingValues(PoisonVals, S);
4296
4297 SmallVector<Value *> Worklist;
4299 Worklist.push_back(I);
4300 while (!Worklist.empty()) {
4301 Value *V = Worklist.pop_back_val();
4302 if (!Visited.insert(V).second)
4303 continue;
4304
4305 // Avoid walking large instruction graphs.
4306 if (Visited.size() > 16)
4307 return false;
4308
4309 // Either the value can't be poison, or the S would also be poison if it
4310 // is.
4311 if (PoisonVals.contains(V) || ::isGuaranteedNotToBePoison(V))
4312 continue;
4313
4314 auto *I = dyn_cast<Instruction>(V);
4315 if (!I)
4316 return false;
4317
4318 // Disjoint or instructions are interpreted as adds by SCEV. However, we
4319 // can't replace an arbitrary add with disjoint or, even if we drop the
4320 // flag. We would need to convert the or into an add.
4321 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
4322 if (PDI->isDisjoint())
4323 return false;
4324
4325 // FIXME: Ignore vscale, even though it technically could be poison. Do this
4326 // because SCEV currently assumes it can't be poison. Remove this special
4327 // case once we proper model when vscale can be poison.
4328 if (auto *II = dyn_cast<IntrinsicInst>(I);
4329 II && II->getIntrinsicID() == Intrinsic::vscale)
4330 continue;
4331
4332 if (canCreatePoison(cast<Operator>(I), /*ConsiderFlagsAndMetadata*/ false))
4333 return false;
4334
4335 // If the instruction can't create poison, we can recurse to its operands.
4336 if (I->hasPoisonGeneratingAnnotations())
4337 DropPoisonGeneratingInsts.push_back(I);
4338
4339 llvm::append_range(Worklist, I->operands());
4340 }
4341 return true;
4342}
4343
4344const SCEV *
4347 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4348 "Not a SCEVSequentialMinMaxExpr!");
4349 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4350 if (Ops.size() == 1)
4351 return Ops[0];
4352#ifndef NDEBUG
4353 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4354 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4355 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4356 "Operand types don't match!");
4357 assert(Ops[0]->getType()->isPointerTy() ==
4358 Ops[i]->getType()->isPointerTy() &&
4359 "min/max should be consistently pointerish");
4360 }
4361#endif
4362
4363 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4364 // so we can *NOT* do any kind of sorting of the expressions!
4365
4366 // Check if we have created the same expression before.
4367 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4368 return S;
4369
4370 // FIXME: there are *some* simplifications that we can do here.
4371
4372 // Keep only the first instance of an operand.
4373 {
4374 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4375 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4376 if (Changed)
4377 return getSequentialMinMaxExpr(Kind, Ops);
4378 }
4379
4380 // Check to see if one of the operands is of the same kind. If so, expand its
4381 // operands onto our operand list, and recurse to simplify.
4382 {
4383 unsigned Idx = 0;
4384 bool DeletedAny = false;
4385 while (Idx < Ops.size()) {
4386 if (Ops[Idx]->getSCEVType() != Kind) {
4387 ++Idx;
4388 continue;
4389 }
4390 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4391 Ops.erase(Ops.begin() + Idx);
4392 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4393 SMME->operands().end());
4394 DeletedAny = true;
4395 }
4396
4397 if (DeletedAny)
4398 return getSequentialMinMaxExpr(Kind, Ops);
4399 }
4400
4401 const SCEV *SaturationPoint;
4403 switch (Kind) {
4405 SaturationPoint = getZero(Ops[0]->getType());
4406 Pred = ICmpInst::ICMP_ULE;
4407 break;
4408 default:
4409 llvm_unreachable("Not a sequential min/max type.");
4410 }
4411
4412 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4413 if (!isGuaranteedNotToCauseUB(Ops[i]))
4414 continue;
4415 // We can replace %x umin_seq %y with %x umin %y if either:
4416 // * %y being poison implies %x is also poison.
4417 // * %x cannot be the saturating value (e.g. zero for umin).
4418 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4419 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4420 SaturationPoint)) {
4421 SmallVector<SCEVUse, 2> SeqOps = {Ops[i - 1], Ops[i]};
4422 Ops[i - 1] = getMinMaxExpr(
4424 SeqOps);
4425 Ops.erase(Ops.begin() + i);
4426 return getSequentialMinMaxExpr(Kind, Ops);
4427 }
4428 // Fold %x umin_seq %y to %x if %x ule %y.
4429 // TODO: We might be able to prove the predicate for a later operand.
4430 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4431 Ops.erase(Ops.begin() + i);
4432 return getSequentialMinMaxExpr(Kind, Ops);
4433 }
4434 }
4435
4436 // Okay, it looks like we really DO need an expr. Check to see if we
4437 // already have one, otherwise create a new one.
4439 ID.AddInteger(Kind);
4440 for (const SCEV *Op : Ops)
4441 ID.AddPointer(Op);
4442 void *IP = nullptr;
4443 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4444 if (ExistingSCEV)
4445 return ExistingSCEV;
4446
4447 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4449 SCEV *S = new (SCEVAllocator)
4450 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4451
4452 UniqueSCEVs.InsertNode(S, IP);
4453 S->computeAndSetCanonical(*this);
4454 registerUser(S, Ops);
4455 return S;
4456}
4457
4462
4466
4471
4475
4480
4484
4486 bool Sequential) {
4487 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4488 return getUMinExpr(Ops, Sequential);
4489}
4490
4496
4497const SCEV *
4499 const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4500 if (Size.isScalable())
4501 Res = getMulExpr(Res, getVScale(IntTy));
4502 return Res;
4503}
4504
4506 return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4507}
4508
4510 return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4511}
4512
4514 StructType *STy,
4515 unsigned FieldNo) {
4516 // We can bypass creating a target-independent constant expression and then
4517 // folding it back into a ConstantInt. This is just a compile-time
4518 // optimization.
4519 const StructLayout *SL = getDataLayout().getStructLayout(STy);
4520 assert(!SL->getSizeInBits().isScalable() &&
4521 "Cannot get offset for structure containing scalable vector types");
4522 return getConstant(IntTy, SL->getElementOffset(FieldNo));
4523}
4524
4526 // Don't attempt to do anything other than create a SCEVUnknown object
4527 // here. createSCEV only calls getUnknown after checking for all other
4528 // interesting possibilities, and any other code that calls getUnknown
4529 // is doing so in order to hide a value from SCEV canonicalization.
4530
4533 ID.AddPointer(V);
4534 void *IP = nullptr;
4535 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
4536 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4537 "Stale SCEVUnknown in uniquing map!");
4538 return S;
4539 }
4540 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4541 FirstUnknown);
4542 FirstUnknown = cast<SCEVUnknown>(S);
4543 UniqueSCEVs.InsertNode(S, IP);
4544 S->computeAndSetCanonical(*this);
4545 return S;
4546}
4547
4548//===----------------------------------------------------------------------===//
4549// Basic SCEV Analysis and PHI Idiom Recognition Code
4550//
4551
4552/// Test if values of the given type are analyzable within the SCEV
4553/// framework. This primarily includes integer types, and it can optionally
4554/// include pointer types if the ScalarEvolution class has access to
4555/// target-specific information.
4557 // Integers and pointers are always SCEVable.
4558 return Ty->isIntOrPtrTy();
4559}
4560
4561/// Return the size in bits of the specified type, for which isSCEVable must
4562/// return true.
4564 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4565 if (Ty->isPointerTy())
4567 return getDataLayout().getTypeSizeInBits(Ty);
4568}
4569
4570/// Return a type with the same bitwidth as the given type and which represents
4571/// how SCEV will treat the given type, for which isSCEVable must return
4572/// true. For pointer types, this is the pointer index sized integer type.
4574 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4575
4576 if (Ty->isIntegerTy())
4577 return Ty;
4578
4579 // The only other support type is pointer.
4580 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4581 return getDataLayout().getIndexType(Ty);
4582}
4583
4585 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4586}
4587
4589 const SCEV *B) {
4590 /// For a valid use point to exist, the defining scope of one operand
4591 /// must dominate the other.
4592 bool PreciseA, PreciseB;
4593 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4594 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4595 if (!PreciseA || !PreciseB)
4596 // Can't tell.
4597 return false;
4598 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4599 DT.dominates(ScopeB, ScopeA);
4600}
4601
4603 return CouldNotCompute.get();
4604}
4605
4606bool ScalarEvolution::checkValidity(const SCEV *S) const {
4607 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4608 auto *SU = dyn_cast<SCEVUnknown>(S);
4609 return SU && SU->getValue() == nullptr;
4610 });
4611
4612 return !ContainsNulls;
4613}
4614
4616 HasRecMapType::iterator I = HasRecMap.find(S);
4617 if (I != HasRecMap.end())
4618 return I->second;
4619
4620 bool FoundAddRec =
4621 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4622 HasRecMap.insert({S, FoundAddRec});
4623 return FoundAddRec;
4624}
4625
4626/// Return the ValueOffsetPair set for \p S. \p S can be represented
4627/// by the value and offset from any ValueOffsetPair in the set.
4628ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4629 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4630 if (SI == ExprValueMap.end())
4631 return {};
4632 return SI->second.getArrayRef();
4633}
4634
4635/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4636/// cannot be used separately. eraseValueFromMap should be used to remove
4637/// V from ValueExprMap and ExprValueMap at the same time.
4638void ScalarEvolution::eraseValueFromMap(Value *V) {
4639 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4640 if (I != ValueExprMap.end()) {
4641 auto EVIt = ExprValueMap.find(I->second);
4642 bool Removed = EVIt->second.remove(V);
4643 (void) Removed;
4644 assert(Removed && "Value not in ExprValueMap?");
4645 ValueExprMap.erase(I);
4646 }
4647}
4648
4649void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4650 // A recursive query may have already computed the SCEV. It should be
4651 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4652 // inferred nowrap flags.
4653 auto It = ValueExprMap.find_as(V);
4654 if (It == ValueExprMap.end()) {
4655 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4656 ExprValueMap[S].insert(V);
4657 }
4658}
4659
4660/// Return an existing SCEV if it exists, otherwise analyze the expression and
4661/// create a new one.
4663 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4664
4665 if (const SCEV *S = getExistingSCEV(V))
4666 return S;
4667 return createSCEVIter(V);
4668}
4669
4671 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4672
4673 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4674 if (I != ValueExprMap.end()) {
4675 const SCEV *S = I->second;
4676 assert(checkValidity(S) &&
4677 "existing SCEV has not been properly invalidated");
4678 return S;
4679 }
4680 return nullptr;
4681}
4682
4683/// Return a SCEV corresponding to -V = -1*V
4685 SCEV::NoWrapFlags Flags) {
4686 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4687 return getConstant(
4688 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4689
4690 Type *Ty = V->getType();
4691 Ty = getEffectiveSCEVType(Ty);
4692 return getMulExpr(V, getMinusOne(Ty), Flags);
4693}
4694
4695/// If Expr computes ~A, return A else return nullptr
4696static const SCEV *MatchNotExpr(const SCEV *Expr) {
4697 const SCEV *MulOp;
4698 if (match(Expr, m_scev_Add(m_scev_AllOnes(),
4699 m_scev_Mul(m_scev_AllOnes(), m_SCEV(MulOp)))))
4700 return MulOp;
4701 return nullptr;
4702}
4703
4704/// Return a SCEV corresponding to ~V = -1-V
4706 assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4707
4708 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4709 return getConstant(
4710 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4711
4712 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4713 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4714 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4715 SmallVector<SCEVUse, 2> MatchedOperands;
4716 for (const SCEV *Operand : MME->operands()) {
4717 const SCEV *Matched = MatchNotExpr(Operand);
4718 if (!Matched)
4719 return (const SCEV *)nullptr;
4720 MatchedOperands.push_back(Matched);
4721 }
4722 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4723 MatchedOperands);
4724 };
4725 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4726 return Replaced;
4727 }
4728
4729 Type *Ty = V->getType();
4730 Ty = getEffectiveSCEVType(Ty);
4731 return getMinusSCEV(getMinusOne(Ty), V);
4732}
4733
4735 assert(P->getType()->isPointerTy());
4736
4737 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4738 // The base of an AddRec is the first operand.
4739 SmallVector<SCEVUse> Ops{AddRec->operands()};
4740 Ops[0] = removePointerBase(Ops[0]);
4741 // Don't try to transfer nowrap flags for now. We could in some cases
4742 // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4743 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
4744 }
4745 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4746 // The base of an Add is the pointer operand.
4747 SmallVector<SCEVUse> Ops{Add->operands()};
4748 SCEVUse *PtrOp = nullptr;
4749 for (SCEVUse &AddOp : Ops) {
4750 if (AddOp->getType()->isPointerTy()) {
4751 assert(!PtrOp && "Cannot have multiple pointer ops");
4752 PtrOp = &AddOp;
4753 }
4754 }
4755 *PtrOp = removePointerBase(*PtrOp);
4756 // Don't try to transfer nowrap flags for now. We could in some cases
4757 // (for example, if the pointer operand of the Add is a SCEVUnknown).
4758 return getAddExpr(Ops);
4759 }
4760 // Any other expression must be a pointer base.
4761 return getZero(P->getType());
4762}
4763
4765 SCEV::NoWrapFlags Flags,
4766 unsigned Depth) {
4767 // Fast path: X - X --> 0.
4768 if (LHS == RHS)
4769 return getZero(LHS->getType());
4770
4771 // If we subtract two pointers with different pointer bases, bail.
4772 // Eventually, we're going to add an assertion to getMulExpr that we
4773 // can't multiply by a pointer.
4774 if (RHS->getType()->isPointerTy()) {
4775 if (!LHS->getType()->isPointerTy() ||
4776 getPointerBase(LHS) != getPointerBase(RHS))
4777 return getCouldNotCompute();
4778 LHS = removePointerBase(LHS);
4779 RHS = removePointerBase(RHS);
4780 }
4781
4782 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4783 // makes it so that we cannot make much use of NUW.
4784 auto AddFlags = SCEV::FlagAnyWrap;
4785 const bool RHSIsNotMinSigned =
4787 if (hasFlags(Flags, SCEV::FlagNSW)) {
4788 // Let M be the minimum representable signed value. Then (-1)*RHS
4789 // signed-wraps if and only if RHS is M. That can happen even for
4790 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4791 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4792 // (-1)*RHS, we need to prove that RHS != M.
4793 //
4794 // If LHS is non-negative and we know that LHS - RHS does not
4795 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4796 // either by proving that RHS > M or that LHS >= 0.
4797 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4798 AddFlags = SCEV::FlagNSW;
4799 }
4800 }
4801
4802 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4803 // RHS is NSW and LHS >= 0.
4804 //
4805 // The difficulty here is that the NSW flag may have been proven
4806 // relative to a loop that is to be found in a recurrence in LHS and
4807 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4808 // larger scope than intended.
4809 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4810
4811 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4812}
4813
4815 unsigned Depth) {
4816 Type *SrcTy = V->getType();
4817 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4818 "Cannot truncate or zero extend with non-integer arguments!");
4819 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4820 return V; // No conversion
4821 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4822 return getTruncateExpr(V, Ty, Depth);
4823 return getZeroExtendExpr(V, Ty, Depth);
4824}
4825
4827 unsigned Depth) {
4828 Type *SrcTy = V->getType();
4829 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4830 "Cannot truncate or zero extend with non-integer arguments!");
4831 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4832 return V; // No conversion
4833 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4834 return getTruncateExpr(V, Ty, Depth);
4835 return getSignExtendExpr(V, Ty, Depth);
4836}
4837
4838const SCEV *
4840 Type *SrcTy = V->getType();
4841 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4842 "Cannot noop or zero extend with non-integer arguments!");
4844 "getNoopOrZeroExtend cannot truncate!");
4845 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4846 return V; // No conversion
4847 return getZeroExtendExpr(V, Ty);
4848}
4849
4850const SCEV *
4852 Type *SrcTy = V->getType();
4853 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4854 "Cannot noop or sign extend with non-integer arguments!");
4856 "getNoopOrSignExtend cannot truncate!");
4857 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4858 return V; // No conversion
4859 return getSignExtendExpr(V, Ty);
4860}
4861
4862const SCEV *
4864 Type *SrcTy = V->getType();
4865 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4866 "Cannot noop or any extend with non-integer arguments!");
4868 "getNoopOrAnyExtend cannot truncate!");
4869 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4870 return V; // No conversion
4871 return getAnyExtendExpr(V, Ty);
4872}
4873
4874const SCEV *
4876 Type *SrcTy = V->getType();
4877 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4878 "Cannot truncate or noop with non-integer arguments!");
4880 "getTruncateOrNoop cannot extend!");
4881 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4882 return V; // No conversion
4883 return getTruncateExpr(V, Ty);
4884}
4885
4887 const SCEV *RHS) {
4888 const SCEV *PromotedLHS = LHS;
4889 const SCEV *PromotedRHS = RHS;
4890
4891 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4892 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4893 else
4894 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4895
4896 return getUMaxExpr(PromotedLHS, PromotedRHS);
4897}
4898
4900 const SCEV *RHS,
4901 bool Sequential) {
4902 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4903 return getUMinFromMismatchedTypes(Ops, Sequential);
4904}
4905
4906const SCEV *
4908 bool Sequential) {
4909 assert(!Ops.empty() && "At least one operand must be!");
4910 // Trivial case.
4911 if (Ops.size() == 1)
4912 return Ops[0];
4913
4914 // Find the max type first.
4915 Type *MaxType = nullptr;
4916 for (SCEVUse S : Ops)
4917 if (MaxType)
4918 MaxType = getWiderType(MaxType, S->getType());
4919 else
4920 MaxType = S->getType();
4921 assert(MaxType && "Failed to find maximum type!");
4922
4923 // Extend all ops to max type.
4924 SmallVector<SCEVUse, 2> PromotedOps;
4925 for (SCEVUse S : Ops)
4926 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4927
4928 // Generate umin.
4929 return getUMinExpr(PromotedOps, Sequential);
4930}
4931
4933 // A pointer operand may evaluate to a nonpointer expression, such as null.
4934 if (!V->getType()->isPointerTy())
4935 return V;
4936
4937 while (true) {
4938 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4939 V = AddRec->getStart();
4940 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4941 const SCEV *PtrOp = nullptr;
4942 for (const SCEV *AddOp : Add->operands()) {
4943 if (AddOp->getType()->isPointerTy()) {
4944 assert(!PtrOp && "Cannot have multiple pointer ops");
4945 PtrOp = AddOp;
4946 }
4947 }
4948 assert(PtrOp && "Must have pointer op");
4949 V = PtrOp;
4950 } else // Not something we can look further into.
4951 return V;
4952 }
4953}
4954
4955/// Push users of the given Instruction onto the given Worklist.
4959 // Push the def-use children onto the Worklist stack.
4960 for (User *U : I->users()) {
4961 auto *UserInsn = cast<Instruction>(U);
4962 if (Visited.insert(UserInsn).second)
4963 Worklist.push_back(UserInsn);
4964 }
4965}
4966
4967namespace {
4968
4969/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4970/// expression in case its Loop is L. If it is not L then
4971/// if IgnoreOtherLoops is true then use AddRec itself
4972/// otherwise rewrite cannot be done.
4973/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4974class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4975public:
4976 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4977 bool IgnoreOtherLoops = true) {
4978 SCEVInitRewriter Rewriter(L, SE);
4979 const SCEV *Result = Rewriter.visit(S);
4980 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4981 return SE.getCouldNotCompute();
4982 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4983 ? SE.getCouldNotCompute()
4984 : Result;
4985 }
4986
4987 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4988 if (!SE.isLoopInvariant(Expr, L))
4989 SeenLoopVariantSCEVUnknown = true;
4990 return Expr;
4991 }
4992
4993 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4994 // Only re-write AddRecExprs for this loop.
4995 if (Expr->getLoop() == L)
4996 return Expr->getStart();
4997 SeenOtherLoops = true;
4998 return Expr;
4999 }
5000
5001 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
5002
5003 bool hasSeenOtherLoops() { return SeenOtherLoops; }
5004
5005private:
5006 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
5007 : SCEVRewriteVisitor(SE), L(L) {}
5008
5009 const Loop *L;
5010 bool SeenLoopVariantSCEVUnknown = false;
5011 bool SeenOtherLoops = false;
5012};
5013
5014/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
5015/// increment expression in case its Loop is L. If it is not L then
5016/// use AddRec itself.
5017/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
5018class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
5019public:
5020 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
5021 SCEVPostIncRewriter Rewriter(L, SE);
5022 const SCEV *Result = Rewriter.visit(S);
5023 return Rewriter.hasSeenLoopVariantSCEVUnknown()
5024 ? SE.getCouldNotCompute()
5025 : Result;
5026 }
5027
5028 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5029 if (!SE.isLoopInvariant(Expr, L))
5030 SeenLoopVariantSCEVUnknown = true;
5031 return Expr;
5032 }
5033
5034 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5035 // Only re-write AddRecExprs for this loop.
5036 if (Expr->getLoop() == L)
5037 return Expr->getPostIncExpr(SE);
5038 SeenOtherLoops = true;
5039 return Expr;
5040 }
5041
5042 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
5043
5044 bool hasSeenOtherLoops() { return SeenOtherLoops; }
5045
5046private:
5047 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
5048 : SCEVRewriteVisitor(SE), L(L) {}
5049
5050 const Loop *L;
5051 bool SeenLoopVariantSCEVUnknown = false;
5052 bool SeenOtherLoops = false;
5053};
5054
5055/// This class evaluates the compare condition by matching it against the
5056/// condition of loop latch. If there is a match we assume a true value
5057/// for the condition while building SCEV nodes.
5058class SCEVBackedgeConditionFolder
5059 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
5060public:
5061 static const SCEV *rewrite(const SCEV *S, const Loop *L,
5062 ScalarEvolution &SE) {
5063 bool IsPosBECond = false;
5064 Value *BECond = nullptr;
5065 if (BasicBlock *Latch = L->getLoopLatch()) {
5066 if (CondBrInst *BI = dyn_cast<CondBrInst>(Latch->getTerminator())) {
5067 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
5068 "Both outgoing branches should not target same header!");
5069 BECond = BI->getCondition();
5070 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
5071 } else {
5072 return S;
5073 }
5074 }
5075 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
5076 return Rewriter.visit(S);
5077 }
5078
5079 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5080 const SCEV *Result = Expr;
5081 bool InvariantF = SE.isLoopInvariant(Expr, L);
5082
5083 if (!InvariantF) {
5085 switch (I->getOpcode()) {
5086 case Instruction::Select: {
5087 SelectInst *SI = cast<SelectInst>(I);
5088 std::optional<const SCEV *> Res =
5089 compareWithBackedgeCondition(SI->getCondition());
5090 if (Res) {
5091 bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
5092 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
5093 }
5094 break;
5095 }
5096 default: {
5097 std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
5098 if (Res)
5099 Result = *Res;
5100 break;
5101 }
5102 }
5103 }
5104 return Result;
5105 }
5106
5107private:
5108 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
5109 bool IsPosBECond, ScalarEvolution &SE)
5110 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
5111 IsPositiveBECond(IsPosBECond) {}
5112
5113 std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
5114
5115 const Loop *L;
5116 /// Loop back condition.
5117 Value *BackedgeCond = nullptr;
5118 /// Set to true if loop back is on positive branch condition.
5119 bool IsPositiveBECond;
5120};
5121
5122std::optional<const SCEV *>
5123SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
5124
5125 // If value matches the backedge condition for loop latch,
5126 // then return a constant evolution node based on loopback
5127 // branch taken.
5128 if (BackedgeCond == IC)
5129 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
5131 return std::nullopt;
5132}
5133
5134class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
5135public:
5136 static const SCEV *rewrite(const SCEV *S, const Loop *L,
5137 ScalarEvolution &SE) {
5138 SCEVShiftRewriter Rewriter(L, SE);
5139 const SCEV *Result = Rewriter.visit(S);
5140 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
5141 }
5142
5143 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5144 // Only allow AddRecExprs for this loop.
5145 if (!SE.isLoopInvariant(Expr, L))
5146 Valid = false;
5147 return Expr;
5148 }
5149
5150 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5151 if (Expr->getLoop() == L && Expr->isAffine())
5152 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
5153 Valid = false;
5154 return Expr;
5155 }
5156
5157 bool isValid() { return Valid; }
5158
5159private:
5160 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
5161 : SCEVRewriteVisitor(SE), L(L) {}
5162
5163 const Loop *L;
5164 bool Valid = true;
5165};
5166
5167} // end anonymous namespace
5168
5169void ScalarEvolution::inferNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
5170 if (!AR->isAffine())
5171 return;
5172
5173 // Force computation of ranges, which will also perform range-based flag
5174 // inference.
5175 if (!AR->hasNoSignedWrap())
5176 (void)getSignedRange(AR);
5177
5178 if (!AR->hasNoUnsignedWrap())
5179 (void)getUnsignedRange(AR);
5180
5181 if (!AR->hasNoSelfWrap()) {
5182 const SCEV *BECount = getConstantMaxBackedgeTakenCount(AR->getLoop());
5183 if (const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(BECount)) {
5184 ConstantRange StepCR = getSignedRange(AR->getStepRecurrence(*this));
5185 const APInt &BECountAP = BECountMax->getAPInt();
5186 unsigned NoOverflowBitWidth =
5187 BECountAP.getActiveBits() + StepCR.getMinSignedBits();
5188 if (NoOverflowBitWidth <= getTypeSizeInBits(AR->getType()))
5189 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
5190 }
5191 }
5192}
5193
5195ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5197
5198 if (AR->hasNoSignedWrap())
5199 return Result;
5200
5201 if (!AR->isAffine())
5202 return Result;
5203
5204 // This function can be expensive, only try to prove NSW once per AddRec.
5205 if (!SignedWrapViaInductionTried.insert(AR).second)
5206 return Result;
5207
5208 const SCEV *Step = AR->getStepRecurrence(*this);
5209 const Loop *L = AR->getLoop();
5210
5211 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5212 // Note that this serves two purposes: It filters out loops that are
5213 // simply not analyzable, and it covers the case where this code is
5214 // being called from within backedge-taken count analysis, such that
5215 // attempting to ask for the backedge-taken count would likely result
5216 // in infinite recursion. In the later case, the analysis code will
5217 // cope with a conservative value, and it will take care to purge
5218 // that value once it has finished.
5219 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5220
5221 // Normally, in the cases we can prove no-overflow via a
5222 // backedge guarding condition, we can also compute a backedge
5223 // taken count for the loop. The exceptions are assumptions and
5224 // guards present in the loop -- SCEV is not great at exploiting
5225 // these to compute max backedge taken counts, but can still use
5226 // these to prove lack of overflow. Use this fact to avoid
5227 // doing extra work that may not pay off.
5228
5229 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5230 AC.assumptions().empty())
5231 return Result;
5232
5233 // If the backedge is guarded by a comparison with the pre-inc value the
5234 // addrec is safe. Also, if the entry is guarded by a comparison with the
5235 // start value and the backedge is guarded by a comparison with the post-inc
5236 // value, the addrec is safe.
5238 const SCEV *OverflowLimit =
5239 getSignedOverflowLimitForStep(Step, &Pred, this);
5240 if (OverflowLimit &&
5241 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5242 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
5243 Result = setFlags(Result, SCEV::FlagNSW);
5244 }
5245 return Result;
5246}
5248ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5250
5251 if (AR->hasNoUnsignedWrap())
5252 return Result;
5253
5254 if (!AR->isAffine())
5255 return Result;
5256
5257 // This function can be expensive, only try to prove NUW once per AddRec.
5258 if (!UnsignedWrapViaInductionTried.insert(AR).second)
5259 return Result;
5260
5261 const SCEV *Step = AR->getStepRecurrence(*this);
5262 unsigned BitWidth = getTypeSizeInBits(AR->getType());
5263 const Loop *L = AR->getLoop();
5264
5265 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5266 // Note that this serves two purposes: It filters out loops that are
5267 // simply not analyzable, and it covers the case where this code is
5268 // being called from within backedge-taken count analysis, such that
5269 // attempting to ask for the backedge-taken count would likely result
5270 // in infinite recursion. In the later case, the analysis code will
5271 // cope with a conservative value, and it will take care to purge
5272 // that value once it has finished.
5273 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5274
5275 // Normally, in the cases we can prove no-overflow via a
5276 // backedge guarding condition, we can also compute a backedge
5277 // taken count for the loop. The exceptions are assumptions and
5278 // guards present in the loop -- SCEV is not great at exploiting
5279 // these to compute max backedge taken counts, but can still use
5280 // these to prove lack of overflow. Use this fact to avoid
5281 // doing extra work that may not pay off.
5282
5283 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5284 AC.assumptions().empty())
5285 return Result;
5286
5287 // If the backedge is guarded by a comparison with the pre-inc value the
5288 // addrec is safe. Also, if the entry is guarded by a comparison with the
5289 // start value and the backedge is guarded by a comparison with the post-inc
5290 // value, the addrec is safe.
5291 if (isKnownPositive(Step)) {
5292 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
5293 getUnsignedRangeMax(Step));
5296 Result = setFlags(Result, SCEV::FlagNUW);
5297 }
5298 }
5299
5300 return Result;
5301}
5302
5303namespace {
5304
5305/// Represents an abstract binary operation. This may exist as a
5306/// normal instruction or constant expression, or may have been
5307/// derived from an expression tree.
5308struct BinaryOp {
5309 unsigned Opcode;
5310 Value *LHS;
5311 Value *RHS;
5312 bool IsNSW = false;
5313 bool IsNUW = false;
5314
5315 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5316 /// constant expression.
5317 Operator *Op = nullptr;
5318
5319 explicit BinaryOp(Operator *Op)
5320 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5321 Op(Op) {
5322 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5323 IsNSW = OBO->hasNoSignedWrap();
5324 IsNUW = OBO->hasNoUnsignedWrap();
5325 }
5326 }
5327
5328 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5329 bool IsNUW = false)
5330 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5331};
5332
5333} // end anonymous namespace
5334
5335/// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
5336static std::optional<BinaryOp> MatchBinaryOp(Value *V, const DataLayout &DL,
5337 AssumptionCache &AC,
5338 const DominatorTree &DT,
5339 const Instruction *CxtI) {
5340 auto *Op = dyn_cast<Operator>(V);
5341 if (!Op)
5342 return std::nullopt;
5343
5344 // Implementation detail: all the cleverness here should happen without
5345 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5346 // SCEV expressions when possible, and we should not break that.
5347
5348 switch (Op->getOpcode()) {
5349 case Instruction::Add:
5350 case Instruction::Sub:
5351 case Instruction::Mul:
5352 case Instruction::UDiv:
5353 case Instruction::URem:
5354 case Instruction::And:
5355 case Instruction::AShr:
5356 case Instruction::Shl:
5357 return BinaryOp(Op);
5358
5359 case Instruction::Or: {
5360 // Convert or disjoint into add nuw nsw.
5361 if (cast<PossiblyDisjointInst>(Op)->isDisjoint()) {
5362 BinaryOp BinOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
5363 /*IsNSW=*/true, /*IsNUW=*/true);
5364 // Keep the reference to the original instruction so that we can later
5365 // check whether it can produce poison value or not.
5366 BinOp.Op = Op;
5367 return BinOp;
5368 }
5369 return BinaryOp(Op);
5370 }
5371
5372 case Instruction::Xor:
5373 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5374 // If the RHS of the xor is a signmask, then this is just an add.
5375 // Instcombine turns add of signmask into xor as a strength reduction step.
5376 if (RHSC->getValue().isSignMask())
5377 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5378 // Binary `xor` is a bit-wise `add`.
5379 if (V->getType()->isIntegerTy(1))
5380 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5381 return BinaryOp(Op);
5382
5383 case Instruction::LShr:
5384 // Turn logical shift right of a constant into a unsigned divide.
5385 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5386 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5387
5388 // If the shift count is not less than the bitwidth, the result of
5389 // the shift is undefined. Don't try to analyze it, because the
5390 // resolution chosen here may differ from the resolution chosen in
5391 // other parts of the compiler.
5392 if (SA->getValue().ult(BitWidth)) {
5393 Constant *X =
5394 ConstantInt::get(SA->getContext(),
5395 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5396 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5397 }
5398 }
5399 return BinaryOp(Op);
5400
5401 case Instruction::ExtractValue: {
5402 auto *EVI = cast<ExtractValueInst>(Op);
5403 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5404 break;
5405
5406 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5407 if (!WO)
5408 break;
5409
5410 Instruction::BinaryOps BinOp = WO->getBinaryOp();
5411 bool Signed = WO->isSigned();
5412 // TODO: Should add nuw/nsw flags for mul as well.
5413 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5414 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5415
5416 // Now that we know that all uses of the arithmetic-result component of
5417 // CI are guarded by the overflow check, we can go ahead and pretend
5418 // that the arithmetic is non-overflowing.
5419 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5420 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5421 }
5422
5423 default:
5424 break;
5425 }
5426
5427 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5428 // semantics as a Sub, return a binary sub expression.
5429 if (auto *II = dyn_cast<IntrinsicInst>(V))
5430 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5431 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5432
5433 return std::nullopt;
5434}
5435
5436/// Helper function to createAddRecFromPHIWithCasts. We have a phi
5437/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5438/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5439/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5440/// follows one of the following patterns:
5441/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5442/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5443/// If the SCEV expression of \p Op conforms with one of the expected patterns
5444/// we return the type of the truncation operation, and indicate whether the
5445/// truncated type should be treated as signed/unsigned by setting
5446/// \p Signed to true/false, respectively.
5447static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5448 bool &Signed, ScalarEvolution &SE) {
5449 // The case where Op == SymbolicPHI (that is, with no type conversions on
5450 // the way) is handled by the regular add recurrence creating logic and
5451 // would have already been triggered in createAddRecForPHI. Reaching it here
5452 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5453 // because one of the other operands of the SCEVAddExpr updating this PHI is
5454 // not invariant).
5455 //
5456 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5457 // this case predicates that allow us to prove that Op == SymbolicPHI will
5458 // be added.
5459 if (Op == SymbolicPHI)
5460 return nullptr;
5461
5462 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5463 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5464 if (SourceBits != NewBits)
5465 return nullptr;
5466
5467 if (match(Op, m_scev_SExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5468 Signed = true;
5469 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5470 }
5471 if (match(Op, m_scev_ZExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5472 Signed = false;
5473 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5474 }
5475 return nullptr;
5476}
5477
5478static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5479 if (!PN->getType()->isIntegerTy())
5480 return nullptr;
5481 const Loop *L = LI.getLoopFor(PN->getParent());
5482 if (!L || L->getHeader() != PN->getParent())
5483 return nullptr;
5484 return L;
5485}
5486
5487// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5488// computation that updates the phi follows the following pattern:
5489// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5490// which correspond to a phi->trunc->sext/zext->add->phi update chain.
5491// If so, try to see if it can be rewritten as an AddRecExpr under some
5492// Predicates. If successful, return them as a pair. Also cache the results
5493// of the analysis.
5494//
5495// Example usage scenario:
5496// Say the Rewriter is called for the following SCEV:
5497// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5498// where:
5499// %X = phi i64 (%Start, %BEValue)
5500// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5501// and call this function with %SymbolicPHI = %X.
5502//
5503// The analysis will find that the value coming around the backedge has
5504// the following SCEV:
5505// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5506// Upon concluding that this matches the desired pattern, the function
5507// will return the pair {NewAddRec, SmallPredsVec} where:
5508// NewAddRec = {%Start,+,%Step}
5509// SmallPredsVec = {P1, P2, P3} as follows:
5510// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5511// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5512// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5513// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5514// under the predicates {P1,P2,P3}.
5515// This predicated rewrite will be cached in PredicatedSCEVRewrites:
5516// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5517//
5518// TODO's:
5519//
5520// 1) Extend the Induction descriptor to also support inductions that involve
5521// casts: When needed (namely, when we are called in the context of the
5522// vectorizer induction analysis), a Set of cast instructions will be
5523// populated by this method, and provided back to isInductionPHI. This is
5524// needed to allow the vectorizer to properly record them to be ignored by
5525// the cost model and to avoid vectorizing them (otherwise these casts,
5526// which are redundant under the runtime overflow checks, will be
5527// vectorized, which can be costly).
5528//
5529// 2) Support additional induction/PHISCEV patterns: We also want to support
5530// inductions where the sext-trunc / zext-trunc operations (partly) occur
5531// after the induction update operation (the induction increment):
5532//
5533// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5534// which correspond to a phi->add->trunc->sext/zext->phi update chain.
5535//
5536// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5537// which correspond to a phi->trunc->add->sext/zext->phi update chain.
5538//
5539// 3) Outline common code with createAddRecFromPHI to avoid duplication.
5540std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5541ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5543
5544 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5545 // return an AddRec expression under some predicate.
5546
5547 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5548 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5549 assert(L && "Expecting an integer loop header phi");
5550
5551 // The loop may have multiple entrances or multiple exits; we can analyze
5552 // this phi as an addrec if it has a unique entry value and a unique
5553 // backedge value.
5554 Value *BEValueV = nullptr, *StartValueV = nullptr;
5555 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5556 Value *V = PN->getIncomingValue(i);
5557 if (L->contains(PN->getIncomingBlock(i))) {
5558 if (!BEValueV) {
5559 BEValueV = V;
5560 } else if (BEValueV != V) {
5561 BEValueV = nullptr;
5562 break;
5563 }
5564 } else if (!StartValueV) {
5565 StartValueV = V;
5566 } else if (StartValueV != V) {
5567 StartValueV = nullptr;
5568 break;
5569 }
5570 }
5571 if (!BEValueV || !StartValueV)
5572 return std::nullopt;
5573
5574 const SCEV *BEValue = getSCEV(BEValueV);
5575
5576 // If the value coming around the backedge is an add with the symbolic
5577 // value we just inserted, possibly with casts that we can ignore under
5578 // an appropriate runtime guard, then we found a simple induction variable!
5579 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5580 if (!Add)
5581 return std::nullopt;
5582
5583 // If there is a single occurrence of the symbolic value, possibly
5584 // casted, replace it with a recurrence.
5585 unsigned FoundIndex = Add->getNumOperands();
5586 Type *TruncTy = nullptr;
5587 bool Signed;
5588 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5589 if ((TruncTy =
5590 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5591 if (FoundIndex == e) {
5592 FoundIndex = i;
5593 break;
5594 }
5595
5596 if (FoundIndex == Add->getNumOperands())
5597 return std::nullopt;
5598
5599 // Create an add with everything but the specified operand.
5601 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5602 if (i != FoundIndex)
5603 Ops.push_back(Add->getOperand(i));
5604 const SCEV *Accum = getAddExpr(Ops);
5605
5606 // The runtime checks will not be valid if the step amount is
5607 // varying inside the loop.
5608 if (!isLoopInvariant(Accum, L))
5609 return std::nullopt;
5610
5611 // *** Part2: Create the predicates
5612
5613 // Analysis was successful: we have a phi-with-cast pattern for which we
5614 // can return an AddRec expression under the following predicates:
5615 //
5616 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5617 // fits within the truncated type (does not overflow) for i = 0 to n-1.
5618 // P2: An Equal predicate that guarantees that
5619 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5620 // P3: An Equal predicate that guarantees that
5621 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5622 //
5623 // As we next prove, the above predicates guarantee that:
5624 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5625 //
5626 //
5627 // More formally, we want to prove that:
5628 // Expr(i+1) = Start + (i+1) * Accum
5629 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5630 //
5631 // Given that:
5632 // 1) Expr(0) = Start
5633 // 2) Expr(1) = Start + Accum
5634 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5635 // 3) Induction hypothesis (step i):
5636 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5637 //
5638 // Proof:
5639 // Expr(i+1) =
5640 // = Start + (i+1)*Accum
5641 // = (Start + i*Accum) + Accum
5642 // = Expr(i) + Accum
5643 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5644 // :: from step i
5645 //
5646 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5647 //
5648 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5649 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
5650 // + Accum :: from P3
5651 //
5652 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5653 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5654 //
5655 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5656 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5657 //
5658 // By induction, the same applies to all iterations 1<=i<n:
5659 //
5660
5661 // Create a truncated addrec for which we will add a no overflow check (P1).
5662 const SCEV *StartVal = getSCEV(StartValueV);
5663 const SCEV *PHISCEV =
5664 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5665 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5666
5667 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5668 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5669 // will be constant.
5670 //
5671 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5672 // add P1.
5673 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5677 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5678 Predicates.push_back(AddRecPred);
5679 }
5680
5681 // Create the Equal Predicates P2,P3:
5682
5683 // It is possible that the predicates P2 and/or P3 are computable at
5684 // compile time due to StartVal and/or Accum being constants.
5685 // If either one is, then we can check that now and escape if either P2
5686 // or P3 is false.
5687
5688 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5689 // for each of StartVal and Accum
5690 auto getExtendedExpr = [&](const SCEV *Expr,
5691 bool CreateSignExtend) -> const SCEV * {
5692 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5693 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5694 const SCEV *ExtendedExpr =
5695 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5696 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5697 return ExtendedExpr;
5698 };
5699
5700 // Given:
5701 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5702 // = getExtendedExpr(Expr)
5703 // Determine whether the predicate P: Expr == ExtendedExpr
5704 // is known to be false at compile time
5705 auto PredIsKnownFalse = [&](const SCEV *Expr,
5706 const SCEV *ExtendedExpr) -> bool {
5707 return Expr != ExtendedExpr &&
5708 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5709 };
5710
5711 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5712 if (PredIsKnownFalse(StartVal, StartExtended)) {
5713 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5714 return std::nullopt;
5715 }
5716
5717 // The Step is always Signed (because the overflow checks are either
5718 // NSSW or NUSW)
5719 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5720 if (PredIsKnownFalse(Accum, AccumExtended)) {
5721 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5722 return std::nullopt;
5723 }
5724
5725 auto AppendPredicate = [&](const SCEV *Expr,
5726 const SCEV *ExtendedExpr) -> void {
5727 if (Expr != ExtendedExpr &&
5728 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5729 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5730 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5731 Predicates.push_back(Pred);
5732 }
5733 };
5734
5735 AppendPredicate(StartVal, StartExtended);
5736 AppendPredicate(Accum, AccumExtended);
5737
5738 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5739 // which the casts had been folded away. The caller can rewrite SymbolicPHI
5740 // into NewAR if it will also add the runtime overflow checks specified in
5741 // Predicates.
5742 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5743
5744 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5745 std::make_pair(NewAR, Predicates);
5746 // Remember the result of the analysis for this SCEV at this locayyytion.
5747 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5748 return PredRewrite;
5749}
5750
5751std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5753 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5754 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5755 if (!L)
5756 return std::nullopt;
5757
5758 // Check to see if we already analyzed this PHI.
5759 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5760 if (I != PredicatedSCEVRewrites.end()) {
5761 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5762 I->second;
5763 // Analysis was done before and failed to create an AddRec:
5764 if (Rewrite.first == SymbolicPHI)
5765 return std::nullopt;
5766 // Analysis was done before and succeeded to create an AddRec under
5767 // a predicate:
5768 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5769 assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5770 return Rewrite;
5771 }
5772
5773 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5774 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5775
5776 // Record in the cache that the analysis failed
5777 if (!Rewrite) {
5779 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5780 return std::nullopt;
5781 }
5782
5783 return Rewrite;
5784}
5785
5786// FIXME: This utility is currently required because the Rewriter currently
5787// does not rewrite this expression:
5788// {0, +, (sext ix (trunc iy to ix) to iy)}
5789// into {0, +, %step},
5790// even when the following Equal predicate exists:
5791// "%step == (sext ix (trunc iy to ix) to iy)".
5793 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2,
5794 ArrayRef<const SCEVPredicate *> NoWrapPreds) const {
5795 if (AR1 == AR2)
5796 return true;
5797
5798 SCEVUnionPredicate NoWrapUnionPred(NoWrapPreds, SE);
5799 SCEVUnionPredicate AllPreds = Preds->getUnionWith(&NoWrapUnionPred, SE);
5800 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5801 if (Expr1 != Expr2 &&
5802 !AllPreds.implies(SE.getEqualPredicate(Expr1, Expr2), SE) &&
5803 !AllPreds.implies(SE.getEqualPredicate(Expr2, Expr1), SE))
5804 return false;
5805 return true;
5806 };
5807
5808 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5809 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5810 return false;
5811 return true;
5812}
5813
5814/// A helper function for createAddRecFromPHI to handle simple cases.
5815///
5816/// This function tries to find an AddRec expression for the simplest (yet most
5817/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5818/// If it fails, createAddRecFromPHI will use a more general, but slow,
5819/// technique for finding the AddRec expression.
5820const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5821 Value *BEValueV,
5822 Value *StartValueV) {
5823 const Loop *L = LI.getLoopFor(PN->getParent());
5824 assert(L && L->getHeader() == PN->getParent());
5825 assert(BEValueV && StartValueV);
5826
5827 auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN);
5828 if (!BO)
5829 return nullptr;
5830
5831 if (BO->Opcode != Instruction::Add)
5832 return nullptr;
5833
5834 const SCEV *Accum = nullptr;
5835 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5836 Accum = getSCEV(BO->RHS);
5837 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5838 Accum = getSCEV(BO->LHS);
5839
5840 if (!Accum)
5841 return nullptr;
5842
5844 if (BO->IsNUW)
5845 Flags = setFlags(Flags, SCEV::FlagNUW);
5846 if (BO->IsNSW)
5847 Flags = setFlags(Flags, SCEV::FlagNSW);
5848
5849 const SCEV *StartVal = getSCEV(StartValueV);
5850 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5851 insertValueToMap(PN, PHISCEV);
5852
5853 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5854 inferNoWrapViaConstantRanges(AR);
5855
5856 // We can add Flags to the post-inc expression only if we
5857 // know that it is *undefined behavior* for BEValueV to
5858 // overflow.
5859 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5860 assert(isLoopInvariant(Accum, L) &&
5861 "Accum is defined outside L, but is not invariant?");
5862 if (isAddRecNeverPoison(BEInst, L))
5863 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5864 }
5865
5866 return PHISCEV;
5867}
5868
5869const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5870 const Loop *L = LI.getLoopFor(PN->getParent());
5871 if (!L || L->getHeader() != PN->getParent())
5872 return nullptr;
5873
5874 // The loop may have multiple entrances or multiple exits; we can analyze
5875 // this phi as an addrec if it has a unique entry value and a unique
5876 // backedge value.
5877 Value *BEValueV = nullptr, *StartValueV = nullptr;
5878 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5879 Value *V = PN->getIncomingValue(i);
5880 if (L->contains(PN->getIncomingBlock(i))) {
5881 if (!BEValueV) {
5882 BEValueV = V;
5883 } else if (BEValueV != V) {
5884 BEValueV = nullptr;
5885 break;
5886 }
5887 } else if (!StartValueV) {
5888 StartValueV = V;
5889 } else if (StartValueV != V) {
5890 StartValueV = nullptr;
5891 break;
5892 }
5893 }
5894 if (!BEValueV || !StartValueV)
5895 return nullptr;
5896
5897 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5898 "PHI node already processed?");
5899
5900 // First, try to find AddRec expression without creating a fictituos symbolic
5901 // value for PN.
5902 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5903 return S;
5904
5905 // Handle PHI node value symbolically.
5906 const SCEV *SymbolicName = getUnknown(PN);
5907 insertValueToMap(PN, SymbolicName);
5908
5909 // Using this symbolic name for the PHI, analyze the value coming around
5910 // the back-edge.
5911 const SCEV *BEValue = getSCEV(BEValueV);
5912
5913 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5914 // has a special value for the first iteration of the loop.
5915
5916 // If the value coming around the backedge is an add with the symbolic
5917 // value we just inserted, then we found a simple induction variable!
5918 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5919 // If there is a single occurrence of the symbolic value, replace it
5920 // with a recurrence.
5921 unsigned FoundIndex = Add->getNumOperands();
5922 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5923 if (Add->getOperand(i) == SymbolicName)
5924 if (FoundIndex == e) {
5925 FoundIndex = i;
5926 break;
5927 }
5928
5929 if (FoundIndex != Add->getNumOperands()) {
5930 // Create an add with everything but the specified operand.
5932 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5933 if (i != FoundIndex)
5934 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5935 L, *this));
5936 const SCEV *Accum = getAddExpr(Ops);
5937
5938 // This is not a valid addrec if the step amount is varying each
5939 // loop iteration, but is not itself an addrec in this loop.
5940 if (isLoopInvariant(Accum, L) ||
5941 (isa<SCEVAddRecExpr>(Accum) &&
5942 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5944
5945 if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
5946 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5947 if (BO->IsNUW)
5948 Flags = setFlags(Flags, SCEV::FlagNUW);
5949 if (BO->IsNSW)
5950 Flags = setFlags(Flags, SCEV::FlagNSW);
5951 }
5952 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5953 if (GEP->getOperand(0) == PN) {
5954 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
5955 // If the increment has any nowrap flags, then we know the address
5956 // space cannot be wrapped around.
5957 if (NW != GEPNoWrapFlags::none())
5958 Flags = setFlags(Flags, SCEV::FlagNW);
5959 // If the GEP is nuw or nusw with non-negative offset, we know that
5960 // no unsigned wrap occurs. We cannot set the nsw flag as only the
5961 // offset is treated as signed, while the base is unsigned.
5962 if (NW.hasNoUnsignedWrap() ||
5964 Flags = setFlags(Flags, SCEV::FlagNUW);
5965 }
5966
5967 // We cannot transfer nuw and nsw flags from subtraction
5968 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5969 // for instance.
5970 }
5971
5972 const SCEV *StartVal = getSCEV(StartValueV);
5973 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5974
5975 // Okay, for the entire analysis of this edge we assumed the PHI
5976 // to be symbolic. We now need to go back and purge all of the
5977 // entries for the scalars that use the symbolic expression.
5978 forgetMemoizedResults({SymbolicName});
5979 insertValueToMap(PN, PHISCEV);
5980
5981 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5982 inferNoWrapViaConstantRanges(AR);
5983
5984 // We can add Flags to the post-inc expression only if we
5985 // know that it is *undefined behavior* for BEValueV to
5986 // overflow.
5987 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5988 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5989 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5990
5991 return PHISCEV;
5992 }
5993 }
5994 } else {
5995 // Otherwise, this could be a loop like this:
5996 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5997 // In this case, j = {1,+,1} and BEValue is j.
5998 // Because the other in-value of i (0) fits the evolution of BEValue
5999 // i really is an addrec evolution.
6000 //
6001 // We can generalize this saying that i is the shifted value of BEValue
6002 // by one iteration:
6003 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
6004
6005 // Do not allow refinement in rewriting of BEValue.
6006 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
6007 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
6008 if (Shifted != getCouldNotCompute() && Start != getCouldNotCompute() &&
6009 isGuaranteedNotToCauseUB(Shifted) && ::impliesPoison(Shifted, Start)) {
6010 const SCEV *StartVal = getSCEV(StartValueV);
6011 if (Start == StartVal) {
6012 // Okay, for the entire analysis of this edge we assumed the PHI
6013 // to be symbolic. We now need to go back and purge all of the
6014 // entries for the scalars that use the symbolic expression.
6015 forgetMemoizedResults({SymbolicName});
6016 insertValueToMap(PN, Shifted);
6017 return Shifted;
6018 }
6019 }
6020 }
6021
6022 // Remove the temporary PHI node SCEV that has been inserted while intending
6023 // to create an AddRecExpr for this PHI node. We can not keep this temporary
6024 // as it will prevent later (possibly simpler) SCEV expressions to be added
6025 // to the ValueExprMap.
6026 eraseValueFromMap(PN);
6027
6028 return nullptr;
6029}
6030
6031// Try to match a control flow sequence that branches out at BI and merges back
6032// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
6033// match.
6035 Value *&C, Value *&LHS, Value *&RHS) {
6036 C = BI->getCondition();
6037
6038 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
6039 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
6040
6041 Use &LeftUse = Merge->getOperandUse(0);
6042 Use &RightUse = Merge->getOperandUse(1);
6043
6044 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
6045 LHS = LeftUse;
6046 RHS = RightUse;
6047 return true;
6048 }
6049
6050 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
6051 LHS = RightUse;
6052 RHS = LeftUse;
6053 return true;
6054 }
6055
6056 return false;
6057}
6058
6060 Value *&Cond, Value *&LHS,
6061 Value *&RHS) {
6062 auto IsReachable =
6063 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
6064 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
6065 // Try to match
6066 //
6067 // br %cond, label %left, label %right
6068 // left:
6069 // br label %merge
6070 // right:
6071 // br label %merge
6072 // merge:
6073 // V = phi [ %x, %left ], [ %y, %right ]
6074 //
6075 // as "select %cond, %x, %y"
6076
6077 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
6078 assert(IDom && "At least the entry block should dominate PN");
6079
6080 auto *BI = dyn_cast<CondBrInst>(IDom->getTerminator());
6081 return BI && BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS);
6082 }
6083 return false;
6084}
6085
6086const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
6087 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6088 if (getOperandsForSelectLikePHI(DT, PN, Cond, LHS, RHS) &&
6091 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
6092
6093 return nullptr;
6094}
6095
6097 BinaryOperator *CommonInst = nullptr;
6098 // Check if instructions are identical.
6099 for (Value *Incoming : PN->incoming_values()) {
6100 auto *IncomingInst = dyn_cast<BinaryOperator>(Incoming);
6101 if (!IncomingInst)
6102 return nullptr;
6103 if (CommonInst) {
6104 if (!CommonInst->isIdenticalToWhenDefined(IncomingInst))
6105 return nullptr; // Not identical, give up
6106 } else {
6107 // Remember binary operator
6108 CommonInst = IncomingInst;
6109 }
6110 }
6111 return CommonInst;
6112}
6113
6114/// Returns SCEV for the first operand of a phi if all phi operands have
6115/// identical opcodes and operands
6116/// eg.
6117/// a: %add = %a + %b
6118/// br %c
6119/// b: %add1 = %a + %b
6120/// br %c
6121/// c: %phi = phi [%add, a], [%add1, b]
6122/// scev(%phi) => scev(%add)
6123const SCEV *
6124ScalarEvolution::createNodeForPHIWithIdenticalOperands(PHINode *PN) {
6125 BinaryOperator *CommonInst = getCommonInstForPHI(PN);
6126 if (!CommonInst)
6127 return nullptr;
6128
6129 // Check if SCEV exprs for instructions are identical.
6130 const SCEV *CommonSCEV = getSCEV(CommonInst);
6131 bool SCEVExprsIdentical =
6133 [this, CommonSCEV](Value *V) { return CommonSCEV == getSCEV(V); });
6134 return SCEVExprsIdentical ? CommonSCEV : nullptr;
6135}
6136
6137const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
6138 if (const SCEV *S = createAddRecFromPHI(PN))
6139 return S;
6140
6141 // We do not allow simplifying phi (undef, X) to X here, to avoid reusing the
6142 // phi node for X.
6143 if (Value *V = simplifyInstruction(
6144 PN, {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
6145 /*UseInstrInfo=*/true, /*CanUseUndef=*/false}))
6146 return getSCEV(V);
6147
6148 if (const SCEV *S = createNodeForPHIWithIdenticalOperands(PN))
6149 return S;
6150
6151 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
6152 return S;
6153
6154 // If it's not a loop phi, we can't handle it yet.
6155 return getUnknown(PN);
6156}
6157
6158bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
6159 SCEVTypes RootKind) {
6160 struct FindClosure {
6161 const SCEV *OperandToFind;
6162 const SCEVTypes RootKind; // Must be a sequential min/max expression.
6163 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
6164
6165 bool Found = false;
6166
6167 bool canRecurseInto(SCEVTypes Kind) const {
6168 // We can only recurse into the SCEV expression of the same effective type
6169 // as the type of our root SCEV expression, and into zero-extensions.
6170 return RootKind == Kind || NonSequentialRootKind == Kind ||
6171 scZeroExtend == Kind;
6172 };
6173
6174 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
6175 : OperandToFind(OperandToFind), RootKind(RootKind),
6176 NonSequentialRootKind(
6178 RootKind)) {}
6179
6180 bool follow(const SCEV *S) {
6181 Found = S == OperandToFind;
6182
6183 return !isDone() && canRecurseInto(S->getSCEVType());
6184 }
6185
6186 bool isDone() const { return Found; }
6187 };
6188
6189 FindClosure FC(OperandToFind, RootKind);
6190 visitAll(Root, FC);
6191 return FC.Found;
6192}
6193
6194std::optional<const SCEV *>
6195ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
6196 ICmpInst *Cond,
6197 Value *TrueVal,
6198 Value *FalseVal) {
6199 // Try to match some simple smax or umax patterns.
6200 auto *ICI = Cond;
6201
6202 Value *LHS = ICI->getOperand(0);
6203 Value *RHS = ICI->getOperand(1);
6204
6205 switch (ICI->getPredicate()) {
6206 case ICmpInst::ICMP_SLT:
6207 case ICmpInst::ICMP_SLE:
6208 case ICmpInst::ICMP_ULT:
6209 case ICmpInst::ICMP_ULE:
6210 std::swap(LHS, RHS);
6211 [[fallthrough]];
6212 case ICmpInst::ICMP_SGT:
6213 case ICmpInst::ICMP_SGE:
6214 case ICmpInst::ICMP_UGT:
6215 case ICmpInst::ICMP_UGE:
6216 // a > b ? a+x : b+x -> max(a, b)+x
6217 // a > b ? b+x : a+x -> min(a, b)+x
6219 bool Signed = ICI->isSigned();
6220 const SCEV *LA = getSCEV(TrueVal);
6221 const SCEV *RA = getSCEV(FalseVal);
6222 const SCEV *LS = getSCEV(LHS);
6223 const SCEV *RS = getSCEV(RHS);
6224 if (LA->getType()->isPointerTy()) {
6225 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6226 // Need to make sure we can't produce weird expressions involving
6227 // negated pointers.
6228 if (LA == LS && RA == RS)
6229 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6230 if (LA == RS && RA == LS)
6231 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6232 }
6233 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6234 if (Op->getType()->isPointerTy()) {
6237 return Op;
6238 }
6239 if (Signed)
6240 Op = getNoopOrSignExtend(Op, Ty);
6241 else
6242 Op = getNoopOrZeroExtend(Op, Ty);
6243 return Op;
6244 };
6245 LS = CoerceOperand(LS);
6246 RS = CoerceOperand(RS);
6248 break;
6249 const SCEV *LDiff = getMinusSCEV(LA, LS);
6250 const SCEV *RDiff = getMinusSCEV(RA, RS);
6251 if (LDiff == RDiff)
6252 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6253 LDiff);
6254 LDiff = getMinusSCEV(LA, RS);
6255 RDiff = getMinusSCEV(RA, LS);
6256 if (LDiff == RDiff)
6257 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6258 LDiff);
6259 }
6260 break;
6261 case ICmpInst::ICMP_NE:
6262 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
6263 std::swap(TrueVal, FalseVal);
6264 [[fallthrough]];
6265 case ICmpInst::ICMP_EQ:
6266 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
6269 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6270 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y
6271 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y
6272 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6273 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y
6274 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6275 return getAddExpr(getUMaxExpr(X, C), Y);
6276 }
6277 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
6278 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
6279 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
6280 // -> umin_seq(x, umin (..., umin_seq(...), ...))
6282 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6283 const SCEV *X = getSCEV(LHS);
6284 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6285 X = ZExt->getOperand();
6286 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6287 const SCEV *FalseValExpr = getSCEV(FalseVal);
6288 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6289 return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6290 /*Sequential=*/true);
6291 }
6292 }
6293 break;
6294 default:
6295 break;
6296 }
6297
6298 return std::nullopt;
6299}
6300
6301static std::optional<const SCEV *>
6303 const SCEV *TrueExpr, const SCEV *FalseExpr) {
6304 assert(CondExpr->getType()->isIntegerTy(1) &&
6305 TrueExpr->getType() == FalseExpr->getType() &&
6306 TrueExpr->getType()->isIntegerTy(1) &&
6307 "Unexpected operands of a select.");
6308
6309 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
6310 // --> C + (umin_seq cond, x - C)
6311 //
6312 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
6313 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6314 // --> C + (umin_seq ~cond, x - C)
6315
6316 // FIXME: while we can't legally model the case where both of the hands
6317 // are fully variable, we only require that the *difference* is constant.
6318 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6319 return std::nullopt;
6320
6321 const SCEV *X, *C;
6322 if (isa<SCEVConstant>(TrueExpr)) {
6323 CondExpr = SE->getNotSCEV(CondExpr);
6324 X = FalseExpr;
6325 C = TrueExpr;
6326 } else {
6327 X = TrueExpr;
6328 C = FalseExpr;
6329 }
6330 return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6331 /*Sequential=*/true));
6332}
6333
6334static std::optional<const SCEV *>
6336 Value *FalseVal) {
6337 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6338 return std::nullopt;
6339
6340 const auto *SECond = SE->getSCEV(Cond);
6341 const auto *SETrue = SE->getSCEV(TrueVal);
6342 const auto *SEFalse = SE->getSCEV(FalseVal);
6343 return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6344}
6345
6346const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6347 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6348 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6349 assert(TrueVal->getType() == FalseVal->getType() &&
6350 V->getType() == TrueVal->getType() &&
6351 "Types of select hands and of the result must match.");
6352
6353 // For now, only deal with i1-typed `select`s.
6354 if (!V->getType()->isIntegerTy(1))
6355 return getUnknown(V);
6356
6357 if (std::optional<const SCEV *> S =
6358 createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6359 return *S;
6360
6361 return getUnknown(V);
6362}
6363
6364const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6365 Value *TrueVal,
6366 Value *FalseVal) {
6367 // Handle "constant" branch or select. This can occur for instance when a
6368 // loop pass transforms an inner loop and moves on to process the outer loop.
6369 if (auto *CI = dyn_cast<ConstantInt>(Cond))
6370 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6371
6372 if (auto *I = dyn_cast<Instruction>(V)) {
6373 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6374 if (std::optional<const SCEV *> S =
6375 createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6376 TrueVal, FalseVal))
6377 return *S;
6378 }
6379 }
6380
6381 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6382}
6383
6384/// Expand GEP instructions into add and multiply operations. This allows them
6385/// to be analyzed by regular SCEV code.
6386const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6387 assert(GEP->getSourceElementType()->isSized() &&
6388 "GEP source element type must be sized");
6389
6390 SmallVector<SCEVUse, 4> IndexExprs;
6391 for (Value *Index : GEP->indices())
6392 IndexExprs.push_back(getSCEV(Index));
6393 return getGEPExpr(GEP, IndexExprs);
6394}
6395
6396APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S,
6397 const Instruction *CtxI) {
6398 uint64_t BitWidth = getTypeSizeInBits(S->getType());
6399 auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6400 return TrailingZeros >= BitWidth
6402 : APInt::getOneBitSet(BitWidth, TrailingZeros);
6403 };
6404 auto GetGCDMultiple = [this, CtxI](const SCEVNAryExpr *N) {
6405 // The result is GCD of all operands results.
6406 APInt Res = getConstantMultiple(N->getOperand(0), CtxI);
6407 for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6409 Res, getConstantMultiple(N->getOperand(I), CtxI));
6410 return Res;
6411 };
6412
6413 switch (S->getSCEVType()) {
6414 case scConstant:
6415 return cast<SCEVConstant>(S)->getAPInt();
6416 case scPtrToAddr:
6417 return getConstantMultiple(cast<SCEVCastExpr>(S)->getOperand());
6418 case scUDivExpr:
6419 case scVScale:
6420 return APInt(BitWidth, 1);
6421 case scTruncate: {
6422 // Only multiples that are a power of 2 will hold after truncation.
6423 const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6424 uint32_t TZ = getMinTrailingZeros(T->getOperand(), CtxI);
6425 return GetShiftedByZeros(TZ);
6426 }
6427 case scZeroExtend: {
6428 const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(S);
6429 return getConstantMultiple(Z->getOperand(), CtxI).zext(BitWidth);
6430 }
6431 case scSignExtend: {
6432 // Only multiples that are a power of 2 will hold after sext.
6433 const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6434 uint32_t TZ = getMinTrailingZeros(E->getOperand(), CtxI);
6435 return GetShiftedByZeros(TZ);
6436 }
6437 case scMulExpr: {
6438 const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6439 if (M->hasNoUnsignedWrap()) {
6440 // The result is the product of all operand results.
6441 APInt Res = getConstantMultiple(M->getOperand(0), CtxI);
6442 for (const SCEV *Operand : M->operands().drop_front())
6443 Res = Res * getConstantMultiple(Operand, CtxI);
6444 return Res;
6445 }
6446
6447 // If there are no wrap guarentees, find the trailing zeros, which is the
6448 // sum of trailing zeros for all its operands.
6449 uint32_t TZ = 0;
6450 for (const SCEV *Operand : M->operands())
6451 TZ += getMinTrailingZeros(Operand, CtxI);
6452 return GetShiftedByZeros(TZ);
6453 }
6454 case scAddExpr:
6455 case scAddRecExpr: {
6456 const SCEVNAryExpr *N = cast<SCEVNAryExpr>(S);
6457 if (N->hasNoUnsignedWrap())
6458 return GetGCDMultiple(N);
6459 // Find the trailing bits, which is the minimum of its operands.
6460 uint32_t TZ = getMinTrailingZeros(N->getOperand(0), CtxI);
6461 for (const SCEV *Operand : N->operands().drop_front())
6462 TZ = std::min(TZ, getMinTrailingZeros(Operand, CtxI));
6463 return GetShiftedByZeros(TZ);
6464 }
6465 case scUMaxExpr:
6466 case scSMaxExpr:
6467 case scUMinExpr:
6468 case scSMinExpr:
6470 return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6471 case scUnknown: {
6472 // Ask ValueTracking for known bits. SCEVUnknown only become available at
6473 // the point their underlying IR instruction has been defined. If CtxI was
6474 // not provided, use:
6475 // * the first instruction in the entry block if it is an argument
6476 // * the instruction itself otherwise.
6477 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6478 if (!CtxI) {
6479 if (isa<Argument>(U->getValue()))
6480 CtxI = &*F.getEntryBlock().begin();
6481 else if (auto *I = dyn_cast<Instruction>(U->getValue()))
6482 CtxI = I;
6483 }
6484 unsigned Known =
6485 computeKnownBits(U->getValue(),
6486 SimplifyQuery(getDataLayout(), &DT, &AC, CtxI)
6487 .allowEphemerals(true))
6488 .countMinTrailingZeros();
6489 return GetShiftedByZeros(Known);
6490 }
6491 case scCouldNotCompute:
6492 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6493 }
6494 llvm_unreachable("Unknown SCEV kind!");
6495}
6496
6498 const Instruction *CtxI) {
6499 // Skip looking up and updating the cache if there is a context instruction,
6500 // as the result will only be valid in the specified context.
6501 if (CtxI)
6502 return getConstantMultipleImpl(S, CtxI);
6503
6504 auto I = ConstantMultipleCache.find(S);
6505 if (I != ConstantMultipleCache.end())
6506 return I->second;
6507
6508 APInt Result = getConstantMultipleImpl(S, CtxI);
6509 auto InsertPair = ConstantMultipleCache.insert({S, Result});
6510 assert(InsertPair.second && "Should insert a new key");
6511 return InsertPair.first->second;
6512}
6513
6515 APInt Multiple = getConstantMultiple(S);
6516 return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6517}
6518
6520 const Instruction *CtxI) {
6521 return std::min(getConstantMultiple(S, CtxI).countTrailingZeros(),
6522 (unsigned)getTypeSizeInBits(S->getType()));
6523}
6524
6525/// Helper method to assign a range to V from metadata present in the IR.
6526static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6528 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6529 return getConstantRangeFromMetadata(*MD);
6530 if (const auto *CB = dyn_cast<CallBase>(V))
6531 if (std::optional<ConstantRange> Range = CB->getRange())
6532 return Range;
6533 }
6534 if (auto *A = dyn_cast<Argument>(V))
6535 if (std::optional<ConstantRange> Range = A->getRange())
6536 return Range;
6537
6538 return std::nullopt;
6539}
6540
6542 SCEV::NoWrapFlags Flags) {
6543 if (AddRec->getNoWrapFlags(Flags) != Flags) {
6544 AddRec->setNoWrapFlags(Flags);
6545 UnsignedRanges.erase(AddRec);
6546 SignedRanges.erase(AddRec);
6547 ConstantMultipleCache.erase(AddRec);
6548 }
6549}
6550
6551ConstantRange ScalarEvolution::
6552getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6553 const DataLayout &DL = getDataLayout();
6554
6555 unsigned BitWidth = getTypeSizeInBits(U->getType());
6556 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6557
6558 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6559 // use information about the trip count to improve our available range. Note
6560 // that the trip count independent cases are already handled by known bits.
6561 // WARNING: The definition of recurrence used here is subtly different than
6562 // the one used by AddRec (and thus most of this file). Step is allowed to
6563 // be arbitrarily loop varying here, where AddRec allows only loop invariant
6564 // and other addrecs in the same loop (for non-affine addrecs). The code
6565 // below intentionally handles the case where step is not loop invariant.
6566 auto *P = dyn_cast<PHINode>(U->getValue());
6567 if (!P)
6568 return FullSet;
6569
6570 // Make sure that no Phi input comes from an unreachable block. Otherwise,
6571 // even the values that are not available in these blocks may come from them,
6572 // and this leads to false-positive recurrence test.
6573 for (auto *Pred : predecessors(P->getParent()))
6574 if (!DT.isReachableFromEntry(Pred))
6575 return FullSet;
6576
6577 BinaryOperator *BO;
6578 Value *Start, *Step;
6579 if (!matchSimpleRecurrence(P, BO, Start, Step))
6580 return FullSet;
6581
6582 // If we found a recurrence in reachable code, we must be in a loop. Note
6583 // that BO might be in some subloop of L, and that's completely okay.
6584 auto *L = LI.getLoopFor(P->getParent());
6585 assert(L && L->getHeader() == P->getParent());
6586 if (!L->contains(BO->getParent()))
6587 // NOTE: This bailout should be an assert instead. However, asserting
6588 // the condition here exposes a case where LoopFusion is querying SCEV
6589 // with malformed loop information during the midst of the transform.
6590 // There doesn't appear to be an obvious fix, so for the moment bailout
6591 // until the caller issue can be fixed. PR49566 tracks the bug.
6592 return FullSet;
6593
6594 // TODO: Extend to other opcodes such as mul, and div
6595 switch (BO->getOpcode()) {
6596 default:
6597 return FullSet;
6598 case Instruction::AShr:
6599 case Instruction::LShr:
6600 case Instruction::Shl:
6601 break;
6602 };
6603
6604 if (BO->getOperand(0) != P)
6605 // TODO: Handle the power function forms some day.
6606 return FullSet;
6607
6608 unsigned TC = getSmallConstantMaxTripCount(L);
6609 if (!TC || TC >= BitWidth)
6610 return FullSet;
6611
6612 auto KnownStart = computeKnownBits(Start, DL, &AC, nullptr, &DT);
6613 auto KnownStep = computeKnownBits(Step, DL, &AC, nullptr, &DT);
6614 assert(KnownStart.getBitWidth() == BitWidth &&
6615 KnownStep.getBitWidth() == BitWidth);
6616
6617 // Compute total shift amount, being careful of overflow and bitwidths.
6618 auto MaxShiftAmt = KnownStep.getMaxValue();
6619 APInt TCAP(BitWidth, TC-1);
6620 bool Overflow = false;
6621 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6622 if (Overflow)
6623 return FullSet;
6624
6625 switch (BO->getOpcode()) {
6626 default:
6627 llvm_unreachable("filtered out above");
6628 case Instruction::AShr: {
6629 // For each ashr, three cases:
6630 // shift = 0 => unchanged value
6631 // saturation => 0 or -1
6632 // other => a value closer to zero (of the same sign)
6633 // Thus, the end value is closer to zero than the start.
6634 auto KnownEnd = KnownBits::ashr(KnownStart,
6635 KnownBits::makeConstant(TotalShift));
6636 if (KnownStart.isNonNegative())
6637 // Analogous to lshr (simply not yet canonicalized)
6638 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6639 KnownStart.getMaxValue() + 1);
6640 if (KnownStart.isNegative())
6641 // End >=u Start && End <=s Start
6642 return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6643 KnownEnd.getMaxValue() + 1);
6644 break;
6645 }
6646 case Instruction::LShr: {
6647 // For each lshr, three cases:
6648 // shift = 0 => unchanged value
6649 // saturation => 0
6650 // other => a smaller positive number
6651 // Thus, the low end of the unsigned range is the last value produced.
6652 auto KnownEnd = KnownBits::lshr(KnownStart,
6653 KnownBits::makeConstant(TotalShift));
6654 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6655 KnownStart.getMaxValue() + 1);
6656 }
6657 case Instruction::Shl: {
6658 // Iff no bits are shifted out, value increases on every shift.
6659 auto KnownEnd = KnownBits::shl(KnownStart,
6660 KnownBits::makeConstant(TotalShift));
6661 if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6662 return ConstantRange(KnownStart.getMinValue(),
6663 KnownEnd.getMaxValue() + 1);
6664 break;
6665 }
6666 };
6667 return FullSet;
6668}
6669
6670// The goal of this function is to check if recursively visiting the operands
6671// of this PHI might lead to an infinite loop. If we do see such a loop,
6672// there's no good way to break it, so we avoid analyzing such cases.
6673//
6674// getRangeRef previously used a visited set to avoid infinite loops, but this
6675// caused other issues: the result was dependent on the order of getRangeRef
6676// calls, and the interaction with createSCEVIter could cause a stack overflow
6677// in some cases (see issue #148253).
6678//
6679// FIXME: The way this is implemented is overly conservative; this checks
6680// for a few obviously safe patterns, but anything that doesn't lead to
6681// recursion is fine.
6683 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6685 return true;
6686
6687 if (all_of(PHI->operands(),
6688 [&](Value *Operand) { return DT.dominates(Operand, PHI); }))
6689 return true;
6690
6691 return false;
6692}
6693
6694const ConstantRange &
6695ScalarEvolution::getRangeRefIter(const SCEV *S,
6696 ScalarEvolution::RangeSignHint SignHint) {
6697 DenseMap<const SCEV *, ConstantRange> &Cache =
6698 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6699 : SignedRanges;
6700 SmallVector<SCEVUse> WorkList;
6701 SmallPtrSet<const SCEV *, 8> Seen;
6702
6703 // Add Expr to the worklist, if Expr is either an N-ary expression or a
6704 // SCEVUnknown PHI node.
6705 auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6706 if (!Seen.insert(Expr).second)
6707 return;
6708 if (Cache.contains(Expr))
6709 return;
6710 switch (Expr->getSCEVType()) {
6711 case scUnknown:
6713 break;
6714 [[fallthrough]];
6715 case scConstant:
6716 case scVScale:
6717 case scTruncate:
6718 case scZeroExtend:
6719 case scSignExtend:
6720 case scPtrToAddr:
6721 case scAddExpr:
6722 case scMulExpr:
6723 case scUDivExpr:
6724 case scAddRecExpr:
6725 case scUMaxExpr:
6726 case scSMaxExpr:
6727 case scUMinExpr:
6728 case scSMinExpr:
6730 WorkList.push_back(Expr);
6731 break;
6732 case scCouldNotCompute:
6733 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6734 }
6735 };
6736 AddToWorklist(S);
6737
6738 // Build worklist by queuing operands of N-ary expressions and phi nodes.
6739 for (unsigned I = 0; I != WorkList.size(); ++I) {
6740 const SCEV *P = WorkList[I];
6741 auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6742 // If it is not a `SCEVUnknown`, just recurse into operands.
6743 if (!UnknownS) {
6744 for (const SCEV *Op : P->operands())
6745 AddToWorklist(Op);
6746 continue;
6747 }
6748 // `SCEVUnknown`'s require special treatment.
6749 if (PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6750 if (!RangeRefPHIAllowedOperands(DT, P))
6751 continue;
6752 for (auto &Op : reverse(P->operands()))
6753 AddToWorklist(getSCEV(Op));
6754 }
6755 }
6756
6757 if (!WorkList.empty()) {
6758 // Use getRangeRef to compute ranges for items in the worklist in reverse
6759 // order. This will force ranges for earlier operands to be computed before
6760 // their users in most cases.
6761 for (const SCEV *P : reverse(drop_begin(WorkList))) {
6762 getRangeRef(P, SignHint);
6763 }
6764 }
6765
6766 return getRangeRef(S, SignHint, 0);
6767}
6768
6769/// Determine the range for a particular SCEV. If SignHint is
6770/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6771/// with a "cleaner" unsigned (resp. signed) representation.
6772const ConstantRange &ScalarEvolution::getRangeRef(
6773 const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6774 DenseMap<const SCEV *, ConstantRange> &Cache =
6775 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6776 : SignedRanges;
6778 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6780
6781 // See if we've computed this range already.
6782 auto I = Cache.find(S);
6783 if (I != Cache.end())
6784 return I->second;
6785
6786 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6787 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6788
6789 // Switch to iteratively computing the range for S, if it is part of a deeply
6790 // nested expression.
6792 return getRangeRefIter(S, SignHint);
6793
6794 unsigned BitWidth = getTypeSizeInBits(S->getType());
6795 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6796 using OBO = OverflowingBinaryOperator;
6797
6798 // If the value has known zeros, the maximum value will have those known zeros
6799 // as well.
6800 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6801 APInt Multiple = getNonZeroConstantMultiple(S);
6802 APInt Remainder = APInt::getMaxValue(BitWidth).urem(Multiple);
6803 if (!Remainder.isZero())
6804 ConservativeResult =
6805 ConstantRange(APInt::getMinValue(BitWidth),
6806 APInt::getMaxValue(BitWidth) - Remainder + 1);
6807 }
6808 else {
6809 uint32_t TZ = getMinTrailingZeros(S);
6810 if (TZ != 0) {
6811 ConservativeResult = ConstantRange(
6813 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6814 }
6815 }
6816
6817 switch (S->getSCEVType()) {
6818 case scConstant:
6819 llvm_unreachable("Already handled above.");
6820 case scVScale:
6821 return setRange(S, SignHint, getVScaleRange(&F, BitWidth));
6822 case scTruncate: {
6823 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6824 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6825 return setRange(
6826 Trunc, SignHint,
6827 ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6828 }
6829 case scZeroExtend: {
6830 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6831 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6832 return setRange(
6833 ZExt, SignHint,
6834 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6835 }
6836 case scSignExtend: {
6837 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6838 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6839 return setRange(
6840 SExt, SignHint,
6841 ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6842 }
6843 case scPtrToAddr: {
6844 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6845 ConstantRange X = getRangeRef(Cast->getOperand(), SignHint, Depth + 1);
6846 return setRange(Cast, SignHint, X);
6847 }
6848 case scAddExpr: {
6849 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6850 // Check if this is a URem pattern: A - (A / B) * B, which is always < B.
6851 const SCEV *URemLHS = nullptr, *URemRHS = nullptr;
6852 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED &&
6853 match(S, m_scev_URem(m_SCEV(URemLHS), m_SCEV(URemRHS), *this))) {
6854 ConstantRange LHSRange = getRangeRef(URemLHS, SignHint, Depth + 1);
6855 ConstantRange RHSRange = getRangeRef(URemRHS, SignHint, Depth + 1);
6856 ConservativeResult =
6857 ConservativeResult.intersectWith(LHSRange.urem(RHSRange), RangeType);
6858 }
6859 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6860 unsigned WrapType = OBO::AnyWrap;
6861 if (Add->hasNoSignedWrap())
6862 WrapType |= OBO::NoSignedWrap;
6863 if (Add->hasNoUnsignedWrap())
6864 WrapType |= OBO::NoUnsignedWrap;
6865 for (const SCEV *Op : drop_begin(Add->operands()))
6866 X = X.addWithNoWrap(getRangeRef(Op, SignHint, Depth + 1), WrapType,
6867 RangeType);
6868 return setRange(Add, SignHint,
6869 ConservativeResult.intersectWith(X, RangeType));
6870 }
6871 case scMulExpr: {
6872 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6873 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6874 for (const SCEV *Op : drop_begin(Mul->operands()))
6875 X = X.multiply(getRangeRef(Op, SignHint, Depth + 1));
6876 return setRange(Mul, SignHint,
6877 ConservativeResult.intersectWith(X, RangeType));
6878 }
6879 case scUDivExpr: {
6880 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6881 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6882 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6883 return setRange(UDiv, SignHint,
6884 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6885 }
6886 case scAddRecExpr: {
6887 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6888 // If there's no unsigned wrap, the value will never be less than its
6889 // initial value.
6890 if (AddRec->hasNoUnsignedWrap()) {
6891 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6892 if (!UnsignedMinValue.isZero())
6893 ConservativeResult = ConservativeResult.intersectWith(
6894 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6895 }
6896
6897 // If there's no signed wrap, and all the operands except initial value have
6898 // the same sign or zero, the value won't ever be:
6899 // 1: smaller than initial value if operands are non negative,
6900 // 2: bigger than initial value if operands are non positive.
6901 // For both cases, value can not cross signed min/max boundary.
6902 if (AddRec->hasNoSignedWrap()) {
6903 bool AllNonNeg = true;
6904 bool AllNonPos = true;
6905 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6906 if (!isKnownNonNegative(AddRec->getOperand(i)))
6907 AllNonNeg = false;
6908 if (!isKnownNonPositive(AddRec->getOperand(i)))
6909 AllNonPos = false;
6910 }
6911 if (AllNonNeg)
6912 ConservativeResult = ConservativeResult.intersectWith(
6915 RangeType);
6916 else if (AllNonPos)
6917 ConservativeResult = ConservativeResult.intersectWith(
6919 getSignedRangeMax(AddRec->getStart()) +
6920 1),
6921 RangeType);
6922 }
6923
6924 // TODO: non-affine addrec
6925 if (AddRec->isAffine()) {
6926 const SCEV *MaxBEScev =
6928 if (!isa<SCEVCouldNotCompute>(MaxBEScev)) {
6929 APInt MaxBECount = cast<SCEVConstant>(MaxBEScev)->getAPInt();
6930
6931 // Adjust MaxBECount to the same bitwidth as AddRec. We can truncate if
6932 // MaxBECount's active bits are all <= AddRec's bit width.
6933 if (MaxBECount.getBitWidth() > BitWidth &&
6934 MaxBECount.getActiveBits() <= BitWidth)
6935 MaxBECount = MaxBECount.trunc(BitWidth);
6936 else if (MaxBECount.getBitWidth() < BitWidth)
6937 MaxBECount = MaxBECount.zext(BitWidth);
6938
6939 if (MaxBECount.getBitWidth() == BitWidth) {
6940 auto [RangeFromAffine, Flags] = getRangeForAffineAR(
6941 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6942 ConservativeResult =
6943 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6944 const_cast<SCEVAddRecExpr *>(AddRec)->setNoWrapFlags(Flags);
6945
6946 auto RangeFromFactoring = getRangeViaFactoring(
6947 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6948 ConservativeResult =
6949 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6950 }
6951 }
6952
6953 // Now try symbolic BE count and more powerful methods.
6955 const SCEV *SymbolicMaxBECount =
6957 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6958 getTypeSizeInBits(MaxBEScev->getType()) <= BitWidth &&
6959 AddRec->hasNoSelfWrap()) {
6960 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6961 AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6962 ConservativeResult =
6963 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6964 }
6965 }
6966 }
6967
6968 return setRange(AddRec, SignHint, std::move(ConservativeResult));
6969 }
6970 case scUMaxExpr:
6971 case scSMaxExpr:
6972 case scUMinExpr:
6973 case scSMinExpr:
6974 case scSequentialUMinExpr: {
6976 switch (S->getSCEVType()) {
6977 case scUMaxExpr:
6978 ID = Intrinsic::umax;
6979 break;
6980 case scSMaxExpr:
6981 ID = Intrinsic::smax;
6982 break;
6983 case scUMinExpr:
6985 ID = Intrinsic::umin;
6986 break;
6987 case scSMinExpr:
6988 ID = Intrinsic::smin;
6989 break;
6990 default:
6991 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6992 }
6993
6994 const auto *NAry = cast<SCEVNAryExpr>(S);
6995 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
6996 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6997 X = X.intrinsic(
6998 ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
6999 return setRange(S, SignHint,
7000 ConservativeResult.intersectWith(X, RangeType));
7001 }
7002 case scUnknown: {
7003 const SCEVUnknown *U = cast<SCEVUnknown>(S);
7004 Value *V = U->getValue();
7005
7006 // Check if the IR explicitly contains !range metadata.
7007 std::optional<ConstantRange> MDRange = GetRangeFromMetadata(V);
7008 if (MDRange)
7009 ConservativeResult =
7010 ConservativeResult.intersectWith(*MDRange, RangeType);
7011
7012 // Use facts about recurrences in the underlying IR. Note that add
7013 // recurrences are AddRecExprs and thus don't hit this path. This
7014 // primarily handles shift recurrences.
7015 auto CR = getRangeForUnknownRecurrence(U);
7016 ConservativeResult = ConservativeResult.intersectWith(CR);
7017
7018 // See if ValueTracking can give us a useful range.
7019 const DataLayout &DL = getDataLayout();
7020 KnownBits Known = computeKnownBits(V, DL, &AC, nullptr, &DT);
7021 if (Known.getBitWidth() != BitWidth)
7022 Known = Known.zextOrTrunc(BitWidth);
7023
7024 // ValueTracking may be able to compute a tighter result for the number of
7025 // sign bits than for the value of those sign bits.
7026 unsigned NS = ComputeNumSignBits(V, DL, &AC, nullptr, &DT);
7027 if (U->getType()->isPointerTy()) {
7028 // If the pointer size is larger than the index size type, this can cause
7029 // NS to be larger than BitWidth. So compensate for this.
7030 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
7031 int ptrIdxDiff = ptrSize - BitWidth;
7032 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
7033 NS -= ptrIdxDiff;
7034 }
7035
7036 if (NS > 1) {
7037 // If we know any of the sign bits, we know all of the sign bits.
7038 if (!Known.Zero.getHiBits(NS).isZero())
7039 Known.Zero.setHighBits(NS);
7040 if (!Known.One.getHiBits(NS).isZero())
7041 Known.One.setHighBits(NS);
7042 }
7043
7044 if (Known.getMinValue() != Known.getMaxValue() + 1)
7045 ConservativeResult = ConservativeResult.intersectWith(
7046 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
7047 RangeType);
7048 if (NS > 1)
7049 ConservativeResult = ConservativeResult.intersectWith(
7050 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
7051 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
7052 RangeType);
7053
7054 if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
7055 // Strengthen the range if the underlying IR value is a
7056 // global/alloca/heap allocation using the size of the object.
7057 bool CanBeNull;
7058 uint64_t DerefBytes = V->getPointerDereferenceableBytes(
7059 DL, CanBeNull, /*CanBeFreed=*/nullptr);
7060 if (DerefBytes > 1 && isUIntN(BitWidth, DerefBytes)) {
7061 // The highest address the object can start is DerefBytes bytes before
7062 // the end (unsigned max value). If this value is not a multiple of the
7063 // alignment, the last possible start value is the next lowest multiple
7064 // of the alignment. Note: The computations below cannot overflow,
7065 // because if they would there's no possible start address for the
7066 // object.
7067 APInt MaxVal =
7068 APInt::getMaxValue(BitWidth) - APInt(BitWidth, DerefBytes);
7069 uint64_t Align = U->getValue()->getPointerAlignment(DL).value();
7070 uint64_t Rem = MaxVal.urem(Align);
7071 MaxVal -= APInt(BitWidth, Rem);
7072 APInt MinVal = APInt::getZero(BitWidth);
7073 if (llvm::isKnownNonZero(V, DL))
7074 MinVal = Align;
7075 ConservativeResult = ConservativeResult.intersectWith(
7076 ConstantRange::getNonEmpty(MinVal, MaxVal + 1), RangeType);
7077 }
7078 }
7079
7080 // A range of Phi is a subset of union of all ranges of its input.
7081 if (PHINode *Phi = dyn_cast<PHINode>(V)) {
7082 // SCEVExpander sometimes creates SCEVUnknowns that are secretly
7083 // AddRecs; return the range for the corresponding AddRec.
7084 if (auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V)))
7085 return getRangeRef(AR, SignHint, Depth + 1);
7086
7087 // Make sure that we do not run over cycled Phis.
7088 if (RangeRefPHIAllowedOperands(DT, Phi)) {
7089 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
7090
7091 for (const auto &Op : Phi->operands()) {
7092 auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
7093 RangeFromOps = RangeFromOps.unionWith(OpRange);
7094 // No point to continue if we already have a full set.
7095 if (RangeFromOps.isFullSet())
7096 break;
7097 }
7098 ConservativeResult =
7099 ConservativeResult.intersectWith(RangeFromOps, RangeType);
7100 }
7101 }
7102
7103 // vscale can't be equal to zero
7104 if (const auto *II = dyn_cast<IntrinsicInst>(V))
7105 if (II->getIntrinsicID() == Intrinsic::vscale) {
7106 ConstantRange Disallowed = APInt::getZero(BitWidth);
7107 ConservativeResult = ConservativeResult.difference(Disallowed);
7108 }
7109
7110 return setRange(U, SignHint, std::move(ConservativeResult));
7111 }
7112 case scCouldNotCompute:
7113 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
7114 }
7115
7116 return setRange(S, SignHint, std::move(ConservativeResult));
7117}
7118
7119// Given a StartRange, Step and MaxBECount for an expression compute a range of
7120// values that the expression can take. Initially, the expression has a value
7121// from StartRange and then is changed by Step up to MaxBECount times. Signed
7122// argument defines if we treat Step as signed or unsigned. The second return
7123// value indicates that no wrapping occurred.
7124static std::pair<ConstantRange, bool>
7126 const APInt &MaxBECount, bool Signed) {
7127 unsigned BitWidth = Step.getBitWidth();
7128 assert(BitWidth == StartRange.getBitWidth() &&
7129 BitWidth == MaxBECount.getBitWidth() && "mismatched bit widths");
7130 // If either Step or MaxBECount is 0, then the expression won't change, and we
7131 // just need to return the initial range.
7132 if (Step == 0 || MaxBECount == 0)
7133 return {StartRange, true};
7134
7135 // If we don't know anything about the initial value (i.e. StartRange is
7136 // FullRange), then we don't know anything about the final range either.
7137 // Return FullRange.
7138 if (StartRange.isFullSet())
7139 return {ConstantRange::getFull(BitWidth), false};
7140
7141 // If Step is signed and negative, then we use its absolute value, but we also
7142 // note that we're moving in the opposite direction.
7143 bool Descending = Signed && Step.isNegative();
7144
7145 if (Signed)
7146 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
7147 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
7148 // This equations hold true due to the well-defined wrap-around behavior of
7149 // APInt.
7150 Step = Step.abs();
7151
7152 // Check if Offset is more than full span of BitWidth. If it is, the
7153 // expression is guaranteed to overflow.
7154 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
7155 return {ConstantRange::getFull(BitWidth), false};
7156
7157 // Offset is by how much the expression can change. Checks above guarantee no
7158 // overflow here.
7159 APInt Offset = Step * MaxBECount;
7160
7161 // Minimum value of the final range will match the minimal value of StartRange
7162 // if the expression is increasing and will be decreased by Offset otherwise.
7163 // Maximum value of the final range will match the maximal value of StartRange
7164 // if the expression is decreasing and will be increased by Offset otherwise.
7165 APInt StartLower = StartRange.getLower();
7166 APInt StartUpper = StartRange.getUpper() - 1;
7167 bool Overflow;
7168 APInt MovedBoundary;
7169 if (Signed) {
7170 // This does not use sadd_ov, as we want to check overflow for a signed
7171 // start with an unsigned offset.
7172 if (Descending) {
7173 MovedBoundary = StartLower - std::move(Offset);
7174 Overflow = MovedBoundary.sgt(StartLower) || StartRange.isSignWrappedSet();
7175 } else {
7176 MovedBoundary = StartUpper + std::move(Offset);
7177 Overflow = MovedBoundary.slt(StartUpper) || StartRange.isSignWrappedSet();
7178 }
7179 } else {
7180 MovedBoundary = StartUpper.uadd_ov(std::move(Offset), Overflow);
7181 Overflow |= StartRange.isWrappedSet();
7182 }
7183
7184 // It's possible that the new minimum/maximum value will fall into the initial
7185 // range (due to wrap around). This means that the expression can take any
7186 // value in this bitwidth, and we have to return full range.
7187 if (StartRange.contains(MovedBoundary))
7188 return {ConstantRange::getFull(BitWidth), false};
7189
7190 APInt NewLower =
7191 Descending ? std::move(MovedBoundary) : std::move(StartLower);
7192 APInt NewUpper =
7193 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
7194 NewUpper += 1;
7195
7196 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
7197 return {ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)),
7198 !Overflow};
7199}
7200
7201std::pair<ConstantRange, SCEV::NoWrapFlags>
7202ScalarEvolution::getRangeForAffineAR(const SCEV *Start, const SCEV *Step,
7203 const APInt &MaxBECount) {
7204 assert(getTypeSizeInBits(Start->getType()) ==
7205 getTypeSizeInBits(Step->getType()) &&
7206 getTypeSizeInBits(Start->getType()) == MaxBECount.getBitWidth() &&
7207 "mismatched bit widths");
7208
7209 // First, consider step signed.
7210 ConstantRange StartSRange = getSignedRange(Start);
7211 ConstantRange StepSRange = getSignedRange(Step);
7212
7213 // If Step can be both positive and negative, we need to find ranges for the
7214 // maximum absolute step values in both directions and union them.
7215 auto [SR1, NSW1] = getRangeForAffineARHelper(
7216 StepSRange.getSignedMin(), StartSRange, MaxBECount, /*Signed=*/true);
7217 auto [SR2, NSW2] = getRangeForAffineARHelper(StepSRange.getSignedMax(),
7218 StartSRange, MaxBECount,
7219 /*Signed=*/true);
7220 ConstantRange SR = SR1.unionWith(SR2);
7221
7222 // Next, consider step unsigned.
7223 auto [UR, NUW] = getRangeForAffineARHelper(
7224 getUnsignedRangeMax(Step), getUnsignedRange(Start), MaxBECount,
7225 /*Signed=*/false);
7226
7228 if (NUW)
7230 if (NSW1 && NSW2)
7232
7233 // Finally, intersect signed and unsigned ranges.
7235}
7236
7237ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
7238 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
7239 ScalarEvolution::RangeSignHint SignHint) {
7240 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
7241 assert(AddRec->hasNoSelfWrap() &&
7242 "This only works for non-self-wrapping AddRecs!");
7243 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
7244 const SCEV *Step = AddRec->getStepRecurrence(*this);
7245 // Only deal with constant step to save compile time.
7246 if (!isa<SCEVConstant>(Step))
7247 return ConstantRange::getFull(BitWidth);
7248 // Let's make sure that we can prove that we do not self-wrap during
7249 // MaxBECount iterations. We need this because MaxBECount is a maximum
7250 // iteration count estimate, and we might infer nw from some exit for which we
7251 // do not know max exit count (or any other side reasoning).
7252 // TODO: Turn into assert at some point.
7253 if (getTypeSizeInBits(MaxBECount->getType()) >
7254 getTypeSizeInBits(AddRec->getType()))
7255 return ConstantRange::getFull(BitWidth);
7256 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
7257 const SCEV *RangeWidth = getMinusOne(AddRec->getType());
7258 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
7259 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
7260 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
7261 MaxItersWithoutWrap))
7262 return ConstantRange::getFull(BitWidth);
7263
7264 ICmpInst::Predicate LEPred =
7266 ICmpInst::Predicate GEPred =
7268 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7269
7270 // We know that there is no self-wrap. Let's take Start and End values and
7271 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7272 // the iteration. They either lie inside the range [Min(Start, End),
7273 // Max(Start, End)] or outside it:
7274 //
7275 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
7276 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
7277 //
7278 // No self wrap flag guarantees that the intermediate values cannot be BOTH
7279 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7280 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7281 // Start <= End and step is positive, or Start >= End and step is negative.
7282 const SCEV *Start = applyLoopGuards(AddRec->getStart(), AddRec->getLoop());
7283 ConstantRange StartRange = getRangeRef(Start, SignHint);
7284 ConstantRange EndRange = getRangeRef(End, SignHint);
7285 ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7286 // If they already cover full iteration space, we will know nothing useful
7287 // even if we prove what we want to prove.
7288 if (RangeBetween.isFullSet())
7289 return RangeBetween;
7290 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7291 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7292 : RangeBetween.isWrappedSet();
7293 if (IsWrappedSet)
7294 return ConstantRange::getFull(BitWidth);
7295
7296 if (isKnownPositive(Step) &&
7297 isKnownPredicateViaConstantRanges(LEPred, Start, End))
7298 return RangeBetween;
7299 if (isKnownNegative(Step) &&
7300 isKnownPredicateViaConstantRanges(GEPred, Start, End))
7301 return RangeBetween;
7302 return ConstantRange::getFull(BitWidth);
7303}
7304
7305ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7306 const SCEV *Step,
7307 const APInt &MaxBECount) {
7308 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7309 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7310
7311 unsigned BitWidth = MaxBECount.getBitWidth();
7312 assert(getTypeSizeInBits(Start->getType()) == BitWidth &&
7313 getTypeSizeInBits(Step->getType()) == BitWidth &&
7314 "mismatched bit widths");
7315
7316 struct SelectPattern {
7317 Value *Condition = nullptr;
7318 APInt TrueValue;
7319 APInt FalseValue;
7320
7321 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7322 const SCEV *S) {
7323 std::optional<unsigned> CastOp;
7324 APInt Offset(BitWidth, 0);
7325
7327 "Should be!");
7328
7329 // Peel off a constant offset. In the future we could consider being
7330 // smarter here and handle {Start+Step,+,Step} too.
7331 const APInt *Off;
7332 if (match(S, m_scev_Add(m_scev_APInt(Off), m_SCEV(S))))
7333 Offset = *Off;
7334
7335 // Peel off a cast operation
7336 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7337 CastOp = SCast->getSCEVType();
7338 S = SCast->getOperand();
7339 }
7340
7341 using namespace llvm::PatternMatch;
7342
7343 auto *SU = dyn_cast<SCEVUnknown>(S);
7344 const APInt *TrueVal, *FalseVal;
7345 if (!SU ||
7346 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7347 m_APInt(FalseVal)))) {
7348 Condition = nullptr;
7349 return;
7350 }
7351
7352 TrueValue = *TrueVal;
7353 FalseValue = *FalseVal;
7354
7355 // Re-apply the cast we peeled off earlier
7356 if (CastOp)
7357 switch (*CastOp) {
7358 default:
7359 llvm_unreachable("Unknown SCEV cast type!");
7360
7361 case scTruncate:
7362 TrueValue = TrueValue.trunc(BitWidth);
7363 FalseValue = FalseValue.trunc(BitWidth);
7364 break;
7365 case scZeroExtend:
7366 TrueValue = TrueValue.zext(BitWidth);
7367 FalseValue = FalseValue.zext(BitWidth);
7368 break;
7369 case scSignExtend:
7370 TrueValue = TrueValue.sext(BitWidth);
7371 FalseValue = FalseValue.sext(BitWidth);
7372 break;
7373 }
7374
7375 // Re-apply the constant offset we peeled off earlier
7376 TrueValue += Offset;
7377 FalseValue += Offset;
7378 }
7379
7380 bool isRecognized() { return Condition != nullptr; }
7381 };
7382
7383 SelectPattern StartPattern(*this, BitWidth, Start);
7384 if (!StartPattern.isRecognized())
7385 return ConstantRange::getFull(BitWidth);
7386
7387 SelectPattern StepPattern(*this, BitWidth, Step);
7388 if (!StepPattern.isRecognized())
7389 return ConstantRange::getFull(BitWidth);
7390
7391 if (StartPattern.Condition != StepPattern.Condition) {
7392 // We don't handle this case today; but we could, by considering four
7393 // possibilities below instead of two. I'm not sure if there are cases where
7394 // that will help over what getRange already does, though.
7395 return ConstantRange::getFull(BitWidth);
7396 }
7397
7398 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7399 // construct arbitrary general SCEV expressions here. This function is called
7400 // from deep in the call stack, and calling getSCEV (on a sext instruction,
7401 // say) can end up caching a suboptimal value.
7402
7403 // FIXME: without the explicit `this` receiver below, MSVC errors out with
7404 // C2352 and C2512 (otherwise it isn't needed).
7405
7406 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7407 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7408 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7409 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7410
7411 ConstantRange TrueRange =
7412 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount).first;
7413 ConstantRange FalseRange =
7414 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount).first;
7415
7416 return TrueRange.unionWith(FalseRange);
7417}
7418
7419SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7420 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
7421 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7422
7423 // Return early if there are no flags to propagate to the SCEV.
7425 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(BinOp);
7426 PDI && PDI->isDisjoint()) {
7428 } else {
7429 if (BinOp->hasNoUnsignedWrap())
7431 if (BinOp->hasNoSignedWrap())
7433 }
7434 if (Flags == SCEV::FlagAnyWrap)
7435 return SCEV::FlagAnyWrap;
7436
7437 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
7438}
7439
7440const Instruction *
7441ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7442 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7443 return &*AddRec->getLoop()->getHeader()->begin();
7444 if (auto *U = dyn_cast<SCEVUnknown>(S))
7445 if (auto *I = dyn_cast<Instruction>(U->getValue()))
7446 return I;
7447 return nullptr;
7448}
7449
7450const Instruction *ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops,
7451 bool &Precise) {
7452 Precise = true;
7453 // Do a bounded search of the def relation of the requested SCEVs.
7454 SmallPtrSet<const SCEV *, 16> Visited;
7455 SmallVector<SCEVUse> Worklist;
7456 auto pushOp = [&](const SCEV *S) {
7457 if (!Visited.insert(S).second)
7458 return;
7459 // Threshold of 30 here is arbitrary.
7460 if (Visited.size() > 30) {
7461 Precise = false;
7462 return;
7463 }
7464 Worklist.push_back(S);
7465 };
7466
7467 for (SCEVUse S : Ops)
7468 pushOp(S);
7469
7470 const Instruction *Bound = nullptr;
7471 while (!Worklist.empty()) {
7472 SCEVUse S = Worklist.pop_back_val();
7473 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7474 if (!Bound || DT.dominates(Bound, DefI))
7475 Bound = DefI;
7476 } else {
7477 for (SCEVUse Op : S->operands())
7478 pushOp(Op);
7479 }
7480 }
7481 return Bound ? Bound : &*F.getEntryBlock().begin();
7482}
7483
7484const Instruction *
7485ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops) {
7486 bool Discard;
7487 return getDefiningScopeBound(Ops, Discard);
7488}
7489
7490bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7491 const Instruction *B) {
7492 if (A->getParent() == B->getParent() &&
7494 B->getIterator()))
7495 return true;
7496
7497 auto *BLoop = LI.getLoopFor(B->getParent());
7498 if (BLoop && BLoop->getHeader() == B->getParent() &&
7499 BLoop->getLoopPreheader() == A->getParent() &&
7501 A->getParent()->end()) &&
7502 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7503 B->getIterator()))
7504 return true;
7505 return false;
7506}
7507
7509 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ true);
7510 visitAll(Op, PC);
7511 return PC.MaybePoison.empty();
7512}
7513
7514bool ScalarEvolution::isGuaranteedNotToCauseUB(const SCEV *Op) {
7515 return !SCEVExprContains(Op, [this](const SCEV *S) {
7516 const SCEV *Op1;
7517 bool M = match(S, m_scev_UDiv(m_SCEV(), m_SCEV(Op1)));
7518 // The UDiv may be UB if the divisor is poison or zero. Unless the divisor
7519 // is a non-zero constant, we have to assume the UDiv may be UB.
7520 return M && (!isKnownNonZero(Op1) || !isGuaranteedNotToBePoison(Op1));
7521 });
7522}
7523
7524bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7525 // Only proceed if we can prove that I does not yield poison.
7527 return false;
7528
7529 // At this point we know that if I is executed, then it does not wrap
7530 // according to at least one of NSW or NUW. If I is not executed, then we do
7531 // not know if the calculation that I represents would wrap. Multiple
7532 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7533 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7534 // derived from other instructions that map to the same SCEV. We cannot make
7535 // that guarantee for cases where I is not executed. So we need to find a
7536 // upper bound on the defining scope for the SCEV, and prove that I is
7537 // executed every time we enter that scope. When the bounding scope is a
7538 // loop (the common case), this is equivalent to proving I executes on every
7539 // iteration of that loop.
7540 SmallVector<SCEVUse> SCEVOps;
7541 for (const Use &Op : I->operands()) {
7542 // I could be an extractvalue from a call to an overflow intrinsic.
7543 // TODO: We can do better here in some cases.
7544 if (isSCEVable(Op->getType()))
7545 SCEVOps.push_back(getSCEV(Op));
7546 }
7547 auto *DefI = getDefiningScopeBound(SCEVOps);
7548 return isGuaranteedToTransferExecutionTo(DefI, I);
7549}
7550
7551bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7552 // If we know that \c I can never be poison period, then that's enough.
7553 if (isSCEVExprNeverPoison(I))
7554 return true;
7555
7556 // If the loop only has one exit, then we know that, if the loop is entered,
7557 // any instruction dominating that exit will be executed. If any such
7558 // instruction would result in UB, the addrec cannot be poison.
7559 //
7560 // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7561 // also handles uses outside the loop header (they just need to dominate the
7562 // single exit).
7563
7564 auto *ExitingBB = L->getExitingBlock();
7565 if (!ExitingBB || !loopHasNoAbnormalExits(L))
7566 return false;
7567
7568 SmallPtrSet<const Value *, 16> KnownPoison;
7570
7571 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
7572 // things that are known to be poison under that assumption go on the
7573 // Worklist.
7574 KnownPoison.insert(I);
7575 Worklist.push_back(I);
7576
7577 while (!Worklist.empty()) {
7578 const Instruction *Poison = Worklist.pop_back_val();
7579
7580 for (const Use &U : Poison->uses()) {
7581 const Instruction *PoisonUser = cast<Instruction>(U.getUser());
7582 if (mustTriggerUB(PoisonUser, KnownPoison) &&
7583 DT.dominates(PoisonUser->getParent(), ExitingBB))
7584 return true;
7585
7586 if (propagatesPoison(U) && L->contains(PoisonUser))
7587 if (KnownPoison.insert(PoisonUser).second)
7588 Worklist.push_back(PoisonUser);
7589 }
7590 }
7591
7592 return false;
7593}
7594
7595ScalarEvolution::LoopProperties
7596ScalarEvolution::getLoopProperties(const Loop *L) {
7597 using LoopProperties = ScalarEvolution::LoopProperties;
7598
7599 auto Itr = LoopPropertiesCache.find(L);
7600 if (Itr == LoopPropertiesCache.end()) {
7601 auto HasSideEffects = [](Instruction *I) {
7602 if (auto *SI = dyn_cast<StoreInst>(I))
7603 return !SI->isSimple();
7604
7605 if (I->mayThrow())
7606 return true;
7607
7608 // Non-volatile memset / memcpy do not count as side-effect for forward
7609 // progress.
7610 if (isa<MemIntrinsic>(I) && !I->isVolatile())
7611 return false;
7612
7613 return I->mayWriteToMemory();
7614 };
7615
7616 LoopProperties LP = {/* HasNoAbnormalExits */ true,
7617 /*HasNoSideEffects*/ true};
7618
7619 for (auto *BB : L->getBlocks())
7620 for (auto &I : *BB) {
7622 LP.HasNoAbnormalExits = false;
7623 if (HasSideEffects(&I))
7624 LP.HasNoSideEffects = false;
7625 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7626 break; // We're already as pessimistic as we can get.
7627 }
7628
7629 auto InsertPair = LoopPropertiesCache.insert({L, LP});
7630 assert(InsertPair.second && "We just checked!");
7631 Itr = InsertPair.first;
7632 }
7633
7634 return Itr->second;
7635}
7636
7638 // A mustprogress loop without side effects must be finite.
7639 // TODO: The check used here is very conservative. It's only *specific*
7640 // side effects which are well defined in infinite loops.
7641 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7642}
7643
7644const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7645 // Worklist item with a Value and a bool indicating whether all operands have
7646 // been visited already.
7649
7650 Stack.emplace_back(V, false);
7651 while (!Stack.empty()) {
7652 auto E = Stack.back();
7653 Value *CurV = E.getPointer();
7654
7655 if (getExistingSCEV(CurV)) {
7656 Stack.pop_back();
7657 continue;
7658 }
7659
7661 const SCEV *CreatedSCEV = nullptr;
7662 // If all operands have been visited already, create the SCEV.
7663 if (E.getInt()) {
7664 CreatedSCEV = createSCEV(CurV);
7665 } else {
7666 // Otherwise get the operands we need to create SCEV's for before creating
7667 // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7668 // just use it.
7669 CreatedSCEV = getOperandsToCreate(CurV, Ops);
7670 }
7671
7672 if (CreatedSCEV) {
7673 insertValueToMap(CurV, CreatedSCEV);
7674 Stack.pop_back();
7675 } else {
7676 Stack.back().setInt(true);
7677 // Queue its operands which need to be constructed.
7678 for (Value *Op : Ops)
7679 Stack.emplace_back(Op, false);
7680 }
7681 }
7682
7683 return getExistingSCEV(V);
7684}
7685
7686const SCEV *
7687ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7688 if (!isSCEVable(V->getType()))
7689 return getUnknown(V);
7690
7691 if (Instruction *I = dyn_cast<Instruction>(V)) {
7692 // Don't attempt to analyze instructions in blocks that aren't
7693 // reachable. Such instructions don't matter, and they aren't required
7694 // to obey basic rules for definitions dominating uses which this
7695 // analysis depends on.
7696 if (!DT.isReachableFromEntry(I->getParent()))
7697 return getUnknown(PoisonValue::get(V->getType()));
7698 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7699 return getConstant(CI);
7700 else if (isa<GlobalAlias>(V))
7701 return getUnknown(V);
7702 else if (!isa<ConstantExpr>(V))
7703 return getUnknown(V);
7704
7706 if (auto BO =
7708 bool IsConstArg = isa<ConstantInt>(BO->RHS);
7709 switch (BO->Opcode) {
7710 case Instruction::Add:
7711 case Instruction::Mul: {
7712 // For additions and multiplications, traverse add/mul chains for which we
7713 // can potentially create a single SCEV, to reduce the number of
7714 // get{Add,Mul}Expr calls.
7715 do {
7716 if (BO->Op) {
7717 if (BO->Op != V && getExistingSCEV(BO->Op)) {
7718 Ops.push_back(BO->Op);
7719 break;
7720 }
7721 }
7722 Ops.push_back(BO->RHS);
7723 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7725 if (!NewBO ||
7726 (BO->Opcode == Instruction::Add &&
7727 (NewBO->Opcode != Instruction::Add &&
7728 NewBO->Opcode != Instruction::Sub)) ||
7729 (BO->Opcode == Instruction::Mul &&
7730 NewBO->Opcode != Instruction::Mul)) {
7731 Ops.push_back(BO->LHS);
7732 break;
7733 }
7734 // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7735 // requires a SCEV for the LHS.
7736 if (BO->Op && (BO->IsNSW || BO->IsNUW)) {
7737 auto *I = dyn_cast<Instruction>(BO->Op);
7738 if (I && programUndefinedIfPoison(I)) {
7739 Ops.push_back(BO->LHS);
7740 break;
7741 }
7742 }
7743 BO = NewBO;
7744 } while (true);
7745 return nullptr;
7746 }
7747 case Instruction::Sub:
7748 case Instruction::UDiv:
7749 case Instruction::URem:
7750 break;
7751 case Instruction::AShr:
7752 case Instruction::Shl:
7753 case Instruction::Xor:
7754 if (!IsConstArg)
7755 return nullptr;
7756 break;
7757 case Instruction::And:
7758 case Instruction::Or:
7759 if (!IsConstArg && !BO->LHS->getType()->isIntegerTy(1))
7760 return nullptr;
7761 break;
7762 case Instruction::LShr:
7763 return getUnknown(V);
7764 default:
7765 llvm_unreachable("Unhandled binop");
7766 break;
7767 }
7768
7769 Ops.push_back(BO->LHS);
7770 Ops.push_back(BO->RHS);
7771 return nullptr;
7772 }
7773
7774 switch (U->getOpcode()) {
7775 case Instruction::Trunc:
7776 case Instruction::ZExt:
7777 case Instruction::SExt:
7778 case Instruction::PtrToAddr:
7779 case Instruction::PtrToInt:
7780 Ops.push_back(U->getOperand(0));
7781 return nullptr;
7782
7783 case Instruction::BitCast:
7784 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
7785 Ops.push_back(U->getOperand(0));
7786 return nullptr;
7787 }
7788 return getUnknown(V);
7789
7790 case Instruction::SDiv:
7791 case Instruction::SRem:
7792 Ops.push_back(U->getOperand(0));
7793 Ops.push_back(U->getOperand(1));
7794 return nullptr;
7795
7796 case Instruction::GetElementPtr:
7797 assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7798 "GEP source element type must be sized");
7799 llvm::append_range(Ops, U->operands());
7800 return nullptr;
7801
7802 case Instruction::IntToPtr:
7803 return getUnknown(V);
7804
7805 case Instruction::PHI:
7806 // getNodeForPHI has four ways to turn a PHI into a SCEV; retrieve the
7807 // relevant nodes for each of them.
7808 //
7809 // The first is just to call simplifyInstruction, and get something back
7810 // that isn't a PHI.
7811 if (Value *V = simplifyInstruction(
7812 cast<PHINode>(U),
7813 {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
7814 /*UseInstrInfo=*/true, /*CanUseUndef=*/false})) {
7815 assert(V);
7816 Ops.push_back(V);
7817 return nullptr;
7818 }
7819 // The second is createNodeForPHIWithIdenticalOperands: this looks for
7820 // operands which all perform the same operation, but haven't been
7821 // CSE'ed for whatever reason.
7822 if (BinaryOperator *BO = getCommonInstForPHI(cast<PHINode>(U))) {
7823 assert(BO);
7824 Ops.push_back(BO);
7825 return nullptr;
7826 }
7827 // The third is createNodeFromSelectLikePHI; this takes a PHI which
7828 // is equivalent to a select, and analyzes it like a select.
7829 {
7830 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
7832 assert(Cond);
7833 assert(LHS);
7834 assert(RHS);
7835 if (auto *CondICmp = dyn_cast<ICmpInst>(Cond)) {
7836 Ops.push_back(CondICmp->getOperand(0));
7837 Ops.push_back(CondICmp->getOperand(1));
7838 }
7839 Ops.push_back(Cond);
7840 Ops.push_back(LHS);
7841 Ops.push_back(RHS);
7842 return nullptr;
7843 }
7844 }
7845 // The fourth way is createAddRecFromPHI. It's complicated to handle here,
7846 // so just construct it recursively.
7847 //
7848 // In addition to getNodeForPHI, also construct nodes which might be needed
7849 // by getRangeRef.
7851 for (Value *V : cast<PHINode>(U)->operands())
7852 Ops.push_back(V);
7853 return nullptr;
7854 }
7855 return nullptr;
7856
7857 case Instruction::Select: {
7858 // Check if U is a select that can be simplified to a SCEVUnknown.
7859 auto CanSimplifyToUnknown = [this, U]() {
7860 if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
7861 return false;
7862
7863 auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
7864 if (!ICI)
7865 return false;
7866 Value *LHS = ICI->getOperand(0);
7867 Value *RHS = ICI->getOperand(1);
7868 if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7869 ICI->getPredicate() == CmpInst::ICMP_NE) {
7871 return true;
7872 } else if (getTypeSizeInBits(LHS->getType()) >
7873 getTypeSizeInBits(U->getType()))
7874 return true;
7875 return false;
7876 };
7877 if (CanSimplifyToUnknown())
7878 return getUnknown(U);
7879
7880 llvm::append_range(Ops, U->operands());
7881 return nullptr;
7882 break;
7883 }
7884 case Instruction::Call:
7885 case Instruction::Invoke:
7886 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7887 Ops.push_back(RV);
7888 return nullptr;
7889 }
7890
7891 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7892 switch (II->getIntrinsicID()) {
7893 case Intrinsic::abs:
7894 Ops.push_back(II->getArgOperand(0));
7895 return nullptr;
7896 case Intrinsic::umax:
7897 case Intrinsic::umin:
7898 case Intrinsic::smax:
7899 case Intrinsic::smin:
7900 case Intrinsic::usub_sat:
7901 case Intrinsic::uadd_sat:
7902 Ops.push_back(II->getArgOperand(0));
7903 Ops.push_back(II->getArgOperand(1));
7904 return nullptr;
7905 case Intrinsic::start_loop_iterations:
7906 case Intrinsic::annotation:
7907 case Intrinsic::ptr_annotation:
7908 Ops.push_back(II->getArgOperand(0));
7909 return nullptr;
7910 default:
7911 break;
7912 }
7913 }
7914 break;
7915 }
7916
7917 return nullptr;
7918}
7919
7920const SCEV *ScalarEvolution::createSCEV(Value *V) {
7921 if (!isSCEVable(V->getType()))
7922 return getUnknown(V);
7923
7924 if (Instruction *I = dyn_cast<Instruction>(V)) {
7925 // Don't attempt to analyze instructions in blocks that aren't
7926 // reachable. Such instructions don't matter, and they aren't required
7927 // to obey basic rules for definitions dominating uses which this
7928 // analysis depends on.
7929 if (!DT.isReachableFromEntry(I->getParent()))
7930 return getUnknown(PoisonValue::get(V->getType()));
7931 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7932 return getConstant(CI);
7933 else if (isa<GlobalAlias>(V))
7934 return getUnknown(V);
7935 else if (!isa<ConstantExpr>(V))
7936 return getUnknown(V);
7937
7938 const SCEV *LHS;
7939 const SCEV *RHS;
7940
7942 if (auto BO =
7944 switch (BO->Opcode) {
7945 case Instruction::Add: {
7946 // The simple thing to do would be to just call getSCEV on both operands
7947 // and call getAddExpr with the result. However if we're looking at a
7948 // bunch of things all added together, this can be quite inefficient,
7949 // because it leads to N-1 getAddExpr calls for N ultimate operands.
7950 // Instead, gather up all the operands and make a single getAddExpr call.
7951 // LLVM IR canonical form means we need only traverse the left operands.
7953 do {
7954 if (BO->Op) {
7955 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7956 AddOps.push_back(OpSCEV);
7957 break;
7958 }
7959
7960 // If a NUW or NSW flag can be applied to the SCEV for this
7961 // addition, then compute the SCEV for this addition by itself
7962 // with a separate call to getAddExpr. We need to do that
7963 // instead of pushing the operands of the addition onto AddOps,
7964 // since the flags are only known to apply to this particular
7965 // addition - they may not apply to other additions that can be
7966 // formed with operands from AddOps.
7967 const SCEV *RHS = getSCEV(BO->RHS);
7968 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7969 if (Flags != SCEV::FlagAnyWrap) {
7970 const SCEV *LHS = getSCEV(BO->LHS);
7971 if (BO->Opcode == Instruction::Sub)
7972 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7973 else
7974 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7975 break;
7976 }
7977 }
7978
7979 if (BO->Opcode == Instruction::Sub)
7980 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7981 else
7982 AddOps.push_back(getSCEV(BO->RHS));
7983
7984 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7986 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7987 NewBO->Opcode != Instruction::Sub)) {
7988 AddOps.push_back(getSCEV(BO->LHS));
7989 break;
7990 }
7991 BO = NewBO;
7992 } while (true);
7993
7994 return getAddExpr(AddOps);
7995 }
7996
7997 case Instruction::Mul: {
7999 do {
8000 if (BO->Op) {
8001 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
8002 MulOps.push_back(OpSCEV);
8003 break;
8004 }
8005
8006 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
8007 if (Flags != SCEV::FlagAnyWrap) {
8008 LHS = getSCEV(BO->LHS);
8009 RHS = getSCEV(BO->RHS);
8010 MulOps.push_back(getMulExpr(LHS, RHS, Flags));
8011 break;
8012 }
8013 }
8014
8015 MulOps.push_back(getSCEV(BO->RHS));
8016 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
8018 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
8019 MulOps.push_back(getSCEV(BO->LHS));
8020 break;
8021 }
8022 BO = NewBO;
8023 } while (true);
8024
8025 return getMulExpr(MulOps);
8026 }
8027 case Instruction::UDiv:
8028 LHS = getSCEV(BO->LHS);
8029 RHS = getSCEV(BO->RHS);
8030 return getUDivExpr(LHS, RHS);
8031 case Instruction::URem:
8032 LHS = getSCEV(BO->LHS);
8033 RHS = getSCEV(BO->RHS);
8034 return getURemExpr(LHS, RHS);
8035 case Instruction::Sub: {
8037 if (BO->Op)
8038 Flags = getNoWrapFlagsFromUB(BO->Op);
8039
8040 // Try to use ptrtoaddr for subtracts with at least one ptrtoint
8041 // operand. While we don't model ptrtoint directly in SCEV, the
8042 // difference between two pointer addresses is well-defined.
8043 Value *PtrLHS = nullptr, *PtrRHS = nullptr;
8044 bool HasPtrLHS = match(BO->LHS, m_PtrToInt(m_Value(PtrLHS)));
8045 bool HasPtrRHS = match(BO->RHS, m_PtrToInt(m_Value(PtrRHS)));
8046 if (HasPtrLHS || HasPtrRHS) {
8047 // Convert a ptrtoint operand (OrigOp) to ptrtoaddr of its pointer
8048 // PtrOp. When only one side is ptrtoint (BothPtr is false), skip
8049 // SCEVUnknown pointers since wrapping them in ptrtoaddr adds no
8050 // useful structure.
8051 auto GetOp = [&](bool HasPtr, Value *PtrOp, Value *OrigOp,
8052 bool BothPtr) -> const SCEV * {
8053 if (!HasPtr)
8054 return getSCEV(OrigOp);
8055 const SCEV *PtrSCEV = getSCEV(PtrOp);
8056 if (BothPtr || !isa<SCEVUnknown>(PtrSCEV)) {
8057 const SCEV *Addr = getPtrToAddrExpr(PtrSCEV);
8058 if (!isa<SCEVCouldNotCompute>(Addr) &&
8059 getTypeSizeInBits(OrigOp->getType()) <=
8060 getTypeSizeInBits(Addr->getType()))
8061 return getTruncateOrNoop(Addr, OrigOp->getType());
8062 }
8063 return getSCEV(OrigOp);
8064 };
8065 const SCEV *L = GetOp(HasPtrLHS, PtrLHS, BO->LHS, HasPtrRHS);
8066 const SCEV *R = GetOp(HasPtrRHS, PtrRHS, BO->RHS, HasPtrLHS);
8067 return getMinusSCEV(L, R, Flags);
8068 }
8069
8070 LHS = getSCEV(BO->LHS);
8071 RHS = getSCEV(BO->RHS);
8072 return getMinusSCEV(LHS, RHS, Flags);
8073 }
8074 case Instruction::And:
8075 // For an expression like x&255 that merely masks off the high bits,
8076 // use zext(trunc(x)) as the SCEV expression.
8077 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
8078 if (CI->isZero())
8079 return getSCEV(BO->RHS);
8080 if (CI->isMinusOne())
8081 return getSCEV(BO->LHS);
8082 const APInt &A = CI->getValue();
8083
8084 // Instcombine's ShrinkDemandedConstant may strip bits out of
8085 // constants, obscuring what would otherwise be a low-bits mask.
8086 // Use computeKnownBits to compute what ShrinkDemandedConstant
8087 // knew about to reconstruct a low-bits mask value.
8088 unsigned LZ = A.countl_zero();
8089 unsigned TZ = A.countr_zero();
8090 unsigned BitWidth = A.getBitWidth();
8091 KnownBits Known(BitWidth);
8092 computeKnownBits(BO->LHS, Known, getDataLayout(), &AC, nullptr, &DT);
8093
8094 APInt EffectiveMask =
8095 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
8096 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
8097 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
8098 const SCEV *LHS = getSCEV(BO->LHS);
8099 const SCEV *ShiftedLHS = nullptr;
8100 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
8101 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
8102 // For an expression like (x * 8) & 8, simplify the multiply.
8103 unsigned MulZeros = OpC->getAPInt().countr_zero();
8104 unsigned GCD = std::min(MulZeros, TZ);
8105 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
8107 MulOps.push_back(getConstant(OpC->getAPInt().ashr(GCD)));
8108 append_range(MulOps, LHSMul->operands().drop_front());
8109 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
8110 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
8111 }
8112 }
8113 if (!ShiftedLHS)
8114 ShiftedLHS = getUDivExpr(LHS, MulCount);
8115 return getMulExpr(
8117 getTruncateExpr(ShiftedLHS,
8118 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
8119 BO->LHS->getType()),
8120 MulCount);
8121 }
8122 }
8123 // Binary `and` is a bit-wise `umin`.
8124 if (BO->LHS->getType()->isIntegerTy(1)) {
8125 LHS = getSCEV(BO->LHS);
8126 RHS = getSCEV(BO->RHS);
8127 return getUMinExpr(LHS, RHS);
8128 }
8129 break;
8130
8131 case Instruction::Or:
8132 // Binary `or` is a bit-wise `umax`.
8133 if (BO->LHS->getType()->isIntegerTy(1)) {
8134 LHS = getSCEV(BO->LHS);
8135 RHS = getSCEV(BO->RHS);
8136 return getUMaxExpr(LHS, RHS);
8137 }
8138 break;
8139
8140 case Instruction::Xor:
8141 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
8142 // If the RHS of xor is -1, then this is a not operation.
8143 if (CI->isMinusOne())
8144 return getNotSCEV(getSCEV(BO->LHS));
8145
8146 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
8147 // This is a variant of the check for xor with -1, and it handles
8148 // the case where instcombine has trimmed non-demanded bits out
8149 // of an xor with -1.
8150 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
8151 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
8152 if (LBO->getOpcode() == Instruction::And &&
8153 LCI->getValue() == CI->getValue())
8154 if (const SCEVZeroExtendExpr *Z =
8156 Type *UTy = BO->LHS->getType();
8157 const SCEV *Z0 = Z->getOperand();
8158 Type *Z0Ty = Z0->getType();
8159 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
8160
8161 // If C is a low-bits mask, the zero extend is serving to
8162 // mask off the high bits. Complement the operand and
8163 // re-apply the zext.
8164 if (CI->getValue().isMask(Z0TySize))
8165 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
8166
8167 // If C is a single bit, it may be in the sign-bit position
8168 // before the zero-extend. In this case, represent the xor
8169 // using an add, which is equivalent, and re-apply the zext.
8170 APInt Trunc = CI->getValue().trunc(Z0TySize);
8171 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
8172 Trunc.isSignMask())
8173 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
8174 UTy);
8175 }
8176 }
8177 break;
8178
8179 case Instruction::Shl:
8180 // Turn shift left of a constant amount into a multiply.
8181 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
8182 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
8183
8184 // If the shift count is not less than the bitwidth, the result of
8185 // the shift is undefined. Don't try to analyze it, because the
8186 // resolution chosen here may differ from the resolution chosen in
8187 // other parts of the compiler.
8188 if (SA->getValue().uge(BitWidth))
8189 break;
8190
8191 // We can safely preserve the nuw flag in all cases. It's also safe to
8192 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
8193 // requires special handling. It can be preserved as long as we're not
8194 // left shifting by bitwidth - 1.
8195 auto Flags = SCEV::FlagAnyWrap;
8196 if (BO->Op) {
8197 auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
8198 if (any(MulFlags & SCEV::FlagNSW) &&
8199 (any(MulFlags & SCEV::FlagNUW) ||
8200 SA->getValue().ult(BitWidth - 1)))
8202 if (any(MulFlags & SCEV::FlagNUW))
8204 }
8205
8206 ConstantInt *X = ConstantInt::get(
8207 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
8208 return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
8209 }
8210 break;
8211
8212 case Instruction::AShr:
8213 // AShr X, C, where C is a constant.
8214 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
8215 if (!CI)
8216 break;
8217
8218 Type *OuterTy = BO->LHS->getType();
8219 uint64_t BitWidth = getTypeSizeInBits(OuterTy);
8220 // If the shift count is not less than the bitwidth, the result of
8221 // the shift is undefined. Don't try to analyze it, because the
8222 // resolution chosen here may differ from the resolution chosen in
8223 // other parts of the compiler.
8224 if (CI->getValue().uge(BitWidth))
8225 break;
8226
8227 if (CI->isZero())
8228 return getSCEV(BO->LHS); // shift by zero --> noop
8229
8230 uint64_t AShrAmt = CI->getZExtValue();
8231 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
8232
8233 Operator *L = dyn_cast<Operator>(BO->LHS);
8234 const SCEV *AddTruncateExpr = nullptr;
8235 ConstantInt *ShlAmtCI = nullptr;
8236 const SCEV *AddConstant = nullptr;
8237
8238 if (L && L->getOpcode() == Instruction::Add) {
8239 // X = Shl A, n
8240 // Y = Add X, c
8241 // Z = AShr Y, m
8242 // n, c and m are constants.
8243
8244 Operator *LShift = dyn_cast<Operator>(L->getOperand(0));
8245 ConstantInt *AddOperandCI = dyn_cast<ConstantInt>(L->getOperand(1));
8246 if (LShift && LShift->getOpcode() == Instruction::Shl) {
8247 if (AddOperandCI) {
8248 const SCEV *ShlOp0SCEV = getSCEV(LShift->getOperand(0));
8249 ShlAmtCI = dyn_cast<ConstantInt>(LShift->getOperand(1));
8250 // since we truncate to TruncTy, the AddConstant should be of the
8251 // same type, so create a new Constant with type same as TruncTy.
8252 // Also, the Add constant should be shifted right by AShr amount.
8253 APInt AddOperand = AddOperandCI->getValue().ashr(AShrAmt);
8254 AddConstant = getConstant(AddOperand.trunc(BitWidth - AShrAmt));
8255 // we model the expression as sext(add(trunc(A), c << n)), since the
8256 // sext(trunc) part is already handled below, we create a
8257 // AddExpr(TruncExp) which will be used later.
8258 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8259 }
8260 }
8261 } else if (L && L->getOpcode() == Instruction::Shl) {
8262 // X = Shl A, n
8263 // Y = AShr X, m
8264 // Both n and m are constant.
8265
8266 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
8267 ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
8268 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8269 }
8270
8271 if (AddTruncateExpr && ShlAmtCI) {
8272 // We can merge the two given cases into a single SCEV statement,
8273 // incase n = m, the mul expression will be 2^0, so it gets resolved to
8274 // a simpler case. The following code handles the two cases:
8275 //
8276 // 1) For a two-shift sext-inreg, i.e. n = m,
8277 // use sext(trunc(x)) as the SCEV expression.
8278 //
8279 // 2) When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
8280 // expression. We already checked that ShlAmt < BitWidth, so
8281 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
8282 // ShlAmt - AShrAmt < Amt.
8283 const APInt &ShlAmt = ShlAmtCI->getValue();
8284 if (ShlAmt.ult(BitWidth) && ShlAmt.uge(AShrAmt)) {
8285 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
8286 ShlAmtCI->getZExtValue() - AShrAmt);
8287 const SCEV *CompositeExpr =
8288 getMulExpr(AddTruncateExpr, getConstant(Mul));
8289 if (L->getOpcode() != Instruction::Shl)
8290 CompositeExpr = getAddExpr(CompositeExpr, AddConstant);
8291
8292 return getSignExtendExpr(CompositeExpr, OuterTy);
8293 }
8294 }
8295 break;
8296 }
8297 }
8298
8299 switch (U->getOpcode()) {
8300 case Instruction::Trunc:
8301 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
8302
8303 case Instruction::ZExt:
8304 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8305
8306 case Instruction::SExt:
8307 if (auto BO = MatchBinaryOp(U->getOperand(0), getDataLayout(), AC, DT,
8309 // The NSW flag of a subtract does not always survive the conversion to
8310 // A + (-1)*B. By pushing sign extension onto its operands we are much
8311 // more likely to preserve NSW and allow later AddRec optimisations.
8312 //
8313 // NOTE: This is effectively duplicating this logic from getSignExtend:
8314 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
8315 // but by that point the NSW information has potentially been lost.
8316 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
8317 Type *Ty = U->getType();
8318 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
8319 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
8320 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
8321 }
8322 }
8323 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8324
8325 case Instruction::BitCast:
8326 // BitCasts are no-op casts so we just eliminate the cast.
8327 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
8328 return getSCEV(U->getOperand(0));
8329 break;
8330
8331 case Instruction::PtrToAddr: {
8332 const SCEV *IntOp = getPtrToAddrExpr(getSCEV(U->getOperand(0)));
8333 if (isa<SCEVCouldNotCompute>(IntOp))
8334 return getUnknown(V);
8335 return IntOp;
8336 }
8337
8338 case Instruction::PtrToInt: {
8339 // Keep ptrtoint as SCEVUnknown, except when the pointer operand has SCEV
8340 // structure (e.g. a pointer add-rec or an offset from a known base). In
8341 // that case model it via ptrtoaddr to preserve the integer structure
8342 // (induction, constant folding). A bare SCEVUnknown pointer gains no
8343 // structure from wrapping it in ptrtoaddr, so leave it opaque.
8344 const SCEV *PtrSCEV = getSCEV(U->getOperand(0));
8345 if (!isa<SCEVUnknown>(PtrSCEV)) {
8346 const SCEV *Addr = getPtrToAddrExpr(PtrSCEV);
8347 if (!isa<SCEVCouldNotCompute>(Addr) &&
8348 getTypeSizeInBits(V->getType()) <= getTypeSizeInBits(Addr->getType()))
8349 return getTruncateOrNoop(Addr, V->getType());
8350 }
8351 return getUnknown(V);
8352 }
8353 case Instruction::IntToPtr:
8354 // Just don't deal with inttoptr casts.
8355 return getUnknown(V);
8356
8357 case Instruction::SDiv:
8358 // If both operands are non-negative, this is just an udiv.
8359 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8360 isKnownNonNegative(getSCEV(U->getOperand(1))))
8361 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8362 break;
8363
8364 case Instruction::SRem:
8365 // If both operands are non-negative, this is just an urem.
8366 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8367 isKnownNonNegative(getSCEV(U->getOperand(1))))
8368 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8369 break;
8370
8371 case Instruction::GetElementPtr:
8372 return createNodeForGEP(cast<GEPOperator>(U));
8373
8374 case Instruction::PHI:
8375 return createNodeForPHI(cast<PHINode>(U));
8376
8377 case Instruction::Select:
8378 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
8379 U->getOperand(2));
8380
8381 case Instruction::Call:
8382 case Instruction::Invoke:
8383 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
8384 return getSCEV(RV);
8385
8386 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
8387 switch (II->getIntrinsicID()) {
8388 case Intrinsic::abs:
8389 return getAbsExpr(
8390 getSCEV(II->getArgOperand(0)),
8391 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
8392 case Intrinsic::umax:
8393 LHS = getSCEV(II->getArgOperand(0));
8394 RHS = getSCEV(II->getArgOperand(1));
8395 return getUMaxExpr(LHS, RHS);
8396 case Intrinsic::umin:
8397 LHS = getSCEV(II->getArgOperand(0));
8398 RHS = getSCEV(II->getArgOperand(1));
8399 return getUMinExpr(LHS, RHS);
8400 case Intrinsic::smax:
8401 LHS = getSCEV(II->getArgOperand(0));
8402 RHS = getSCEV(II->getArgOperand(1));
8403 return getSMaxExpr(LHS, RHS);
8404 case Intrinsic::smin:
8405 LHS = getSCEV(II->getArgOperand(0));
8406 RHS = getSCEV(II->getArgOperand(1));
8407 return getSMinExpr(LHS, RHS);
8408 case Intrinsic::usub_sat: {
8409 const SCEV *X = getSCEV(II->getArgOperand(0));
8410 const SCEV *Y = getSCEV(II->getArgOperand(1));
8411 const SCEV *ClampedY = getUMinExpr(X, Y);
8412 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
8413 }
8414 case Intrinsic::uadd_sat: {
8415 const SCEV *X = getSCEV(II->getArgOperand(0));
8416 const SCEV *Y = getSCEV(II->getArgOperand(1));
8417 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
8418 return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
8419 }
8420 case Intrinsic::start_loop_iterations:
8421 case Intrinsic::annotation:
8422 case Intrinsic::ptr_annotation:
8423 // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8424 // just eqivalent to the first operand for SCEV purposes.
8425 return getSCEV(II->getArgOperand(0));
8426 case Intrinsic::vscale:
8427 return getVScale(II->getType());
8428 default:
8429 break;
8430 }
8431 }
8432 break;
8433 }
8434
8435 return getUnknown(V);
8436}
8437
8438//===----------------------------------------------------------------------===//
8439// Iteration Count Computation Code
8440//
8441
8443 if (isa<SCEVCouldNotCompute>(ExitCount))
8444 return getCouldNotCompute();
8445
8446 auto *ExitCountType = ExitCount->getType();
8447 assert(ExitCountType->isIntegerTy());
8448 auto *EvalTy = Type::getIntNTy(ExitCountType->getContext(),
8449 1 + ExitCountType->getScalarSizeInBits());
8450 return getTripCountFromExitCount(ExitCount, EvalTy, nullptr);
8451}
8452
8454 Type *EvalTy,
8455 const Loop *L) {
8456 if (isa<SCEVCouldNotCompute>(ExitCount))
8457 return getCouldNotCompute();
8458
8459 unsigned ExitCountSize = getTypeSizeInBits(ExitCount->getType());
8460 unsigned EvalSize = EvalTy->getPrimitiveSizeInBits();
8461
8462 auto CanAddOneWithoutOverflow = [&]() {
8463 ConstantRange ExitCountRange =
8464 getRangeRef(ExitCount, RangeSignHint::HINT_RANGE_UNSIGNED);
8465 if (!ExitCountRange.contains(APInt::getMaxValue(ExitCountSize)))
8466 return true;
8467
8468 return L && isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
8469 getMinusOne(ExitCount->getType()));
8470 };
8471
8472 // If we need to zero extend the backedge count, check if we can add one to
8473 // it prior to zero extending without overflow. Provided this is safe, it
8474 // allows better simplification of the +1.
8475 if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8476 return getZeroExtendExpr(
8477 getAddExpr(ExitCount, getOne(ExitCount->getType())), EvalTy);
8478
8479 // Get the total trip count from the count by adding 1. This may wrap.
8480 return getAddExpr(getTruncateOrZeroExtend(ExitCount, EvalTy), getOne(EvalTy));
8481}
8482
8483static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8484 if (!ExitCount)
8485 return 0;
8486
8487 ConstantInt *ExitConst = ExitCount->getValue();
8488
8489 // Guard against huge trip counts.
8490 if (ExitConst->getValue().getActiveBits() > 32)
8491 return 0;
8492
8493 // In case of integer overflow, this returns 0, which is correct.
8494 return ((unsigned)ExitConst->getZExtValue()) + 1;
8495}
8496
8498 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
8499 return getConstantTripCount(ExitCount);
8500}
8501
8502unsigned
8504 const BasicBlock *ExitingBlock) {
8505 assert(ExitingBlock && "Must pass a non-null exiting block!");
8506 assert(L->isLoopExiting(ExitingBlock) &&
8507 "Exiting block must actually branch out of the loop!");
8508 const SCEVConstant *ExitCount =
8509 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
8510 return getConstantTripCount(ExitCount);
8511}
8512
8514 const Loop *L, SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8515
8516 const auto *MaxExitCount =
8517 Predicates ? getPredicatedConstantMaxBackedgeTakenCount(L, *Predicates)
8519 return getConstantTripCount(dyn_cast<SCEVConstant>(MaxExitCount));
8520}
8521
8523 SmallVector<BasicBlock *, 8> ExitingBlocks;
8524 L->getExitingBlocks(ExitingBlocks);
8525
8526 std::optional<unsigned> Res;
8527 for (auto *ExitingBB : ExitingBlocks) {
8528 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
8529 if (!Res)
8530 Res = Multiple;
8531 Res = std::gcd(*Res, Multiple);
8532 }
8533 return Res.value_or(1);
8534}
8535
8537 const SCEV *ExitCount) {
8538 if (isa<SCEVCouldNotCompute>(ExitCount))
8539 return 1;
8540
8541 // Get the trip count
8542 const SCEV *TCExpr = getTripCountFromExitCount(applyLoopGuards(ExitCount, L));
8543
8544 APInt Multiple = getNonZeroConstantMultiple(TCExpr);
8545 // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8546 // the greatest power of 2 divisor less than 2^32.
8547 return Multiple.getActiveBits() > 32
8548 ? 1U << std::min(31U, Multiple.countTrailingZeros())
8549 : (unsigned)Multiple.getZExtValue();
8550}
8551
8552/// Returns the largest constant divisor of the trip count of this loop as a
8553/// normal unsigned value, if possible. This means that the actual trip count is
8554/// always a multiple of the returned value (don't forget the trip count could
8555/// very well be zero as well!).
8556///
8557/// Returns 1 if the trip count is unknown or not guaranteed to be the
8558/// multiple of a constant (which is also the case if the trip count is simply
8559/// constant, use getSmallConstantTripCount for that case), Will also return 1
8560/// if the trip count is very large (>= 2^32).
8561///
8562/// As explained in the comments for getSmallConstantTripCount, this assumes
8563/// that control exits the loop via ExitingBlock.
8564unsigned
8566 const BasicBlock *ExitingBlock) {
8567 assert(ExitingBlock && "Must pass a non-null exiting block!");
8568 assert(L->isLoopExiting(ExitingBlock) &&
8569 "Exiting block must actually branch out of the loop!");
8570 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8571 return getSmallConstantTripMultiple(L, ExitCount);
8572}
8573
8575 const BasicBlock *ExitingBlock,
8576 ExitCountKind Kind) {
8577 switch (Kind) {
8578 case Exact:
8579 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8580 case SymbolicMaximum:
8581 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8582 case ConstantMaximum:
8583 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8584 };
8585 llvm_unreachable("Invalid ExitCountKind!");
8586}
8587
8589 const Loop *L, const BasicBlock *ExitingBlock,
8591 switch (Kind) {
8592 case Exact:
8593 return getPredicatedBackedgeTakenInfo(L).getExact(ExitingBlock, this,
8594 Predicates);
8595 case SymbolicMaximum:
8596 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this,
8597 Predicates);
8598 case ConstantMaximum:
8599 return getPredicatedBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this,
8600 Predicates);
8601 };
8602 llvm_unreachable("Invalid ExitCountKind!");
8603}
8604
8607 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8608}
8609
8611 ExitCountKind Kind) {
8612 switch (Kind) {
8613 case Exact:
8614 return getBackedgeTakenInfo(L).getExact(L, this);
8615 case ConstantMaximum:
8616 return getBackedgeTakenInfo(L).getConstantMax(this);
8617 case SymbolicMaximum:
8618 return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8619 };
8620 llvm_unreachable("Invalid ExitCountKind!");
8621}
8622
8625 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(L, this, &Preds);
8626}
8627
8630 return getPredicatedBackedgeTakenInfo(L).getConstantMax(this, &Preds);
8631}
8632
8634 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8635}
8636
8637ScalarEvolution::BackedgeTakenInfo &
8638ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8639 auto &BTI = getBackedgeTakenInfo(L);
8640 if (BTI.hasFullInfo())
8641 return BTI;
8642
8643 auto Pair = PredicatedBackedgeTakenCounts.try_emplace(L);
8644
8645 if (!Pair.second)
8646 return Pair.first->second;
8647
8648 BackedgeTakenInfo Result =
8649 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8650
8651 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8652}
8653
8654ScalarEvolution::BackedgeTakenInfo &
8655ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8656 // Initially insert an invalid entry for this loop. If the insertion
8657 // succeeds, proceed to actually compute a backedge-taken count and
8658 // update the value. The temporary CouldNotCompute value tells SCEV
8659 // code elsewhere that it shouldn't attempt to request a new
8660 // backedge-taken count, which could result in infinite recursion.
8661 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8662 BackedgeTakenCounts.try_emplace(L);
8663 if (!Pair.second)
8664 return Pair.first->second;
8665
8666 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8667 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8668 // must be cleared in this scope.
8669 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8670
8671 // Now that we know more about the trip count for this loop, forget any
8672 // existing SCEV values for PHI nodes in this loop since they are only
8673 // conservative estimates made without the benefit of trip count
8674 // information. This invalidation is not necessary for correctness, and is
8675 // only done to produce more precise results.
8676 if (Result.hasAnyInfo()) {
8677 // Invalidate any expression using an addrec in this loop.
8678 SmallVector<SCEVUse, 8> ToForget;
8679 auto LoopUsersIt = LoopUsers.find(L);
8680 if (LoopUsersIt != LoopUsers.end())
8681 append_range(ToForget, LoopUsersIt->second);
8682 forgetMemoizedResults(ToForget);
8683
8684 // Invalidate constant-evolved loop header phis.
8685 for (PHINode &PN : L->getHeader()->phis())
8686 ConstantEvolutionLoopExitValue.erase(&PN);
8687 }
8688
8689 // Re-lookup the insert position, since the call to
8690 // computeBackedgeTakenCount above could result in a
8691 // recusive call to getBackedgeTakenInfo (on a different
8692 // loop), which would invalidate the iterator computed
8693 // earlier.
8694 return BackedgeTakenCounts.find(L)->second = std::move(Result);
8695}
8696
8698 // This method is intended to forget all info about loops. It should
8699 // invalidate caches as if the following happened:
8700 // - The trip counts of all loops have changed arbitrarily
8701 // - Every llvm::Value has been updated in place to produce a different
8702 // result.
8703 BackedgeTakenCounts.clear();
8704 PredicatedBackedgeTakenCounts.clear();
8705 BECountUsers.clear();
8706 LoopPropertiesCache.clear();
8707 ConstantEvolutionLoopExitValue.clear();
8708 ValueExprMap.clear();
8709 ValuesAtScopes.clear();
8710 ValuesAtScopesUsers.clear();
8711 LoopDispositions.clear();
8712 BlockDispositions.clear();
8713 UnsignedRanges.clear();
8714 SignedRanges.clear();
8715 ExprValueMap.clear();
8716 HasRecMap.clear();
8717 ConstantMultipleCache.clear();
8718 PredicatedSCEVRewrites.clear();
8719 FoldCache.clear();
8720 FoldCacheUser.clear();
8721}
8722void ScalarEvolution::visitAndClearUsers(
8725 SmallVectorImpl<SCEVUse> &ToForget) {
8726 while (!Worklist.empty()) {
8727 Instruction *I = Worklist.pop_back_val();
8728 if (!isSCEVable(I->getType()) && !isa<WithOverflowInst>(I))
8729 continue;
8730
8732 ValueExprMap.find_as(static_cast<Value *>(I));
8733 if (It != ValueExprMap.end()) {
8734 ToForget.push_back(It->second);
8735 eraseValueFromMap(It->first);
8736 if (PHINode *PN = dyn_cast<PHINode>(I))
8737 ConstantEvolutionLoopExitValue.erase(PN);
8738 }
8739
8740 PushDefUseChildren(I, Worklist, Visited);
8741 }
8742}
8743
8745 SmallVector<const Loop *, 16> LoopWorklist(1, L);
8746 SmallVector<SCEVUse, 16> ToForget;
8747
8748 // Iterate over all the loops and sub-loops to drop SCEV information.
8749 while (!LoopWorklist.empty()) {
8750 auto *CurrL = LoopWorklist.pop_back_val();
8751
8752 // Drop any stored trip count value.
8753 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8754 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8755
8756 // Drop information about predicated SCEV rewrites for this loop.
8757 PredicatedSCEVRewrites.remove_if(
8758 [&](const auto &Entry) { return Entry.first.second == CurrL; });
8759
8760 auto LoopUsersItr = LoopUsers.find(CurrL);
8761 if (LoopUsersItr != LoopUsers.end())
8762 llvm::append_range(ToForget, LoopUsersItr->second);
8763
8764 // Drop information about expressions based on loop-header PHIs.
8765 for (PHINode &PN : CurrL->getHeader()->phis()) {
8766 ConstantEvolutionLoopExitValue.erase(&PN);
8767 auto VIt = ValueExprMap.find_as(static_cast<Value *>(&PN));
8768 if (VIt != ValueExprMap.end())
8769 ToForget.push_back(VIt->second);
8770 }
8771
8772 LoopPropertiesCache.erase(CurrL);
8773 // Forget all contained loops too, to avoid dangling entries in the
8774 // ValuesAtScopes map.
8775 LoopWorklist.append(CurrL->begin(), CurrL->end());
8776 }
8777 forgetMemoizedResults(ToForget);
8778}
8779
8781 forgetLoop(L->getOutermostLoop());
8782}
8783
8786 if (!I) return;
8787
8788 // Drop information about expressions based on loop-header PHIs.
8791 SmallVector<SCEVUse, 8> ToForget;
8792 Worklist.push_back(I);
8793 Visited.insert(I);
8794 visitAndClearUsers(Worklist, Visited, ToForget);
8795
8796 forgetMemoizedResults(ToForget);
8797}
8798
8800 if (!isSCEVable(V->getType()))
8801 return;
8802
8803 // If SCEV looked through a trivial LCSSA phi node, we might have SCEV's
8804 // directly using a SCEVUnknown/SCEVAddRec defined in the loop. After an
8805 // extra predecessor is added, this is no longer valid. Find all Unknowns and
8806 // AddRecs defined in the loop and invalidate any SCEV's making use of them.
8807 if (const SCEV *S = getExistingSCEV(V)) {
8808 struct InvalidationRootCollector {
8809 Loop *L;
8811
8812 InvalidationRootCollector(Loop *L) : L(L) {}
8813
8814 bool follow(const SCEV *S) {
8815 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
8816 if (auto *I = dyn_cast<Instruction>(SU->getValue()))
8817 if (L->contains(I))
8818 Roots.push_back(S);
8819 } else if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
8820 if (L->contains(AddRec->getLoop()))
8821 Roots.push_back(S);
8822 }
8823 return true;
8824 }
8825 bool isDone() const { return false; }
8826 };
8827
8828 InvalidationRootCollector C(L);
8829 visitAll(S, C);
8830 forgetMemoizedResults(C.Roots);
8831 }
8832
8833 // Also perform the normal invalidation.
8834 forgetValue(V);
8835}
8836
8837void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8838
8840 // Unless a specific value is passed to invalidation, completely clear both
8841 // caches.
8842 if (!V) {
8843 BlockDispositions.clear();
8844 LoopDispositions.clear();
8845 return;
8846 }
8847
8848 if (!isSCEVable(V->getType()))
8849 return;
8850
8851 const SCEV *S = getExistingSCEV(V);
8852 if (!S)
8853 return;
8854
8855 // Invalidate the block and loop dispositions cached for S. Dispositions of
8856 // S's users may change if S's disposition changes (i.e. a user may change to
8857 // loop-invariant, if S changes to loop invariant), so also invalidate
8858 // dispositions of S's users recursively.
8859 SmallVector<SCEVUse, 8> Worklist = {S};
8861 while (!Worklist.empty()) {
8862 const SCEV *Curr = Worklist.pop_back_val();
8863 bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8864 bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8865 if (!LoopDispoRemoved && !BlockDispoRemoved)
8866 continue;
8867 auto Users = SCEVUsers.find(Curr);
8868 if (Users != SCEVUsers.end())
8869 for (const auto *User : Users->second)
8870 if (Seen.insert(User).second)
8871 Worklist.push_back(User);
8872 }
8873}
8874
8875/// Get the exact loop backedge taken count considering all loop exits. A
8876/// computable result can only be returned for loops with all exiting blocks
8877/// dominating the latch. howFarToZero assumes that the limit of each loop test
8878/// is never skipped. This is a valid assumption as long as the loop exits via
8879/// that test. For precise results, it is the caller's responsibility to specify
8880/// the relevant loop exiting block using getExact(ExitingBlock, SE).
8881const SCEV *ScalarEvolution::BackedgeTakenInfo::getExact(
8882 const Loop *L, ScalarEvolution *SE,
8884 // If any exits were not computable, the loop is not computable.
8885 if (!isComplete() || ExitNotTaken.empty())
8886 return SE->getCouldNotCompute();
8887
8888 const BasicBlock *Latch = L->getLoopLatch();
8889 // All exiting blocks we have collected must dominate the only backedge.
8890 if (!Latch)
8891 return SE->getCouldNotCompute();
8892
8893 // All exiting blocks we have gathered dominate loop's latch, so exact trip
8894 // count is simply a minimum out of all these calculated exit counts.
8896 for (const auto &ENT : ExitNotTaken) {
8897 const SCEV *BECount = ENT.ExactNotTaken;
8898 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8899 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8900 "We should only have known counts for exiting blocks that dominate "
8901 "latch!");
8902
8903 Ops.push_back(BECount);
8904
8905 if (Preds)
8906 append_range(*Preds, ENT.Predicates);
8907
8908 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8909 "Predicate should be always true!");
8910 }
8911
8912 // If an earlier exit exits on the first iteration (exit count zero), then
8913 // a later poison exit count should not propagate into the result. This are
8914 // exactly the semantics provided by umin_seq.
8915 return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8916}
8917
8918const ScalarEvolution::ExitNotTakenInfo *
8919ScalarEvolution::BackedgeTakenInfo::getExitNotTaken(
8920 const BasicBlock *ExitingBlock,
8921 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8922 for (const auto &ENT : ExitNotTaken)
8923 if (ENT.ExitingBlock == ExitingBlock) {
8924 if (ENT.hasAlwaysTruePredicate())
8925 return &ENT;
8926 else if (Predicates) {
8927 append_range(*Predicates, ENT.Predicates);
8928 return &ENT;
8929 }
8930 }
8931
8932 return nullptr;
8933}
8934
8935/// getConstantMax - Get the constant max backedge taken count for the loop.
8936const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8937 ScalarEvolution *SE,
8938 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8939 if (!getConstantMax())
8940 return SE->getCouldNotCompute();
8941
8942 for (const auto &ENT : ExitNotTaken)
8943 if (!ENT.hasAlwaysTruePredicate()) {
8944 if (!Predicates)
8945 return SE->getCouldNotCompute();
8946 append_range(*Predicates, ENT.Predicates);
8947 }
8948
8949 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8950 isa<SCEVConstant>(getConstantMax())) &&
8951 "No point in having a non-constant max backedge taken count!");
8952 return getConstantMax();
8953}
8954
8955const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8956 const Loop *L, ScalarEvolution *SE,
8957 SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8958 if (!SymbolicMax) {
8959 // Form an expression for the maximum exit count possible for this loop. We
8960 // merge the max and exact information to approximate a version of
8961 // getConstantMaxBackedgeTakenCount which isn't restricted to just
8962 // constants.
8963 SmallVector<SCEVUse, 4> ExitCounts;
8964
8965 for (const auto &ENT : ExitNotTaken) {
8966 const SCEV *ExitCount = ENT.SymbolicMaxNotTaken;
8967 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
8968 assert(SE->DT.dominates(ENT.ExitingBlock, L->getLoopLatch()) &&
8969 "We should only have known counts for exiting blocks that "
8970 "dominate latch!");
8971 ExitCounts.push_back(ExitCount);
8972 if (Predicates)
8973 append_range(*Predicates, ENT.Predicates);
8974
8975 assert((Predicates || ENT.hasAlwaysTruePredicate()) &&
8976 "Predicate should be always true!");
8977 }
8978 }
8979 if (ExitCounts.empty())
8980 SymbolicMax = SE->getCouldNotCompute();
8981 else
8982 SymbolicMax =
8983 SE->getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
8984 }
8985 return SymbolicMax;
8986}
8987
8988bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8989 ScalarEvolution *SE) const {
8990 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8991 return !ENT.hasAlwaysTruePredicate();
8992 };
8993 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8994}
8995
8998
9000 const SCEV *E, const SCEV *ConstantMaxNotTaken,
9001 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
9005 // If we prove the max count is zero, so is the symbolic bound. This happens
9006 // in practice due to differences in a) how context sensitive we've chosen
9007 // to be and b) how we reason about bounds implied by UB.
9008 if (ConstantMaxNotTaken->isZero()) {
9009 this->ExactNotTaken = E = ConstantMaxNotTaken;
9010 this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
9011 }
9012
9015 "Exact is not allowed to be less precise than Constant Max");
9018 "Exact is not allowed to be less precise than Symbolic Max");
9021 "Symbolic Max is not allowed to be less precise than Constant Max");
9024 "No point in having a non-constant max backedge taken count!");
9026 for (const auto PredList : PredLists)
9027 for (const auto *P : PredList) {
9028 if (SeenPreds.contains(P))
9029 continue;
9030 assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!");
9031 SeenPreds.insert(P);
9032 Predicates.push_back(P);
9033 }
9034 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
9035 "Backedge count should be int");
9037 !ConstantMaxNotTaken->getType()->isPointerTy()) &&
9038 "Max backedge count should be int");
9039}
9040
9048
9049/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
9050/// computable exit into a persistent ExitNotTakenInfo array.
9051ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
9053 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
9054 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
9055 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
9056
9057 ExitNotTaken.reserve(ExitCounts.size());
9058 std::transform(ExitCounts.begin(), ExitCounts.end(),
9059 std::back_inserter(ExitNotTaken),
9060 [&](const EdgeExitInfo &EEI) {
9061 BasicBlock *ExitBB = EEI.first;
9062 const ExitLimit &EL = EEI.second;
9063 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
9064 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
9065 EL.Predicates);
9066 });
9067 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
9068 isa<SCEVConstant>(ConstantMax)) &&
9069 "No point in having a non-constant max backedge taken count!");
9070}
9071
9072/// Compute the number of times the backedge of the specified loop will execute.
9073ScalarEvolution::BackedgeTakenInfo
9074ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
9075 bool AllowPredicates) {
9076 SmallVector<BasicBlock *, 8> ExitingBlocks;
9077 L->getExitingBlocks(ExitingBlocks);
9078
9079 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
9080
9082 bool CouldComputeBECount = true;
9083 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
9084 const SCEV *MustExitMaxBECount = nullptr;
9085 const SCEV *MayExitMaxBECount = nullptr;
9086 bool MustExitMaxOrZero = false;
9087 bool IsOnlyExit = ExitingBlocks.size() == 1;
9088
9089 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
9090 // and compute maxBECount.
9091 // Do a union of all the predicates here.
9092 for (BasicBlock *ExitBB : ExitingBlocks) {
9093 // We canonicalize untaken exits to br (constant), ignore them so that
9094 // proving an exit untaken doesn't negatively impact our ability to reason
9095 // about the loop as whole.
9096 if (auto *BI = dyn_cast<CondBrInst>(ExitBB->getTerminator()))
9097 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
9098 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9099 if (ExitIfTrue == CI->isZero())
9100 continue;
9101 }
9102
9103 ExitLimit EL = computeExitLimit(L, ExitBB, IsOnlyExit, AllowPredicates);
9104
9105 assert((AllowPredicates || EL.Predicates.empty()) &&
9106 "Predicated exit limit when predicates are not allowed!");
9107
9108 // 1. For each exit that can be computed, add an entry to ExitCounts.
9109 // CouldComputeBECount is true only if all exits can be computed.
9110 if (EL.ExactNotTaken != getCouldNotCompute())
9111 ++NumExitCountsComputed;
9112 else
9113 // We couldn't compute an exact value for this exit, so
9114 // we won't be able to compute an exact value for the loop.
9115 CouldComputeBECount = false;
9116 // Remember exit count if either exact or symbolic is known. Because
9117 // Exact always implies symbolic, only check symbolic.
9118 if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
9119 ExitCounts.emplace_back(ExitBB, EL);
9120 else {
9121 assert(EL.ExactNotTaken == getCouldNotCompute() &&
9122 "Exact is known but symbolic isn't?");
9123 ++NumExitCountsNotComputed;
9124 }
9125
9126 // 2. Derive the loop's MaxBECount from each exit's max number of
9127 // non-exiting iterations. Partition the loop exits into two kinds:
9128 // LoopMustExits and LoopMayExits.
9129 //
9130 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
9131 // is a LoopMayExit. If any computable LoopMustExit is found, then
9132 // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
9133 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
9134 // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
9135 // any
9136 // computable EL.ConstantMaxNotTaken.
9137 if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
9138 DT.dominates(ExitBB, Latch)) {
9139 if (!MustExitMaxBECount) {
9140 MustExitMaxBECount = EL.ConstantMaxNotTaken;
9141 MustExitMaxOrZero = EL.MaxOrZero;
9142 } else {
9143 MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
9144 EL.ConstantMaxNotTaken);
9145 }
9146 } else if (MayExitMaxBECount != getCouldNotCompute()) {
9147 if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
9148 MayExitMaxBECount = EL.ConstantMaxNotTaken;
9149 else {
9150 MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
9151 EL.ConstantMaxNotTaken);
9152 }
9153 }
9154 }
9155 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
9156 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
9157 // The loop backedge will be taken the maximum or zero times if there's
9158 // a single exit that must be taken the maximum or zero times.
9159 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
9160
9161 // Remember which SCEVs are used in exit limits for invalidation purposes.
9162 // We only care about non-constant SCEVs here, so we can ignore
9163 // EL.ConstantMaxNotTaken
9164 // and MaxBECount, which must be SCEVConstant.
9165 for (const auto &Pair : ExitCounts) {
9166 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
9167 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
9168 if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
9169 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
9170 {L, AllowPredicates});
9171 }
9172 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
9173 MaxBECount, MaxOrZero);
9174}
9175
9176ScalarEvolution::ExitLimit
9177ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
9178 bool IsOnlyExit, bool AllowPredicates) {
9179 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
9180 // If our exiting block does not dominate the latch, then its connection with
9181 // loop's exit limit may be far from trivial.
9182 const BasicBlock *Latch = L->getLoopLatch();
9183 if (!Latch || !DT.dominates(ExitingBlock, Latch))
9184 return getCouldNotCompute();
9185
9186 Instruction *Term = ExitingBlock->getTerminator();
9187 if (CondBrInst *BI = dyn_cast<CondBrInst>(Term)) {
9188 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9189 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
9190 "It should have one successor in loop and one exit block!");
9191 // Proceed to the next level to examine the exit condition expression.
9192 return computeExitLimitFromCond(L, BI->getCondition(), ExitIfTrue,
9193 /*ControlsOnlyExit=*/IsOnlyExit,
9194 AllowPredicates);
9195 }
9196
9197 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
9198 // For switch, make sure that there is a single exit from the loop.
9199 BasicBlock *Exit = nullptr;
9200 for (auto *SBB : successors(ExitingBlock))
9201 if (!L->contains(SBB)) {
9202 if (Exit) // Multiple exit successors.
9203 return getCouldNotCompute();
9204 Exit = SBB;
9205 }
9206 assert(Exit && "Exiting block must have at least one exit");
9207 return computeExitLimitFromSingleExitSwitch(
9208 L, SI, Exit, /*ControlsOnlyExit=*/IsOnlyExit);
9209 }
9210
9211 return getCouldNotCompute();
9212}
9213
9215 const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9216 bool AllowPredicates) {
9217 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
9218 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
9219 ControlsOnlyExit, AllowPredicates);
9220}
9221
9222std::optional<ScalarEvolution::ExitLimit>
9223ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
9224 bool ExitIfTrue, bool ControlsOnlyExit,
9225 bool AllowPredicates) {
9226 (void)this->L;
9227 (void)this->ExitIfTrue;
9228 (void)this->AllowPredicates;
9229
9230 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9231 this->AllowPredicates == AllowPredicates &&
9232 "Variance in assumed invariant key components!");
9233 auto Itr = TripCountMap.find({ExitCond, ControlsOnlyExit});
9234 if (Itr == TripCountMap.end())
9235 return std::nullopt;
9236 return Itr->second;
9237}
9238
9239void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
9240 bool ExitIfTrue,
9241 bool ControlsOnlyExit,
9242 bool AllowPredicates,
9243 const ExitLimit &EL) {
9244 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9245 this->AllowPredicates == AllowPredicates &&
9246 "Variance in assumed invariant key components!");
9247
9248 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsOnlyExit}, EL});
9249 assert(InsertResult.second && "Expected successful insertion!");
9250 (void)InsertResult;
9251 (void)ExitIfTrue;
9252}
9253
9254ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
9255 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9256 bool ControlsOnlyExit, bool AllowPredicates) {
9257
9258 if (auto MaybeEL = Cache.find(L, ExitCond, ExitIfTrue, ControlsOnlyExit,
9259 AllowPredicates))
9260 return *MaybeEL;
9261
9262 ExitLimit EL = computeExitLimitFromCondImpl(
9263 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates);
9264 Cache.insert(L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates, EL);
9265 return EL;
9266}
9267
9268ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
9269 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9270 bool ControlsOnlyExit, bool AllowPredicates) {
9271 // Handle BinOp conditions (And, Or).
9272 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
9273 Cache, L, ExitCond, ExitIfTrue, AllowPredicates))
9274 return *LimitFromBinOp;
9275
9276 // With an icmp, it may be feasible to compute an exact backedge-taken count.
9277 // Proceed to the next level to examine the icmp.
9278 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
9279 ExitLimit EL =
9280 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsOnlyExit);
9281 if (EL.hasFullInfo() || !AllowPredicates)
9282 return EL;
9283
9284 // Try again, but use SCEV predicates this time.
9285 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue,
9286 ControlsOnlyExit,
9287 /*AllowPredicates=*/true);
9288 }
9289
9290 // Check for a constant condition. These are normally stripped out by
9291 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
9292 // preserve the CFG and is temporarily leaving constant conditions
9293 // in place.
9294 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
9295 if (ExitIfTrue == !CI->getZExtValue())
9296 // The backedge is always taken.
9297 return getCouldNotCompute();
9298 // The backedge is never taken.
9299 return getZero(CI->getType());
9300 }
9301
9302 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
9303 // with a constant step, we can form an equivalent icmp predicate and figure
9304 // out how many iterations will be taken before we exit.
9305 const WithOverflowInst *WO;
9306 const APInt *C;
9307 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
9308 match(WO->getRHS(), m_APInt(C))) {
9309 ConstantRange NWR =
9311 WO->getNoWrapKind());
9312 CmpInst::Predicate Pred;
9313 APInt NewRHSC, Offset;
9314 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
9315 if (!ExitIfTrue)
9316 Pred = ICmpInst::getInversePredicate(Pred);
9317 auto *LHS = getSCEV(WO->getLHS());
9318 if (Offset != 0)
9320 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
9321 ControlsOnlyExit, AllowPredicates);
9322 if (EL.hasAnyInfo())
9323 return EL;
9324 }
9325
9326 // If it's not an integer or pointer comparison then compute it the hard way.
9327 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9328}
9329
9330std::optional<ScalarEvolution::ExitLimit>
9331ScalarEvolution::computeExitLimitFromCondFromBinOp(ExitLimitCacheTy &Cache,
9332 const Loop *L,
9333 Value *ExitCond,
9334 bool ExitIfTrue,
9335 bool AllowPredicates) {
9336 // Check if the controlling expression for this loop is an And or Or.
9337 Value *Op0, *Op1;
9338 bool IsAnd;
9339 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
9340 IsAnd = true;
9341 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
9342 IsAnd = false;
9343 else
9344 return std::nullopt;
9345
9346 // A sub-condition of a non-trivial binop never solely controls the exit,
9347 // whether we exit always depends on both conditions.
9348 ExitLimit EL0 = computeExitLimitFromCondCached(
9349 Cache, L, Op0, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9350 ExitLimit EL1 = computeExitLimitFromCondCached(
9351 Cache, L, Op1, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9352
9353 // EitherMayExit is true in these two cases:
9354 // br (and Op0 Op1), loop, exit
9355 // br (or Op0 Op1), exit, loop
9356 bool EitherMayExit = IsAnd ^ ExitIfTrue;
9357
9358 const SCEV *BECount = getCouldNotCompute();
9359 const SCEV *ConstantMaxBECount = getCouldNotCompute();
9360 const SCEV *SymbolicMaxBECount = getCouldNotCompute();
9361 if (EitherMayExit) {
9362 bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
9363 // Both conditions must be same for the loop to continue executing.
9364 // Choose the less conservative count.
9365 if (EL0.ExactNotTaken != getCouldNotCompute() &&
9366 EL1.ExactNotTaken != getCouldNotCompute()) {
9367 BECount = getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken,
9368 UseSequentialUMin);
9369 }
9370 if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
9371 ConstantMaxBECount = EL1.ConstantMaxNotTaken;
9372 else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
9373 ConstantMaxBECount = EL0.ConstantMaxNotTaken;
9374 else
9375 ConstantMaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
9376 EL1.ConstantMaxNotTaken);
9377 if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
9378 SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
9379 else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
9380 SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
9381 else
9382 SymbolicMaxBECount = getUMinFromMismatchedTypes(
9383 EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
9384 } else {
9385 // Both conditions must be same at the same time for the loop to exit.
9386 // For now, be conservative.
9387 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
9388 BECount = EL0.ExactNotTaken;
9389 }
9390
9391 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
9392 // to be more aggressive when computing BECount than when computing
9393 // ConstantMaxBECount. In these cases it is possible for EL0.ExactNotTaken
9394 // and
9395 // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
9396 // EL1.ConstantMaxNotTaken to not.
9397 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
9398 !isa<SCEVCouldNotCompute>(BECount))
9399 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
9400 if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
9401 SymbolicMaxBECount =
9402 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
9403 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
9404 {ArrayRef(EL0.Predicates), ArrayRef(EL1.Predicates)});
9405}
9406
9407ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9408 const Loop *L, ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9409 bool AllowPredicates) {
9410 // If the condition was exit on true, convert the condition to exit on false
9411 CmpPredicate Pred;
9412 if (!ExitIfTrue)
9413 Pred = ExitCond->getCmpPredicate();
9414 else
9415 Pred = ExitCond->getInverseCmpPredicate();
9416 const ICmpInst::Predicate OriginalPred = Pred;
9417
9418 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
9419 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
9420
9421 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsOnlyExit,
9422 AllowPredicates);
9423 if (EL.hasAnyInfo())
9424 return EL;
9425
9426 auto *ExhaustiveCount =
9427 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9428
9429 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
9430 return ExhaustiveCount;
9431
9432 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
9433 ExitCond->getOperand(1), L, OriginalPred);
9434}
9435ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9436 const Loop *L, CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS,
9437 bool ControlsOnlyExit, bool AllowPredicates) {
9438
9439 // Try to evaluate any dependencies out of the loop.
9440 LHS = getSCEVAtScope(LHS, L);
9441 RHS = getSCEVAtScope(RHS, L);
9442
9443 // At this point, we would like to compute how many iterations of the
9444 // loop the predicate will return true for these inputs.
9445 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
9446 // If there is a loop-invariant, force it into the RHS.
9447 std::swap(LHS, RHS);
9449 }
9450
9451 bool ControllingFiniteLoop = ControlsOnlyExit && loopHasNoAbnormalExits(L) &&
9453 // Simplify the operands before analyzing them.
9454 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0);
9455
9456 // If we have a comparison of a chrec against a constant, try to use value
9457 // ranges to answer this query.
9458 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
9459 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
9460 if (AddRec->getLoop() == L) {
9461 // Form the constant range.
9462 ConstantRange CompRange =
9463 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
9464
9465 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
9466 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
9467 }
9468
9469 // If this loop must exit based on this condition (or execute undefined
9470 // behaviour), see if we can improve wrap flags. This is essentially
9471 // a must execute style proof.
9472 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
9473 // If we can prove the test sequence produced must repeat the same values
9474 // on self-wrap of the IV, then we can infer that IV doesn't self wrap
9475 // because if it did, we'd have an infinite (undefined) loop.
9476 // TODO: We can peel off any functions which are invertible *in L*. Loop
9477 // invariant terms are effectively constants for our purposes here.
9478 SCEVUse InnerLHS = LHS;
9479 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
9480 InnerLHS = ZExt->getOperand();
9481 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS);
9482 AR && !AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
9483 isKnownToBeAPowerOfTwo(AR->getStepRecurrence(*this), /*OrZero=*/true,
9484 /*OrNegative=*/true)) {
9485 auto Flags = AR->getNoWrapFlags();
9486 Flags = setFlags(Flags, SCEV::FlagNW);
9487 SmallVector<SCEVUse> Operands{AR->operands()};
9488 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
9489 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9490 }
9491
9492 // For a slt/ult condition with a positive step, can we prove nsw/nuw?
9493 // From no-self-wrap, this follows trivially from the fact that every
9494 // (un)signed-wrapped, but not self-wrapped value must be LT than the
9495 // last value before (un)signed wrap. Since we know that last value
9496 // didn't exit, nor will any smaller one.
9497 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT) {
9498 auto WrapType = Pred == ICmpInst::ICMP_SLT ? SCEV::FlagNSW : SCEV::FlagNUW;
9499 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9500 AR && AR->getLoop() == L && AR->isAffine() &&
9501 !AR->getNoWrapFlags(WrapType) && AR->hasNoSelfWrap() &&
9502 isKnownPositive(AR->getStepRecurrence(*this))) {
9503 auto Flags = AR->getNoWrapFlags();
9504 Flags = setFlags(Flags, WrapType);
9505 SmallVector<SCEVUse> Operands{AR->operands()};
9506 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
9507 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9508 }
9509 }
9510 }
9511
9512 switch (Pred) {
9513 case ICmpInst::ICMP_NE: { // while (X != Y)
9514 // Convert to: while (X-Y != 0)
9515 if (LHS->getType()->isPointerTy()) {
9518 return LHS;
9519 }
9520 if (RHS->getType()->isPointerTy()) {
9523 return RHS;
9524 }
9525 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit,
9526 AllowPredicates);
9527 if (EL.hasAnyInfo())
9528 return EL;
9529 break;
9530 }
9531 case ICmpInst::ICMP_EQ: { // while (X == Y)
9532 // Convert to: while (X-Y == 0)
9533 if (LHS->getType()->isPointerTy()) {
9536 return LHS;
9537 }
9538 if (RHS->getType()->isPointerTy()) {
9541 return RHS;
9542 }
9543 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
9544 if (EL.hasAnyInfo()) return EL;
9545 break;
9546 }
9547 case ICmpInst::ICMP_SLE:
9548 case ICmpInst::ICMP_ULE:
9549 // Since the loop is finite, an invariant RHS cannot include the boundary
9550 // value, otherwise it would loop forever.
9551 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9552 !isLoopInvariant(RHS, L)) {
9553 // Otherwise, perform the addition in a wider type, to avoid overflow.
9554 // If the LHS is an addrec with the appropriate nowrap flag, the
9555 // extension will be sunk into it and the exit count can be analyzed.
9556 auto *OldType = dyn_cast<IntegerType>(LHS->getType());
9557 if (!OldType)
9558 break;
9559 // Prefer doubling the bitwidth over adding a single bit to make it more
9560 // likely that we use a legal type.
9561 auto *NewType =
9562 Type::getIntNTy(OldType->getContext(), OldType->getBitWidth() * 2);
9563 if (ICmpInst::isSigned(Pred)) {
9564 LHS = getSignExtendExpr(LHS, NewType);
9565 RHS = getSignExtendExpr(RHS, NewType);
9566 } else {
9567 LHS = getZeroExtendExpr(LHS, NewType);
9568 RHS = getZeroExtendExpr(RHS, NewType);
9569 }
9570 }
9572 [[fallthrough]];
9573 case ICmpInst::ICMP_SLT:
9574 case ICmpInst::ICMP_ULT: { // while (X < Y)
9575 bool IsSigned = ICmpInst::isSigned(Pred);
9576 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9577 AllowPredicates);
9578 if (EL.hasAnyInfo())
9579 return EL;
9580 break;
9581 }
9582 case ICmpInst::ICMP_SGE:
9583 case ICmpInst::ICMP_UGE:
9584 // Since the loop is finite, an invariant RHS cannot include the boundary
9585 // value, otherwise it would loop forever.
9586 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9587 !isLoopInvariant(RHS, L))
9588 break;
9590 [[fallthrough]];
9591 case ICmpInst::ICMP_SGT:
9592 case ICmpInst::ICMP_UGT: { // while (X > Y)
9593 bool IsSigned = ICmpInst::isSigned(Pred);
9594 ExitLimit EL = howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9595 AllowPredicates);
9596 if (EL.hasAnyInfo())
9597 return EL;
9598 break;
9599 }
9600 default:
9601 break;
9602 }
9603
9604 return getCouldNotCompute();
9605}
9606
9607ScalarEvolution::ExitLimit
9608ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
9609 SwitchInst *Switch,
9610 BasicBlock *ExitingBlock,
9611 bool ControlsOnlyExit) {
9612 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
9613
9614 // Give up if the exit is the default dest of a switch.
9615 if (Switch->getDefaultDest() == ExitingBlock)
9616 return getCouldNotCompute();
9617
9618 assert(L->contains(Switch->getDefaultDest()) &&
9619 "Default case must not exit the loop!");
9620 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
9621 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
9622
9623 // while (X != Y) --> while (X-Y != 0)
9624 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit);
9625 if (EL.hasAnyInfo())
9626 return EL;
9627
9628 return getCouldNotCompute();
9629}
9630
9631static ConstantInt *
9633 ScalarEvolution &SE) {
9634 const SCEV *InVal = SE.getConstant(C);
9635 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
9637 "Evaluation of SCEV at constant didn't fold correctly?");
9638 return cast<SCEVConstant>(Val)->getValue();
9639}
9640
9641ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
9642 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
9643 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
9644 if (!RHS)
9645 return getCouldNotCompute();
9646
9647 const BasicBlock *Latch = L->getLoopLatch();
9648 if (!Latch)
9649 return getCouldNotCompute();
9650
9651 const BasicBlock *Predecessor = L->getLoopPredecessor();
9652 if (!Predecessor)
9653 return getCouldNotCompute();
9654
9655 // Return true if V is of the form "LHS `shift_op` <positive constant>".
9656 // Return LHS in OutLHS, shift_op in OutOpCode, and the shift amount in
9657 // OutShiftAmt.
9658 auto MatchPositiveShift = [](Value *V, Value *&OutLHS,
9659 Instruction::BinaryOps &OutOpCode,
9660 unsigned &OutShiftAmt) {
9661 using namespace PatternMatch;
9662
9663 ConstantInt *ShiftAmt;
9664 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9665 OutOpCode = Instruction::LShr;
9666 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9667 OutOpCode = Instruction::AShr;
9668 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9669 OutOpCode = Instruction::Shl;
9670 else
9671 return false;
9672
9673 uint64_t Amt = ShiftAmt->getValue().getLimitedValue();
9674 if (Amt == 0 || Amt >= OutLHS->getType()->getScalarSizeInBits())
9675 return false;
9676 OutShiftAmt = Amt;
9677 return true;
9678 };
9679
9680 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
9681 //
9682 // loop:
9683 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
9684 // %iv.shifted = lshr i32 %iv, <positive constant>
9685 //
9686 // Return true on a successful match. Return the corresponding PHI node (%iv
9687 // above) in PNOut, the opcode of the shift operation in OpCodeOut, and the
9688 // shift amount in ShiftAmtOut.
9689 auto MatchShiftRecurrence = [&](Value *V, PHINode *&PNOut,
9690 Instruction::BinaryOps &OpCodeOut,
9691 unsigned &ShiftAmtOut) {
9692 std::optional<Instruction::BinaryOps> PostShiftOpCode;
9693
9694 {
9696 Value *V;
9697 unsigned Amt;
9698
9699 // If we encounter a shift instruction, "peel off" the shift operation,
9700 // and remember that we did so. Later when we inspect %iv's backedge
9701 // value, we will make sure that the backedge value uses the same
9702 // operation.
9703 //
9704 // Note: the peeled shift operation does not have to be the same
9705 // instruction as the one feeding into the PHI's backedge value. We only
9706 // really care about it being the same *kind* of shift instruction --
9707 // that's all that is required for our later inferences to hold.
9708 if (MatchPositiveShift(LHS, V, OpC, Amt)) {
9709 PostShiftOpCode = OpC;
9710 LHS = V;
9711 }
9712 }
9713
9714 PNOut = dyn_cast<PHINode>(LHS);
9715 if (!PNOut || PNOut->getParent() != L->getHeader())
9716 return false;
9717
9718 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
9719 Value *OpLHS;
9720
9721 return
9722 // The backedge value for the PHI node must be a shift by a positive
9723 // amount
9724 MatchPositiveShift(BEValue, OpLHS, OpCodeOut, ShiftAmtOut) &&
9725
9726 // of the PHI node itself
9727 OpLHS == PNOut &&
9728
9729 // and the kind of shift should be match the kind of shift we peeled
9730 // off, if any.
9731 (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9732 };
9733
9734 PHINode *PN;
9736 unsigned ShiftAmt;
9737 if (!MatchShiftRecurrence(LHS, PN, OpCode, ShiftAmt))
9738 return getCouldNotCompute();
9739
9740 const DataLayout &DL = getDataLayout();
9741
9742 // The key rationale for this optimization is that for some kinds of shift
9743 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
9744 // within a finite number of iterations. If the condition guarding the
9745 // backedge (in the sense that the backedge is taken if the condition is true)
9746 // is false for the value the shift recurrence stabilizes to, then we know
9747 // that the backedge is taken only a finite number of times.
9748
9749 ConstantInt *StableValue = nullptr;
9750 switch (OpCode) {
9751 default:
9752 llvm_unreachable("Impossible case!");
9753
9754 case Instruction::AShr: {
9755 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
9756 // bitwidth(K) iterations.
9757 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
9758 KnownBits Known = computeKnownBits(FirstValue, DL, &AC,
9759 Predecessor->getTerminator(), &DT);
9760 auto *Ty = cast<IntegerType>(RHS->getType());
9761 if (Known.isNonNegative())
9762 StableValue = ConstantInt::get(Ty, 0);
9763 else if (Known.isNegative())
9764 StableValue = ConstantInt::get(Ty, -1, true);
9765 else
9766 return getCouldNotCompute();
9767
9768 break;
9769 }
9770 case Instruction::LShr:
9771 case Instruction::Shl:
9772 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
9773 // stabilize to 0 in at most bitwidth(K) iterations.
9774 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
9775 break;
9776 }
9777
9778 auto *Result =
9779 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
9780 assert(Result->getType()->isIntegerTy(1) &&
9781 "Otherwise cannot be an operand to a branch instruction");
9782
9783 if (Result->isNullValue()) {
9784 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9785 unsigned MaxBTC = BitWidth;
9786
9787 // For right-shift recurrences (lshr/ashr with non-negative start), we can
9788 // compute a tighter max backedge-taken count from the range of the start
9789 // value. After k shifts of ShiftAmt, value = start >> (k * ShiftAmt).
9790 // The value reaches 0 (the stable value) when k * ShiftAmt >=
9791 // activeBits(start), so max BTC = ceil(activeBits(maxStart) / ShiftAmt).
9792 if (OpCode == Instruction::LShr || OpCode == Instruction::AShr) {
9793 Value *StartValue = PN->getIncomingValueForBlock(Predecessor);
9794 const SCEV *StartSCEV = getSCEV(StartValue);
9795 APInt MaxStart = getUnsignedRangeMax(StartSCEV);
9796 if (MaxStart.isStrictlyPositive()) {
9797 unsigned ActiveBits = MaxStart.getActiveBits();
9798 unsigned RangeBTC = divideCeil(ActiveBits, ShiftAmt);
9799 MaxBTC = std::min(MaxBTC, RangeBTC);
9800 }
9801 }
9802
9803 const SCEV *UpperBound =
9805 return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
9806 }
9807
9808 return getCouldNotCompute();
9809}
9810
9811/// Return true if we can constant fold an instruction of the specified type,
9812/// assuming that all operands were constants.
9813static bool CanConstantFold(const Instruction *I) {
9817 return true;
9818
9819 if (const CallInst *CI = dyn_cast<CallInst>(I))
9820 if (const Function *F = CI->getCalledFunction())
9821 return canConstantFoldCallTo(CI, F);
9822 return false;
9823}
9824
9825/// Determine whether this instruction can constant evolve within this loop
9826/// assuming its operands can all constant evolve.
9827static bool canConstantEvolve(Instruction *I, const Loop *L) {
9828 // An instruction outside of the loop can't be derived from a loop PHI.
9829 if (!L->contains(I)) return false;
9830
9831 if (isa<PHINode>(I)) {
9832 // We don't currently keep track of the control flow needed to evaluate
9833 // PHIs, so we cannot handle PHIs inside of loops.
9834 return L->getHeader() == I->getParent();
9835 }
9836
9837 // If we won't be able to constant fold this expression even if the operands
9838 // are constants, bail early.
9839 return CanConstantFold(I);
9840}
9841
9842/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
9843/// recursing through each instruction operand until reaching a loop header phi.
9844static PHINode *
9847 unsigned Depth) {
9849 return nullptr;
9850
9851 // Otherwise, we can evaluate this instruction if all of its operands are
9852 // constant or derived from a PHI node themselves.
9853 PHINode *PHI = nullptr;
9854 for (Value *Op : UseInst->operands()) {
9855 if (isa<Constant>(Op)) continue;
9856
9858 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
9859
9860 PHINode *P = dyn_cast<PHINode>(OpInst);
9861 if (!P)
9862 // If this operand is already visited, reuse the prior result.
9863 // We may have P != PHI if this is the deepest point at which the
9864 // inconsistent paths meet.
9865 P = PHIMap.lookup(OpInst);
9866 if (!P) {
9867 // Recurse and memoize the results, whether a phi is found or not.
9868 // This recursive call invalidates pointers into PHIMap.
9869 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
9870 PHIMap[OpInst] = P;
9871 }
9872 if (!P)
9873 return nullptr; // Not evolving from PHI
9874 if (PHI && PHI != P)
9875 return nullptr; // Evolving from multiple different PHIs.
9876 PHI = P;
9877 }
9878 // This is a expression evolving from a constant PHI!
9879 return PHI;
9880}
9881
9882/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9883/// in the loop that V is derived from. We allow arbitrary operations along the
9884/// way, but the operands of an operation must either be constants or a value
9885/// derived from a constant PHI. If this expression does not fit with these
9886/// constraints, return null.
9889 if (!I || !canConstantEvolve(I, L)) return nullptr;
9890
9891 if (PHINode *PN = dyn_cast<PHINode>(I))
9892 return PN;
9893
9894 // Record non-constant instructions contained by the loop.
9896 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
9897}
9898
9899/// EvaluateExpression - Given an expression that passes the
9900/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9901/// in the loop has the value PHIVal. If we can't fold this expression for some
9902/// reason, return null.
9905 const DataLayout &DL,
9906 const TargetLibraryInfo *TLI) {
9907 // Convenient constant check, but redundant for recursive calls.
9908 if (Constant *C = dyn_cast<Constant>(V)) return C;
9910 if (!I) return nullptr;
9911
9912 if (Constant *C = Vals.lookup(I)) return C;
9913
9914 // An instruction inside the loop depends on a value outside the loop that we
9915 // weren't given a mapping for, or a value such as a call inside the loop.
9916 if (!canConstantEvolve(I, L)) return nullptr;
9917
9918 // An unmapped PHI can be due to a branch or another loop inside this loop,
9919 // or due to this not being the initial iteration through a loop where we
9920 // couldn't compute the evolution of this particular PHI last time.
9921 if (isa<PHINode>(I)) return nullptr;
9922
9923 std::vector<Constant*> Operands(I->getNumOperands());
9924
9925 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9926 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9927 if (!Operand) {
9928 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9929 if (!Operands[i]) return nullptr;
9930 continue;
9931 }
9932 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9933 Vals[Operand] = C;
9934 if (!C) return nullptr;
9935 Operands[i] = C;
9936 }
9937
9938 return ConstantFoldInstOperands(I, Operands, DL, TLI,
9939 /*AllowNonDeterministic=*/false);
9940}
9941
9942
9943// If every incoming value to PN except the one for BB is a specific Constant,
9944// return that, else return nullptr.
9946 Constant *IncomingVal = nullptr;
9947
9948 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9949 if (PN->getIncomingBlock(i) == BB)
9950 continue;
9951
9952 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
9953 if (!CurrentVal)
9954 return nullptr;
9955
9956 if (IncomingVal != CurrentVal) {
9957 if (IncomingVal)
9958 return nullptr;
9959 IncomingVal = CurrentVal;
9960 }
9961 }
9962
9963 return IncomingVal;
9964}
9965
9966/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9967/// in the header of its containing loop, we know the loop executes a
9968/// constant number of times, and the PHI node is just a recurrence
9969/// involving constants, fold it.
9970Constant *
9971ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9972 const APInt &BEs,
9973 const Loop *L) {
9974 auto [I, Inserted] = ConstantEvolutionLoopExitValue.try_emplace(PN);
9975 if (!Inserted)
9976 return I->second;
9977
9979 return nullptr; // Not going to evaluate it.
9980
9981 Constant *&RetVal = I->second;
9982
9983 DenseMap<Instruction *, Constant *> CurrentIterVals;
9984 BasicBlock *Header = L->getHeader();
9985 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9986
9987 BasicBlock *Latch = L->getLoopLatch();
9988 if (!Latch)
9989 return nullptr;
9990
9991 for (PHINode &PHI : Header->phis()) {
9992 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9993 CurrentIterVals[&PHI] = StartCST;
9994 }
9995 if (!CurrentIterVals.count(PN))
9996 return RetVal = nullptr;
9997
9998 Value *BEValue = PN->getIncomingValueForBlock(Latch);
9999
10000 // Execute the loop symbolically to determine the exit value.
10001 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
10002 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
10003
10004 unsigned NumIterations = BEs.getZExtValue(); // must be in range
10005 unsigned IterationNum = 0;
10006 const DataLayout &DL = getDataLayout();
10007 for (; ; ++IterationNum) {
10008 if (IterationNum == NumIterations)
10009 return RetVal = CurrentIterVals[PN]; // Got exit value!
10010
10011 // Compute the value of the PHIs for the next iteration.
10012 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
10013 DenseMap<Instruction *, Constant *> NextIterVals;
10014 Constant *NextPHI =
10015 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
10016 if (!NextPHI)
10017 return nullptr; // Couldn't evaluate!
10018 NextIterVals[PN] = NextPHI;
10019
10020 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
10021
10022 // Also evaluate the other PHI nodes. However, we don't get to stop if we
10023 // cease to be able to evaluate one of them or if they stop evolving,
10024 // because that doesn't necessarily prevent us from computing PN.
10026 for (const auto &I : CurrentIterVals) {
10027 PHINode *PHI = dyn_cast<PHINode>(I.first);
10028 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
10029 PHIsToCompute.emplace_back(PHI, I.second);
10030 }
10031 // We use two distinct loops because EvaluateExpression may invalidate any
10032 // iterators into CurrentIterVals.
10033 for (const auto &I : PHIsToCompute) {
10034 PHINode *PHI = I.first;
10035 Constant *&NextPHI = NextIterVals[PHI];
10036 if (!NextPHI) { // Not already computed.
10037 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
10038 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
10039 }
10040 if (NextPHI != I.second)
10041 StoppedEvolving = false;
10042 }
10043
10044 // If all entries in CurrentIterVals == NextIterVals then we can stop
10045 // iterating, the loop can't continue to change.
10046 if (StoppedEvolving)
10047 return RetVal = CurrentIterVals[PN];
10048
10049 CurrentIterVals.swap(NextIterVals);
10050 }
10051}
10052
10053const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
10054 Value *Cond,
10055 bool ExitWhen) {
10056 PHINode *PN = getConstantEvolvingPHI(Cond, L);
10057 if (!PN) return getCouldNotCompute();
10058
10059 // If the loop is canonicalized, the PHI will have exactly two entries.
10060 // That's the only form we support here.
10061 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
10062
10063 DenseMap<Instruction *, Constant *> CurrentIterVals;
10064 BasicBlock *Header = L->getHeader();
10065 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
10066
10067 BasicBlock *Latch = L->getLoopLatch();
10068 assert(Latch && "Should follow from NumIncomingValues == 2!");
10069
10070 for (PHINode &PHI : Header->phis()) {
10071 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
10072 CurrentIterVals[&PHI] = StartCST;
10073 }
10074 if (!CurrentIterVals.count(PN))
10075 return getCouldNotCompute();
10076
10077 // Okay, we find a PHI node that defines the trip count of this loop. Execute
10078 // the loop symbolically to determine when the condition gets a value of
10079 // "ExitWhen".
10080 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
10081 const DataLayout &DL = getDataLayout();
10082 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
10083 auto *CondVal = dyn_cast_or_null<ConstantInt>(
10084 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
10085
10086 // Couldn't symbolically evaluate.
10087 if (!CondVal) return getCouldNotCompute();
10088
10089 if (CondVal->getValue() == uint64_t(ExitWhen)) {
10090 ++NumBruteForceTripCountsComputed;
10091 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
10092 }
10093
10094 // Update all the PHI nodes for the next iteration.
10095 DenseMap<Instruction *, Constant *> NextIterVals;
10096
10097 // Create a list of which PHIs we need to compute. We want to do this before
10098 // calling EvaluateExpression on them because that may invalidate iterators
10099 // into CurrentIterVals.
10100 SmallVector<PHINode *, 8> PHIsToCompute;
10101 for (const auto &I : CurrentIterVals) {
10102 PHINode *PHI = dyn_cast<PHINode>(I.first);
10103 if (!PHI || PHI->getParent() != Header) continue;
10104 PHIsToCompute.push_back(PHI);
10105 }
10106 for (PHINode *PHI : PHIsToCompute) {
10107 Constant *&NextPHI = NextIterVals[PHI];
10108 if (NextPHI) continue; // Already computed!
10109
10110 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
10111 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
10112 }
10113 CurrentIterVals.swap(NextIterVals);
10114 }
10115
10116 // Too many iterations were needed to evaluate.
10117 return getCouldNotCompute();
10118}
10119
10120const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
10122 ValuesAtScopes[V];
10123 // Check to see if we've folded this expression at this loop before.
10124 for (auto &LS : Values)
10125 if (LS.first == L)
10126 return LS.second ? LS.second : V;
10127
10128 Values.emplace_back(L, nullptr);
10129
10130 // Otherwise compute it.
10131 const SCEV *C = computeSCEVAtScope(V, L);
10132 for (auto &LS : reverse(ValuesAtScopes[V]))
10133 if (LS.first == L) {
10134 LS.second = C;
10135 if (!isa<SCEVConstant>(C))
10136 ValuesAtScopesUsers[C].push_back({L, V});
10137 break;
10138 }
10139 return C;
10140}
10141
10142/// This builds up a Constant using the ConstantExpr interface. That way, we
10143/// will return Constants for objects which aren't represented by a
10144/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
10145/// Returns NULL if the SCEV isn't representable as a Constant.
10147 switch (V->getSCEVType()) {
10148 case scCouldNotCompute:
10149 case scAddRecExpr:
10150 case scVScale:
10151 return nullptr;
10152 case scConstant:
10153 return cast<SCEVConstant>(V)->getValue();
10154 case scUnknown:
10156 case scPtrToAddr: {
10158 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
10159 return ConstantExpr::getPtrToAddr(CastOp, P2I->getType());
10160
10161 return nullptr;
10162 }
10163 case scTruncate: {
10165 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
10166 return ConstantExpr::getTrunc(CastOp, ST->getType());
10167 return nullptr;
10168 }
10169 case scAddExpr: {
10170 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
10171 Constant *C = nullptr;
10172 for (const SCEV *Op : SA->operands()) {
10174 if (!OpC)
10175 return nullptr;
10176 if (!C) {
10177 C = OpC;
10178 continue;
10179 }
10180 assert(!C->getType()->isPointerTy() &&
10181 "Can only have one pointer, and it must be last");
10182 if (OpC->getType()->isPointerTy()) {
10183 // The offsets have been converted to bytes. We can add bytes using
10184 // an i8 GEP.
10185 C = ConstantExpr::getPtrAdd(OpC, C);
10186 } else {
10187 C = ConstantExpr::getAdd(C, OpC);
10188 }
10189 }
10190 return C;
10191 }
10192 case scMulExpr:
10193 case scSignExtend:
10194 case scZeroExtend:
10195 case scUDivExpr:
10196 case scSMaxExpr:
10197 case scUMaxExpr:
10198 case scSMinExpr:
10199 case scUMinExpr:
10201 return nullptr;
10202 }
10203 llvm_unreachable("Unknown SCEV kind!");
10204}
10205
10206const SCEV *ScalarEvolution::getWithOperands(const SCEV *S,
10207 SmallVectorImpl<SCEVUse> &NewOps) {
10208 switch (S->getSCEVType()) {
10209 case scTruncate:
10210 case scZeroExtend:
10211 case scSignExtend:
10212 case scPtrToAddr:
10213 return getCastExpr(S->getSCEVType(), NewOps[0], S->getType());
10214 case scAddRecExpr: {
10215 auto *AddRec = cast<SCEVAddRecExpr>(S);
10216 return getAddRecExpr(NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags());
10217 }
10218 case scAddExpr:
10219 return getAddExpr(NewOps, cast<SCEVAddExpr>(S)->getNoWrapFlags());
10220 case scMulExpr:
10221 return getMulExpr(NewOps, cast<SCEVMulExpr>(S)->getNoWrapFlags());
10222 case scUDivExpr:
10223 return getUDivExpr(NewOps[0], NewOps[1]);
10224 case scUMaxExpr:
10225 case scSMaxExpr:
10226 case scUMinExpr:
10227 case scSMinExpr:
10228 return getMinMaxExpr(S->getSCEVType(), NewOps);
10230 return getSequentialMinMaxExpr(S->getSCEVType(), NewOps);
10231 case scConstant:
10232 case scVScale:
10233 case scUnknown:
10234 return S;
10235 case scCouldNotCompute:
10236 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10237 }
10238 llvm_unreachable("Unknown SCEV kind!");
10239}
10240
10241const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
10242 switch (V->getSCEVType()) {
10243 case scConstant:
10244 case scVScale:
10245 return V;
10246 case scAddRecExpr: {
10247 // If this is a loop recurrence for a loop that does not contain L, then we
10248 // are dealing with the final value computed by the loop.
10249 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(V);
10250 // First, attempt to evaluate each operand.
10251 // Avoid performing the look-up in the common case where the specified
10252 // expression has no loop-variant portions.
10253 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
10254 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
10255 if (OpAtScope == AddRec->getOperand(i))
10256 continue;
10257
10258 // Okay, at least one of these operands is loop variant but might be
10259 // foldable. Build a new instance of the folded commutative expression.
10261 NewOps.reserve(AddRec->getNumOperands());
10262 append_range(NewOps, AddRec->operands().take_front(i));
10263 NewOps.push_back(OpAtScope);
10264 for (++i; i != e; ++i)
10265 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
10266
10267 const SCEV *FoldedRec = getAddRecExpr(
10268 NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags(SCEV::FlagNW));
10269 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
10270 // The addrec may be folded to a nonrecurrence, for example, if the
10271 // induction variable is multiplied by zero after constant folding. Go
10272 // ahead and return the folded value.
10273 if (!AddRec)
10274 return FoldedRec;
10275 break;
10276 }
10277
10278 // If the scope is outside the addrec's loop, evaluate it by using the
10279 // loop exit value of the addrec.
10280 if (!AddRec->getLoop()->contains(L)) {
10281 // To evaluate this recurrence, we need to know how many times the AddRec
10282 // loop iterates. Compute this now.
10283 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
10284 if (BackedgeTakenCount == getCouldNotCompute())
10285 return AddRec;
10286
10287 // Then, evaluate the AddRec.
10288 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
10289 }
10290
10291 return AddRec;
10292 }
10293 case scTruncate:
10294 case scZeroExtend:
10295 case scSignExtend:
10296 case scPtrToAddr:
10297 case scAddExpr:
10298 case scMulExpr:
10299 case scUDivExpr:
10300 case scUMaxExpr:
10301 case scSMaxExpr:
10302 case scUMinExpr:
10303 case scSMinExpr:
10304 case scSequentialUMinExpr: {
10305 ArrayRef<SCEVUse> Ops = V->operands();
10306 // Avoid performing the look-up in the common case where the specified
10307 // expression has no loop-variant portions.
10308 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
10309 const SCEV *OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10310 if (OpAtScope != Ops[i].getPointer()) {
10311 // Okay, at least one of these operands is loop variant but might be
10312 // foldable. Build a new instance of the folded commutative expression.
10314 NewOps.reserve(Ops.size());
10315 append_range(NewOps, Ops.take_front(i));
10316 NewOps.push_back(OpAtScope);
10317
10318 for (++i; i != e; ++i) {
10319 OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10320 NewOps.push_back(OpAtScope);
10321 }
10322
10323 return getWithOperands(V, NewOps);
10324 }
10325 }
10326 // If we got here, all operands are loop invariant.
10327 return V;
10328 }
10329 case scUnknown: {
10330 // If this instruction is evolved from a constant-evolving PHI, compute the
10331 // exit value from the loop without using SCEVs.
10332 const SCEVUnknown *SU = cast<SCEVUnknown>(V);
10334 if (!I)
10335 return V; // This is some other type of SCEVUnknown, just return it.
10336
10337 if (PHINode *PN = dyn_cast<PHINode>(I)) {
10338 const Loop *CurrLoop = this->LI[I->getParent()];
10339 // Looking for loop exit value.
10340 if (CurrLoop && CurrLoop->getParentLoop() == L &&
10341 PN->getParent() == CurrLoop->getHeader()) {
10342 // Okay, there is no closed form solution for the PHI node. Check
10343 // to see if the loop that contains it has a known backedge-taken
10344 // count. If so, we may be able to force computation of the exit
10345 // value.
10346 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
10347 // This trivial case can show up in some degenerate cases where
10348 // the incoming IR has not yet been fully simplified.
10349 if (BackedgeTakenCount->isZero()) {
10350 Value *InitValue = nullptr;
10351 bool MultipleInitValues = false;
10352 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
10353 if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
10354 if (!InitValue)
10355 InitValue = PN->getIncomingValue(i);
10356 else if (InitValue != PN->getIncomingValue(i)) {
10357 MultipleInitValues = true;
10358 break;
10359 }
10360 }
10361 }
10362 if (!MultipleInitValues && InitValue)
10363 return getSCEV(InitValue);
10364 }
10365 // Do we have a loop invariant value flowing around the backedge
10366 // for a loop which must execute the backedge?
10367 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
10368 isKnownNonZero(BackedgeTakenCount) &&
10369 PN->getNumIncomingValues() == 2) {
10370
10371 unsigned InLoopPred =
10372 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
10373 Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
10374 if (CurrLoop->isLoopInvariant(BackedgeVal))
10375 return getSCEV(BackedgeVal);
10376 }
10377 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
10378 // Okay, we know how many times the containing loop executes. If
10379 // this is a constant evolving PHI node, get the final value at
10380 // the specified iteration number.
10381 Constant *RV =
10382 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
10383 if (RV)
10384 return getSCEV(RV);
10385 }
10386 }
10387 }
10388
10389 // Okay, this is an expression that we cannot symbolically evaluate
10390 // into a SCEV. Check to see if it's possible to symbolically evaluate
10391 // the arguments into constants, and if so, try to constant propagate the
10392 // result. This is particularly useful for computing loop exit values.
10393 if (!CanConstantFold(I))
10394 return V; // This is some other type of SCEVUnknown, just return it.
10395
10396 SmallVector<Constant *, 4> Operands;
10397 Operands.reserve(I->getNumOperands());
10398 bool MadeImprovement = false;
10399 for (Value *Op : I->operands()) {
10400 if (Constant *C = dyn_cast<Constant>(Op)) {
10401 Operands.push_back(C);
10402 continue;
10403 }
10404
10405 // If any of the operands is non-constant and if they are
10406 // non-integer and non-pointer, don't even try to analyze them
10407 // with scev techniques.
10408 if (!isSCEVable(Op->getType()))
10409 return V;
10410
10411 const SCEV *OrigV = getSCEV(Op);
10412 const SCEV *OpV = getSCEVAtScope(OrigV, L);
10413 MadeImprovement |= OrigV != OpV;
10414
10416 if (!C)
10417 return V;
10418 assert(C->getType() == Op->getType() && "Type mismatch");
10419 Operands.push_back(C);
10420 }
10421
10422 // Check to see if getSCEVAtScope actually made an improvement.
10423 if (!MadeImprovement)
10424 return V; // This is some other type of SCEVUnknown, just return it.
10425
10426 Constant *C = nullptr;
10427 const DataLayout &DL = getDataLayout();
10428 C = ConstantFoldInstOperands(I, Operands, DL, &TLI,
10429 /*AllowNonDeterministic=*/false);
10430 if (!C)
10431 return V;
10432 return getSCEV(C);
10433 }
10434 case scCouldNotCompute:
10435 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10436 }
10437 llvm_unreachable("Unknown SCEV type!");
10438}
10439
10441 return getSCEVAtScope(getSCEV(V), L);
10442}
10443
10444const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
10446 return stripInjectiveFunctions(ZExt->getOperand());
10448 return stripInjectiveFunctions(SExt->getOperand());
10449 return S;
10450}
10451
10452/// Finds the minimum unsigned root of the following equation:
10453///
10454/// A * X = B (mod N)
10455///
10456/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
10457/// A and B isn't important.
10458///
10459/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
10460static const SCEV *
10463 ScalarEvolution &SE, const Loop *L) {
10464 uint32_t BW = A.getBitWidth();
10465 assert(BW == SE.getTypeSizeInBits(B->getType()));
10466 assert(A != 0 && "A must be non-zero.");
10467
10468 // 1. D = gcd(A, N)
10469 //
10470 // The gcd of A and N may have only one prime factor: 2. The number of
10471 // trailing zeros in A is its multiplicity
10472 uint32_t Mult2 = A.countr_zero();
10473 // D = 2^Mult2
10474
10475 // 2. Check if B is divisible by D.
10476 //
10477 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
10478 // is not less than multiplicity of this prime factor for D.
10479 unsigned MinTZ = SE.getMinTrailingZeros(B);
10480 // Try again with the terminator of the loop predecessor for context-specific
10481 // result, if MinTZ s too small.
10482 if (MinTZ < Mult2 && L->getLoopPredecessor())
10483 MinTZ = SE.getMinTrailingZeros(B, L->getLoopPredecessor()->getTerminator());
10484 if (MinTZ < Mult2) {
10485 // Check if we can prove there's no remainder using URem.
10486 const SCEV *URem =
10487 SE.getURemExpr(B, SE.getConstant(APInt::getOneBitSet(BW, Mult2)));
10488 const SCEV *Zero = SE.getZero(B->getType());
10489 if (!SE.isKnownPredicate(CmpInst::ICMP_EQ, URem, Zero)) {
10490 // Try to add a predicate ensuring B is a multiple of 1 << Mult2.
10491 if (!Predicates)
10492 return SE.getCouldNotCompute();
10493
10494 // Avoid adding a predicate that is known to be false.
10495 if (SE.isKnownPredicate(CmpInst::ICMP_NE, URem, Zero))
10496 return SE.getCouldNotCompute();
10497 Predicates->push_back(SE.getEqualPredicate(URem, Zero));
10498 }
10499 }
10500
10501 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
10502 // modulo (N / D).
10503 //
10504 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
10505 // (N / D) in general. The inverse itself always fits into BW bits, though,
10506 // so we immediately truncate it.
10507 APInt AD = A.lshr(Mult2).trunc(BW - Mult2); // AD = A / D
10508 APInt I = AD.multiplicativeInverse().zext(BW);
10509
10510 // 4. Compute the minimum unsigned root of the equation:
10511 // I * (B / D) mod (N / D)
10512 // To simplify the computation, we factor out the divide by D:
10513 // (I * B mod N) / D
10514 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
10515 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
10516}
10517
10518/// For a given quadratic addrec, generate coefficients of the corresponding
10519/// quadratic equation, multiplied by a common value to ensure that they are
10520/// integers.
10521/// The returned value is a tuple { A, B, C, M, BitWidth }, where
10522/// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
10523/// were multiplied by, and BitWidth is the bit width of the original addrec
10524/// coefficients.
10525/// This function returns std::nullopt if the addrec coefficients are not
10526/// compile- time constants.
10527static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
10529 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
10530 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
10531 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
10532 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
10533 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
10534 << *AddRec << '\n');
10535
10536 // We currently can only solve this if the coefficients are constants.
10537 if (!LC || !MC || !NC) {
10538 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
10539 return std::nullopt;
10540 }
10541
10542 APInt L = LC->getAPInt();
10543 APInt M = MC->getAPInt();
10544 APInt N = NC->getAPInt();
10545 assert(!N.isZero() && "This is not a quadratic addrec");
10546
10547 unsigned BitWidth = LC->getAPInt().getBitWidth();
10548 unsigned NewWidth = BitWidth + 1;
10549 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
10550 << BitWidth << '\n');
10551 // The sign-extension (as opposed to a zero-extension) here matches the
10552 // extension used in SolveQuadraticEquationWrap (with the same motivation).
10553 N = N.sext(NewWidth);
10554 M = M.sext(NewWidth);
10555 L = L.sext(NewWidth);
10556
10557 // The increments are M, M+N, M+2N, ..., so the accumulated values are
10558 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
10559 // L+M, L+2M+N, L+3M+3N, ...
10560 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
10561 //
10562 // The equation Acc = 0 is then
10563 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
10564 // In a quadratic form it becomes:
10565 // N n^2 + (2M-N) n + 2L = 0.
10566
10567 APInt A = N;
10568 APInt B = 2 * M - A;
10569 APInt C = 2 * L;
10570 APInt T = APInt(NewWidth, 2);
10571 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
10572 << "x + " << C << ", coeff bw: " << NewWidth
10573 << ", multiplied by " << T << '\n');
10574 return std::make_tuple(A, B, C, T, BitWidth);
10575}
10576
10577/// Helper function to compare optional APInts:
10578/// (a) if X and Y both exist, return min(X, Y),
10579/// (b) if neither X nor Y exist, return std::nullopt,
10580/// (c) if exactly one of X and Y exists, return that value.
10581static std::optional<APInt> MinOptional(std::optional<APInt> X,
10582 std::optional<APInt> Y) {
10583 if (X && Y) {
10584 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
10585 APInt XW = X->sext(W);
10586 APInt YW = Y->sext(W);
10587 return XW.slt(YW) ? *X : *Y;
10588 }
10589 if (!X && !Y)
10590 return std::nullopt;
10591 return X ? *X : *Y;
10592}
10593
10594/// Helper function to truncate an optional APInt to a given BitWidth.
10595/// When solving addrec-related equations, it is preferable to return a value
10596/// that has the same bit width as the original addrec's coefficients. If the
10597/// solution fits in the original bit width, truncate it (except for i1).
10598/// Returning a value of a different bit width may inhibit some optimizations.
10599///
10600/// In general, a solution to a quadratic equation generated from an addrec
10601/// may require BW+1 bits, where BW is the bit width of the addrec's
10602/// coefficients. The reason is that the coefficients of the quadratic
10603/// equation are BW+1 bits wide (to avoid truncation when converting from
10604/// the addrec to the equation).
10605static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
10606 unsigned BitWidth) {
10607 if (!X)
10608 return std::nullopt;
10609 unsigned W = X->getBitWidth();
10611 return X->trunc(BitWidth);
10612 return X;
10613}
10614
10615/// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
10616/// iterations. The values L, M, N are assumed to be signed, and they
10617/// should all have the same bit widths.
10618/// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
10619/// where BW is the bit width of the addrec's coefficients.
10620/// If the calculated value is a BW-bit integer (for BW > 1), it will be
10621/// returned as such, otherwise the bit width of the returned value may
10622/// be greater than BW.
10623///
10624/// This function returns std::nullopt if
10625/// (a) the addrec coefficients are not constant, or
10626/// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
10627/// like x^2 = 5, no integer solutions exist, in other cases an integer
10628/// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
10629static std::optional<APInt>
10631 APInt A, B, C, M;
10632 unsigned BitWidth;
10633 auto T = GetQuadraticEquation(AddRec);
10634 if (!T)
10635 return std::nullopt;
10636
10637 std::tie(A, B, C, M, BitWidth) = *T;
10638 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
10639 std::optional<APInt> X =
10641 if (!X)
10642 return std::nullopt;
10643
10644 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
10645 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
10646 if (!V->isZero())
10647 return std::nullopt;
10648
10649 return TruncIfPossible(X, BitWidth);
10650}
10651
10652/// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
10653/// iterations. The values M, N are assumed to be signed, and they
10654/// should all have the same bit widths.
10655/// Find the least n such that c(n) does not belong to the given range,
10656/// while c(n-1) does.
10657///
10658/// This function returns std::nullopt if
10659/// (a) the addrec coefficients are not constant, or
10660/// (b) SolveQuadraticEquationWrap was unable to find a solution for the
10661/// bounds of the range.
10662static std::optional<APInt>
10664 const ConstantRange &Range, ScalarEvolution &SE) {
10665 assert(AddRec->getOperand(0)->isZero() &&
10666 "Starting value of addrec should be 0");
10667 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
10668 << Range << ", addrec " << *AddRec << '\n');
10669 // This case is handled in getNumIterationsInRange. Here we can assume that
10670 // we start in the range.
10671 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
10672 "Addrec's initial value should be in range");
10673
10674 APInt A, B, C, M;
10675 unsigned BitWidth;
10676 auto T = GetQuadraticEquation(AddRec);
10677 if (!T)
10678 return std::nullopt;
10679
10680 // Be careful about the return value: there can be two reasons for not
10681 // returning an actual number. First, if no solutions to the equations
10682 // were found, and second, if the solutions don't leave the given range.
10683 // The first case means that the actual solution is "unknown", the second
10684 // means that it's known, but not valid. If the solution is unknown, we
10685 // cannot make any conclusions.
10686 // Return a pair: the optional solution and a flag indicating if the
10687 // solution was found.
10688 auto SolveForBoundary =
10689 [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
10690 // Solve for signed overflow and unsigned overflow, pick the lower
10691 // solution.
10692 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
10693 << Bound << " (before multiplying by " << M << ")\n");
10694 Bound *= M; // The quadratic equation multiplier.
10695
10696 std::optional<APInt> SO;
10697 if (BitWidth > 1) {
10698 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10699 "signed overflow\n");
10701 }
10702 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10703 "unsigned overflow\n");
10704 std::optional<APInt> UO =
10706
10707 auto LeavesRange = [&] (const APInt &X) {
10708 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
10709 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
10710 if (Range.contains(V0->getValue()))
10711 return false;
10712 // X should be at least 1, so X-1 is non-negative.
10713 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
10715 if (Range.contains(V1->getValue()))
10716 return true;
10717 return false;
10718 };
10719
10720 // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
10721 // can be a solution, but the function failed to find it. We cannot treat it
10722 // as "no solution".
10723 if (!SO || !UO)
10724 return {std::nullopt, false};
10725
10726 // Check the smaller value first to see if it leaves the range.
10727 // At this point, both SO and UO must have values.
10728 std::optional<APInt> Min = MinOptional(SO, UO);
10729 if (LeavesRange(*Min))
10730 return { Min, true };
10731 std::optional<APInt> Max = Min == SO ? UO : SO;
10732 if (LeavesRange(*Max))
10733 return { Max, true };
10734
10735 // Solutions were found, but were eliminated, hence the "true".
10736 return {std::nullopt, true};
10737 };
10738
10739 std::tie(A, B, C, M, BitWidth) = *T;
10740 // Lower bound is inclusive, subtract 1 to represent the exiting value.
10741 APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
10742 APInt Upper = Range.getUpper().sext(A.getBitWidth());
10743 auto SL = SolveForBoundary(Lower);
10744 auto SU = SolveForBoundary(Upper);
10745 // If any of the solutions was unknown, no meaninigful conclusions can
10746 // be made.
10747 if (!SL.second || !SU.second)
10748 return std::nullopt;
10749
10750 // Claim: The correct solution is not some value between Min and Max.
10751 //
10752 // Justification: Assuming that Min and Max are different values, one of
10753 // them is when the first signed overflow happens, the other is when the
10754 // first unsigned overflow happens. Crossing the range boundary is only
10755 // possible via an overflow (treating 0 as a special case of it, modeling
10756 // an overflow as crossing k*2^W for some k).
10757 //
10758 // The interesting case here is when Min was eliminated as an invalid
10759 // solution, but Max was not. The argument is that if there was another
10760 // overflow between Min and Max, it would also have been eliminated if
10761 // it was considered.
10762 //
10763 // For a given boundary, it is possible to have two overflows of the same
10764 // type (signed/unsigned) without having the other type in between: this
10765 // can happen when the vertex of the parabola is between the iterations
10766 // corresponding to the overflows. This is only possible when the two
10767 // overflows cross k*2^W for the same k. In such case, if the second one
10768 // left the range (and was the first one to do so), the first overflow
10769 // would have to enter the range, which would mean that either we had left
10770 // the range before or that we started outside of it. Both of these cases
10771 // are contradictions.
10772 //
10773 // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
10774 // solution is not some value between the Max for this boundary and the
10775 // Min of the other boundary.
10776 //
10777 // Justification: Assume that we had such Max_A and Min_B corresponding
10778 // to range boundaries A and B and such that Max_A < Min_B. If there was
10779 // a solution between Max_A and Min_B, it would have to be caused by an
10780 // overflow corresponding to either A or B. It cannot correspond to B,
10781 // since Min_B is the first occurrence of such an overflow. If it
10782 // corresponded to A, it would have to be either a signed or an unsigned
10783 // overflow that is larger than both eliminated overflows for A. But
10784 // between the eliminated overflows and this overflow, the values would
10785 // cover the entire value space, thus crossing the other boundary, which
10786 // is a contradiction.
10787
10788 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
10789}
10790
10791ScalarEvolution::ExitLimit ScalarEvolution::howFarToZero(const SCEV *V,
10792 const Loop *L,
10793 bool ControlsOnlyExit,
10794 bool AllowPredicates) {
10795
10796 // This is only used for loops with a "x != y" exit test. The exit condition
10797 // is now expressed as a single expression, V = x-y. So the exit test is
10798 // effectively V != 0. We know and take advantage of the fact that this
10799 // expression only being used in a comparison by zero context.
10800
10802 // If the value is a constant
10803 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10804 // If the value is already zero, the branch will execute zero times.
10805 if (C->getValue()->isZero()) return C;
10806 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10807 }
10808
10809 const SCEVAddRecExpr *AddRec =
10810 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
10811
10812 if (!AddRec && AllowPredicates)
10813 // Try to make this an AddRec using runtime tests, in the first X
10814 // iterations of this loop, where X is the SCEV expression found by the
10815 // algorithm below.
10816 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
10817
10818 if (!AddRec || AddRec->getLoop() != L)
10819 return getCouldNotCompute();
10820
10821 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
10822 // the quadratic equation to solve it.
10823 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
10824 // We can only use this value if the chrec ends up with an exact zero
10825 // value at this index. When solving for "X*X != 5", for example, we
10826 // should not accept a root of 2.
10827 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
10828 const auto *R = cast<SCEVConstant>(getConstant(*S));
10829 return ExitLimit(R, R, R, false, Predicates);
10830 }
10831 return getCouldNotCompute();
10832 }
10833
10834 // Otherwise we can only handle this if it is affine.
10835 if (!AddRec->isAffine())
10836 return getCouldNotCompute();
10837
10838 // If this is an affine expression, the execution count of this branch is
10839 // the minimum unsigned root of the following equation:
10840 //
10841 // Start + Step*N = 0 (mod 2^BW)
10842 //
10843 // equivalent to:
10844 //
10845 // Step*N = -Start (mod 2^BW)
10846 //
10847 // where BW is the common bit width of Start and Step.
10848
10849 // Get the initial value for the loop.
10850 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
10851 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
10852
10853 if (!isLoopInvariant(Step, L))
10854 return getCouldNotCompute();
10855
10856 LoopGuards Guards = LoopGuards::collect(L, *this);
10857 // Specialize step for this loop so we get context sensitive facts below.
10858 const SCEV *StepWLG = applyLoopGuards(Step, Guards);
10859
10860 // For positive steps (counting up until unsigned overflow):
10861 // N = -Start/Step (as unsigned)
10862 // For negative steps (counting down to zero):
10863 // N = Start/-Step
10864 // First compute the unsigned distance from zero in the direction of Step.
10865 bool CountDown = isKnownNegative(StepWLG);
10866 if (!CountDown && !isKnownNonNegative(StepWLG))
10867 return getCouldNotCompute();
10868
10869 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
10870 // Handle unitary steps, which cannot wraparound.
10871 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10872 // N = Distance (as unsigned)
10873
10874 if (match(Step, m_CombineOr(m_scev_One(), m_scev_AllOnes()))) {
10875 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, Guards));
10876 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
10877
10878 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10879 // we end up with a loop whose backedge-taken count is n - 1. Detect this
10880 // case, and see if we can improve the bound.
10881 //
10882 // Explicitly handling this here is necessary because getUnsignedRange
10883 // isn't context-sensitive; it doesn't know that we only care about the
10884 // range inside the loop.
10885 const SCEV *Zero = getZero(Distance->getType());
10886 const SCEV *One = getOne(Distance->getType());
10887 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
10888 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
10889 // If Distance + 1 doesn't overflow, we can compute the maximum distance
10890 // as "unsigned_max(Distance + 1) - 1".
10891 ConstantRange CR = getUnsignedRange(DistancePlusOne);
10892 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
10893 }
10894 return ExitLimit(Distance, getConstant(MaxBECount), Distance, false,
10895 Predicates);
10896 }
10897
10898 // If the condition controls loop exit (the loop exits only if the expression
10899 // is true) and the addition is no-wrap we can use unsigned divide to
10900 // compute the backedge count. In this case, the step may not divide the
10901 // distance, but we don't care because if the condition is "missed" the loop
10902 // will have undefined behavior due to wrapping.
10903 if (ControlsOnlyExit && AddRec->hasNoSelfWrap() &&
10904 loopHasNoAbnormalExits(AddRec->getLoop())) {
10905
10906 // If the stride is zero and the start is non-zero, the loop must be
10907 // infinite. In C++, most loops are finite by assumption, in which case the
10908 // step being zero implies UB must execute if the loop is entered.
10909 if (!(loopIsFiniteByAssumption(L) && isKnownNonZero(Start)) &&
10910 !isKnownNonZero(StepWLG))
10911 return getCouldNotCompute();
10912
10913 const SCEV *Exact =
10914 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10915 const SCEV *ConstantMax = getCouldNotCompute();
10916 if (Exact != getCouldNotCompute()) {
10917 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, Guards));
10918 ConstantMax =
10920 }
10921 const SCEV *SymbolicMax =
10922 isa<SCEVCouldNotCompute>(Exact) ? ConstantMax : Exact;
10923 return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
10924 }
10925
10926 // Solve the general equation.
10927 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
10928 if (!StepC || StepC->getValue()->isZero())
10929 return getCouldNotCompute();
10930 const SCEV *E = SolveLinEquationWithOverflow(
10931 StepC->getAPInt(), getNegativeSCEV(Start),
10932 AllowPredicates ? &Predicates : nullptr, *this, L);
10933
10934 const SCEV *M = E;
10935 if (E != getCouldNotCompute()) {
10936 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, Guards));
10937 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
10938 }
10939 auto *S = isa<SCEVCouldNotCompute>(E) ? M : E;
10940 return ExitLimit(E, M, S, false, Predicates);
10941}
10942
10943ScalarEvolution::ExitLimit
10944ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10945 // Loops that look like: while (X == 0) are very strange indeed. We don't
10946 // handle them yet except for the trivial case. This could be expanded in the
10947 // future as needed.
10948
10949 // If the value is a constant, check to see if it is known to be non-zero
10950 // already. If so, the backedge will execute zero times.
10951 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10952 if (!C->getValue()->isZero())
10953 return getZero(C->getType());
10954 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10955 }
10956
10957 // We could implement others, but I really doubt anyone writes loops like
10958 // this, and if they did, they would already be constant folded.
10959 return getCouldNotCompute();
10960}
10961
10962std::pair<const BasicBlock *, const BasicBlock *>
10963ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10964 const {
10965 // If the block has a unique predecessor, then there is no path from the
10966 // predecessor to the block that does not go through the direct edge
10967 // from the predecessor to the block.
10968 if (const BasicBlock *Pred = BB->getSinglePredecessor())
10969 return {Pred, BB};
10970
10971 // A loop's header is defined to be a block that dominates the loop.
10972 // If the header has a unique predecessor outside the loop, it must be
10973 // a block that has exactly one successor that can reach the loop.
10974 if (const Loop *L = LI.getLoopFor(BB))
10975 return {L->getLoopPredecessor(), L->getHeader()};
10976
10977 return {nullptr, BB};
10978}
10979
10980/// SCEV structural equivalence is usually sufficient for testing whether two
10981/// expressions are equal, however for the purposes of looking for a condition
10982/// guarding a loop, it can be useful to be a little more general, since a
10983/// front-end may have replicated the controlling expression.
10984static bool HasSameValue(const SCEV *A, const SCEV *B) {
10985 // Quick check to see if they are the same SCEV.
10986 if (A == B) return true;
10987
10988 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10989 // Not all instructions that are "identical" compute the same value. For
10990 // instance, two distinct alloca instructions allocating the same type are
10991 // identical and do not read memory; but compute distinct values.
10992 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
10993 };
10994
10995 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10996 // two different instructions with the same value. Check for this case.
10997 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
10998 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
10999 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
11000 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
11001 if (ComputesEqualValues(AI, BI))
11002 return true;
11003
11004 // Otherwise assume they may have a different value.
11005 return false;
11006}
11007
11008static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS) {
11009 const SCEV *Op0, *Op1;
11010 if (!match(S, m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))))
11011 return false;
11012 if (match(Op0, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
11013 LHS = Op1;
11014 return true;
11015 }
11016 if (match(Op1, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
11017 LHS = Op0;
11018 return true;
11019 }
11020 return false;
11021}
11022
11024 SCEVUse &RHS, unsigned Depth) {
11025 bool Changed = false;
11026 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
11027 // '0 != 0'.
11028 auto TrivialCase = [&](bool TriviallyTrue) {
11030 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
11031 return true;
11032 };
11033 // If we hit the max recursion limit bail out.
11034 if (Depth >= 3)
11035 return false;
11036
11037 const SCEV *NewLHS, *NewRHS;
11038 if (match(LHS, m_scev_c_Mul(m_SCEV(NewLHS), m_SCEVVScale())) &&
11039 match(RHS, m_scev_c_Mul(m_SCEV(NewRHS), m_SCEVVScale()))) {
11040 const SCEVMulExpr *LMul = cast<SCEVMulExpr>(LHS);
11041 const SCEVMulExpr *RMul = cast<SCEVMulExpr>(RHS);
11042
11043 // (X * vscale) pred (Y * vscale) ==> X pred Y
11044 // when both multiples are NSW.
11045 // (X * vscale) uicmp/eq/ne (Y * vscale) ==> X uicmp/eq/ne Y
11046 // when both multiples are NUW.
11047 if ((LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap()) ||
11048 (LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap() &&
11049 !ICmpInst::isSigned(Pred))) {
11050 LHS = NewLHS;
11051 RHS = NewRHS;
11052 Changed = true;
11053 }
11054 }
11055
11056 // Canonicalize a constant to the right side.
11057 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
11058 // Check for both operands constant.
11059 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
11060 if (!ICmpInst::compare(LHSC->getAPInt(), RHSC->getAPInt(), Pred))
11061 return TrivialCase(false);
11062 return TrivialCase(true);
11063 }
11064 // Otherwise swap the operands to put the constant on the right.
11065 std::swap(LHS, RHS);
11067 Changed = true;
11068 }
11069
11070 // (K + A) pred (K + B) --> A pred B
11071 // For equality, no flags are needed.
11072 // For signed, both adds must be NSW. For unsigned, both must be NUW.
11073 {
11074 const SCEVConstant *C = nullptr;
11075 if (match(LHS, m_scev_Add(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11076 match(RHS, m_scev_Add(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11077 const auto *LAdd = cast<SCEVAddExpr>(LHS);
11078 const auto *RAdd = cast<SCEVAddExpr>(RHS);
11079 if (ICmpInst::isEquality(Pred) ||
11080 (ICmpInst::isSigned(Pred) && LAdd->hasNoSignedWrap() &&
11081 RAdd->hasNoSignedWrap()) ||
11082 (ICmpInst::isUnsigned(Pred) && LAdd->hasNoUnsignedWrap() &&
11083 RAdd->hasNoUnsignedWrap())) {
11084 LHS = NewLHS;
11085 RHS = NewRHS;
11086 Changed = true;
11087 }
11088 }
11089 }
11090
11091 // (C * A) pred (C * B) --> A pred B
11092 // For equality predicates, both muls must be NUW or both must be NSW
11093 // (either suffices to make multiplication by C injective; C == 0 is
11094 // impossible because SCEV folds 0 * X to 0).
11095 // For signed ordering, C must be positive and both muls must be NSW.
11096 // For unsigned ordering, both muls must be NUW.
11097 {
11098 const SCEVConstant *C = nullptr;
11099 if (match(LHS, m_scev_Mul(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11100 match(RHS, m_scev_Mul(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11101 const auto *LMul = cast<SCEVMulExpr>(LHS);
11102 const auto *RMul = cast<SCEVMulExpr>(RHS);
11103 bool BothNUW = LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap();
11104 bool BothNSW = LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap();
11105 if ((ICmpInst::isEquality(Pred) && (BothNUW || BothNSW)) ||
11106 (ICmpInst::isSigned(Pred) && BothNSW &&
11107 C->getAPInt().isStrictlyPositive()) ||
11108 (ICmpInst::isUnsigned(Pred) && BothNUW)) {
11109 LHS = NewLHS;
11110 RHS = NewRHS;
11111 Changed = true;
11112 }
11113 }
11114 }
11115
11116 // If we're comparing an addrec with a value which is loop-invariant in the
11117 // addrec's loop, put the addrec on the left. Also make a dominance check,
11118 // as both operands could be addrecs loop-invariant in each other's loop.
11119 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
11120 const Loop *L = AR->getLoop();
11121 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
11122 std::swap(LHS, RHS);
11124 Changed = true;
11125 }
11126 }
11127
11128 // If there's a constant operand, canonicalize comparisons with boundary
11129 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
11130 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
11131 const APInt &RA = RC->getAPInt();
11132
11133 bool SimplifiedByConstantRange = false;
11134
11135 if (!ICmpInst::isEquality(Pred)) {
11137 if (ExactCR.isFullSet())
11138 return TrivialCase(true);
11139 if (ExactCR.isEmptySet())
11140 return TrivialCase(false);
11141
11142 APInt NewRHS;
11143 CmpInst::Predicate NewPred;
11144 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
11145 ICmpInst::isEquality(NewPred)) {
11146 // We were able to convert an inequality to an equality.
11147 Pred = NewPred;
11148 RHS = getConstant(NewRHS);
11149 Changed = SimplifiedByConstantRange = true;
11150 }
11151 }
11152
11153 if (!SimplifiedByConstantRange) {
11154 switch (Pred) {
11155 default:
11156 break;
11157 case ICmpInst::ICMP_EQ:
11158 case ICmpInst::ICMP_NE:
11159 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
11160 if (RA.isZero() && MatchBinarySub(LHS, LHS, RHS))
11161 Changed = true;
11162 break;
11163
11164 // The "Should have been caught earlier!" messages refer to the fact
11165 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
11166 // should have fired on the corresponding cases, and canonicalized the
11167 // check to trivial case.
11168
11169 case ICmpInst::ICMP_UGE:
11170 assert(!RA.isMinValue() && "Should have been caught earlier!");
11171 Pred = ICmpInst::ICMP_UGT;
11172 RHS = getConstant(RA - 1);
11173 Changed = true;
11174 break;
11175 case ICmpInst::ICMP_ULE:
11176 assert(!RA.isMaxValue() && "Should have been caught earlier!");
11177 Pred = ICmpInst::ICMP_ULT;
11178 RHS = getConstant(RA + 1);
11179 Changed = true;
11180 break;
11181 case ICmpInst::ICMP_SGE:
11182 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
11183 Pred = ICmpInst::ICMP_SGT;
11184 RHS = getConstant(RA - 1);
11185 Changed = true;
11186 break;
11187 case ICmpInst::ICMP_SLE:
11188 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
11189 Pred = ICmpInst::ICMP_SLT;
11190 RHS = getConstant(RA + 1);
11191 Changed = true;
11192 break;
11193 }
11194 }
11195 }
11196
11197 // Check for obvious equality.
11198 if (HasSameValue(LHS, RHS)) {
11199 if (ICmpInst::isTrueWhenEqual(Pred))
11200 return TrivialCase(true);
11202 return TrivialCase(false);
11203 }
11204
11205 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
11206 // adding or subtracting 1 from one of the operands.
11207 switch (Pred) {
11208 case ICmpInst::ICMP_SLE:
11209 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
11210 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11212 Pred = ICmpInst::ICMP_SLT;
11213 Changed = true;
11214 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
11215 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
11217 Pred = ICmpInst::ICMP_SLT;
11218 Changed = true;
11219 }
11220 break;
11221 case ICmpInst::ICMP_SGE:
11222 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
11223 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
11225 Pred = ICmpInst::ICMP_SGT;
11226 Changed = true;
11227 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
11228 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11230 Pred = ICmpInst::ICMP_SGT;
11231 Changed = true;
11232 }
11233 break;
11234 case ICmpInst::ICMP_ULE:
11235 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
11236 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11238 Pred = ICmpInst::ICMP_ULT;
11239 Changed = true;
11240 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
11241 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
11242 Pred = ICmpInst::ICMP_ULT;
11243 Changed = true;
11244 }
11245 break;
11246 case ICmpInst::ICMP_UGE:
11247 // If RHS is an op we can fold the -1, try that first.
11248 // Otherwise prefer LHS to preserve the nuw flag.
11249 if ((isa<SCEVConstant>(RHS) ||
11251 isa<SCEVConstant>(cast<SCEVNAryExpr>(RHS)->getOperand(0)))) &&
11252 !getUnsignedRangeMin(RHS).isMinValue()) {
11253 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11254 Pred = ICmpInst::ICMP_UGT;
11255 Changed = true;
11256 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
11257 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11259 Pred = ICmpInst::ICMP_UGT;
11260 Changed = true;
11261 } else if (!getUnsignedRangeMin(RHS).isMinValue()) {
11262 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11263 Pred = ICmpInst::ICMP_UGT;
11264 Changed = true;
11265 }
11266 break;
11267 default:
11268 break;
11269 }
11270
11271 // TODO: More simplifications are possible here.
11272
11273 // Recursively simplify until we either hit a recursion limit or nothing
11274 // changes.
11275 if (Changed)
11276 (void)SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1);
11277
11278 return Changed;
11279}
11280
11282 return getSignedRangeMax(S).isNegative();
11283}
11284
11288
11290 return !getSignedRangeMin(S).isNegative();
11291}
11292
11296
11298 // Query push down for cases where the unsigned range is
11299 // less than sufficient.
11300 if (const auto *SExt = dyn_cast<SCEVSignExtendExpr>(S))
11301 return isKnownNonZero(SExt->getOperand(0));
11302 return getUnsignedRangeMin(S) != 0;
11303}
11304
11306 bool OrNegative) {
11307 auto NonRecursive = [OrNegative](const SCEV *S) {
11308 if (auto *C = dyn_cast<SCEVConstant>(S))
11309 return C->getAPInt().isPowerOf2() ||
11310 (OrNegative && C->getAPInt().isNegatedPowerOf2());
11311
11312 // vscale is a power-of-two.
11313 return isa<SCEVVScale>(S);
11314 };
11315
11316 if (NonRecursive(S))
11317 return true;
11318
11319 auto *Mul = dyn_cast<SCEVMulExpr>(S);
11320 if (!Mul)
11321 return false;
11322 return all_of(Mul->operands(), NonRecursive) && (OrZero || isKnownNonZero(S));
11323}
11324
11326 const SCEV *S, uint64_t M,
11328 if (M == 0)
11329 return false;
11330 if (M == 1)
11331 return true;
11332
11333 // Recursively check AddRec operands. An AddRecExpr S is a multiple of M if S
11334 // starts with a multiple of M and at every iteration step S only adds
11335 // multiples of M.
11336 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
11337 return isKnownMultipleOf(AddRec->getStart(), M, Assumptions) &&
11338 isKnownMultipleOf(AddRec->getStepRecurrence(*this), M, Assumptions);
11339
11340 // For a constant, check that "S % M == 0".
11341 if (auto *Cst = dyn_cast<SCEVConstant>(S)) {
11342 APInt C = Cst->getAPInt();
11343 return C.urem(M) == 0;
11344 }
11345
11346 // TODO: Also check other SCEV expressions, i.e., SCEVAddRecExpr, etc.
11347
11348 // Basic tests have failed.
11349 // Check "S % M == 0" at compile time and record runtime Assumptions.
11350 auto *STy = dyn_cast<IntegerType>(S->getType());
11351 const SCEV *SmodM =
11352 getURemExpr(S, getConstant(ConstantInt::get(STy, M, false)));
11353 const SCEV *Zero = getZero(STy);
11354
11355 // Check whether "S % M == 0" is known at compile time.
11356 if (isKnownPredicate(ICmpInst::ICMP_EQ, SmodM, Zero))
11357 return true;
11358
11359 // Check whether "S % M != 0" is known at compile time.
11360 if (isKnownPredicate(ICmpInst::ICMP_NE, SmodM, Zero))
11361 return false;
11362
11364
11365 // Detect redundant predicates.
11366 for (auto *A : Assumptions)
11367 if (A->implies(P, *this))
11368 return true;
11369
11370 // Only record non-redundant predicates.
11371 Assumptions.push_back(P);
11372 return true;
11373}
11374
11376 return ((isKnownNonNegative(S1) && isKnownNonNegative(S2)) ||
11378}
11379
11380std::pair<const SCEV *, const SCEV *>
11382 // Compute SCEV on entry of loop L.
11383 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
11384 if (Start == getCouldNotCompute())
11385 return { Start, Start };
11386 // Compute post increment SCEV for loop L.
11387 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
11388 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
11389 return { Start, PostInc };
11390}
11391
11393 SCEVUse RHS) {
11394 // First collect all loops.
11396 getUsedLoops(LHS, LoopsUsed);
11397 getUsedLoops(RHS, LoopsUsed);
11398
11399 if (LoopsUsed.empty())
11400 return false;
11401
11402 // Domination relationship must be a linear order on collected loops.
11403#ifndef NDEBUG
11404 for (const auto *L1 : LoopsUsed)
11405 for (const auto *L2 : LoopsUsed)
11406 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
11407 DT.dominates(L2->getHeader(), L1->getHeader())) &&
11408 "Domination relationship is not a linear order");
11409#endif
11410
11411 const Loop *MDL =
11412 *llvm::max_element(LoopsUsed, [&](const Loop *L1, const Loop *L2) {
11413 return DT.properlyDominates(L1->getHeader(), L2->getHeader());
11414 });
11415
11416 // Get init and post increment value for LHS.
11417 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
11418 // if LHS contains unknown non-invariant SCEV then bail out.
11419 if (SplitLHS.first == getCouldNotCompute())
11420 return false;
11421 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
11422 // Get init and post increment value for RHS.
11423 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
11424 // if RHS contains unknown non-invariant SCEV then bail out.
11425 if (SplitRHS.first == getCouldNotCompute())
11426 return false;
11427 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
11428 // It is possible that init SCEV contains an invariant load but it does
11429 // not dominate MDL and is not available at MDL loop entry, so we should
11430 // check it here.
11431 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
11432 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
11433 return false;
11434
11435 // It seems backedge guard check is faster than entry one so in some cases
11436 // it can speed up whole estimation by short circuit
11437 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
11438 SplitRHS.second) &&
11439 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
11440}
11441
11443 SCEVUse RHS) {
11444 // Canonicalize the inputs first.
11445 (void)SimplifyICmpOperands(Pred, LHS, RHS);
11446
11447 if (isKnownViaInduction(Pred, LHS, RHS))
11448 return true;
11449
11450 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
11451 return true;
11452
11453 // Otherwise see what can be done with some simple reasoning.
11454 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
11455}
11456
11458 const SCEV *LHS,
11459 const SCEV *RHS) {
11460 if (isKnownPredicate(Pred, LHS, RHS))
11461 return true;
11463 return false;
11464 return std::nullopt;
11465}
11466
11468 const SCEV *RHS,
11469 const Instruction *CtxI) {
11470 // TODO: Analyze guards and assumes from Context's block.
11471 return isKnownPredicate(Pred, LHS, RHS) ||
11472 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
11473}
11474
11475std::optional<bool>
11477 const SCEV *RHS, const Instruction *CtxI) {
11478 std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
11479 if (KnownWithoutContext)
11480 return KnownWithoutContext;
11481
11482 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
11483 return true;
11485 CtxI->getParent(), ICmpInst::getInverseCmpPredicate(Pred), LHS, RHS))
11486 return false;
11487 return std::nullopt;
11488}
11489
11491 const SCEVAddRecExpr *LHS,
11492 const SCEV *RHS) {
11493 const Loop *L = LHS->getLoop();
11494 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
11495 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
11496}
11497
11498std::optional<ScalarEvolution::MonotonicPredicateType>
11500 ICmpInst::Predicate Pred) {
11501 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
11502
11503#ifndef NDEBUG
11504 // Verify an invariant: inverting the predicate should turn a monotonically
11505 // increasing change to a monotonically decreasing one, and vice versa.
11506 if (Result) {
11507 auto ResultSwapped =
11508 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
11509
11510 assert(*ResultSwapped != *Result &&
11511 "monotonicity should flip as we flip the predicate");
11512 }
11513#endif
11514
11515 return Result;
11516}
11517
11518std::optional<ScalarEvolution::MonotonicPredicateType>
11519ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
11520 ICmpInst::Predicate Pred) {
11521 // A zero step value for LHS means the induction variable is essentially a
11522 // loop invariant value. We don't really depend on the predicate actually
11523 // flipping from false to true (for increasing predicates, and the other way
11524 // around for decreasing predicates), all we care about is that *if* the
11525 // predicate changes then it only changes from false to true.
11526 //
11527 // A zero step value in itself is not very useful, but there may be places
11528 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
11529 // as general as possible.
11530
11531 // Only handle LE/LT/GE/GT predicates.
11532 if (!ICmpInst::isRelational(Pred))
11533 return std::nullopt;
11534
11535 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
11536 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
11537 "Should be greater or less!");
11538
11539 // Check that AR does not wrap.
11540 if (ICmpInst::isUnsigned(Pred)) {
11541 if (!LHS->hasNoUnsignedWrap())
11542 return std::nullopt;
11544 }
11545 assert(ICmpInst::isSigned(Pred) &&
11546 "Relational predicate is either signed or unsigned!");
11547 if (!LHS->hasNoSignedWrap())
11548 return std::nullopt;
11549
11550 const SCEV *Step = LHS->getStepRecurrence(*this);
11551
11552 if (isKnownNonNegative(Step))
11554
11555 if (isKnownNonPositive(Step))
11557
11558 return std::nullopt;
11559}
11560
11561std::optional<ScalarEvolution::LoopInvariantPredicate>
11563 const SCEV *RHS, const Loop *L,
11564 const Instruction *CtxI) {
11565 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11566 if (!isLoopInvariant(RHS, L)) {
11567 if (!isLoopInvariant(LHS, L))
11568 return std::nullopt;
11569
11570 std::swap(LHS, RHS);
11572 }
11573
11574 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11575 if (!ArLHS || ArLHS->getLoop() != L)
11576 return std::nullopt;
11577
11578 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
11579 if (!MonotonicType)
11580 return std::nullopt;
11581 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
11582 // true as the loop iterates, and the backedge is control dependent on
11583 // "ArLHS `Pred` RHS" == true then we can reason as follows:
11584 //
11585 // * if the predicate was false in the first iteration then the predicate
11586 // is never evaluated again, since the loop exits without taking the
11587 // backedge.
11588 // * if the predicate was true in the first iteration then it will
11589 // continue to be true for all future iterations since it is
11590 // monotonically increasing.
11591 //
11592 // For both the above possibilities, we can replace the loop varying
11593 // predicate with its value on the first iteration of the loop (which is
11594 // loop invariant).
11595 //
11596 // A similar reasoning applies for a monotonically decreasing predicate, by
11597 // replacing true with false and false with true in the above two bullets.
11599 auto P = Increasing ? Pred : ICmpInst::getInverseCmpPredicate(Pred);
11600
11601 if (isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
11603 RHS);
11604
11605 if (!CtxI)
11606 return std::nullopt;
11607 // Try to prove via context.
11608 // TODO: Support other cases.
11609 switch (Pred) {
11610 default:
11611 break;
11612 case ICmpInst::ICMP_ULE:
11613 case ICmpInst::ICMP_ULT: {
11614 assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!");
11615 // Given preconditions
11616 // (1) ArLHS does not cross the border of positive and negative parts of
11617 // range because of:
11618 // - Positive step; (TODO: lift this limitation)
11619 // - nuw - does not cross zero boundary;
11620 // - nsw - does not cross SINT_MAX boundary;
11621 // (2) ArLHS <s RHS
11622 // (3) RHS >=s 0
11623 // we can replace the loop variant ArLHS <u RHS condition with loop
11624 // invariant Start(ArLHS) <u RHS.
11625 //
11626 // Because of (1) there are two options:
11627 // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
11628 // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
11629 // It means that ArLHS <s RHS <=> ArLHS <u RHS.
11630 // Because of (2) ArLHS <u RHS is trivially true.
11631 // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
11632 // We can strengthen this to Start(ArLHS) <u RHS.
11633 auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
11634 if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
11635 isKnownPositive(ArLHS->getStepRecurrence(*this)) &&
11636 isKnownNonNegative(RHS) &&
11637 isKnownPredicateAt(SignFlippedPred, ArLHS, RHS, CtxI))
11639 RHS);
11640 }
11641 }
11642
11643 return std::nullopt;
11644}
11645
11646std::optional<ScalarEvolution::LoopInvariantPredicate>
11648 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11649 const Instruction *CtxI, const SCEV *MaxIter) {
11651 Pred, LHS, RHS, L, CtxI, MaxIter))
11652 return LIP;
11653 if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
11654 // Number of iterations expressed as UMIN isn't always great for expressing
11655 // the value on the last iteration. If the straightforward approach didn't
11656 // work, try the following trick: if the a predicate is invariant for X, it
11657 // is also invariant for umin(X, ...). So try to find something that works
11658 // among subexpressions of MaxIter expressed as umin.
11659 for (SCEVUse Op : UMin->operands())
11661 Pred, LHS, RHS, L, CtxI, Op))
11662 return LIP;
11663 return std::nullopt;
11664}
11665
11666std::optional<ScalarEvolution::LoopInvariantPredicate>
11668 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11669 const Instruction *CtxI, const SCEV *MaxIter) {
11670 // Try to prove the following set of facts:
11671 // - The predicate is monotonic in the iteration space.
11672 // - If the check does not fail on the 1st iteration:
11673 // - No overflow will happen during first MaxIter iterations;
11674 // - It will not fail on the MaxIter'th iteration.
11675 // If the check does fail on the 1st iteration, we leave the loop and no
11676 // other checks matter.
11677
11678 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11679 if (!isLoopInvariant(RHS, L)) {
11680 if (!isLoopInvariant(LHS, L))
11681 return std::nullopt;
11682
11683 std::swap(LHS, RHS);
11685 }
11686
11687 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
11688 if (!AR || AR->getLoop() != L)
11689 return std::nullopt;
11690
11691 // Even if both are valid, we need to consistently chose the unsigned or the
11692 // signed predicate below, not mixtures of both. For now, prefer the unsigned
11693 // predicate.
11694 Pred = Pred.dropSameSign();
11695
11696 // The predicate must be relational (i.e. <, <=, >=, >).
11697 if (!ICmpInst::isRelational(Pred))
11698 return std::nullopt;
11699
11700 // TODO: Support steps other than +/- 1.
11701 const SCEV *Step = AR->getStepRecurrence(*this);
11702 auto *One = getOne(Step->getType());
11703 auto *MinusOne = getNegativeSCEV(One);
11704 if (Step != One && Step != MinusOne)
11705 return std::nullopt;
11706
11707 // Type mismatch here means that MaxIter is potentially larger than max
11708 // unsigned value in start type, which mean we cannot prove no wrap for the
11709 // indvar.
11710 if (AR->getType() != MaxIter->getType())
11711 return std::nullopt;
11712
11713 // Value of IV on suggested last iteration.
11714 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
11715 // Does it still meet the requirement?
11716 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
11717 return std::nullopt;
11718 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
11719 // not exceed max unsigned value of this type), this effectively proves
11720 // that there is no wrap during the iteration. To prove that there is no
11721 // signed/unsigned wrap, we need to check that
11722 // Start <= Last for step = 1 or Start >= Last for step = -1.
11723 ICmpInst::Predicate NoOverflowPred =
11725 if (Step == MinusOne)
11726 NoOverflowPred = ICmpInst::getSwappedPredicate(NoOverflowPred);
11727 const SCEV *Start = AR->getStart();
11728 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
11729 return std::nullopt;
11730
11731 // Everything is fine.
11732 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
11733}
11734
11735bool ScalarEvolution::isKnownPredicateViaConstantRanges(CmpPredicate Pred,
11736 SCEVUse LHS,
11737 SCEVUse RHS) {
11738 if (HasSameValue(LHS, RHS))
11739 return ICmpInst::isTrueWhenEqual(Pred);
11740
11741 auto CheckRange = [&](bool IsSigned) {
11742 auto RangeLHS = IsSigned ? getSignedRange(LHS) : getUnsignedRange(LHS);
11743 auto RangeRHS = IsSigned ? getSignedRange(RHS) : getUnsignedRange(RHS);
11744 return RangeLHS.icmp(Pred, RangeRHS);
11745 };
11746
11747 // The check at the top of the function catches the case where the values are
11748 // known to be equal.
11749 if (Pred == CmpInst::ICMP_EQ)
11750 return false;
11751
11752 if (Pred == CmpInst::ICMP_NE) {
11753 if (CheckRange(true) || CheckRange(false))
11754 return true;
11755 auto *Diff = getMinusSCEV(LHS, RHS);
11756 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
11757 }
11758
11759 return CheckRange(CmpInst::isSigned(Pred));
11760}
11761
11762bool ScalarEvolution::isKnownPredicateViaNoOverflow(CmpPredicate Pred,
11764 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
11765 // C1 and C2 are constant integers. If either X or Y are not add expressions,
11766 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
11767 // OutC1 and OutC2.
11768 auto MatchBinaryAddToConst = [this](SCEVUse X, SCEVUse Y, APInt &OutC1,
11769 APInt &OutC2,
11770 SCEV::NoWrapFlags ExpectedFlags) {
11771 SCEVUse XNonConstOp, XConstOp;
11772 SCEVUse YNonConstOp, YConstOp;
11773 SCEV::NoWrapFlags XFlagsPresent;
11774 SCEV::NoWrapFlags YFlagsPresent;
11775
11776 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
11777 XConstOp = getZero(X->getType());
11778 XNonConstOp = X;
11779 XFlagsPresent = ExpectedFlags;
11780 }
11781 if (!isa<SCEVConstant>(XConstOp))
11782 return false;
11783
11784 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
11785 YConstOp = getZero(Y->getType());
11786 YNonConstOp = Y;
11787 YFlagsPresent = ExpectedFlags;
11788 }
11789
11790 if (YNonConstOp != XNonConstOp)
11791 return false;
11792
11793 if (!isa<SCEVConstant>(YConstOp))
11794 return false;
11795
11796 // When matching ADDs with NUW flags (and unsigned predicates), only the
11797 // second ADD (with the larger constant) requires NUW.
11798 if ((YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11799 return false;
11800 if (ExpectedFlags != SCEV::FlagNUW &&
11801 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) {
11802 return false;
11803 }
11804
11805 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
11806 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
11807
11808 return true;
11809 };
11810
11811 APInt C1;
11812 APInt C2;
11813
11814 switch (Pred) {
11815 default:
11816 break;
11817
11818 case ICmpInst::ICMP_SGE:
11819 std::swap(LHS, RHS);
11820 [[fallthrough]];
11821 case ICmpInst::ICMP_SLE:
11822 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
11823 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
11824 return true;
11825
11826 break;
11827
11828 case ICmpInst::ICMP_SGT:
11829 std::swap(LHS, RHS);
11830 [[fallthrough]];
11831 case ICmpInst::ICMP_SLT:
11832 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
11833 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
11834 return true;
11835
11836 break;
11837
11838 case ICmpInst::ICMP_UGE:
11839 std::swap(LHS, RHS);
11840 [[fallthrough]];
11841 case ICmpInst::ICMP_ULE:
11842 // (X + C1) u<= (X + C2)<nuw> for C1 u<= C2.
11843 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ule(C2))
11844 return true;
11845
11846 break;
11847
11848 case ICmpInst::ICMP_UGT:
11849 std::swap(LHS, RHS);
11850 [[fallthrough]];
11851 case ICmpInst::ICMP_ULT:
11852 // (X + C1) u< (X + C2)<nuw> if C1 u< C2.
11853 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ult(C2))
11854 return true;
11855 break;
11856 }
11857
11858 return false;
11859}
11860
11861bool ScalarEvolution::isKnownPredicateViaSplitting(CmpPredicate Pred,
11863 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
11864 return false;
11865
11866 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
11867 // the stack can result in exponential time complexity.
11868 SaveAndRestore Restore(ProvingSplitPredicate, true);
11869
11870 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
11871 //
11872 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
11873 // isKnownPredicate. isKnownPredicate is more powerful, but also more
11874 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
11875 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
11876 // use isKnownPredicate later if needed.
11877 return isKnownNonNegative(RHS) &&
11880}
11881
11882bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, CmpPredicate Pred,
11883 const SCEV *LHS, const SCEV *RHS) {
11884 // No need to even try if we know the module has no guards.
11885 if (!HasGuards)
11886 return false;
11887
11888 return any_of(*BB, [&](const Instruction &I) {
11889 using namespace llvm::PatternMatch;
11890
11891 Value *Condition;
11893 m_Value(Condition))) &&
11894 isImpliedCond(Pred, LHS, RHS, Condition, false);
11895 });
11896}
11897
11898/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
11899/// protected by a conditional between LHS and RHS. This is used to
11900/// to eliminate casts.
11902 CmpPredicate Pred,
11903 const SCEV *LHS,
11904 const SCEV *RHS) {
11905 // Interpret a null as meaning no loop, where there is obviously no guard
11906 // (interprocedural conditions notwithstanding). Do not bother about
11907 // unreachable loops.
11908 if (!L || !DT.isReachableFromEntry(L->getHeader()))
11909 return true;
11910
11911 if (VerifyIR)
11912 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
11913 "This cannot be done on broken IR!");
11914
11915
11916 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11917 return true;
11918
11919 BasicBlock *Latch = L->getLoopLatch();
11920 if (!Latch)
11921 return false;
11922
11923 CondBrInst *LoopContinuePredicate =
11925 if (LoopContinuePredicate &&
11926 isImpliedCond(Pred, LHS, RHS, LoopContinuePredicate->getCondition(),
11927 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
11928 return true;
11929
11930 // We don't want more than one activation of the following loops on the stack
11931 // -- that can lead to O(n!) time complexity.
11932 if (WalkingBEDominatingConds)
11933 return false;
11934
11935 SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
11936
11937 // See if we can exploit a trip count to prove the predicate.
11938 const auto &BETakenInfo = getBackedgeTakenInfo(L);
11939 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
11940 if (LatchBECount != getCouldNotCompute()) {
11941 // We know that Latch branches back to the loop header exactly
11942 // LatchBECount times. This means the backdege condition at Latch is
11943 // equivalent to "{0,+,1} u< LatchBECount".
11944 Type *Ty = LatchBECount->getType();
11945 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
11946 const SCEV *LoopCounter =
11947 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
11948 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
11949 LatchBECount))
11950 return true;
11951 }
11952
11953 // Check conditions due to any @llvm.assume intrinsics.
11954 for (auto &AssumeVH : AC.assumptions()) {
11955 if (!AssumeVH)
11956 continue;
11957 auto *CI = cast<CallInst>(AssumeVH);
11958 if (!DT.dominates(CI, Latch->getTerminator()))
11959 continue;
11960
11961 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
11962 return true;
11963 }
11964
11965 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
11966 return true;
11967
11968 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
11969 DTN != HeaderDTN; DTN = DTN->getIDom()) {
11970 assert(DTN && "should reach the loop header before reaching the root!");
11971
11972 BasicBlock *BB = DTN->getBlock();
11973 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
11974 return true;
11975
11976 BasicBlock *PBB = BB->getSinglePredecessor();
11977 if (!PBB)
11978 continue;
11979
11981 if (!ContBr || ContBr->getSuccessor(0) == ContBr->getSuccessor(1))
11982 continue;
11983
11984 // If we have an edge `E` within the loop body that dominates the only
11985 // latch, the condition guarding `E` also guards the backedge. This
11986 // reasoning works only for loops with a single latch.
11987 // We're constructively (and conservatively) enumerating edges within the
11988 // loop body that dominate the latch. The dominator tree better agree
11989 // with us on this:
11990 assert(DT.dominates(BasicBlockEdge(PBB, BB), Latch) && "should be!");
11991 if (isImpliedCond(Pred, LHS, RHS, ContBr->getCondition(),
11992 BB != ContBr->getSuccessor(0)))
11993 return true;
11994 }
11995
11996 return false;
11997}
11998
12000 CmpPredicate Pred,
12001 const SCEV *LHS,
12002 const SCEV *RHS) {
12003 // Do not bother proving facts for unreachable code.
12004 if (!DT.isReachableFromEntry(BB))
12005 return true;
12006 if (VerifyIR)
12007 assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
12008 "This cannot be done on broken IR!");
12009
12010 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
12011 // the facts (a >= b && a != b) separately. A typical situation is when the
12012 // non-strict comparison is known from ranges and non-equality is known from
12013 // dominating predicates. If we are proving strict comparison, we always try
12014 // to prove non-equality and non-strict comparison separately.
12015 CmpPredicate NonStrictPredicate = ICmpInst::getNonStrictCmpPredicate(Pred);
12016 const bool ProvingStrictComparison =
12017 Pred != NonStrictPredicate.dropSameSign();
12018 bool ProvedNonStrictComparison = false;
12019 bool ProvedNonEquality = false;
12020
12021 auto SplitAndProve = [&](std::function<bool(CmpPredicate)> Fn) -> bool {
12022 if (!ProvedNonStrictComparison)
12023 ProvedNonStrictComparison = Fn(NonStrictPredicate);
12024 if (!ProvedNonEquality)
12025 ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
12026 if (ProvedNonStrictComparison && ProvedNonEquality)
12027 return true;
12028 return false;
12029 };
12030
12031 if (ProvingStrictComparison) {
12032 auto ProofFn = [&](CmpPredicate P) {
12033 return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
12034 };
12035 if (SplitAndProve(ProofFn))
12036 return true;
12037 }
12038
12039 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
12040 auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
12041 const Instruction *CtxI = &BB->front();
12042 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
12043 return true;
12044 if (ProvingStrictComparison) {
12045 auto ProofFn = [&](CmpPredicate P) {
12046 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
12047 };
12048 if (SplitAndProve(ProofFn))
12049 return true;
12050 }
12051 return false;
12052 };
12053
12054 // Starting at the block's predecessor, climb up the predecessor chain, as long
12055 // as there are predecessors that can be found that have unique successors
12056 // leading to the original block.
12057 const Loop *ContainingLoop = LI.getLoopFor(BB);
12058 const BasicBlock *PredBB;
12059 if (ContainingLoop && ContainingLoop->getHeader() == BB)
12060 PredBB = ContainingLoop->getLoopPredecessor();
12061 else
12062 PredBB = BB->getSinglePredecessor();
12063 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
12064 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
12065 const CondBrInst *BlockEntryPredicate =
12066 dyn_cast<CondBrInst>(Pair.first->getTerminator());
12067 if (!BlockEntryPredicate)
12068 continue;
12069
12070 if (ProveViaCond(BlockEntryPredicate->getCondition(),
12071 BlockEntryPredicate->getSuccessor(0) != Pair.second))
12072 return true;
12073 }
12074
12075 // Check conditions due to any @llvm.assume intrinsics.
12076 for (auto &AssumeVH : AC.assumptions()) {
12077 if (!AssumeVH)
12078 continue;
12079 auto *CI = cast<CallInst>(AssumeVH);
12080 if (!DT.dominates(CI, BB))
12081 continue;
12082
12083 if (ProveViaCond(CI->getArgOperand(0), false))
12084 return true;
12085 }
12086
12087 // Check conditions due to any @llvm.experimental.guard intrinsics.
12088 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
12089 F.getParent(), Intrinsic::experimental_guard);
12090 if (GuardDecl)
12091 for (const auto *GU : GuardDecl->users())
12092 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
12093 if (Guard->getFunction() == BB->getParent() && DT.dominates(Guard, BB))
12094 if (ProveViaCond(Guard->getArgOperand(0), false))
12095 return true;
12096 return false;
12097}
12098
12100 const SCEV *LHS,
12101 const SCEV *RHS) {
12102 // Interpret a null as meaning no loop, where there is obviously no guard
12103 // (interprocedural conditions notwithstanding).
12104 if (!L)
12105 return false;
12106
12107 // Both LHS and RHS must be available at loop entry.
12109 "LHS is not available at Loop Entry");
12111 "RHS is not available at Loop Entry");
12112
12113 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
12114 return true;
12115
12116 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
12117}
12118
12119bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12120 const SCEV *RHS,
12121 const Value *FoundCondValue, bool Inverse,
12122 const Instruction *CtxI) {
12123 // False conditions implies anything. Do not bother analyzing it further.
12124 if (FoundCondValue ==
12125 ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
12126 return true;
12127
12128 if (!PendingLoopPredicates.insert(FoundCondValue).second)
12129 return false;
12130
12131 llvm::scope_exit ClearOnExit(
12132 [&]() { PendingLoopPredicates.erase(FoundCondValue); });
12133
12134 // Recursively handle And and Or conditions.
12135 const Value *Op0, *Op1;
12136 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
12137 if (!Inverse)
12138 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12139 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12140 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
12141 if (Inverse)
12142 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12143 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12144 }
12145
12146 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
12147 if (!ICI) return false;
12148
12149 // Now that we found a conditional branch that dominates the loop or controls
12150 // the loop latch. Check to see if it is the comparison we are looking for.
12151 CmpPredicate FoundPred;
12152 if (Inverse)
12153 FoundPred = ICI->getInverseCmpPredicate();
12154 else
12155 FoundPred = ICI->getCmpPredicate();
12156
12157 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
12158 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
12159
12160 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
12161}
12162
12163bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12164 const SCEV *RHS, CmpPredicate FoundPred,
12165 const SCEV *FoundLHS, const SCEV *FoundRHS,
12166 const Instruction *CtxI) {
12167 // Balance the types.
12168 if (getTypeSizeInBits(LHS->getType()) <
12169 getTypeSizeInBits(FoundLHS->getType())) {
12170 // For unsigned and equality predicates, try to prove that both found
12171 // operands fit into narrow unsigned range. If so, try to prove facts in
12172 // narrow types.
12173 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
12174 !FoundRHS->getType()->isPointerTy()) {
12175 auto *NarrowType = LHS->getType();
12176 auto *WideType = FoundLHS->getType();
12177 auto BitWidth = getTypeSizeInBits(NarrowType);
12178 const SCEV *MaxValue = getZeroExtendExpr(
12180 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
12181 MaxValue) &&
12182 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
12183 MaxValue)) {
12184 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
12185 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
12186 // We cannot preserve samesign after truncation.
12187 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred.dropSameSign(),
12188 TruncFoundLHS, TruncFoundRHS, CtxI))
12189 return true;
12190 }
12191 }
12192
12193 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
12194 return false;
12195 if (CmpInst::isSigned(Pred)) {
12196 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
12197 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
12198 } else {
12199 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
12200 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
12201 }
12202 } else if (getTypeSizeInBits(LHS->getType()) >
12203 getTypeSizeInBits(FoundLHS->getType())) {
12204 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
12205 return false;
12206 if (CmpInst::isSigned(FoundPred)) {
12207 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
12208 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
12209 } else {
12210 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
12211 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
12212 }
12213 }
12214 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
12215 FoundRHS, CtxI);
12216}
12217
12218bool ScalarEvolution::isImpliedCondBalancedTypes(
12219 CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, CmpPredicate FoundPred,
12220 SCEVUse FoundLHS, SCEVUse FoundRHS, const Instruction *CtxI) {
12222 getTypeSizeInBits(FoundLHS->getType()) &&
12223 "Types should be balanced!");
12224 // Canonicalize the query to match the way instcombine will have
12225 // canonicalized the comparison.
12226 if (SimplifyICmpOperands(Pred, LHS, RHS))
12227 if (LHS == RHS)
12228 return CmpInst::isTrueWhenEqual(Pred);
12229 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
12230 if (FoundLHS == FoundRHS)
12231 return CmpInst::isFalseWhenEqual(FoundPred);
12232
12233 // Check to see if we can make the LHS or RHS match.
12234 if (LHS == FoundRHS || RHS == FoundLHS) {
12235 if (isa<SCEVConstant>(RHS)) {
12236 std::swap(FoundLHS, FoundRHS);
12237 FoundPred = ICmpInst::getSwappedCmpPredicate(FoundPred);
12238 } else {
12239 std::swap(LHS, RHS);
12241 }
12242 }
12243
12244 // Check whether the found predicate is the same as the desired predicate.
12245 if (auto P = CmpPredicate::getMatching(FoundPred, Pred))
12246 return isImpliedCondOperands(*P, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12247
12248 // Check whether swapping the found predicate makes it the same as the
12249 // desired predicate.
12250 if (auto P = CmpPredicate::getMatching(
12251 ICmpInst::getSwappedCmpPredicate(FoundPred), Pred)) {
12252 // We can write the implication
12253 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS
12254 // using one of the following ways:
12255 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS
12256 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS
12257 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS
12258 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS
12259 // Forms 1. and 2. require swapping the operands of one condition. Don't
12260 // do this if it would break canonical constant/addrec ordering.
12262 return isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P), RHS,
12263 LHS, FoundLHS, FoundRHS, CtxI);
12264 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
12265 return isImpliedCondOperands(*P, LHS, RHS, FoundRHS, FoundLHS, CtxI);
12266
12267 // There's no clear preference between forms 3. and 4., try both. Avoid
12268 // forming getNotSCEV of pointer values as the resulting subtract is
12269 // not legal.
12270 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() &&
12271 isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P),
12272 getNotSCEV(LHS), getNotSCEV(RHS), FoundLHS,
12273 FoundRHS, CtxI))
12274 return true;
12275
12276 if (!FoundLHS->getType()->isPointerTy() &&
12277 !FoundRHS->getType()->isPointerTy() &&
12278 isImpliedCondOperands(*P, LHS, RHS, getNotSCEV(FoundLHS),
12279 getNotSCEV(FoundRHS), CtxI))
12280 return true;
12281
12282 return false;
12283 }
12284
12285 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
12287 assert(P1 != P2 && "Handled earlier!");
12288 return CmpInst::isRelational(P2) &&
12290 };
12291 if (IsSignFlippedPredicate(Pred, FoundPred)) {
12292 // Unsigned comparison is the same as signed comparison when both the
12293 // operands are non-negative or negative.
12294 if (haveSameSign(FoundLHS, FoundRHS))
12295 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12296 // Create local copies that we can freely swap and canonicalize our
12297 // conditions to "le/lt".
12298 CmpPredicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
12299 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
12300 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
12301 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
12302 CanonicalPred = ICmpInst::getSwappedCmpPredicate(CanonicalPred);
12303 CanonicalFoundPred = ICmpInst::getSwappedCmpPredicate(CanonicalFoundPred);
12304 std::swap(CanonicalLHS, CanonicalRHS);
12305 std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
12306 }
12307 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
12308 "Must be!");
12309 assert((ICmpInst::isLT(CanonicalFoundPred) ||
12310 ICmpInst::isLE(CanonicalFoundPred)) &&
12311 "Must be!");
12312 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
12313 // Use implication:
12314 // x <u y && y >=s 0 --> x <s y.
12315 // If we can prove the left part, the right part is also proven.
12316 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
12317 CanonicalRHS, CanonicalFoundLHS,
12318 CanonicalFoundRHS);
12319 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
12320 // Use implication:
12321 // x <s y && y <s 0 --> x <u y.
12322 // If we can prove the left part, the right part is also proven.
12323 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
12324 CanonicalRHS, CanonicalFoundLHS,
12325 CanonicalFoundRHS);
12326 }
12327
12328 // Check if we can make progress by sharpening ranges.
12329 if (FoundPred == ICmpInst::ICMP_NE &&
12330 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
12331
12332 const SCEVConstant *C = nullptr;
12333 const SCEV *V = nullptr;
12334
12335 if (isa<SCEVConstant>(FoundLHS)) {
12336 C = cast<SCEVConstant>(FoundLHS);
12337 V = FoundRHS;
12338 } else {
12339 C = cast<SCEVConstant>(FoundRHS);
12340 V = FoundLHS;
12341 }
12342
12343 // The guarding predicate tells us that C != V. If the known range
12344 // of V is [C, t), we can sharpen the range to [C + 1, t). The
12345 // range we consider has to correspond to same signedness as the
12346 // predicate we're interested in folding.
12347
12348 APInt Min = ICmpInst::isSigned(Pred) ?
12350
12351 if (Min == C->getAPInt()) {
12352 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
12353 // This is true even if (Min + 1) wraps around -- in case of
12354 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
12355
12356 APInt SharperMin = Min + 1;
12357
12358 switch (Pred) {
12359 case ICmpInst::ICMP_SGE:
12360 case ICmpInst::ICMP_UGE:
12361 // We know V `Pred` SharperMin. If this implies LHS `Pred`
12362 // RHS, we're done.
12363 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
12364 CtxI))
12365 return true;
12366 [[fallthrough]];
12367
12368 case ICmpInst::ICMP_SGT:
12369 case ICmpInst::ICMP_UGT:
12370 // We know from the range information that (V `Pred` Min ||
12371 // V == Min). We know from the guarding condition that !(V
12372 // == Min). This gives us
12373 //
12374 // V `Pred` Min || V == Min && !(V == Min)
12375 // => V `Pred` Min
12376 //
12377 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
12378
12379 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
12380 return true;
12381 break;
12382
12383 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
12384 case ICmpInst::ICMP_SLE:
12385 case ICmpInst::ICMP_ULE:
12386 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12387 LHS, V, getConstant(SharperMin), CtxI))
12388 return true;
12389 [[fallthrough]];
12390
12391 case ICmpInst::ICMP_SLT:
12392 case ICmpInst::ICMP_ULT:
12393 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12394 LHS, V, getConstant(Min), CtxI))
12395 return true;
12396 break;
12397
12398 default:
12399 // No change
12400 break;
12401 }
12402 }
12403 }
12404
12405 // Check whether the actual condition is beyond sufficient.
12406 if (FoundPred == ICmpInst::ICMP_EQ)
12407 if (ICmpInst::isTrueWhenEqual(Pred))
12408 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12409 return true;
12410 if (Pred == ICmpInst::ICMP_NE)
12411 if (!ICmpInst::isTrueWhenEqual(FoundPred))
12412 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12413 return true;
12414
12415 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS))
12416 return true;
12417
12418 // Otherwise assume the worst.
12419 return false;
12420}
12421
12422bool ScalarEvolution::splitBinaryAdd(SCEVUse Expr, SCEVUse &L, SCEVUse &R,
12423 SCEV::NoWrapFlags &Flags) {
12424 if (!match(Expr, m_scev_Add(m_SCEV(L), m_SCEV(R))))
12425 return false;
12426
12427 Flags = cast<SCEVAddExpr>(Expr)->getNoWrapFlags();
12428 return true;
12429}
12430
12431std::optional<APInt>
12433 // We avoid subtracting expressions here because this function is usually
12434 // fairly deep in the call stack (i.e. is called many times).
12435
12436 unsigned BW = getTypeSizeInBits(More->getType());
12437 APInt Diff(BW, 0);
12438 APInt DiffMul(BW, 1);
12439 // Try various simplifications to reduce the difference to a constant. Limit
12440 // the number of allowed simplifications to keep compile-time low.
12441 for (unsigned I = 0; I < 8; ++I) {
12442 if (More == Less)
12443 return Diff;
12444
12445 // Reduce addrecs with identical steps to their start value.
12447 const auto *LAR = cast<SCEVAddRecExpr>(Less);
12448 const auto *MAR = cast<SCEVAddRecExpr>(More);
12449
12450 if (LAR->getLoop() != MAR->getLoop())
12451 return std::nullopt;
12452
12453 // We look at affine expressions only; not for correctness but to keep
12454 // getStepRecurrence cheap.
12455 if (!LAR->isAffine() || !MAR->isAffine())
12456 return std::nullopt;
12457
12458 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
12459 return std::nullopt;
12460
12461 Less = LAR->getStart();
12462 More = MAR->getStart();
12463 continue;
12464 }
12465
12466 // Try to match a common constant multiply.
12467 auto MatchConstMul =
12468 [](const SCEV *S) -> std::optional<std::pair<const SCEV *, APInt>> {
12469 const APInt *C;
12470 const SCEV *Op;
12471 if (match(S, m_scev_Mul(m_scev_APInt(C), m_SCEV(Op))))
12472 return {{Op, *C}};
12473 return std::nullopt;
12474 };
12475 if (auto MatchedMore = MatchConstMul(More)) {
12476 if (auto MatchedLess = MatchConstMul(Less)) {
12477 if (MatchedMore->second == MatchedLess->second) {
12478 More = MatchedMore->first;
12479 Less = MatchedLess->first;
12480 DiffMul *= MatchedMore->second;
12481 continue;
12482 }
12483 }
12484 }
12485
12486 // Try to cancel out common factors in two add expressions.
12488 auto Add = [&](const SCEV *S, int Mul) {
12489 if (auto *C = dyn_cast<SCEVConstant>(S)) {
12490 if (Mul == 1) {
12491 Diff += C->getAPInt() * DiffMul;
12492 } else {
12493 assert(Mul == -1);
12494 Diff -= C->getAPInt() * DiffMul;
12495 }
12496 } else
12497 Multiplicity[S] += Mul;
12498 };
12499 auto Decompose = [&](const SCEV *S, int Mul) {
12500 if (isa<SCEVAddExpr>(S)) {
12501 for (const SCEV *Op : S->operands())
12502 Add(Op, Mul);
12503 } else
12504 Add(S, Mul);
12505 };
12506 Decompose(More, 1);
12507 Decompose(Less, -1);
12508
12509 // Check whether all the non-constants cancel out, or reduce to new
12510 // More/Less values.
12511 const SCEV *NewMore = nullptr, *NewLess = nullptr;
12512 for (const auto &[S, Mul] : Multiplicity) {
12513 if (Mul == 0)
12514 continue;
12515 if (Mul == 1) {
12516 if (NewMore)
12517 return std::nullopt;
12518 NewMore = S;
12519 } else if (Mul == -1) {
12520 if (NewLess)
12521 return std::nullopt;
12522 NewLess = S;
12523 } else
12524 return std::nullopt;
12525 }
12526
12527 // Values stayed the same, no point in trying further.
12528 if (NewMore == More || NewLess == Less)
12529 return std::nullopt;
12530
12531 More = NewMore;
12532 Less = NewLess;
12533
12534 // Reduced to constant.
12535 if (!More && !Less)
12536 return Diff;
12537
12538 // Left with variable on only one side, bail out.
12539 if (!More || !Less)
12540 return std::nullopt;
12541 }
12542
12543 // Did not reduce to constant.
12544 return std::nullopt;
12545}
12546
12547bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
12548 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12549 const SCEV *FoundRHS, const Instruction *CtxI) {
12550 // Try to recognize the following pattern:
12551 //
12552 // FoundRHS = ...
12553 // ...
12554 // loop:
12555 // FoundLHS = {Start,+,W}
12556 // context_bb: // Basic block from the same loop
12557 // known(Pred, FoundLHS, FoundRHS)
12558 //
12559 // If some predicate is known in the context of a loop, it is also known on
12560 // each iteration of this loop, including the first iteration. Therefore, in
12561 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
12562 // prove the original pred using this fact.
12563 if (!CtxI)
12564 return false;
12565 const BasicBlock *ContextBB = CtxI->getParent();
12566 // Make sure AR varies in the context block.
12567 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
12568 const Loop *L = AR->getLoop();
12569 const auto *Latch = L->getLoopLatch();
12570 // Make sure that context belongs to the loop and executes on 1st iteration
12571 // (if it ever executes at all).
12572 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12573 return false;
12574 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
12575 return false;
12576 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
12577 }
12578
12579 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
12580 const Loop *L = AR->getLoop();
12581 const auto *Latch = L->getLoopLatch();
12582 // Make sure that context belongs to the loop and executes on 1st iteration
12583 // (if it ever executes at all).
12584 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12585 return false;
12586 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
12587 return false;
12588 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
12589 }
12590
12591 return false;
12592}
12593
12594bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(CmpPredicate Pred,
12595 const SCEV *LHS,
12596 const SCEV *RHS,
12597 const SCEV *FoundLHS,
12598 const SCEV *FoundRHS) {
12599 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
12600 return false;
12601
12602 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
12603 if (!AddRecLHS)
12604 return false;
12605
12606 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12607 if (!AddRecFoundLHS)
12608 return false;
12609
12610 // We'd like to let SCEV reason about control dependencies, so we constrain
12611 // both the inequalities to be about add recurrences on the same loop. This
12612 // way we can use isLoopEntryGuardedByCond later.
12613
12614 const Loop *L = AddRecFoundLHS->getLoop();
12615 if (L != AddRecLHS->getLoop())
12616 return false;
12617
12618 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
12619 //
12620 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
12621 // ... (2)
12622 //
12623 // Informal proof for (2), assuming (1) [*]:
12624 //
12625 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
12626 //
12627 // Then
12628 //
12629 // FoundLHS s< FoundRHS s< INT_MIN - C
12630 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
12631 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
12632 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
12633 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
12634 // <=> FoundLHS + C s< FoundRHS + C
12635 //
12636 // [*]: (1) can be proved by ruling out overflow.
12637 //
12638 // [**]: This can be proved by analyzing all the four possibilities:
12639 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
12640 // (A s>= 0, B s>= 0).
12641 //
12642 // Note:
12643 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
12644 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
12645 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
12646 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
12647 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
12648 // C)".
12649
12650 std::optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
12651 if (!LDiff)
12652 return false;
12653 std::optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
12654 if (!RDiff || *LDiff != *RDiff)
12655 return false;
12656
12657 if (LDiff->isMinValue())
12658 return true;
12659
12660 APInt FoundRHSLimit;
12661
12662 if (Pred == CmpInst::ICMP_ULT) {
12663 FoundRHSLimit = -(*RDiff);
12664 } else {
12665 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
12666 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
12667 }
12668
12669 // Try to prove (1) or (2), as needed.
12670 return isAvailableAtLoopEntry(FoundRHS, L) &&
12671 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
12672 getConstant(FoundRHSLimit));
12673}
12674
12675bool ScalarEvolution::isImpliedViaMerge(CmpPredicate Pred, const SCEV *LHS,
12676 const SCEV *RHS, const SCEV *FoundLHS,
12677 const SCEV *FoundRHS, unsigned Depth) {
12678 const PHINode *LPhi = nullptr, *RPhi = nullptr;
12679
12680 llvm::scope_exit ClearOnExit([&]() {
12681 if (LPhi) {
12682 bool Erased = PendingMerges.erase(LPhi);
12683 assert(Erased && "Failed to erase LPhi!");
12684 (void)Erased;
12685 }
12686 if (RPhi) {
12687 bool Erased = PendingMerges.erase(RPhi);
12688 assert(Erased && "Failed to erase RPhi!");
12689 (void)Erased;
12690 }
12691 });
12692
12693 // Find respective Phis and check that they are not being pending.
12694 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
12695 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
12696 if (!PendingMerges.insert(Phi).second)
12697 return false;
12698 LPhi = Phi;
12699 }
12700 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
12701 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
12702 // If we detect a loop of Phi nodes being processed by this method, for
12703 // example:
12704 //
12705 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
12706 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
12707 //
12708 // we don't want to deal with a case that complex, so return conservative
12709 // answer false.
12710 if (!PendingMerges.insert(Phi).second)
12711 return false;
12712 RPhi = Phi;
12713 }
12714
12715 // If none of LHS, RHS is a Phi, nothing to do here.
12716 if (!LPhi && !RPhi)
12717 return false;
12718
12719 // If there is a SCEVUnknown Phi we are interested in, make it left.
12720 if (!LPhi) {
12721 std::swap(LHS, RHS);
12722 std::swap(FoundLHS, FoundRHS);
12723 std::swap(LPhi, RPhi);
12725 }
12726
12727 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
12728 const BasicBlock *LBB = LPhi->getParent();
12729 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12730
12731 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
12732 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
12733 isImpliedCondOperandsViaRanges(Pred, S1, S2, Pred, FoundLHS, FoundRHS) ||
12734 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
12735 };
12736
12737 if (RPhi && RPhi->getParent() == LBB) {
12738 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
12739 // If we compare two Phis from the same block, and for each entry block
12740 // the predicate is true for incoming values from this block, then the
12741 // predicate is also true for the Phis.
12742 for (const BasicBlock *IncBB : predecessors(LBB)) {
12743 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12744 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
12745 if (!ProvedEasily(L, R))
12746 return false;
12747 }
12748 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
12749 // Case two: RHS is also a Phi from the same basic block, and it is an
12750 // AddRec. It means that there is a loop which has both AddRec and Unknown
12751 // PHIs, for it we can compare incoming values of AddRec from above the loop
12752 // and latch with their respective incoming values of LPhi.
12753 // TODO: Generalize to handle loops with many inputs in a header.
12754 if (LPhi->getNumIncomingValues() != 2) return false;
12755
12756 auto *RLoop = RAR->getLoop();
12757 auto *Predecessor = RLoop->getLoopPredecessor();
12758 assert(Predecessor && "Loop with AddRec with no predecessor?");
12759 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
12760 if (!ProvedEasily(L1, RAR->getStart()))
12761 return false;
12762 auto *Latch = RLoop->getLoopLatch();
12763 assert(Latch && "Loop with AddRec with no latch?");
12764 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
12765 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
12766 return false;
12767 } else {
12768 // In all other cases go over inputs of LHS and compare each of them to RHS,
12769 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
12770 // At this point RHS is either a non-Phi, or it is a Phi from some block
12771 // different from LBB.
12772 for (const BasicBlock *IncBB : predecessors(LBB)) {
12773 // Check that RHS is available in this block.
12774 if (!dominates(RHS, IncBB))
12775 return false;
12776 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12777 // Make sure L does not refer to a value from a potentially previous
12778 // iteration of a loop.
12779 if (!properlyDominates(L, LBB))
12780 return false;
12781 // Addrecs are considered to properly dominate their loop, so are missed
12782 // by the previous check. Discard any values that have computable
12783 // evolution in this loop.
12784 if (auto *Loop = LI.getLoopFor(LBB))
12785 if (hasComputableLoopEvolution(L, Loop))
12786 return false;
12787 if (!ProvedEasily(L, RHS))
12788 return false;
12789 }
12790 }
12791 return true;
12792}
12793
12794bool ScalarEvolution::isImpliedCondOperandsViaShift(CmpPredicate Pred,
12795 const SCEV *LHS,
12796 const SCEV *RHS,
12797 const SCEV *FoundLHS,
12798 const SCEV *FoundRHS) {
12799 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make
12800 // sure that we are dealing with same LHS.
12801 if (RHS == FoundRHS) {
12802 std::swap(LHS, RHS);
12803 std::swap(FoundLHS, FoundRHS);
12805 }
12806 if (LHS != FoundLHS)
12807 return false;
12808
12809 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
12810 if (!SUFoundRHS)
12811 return false;
12812
12813 Value *Shiftee, *ShiftValue;
12814
12815 using namespace PatternMatch;
12816 if (match(SUFoundRHS->getValue(),
12817 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
12818 auto *ShifteeS = getSCEV(Shiftee);
12819 // Prove one of the following:
12820 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
12821 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
12822 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12823 // ---> LHS <s RHS
12824 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12825 // ---> LHS <=s RHS
12826 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
12827 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
12828 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
12829 if (isKnownNonNegative(ShifteeS))
12830 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
12831 }
12832
12833 return false;
12834}
12835
12836bool ScalarEvolution::isImpliedCondOperandsViaMatchingDiff(
12837 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12838 const SCEV *FoundRHS) {
12839 // Only valid for equality predicates: (A == B) implies (C == D) when
12840 // the SCEV difference A - B equals C - D (they check the same
12841 // underlying relationship at every iteration).
12842 if (!ICmpInst::isEquality(Pred))
12843 return false;
12844
12845 // Restrict to cases involving loop recurrences - that's where this
12846 // pattern arises (correlated IV comparisons). This avoids calling
12847 // getMinusSCEV on arbitrary non-loop expressions.
12849 (!isa<SCEVAddRecExpr>(FoundLHS) && !isa<SCEVAddRecExpr>(FoundRHS)))
12850 return false;
12851
12852 // AddRecs from different loops can never produce matching differences.
12853 const SCEVAddRecExpr *QueryAddRec = dyn_cast<SCEVAddRecExpr>(LHS);
12854 if (!QueryAddRec)
12855 QueryAddRec = cast<SCEVAddRecExpr>(RHS);
12856 const SCEVAddRecExpr *FoundAddRec = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12857 if (!FoundAddRec)
12858 FoundAddRec = cast<SCEVAddRecExpr>(FoundRHS);
12859 if (QueryAddRec->getLoop() != FoundAddRec->getLoop())
12860 return false;
12861
12862 // If the strides differ, the differences can never match.
12863 if (QueryAddRec->getStepRecurrence(*this) !=
12864 FoundAddRec->getStepRecurrence(*this))
12865 return false;
12866
12867 // Compute differences. For pointer-typed operands sharing the same base,
12868 // getMinusSCEV strips the common base and returns an integer SCEV.
12869 // For example, {base,+,8} - (base+8*n) = {-8n,+,8}
12870 const SCEV *FoundDiff = getMinusSCEV(FoundLHS, FoundRHS);
12871 if (isa<SCEVCouldNotCompute>(FoundDiff))
12872 return false;
12873
12874 const SCEV *Diff = getMinusSCEV(LHS, RHS);
12875 if (isa<SCEVCouldNotCompute>(Diff))
12876 return false;
12877
12878 return Diff == FoundDiff;
12879}
12880
12881bool ScalarEvolution::isImpliedCondOperands(CmpPredicate Pred, const SCEV *LHS,
12882 const SCEV *RHS,
12883 const SCEV *FoundLHS,
12884 const SCEV *FoundRHS,
12885 const Instruction *CtxI) {
12886 return isImpliedCondOperandsViaRanges(Pred, LHS, RHS, Pred, FoundLHS,
12887 FoundRHS) ||
12888 isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS,
12889 FoundRHS) ||
12890 isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS) ||
12891 isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12892 CtxI) ||
12893 isImpliedCondOperandsViaMatchingDiff(Pred, LHS, RHS, FoundLHS,
12894 FoundRHS) ||
12895 isImpliedCondOperandsHelper(Pred, LHS, RHS, FoundLHS, FoundRHS);
12896}
12897
12898/// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
12899template <typename MinMaxExprType>
12900static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
12901 const SCEV *Candidate) {
12902 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12903 if (!MinMaxExpr)
12904 return false;
12905
12906 return is_contained(MinMaxExpr->operands(), Candidate);
12907}
12908
12910 CmpPredicate Pred, const SCEV *LHS,
12911 const SCEV *RHS) {
12912 // If both sides are affine addrecs for the same loop, with equal
12913 // steps, and we know the recurrences don't wrap, then we only
12914 // need to check the predicate on the starting values.
12915
12916 if (!ICmpInst::isRelational(Pred))
12917 return false;
12918
12919 const SCEV *LStart, *RStart, *Step;
12920 const Loop *L;
12921 if (!match(LHS,
12922 m_scev_AffineAddRec(m_SCEV(LStart), m_SCEV(Step), m_Loop(L))) ||
12924 m_SpecificLoop(L))))
12925 return false;
12930 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
12931 return false;
12932
12933 return SE.isKnownPredicate(Pred, LStart, RStart);
12934}
12935
12936/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
12937/// expression?
12939 const SCEV *LHS, const SCEV *RHS) {
12940 switch (Pred) {
12941 default:
12942 return false;
12943
12944 case ICmpInst::ICMP_SGE:
12945 std::swap(LHS, RHS);
12946 [[fallthrough]];
12947 case ICmpInst::ICMP_SLE:
12948 return
12949 // min(A, ...) <= A
12951 // A <= max(A, ...)
12953
12954 case ICmpInst::ICMP_UGE:
12955 std::swap(LHS, RHS);
12956 [[fallthrough]];
12957 case ICmpInst::ICMP_ULE:
12958 return
12959 // min(A, ...) <= A
12960 // FIXME: what about umin_seq?
12962 // A <= max(A, ...)
12964
12965 case ICmpInst::ICMP_UGT:
12966 std::swap(LHS, RHS);
12967 [[fallthrough]];
12968 case ICmpInst::ICMP_ULT:
12969 // umin(Ops) u<= each Op, so proving Op u< RHS for any Op proves
12970 // umin(Ops) u< RHS.
12971 //
12972 // Use computeConstantDifference instead of the more powerful
12973 // isKnownPredicate to keep this check cheap: isKnownPredicateViaMinOrMax
12974 // is called from isKnownViaNonRecursiveReasoning, so recursing into
12975 // the full predicate prover would be expensive.
12976 if (const auto *Min = dyn_cast<SCEVUMinExpr>(LHS)) {
12977 for (SCEVUse Op : Min->operands()) {
12978 std::optional<APInt> Diff = SE.computeConstantDifference(RHS, Op);
12979 // When Op and RHS share a common base differing by a
12980 // constant offset D (RHS - Op = D), Op u< RHS holds iff D != 0 and
12981 // RHS >= D (unsigned), i.e. the subtraction doesn't underflow.
12982 if (Diff && !Diff->isZero() && SE.getUnsignedRangeMin(RHS).uge(*Diff))
12983 return true;
12984 }
12985 }
12986 return false;
12987 }
12988
12989 llvm_unreachable("covered switch fell through?!");
12990}
12991
12992bool ScalarEvolution::isImpliedViaOperations(CmpPredicate Pred, const SCEV *LHS,
12993 const SCEV *RHS,
12994 const SCEV *FoundLHS,
12995 const SCEV *FoundRHS,
12996 unsigned Depth) {
12999 "LHS and RHS have different sizes?");
13000 assert(getTypeSizeInBits(FoundLHS->getType()) ==
13001 getTypeSizeInBits(FoundRHS->getType()) &&
13002 "FoundLHS and FoundRHS have different sizes?");
13003 // We want to avoid hurting the compile time with analysis of too big trees.
13005 return false;
13006
13007 // We only want to work with GT comparison so far.
13008 if (ICmpInst::isLT(Pred)) {
13010 std::swap(LHS, RHS);
13011 std::swap(FoundLHS, FoundRHS);
13012 }
13013
13015
13016 // For unsigned, try to reduce it to corresponding signed comparison.
13017 if (P == ICmpInst::ICMP_UGT)
13018 // We can replace unsigned predicate with its signed counterpart if all
13019 // involved values are non-negative.
13020 // TODO: We could have better support for unsigned.
13021 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
13022 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
13023 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
13024 // use this fact to prove that LHS and RHS are non-negative.
13025 const SCEV *MinusOne = getMinusOne(LHS->getType());
13026 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
13027 FoundRHS) &&
13028 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
13029 FoundRHS))
13031 }
13032
13033 if (P != ICmpInst::ICMP_SGT)
13034 return false;
13035
13036 auto GetOpFromSExt = [&](const SCEV *S) -> const SCEV * {
13037 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
13038 return Ext->getOperand();
13039 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
13040 // the constant in some cases.
13041 return S;
13042 };
13043
13044 // Acquire values from extensions.
13045 auto *OrigLHS = LHS;
13046 auto *OrigFoundLHS = FoundLHS;
13047 LHS = GetOpFromSExt(LHS);
13048 FoundLHS = GetOpFromSExt(FoundLHS);
13049
13050 // Is the SGT predicate can be proved trivially or using the found context.
13051 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
13052 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
13053 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
13054 FoundRHS, Depth + 1);
13055 };
13056
13057 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
13058 // We want to avoid creation of any new non-constant SCEV. Since we are
13059 // going to compare the operands to RHS, we should be certain that we don't
13060 // need any size extensions for this. So let's decline all cases when the
13061 // sizes of types of LHS and RHS do not match.
13062 // TODO: Maybe try to get RHS from sext to catch more cases?
13064 return false;
13065
13066 // Should not overflow.
13067 if (!LHSAddExpr->hasNoSignedWrap())
13068 return false;
13069
13070 SCEVUse LL = LHSAddExpr->getOperand(0);
13071 SCEVUse LR = LHSAddExpr->getOperand(1);
13072 auto *MinusOne = getMinusOne(RHS->getType());
13073
13074 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
13075 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
13076 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
13077 };
13078 // Try to prove the following rule:
13079 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
13080 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
13081 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
13082 return true;
13083 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
13084 Value *LL, *LR;
13085 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
13086
13087 using namespace llvm::PatternMatch;
13088
13089 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
13090 // Rules for division.
13091 // We are going to perform some comparisons with Denominator and its
13092 // derivative expressions. In general case, creating a SCEV for it may
13093 // lead to a complex analysis of the entire graph, and in particular it
13094 // can request trip count recalculation for the same loop. This would
13095 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
13096 // this, we only want to create SCEVs that are constants in this section.
13097 // So we bail if Denominator is not a constant.
13098 if (!isa<ConstantInt>(LR))
13099 return false;
13100
13101 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
13102
13103 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
13104 // then a SCEV for the numerator already exists and matches with FoundLHS.
13105 auto *Numerator = getExistingSCEV(LL);
13106 if (!Numerator || Numerator->getType() != FoundLHS->getType())
13107 return false;
13108
13109 // Make sure that the numerator matches with FoundLHS and the denominator
13110 // is positive.
13111 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
13112 return false;
13113
13114 auto *DTy = Denominator->getType();
13115 auto *FRHSTy = FoundRHS->getType();
13116 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
13117 // One of types is a pointer and another one is not. We cannot extend
13118 // them properly to a wider type, so let us just reject this case.
13119 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
13120 // to avoid this check.
13121 return false;
13122
13123 // Given that:
13124 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
13125 auto *WTy = getWiderType(DTy, FRHSTy);
13126 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
13127 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
13128
13129 // Try to prove the following rule:
13130 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
13131 // For example, given that FoundLHS > 2. It means that FoundLHS is at
13132 // least 3. If we divide it by Denominator < 4, we will have at least 1.
13133 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
13134 if (isKnownNonPositive(RHS) &&
13135 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
13136 return true;
13137
13138 // Try to prove the following rule:
13139 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
13140 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
13141 // If we divide it by Denominator > 2, then:
13142 // 1. If FoundLHS is negative, then the result is 0.
13143 // 2. If FoundLHS is non-negative, then the result is non-negative.
13144 // Anyways, the result is non-negative.
13145 auto *MinusOne = getMinusOne(WTy);
13146 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
13147 if (isKnownNegative(RHS) &&
13148 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
13149 return true;
13150 }
13151 }
13152
13153 // If our expression contained SCEVUnknown Phis, and we split it down and now
13154 // need to prove something for them, try to prove the predicate for every
13155 // possible incoming values of those Phis.
13156 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
13157 return true;
13158
13159 return false;
13160}
13161
13163 const SCEV *RHS) {
13164 // zext x u<= sext x, sext x s<= zext x
13165 const SCEV *Op;
13166 switch (Pred) {
13167 case ICmpInst::ICMP_SGE:
13168 std::swap(LHS, RHS);
13169 [[fallthrough]];
13170 case ICmpInst::ICMP_SLE: {
13171 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt.
13172 return match(LHS, m_scev_SExt(m_SCEV(Op))) &&
13174 }
13175 case ICmpInst::ICMP_UGE:
13176 std::swap(LHS, RHS);
13177 [[fallthrough]];
13178 case ICmpInst::ICMP_ULE: {
13179 // If operand >=u 0 then ZExt == SExt. If operand <u 0 then ZExt <u SExt.
13180 return match(LHS, m_scev_ZExt(m_SCEV(Op))) &&
13182 }
13183 default:
13184 return false;
13185 };
13186 llvm_unreachable("unhandled case");
13187}
13188
13189bool ScalarEvolution::isKnownViaNonRecursiveReasoning(CmpPredicate Pred,
13190 SCEVUse LHS,
13191 SCEVUse RHS) {
13192 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
13193 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
13194 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
13195 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
13196 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
13197}
13198
13199bool ScalarEvolution::isImpliedCondOperandsHelper(CmpPredicate Pred,
13200 const SCEV *LHS,
13201 const SCEV *RHS,
13202 const SCEV *FoundLHS,
13203 const SCEV *FoundRHS) {
13204 switch (Pred) {
13205 default:
13206 llvm_unreachable("Unexpected CmpPredicate value!");
13207 case ICmpInst::ICMP_EQ:
13208 case ICmpInst::ICMP_NE:
13209 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
13210 return true;
13211 break;
13212 case ICmpInst::ICMP_SLT:
13213 case ICmpInst::ICMP_SLE:
13214 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
13215 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
13216 return true;
13217 break;
13218 case ICmpInst::ICMP_SGT:
13219 case ICmpInst::ICMP_SGE:
13220 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
13221 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
13222 return true;
13223 break;
13224 case ICmpInst::ICMP_ULT:
13225 case ICmpInst::ICMP_ULE:
13226 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
13227 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
13228 return true;
13229 break;
13230 case ICmpInst::ICMP_UGT:
13231 case ICmpInst::ICMP_UGE:
13232 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
13233 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
13234 return true;
13235 break;
13236 }
13237
13238 // Maybe it can be proved via operations?
13239 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
13240 return true;
13241
13242 return false;
13243}
13244
13245bool ScalarEvolution::isImpliedCondOperandsViaRanges(
13246 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, CmpPredicate FoundPred,
13247 const SCEV *FoundLHS, const SCEV *FoundRHS) {
13248 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
13249 // The restriction on `FoundRHS` be lifted easily -- it exists only to
13250 // reduce the compile time impact of this optimization.
13251 return false;
13252
13253 std::optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
13254 if (!Addend)
13255 return false;
13256
13257 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
13258
13259 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
13260 // antecedent "`FoundLHS` `FoundPred` `FoundRHS`".
13261 ConstantRange FoundLHSRange =
13262 ConstantRange::makeExactICmpRegion(FoundPred, ConstFoundRHS);
13263
13264 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
13265 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
13266
13267 // We can also compute the range of values for `LHS` that satisfy the
13268 // consequent, "`LHS` `Pred` `RHS`":
13269 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
13270 // The antecedent implies the consequent if every value of `LHS` that
13271 // satisfies the antecedent also satisfies the consequent.
13272 return LHSRange.icmp(Pred, ConstRHS);
13273}
13274
13275bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
13276 bool IsSigned) {
13277 assert(isKnownPositive(Stride) && "Positive stride expected!");
13278
13279 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13280 const SCEV *One = getOne(Stride->getType());
13281
13282 if (IsSigned) {
13283 APInt MaxRHS = getSignedRangeMax(RHS);
13284 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
13285 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13286
13287 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
13288 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
13289 }
13290
13291 APInt MaxRHS = getUnsignedRangeMax(RHS);
13292 APInt MaxValue = APInt::getMaxValue(BitWidth);
13293 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13294
13295 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
13296 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
13297}
13298
13299bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
13300 bool IsSigned) {
13301
13302 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13303 const SCEV *One = getOne(Stride->getType());
13304
13305 if (IsSigned) {
13306 APInt MinRHS = getSignedRangeMin(RHS);
13307 APInt MinValue = APInt::getSignedMinValue(BitWidth);
13308 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13309
13310 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
13311 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
13312 }
13313
13314 APInt MinRHS = getUnsignedRangeMin(RHS);
13315 APInt MinValue = APInt::getMinValue(BitWidth);
13316 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13317
13318 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
13319 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
13320}
13321
13323 // umin(N, 1) + floor((N - umin(N, 1)) / D)
13324 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
13325 // expression fixes the case of N=0.
13326 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
13327 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
13328 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
13329}
13330
13331const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
13332 const SCEV *Stride,
13333 const SCEV *End,
13334 unsigned BitWidth,
13335 bool IsSigned) {
13336 // The logic in this function assumes we can represent a positive stride.
13337 // If we can't, the backedge-taken count must be zero.
13338 if (IsSigned && BitWidth == 1)
13339 return getZero(Stride->getType());
13340
13341 // This code below only been closely audited for negative strides in the
13342 // unsigned comparison case, it may be correct for signed comparison, but
13343 // that needs to be established.
13344 if (IsSigned && isKnownNegative(Stride))
13345 return getCouldNotCompute();
13346
13347 // Calculate the maximum backedge count based on the range of values
13348 // permitted by Start, End, and Stride.
13349 APInt MinStart =
13350 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
13351
13352 APInt MinStride =
13353 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
13354
13355 // We assume either the stride is positive, or the backedge-taken count
13356 // is zero. So force StrideForMaxBECount to be at least one.
13357 APInt One(BitWidth, 1);
13358 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
13359 : APIntOps::umax(One, MinStride);
13360
13361 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
13362 : APInt::getMaxValue(BitWidth);
13363 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
13364
13365 // Although End can be a MAX expression we estimate MaxEnd considering only
13366 // the case End = RHS of the loop termination condition. This is safe because
13367 // in the other case (End - Start) is zero, leading to a zero maximum backedge
13368 // taken count.
13369 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
13370 : APIntOps::umin(getUnsignedRangeMax(End), Limit);
13371
13372 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
13373 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
13374 : APIntOps::umax(MaxEnd, MinStart);
13375
13376 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */,
13377 getConstant(StrideForMaxBECount) /* Step */);
13378}
13379
13381ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
13382 const Loop *L, bool IsSigned,
13383 bool ControlsOnlyExit, bool AllowPredicates) {
13385
13387 bool PredicatedIV = false;
13388 if (!IV) {
13389 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
13390 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
13391 if (AR && AR->getLoop() == L && AR->isAffine()) {
13392 auto canProveNUW = [&]() {
13393 // We can use the comparison to infer no-wrap flags only if it fully
13394 // controls the loop exit.
13395 if (!ControlsOnlyExit)
13396 return false;
13397
13398 if (!isLoopInvariant(RHS, L))
13399 return false;
13400
13401 if (!isKnownNonZero(AR->getStepRecurrence(*this)))
13402 // We need the sequence defined by AR to strictly increase in the
13403 // unsigned integer domain for the logic below to hold.
13404 return false;
13405
13406 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
13407 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
13408 // If RHS <=u Limit, then there must exist a value V in the sequence
13409 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
13410 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned
13411 // overflow occurs. This limit also implies that a signed comparison
13412 // (in the wide bitwidth) is equivalent to an unsigned comparison as
13413 // the high bits on both sides must be zero.
13414 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
13415 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
13416 Limit = Limit.zext(OuterBitWidth);
13417 return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit);
13418 };
13419 auto Flags = AR->getNoWrapFlags();
13420 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
13421 Flags = setFlags(Flags, SCEV::FlagNUW);
13422
13423 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
13424 if (AR->hasNoUnsignedWrap()) {
13425 // Emulate what getZeroExtendExpr would have done during construction
13426 // if we'd been able to infer the fact just above at that time.
13427 const SCEV *Step = AR->getStepRecurrence(*this);
13428 Type *Ty = ZExt->getType();
13429 auto *S = getAddRecExpr(
13431 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
13433 }
13434 }
13435 }
13436 }
13437
13438
13439 if (!IV && AllowPredicates) {
13440 // Try to make this an AddRec using runtime tests, in the first X
13441 // iterations of this loop, where X is the SCEV expression found by the
13442 // algorithm below.
13443 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13444 PredicatedIV = true;
13445 }
13446
13447 // Avoid weird loops
13448 if (!IV || IV->getLoop() != L || !IV->isAffine())
13449 return getCouldNotCompute();
13450
13451 // A precondition of this method is that the condition being analyzed
13452 // reaches an exiting branch which dominates the latch. Given that, we can
13453 // assume that an increment which violates the nowrap specification and
13454 // produces poison must cause undefined behavior when the resulting poison
13455 // value is branched upon and thus we can conclude that the backedge is
13456 // taken no more often than would be required to produce that poison value.
13457 // Note that a well defined loop can exit on the iteration which violates
13458 // the nowrap specification if there is another exit (either explicit or
13459 // implicit/exceptional) which causes the loop to execute before the
13460 // exiting instruction we're analyzing would trigger UB.
13461 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13462 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13464
13465 const SCEV *Stride = IV->getStepRecurrence(*this);
13466
13467 bool PositiveStride = isKnownPositive(Stride);
13468
13469 // Avoid negative or zero stride values.
13470 if (!PositiveStride) {
13471 // We can compute the correct backedge taken count for loops with unknown
13472 // strides if we can prove that the loop is not an infinite loop with side
13473 // effects. Here's the loop structure we are trying to handle -
13474 //
13475 // i = start
13476 // do {
13477 // A[i] = i;
13478 // i += s;
13479 // } while (i < end);
13480 //
13481 // The backedge taken count for such loops is evaluated as -
13482 // (max(end, start + stride) - start - 1) /u stride
13483 //
13484 // The additional preconditions that we need to check to prove correctness
13485 // of the above formula is as follows -
13486 //
13487 // a) IV is either nuw or nsw depending upon signedness (indicated by the
13488 // NoWrap flag).
13489 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13490 // no side effects within the loop)
13491 // c) loop has a single static exit (with no abnormal exits)
13492 //
13493 // Precondition a) implies that if the stride is negative, this is a single
13494 // trip loop. The backedge taken count formula reduces to zero in this case.
13495 //
13496 // Precondition b) and c) combine to imply that if rhs is invariant in L,
13497 // then a zero stride means the backedge can't be taken without executing
13498 // undefined behavior.
13499 //
13500 // The positive stride case is the same as isKnownPositive(Stride) returning
13501 // true (original behavior of the function).
13502 //
13503 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
13505 return getCouldNotCompute();
13506
13507 if (!isKnownNonZero(Stride)) {
13508 // If we have a step of zero, and RHS isn't invariant in L, we don't know
13509 // if it might eventually be greater than start and if so, on which
13510 // iteration. We can't even produce a useful upper bound.
13511 if (!isLoopInvariant(RHS, L))
13512 return getCouldNotCompute();
13513
13514 // We allow a potentially zero stride, but we need to divide by stride
13515 // below. Since the loop can't be infinite and this check must control
13516 // the sole exit, we can infer the exit must be taken on the first
13517 // iteration (e.g. backedge count = 0) if the stride is zero. Given that,
13518 // we know the numerator in the divides below must be zero, so we can
13519 // pick an arbitrary non-zero value for the denominator (e.g. stride)
13520 // and produce the right result.
13521 // FIXME: Handle the case where Stride is poison?
13522 auto wouldZeroStrideBeUB = [&]() {
13523 // Proof by contradiction. Suppose the stride were zero. If we can
13524 // prove that the backedge *is* taken on the first iteration, then since
13525 // we know this condition controls the sole exit, we must have an
13526 // infinite loop. We can't have a (well defined) infinite loop per
13527 // check just above.
13528 // Note: The (Start - Stride) term is used to get the start' term from
13529 // (start' + stride,+,stride). Remember that we only care about the
13530 // result of this expression when stride == 0 at runtime.
13531 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
13532 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
13533 };
13534 if (!wouldZeroStrideBeUB()) {
13535 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13536 }
13537 }
13538 } else if (!NoWrap) {
13539 // Avoid proven overflow cases: this will ensure that the backedge taken
13540 // count will not generate any unsigned overflow.
13541 if (canIVOverflowOnLT(RHS, Stride, IsSigned))
13542 return getCouldNotCompute();
13543 }
13544
13545 // On all paths just preceeding, we established the following invariant:
13546 // IV can be assumed not to overflow up to and including the exiting
13547 // iteration. We proved this in one of two ways:
13548 // 1) We can show overflow doesn't occur before the exiting iteration
13549 // 1a) canIVOverflowOnLT, and b) step of one
13550 // 2) We can show that if overflow occurs, the loop must execute UB
13551 // before any possible exit.
13552 // Note that we have not yet proved RHS invariant (in general).
13553
13554 const SCEV *Start = IV->getStart();
13555
13556 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
13557 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
13558 // Use integer-typed versions for actual computation; we can't subtract
13559 // pointers in general.
13560 const SCEV *OrigStart = Start;
13561 const SCEV *OrigRHS = RHS;
13562 if (Start->getType()->isPointerTy()) {
13563 Start = getPtrToAddrExpr(Start);
13564 if (isa<SCEVCouldNotCompute>(Start))
13565 return Start;
13566 }
13567 if (RHS->getType()->isPointerTy()) {
13570 return RHS;
13571 }
13572
13573 const SCEV *End = nullptr, *BECount = nullptr,
13574 *BECountIfBackedgeTaken = nullptr;
13575 if (!isLoopInvariant(RHS, L)) {
13576 const auto *RHSAddRec = dyn_cast<SCEVAddRecExpr>(RHS);
13577 if (PositiveStride && RHSAddRec != nullptr && RHSAddRec->getLoop() == L &&
13578 any(RHSAddRec->getNoWrapFlags())) {
13579 // The structure of loop we are trying to calculate backedge count of:
13580 //
13581 // left = left_start
13582 // right = right_start
13583 //
13584 // while(left < right){
13585 // ... do something here ...
13586 // left += s1; // stride of left is s1 (s1 > 0)
13587 // right += s2; // stride of right is s2 (s2 < 0)
13588 // }
13589 //
13590
13591 const SCEV *RHSStart = RHSAddRec->getStart();
13592 const SCEV *RHSStride = RHSAddRec->getStepRecurrence(*this);
13593
13594 // If Stride - RHSStride is positive and does not overflow, we can write
13595 // backedge count as ->
13596 // ceil((End - Start) /u (Stride - RHSStride))
13597 // Where, End = max(RHSStart, Start)
13598
13599 // Check if RHSStride < 0 and Stride - RHSStride will not overflow.
13600 if (isKnownNegative(RHSStride) &&
13601 willNotOverflow(Instruction::Sub, /*Signed=*/true, Stride,
13602 RHSStride)) {
13603
13604 const SCEV *Denominator = getMinusSCEV(Stride, RHSStride);
13605 if (isKnownPositive(Denominator)) {
13606 End = IsSigned ? getSMaxExpr(RHSStart, Start)
13607 : getUMaxExpr(RHSStart, Start);
13608
13609 // We can do this because End >= Start, as End = max(RHSStart, Start)
13610 const SCEV *Delta = getMinusSCEV(End, Start);
13611
13612 BECount = getUDivCeilSCEV(Delta, Denominator);
13613 BECountIfBackedgeTaken =
13614 getUDivCeilSCEV(getMinusSCEV(RHSStart, Start), Denominator);
13615 }
13616 }
13617 }
13618 if (BECount == nullptr) {
13619 // If we cannot calculate ExactBECount, we can calculate the MaxBECount,
13620 // given the start, stride and max value for the end bound of the
13621 // loop (RHS), and the fact that IV does not overflow (which is
13622 // checked above).
13623 const SCEV *MaxBECount = computeMaxBECountForLT(
13624 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
13625 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
13626 MaxBECount, false /*MaxOrZero*/, Predicates);
13627 }
13628 } else {
13629 // We use the expression (max(End,Start)-Start)/Stride to describe the
13630 // backedge count, as if the backedge is taken at least once
13631 // max(End,Start) is End and so the result is as above, and if not
13632 // max(End,Start) is Start so we get a backedge count of zero.
13633 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
13634 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!");
13635 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
13636 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
13637 // Can we prove (max(RHS,Start) > Start - Stride?
13638 if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) &&
13639 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
13640 // In this case, we can use a refined formula for computing backedge
13641 // taken count. The general formula remains:
13642 // "End-Start /uceiling Stride" where "End = max(RHS,Start)"
13643 // We want to use the alternate formula:
13644 // "((End - 1) - (Start - Stride)) /u Stride"
13645 // Let's do a quick case analysis to show these are equivalent under
13646 // our precondition that max(RHS,Start) > Start - Stride.
13647 // * For RHS <= Start, the backedge-taken count must be zero.
13648 // "((End - 1) - (Start - Stride)) /u Stride" reduces to
13649 // "((Start - 1) - (Start - Stride)) /u Stride" which simplies to
13650 // "Stride - 1 /u Stride" which is indeed zero for all non-zero values
13651 // of Stride. For 0 stride, we've use umin(1,Stride) above,
13652 // reducing this to the stride of 1 case.
13653 // * For RHS >= Start, the backedge count must be "RHS-Start /uceil
13654 // Stride".
13655 // "((End - 1) - (Start - Stride)) /u Stride" reduces to
13656 // "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to
13657 // "((RHS - (Start - Stride) - 1) /u Stride".
13658 // Our preconditions trivially imply no overflow in that form.
13659 const SCEV *MinusOne = getMinusOne(Stride->getType());
13660 const SCEV *Numerator =
13661 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
13662 BECount = getUDivExpr(Numerator, Stride);
13663 }
13664
13665 if (!BECount) {
13666 auto canProveRHSGreaterThanEqualStart = [&]() {
13667 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
13668 const SCEV *GuardedRHS = applyLoopGuards(OrigRHS, L);
13669 const SCEV *GuardedStart = applyLoopGuards(OrigStart, L);
13670
13671 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart) ||
13672 isKnownPredicate(CondGE, GuardedRHS, GuardedStart))
13673 return true;
13674
13675 // (RHS > Start - 1) implies RHS >= Start.
13676 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
13677 // "Start - 1" doesn't overflow.
13678 // * For signed comparison, if Start - 1 does overflow, it's equal
13679 // to INT_MAX, and "RHS >s INT_MAX" is trivially false.
13680 // * For unsigned comparison, if Start - 1 does overflow, it's equal
13681 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
13682 //
13683 // FIXME: Should isLoopEntryGuardedByCond do this for us?
13684 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13685 auto *StartMinusOne =
13686 getAddExpr(OrigStart, getMinusOne(OrigStart->getType()));
13687 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
13688 };
13689
13690 // If we know that RHS >= Start in the context of loop, then we know
13691 // that max(RHS, Start) = RHS at this point.
13692 if (canProveRHSGreaterThanEqualStart()) {
13693 End = RHS;
13694 } else {
13695 // If RHS < Start, the backedge will be taken zero times. So in
13696 // general, we can write the backedge-taken count as:
13697 //
13698 // RHS >= Start ? ceil(RHS - Start) / Stride : 0
13699 //
13700 // We convert it to the following to make it more convenient for SCEV:
13701 //
13702 // ceil(max(RHS, Start) - Start) / Stride
13703 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
13704
13705 // See what would happen if we assume the backedge is taken. This is
13706 // used to compute MaxBECount.
13707 BECountIfBackedgeTaken =
13708 getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
13709 }
13710
13711 // At this point, we know:
13712 //
13713 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
13714 // 2. The index variable doesn't overflow.
13715 //
13716 // Therefore, we know N exists such that
13717 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
13718 // doesn't overflow.
13719 //
13720 // Using this information, try to prove whether the addition in
13721 // "(Start - End) + (Stride - 1)" has unsigned overflow.
13722 const SCEV *One = getOne(Stride->getType());
13723 bool MayAddOverflow = [&] {
13724 if (isKnownToBeAPowerOfTwo(Stride)) {
13725 // Suppose Stride is a power of two, and Start/End are unsigned
13726 // integers. Let UMAX be the largest representable unsigned
13727 // integer.
13728 //
13729 // By the preconditions of this function, we know
13730 // "(Start + Stride * N) >= End", and this doesn't overflow.
13731 // As a formula:
13732 //
13733 // End <= (Start + Stride * N) <= UMAX
13734 //
13735 // Subtracting Start from all the terms:
13736 //
13737 // End - Start <= Stride * N <= UMAX - Start
13738 //
13739 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore:
13740 //
13741 // End - Start <= Stride * N <= UMAX
13742 //
13743 // Stride * N is a multiple of Stride. Therefore,
13744 //
13745 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
13746 //
13747 // Since Stride is a power of two, UMAX + 1 is divisible by
13748 // Stride. Therefore, UMAX mod Stride == Stride - 1. So we can
13749 // write:
13750 //
13751 // End - Start <= Stride * N <= UMAX - Stride - 1
13752 //
13753 // Dropping the middle term:
13754 //
13755 // End - Start <= UMAX - Stride - 1
13756 //
13757 // Adding Stride - 1 to both sides:
13758 //
13759 // (End - Start) + (Stride - 1) <= UMAX
13760 //
13761 // In other words, the addition doesn't have unsigned overflow.
13762 //
13763 // A similar proof works if we treat Start/End as signed values.
13764 // Just rewrite steps before "End - Start <= Stride * N <= UMAX"
13765 // to use signed max instead of unsigned max. Note that we're
13766 // trying to prove a lack of unsigned overflow in either case.
13767 return false;
13768 }
13769 if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
13770 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End
13771 // - 1. If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1
13772 // <u End. If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End -
13773 // 1 <s End.
13774 //
13775 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 ==
13776 // End.
13777 return false;
13778 }
13779 return true;
13780 }();
13781
13782 const SCEV *Delta = getMinusSCEV(End, Start);
13783 if (!MayAddOverflow) {
13784 // floor((D + (S - 1)) / S)
13785 // We prefer this formulation if it's legal because it's fewer
13786 // operations.
13787 BECount =
13788 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13789 } else {
13790 BECount = getUDivCeilSCEV(Delta, Stride);
13791 }
13792 }
13793 }
13794
13795 const SCEV *ConstantMaxBECount;
13796 bool MaxOrZero = false;
13797 if (isa<SCEVConstant>(BECount)) {
13798 ConstantMaxBECount = BECount;
13799 } else if (BECountIfBackedgeTaken &&
13800 isa<SCEVConstant>(BECountIfBackedgeTaken)) {
13801 // If we know exactly how many times the backedge will be taken if it's
13802 // taken at least once, then the backedge count will either be that or
13803 // zero.
13804 ConstantMaxBECount = BECountIfBackedgeTaken;
13805 MaxOrZero = true;
13806 } else {
13807 ConstantMaxBECount = computeMaxBECountForLT(
13808 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
13809 }
13810
13811 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
13812 !isa<SCEVCouldNotCompute>(BECount))
13813 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
13814
13815 const SCEV *SymbolicMaxBECount =
13816 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13817 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
13818 Predicates);
13819}
13820
13821ScalarEvolution::ExitLimit ScalarEvolution::howManyGreaterThans(
13822 const SCEV *LHS, const SCEV *RHS, const Loop *L, bool IsSigned,
13823 bool ControlsOnlyExit, bool AllowPredicates) {
13825 // We handle only IV > Invariant
13826 if (!isLoopInvariant(RHS, L))
13827 return getCouldNotCompute();
13828
13829 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
13830 if (!IV && AllowPredicates)
13831 // Try to make this an AddRec using runtime tests, in the first X
13832 // iterations of this loop, where X is the SCEV expression found by the
13833 // algorithm below.
13834 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13835
13836 // Avoid weird loops
13837 if (!IV || IV->getLoop() != L || !IV->isAffine())
13838 return getCouldNotCompute();
13839
13840 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13841 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13843
13844 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
13845
13846 // Avoid negative or zero stride values
13847 if (!isKnownPositive(Stride))
13848 return getCouldNotCompute();
13849
13850 // Avoid proven overflow cases: this will ensure that the backedge taken count
13851 // will not generate any unsigned overflow. Relaxed no-overflow conditions
13852 // exploit NoWrapFlags, allowing to optimize in presence of undefined
13853 // behaviors like the case of C language.
13854 if (!Stride->isOne() && !NoWrap)
13855 if (canIVOverflowOnGT(RHS, Stride, IsSigned))
13856 return getCouldNotCompute();
13857
13858 const SCEV *Start = IV->getStart();
13859 const SCEV *End = RHS;
13860 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
13861 // If we know that Start >= RHS in the context of loop, then we know that
13862 // min(RHS, Start) = RHS at this point.
13864 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
13865 End = RHS;
13866 else
13867 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
13868 }
13869
13870 if (Start->getType()->isPointerTy()) {
13871 Start = getPtrToAddrExpr(Start);
13872 if (isa<SCEVCouldNotCompute>(Start))
13873 return Start;
13874 }
13875 if (End->getType()->isPointerTy()) {
13876 End = getPtrToAddrExpr(End);
13877 if (isa<SCEVCouldNotCompute>(End))
13878 return End;
13879 }
13880
13881 // Compute ((Start - End) + (Stride - 1)) / Stride.
13882 // FIXME: This can overflow. Holding off on fixing this for now;
13883 // howManyGreaterThans will hopefully be gone soon.
13884 const SCEV *One = getOne(Stride->getType());
13885 const SCEV *BECount = getUDivExpr(
13886 getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride);
13887
13888 APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
13890
13891 APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
13892 : getUnsignedRangeMin(Stride);
13893
13894 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
13895 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
13896 : APInt::getMinValue(BitWidth) + (MinStride - 1);
13897
13898 // Although End can be a MIN expression we estimate MinEnd considering only
13899 // the case End = RHS. This is safe because in the other case (Start - End)
13900 // is zero, leading to a zero maximum backedge taken count.
13901 APInt MinEnd =
13902 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
13903 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
13904
13905 const SCEV *ConstantMaxBECount =
13906 isa<SCEVConstant>(BECount)
13907 ? BECount
13908 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd),
13909 getConstant(MinStride));
13910
13911 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount))
13912 ConstantMaxBECount = BECount;
13913 const SCEV *SymbolicMaxBECount =
13914 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13915
13916 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
13917 Predicates);
13918}
13919
13921 ScalarEvolution &SE) const {
13922 if (Range.isFullSet()) // Infinite loop.
13923 return SE.getCouldNotCompute();
13924
13925 // If the start is a non-zero constant, shift the range to simplify things.
13926 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
13927 if (!SC->getValue()->isZero()) {
13929 Operands[0] = SE.getZero(SC->getType());
13930 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
13932 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
13933 return ShiftedAddRec->getNumIterationsInRange(
13934 Range.subtract(SC->getAPInt()), SE);
13935 // This is strange and shouldn't happen.
13936 return SE.getCouldNotCompute();
13937 }
13938
13939 // The only time we can solve this is when we have all constant indices.
13940 // Otherwise, we cannot determine the overflow conditions.
13941 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
13942 return SE.getCouldNotCompute();
13943
13944 // Okay at this point we know that all elements of the chrec are constants and
13945 // that the start element is zero.
13946
13947 // First check to see if the range contains zero. If not, the first
13948 // iteration exits.
13949 unsigned BitWidth = SE.getTypeSizeInBits(getType());
13950 if (!Range.contains(APInt(BitWidth, 0)))
13951 return SE.getZero(getType());
13952
13953 if (isAffine()) {
13954 // If this is an affine expression then we have this situation:
13955 // Solve {0,+,A} in Range === Ax in Range
13956
13957 // We know that zero is in the range. If A is positive then we know that
13958 // the upper value of the range must be the first possible exit value.
13959 // If A is negative then the lower of the range is the last possible loop
13960 // value. Also note that we already checked for a full range.
13961 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
13962 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
13963
13964 // The exit value should be (End+A)/A.
13965 APInt ExitVal = (End + A).udiv(A);
13966 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
13967
13968 // Evaluate at the exit value. If we really did fall out of the valid
13969 // range, then we computed our trip count, otherwise wrap around or other
13970 // things must have happened.
13971 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
13972 if (Range.contains(Val->getValue()))
13973 return SE.getCouldNotCompute(); // Something strange happened
13974
13975 // Ensure that the previous value is in the range.
13976 assert(Range.contains(
13978 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
13979 "Linear scev computation is off in a bad way!");
13980 return SE.getConstant(ExitValue);
13981 }
13982
13983 if (isQuadratic()) {
13984 if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
13985 return SE.getConstant(*S);
13986 }
13987
13988 return SE.getCouldNotCompute();
13989}
13990
13991const SCEVAddRecExpr *
13993 assert(getNumOperands() > 1 && "AddRec with zero step?");
13994 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
13995 // but in this case we cannot guarantee that the value returned will be an
13996 // AddRec because SCEV does not have a fixed point where it stops
13997 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
13998 // may happen if we reach arithmetic depth limit while simplifying. So we
13999 // construct the returned value explicitly.
14001 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
14002 // (this + Step) is {A+B,+,B+C,+...,+,N}.
14003 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
14004 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
14005 // We know that the last operand is not a constant zero (otherwise it would
14006 // have been popped out earlier). This guarantees us that if the result has
14007 // the same last operand, then it will also not be popped out, meaning that
14008 // the returned value will be an AddRec.
14009 const SCEV *Last = getOperand(getNumOperands() - 1);
14010 assert(!Last->isZero() && "Recurrency with zero step?");
14011 Ops.push_back(Last);
14014}
14015
14016// Return true when S contains at least an undef value.
14018 return SCEVExprContains(
14019 S, [](const SCEV *S) { return match(S, m_scev_UndefOrPoison()); });
14020}
14021
14022// Return true when S contains a value that is a nullptr.
14024 return SCEVExprContains(S, [](const SCEV *S) {
14025 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
14026 return SU->getValue() == nullptr;
14027 return false;
14028 });
14029}
14030
14031/// Return the size of an element read or written by Inst.
14033 Type *Ty;
14034 Type *PtrTy;
14035 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
14036 Ty = Store->getValueOperand()->getType();
14037 PtrTy = Store->getPointerOperandType();
14038 } else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
14039 Ty = Load->getType();
14040 PtrTy = Load->getPointerOperandType();
14041 } else {
14042 return nullptr;
14043 }
14044
14045 Type *ETy = getEffectiveSCEVType(PtrTy);
14046 return getSizeOfExpr(ETy, Ty);
14047}
14048
14049//===----------------------------------------------------------------------===//
14050// SCEVCallbackVH Class Implementation
14051//===----------------------------------------------------------------------===//
14052
14054 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14055 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
14056 SE->ConstantEvolutionLoopExitValue.erase(PN);
14057 SE->eraseValueFromMap(getValPtr());
14058 // this now dangles!
14059}
14060
14061void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
14062 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14063
14064 // Forget all the expressions associated with users of the old value,
14065 // so that future queries will recompute the expressions using the new
14066 // value.
14067 SE->forgetValue(getValPtr());
14068 // this now dangles!
14069}
14070
14071ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
14072 : CallbackVH(V), SE(se) {}
14073
14074//===----------------------------------------------------------------------===//
14075// ScalarEvolution Class Implementation
14076//===----------------------------------------------------------------------===//
14077
14080 LoopInfo &LI)
14081 : F(F), DL(F.getDataLayout()), TLI(TLI), AC(AC), DT(DT), LI(LI),
14082 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
14083 LoopDispositions(64), BlockDispositions(64) {
14084 // To use guards for proving predicates, we need to scan every instruction in
14085 // relevant basic blocks, and not just terminators. Doing this is a waste of
14086 // time if the IR does not actually contain any calls to
14087 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
14088 //
14089 // This pessimizes the case where a pass that preserves ScalarEvolution wants
14090 // to _add_ guards to the module when there weren't any before, and wants
14091 // ScalarEvolution to optimize based on those guards. For now we prefer to be
14092 // efficient in lieu of being smart in that rather obscure case.
14093
14094 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
14095 F.getParent(), Intrinsic::experimental_guard);
14096 HasGuards = GuardDecl && !GuardDecl->use_empty();
14097}
14098
14100 : F(Arg.F), DL(Arg.DL), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC),
14101 DT(Arg.DT), LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
14102 ValueExprMap(std::move(Arg.ValueExprMap)),
14103 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
14104 PendingMerges(std::move(Arg.PendingMerges)),
14105 ConstantMultipleCache(std::move(Arg.ConstantMultipleCache)),
14106 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
14107 PredicatedBackedgeTakenCounts(
14108 std::move(Arg.PredicatedBackedgeTakenCounts)),
14109 BECountUsers(std::move(Arg.BECountUsers)),
14110 ConstantEvolutionLoopExitValue(
14111 std::move(Arg.ConstantEvolutionLoopExitValue)),
14112 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
14113 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
14114 LoopDispositions(std::move(Arg.LoopDispositions)),
14115 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
14116 BlockDispositions(std::move(Arg.BlockDispositions)),
14117 SCEVUsers(std::move(Arg.SCEVUsers)),
14118 UnsignedRanges(std::move(Arg.UnsignedRanges)),
14119 SignedRanges(std::move(Arg.SignedRanges)),
14120 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
14121 UniquePreds(std::move(Arg.UniquePreds)),
14122 SCEVAllocator(std::move(Arg.SCEVAllocator)),
14123 ConstantSCEVs(std::move(Arg.ConstantSCEVs)),
14124 LoopUsers(std::move(Arg.LoopUsers)),
14125 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
14126 FirstUnknown(Arg.FirstUnknown) {
14127 Arg.FirstUnknown = nullptr;
14128}
14129
14131 // Iterate through all the SCEVUnknown instances and call their
14132 // destructors, so that they release their references to their values.
14133 for (SCEVUnknown *U = FirstUnknown; U;) {
14134 SCEVUnknown *Tmp = U;
14135 U = U->Next;
14136 Tmp->~SCEVUnknown();
14137 }
14138 FirstUnknown = nullptr;
14139
14140 ExprValueMap.clear();
14141 ValueExprMap.clear();
14142 HasRecMap.clear();
14143 BackedgeTakenCounts.clear();
14144 PredicatedBackedgeTakenCounts.clear();
14145
14146 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
14147 assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
14148 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
14149 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
14150}
14151
14155
14156/// When printing a top-level SCEV for trip counts, it's helpful to include
14157/// a type for constants which are otherwise hard to disambiguate.
14158static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV* S) {
14159 if (isa<SCEVConstant>(S))
14160 OS << *S->getType() << " ";
14161 OS << *S;
14162}
14163
14165 const Loop *L) {
14166 // Print all inner loops first
14167 for (Loop *I : *L)
14168 PrintLoopInfo(OS, SE, I);
14169
14170 OS << "Loop ";
14171 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14172 OS << ": ";
14173
14174 SmallVector<BasicBlock *, 8> ExitingBlocks;
14175 L->getExitingBlocks(ExitingBlocks);
14176 if (ExitingBlocks.size() != 1)
14177 OS << "<multiple exits> ";
14178
14179 auto *BTC = SE->getBackedgeTakenCount(L);
14180 if (!isa<SCEVCouldNotCompute>(BTC)) {
14181 OS << "backedge-taken count is ";
14182 PrintSCEVWithTypeHint(OS, BTC);
14183 } else
14184 OS << "Unpredictable backedge-taken count.";
14185 OS << "\n";
14186
14187 if (ExitingBlocks.size() > 1)
14188 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14189 OS << " exit count for " << ExitingBlock->getName() << ": ";
14190 const SCEV *EC = SE->getExitCount(L, ExitingBlock);
14191 PrintSCEVWithTypeHint(OS, EC);
14192 if (isa<SCEVCouldNotCompute>(EC)) {
14193 // Retry with predicates.
14195 EC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates);
14196 if (!isa<SCEVCouldNotCompute>(EC)) {
14197 OS << "\n predicated exit count for " << ExitingBlock->getName()
14198 << ": ";
14199 PrintSCEVWithTypeHint(OS, EC);
14200 OS << "\n Predicates:\n";
14201 for (const auto *P : Predicates)
14202 P->print(OS, 4);
14203 }
14204 }
14205 OS << "\n";
14206 }
14207
14208 OS << "Loop ";
14209 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14210 OS << ": ";
14211
14212 auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
14213 if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
14214 OS << "constant max backedge-taken count is ";
14215 PrintSCEVWithTypeHint(OS, ConstantBTC);
14217 OS << ", actual taken count either this or zero.";
14218 } else {
14219 OS << "Unpredictable constant max backedge-taken count. ";
14220 }
14221
14222 OS << "\n"
14223 "Loop ";
14224 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14225 OS << ": ";
14226
14227 auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
14228 if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
14229 OS << "symbolic max backedge-taken count is ";
14230 PrintSCEVWithTypeHint(OS, SymbolicBTC);
14232 OS << ", actual taken count either this or zero.";
14233 } else {
14234 OS << "Unpredictable symbolic max backedge-taken count. ";
14235 }
14236 OS << "\n";
14237
14238 if (ExitingBlocks.size() > 1)
14239 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14240 OS << " symbolic max exit count for " << ExitingBlock->getName() << ": ";
14241 auto *ExitBTC = SE->getExitCount(L, ExitingBlock,
14243 PrintSCEVWithTypeHint(OS, ExitBTC);
14244 if (isa<SCEVCouldNotCompute>(ExitBTC)) {
14245 // Retry with predicates.
14247 ExitBTC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates,
14249 if (!isa<SCEVCouldNotCompute>(ExitBTC)) {
14250 OS << "\n predicated symbolic max exit count for "
14251 << ExitingBlock->getName() << ": ";
14252 PrintSCEVWithTypeHint(OS, ExitBTC);
14253 OS << "\n Predicates:\n";
14254 for (const auto *P : Predicates)
14255 P->print(OS, 4);
14256 }
14257 }
14258 OS << "\n";
14259 }
14260
14262 auto *PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
14263 if (PBT != BTC) {
14264 OS << "Loop ";
14265 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14266 OS << ": ";
14267 if (!isa<SCEVCouldNotCompute>(PBT)) {
14268 OS << "Predicated backedge-taken count is ";
14269 PrintSCEVWithTypeHint(OS, PBT);
14270 } else
14271 OS << "Unpredictable predicated backedge-taken count.";
14272 OS << "\n";
14273 OS << " Predicates:\n";
14274 for (const auto *P : Preds)
14275 P->print(OS, 4);
14276 }
14277 Preds.clear();
14278
14279 auto *PredConstantMax =
14281 if (PredConstantMax != ConstantBTC) {
14282 OS << "Loop ";
14283 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14284 OS << ": ";
14285 if (!isa<SCEVCouldNotCompute>(PredConstantMax)) {
14286 OS << "Predicated constant max backedge-taken count is ";
14287 PrintSCEVWithTypeHint(OS, PredConstantMax);
14288 } else
14289 OS << "Unpredictable predicated constant max backedge-taken count.";
14290 OS << "\n";
14291 OS << " Predicates:\n";
14292 for (const auto *P : Preds)
14293 P->print(OS, 4);
14294 }
14295 Preds.clear();
14296
14297 auto *PredSymbolicMax =
14299 if (SymbolicBTC != PredSymbolicMax) {
14300 OS << "Loop ";
14301 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14302 OS << ": ";
14303 if (!isa<SCEVCouldNotCompute>(PredSymbolicMax)) {
14304 OS << "Predicated symbolic max backedge-taken count is ";
14305 PrintSCEVWithTypeHint(OS, PredSymbolicMax);
14306 } else
14307 OS << "Unpredictable predicated symbolic max backedge-taken count.";
14308 OS << "\n";
14309 OS << " Predicates:\n";
14310 for (const auto *P : Preds)
14311 P->print(OS, 4);
14312 }
14313
14315 OS << "Loop ";
14316 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14317 OS << ": ";
14318 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
14319 }
14320}
14321
14322namespace llvm {
14323// Note: these overloaded operators need to be in the llvm namespace for them
14324// to be resolved correctly. If we put them outside the llvm namespace, the
14325//
14326// OS << ": " << SE.getLoopDisposition(SV, InnerL);
14327//
14328// code below "breaks" and start printing raw enum values as opposed to the
14329// string values.
14332 switch (LD) {
14334 OS << "Variant";
14335 break;
14337 OS << "Invariant";
14338 break;
14340 OS << "Uniform";
14341 break;
14343 OS << "Computable";
14344 break;
14345 }
14346 return OS;
14347}
14348
14351 switch (BD) {
14353 OS << "DoesNotDominate";
14354 break;
14356 OS << "Dominates";
14357 break;
14359 OS << "ProperlyDominates";
14360 break;
14361 }
14362 return OS;
14363}
14364} // namespace llvm
14365
14367 // ScalarEvolution's implementation of the print method is to print
14368 // out SCEV values of all instructions that are interesting. Doing
14369 // this potentially causes it to create new SCEV objects though,
14370 // which technically conflicts with the const qualifier. This isn't
14371 // observable from outside the class though, so casting away the
14372 // const isn't dangerous.
14373 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14374
14375 if (ClassifyExpressions) {
14376 OS << "Classifying expressions for: ";
14377 F.printAsOperand(OS, /*PrintType=*/false);
14378 OS << "\n";
14379 for (Instruction &I : instructions(F))
14380 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
14381 OS << I << '\n';
14382 OS << " --> ";
14383 const SCEV *SV = SE.getSCEV(&I);
14384 SV->print(OS);
14385 if (!isa<SCEVCouldNotCompute>(SV)) {
14386 OS << " U: ";
14387 SE.getUnsignedRange(SV).print(OS);
14388 OS << " S: ";
14389 SE.getSignedRange(SV).print(OS);
14390 }
14391
14392 const Loop *L = LI.getLoopFor(I.getParent());
14393
14394 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
14395 if (AtUse != SV) {
14396 OS << " --> ";
14397 AtUse->print(OS);
14398 if (!isa<SCEVCouldNotCompute>(AtUse)) {
14399 OS << " U: ";
14400 SE.getUnsignedRange(AtUse).print(OS);
14401 OS << " S: ";
14402 SE.getSignedRange(AtUse).print(OS);
14403 }
14404 }
14405
14406 if (L) {
14407 OS << "\t\t" "Exits: ";
14408 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
14409 if (!SE.isLoopInvariant(ExitValue, L)) {
14410 OS << "<<Unknown>>";
14411 } else {
14412 OS << *ExitValue;
14413 }
14414
14415 ListSeparator LS(", ", "\t\tLoopDispositions: { ");
14416 for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
14417 OS << LS;
14418 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14419 OS << ": " << SE.getLoopDisposition(SV, Iter);
14420 }
14421
14422 for (const auto *InnerL : depth_first(L)) {
14423 if (InnerL == L)
14424 continue;
14425 OS << LS;
14426 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14427 OS << ": " << SE.getLoopDisposition(SV, InnerL);
14428 }
14429
14430 OS << " }";
14431 }
14432
14433 OS << "\n";
14434 }
14435 }
14436
14437 OS << "Determining loop execution counts for: ";
14438 F.printAsOperand(OS, /*PrintType=*/false);
14439 OS << "\n";
14440 for (Loop *I : LI)
14441 PrintLoopInfo(OS, &SE, I);
14442}
14443
14446 auto &Values = LoopDispositions[S];
14447 for (auto &V : Values) {
14448 if (V.getPointer() == L)
14449 return V.getInt();
14450 }
14451 Values.emplace_back(L, LoopVariant);
14452 LoopDisposition D = computeLoopDisposition(S, L);
14453 auto &Values2 = LoopDispositions[S];
14454 for (auto &V : llvm::reverse(Values2)) {
14455 if (V.getPointer() == L) {
14456 V.setInt(D);
14457 break;
14458 }
14459 }
14460 return D;
14461}
14462
14464ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
14465 switch (S->getSCEVType()) {
14466 case scConstant:
14467 case scVScale:
14468 return LoopInvariant;
14469 case scAddRecExpr: {
14470 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14471
14472 // If L is the addrec's loop, it's computable.
14473 if (AR->getLoop() == L)
14474 return LoopComputable;
14475
14476 // Add recurrences are never invariant in the function-body (null loop).
14477 if (!L)
14478 return LoopVariant;
14479
14480 // Everything that is not defined at loop entry is variant.
14481 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) {
14482 if (L->contains(AR->getLoop()) &&
14483 llvm::all_of(AR->operands(),
14484 [&](const SCEV *Op) { return isLoopUniform(Op, L); }))
14485 return LoopUniform;
14486
14487 return LoopVariant;
14488 }
14489 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
14490 " dominate the contained loop's header?");
14491
14492 // This recurrence is invariant w.r.t. L if AR's loop contains L.
14493 if (AR->getLoop()->contains(L))
14494 return LoopInvariant;
14495
14496 // This recurrence is variant w.r.t. L if any of its operands
14497 // are variant.
14498 for (SCEVUse Op : AR->operands())
14499 if (!isLoopInvariant(Op, L))
14500 return LoopVariant;
14501
14502 // Otherwise it's loop-invariant.
14503 return LoopInvariant;
14504 }
14505 case scTruncate:
14506 case scZeroExtend:
14507 case scSignExtend:
14508 case scPtrToAddr:
14509 case scAddExpr:
14510 case scMulExpr:
14511 case scUDivExpr:
14512 case scUMaxExpr:
14513 case scSMaxExpr:
14514 case scUMinExpr:
14515 case scSMinExpr:
14516 case scSequentialUMinExpr: {
14517 bool HasVarying = false;
14518 bool HasUniform = false;
14519 for (SCEVUse Op : S->operands()) {
14521 if (D == LoopVariant)
14522 return LoopVariant;
14523 if (D == LoopComputable)
14524 HasVarying = true;
14525 if (D == LoopUniform)
14526 HasUniform = true;
14527 }
14528 return HasVarying ? (HasUniform ? LoopVariant : LoopComputable)
14529 : (HasUniform ? LoopUniform : LoopInvariant);
14530 }
14531 case scUnknown:
14532 // All non-instruction values are loop invariant. All instructions are loop
14533 // invariant if they are not contained in the specified loop.
14534 // Instructions are never considered invariant in the function body
14535 // (null loop) because they are defined within the "loop".
14537 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
14538 return LoopInvariant;
14539 case scCouldNotCompute:
14540 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14541 }
14542 llvm_unreachable("Unknown SCEV kind!");
14543}
14544
14545bool ScalarEvolution::isLoopUniform(const SCEV *S, const Loop *L) {
14547 return D == LoopUniform || D == LoopInvariant;
14548}
14549
14551 return getLoopDisposition(S, L) == LoopInvariant;
14552}
14553
14555 return getLoopDisposition(S, L) == LoopComputable;
14556}
14557
14560 auto &Values = BlockDispositions[S];
14561 for (auto &V : Values) {
14562 if (V.getPointer() == BB)
14563 return V.getInt();
14564 }
14565 Values.emplace_back(BB, DoesNotDominateBlock);
14566 BlockDisposition D = computeBlockDisposition(S, BB);
14567 auto &Values2 = BlockDispositions[S];
14568 for (auto &V : llvm::reverse(Values2)) {
14569 if (V.getPointer() == BB) {
14570 V.setInt(D);
14571 break;
14572 }
14573 }
14574 return D;
14575}
14576
14578ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
14579 switch (S->getSCEVType()) {
14580 case scConstant:
14581 case scVScale:
14583 case scAddRecExpr: {
14584 // This uses a "dominates" query instead of "properly dominates" query
14585 // to test for proper dominance too, because the instruction which
14586 // produces the addrec's value is a PHI, and a PHI effectively properly
14587 // dominates its entire containing block.
14588 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14589 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
14590 return DoesNotDominateBlock;
14591
14592 // Fall through into SCEVNAryExpr handling.
14593 [[fallthrough]];
14594 }
14595 case scTruncate:
14596 case scZeroExtend:
14597 case scSignExtend:
14598 case scPtrToAddr:
14599 case scAddExpr:
14600 case scMulExpr:
14601 case scUDivExpr:
14602 case scUMaxExpr:
14603 case scSMaxExpr:
14604 case scUMinExpr:
14605 case scSMinExpr:
14606 case scSequentialUMinExpr: {
14607 bool Proper = true;
14608 for (const SCEV *NAryOp : S->operands()) {
14610 if (D == DoesNotDominateBlock)
14611 return DoesNotDominateBlock;
14612 if (D == DominatesBlock)
14613 Proper = false;
14614 }
14615 return Proper ? ProperlyDominatesBlock : DominatesBlock;
14616 }
14617 case scUnknown:
14618 if (Instruction *I =
14620 if (I->getParent() == BB)
14621 return DominatesBlock;
14622 if (DT.properlyDominates(I->getParent(), BB))
14624 return DoesNotDominateBlock;
14625 }
14627 case scCouldNotCompute:
14628 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14629 }
14630 llvm_unreachable("Unknown SCEV kind!");
14631}
14632
14633bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
14634 return getBlockDisposition(S, BB) >= DominatesBlock;
14635}
14636
14639}
14640
14641bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
14642 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
14643}
14644
14645void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
14646 bool Predicated) {
14647 auto &BECounts =
14648 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14649 auto It = BECounts.find(L);
14650 if (It != BECounts.end()) {
14651 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
14652 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14653 if (!isa<SCEVConstant>(S)) {
14654 auto UserIt = BECountUsers.find(S);
14655 assert(UserIt != BECountUsers.end());
14656 UserIt->second.erase({L, Predicated});
14657 }
14658 }
14659 }
14660 BECounts.erase(It);
14661 }
14662}
14663
14664void ScalarEvolution::forgetMemoizedResults(ArrayRef<SCEVUse> SCEVs) {
14665 SmallPtrSet<const SCEV *, 8> ToForget(llvm::from_range, SCEVs);
14666 SmallVector<SCEVUse, 8> Worklist(ToForget.begin(), ToForget.end());
14667
14668 while (!Worklist.empty()) {
14669 const SCEV *Curr = Worklist.pop_back_val();
14670 auto Users = SCEVUsers.find(Curr);
14671 if (Users != SCEVUsers.end())
14672 for (const auto *User : Users->second)
14673 if (ToForget.insert(User).second)
14674 Worklist.push_back(User);
14675 }
14676
14677 for (const auto *S : ToForget)
14678 forgetMemoizedResultsImpl(S);
14679
14680 PredicatedSCEVRewrites.remove_if(
14681 [&](const auto &Entry) { return ToForget.count(Entry.first.first); });
14682}
14683
14684void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
14685 LoopDispositions.erase(S);
14686 BlockDispositions.erase(S);
14687 UnsignedRanges.erase(S);
14688 SignedRanges.erase(S);
14689 HasRecMap.erase(S);
14690 ConstantMultipleCache.erase(S);
14691
14692 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
14693 UnsignedWrapViaInductionTried.erase(AR);
14694 SignedWrapViaInductionTried.erase(AR);
14695 }
14696
14697 auto ExprIt = ExprValueMap.find(S);
14698 if (ExprIt != ExprValueMap.end()) {
14699 for (Value *V : ExprIt->second) {
14700 auto ValueIt = ValueExprMap.find_as(V);
14701 if (ValueIt != ValueExprMap.end())
14702 ValueExprMap.erase(ValueIt);
14703 }
14704 ExprValueMap.erase(ExprIt);
14705 }
14706
14707 auto ScopeIt = ValuesAtScopes.find(S);
14708 if (ScopeIt != ValuesAtScopes.end()) {
14709 for (const auto &Pair : ScopeIt->second)
14710 if (!isa_and_nonnull<SCEVConstant>(Pair.second))
14711 llvm::erase(ValuesAtScopesUsers[Pair.second],
14712 std::make_pair(Pair.first, S));
14713 ValuesAtScopes.erase(ScopeIt);
14714 }
14715
14716 auto ScopeUserIt = ValuesAtScopesUsers.find(S);
14717 if (ScopeUserIt != ValuesAtScopesUsers.end()) {
14718 for (const auto &Pair : ScopeUserIt->second)
14719 llvm::erase(ValuesAtScopes[Pair.second], std::make_pair(Pair.first, S));
14720 ValuesAtScopesUsers.erase(ScopeUserIt);
14721 }
14722
14723 auto BEUsersIt = BECountUsers.find(S);
14724 if (BEUsersIt != BECountUsers.end()) {
14725 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
14726 auto Copy = BEUsersIt->second;
14727 for (const auto &Pair : Copy)
14728 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
14729 BECountUsers.erase(BEUsersIt);
14730 }
14731
14732 auto FoldUser = FoldCacheUser.find(S);
14733 if (FoldUser != FoldCacheUser.end())
14734 for (auto &KV : FoldUser->second)
14735 FoldCache.erase(KV);
14736 FoldCacheUser.erase(S);
14737}
14738
14739void
14740ScalarEvolution::getUsedLoops(const SCEV *S,
14741 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
14742 struct FindUsedLoops {
14743 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
14744 : LoopsUsed(LoopsUsed) {}
14745 SmallPtrSetImpl<const Loop *> &LoopsUsed;
14746 bool follow(const SCEV *S) {
14747 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
14748 LoopsUsed.insert(AR->getLoop());
14749 return true;
14750 }
14751
14752 bool isDone() const { return false; }
14753 };
14754
14755 FindUsedLoops F(LoopsUsed);
14756 SCEVTraversal<FindUsedLoops>(F).visitAll(S);
14757}
14758
14759void ScalarEvolution::getReachableBlocks(
14762 Worklist.push_back(&F.getEntryBlock());
14763 while (!Worklist.empty()) {
14764 BasicBlock *BB = Worklist.pop_back_val();
14765 if (!Reachable.insert(BB).second)
14766 continue;
14767
14768 Value *Cond;
14769 BasicBlock *TrueBB, *FalseBB;
14770 if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
14771 m_BasicBlock(FalseBB)))) {
14772 if (auto *C = dyn_cast<ConstantInt>(Cond)) {
14773 Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
14774 continue;
14775 }
14776
14777 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14778 const SCEV *L = getSCEV(Cmp->getOperand(0));
14779 const SCEV *R = getSCEV(Cmp->getOperand(1));
14780 if (isKnownPredicateViaConstantRanges(Cmp->getCmpPredicate(), L, R)) {
14781 Worklist.push_back(TrueBB);
14782 continue;
14783 }
14784 if (isKnownPredicateViaConstantRanges(Cmp->getInverseCmpPredicate(), L,
14785 R)) {
14786 Worklist.push_back(FalseBB);
14787 continue;
14788 }
14789 }
14790 }
14791
14792 append_range(Worklist, successors(BB));
14793 }
14794}
14795
14797 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14798 ScalarEvolution SE2(F, TLI, AC, DT, LI);
14799
14800 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
14801
14802 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
14803 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
14804 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
14805
14806 const SCEV *visitConstant(const SCEVConstant *Constant) {
14807 return SE.getConstant(Constant->getAPInt());
14808 }
14809
14810 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14811 return SE.getUnknown(Expr->getValue());
14812 }
14813
14814 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
14815 return SE.getCouldNotCompute();
14816 }
14817 };
14818
14819 SCEVMapper SCM(SE2);
14820 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
14821 SE2.getReachableBlocks(ReachableBlocks, F);
14822
14823 auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
14824 if (containsUndefs(Old) || containsUndefs(New)) {
14825 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
14826 // not propagate undef aggressively). This means we can (and do) fail
14827 // verification in cases where a transform makes a value go from "undef"
14828 // to "undef+1" (say). The transform is fine, since in both cases the
14829 // result is "undef", but SCEV thinks the value increased by 1.
14830 return nullptr;
14831 }
14832
14833 // Unless VerifySCEVStrict is set, we only compare constant deltas.
14834 const SCEV *Delta = SE2.getMinusSCEV(Old, New);
14835 if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
14836 return nullptr;
14837
14838 return Delta;
14839 };
14840
14841 while (!LoopStack.empty()) {
14842 auto *L = LoopStack.pop_back_val();
14843 llvm::append_range(LoopStack, *L);
14844
14845 // Only verify BECounts in reachable loops. For an unreachable loop,
14846 // any BECount is legal.
14847 if (!ReachableBlocks.contains(L->getHeader()))
14848 continue;
14849
14850 // Only verify cached BECounts. Computing new BECounts may change the
14851 // results of subsequent SCEV uses.
14852 auto It = BackedgeTakenCounts.find(L);
14853 if (It == BackedgeTakenCounts.end())
14854 continue;
14855
14856 auto *CurBECount =
14857 SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
14858 auto *NewBECount = SE2.getBackedgeTakenCount(L);
14859
14860 if (CurBECount == SE2.getCouldNotCompute() ||
14861 NewBECount == SE2.getCouldNotCompute()) {
14862 // NB! This situation is legal, but is very suspicious -- whatever pass
14863 // change the loop to make a trip count go from could not compute to
14864 // computable or vice-versa *should have* invalidated SCEV. However, we
14865 // choose not to assert here (for now) since we don't want false
14866 // positives.
14867 continue;
14868 }
14869
14870 if (SE.getTypeSizeInBits(CurBECount->getType()) >
14871 SE.getTypeSizeInBits(NewBECount->getType()))
14872 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
14873 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
14874 SE.getTypeSizeInBits(NewBECount->getType()))
14875 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
14876
14877 const SCEV *Delta = GetDelta(CurBECount, NewBECount);
14878 if (Delta && !Delta->isZero()) {
14879 dbgs() << "Trip Count for " << *L << " Changed!\n";
14880 dbgs() << "Old: " << *CurBECount << "\n";
14881 dbgs() << "New: " << *NewBECount << "\n";
14882 dbgs() << "Delta: " << *Delta << "\n";
14883 std::abort();
14884 }
14885 }
14886
14887 // Collect all valid loops currently in LoopInfo.
14888 SmallPtrSet<Loop *, 32> ValidLoops;
14889 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
14890 while (!Worklist.empty()) {
14891 Loop *L = Worklist.pop_back_val();
14892 if (ValidLoops.insert(L).second)
14893 Worklist.append(L->begin(), L->end());
14894 }
14895 for (const auto &KV : ValueExprMap) {
14896#ifndef NDEBUG
14897 // Check for SCEV expressions referencing invalid/deleted loops.
14898 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14899 assert(ValidLoops.contains(AR->getLoop()) &&
14900 "AddRec references invalid loop");
14901 }
14902#endif
14903
14904 // Check that the value is also part of the reverse map.
14905 auto It = ExprValueMap.find(KV.second);
14906 if (It == ExprValueMap.end() || !It->second.contains(KV.first)) {
14907 dbgs() << "Value " << *KV.first
14908 << " is in ValueExprMap but not in ExprValueMap\n";
14909 std::abort();
14910 }
14911
14912 if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
14913 if (!ReachableBlocks.contains(I->getParent()))
14914 continue;
14915 const SCEV *OldSCEV = SCM.visit(KV.second);
14916 const SCEV *NewSCEV = SE2.getSCEV(I);
14917 const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14918 if (Delta && !Delta->isZero()) {
14919 dbgs() << "SCEV for value " << *I << " changed!\n"
14920 << "Old: " << *OldSCEV << "\n"
14921 << "New: " << *NewSCEV << "\n"
14922 << "Delta: " << *Delta << "\n";
14923 std::abort();
14924 }
14925 }
14926 }
14927
14928 for (const auto &KV : ExprValueMap) {
14929 for (Value *V : KV.second) {
14930 const SCEV *S = ValueExprMap.lookup(V);
14931 if (!S) {
14932 dbgs() << "Value " << *V
14933 << " is in ExprValueMap but not in ValueExprMap\n";
14934 std::abort();
14935 }
14936 if (S != KV.first) {
14937 dbgs() << "Value " << *V << " mapped to " << *S << " rather than "
14938 << *KV.first << "\n";
14939 std::abort();
14940 }
14941 }
14942 }
14943
14944 // Verify integrity of SCEV users.
14945 for (const auto &S : UniqueSCEVs) {
14946 for (SCEVUse Op : S.operands()) {
14947 // We do not store dependencies of constants.
14948 if (isa<SCEVConstant>(Op))
14949 continue;
14950 auto It = SCEVUsers.find(Op);
14951 if (It != SCEVUsers.end() && It->second.count(&S))
14952 continue;
14953 dbgs() << "Use of operand " << *Op << " by user " << S
14954 << " is not being tracked!\n";
14955 std::abort();
14956 }
14957 }
14958
14959 // Verify integrity of ValuesAtScopes users.
14960 for (const auto &ValueAndVec : ValuesAtScopes) {
14961 const SCEV *Value = ValueAndVec.first;
14962 for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
14963 const Loop *L = LoopAndValueAtScope.first;
14964 const SCEV *ValueAtScope = LoopAndValueAtScope.second;
14965 if (!isa<SCEVConstant>(ValueAtScope)) {
14966 auto It = ValuesAtScopesUsers.find(ValueAtScope);
14967 if (It != ValuesAtScopesUsers.end() &&
14968 is_contained(It->second, std::make_pair(L, Value)))
14969 continue;
14970 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14971 << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
14972 std::abort();
14973 }
14974 }
14975 }
14976
14977 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
14978 const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
14979 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
14980 const Loop *L = LoopAndValue.first;
14981 const SCEV *Value = LoopAndValue.second;
14983 auto It = ValuesAtScopes.find(Value);
14984 if (It != ValuesAtScopes.end() &&
14985 is_contained(It->second, std::make_pair(L, ValueAtScope)))
14986 continue;
14987 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14988 << *ValueAtScope << " missing in ValuesAtScopes\n";
14989 std::abort();
14990 }
14991 }
14992
14993 // Verify integrity of BECountUsers.
14994 auto VerifyBECountUsers = [&](bool Predicated) {
14995 auto &BECounts =
14996 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14997 for (const auto &LoopAndBEInfo : BECounts) {
14998 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
14999 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
15000 if (!isa<SCEVConstant>(S)) {
15001 auto UserIt = BECountUsers.find(S);
15002 if (UserIt != BECountUsers.end() &&
15003 UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
15004 continue;
15005 dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
15006 << " missing from BECountUsers\n";
15007 std::abort();
15008 }
15009 }
15010 }
15011 }
15012 };
15013 VerifyBECountUsers(/* Predicated */ false);
15014 VerifyBECountUsers(/* Predicated */ true);
15015
15016 // Verify intergity of loop disposition cache.
15017 for (auto &[S, Values] : LoopDispositions) {
15018 for (auto [Loop, CachedDisposition] : Values) {
15019 const auto RecomputedDisposition = SE2.getLoopDisposition(S, Loop);
15020 if (CachedDisposition != RecomputedDisposition) {
15021 dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
15022 << " is incorrect: cached " << CachedDisposition << ", actual "
15023 << RecomputedDisposition << "\n";
15024 std::abort();
15025 }
15026 }
15027 }
15028
15029 // Verify integrity of the block disposition cache.
15030 for (auto &[S, Values] : BlockDispositions) {
15031 for (auto [BB, CachedDisposition] : Values) {
15032 const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
15033 if (CachedDisposition != RecomputedDisposition) {
15034 dbgs() << "Cached disposition of " << *S << " for block %"
15035 << BB->getName() << " is incorrect: cached " << CachedDisposition
15036 << ", actual " << RecomputedDisposition << "\n";
15037 std::abort();
15038 }
15039 }
15040 }
15041
15042 // Verify FoldCache/FoldCacheUser caches.
15043 for (auto [FoldID, Expr] : FoldCache) {
15044 auto I = FoldCacheUser.find(Expr);
15045 if (I == FoldCacheUser.end()) {
15046 dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
15047 << "!\n";
15048 std::abort();
15049 }
15050 if (!is_contained(I->second, FoldID)) {
15051 dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
15052 std::abort();
15053 }
15054 }
15055 for (auto [Expr, IDs] : FoldCacheUser) {
15056 for (auto &FoldID : IDs) {
15057 const SCEV *S = FoldCache.lookup(FoldID);
15058 if (!S) {
15059 dbgs() << "Missing entry in FoldCache for expression " << *Expr
15060 << "!\n";
15061 std::abort();
15062 }
15063 if (S != Expr) {
15064 dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: " << *S
15065 << " != " << *Expr << "!\n";
15066 std::abort();
15067 }
15068 }
15069 }
15070
15071 // Verify that ConstantMultipleCache computations are correct. We check that
15072 // cached multiples and recomputed multiples are multiples of each other to
15073 // verify correctness. It is possible that a recomputed multiple is different
15074 // from the cached multiple due to strengthened no wrap flags or changes in
15075 // KnownBits computations.
15076 for (auto [S, Multiple] : ConstantMultipleCache) {
15077 APInt RecomputedMultiple = SE2.getConstantMultiple(S);
15078 if ((Multiple != 0 && RecomputedMultiple != 0 &&
15079 Multiple.urem(RecomputedMultiple) != 0 &&
15080 RecomputedMultiple.urem(Multiple) != 0)) {
15081 dbgs() << "Incorrect cached computation in ConstantMultipleCache for "
15082 << *S << " : Computed " << RecomputedMultiple
15083 << " but cache contains " << Multiple << "!\n";
15084 std::abort();
15085 }
15086 }
15087}
15088
15090 Function &F, const PreservedAnalyses &PA,
15091 FunctionAnalysisManager::Invalidator &Inv) {
15092 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
15093 // of its dependencies is invalidated.
15094 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
15095 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
15096 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
15097 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
15098 Inv.invalidate<LoopAnalysis>(F, PA);
15099}
15100
15101AnalysisKey ScalarEvolutionAnalysis::Key;
15102
15105 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
15106 auto &AC = AM.getResult<AssumptionAnalysis>(F);
15107 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
15108 auto &LI = AM.getResult<LoopAnalysis>(F);
15109 return ScalarEvolution(F, TLI, AC, DT, LI);
15110}
15111
15117
15120 // For compatibility with opt's -analyze feature under legacy pass manager
15121 // which was not ported to NPM. This keeps tests using
15122 // update_analyze_test_checks.py working.
15123 OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
15124 << F.getName() << "':\n";
15126 return PreservedAnalyses::all();
15127}
15128
15130 "Scalar Evolution Analysis", false, true)
15136 "Scalar Evolution Analysis", false, true)
15137
15138char ScalarEvolutionWrapperPass::ID = 0;
15139
15141
15143 SE.reset(new ScalarEvolution(
15145 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
15147 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
15148 return false;
15149}
15150
15152
15154 SE->print(OS);
15155}
15156
15158 if (!VerifySCEV)
15159 return;
15160
15161 SE->verify();
15162}
15163
15171
15173 const SCEV *RHS) {
15174 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
15175}
15176
15177const SCEVPredicate *
15179 const SCEV *LHS, const SCEV *RHS) {
15181 assert(LHS->getType() == RHS->getType() &&
15182 "Type mismatch between LHS and RHS");
15183 // Unique this node based on the arguments
15184 ID.AddInteger(SCEVPredicate::P_Compare);
15185 ID.AddInteger(Pred);
15186 ID.AddPointer(LHS);
15187 ID.AddPointer(RHS);
15188 void *IP = nullptr;
15189 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
15190 return S;
15191 SCEVComparePredicate *Eq = new (SCEVAllocator)
15192 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
15193 UniquePreds.InsertNode(Eq, IP);
15194 return Eq;
15195}
15196
15198 const SCEVAddRecExpr *AR,
15201 // Unique this node based on the arguments
15203 ID.AddPointer(AR);
15204 ID.AddInteger(AddedFlags);
15205 void *IP = nullptr;
15206 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
15207 return S;
15208 auto *OF = new (SCEVAllocator)
15209 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
15210 UniquePreds.InsertNode(OF, IP);
15211 return OF;
15212}
15213
15214namespace {
15215
15216class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
15217public:
15218
15219 /// Rewrites \p S in the context of a loop L and the SCEV predication
15220 /// infrastructure.
15221 ///
15222 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
15223 /// equivalences present in \p Pred.
15224 ///
15225 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
15226 /// \p NewPreds such that the result will be an AddRecExpr.
15227 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
15229 const SCEVPredicate *Pred) {
15230 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
15231 return Rewriter.visit(S);
15232 }
15233
15234 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
15235 if (Pred) {
15236 if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
15237 for (const auto *Pred : U->getPredicates())
15238 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
15239 if (IPred->getLHS() == Expr &&
15240 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15241 return IPred->getRHS();
15242 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
15243 if (IPred->getLHS() == Expr &&
15244 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15245 return IPred->getRHS();
15246 }
15247 }
15248 return convertToAddRecWithPreds(Expr);
15249 }
15250
15251 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
15252 const SCEV *Operand = visit(Expr->getOperand());
15253 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15254 if (AR && AR->getLoop() == L && AR->isAffine()) {
15255 // This couldn't be folded because the operand didn't have the nuw
15256 // flag. Add the nusw flag as an assumption that we could make.
15257 const SCEV *Step = AR->getStepRecurrence(SE);
15258 Type *Ty = Expr->getType();
15259 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
15260 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
15261 SE.getSignExtendExpr(Step, Ty), L,
15262 AR->getNoWrapFlags());
15263 }
15264 return SE.getZeroExtendExpr(Operand, Expr->getType());
15265 }
15266
15267 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
15268 const SCEV *Operand = visit(Expr->getOperand());
15269 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15270 if (AR && AR->getLoop() == L && AR->isAffine()) {
15271 // This couldn't be folded because the operand didn't have the nsw
15272 // flag. Add the nssw flag as an assumption that we could make.
15273 const SCEV *Step = AR->getStepRecurrence(SE);
15274 Type *Ty = Expr->getType();
15275 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
15276 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
15277 SE.getSignExtendExpr(Step, Ty), L,
15278 AR->getNoWrapFlags());
15279 }
15280 return SE.getSignExtendExpr(Operand, Expr->getType());
15281 }
15282
15283private:
15284 explicit SCEVPredicateRewriter(
15285 const Loop *L, ScalarEvolution &SE,
15286 SmallVectorImpl<const SCEVPredicate *> *NewPreds,
15287 const SCEVPredicate *Pred)
15288 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
15289
15290 bool addOverflowAssumption(const SCEVPredicate *P) {
15291 if (!NewPreds) {
15292 // Check if we've already made this assumption.
15293 return Pred && Pred->implies(P, SE);
15294 }
15295 NewPreds->push_back(P);
15296 return true;
15297 }
15298
15299 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
15301 auto *A = SE.getWrapPredicate(AR, AddedFlags);
15302 return addOverflowAssumption(A);
15303 }
15304
15305 // If \p Expr represents a PHINode, we try to see if it can be represented
15306 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
15307 // to add this predicate as a runtime overflow check, we return the AddRec.
15308 // If \p Expr does not meet these conditions (is not a PHI node, or we
15309 // couldn't create an AddRec for it, or couldn't add the predicate), we just
15310 // return \p Expr.
15311 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
15312 if (!isa<PHINode>(Expr->getValue()))
15313 return Expr;
15314 std::optional<
15315 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
15316 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
15317 if (!PredicatedRewrite)
15318 return Expr;
15319 for (const auto *P : PredicatedRewrite->second){
15320 // Wrap predicates from outer loops are not supported.
15321 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
15322 if (L != WP->getExpr()->getLoop())
15323 return Expr;
15324 }
15325 if (!addOverflowAssumption(P))
15326 return Expr;
15327 }
15328 return PredicatedRewrite->first;
15329 }
15330
15331 SmallVectorImpl<const SCEVPredicate *> *NewPreds;
15332 const SCEVPredicate *Pred;
15333 const Loop *L;
15334};
15335
15336} // end anonymous namespace
15337
15338const SCEV *
15340 const SCEVPredicate &Preds) {
15341 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
15342}
15343
15345 const SCEV *S, const Loop *L,
15348 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
15349 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
15350
15351 if (!AddRec)
15352 return nullptr;
15353
15354 // Check if any of the transformed predicates is known to be false. In that
15355 // case, it doesn't make sense to convert to a predicated AddRec, as the
15356 // versioned loop will never execute.
15357 for (const SCEVPredicate *Pred : TransformPreds) {
15358 auto *WrapPred = dyn_cast<SCEVWrapPredicate>(Pred);
15359 if (!WrapPred || WrapPred->getFlags() != SCEVWrapPredicate::IncrementNSSW)
15360 continue;
15361
15362 const SCEVAddRecExpr *AddRecToCheck = WrapPred->getExpr();
15363 const SCEV *ExitCount = getBackedgeTakenCount(AddRecToCheck->getLoop());
15364 if (isa<SCEVCouldNotCompute>(ExitCount))
15365 continue;
15366
15367 const SCEV *Step = AddRecToCheck->getStepRecurrence(*this);
15368 if (!Step->isOne())
15369 continue;
15370
15371 ExitCount = getTruncateOrSignExtend(ExitCount, Step->getType());
15372 const SCEV *Add = getAddExpr(AddRecToCheck->getStart(), ExitCount);
15373 if (isKnownPredicate(CmpInst::ICMP_SLT, Add, AddRecToCheck->getStart()))
15374 return nullptr;
15375 }
15376
15377 // Since the transformation was successful, we can now transfer the SCEV
15378 // predicates.
15379 Preds.append(TransformPreds.begin(), TransformPreds.end());
15380
15381 return AddRec;
15382}
15383
15384/// SCEV predicates
15388
15390 const ICmpInst::Predicate Pred,
15391 const SCEV *LHS, const SCEV *RHS)
15392 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
15393 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
15394 assert(LHS != RHS && "LHS and RHS are the same SCEV");
15395}
15396
15398 ScalarEvolution &SE) const {
15399 const auto *Op = dyn_cast<SCEVComparePredicate>(N);
15400
15401 if (!Op)
15402 return false;
15403
15404 if (Pred != ICmpInst::ICMP_EQ)
15405 return false;
15406
15407 return Op->LHS == LHS && Op->RHS == RHS;
15408}
15409
15410bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
15411
15413 if (Pred == ICmpInst::ICMP_EQ)
15414 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
15415 else
15416 OS.indent(Depth) << "Compare predicate: " << *LHS << " " << Pred << ") "
15417 << *RHS << "\n";
15418
15419}
15420
15422 const SCEVAddRecExpr *AR,
15423 IncrementWrapFlags Flags)
15424 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
15425
15426const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
15427
15429 ScalarEvolution &SE) const {
15430 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
15431 if (!Op || setFlags(Flags, Op->Flags) != Flags)
15432 return false;
15433
15434 if (Op->AR == AR)
15435 return true;
15436
15437 if (Flags != SCEVWrapPredicate::IncrementNSSW &&
15439 return false;
15440
15441 const SCEV *Start = AR->getStart();
15442 const SCEV *OpStart = Op->AR->getStart();
15443 if (Start->getType()->isPointerTy() != OpStart->getType()->isPointerTy())
15444 return false;
15445
15446 // Reject pointers to different address spaces.
15447 if (Start->getType()->isPointerTy() && Start->getType() != OpStart->getType())
15448 return false;
15449
15450 // NUSW/NSSW on a wider-type AddRec does not imply the same on a
15451 // narrower-type AddRec.
15452 if (SE.getTypeSizeInBits(AR->getType()) >
15453 SE.getTypeSizeInBits(Op->AR->getType()))
15454 return false;
15455
15456 const SCEV *Step = AR->getStepRecurrence(SE);
15457 const SCEV *OpStep = Op->AR->getStepRecurrence(SE);
15458 if (!SE.isKnownPositive(Step) || !SE.isKnownPositive(OpStep))
15459 return false;
15460
15461 // If both steps are positive, this implies N, if N's start and step are
15462 // ULE/SLE (for NSUW/NSSW) than this'.
15463 Type *WiderTy = SE.getWiderType(Step->getType(), OpStep->getType());
15464 Step = SE.getNoopOrZeroExtend(Step, WiderTy);
15465 OpStep = SE.getNoopOrZeroExtend(OpStep, WiderTy);
15466
15467 bool IsNUW = Flags == SCEVWrapPredicate::IncrementNUSW;
15468 OpStart = IsNUW ? SE.getNoopOrZeroExtend(OpStart, WiderTy)
15469 : SE.getNoopOrSignExtend(OpStart, WiderTy);
15470 Start = IsNUW ? SE.getNoopOrZeroExtend(Start, WiderTy)
15471 : SE.getNoopOrSignExtend(Start, WiderTy);
15473 return SE.isKnownPredicate(Pred, OpStep, Step) &&
15474 SE.isKnownPredicate(Pred, OpStart, Start);
15475}
15476
15478 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
15479 IncrementWrapFlags IFlags = Flags;
15480
15481 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
15482 IFlags = clearFlags(IFlags, IncrementNSSW);
15483
15484 return IFlags == IncrementAnyWrap;
15485}
15486
15487void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
15488 OS.indent(Depth) << *getExpr() << " Added Flags: ";
15490 OS << "<nusw>";
15492 OS << "<nssw>";
15493 OS << "\n";
15494}
15495
15498 ScalarEvolution &SE) {
15499 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
15500 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
15501
15502 // We can safely transfer the NSW flag as NSSW.
15503 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
15504 ImpliedFlags = IncrementNSSW;
15505
15506 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
15507 // If the increment is positive, the SCEV NUW flag will also imply the
15508 // WrapPredicate NUSW flag.
15509 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
15510 if (Step->getValue()->getValue().isNonNegative())
15511 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
15512 }
15513
15514 return ImpliedFlags;
15515}
15516
15517/// Union predicates don't get cached so create a dummy set ID for it.
15519 ScalarEvolution &SE)
15520 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {
15521 for (const auto *P : Preds)
15522 add(P, SE);
15523}
15524
15526 return all_of(Preds,
15527 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
15528}
15529
15531 ScalarEvolution &SE) const {
15532 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
15533 return all_of(Set->Preds, [this, &SE](const SCEVPredicate *I) {
15534 return this->implies(I, SE);
15535 });
15536
15537 if (any_of(Preds,
15538 [N, &SE](const SCEVPredicate *I) { return I->implies(N, SE); }))
15539 return true;
15540
15541 // A wrap predicate may be implied by a wrap predicate in Preds after applying
15542 // equal predicates.
15543 const auto *NWrap = dyn_cast<SCEVWrapPredicate>(N);
15544 if (!NWrap)
15545 return false;
15546 const Loop *L = NWrap->getExpr()->getLoop();
15547 return any_of(Preds, [&](const SCEVPredicate *I) {
15548 const auto *IWrap = dyn_cast<SCEVWrapPredicate>(I);
15549 if (!IWrap)
15550 return false;
15551 const auto *RewrittenAR = dyn_cast<SCEVAddRecExpr>(
15552 SE.rewriteUsingPredicate(IWrap->getExpr(), L, *this));
15553 return RewrittenAR &&
15554 SE.getWrapPredicate(RewrittenAR, IWrap->getFlags())->implies(N, SE);
15555 });
15556}
15557
15559 for (const auto *Pred : Preds)
15560 Pred->print(OS, Depth);
15561}
15562
15563void SCEVUnionPredicate::add(const SCEVPredicate *N, ScalarEvolution &SE) {
15564 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
15565 for (const auto *Pred : Set->Preds)
15566 add(Pred, SE);
15567 return;
15568 }
15569
15570 // Implication checks are quadratic in the number of predicates. Stop doing
15571 // them if there are many predicates, as they should be too expensive to use
15572 // anyway at that point.
15573 bool CheckImplies = Preds.size() < 16;
15574
15575 // Only add predicate if it is not already implied by this union predicate.
15576 if (CheckImplies && implies(N, SE))
15577 return;
15578
15579 // Build a new vector containing the current predicates, except the ones that
15580 // are implied by the new predicate N.
15582 for (auto *P : Preds) {
15583 if (CheckImplies && N->implies(P, SE))
15584 continue;
15585 PrunedPreds.push_back(P);
15586 }
15587 Preds = std::move(PrunedPreds);
15588 Preds.push_back(N);
15589}
15590
15592 Loop &L)
15593 : SE(SE), L(L) {
15595 Preds = std::make_unique<SCEVUnionPredicate>(Empty, SE);
15596}
15597
15600 for (const auto *Op : Ops)
15601 // We do not expect that forgetting cached data for SCEVConstants will ever
15602 // open any prospects for sharpening or introduce any correctness issues,
15603 // so we don't bother storing their dependencies.
15604 if (!isa<SCEVConstant>(Op))
15605 SCEVUsers[Op].insert(User);
15606}
15607
15609 for (const SCEV *Op : Ops)
15610 // We do not expect that forgetting cached data for SCEVConstants will ever
15611 // open any prospects for sharpening or introduce any correctness issues,
15612 // so we don't bother storing their dependencies.
15613 if (!isa<SCEVConstant>(Op))
15614 SCEVUsers[Op].insert(User);
15615}
15616
15618 const SCEV *Expr = SE.getSCEV(V);
15619 return getPredicatedSCEV(Expr);
15620}
15621
15623 RewriteEntry &Entry = RewriteMap[Expr];
15624
15625 // If we already have an entry and the version matches, return it.
15626 if (Entry.second && Generation == Entry.first)
15627 return Entry.second;
15628
15629 // We found an entry but it's stale. Rewrite the stale entry
15630 // according to the current predicate.
15631 if (Entry.second)
15632 Expr = Entry.second;
15633
15634 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
15635 Entry = {Generation, NewSCEV};
15636
15637 return NewSCEV;
15638}
15639
15641 if (!BackedgeCount) {
15643 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
15644 for (const auto *P : Preds)
15645 addPredicate(*P);
15646 }
15647 return BackedgeCount;
15648}
15649
15651 if (!SymbolicMaxBackedgeCount) {
15653 SymbolicMaxBackedgeCount =
15654 SE.getPredicatedSymbolicMaxBackedgeTakenCount(&L, Preds);
15655 for (const auto *P : Preds)
15656 addPredicate(*P);
15657 }
15658 return SymbolicMaxBackedgeCount;
15659}
15660
15662 if (!SmallConstantMaxTripCount) {
15664 SmallConstantMaxTripCount = SE.getSmallConstantMaxTripCount(&L, &Preds);
15665 for (const auto *P : Preds)
15666 addPredicate(*P);
15667 }
15668 return *SmallConstantMaxTripCount;
15669}
15670
15672 if (Preds->implies(&Pred, SE))
15673 return;
15674
15675 SmallVector<const SCEVPredicate *, 4> NewPreds(Preds->getPredicates());
15676 NewPreds.push_back(&Pred);
15677 Preds = std::make_unique<SCEVUnionPredicate>(NewPreds, SE);
15678 updateGeneration();
15679}
15680
15683 for (const SCEVPredicate *P : Preds)
15684 addPredicate(*P);
15685}
15686
15688 return *Preds;
15689}
15690
15691void PredicatedScalarEvolution::updateGeneration() {
15692 // If the generation number wrapped recompute everything.
15693 if (++Generation == 0) {
15694 for (auto &II : RewriteMap) {
15695 const SCEV *Rewritten = II.second.second;
15696 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
15697 }
15698 }
15699}
15700
15703 const auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V));
15704 if (!AR)
15705 return false;
15706
15708 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
15709
15711}
15712
15715 const SCEV *Expr = this->getSCEV(V);
15717 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
15718
15719 if (!New)
15720 return nullptr;
15721
15722 if (ExtraPreds) {
15723 ExtraPreds->append(NewPreds);
15724 return New;
15725 }
15726
15727 addPredicates(NewPreds);
15728
15729 RewriteMap[SE.getSCEV(V)] = {Generation, New};
15730 return New;
15731}
15732
15735 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
15736 Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates(),
15737 SE)),
15738 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {}
15739
15741 // For each block.
15742 for (auto *BB : L.getBlocks())
15743 for (auto &I : *BB) {
15744 if (!SE.isSCEVable(I.getType()))
15745 continue;
15746
15747 auto *Expr = SE.getSCEV(&I);
15748 auto II = RewriteMap.find(Expr);
15749
15750 if (II == RewriteMap.end())
15751 continue;
15752
15753 // Don't print things that are not interesting.
15754 if (II->second.second == Expr)
15755 continue;
15756
15757 OS.indent(Depth) << "[PSE]" << I << ":\n";
15758 OS.indent(Depth + 2) << *Expr << "\n";
15759 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
15760 }
15761}
15762
15765 BasicBlock *Header = L->getHeader();
15766 BasicBlock *Pred = L->getLoopPredecessor();
15767 LoopGuards Guards(SE);
15768 if (!Pred)
15769 return Guards;
15771 collectFromBlock(SE, Guards, Header, Pred, VisitedBlocks);
15772 return Guards;
15773}
15774
15775void ScalarEvolution::LoopGuards::collectFromPHI(
15779 unsigned Depth) {
15780 if (!SE.isSCEVable(Phi.getType()))
15781 return;
15782
15783 using MinMaxPattern = std::pair<const SCEVConstant *, SCEVTypes>;
15784 auto GetMinMaxConst = [&](unsigned IncomingIdx) -> MinMaxPattern {
15785 const BasicBlock *InBlock = Phi.getIncomingBlock(IncomingIdx);
15786 if (!VisitedBlocks.insert(InBlock).second)
15787 return {nullptr, scCouldNotCompute};
15788
15789 // Avoid analyzing unreachable blocks so that we don't get trapped
15790 // traversing cycles with ill-formed dominance or infinite cycles
15791 if (!SE.DT.isReachableFromEntry(InBlock))
15792 return {nullptr, scCouldNotCompute};
15793
15794 auto [G, Inserted] = IncomingGuards.try_emplace(InBlock, LoopGuards(SE));
15795 if (Inserted)
15796 collectFromBlock(SE, G->second, Phi.getParent(), InBlock, VisitedBlocks,
15797 Depth + 1);
15798 auto &RewriteMap = G->second.RewriteMap;
15799 if (RewriteMap.empty())
15800 return {nullptr, scCouldNotCompute};
15801 auto S = RewriteMap.find(SE.getSCEV(Phi.getIncomingValue(IncomingIdx)));
15802 if (S == RewriteMap.end())
15803 return {nullptr, scCouldNotCompute};
15804 auto *SM = dyn_cast_if_present<SCEVMinMaxExpr>(S->second);
15805 if (!SM)
15806 return {nullptr, scCouldNotCompute};
15807 if (const SCEVConstant *C0 = dyn_cast<SCEVConstant>(SM->getOperand(0)))
15808 return {C0, SM->getSCEVType()};
15809 return {nullptr, scCouldNotCompute};
15810 };
15811 auto MergeMinMaxConst = [](MinMaxPattern P1,
15812 MinMaxPattern P2) -> MinMaxPattern {
15813 auto [C1, T1] = P1;
15814 auto [C2, T2] = P2;
15815 if (!C1 || !C2 || T1 != T2)
15816 return {nullptr, scCouldNotCompute};
15817 switch (T1) {
15818 case scUMaxExpr:
15819 return {C1->getAPInt().ult(C2->getAPInt()) ? C1 : C2, T1};
15820 case scSMaxExpr:
15821 return {C1->getAPInt().slt(C2->getAPInt()) ? C1 : C2, T1};
15822 case scUMinExpr:
15823 return {C1->getAPInt().ugt(C2->getAPInt()) ? C1 : C2, T1};
15824 case scSMinExpr:
15825 return {C1->getAPInt().sgt(C2->getAPInt()) ? C1 : C2, T1};
15826 default:
15827 llvm_unreachable("Trying to merge non-MinMaxExpr SCEVs.");
15828 }
15829 };
15830 auto P = GetMinMaxConst(0);
15831 for (unsigned int In = 1; In < Phi.getNumIncomingValues(); In++) {
15832 if (!P.first)
15833 break;
15834 P = MergeMinMaxConst(P, GetMinMaxConst(In));
15835 }
15836 if (P.first) {
15837 const SCEV *LHS = SE.getSCEV(const_cast<PHINode *>(&Phi));
15838 SmallVector<SCEVUse, 2> Ops({P.first, LHS});
15839 const SCEV *RHS = SE.getMinMaxExpr(P.second, Ops);
15840 Guards.RewriteMap.insert({LHS, RHS});
15841 }
15842}
15843
15844// Return a new SCEV that modifies \p Expr to the closest number divides by
15845// \p Divisor and less or equal than Expr. For now, only handle constant
15846// Expr.
15848 const APInt &DivisorVal,
15849 ScalarEvolution &SE) {
15850 const APInt *ExprVal;
15851 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15852 DivisorVal.isNonPositive())
15853 return Expr;
15854 APInt Rem = ExprVal->urem(DivisorVal);
15855 // return the SCEV: Expr - Expr % Divisor
15856 return SE.getConstant(*ExprVal - Rem);
15857}
15858
15859// Return a new SCEV that modifies \p Expr to the closest number divides by
15860// \p Divisor and greater or equal than Expr. For now, only handle constant
15861// Expr.
15862static const SCEV *getNextSCEVDivisibleByDivisor(const SCEV *Expr,
15863 const APInt &DivisorVal,
15864 ScalarEvolution &SE) {
15865 const APInt *ExprVal;
15866 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15867 DivisorVal.isNonPositive())
15868 return Expr;
15869 APInt Rem = ExprVal->urem(DivisorVal);
15870 if (Rem.isZero())
15871 return Expr;
15872 // return the SCEV: Expr + Divisor - Expr % Divisor
15873 return SE.getConstant(*ExprVal + DivisorVal - Rem);
15874}
15875
15877 ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS,
15880 // If we have LHS == 0, check if LHS is computing a property of some unknown
15881 // SCEV %v which we can rewrite %v to express explicitly.
15883 return false;
15884 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
15885 // explicitly express that.
15886 const SCEVUnknown *URemLHS = nullptr;
15887 const SCEV *URemRHS = nullptr;
15888 if (!match(LHS, m_scev_URem(m_SCEVUnknown(URemLHS), m_SCEV(URemRHS), SE)))
15889 return false;
15890
15891 const SCEV *Multiple =
15892 SE.getMulExpr(SE.getUDivExpr(URemLHS, URemRHS), URemRHS);
15893 DivInfo[URemLHS] = Multiple;
15894 if (auto *C = dyn_cast<SCEVConstant>(URemRHS))
15895 Multiples[URemLHS] = C->getAPInt();
15896 return true;
15897}
15898
15899// Check if the condition is a divisibility guard (A % B == 0).
15900static bool isDivisibilityGuard(const SCEV *LHS, const SCEV *RHS,
15901 ScalarEvolution &SE) {
15902 const SCEV *X, *Y;
15903 return match(LHS, m_scev_URem(m_SCEV(X), m_SCEV(Y), SE)) && RHS->isZero();
15904}
15905
15906// Apply divisibility by \p Divisor on MinMaxExpr with constant values,
15907// recursively. This is done by aligning up/down the constant value to the
15908// Divisor.
15909static const SCEV *applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr,
15910 APInt Divisor,
15911 ScalarEvolution &SE) {
15912 // Return true if \p Expr is a MinMax SCEV expression with a non-negative
15913 // constant operand. If so, return in \p SCTy the SCEV type and in \p RHS
15914 // the non-constant operand and in \p LHS the constant operand.
15915 auto IsMinMaxSCEVWithNonNegativeConstant =
15916 [&](const SCEV *Expr, SCEVTypes &SCTy, const SCEV *&LHS,
15917 const SCEV *&RHS) {
15918 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr)) {
15919 if (MinMax->getNumOperands() != 2)
15920 return false;
15921 if (auto *C = dyn_cast<SCEVConstant>(MinMax->getOperand(0))) {
15922 if (C->getAPInt().isNegative())
15923 return false;
15924 SCTy = MinMax->getSCEVType();
15925 LHS = MinMax->getOperand(0);
15926 RHS = MinMax->getOperand(1);
15927 return true;
15928 }
15929 }
15930 return false;
15931 };
15932
15933 const SCEV *MinMaxLHS = nullptr, *MinMaxRHS = nullptr;
15934 SCEVTypes SCTy;
15935 if (!IsMinMaxSCEVWithNonNegativeConstant(MinMaxExpr, SCTy, MinMaxLHS,
15936 MinMaxRHS))
15937 return MinMaxExpr;
15938 auto IsMin = isa<SCEVSMinExpr>(MinMaxExpr) || isa<SCEVUMinExpr>(MinMaxExpr);
15939 assert(SE.isKnownNonNegative(MinMaxLHS) && "Expected non-negative operand!");
15940 auto *DivisibleExpr =
15941 IsMin ? getPreviousSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE)
15942 : getNextSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE);
15944 applyDivisibilityOnMinMaxExpr(MinMaxRHS, Divisor, SE), DivisibleExpr};
15945 return SE.getMinMaxExpr(SCTy, Ops);
15946}
15947
15948void ScalarEvolution::LoopGuards::collectFromBlock(
15949 ScalarEvolution &SE, ScalarEvolution::LoopGuards &Guards,
15950 const BasicBlock *Block, const BasicBlock *Pred,
15951 SmallPtrSetImpl<const BasicBlock *> &VisitedBlocks, unsigned Depth) {
15952
15954
15955 SmallVector<SCEVUse> ExprsToRewrite;
15956 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
15957 const SCEV *RHS,
15958 DenseMap<const SCEV *, const SCEV *> &RewriteMap,
15959 const LoopGuards &DivGuards) {
15960 // WARNING: It is generally unsound to apply any wrap flags to the proposed
15961 // replacement SCEV which isn't directly implied by the structure of that
15962 // SCEV. In particular, using contextual facts to imply flags is *NOT*
15963 // legal. See the scoping rules for flags in the header to understand why.
15964
15965 // Puts rewrite rule \p From -> \p To into the rewrite map. Also if \p From
15966 // and \p FromRewritten are the same (i.e. there has been no rewrite
15967 // registered for \p From), then puts this value in the list of rewritten
15968 // expressions.
15969 auto AddRewrite = [&](const SCEV *From, const SCEV *FromRewritten,
15970 const SCEV *To) {
15971 if (From == FromRewritten)
15972 ExprsToRewrite.push_back(From);
15973 RewriteMap[From] = To;
15974 };
15975
15976 // Checks whether \p S has already been rewritten. In that case returns the
15977 // existing rewrite because we want to chain further rewrites onto the
15978 // already rewritten value. Otherwise returns \p S.
15979 auto GetMaybeRewritten = [&](const SCEV *S) {
15980 return RewriteMap.lookup_or(S, S);
15981 };
15982
15983 // Check for a condition of the form (-C1 + X < C2). InstCombine will
15984 // create this form when combining two checks of the form (X u< C2 + C1) and
15985 // (X >=u C1).
15986 auto MatchRangeCheckIdiom = [&](ICmpInst::Predicate Pred,
15987 const SCEV *MatchLHS,
15988 const SCEV *MatchRHS) {
15989 const SCEVConstant *C1;
15990 const SCEVUnknown *LHSUnknown;
15991 auto *C2 = dyn_cast<SCEVConstant>(MatchRHS);
15992 if (!match(MatchLHS,
15993 m_scev_Add(m_SCEVConstant(C1), m_SCEVUnknown(LHSUnknown))) ||
15994 !C2)
15995 return false;
15996
15997 auto ExactRegion =
15998 ConstantRange::makeExactICmpRegion(Pred, C2->getAPInt())
15999 .sub(C1->getAPInt());
16000
16001 // Tighten the raw range with what we already know about LHSUnknown
16002 // from prior guards recorded in RewriteMap, or from SCEV's own range
16003 // analysis.
16004 const SCEV *RewrittenLHS = GetMaybeRewritten(LHSUnknown);
16005 ExactRegion = ExactRegion.intersectWith(SE.getUnsignedRange(RewrittenLHS),
16007
16008 // Bail if the guard is inconsistent with prior facts, or if the range
16009 // is still not a monotonic non-wrapping interval after tightening.
16010 if (ExactRegion.isEmptySet() || ExactRegion.isWrappedSet() ||
16011 ExactRegion.isFullSet())
16012 return false;
16013
16014 const SCEV *RegionMin = SE.getConstant(ExactRegion.getUnsignedMin());
16015 const SCEV *RegionMax = SE.getConstant(ExactRegion.getUnsignedMax());
16016 const SCEV *ClampedLHS =
16017 SE.getUMaxExpr(RegionMin, SE.getUMinExpr(RewrittenLHS, RegionMax));
16018 AddRewrite(LHSUnknown, RewrittenLHS, ClampedLHS);
16019 return true;
16020 };
16021 if (MatchRangeCheckIdiom(Predicate, LHS, RHS))
16022 return;
16023
16024 // Do not apply information for constants or if RHS contains an AddRec.
16026 return;
16027
16028 // If RHS is SCEVUnknown, make sure the information is applied to it.
16030 std::swap(LHS, RHS);
16032 }
16033
16034 const SCEV *RewrittenLHS = GetMaybeRewritten(LHS);
16035 // Apply divisibility information when computing the constant multiple.
16036 const APInt &DividesBy =
16037 SE.getConstantMultiple(DivGuards.rewrite(RewrittenLHS));
16038
16039 // Collect rewrites for LHS and its transitive operands based on the
16040 // condition.
16041 // For min/max expressions, also apply the guard to its operands:
16042 // 'min(a, b) >= c' -> '(a >= c) and (b >= c)',
16043 // 'min(a, b) > c' -> '(a > c) and (b > c)',
16044 // 'max(a, b) <= c' -> '(a <= c) and (b <= c)',
16045 // 'max(a, b) < c' -> '(a < c) and (b < c)'.
16046
16047 // We cannot express strict predicates in SCEV, so instead we replace them
16048 // with non-strict ones against plus or minus one of RHS depending on the
16049 // predicate.
16050 const SCEV *One = SE.getOne(RHS->getType());
16051 switch (Predicate) {
16052 case CmpInst::ICMP_ULT:
16053 if (RHS->getType()->isPointerTy())
16054 return;
16055 RHS = SE.getUMaxExpr(RHS, One);
16056 [[fallthrough]];
16057 case CmpInst::ICMP_SLT: {
16058 RHS = SE.getMinusSCEV(RHS, One);
16059 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16060 break;
16061 }
16062 case CmpInst::ICMP_UGT:
16063 case CmpInst::ICMP_SGT:
16064 RHS = SE.getAddExpr(RHS, One);
16065 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16066 break;
16067 case CmpInst::ICMP_ULE:
16068 case CmpInst::ICMP_SLE:
16069 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16070 break;
16071 case CmpInst::ICMP_UGE:
16072 case CmpInst::ICMP_SGE:
16073 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16074 break;
16075 default:
16076 break;
16077 }
16078
16079 SmallVector<SCEVUse, 16> Worklist(1, LHS);
16080 SmallPtrSet<const SCEV *, 16> Visited;
16081
16082 auto EnqueueOperands = [&Worklist](const SCEVNAryExpr *S) {
16083 append_range(Worklist, S->operands());
16084 };
16085
16086 while (!Worklist.empty()) {
16087 const SCEV *From = Worklist.pop_back_val();
16088 if (isa<SCEVConstant>(From))
16089 continue;
16090 if (!Visited.insert(From).second)
16091 continue;
16092 const SCEV *FromRewritten = GetMaybeRewritten(From);
16093 const SCEV *To = nullptr;
16094
16095 switch (Predicate) {
16096 case CmpInst::ICMP_ULT:
16097 case CmpInst::ICMP_ULE:
16098 To = SE.getUMinExpr(FromRewritten, RHS);
16099 if (auto *UMax = dyn_cast<SCEVUMaxExpr>(FromRewritten))
16100 EnqueueOperands(UMax);
16101 break;
16102 case CmpInst::ICMP_SLT:
16103 case CmpInst::ICMP_SLE:
16104 To = SE.getSMinExpr(FromRewritten, RHS);
16105 if (auto *SMax = dyn_cast<SCEVSMaxExpr>(FromRewritten))
16106 EnqueueOperands(SMax);
16107 break;
16108 case CmpInst::ICMP_UGT:
16109 case CmpInst::ICMP_UGE:
16110 To = SE.getUMaxExpr(FromRewritten, RHS);
16111 if (auto *UMin = dyn_cast<SCEVUMinExpr>(FromRewritten))
16112 EnqueueOperands(UMin);
16113 break;
16114 case CmpInst::ICMP_SGT:
16115 case CmpInst::ICMP_SGE:
16116 To = SE.getSMaxExpr(FromRewritten, RHS);
16117 if (auto *SMin = dyn_cast<SCEVSMinExpr>(FromRewritten))
16118 EnqueueOperands(SMin);
16119 break;
16120 case CmpInst::ICMP_EQ:
16122 To = RHS;
16123 break;
16124 case CmpInst::ICMP_NE:
16125 if (match(RHS, m_scev_Zero())) {
16126 const SCEV *OneAlignedUp =
16127 getNextSCEVDivisibleByDivisor(One, DividesBy, SE);
16128 To = SE.getUMaxExpr(FromRewritten, OneAlignedUp);
16129 } else {
16130 // LHS != RHS can be rewritten as (LHS - RHS) = UMax(1, LHS - RHS),
16131 // but creating the subtraction eagerly is expensive. Track the
16132 // inequalities in a separate map, and materialize the rewrite lazily
16133 // when encountering a suitable subtraction while re-writing.
16134 if (LHS->getType()->isPointerTy()) {
16135 LHS = SE.getPtrToAddrExpr(LHS);
16136 RHS = SE.getPtrToAddrExpr(RHS);
16138 break;
16139 }
16140 const SCEVConstant *C;
16141 const SCEV *A, *B;
16144 RHS = A;
16145 LHS = B;
16146 }
16147 if (LHS > RHS)
16148 std::swap(LHS, RHS);
16149 Guards.NotEqual.insert({LHS, RHS});
16150 continue;
16151 }
16152 break;
16153 default:
16154 break;
16155 }
16156
16157 if (To)
16158 AddRewrite(From, FromRewritten, To);
16159 }
16160 };
16161
16163 // First, collect information from assumptions dominating the loop.
16164 for (auto &AssumeVH : SE.AC.assumptions()) {
16165 if (!AssumeVH)
16166 continue;
16167 auto *AssumeI = cast<CallInst>(AssumeVH);
16168 if (!SE.DT.dominates(AssumeI, Block))
16169 continue;
16170 Terms.emplace_back(AssumeI->getOperand(0), true);
16171 }
16172
16173 // Second, collect information from llvm.experimental.guards dominating the loop.
16174 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
16175 SE.F.getParent(), Intrinsic::experimental_guard);
16176 if (GuardDecl)
16177 for (const auto *GU : GuardDecl->users())
16178 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
16179 if (Guard->getFunction() == Block->getParent() &&
16180 SE.DT.dominates(Guard, Block))
16181 Terms.emplace_back(Guard->getArgOperand(0), true);
16182
16183 // Third, collect conditions from dominating branches. Starting at the loop
16184 // predecessor, climb up the predecessor chain, as long as there are
16185 // predecessors that can be found that have unique successors leading to the
16186 // original header.
16187 // TODO: share this logic with isLoopEntryGuardedByCond.
16188 unsigned NumCollectedConditions = 0;
16190 std::pair<const BasicBlock *, const BasicBlock *> Pair(Pred, Block);
16191 for (; Pair.first;
16192 Pair = SE.getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
16193 VisitedBlocks.insert(Pair.second);
16194 const CondBrInst *LoopEntryPredicate =
16195 dyn_cast<CondBrInst>(Pair.first->getTerminator());
16196 if (!LoopEntryPredicate)
16197 continue;
16198
16199 Terms.emplace_back(LoopEntryPredicate->getCondition(),
16200 LoopEntryPredicate->getSuccessor(0) == Pair.second);
16201 NumCollectedConditions++;
16202
16203 // If we are recursively collecting guards stop after 2
16204 // conditions to limit compile-time impact for now.
16205 if (Depth > 0 && NumCollectedConditions == 2)
16206 break;
16207 }
16208 // Finally, if we stopped climbing the predecessor chain because
16209 // there wasn't a unique one to continue, try to collect conditions
16210 // for PHINodes by recursively following all of their incoming
16211 // blocks and try to merge the found conditions to build a new one
16212 // for the Phi.
16213 if (Pair.second->hasNPredecessorsOrMore(2) &&
16215 SmallDenseMap<const BasicBlock *, LoopGuards> IncomingGuards;
16216 for (auto &Phi : Pair.second->phis())
16217 collectFromPHI(SE, Guards, Phi, VisitedBlocks, IncomingGuards, Depth);
16218 }
16219
16220 // Now apply the information from the collected conditions to
16221 // Guards.RewriteMap. Conditions are processed in reverse order, so the
16222 // earliest conditions is processed first, except guards with divisibility
16223 // information, which are moved to the back. This ensures the SCEVs with the
16224 // shortest dependency chains are constructed first.
16226 GuardsToProcess;
16227 for (auto [Term, EnterIfTrue] : reverse(Terms)) {
16228 SmallVector<Value *, 8> Worklist;
16229 SmallPtrSet<Value *, 8> Visited;
16230 Worklist.push_back(Term);
16231 while (!Worklist.empty()) {
16232 Value *Cond = Worklist.pop_back_val();
16233 if (!Visited.insert(Cond).second)
16234 continue;
16235
16236 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
16237 auto Predicate =
16238 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
16239 const auto *LHS = SE.getSCEV(Cmp->getOperand(0));
16240 const auto *RHS = SE.getSCEV(Cmp->getOperand(1));
16241 // If LHS is a constant, apply information to the other expression.
16242 // TODO: If LHS is not a constant, check if using CompareSCEVComplexity
16243 // can improve results.
16244 if (isa<SCEVConstant>(LHS)) {
16245 std::swap(LHS, RHS);
16247 }
16248 GuardsToProcess.emplace_back(Predicate, LHS, RHS);
16249 continue;
16250 }
16251
16252 Value *L, *R;
16253 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
16254 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
16255 Worklist.push_back(L);
16256 Worklist.push_back(R);
16257 }
16258 }
16259 }
16260
16261 // Process divisibility guards in reverse order to populate DivGuards early.
16262 DenseMap<const SCEV *, APInt> Multiples;
16263 LoopGuards DivGuards(SE);
16264 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess) {
16265 if (!isDivisibilityGuard(LHS, RHS, SE))
16266 continue;
16267 collectDivisibilityInformation(Predicate, LHS, RHS, DivGuards.RewriteMap,
16268 Multiples, SE);
16269 }
16270
16271 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess)
16272 CollectCondition(Predicate, LHS, RHS, Guards.RewriteMap, DivGuards);
16273
16274 // Apply divisibility information last. This ensures it is applied to the
16275 // outermost expression after other rewrites for the given value.
16276 for (const auto &[K, Divisor] : Multiples) {
16277 const SCEV *DivisorSCEV = SE.getConstant(Divisor);
16278 Guards.RewriteMap[K] =
16280 Guards.rewrite(K), Divisor, SE),
16281 DivisorSCEV),
16282 DivisorSCEV);
16283 ExprsToRewrite.push_back(K);
16284 }
16285
16286 // Let the rewriter preserve NUW/NSW flags if the unsigned/signed ranges of
16287 // the replacement expressions are contained in the ranges of the replaced
16288 // expressions.
16289 Guards.PreserveNUW = true;
16290 Guards.PreserveNSW = true;
16291 for (const SCEV *Expr : ExprsToRewrite) {
16292 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16293 Guards.PreserveNUW &=
16294 SE.getUnsignedRange(Expr).contains(SE.getUnsignedRange(RewriteTo));
16295 Guards.PreserveNSW &=
16296 SE.getSignedRange(Expr).contains(SE.getSignedRange(RewriteTo));
16297 }
16298
16299 // Now that all rewrite information is collect, rewrite the collected
16300 // expressions with the information in the map. This applies information to
16301 // sub-expressions.
16302 if (ExprsToRewrite.size() > 1) {
16303 for (const SCEV *Expr : ExprsToRewrite) {
16304 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16305 Guards.RewriteMap.erase(Expr);
16306 Guards.RewriteMap.insert({Expr, Guards.rewrite(RewriteTo)});
16307 }
16308 }
16309}
16310
16312 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
16313 /// in the map. It skips AddRecExpr because we cannot guarantee that the
16314 /// replacement is loop invariant in the loop of the AddRec.
16315 class SCEVLoopGuardRewriter
16316 : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
16319
16321
16322 public:
16323 SCEVLoopGuardRewriter(ScalarEvolution &SE,
16324 const ScalarEvolution::LoopGuards &Guards)
16325 : SCEVRewriteVisitor(SE), Map(Guards.RewriteMap),
16326 NotEqual(Guards.NotEqual) {
16327 if (Guards.PreserveNUW)
16328 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNUW);
16329 if (Guards.PreserveNSW)
16330 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNSW);
16331 }
16332
16333 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
16334
16335 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
16336 return Map.lookup_or(Expr, Expr);
16337 }
16338
16339 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
16340 if (const SCEV *S = Map.lookup(Expr))
16341 return S;
16342
16343 // If we didn't find the extact ZExt expr in the map, check if there's
16344 // an entry for a smaller ZExt we can use instead.
16345 Type *Ty = Expr->getType();
16346 const SCEV *Op = Expr->getOperand(0);
16347 unsigned Bitwidth = Ty->getScalarSizeInBits() / 2;
16348 while (Bitwidth % 8 == 0 && Bitwidth >= 8 &&
16349 Bitwidth > Op->getType()->getScalarSizeInBits()) {
16350 Type *NarrowTy = IntegerType::get(SE.getContext(), Bitwidth);
16351 auto *NarrowExt = SE.getZeroExtendExpr(Op, NarrowTy);
16352 if (const SCEV *S = Map.lookup(NarrowExt))
16353 return SE.getZeroExtendExpr(S, Ty);
16354 Bitwidth = Bitwidth / 2;
16355 }
16356
16358 Expr);
16359 }
16360
16361 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
16362 if (const SCEV *S = Map.lookup(Expr))
16363 return S;
16365 Expr);
16366 }
16367
16368 const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
16369 if (const SCEV *S = Map.lookup(Expr))
16370 return S;
16372 }
16373
16374 const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
16375 if (const SCEV *S = Map.lookup(Expr))
16376 return S;
16378 }
16379
16380 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
16381 if (const SCEV *S = Map.lookup(Expr))
16382 return S;
16383
16384 // Helper to check if S is a subtraction (A - B) where A != B, and if so,
16385 // return UMax(S, 1).
16386 auto RewriteSubtraction = [&](const SCEV *S) -> const SCEV * {
16387 SCEVUse LHS, RHS;
16388 if (MatchBinarySub(S, LHS, RHS)) {
16389 if (LHS > RHS)
16390 std::swap(LHS, RHS);
16391 if (NotEqual.contains({LHS, RHS})) {
16392 const SCEV *OneAlignedUp = getNextSCEVDivisibleByDivisor(
16393 SE.getOne(S->getType()), SE.getConstantMultiple(S), SE);
16394 return SE.getUMaxExpr(OneAlignedUp, S);
16395 }
16396 }
16397 return nullptr;
16398 };
16399
16400 // Check if Expr itself is a subtraction pattern with guard info.
16401 if (const SCEV *Rewritten = RewriteSubtraction(Expr))
16402 return Rewritten;
16403
16404 // Trip count expressions sometimes consist of adding 3 operands, i.e.
16405 // (Const + A + B). There may be guard info for A + B, and if so, apply
16406 // it.
16407 // TODO: Could more generally apply guards to Add sub-expressions.
16408 if (isa<SCEVConstant>(Expr->getOperand(0))) {
16409 if (Expr->getNumOperands() == 3) {
16410 const SCEV *Add =
16411 SE.getAddExpr(Expr->getOperand(1), Expr->getOperand(2));
16412 if (const SCEV *Rewritten = RewriteSubtraction(Add))
16413 return SE.getAddExpr(
16414 Expr->getOperand(0), Rewritten,
16415 ScalarEvolution::maskFlags(Expr->getNoWrapFlags(), FlagMask));
16416 if (const SCEV *S = Map.lookup(Add))
16417 return SE.getAddExpr(Expr->getOperand(0), S);
16418 }
16419
16420 // For expressions of the form (Const + A), check if we have guard info
16421 // for (Const + 1 + A), and rewrite to ((Const + 1 + A) - 1). This makes
16422 // sure we don't lose information when rewriting expressions based on
16423 // back-edge taken counts in some cases.
16424 if (Expr->getNumOperands() == 2) {
16425 const SCEV *S = nullptr;
16426 // Handle (-1 + 1 + A) without constructing SCEVs.
16427 if (match(Expr->getOperand(0), m_scev_AllOnes())) {
16428 S = Map.lookup(Expr->getOperand(1));
16429 } else {
16430 const SCEV *NewC =
16431 SE.getAddExpr(Expr->getOperand(0), SE.getOne(Expr->getType()));
16432 S = Map.lookup(SE.getAddExpr(NewC, Expr->getOperand(1)));
16433 }
16434 if (S)
16435 return SE.getAddExpr(S, SE.getMinusOne(Expr->getType()));
16436 }
16437 }
16438 SmallVector<SCEVUse, 2> Operands;
16439 bool Changed = false;
16440 for (SCEVUse Op : Expr->operands()) {
16441 Operands.push_back(
16443 Changed |= Op != Operands.back();
16444 }
16445 // We are only replacing operands with equivalent values, so transfer the
16446 // flags from the original expression.
16447 return !Changed ? Expr
16448 : SE.getAddExpr(Operands,
16450 Expr->getNoWrapFlags(), FlagMask));
16451 }
16452
16453 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
16454 SmallVector<SCEVUse, 2> Operands;
16455 bool Changed = false;
16456 for (SCEVUse Op : Expr->operands()) {
16457 Operands.push_back(
16459 Changed |= Op != Operands.back();
16460 }
16461 // We are only replacing operands with equivalent values, so transfer the
16462 // flags from the original expression.
16463 return !Changed ? Expr
16464 : SE.getMulExpr(Operands,
16466 Expr->getNoWrapFlags(), FlagMask));
16467 }
16468 };
16469
16470 if (RewriteMap.empty() && NotEqual.empty())
16471 return Expr;
16472
16473 SCEVLoopGuardRewriter Rewriter(SE, *this);
16474 return Rewriter.visit(Expr);
16475}
16476
16477const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
16478 return applyLoopGuards(Expr, LoopGuards::collect(L, *this));
16479}
16480
16482 const LoopGuards &Guards) {
16483 return Guards.rewrite(Expr);
16484}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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
MachineInstr unsigned OpIdx
static constexpr unsigned SM(unsigned Version)
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 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 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 cl::opt< unsigned > MaxPhiSCCAnalysisSize("scalar-evolution-max-scc-analysis-depth", cl::Hidden, cl::desc("Maximum amount of nodes to process while searching SCEVUnknown " "Phi strongly connected components"), cl::init(8))
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:2006
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1055
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:424
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1565
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1537
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:968
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:207
APInt abs() const
Get the absolute value.
Definition APInt.h:1820
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1210
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:372
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1191
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:381
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition APInt.h:467
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1692
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1513
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1120
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:210
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:217
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:330
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1175
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1970
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:220
bool isNonPositive() const
Determine if this APInt Value is non-positive (<= 0).
Definition APInt.h:362
unsigned countTrailingZeros() const
Definition APInt.h:1672
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:357
unsigned logBase2() const
Definition APInt.h:1786
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:476
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:834
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1300
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1159
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1028
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:880
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:441
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:307
bool isSignBitSet() const
Determine if sign bit of this APInt is set.
Definition APInt.h:342
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1139
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:201
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition APInt.h:433
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1246
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:240
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1230
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:461
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:484
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:171
This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:208
void AddInteger(signed I)
Definition FoldingSet.h:237
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:587
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:612
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 * 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 * getZeroExtendExprImpl(const SCEV *Op, Type *Ty, unsigned Depth=0)
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 * getCastExpr(SCEVTypes Kind, const SCEV *Op, Type *Ty)
LLVM_ABI const SCEV * getSequentialMinMaxExpr(SCEVTypes Kind, SmallVectorImpl< SCEVUse > &Operands)
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 * getSignExtendExprImpl(const SCEV *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 * getZeroExtendExpr(const SCEV *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 * 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 * getTruncateExpr(const SCEV *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 const SCEV * getAnyExtendExpr(const SCEV *Op, Type *Ty)
getAnyExtendExpr - Return a SCEV for the given operand extended with unspecified bits out to the give...
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 const SCEV * getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
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 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
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:2279
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition APInt.h:2284
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition APInt.h:2289
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:2847
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2294
LLVM_ABI APInt GreatestCommonDivisor(APInt A, APInt B)
Compute GCD of two unsigned APInt values.
Definition APInt.cpp:830
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< SCEVMulExpr, Op0_t, Op1_t, SCEV::FlagAnyWrap, true > m_scev_c_Mul(const Op0_t &Op0, const Op1_t &Op1)
SCEVBinaryExpr_match< SCEVSMaxExpr, Op0_t, Op1_t > m_scev_SMax(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
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt gcd(const DynamicAPInt &A, const DynamicAPInt &B)
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
iterator_range< pointee_iterator< WrappedIteratorT > > make_pointee_range(RangeT &&Range)
Definition iterator.h:341
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:378
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:395
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.