LLVM 24.0.0git
ScalarEvolution.cpp
Go to the documentation of this file.
1//===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the implementation of the scalar evolution analysis
10// engine, which is used primarily to analyze expressions involving induction
11// variables in loops.
12//
13// There are several aspects to this library. First is the representation of
14// scalar expressions, which are represented as subclasses of the SCEV class.
15// These classes are used to represent certain types of subexpressions that we
16// can handle. We only create one SCEV of a particular shape, so
17// pointer-comparisons for equality are legal.
18//
19// One important aspect of the SCEV objects is that they are never cyclic, even
20// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
21// the PHI node is one of the idioms that we can represent (e.g., a polynomial
22// recurrence) then we represent it directly as a recurrence node, otherwise we
23// represent it as a SCEVUnknown node.
24//
25// In addition to being able to represent expressions of various types, we also
26// have folders that are used to build the *canonical* representation for a
27// particular expression. These folders are capable of using a variety of
28// rewrite rules to simplify the expressions.
29//
30// Once the folders are defined, we can implement the more interesting
31// higher-level code, such as the code that recognizes PHI nodes of various
32// types, computes the execution count of a loop, etc.
33//
34// TODO: We should use these routines and value representations to implement
35// dependence analysis!
36//
37//===----------------------------------------------------------------------===//
38//
39// There are several good references for the techniques used in this analysis.
40//
41// Chains of recurrences -- a method to expedite the evaluation
42// of closed-form functions
43// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
44//
45// On computational properties of chains of recurrences
46// Eugene V. Zima
47//
48// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
49// Robert A. van Engelen
50//
51// Efficient Symbolic Analysis for Optimizing Compilers
52// Robert A. van Engelen
53//
54// Using the chains of recurrences algebra for data dependence testing and
55// induction variable substitution
56// MS Thesis, Johnie Birch
57//
58//===----------------------------------------------------------------------===//
59
61#include "llvm/ADT/APInt.h"
62#include "llvm/ADT/ArrayRef.h"
63#include "llvm/ADT/DenseMap.h"
65#include "llvm/ADT/FoldingSet.h"
66#include "llvm/ADT/STLExtras.h"
67#include "llvm/ADT/ScopeExit.h"
68#include "llvm/ADT/Sequence.h"
71#include "llvm/ADT/Statistic.h"
73#include "llvm/ADT/StringRef.h"
83#include "llvm/Config/llvm-config.h"
84#include "llvm/IR/Argument.h"
85#include "llvm/IR/BasicBlock.h"
86#include "llvm/IR/CFG.h"
87#include "llvm/IR/Constant.h"
89#include "llvm/IR/Constants.h"
90#include "llvm/IR/DataLayout.h"
92#include "llvm/IR/Dominators.h"
93#include "llvm/IR/Function.h"
94#include "llvm/IR/GlobalAlias.h"
95#include "llvm/IR/GlobalValue.h"
97#include "llvm/IR/InstrTypes.h"
98#include "llvm/IR/Instruction.h"
101#include "llvm/IR/Intrinsics.h"
102#include "llvm/IR/LLVMContext.h"
103#include "llvm/IR/Operator.h"
104#include "llvm/IR/PatternMatch.h"
105#include "llvm/IR/Type.h"
106#include "llvm/IR/Use.h"
107#include "llvm/IR/User.h"
108#include "llvm/IR/Value.h"
109#include "llvm/IR/Verifier.h"
111#include "llvm/Pass.h"
112#include "llvm/Support/Casting.h"
115#include "llvm/Support/Debug.h"
121#include <algorithm>
122#include <cassert>
123#include <climits>
124#include <cstdint>
125#include <cstdlib>
126#include <map>
127#include <memory>
128#include <numeric>
129#include <optional>
130#include <tuple>
131#include <utility>
132#include <vector>
133
134using namespace llvm;
135using namespace PatternMatch;
136using namespace SCEVPatternMatch;
137
138#define DEBUG_TYPE "scalar-evolution"
139
140STATISTIC(NumExitCountsComputed,
141 "Number of loop exits with predictable exit counts");
142STATISTIC(NumExitCountsNotComputed,
143 "Number of loop exits without predictable exit counts");
144STATISTIC(NumBruteForceTripCountsComputed,
145 "Number of loops with trip counts computed by force");
146
147#ifdef EXPENSIVE_CHECKS
148bool llvm::VerifySCEV = true;
149#else
150bool llvm::VerifySCEV = false;
151#endif
152
154 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
155 cl::desc("Maximum number of iterations SCEV will "
156 "symbolically execute a constant "
157 "derived loop"),
158 cl::init(100));
159
161 "verify-scev", cl::Hidden, cl::location(VerifySCEV),
162 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
164 "verify-scev-strict", cl::Hidden,
165 cl::desc("Enable stricter verification with -verify-scev is passed"));
166
168 "scev-verify-ir", cl::Hidden,
169 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
170 cl::init(false));
171
173 "scev-mulops-inline-threshold", cl::Hidden,
174 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
175 cl::init(32));
176
178 "scev-addops-inline-threshold", cl::Hidden,
179 cl::desc("Threshold for inlining addition operands into a SCEV"),
180 cl::init(500));
181
183 "scalar-evolution-max-scev-compare-depth", cl::Hidden,
184 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
185 cl::init(32));
186
188 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
189 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
190 cl::init(2));
191
193 "scalar-evolution-max-value-compare-depth", cl::Hidden,
194 cl::desc("Maximum depth of recursive value complexity comparisons"),
195 cl::init(2));
196
198 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
199 cl::desc("Maximum depth of recursive arithmetics"),
200 cl::init(32));
201
203 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
204 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
205
207 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
208 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
209 cl::init(8));
210
212 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
213 cl::desc("Max coefficients in AddRec during evolving"),
214 cl::init(8));
215
217 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
218 cl::desc("Size of the expression which is considered huge"),
219 cl::init(4096));
220
222 "scev-range-iter-threshold", cl::Hidden,
223 cl::desc("Threshold for switching to iteratively computing SCEV ranges"),
224 cl::init(32));
225
227 "scalar-evolution-max-loop-guard-collection-depth", cl::Hidden,
228 cl::desc("Maximum depth for recursive loop guard collection"), cl::init(1));
229
230static cl::opt<bool>
231ClassifyExpressions("scalar-evolution-classify-expressions",
232 cl::Hidden, cl::init(true),
233 cl::desc("When printing analysis, include information on every instruction"));
234
236 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
237 cl::init(false),
238 cl::desc("Use more powerful methods of sharpening expression ranges. May "
239 "be costly in terms of compile time"));
240
241static cl::opt<bool>
242 EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
243 cl::desc("Handle <= and >= in finite loops"),
244 cl::init(true));
245
247 "scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden,
248 cl::desc("Infer nuw/nsw flags using context where suitable"),
249 cl::init(true));
250
251//===----------------------------------------------------------------------===//
252// SCEV class definitions
253//===----------------------------------------------------------------------===//
254
256 // Leaf nodes are always their own canonical.
257 switch (getSCEVType()) {
258 case scConstant:
259 case scVScale:
260 case scUnknown:
261 CanonicalSCEV = this;
262 return;
263 default:
264 break;
265 }
266
267 // For all other expressions, check whether any immediate operand has a
268 // different canonical. Since operands are always created before their parent,
269 // their canonical pointers are already set — no recursion needed.
270 bool Changed = false;
272 for (SCEVUse Op : operands()) {
273 CanonOps.push_back(Op->getCanonical());
274 Changed |= CanonOps.back() != Op;
275 }
276
277 if (!Changed) {
278 CanonicalSCEV = this;
279 return;
280 }
281
282 // Rebuild the expression from the canonical operands, stripping use flags.
283 CanonicalSCEV = SE.getWithOperands(this, CanonOps);
284}
285
286//===----------------------------------------------------------------------===//
287// Implementation of the SCEV class.
288//
289
290#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
292 print(dbgs());
293 dbgs() << '\n';
294}
295#endif
296
297void SCEV::print(raw_ostream &OS) const {
298 switch (getSCEVType()) {
299 case scConstant:
300 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
301 return;
302 case scVScale:
303 OS << "vscale";
304 return;
305 case scPtrToAddr: {
306 const SCEVCastExpr *PtrCast = cast<SCEVCastExpr>(this);
307 SCEVUse Op = PtrCast->getOperand();
308 OS << "(ptrtoaddr " << *Op->getType() << " " << Op << " to "
309 << *PtrCast->getType() << ")";
310 return;
311 }
312 case scTruncate: {
313 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
314 SCEVUse Op = Trunc->getOperand();
315 OS << "(trunc " << *Op->getType() << " " << Op << " to "
316 << *Trunc->getType() << ")";
317 return;
318 }
319 case scZeroExtend: {
321 SCEVUse Op = ZExt->getOperand();
322 OS << "(zext " << *Op->getType() << " " << Op << " to " << *ZExt->getType()
323 << ")";
324 return;
325 }
326 case scSignExtend: {
328 SCEVUse Op = SExt->getOperand();
329 OS << "(sext " << *Op->getType() << " " << Op << " to " << *SExt->getType()
330 << ")";
331 return;
332 }
333 case scAddRecExpr: {
334 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
335 OS << "{" << AR->getOperand(0);
336 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
337 OS << ",+," << AR->getOperand(i);
338 OS << "}<";
339 if (AR->hasNoUnsignedWrap())
340 OS << "nuw><";
341 if (AR->hasNoSignedWrap())
342 OS << "nsw><";
343 if (AR->hasNoSelfWrap() && !AR->hasNoUnsignedWrap() &&
344 !AR->hasNoSignedWrap())
345 OS << "nw><";
346 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
347 OS << ">";
348 return;
349 }
350 case scAddExpr:
351 case scMulExpr:
352 case scUMaxExpr:
353 case scSMaxExpr:
354 case scUMinExpr:
355 case scSMinExpr:
357 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
358 const char *OpStr = nullptr;
359 switch (NAry->getSCEVType()) {
360 case scAddExpr: OpStr = " + "; break;
361 case scMulExpr: OpStr = " * "; break;
362 case scUMaxExpr: OpStr = " umax "; break;
363 case scSMaxExpr: OpStr = " smax "; break;
364 case scUMinExpr:
365 OpStr = " umin ";
366 break;
367 case scSMinExpr:
368 OpStr = " smin ";
369 break;
371 OpStr = " umin_seq ";
372 break;
373 default:
374 llvm_unreachable("There are no other nary expression types.");
375 }
376 OS << "(" << llvm::interleaved(NAry->operands(), OpStr) << ")";
377 switch (NAry->getSCEVType()) {
378 case scAddExpr:
379 case scMulExpr:
380 if (NAry->hasNoUnsignedWrap())
381 OS << "<nuw>";
382 if (NAry->hasNoSignedWrap())
383 OS << "<nsw>";
384 break;
385 default:
386 // Nothing to print for other nary expressions.
387 break;
388 }
389 return;
390 }
391 case scUDivExpr: {
392 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
393 OS << "(" << UDiv->getLHS() << " /u " << UDiv->getRHS() << ")";
394 return;
395 }
396 case scUnknown:
397 cast<SCEVUnknown>(this)->getValue()->printAsOperand(OS, false);
398 return;
400 OS << "***COULDNOTCOMPUTE***";
401 return;
402 }
403 llvm_unreachable("Unknown SCEV kind!");
404}
405
407 switch (getSCEVType()) {
408 case scConstant:
409 case scVScale:
410 case scUnknown:
411 return {};
412 case scPtrToAddr:
413 case scTruncate:
414 case scZeroExtend:
415 case scSignExtend:
416 return cast<SCEVCastExpr>(this)->operands();
417 case scAddRecExpr:
418 case scAddExpr:
419 case scMulExpr:
420 case scUMaxExpr:
421 case scSMaxExpr:
422 case scUMinExpr:
423 case scSMinExpr:
425 return cast<SCEVNAryExpr>(this)->operands();
426 case scUDivExpr:
427 return cast<SCEVUDivExpr>(this)->operands();
429 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
430 }
431 llvm_unreachable("Unknown SCEV kind!");
432}
433
434bool SCEV::isZero() const { return match(this, m_scev_Zero()); }
435
436bool SCEV::isOne() const { return match(this, m_scev_One()); }
437
438bool SCEV::isAllOnesValue() const { return match(this, m_scev_AllOnes()); }
439
442 if (!Mul) return false;
443
444 // If there is a constant factor, it will be first.
445 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
446 if (!SC) return false;
447
448 // Return true if the value is negative, this matches things like (-42 * V).
449 return SC->getAPInt().isNegative();
450}
451
454
456 return S->getSCEVType() == scCouldNotCompute;
457}
458
460 auto &Entry = ConstantSCEVs[V];
461 if (Entry)
462 return Entry;
463
466 ID.AddPointer(V);
468 if (SCEVConstant *S =
469 static_cast<SCEVConstant *>(UniqueSCEVs.lookup(ID, Token)))
470 return Entry = S;
471 SCEVConstant *S =
472 new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
473 UniqueSCEVs.insert(S, Token);
474 S->computeAndSetCanonical(*this);
475 return Entry = S;
476}
477
479 return getConstant(ConstantInt::get(getContext(), Val));
480}
481
482const SCEV *
485 // TODO: Avoid implicit trunc?
486 // See https://github.com/llvm/llvm-project/issues/112510.
487 return getConstant(
488 ConstantInt::get(ITy, V, isSigned, /*ImplicitTrunc=*/true));
489}
490
494 ID.AddPointer(Ty);
496 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
497 return S;
498 SCEV *S = new (SCEVAllocator) SCEVVScale(ID.Intern(SCEVAllocator), Ty);
499 UniqueSCEVs.insert(S, Token);
500 S->computeAndSetCanonical(*this);
501 return S;
502}
503
505 SCEV::NoWrapFlags Flags) {
506 const SCEV *Res = getConstant(Ty, EC.getKnownMinValue());
507 if (EC.isScalable())
508 Res = getMulExpr(Res, getVScale(Ty), Flags);
509 return Res;
510}
511
513 SCEVUse op, Type *ty)
514 : SCEV(ID, SCEVTy, computeExpressionSize(op), ty), Op(op) {}
515
516SCEVPtrToAddrExpr::SCEVPtrToAddrExpr(const FoldingSetNodeIDRef ID,
517 const SCEV *Op, Type *ITy)
518 : SCEVCastExpr(ID, scPtrToAddr, Op, ITy) {
519 assert(getOperand()->getType()->isPointerTy() && getType()->isIntegerTy() &&
520 "Must be a non-bit-width-changing pointer-to-integer cast!");
521}
522
527
528SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
529 Type *ty)
531 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
532 "Cannot truncate non-integer value!");
533}
534
535SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
536 Type *ty)
538 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
539 "Cannot zero extend non-integer value!");
540}
541
542SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
543 Type *ty)
545 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
546 "Cannot sign extend non-integer value!");
547}
548
550 // Clear this SCEVUnknown from various maps.
551 SE->forgetMemoizedResults({this});
552
553 // Remove this SCEVUnknown from the uniquing map.
554 SE->UniqueSCEVs.erase(this);
555
556 // Release the value.
557 setValPtr(nullptr);
558}
559
560void SCEVUnknown::allUsesReplacedWith(Value *New) {
561 // Clear this SCEVUnknown from various maps.
562 SE->forgetMemoizedResults({this});
563
564 // Remove this SCEVUnknown from the uniquing map.
565 SE->UniqueSCEVs.erase(this);
566
567 // Replace the value pointer in case someone is still using this SCEVUnknown.
568 setValPtr(New);
569}
570
571//===----------------------------------------------------------------------===//
572// SCEV Utilities
573//===----------------------------------------------------------------------===//
574
575/// Compare the two values \p LV and \p RV in terms of their "complexity" where
576/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
577/// operands in SCEV expressions.
578static int CompareValueComplexity(const LoopInfo *const LI, Value *LV,
579 Value *RV, unsigned Depth) {
581 return 0;
582
583 // Order pointer values after integer values. This helps SCEVExpander form
584 // GEPs.
585 bool LIsPointer = LV->getType()->isPointerTy(),
586 RIsPointer = RV->getType()->isPointerTy();
587 if (LIsPointer != RIsPointer)
588 return (int)LIsPointer - (int)RIsPointer;
589
590 // Compare getValueID values.
591 unsigned LID = LV->getValueID(), RID = RV->getValueID();
592 if (LID != RID)
593 return (int)LID - (int)RID;
594
595 // Sort arguments by their position.
596 if (const auto *LA = dyn_cast<Argument>(LV)) {
597 const auto *RA = cast<Argument>(RV);
598 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
599 return (int)LArgNo - (int)RArgNo;
600 }
601
602 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
603 const auto *RGV = cast<GlobalValue>(RV);
604
605 if (auto L = LGV->getLinkage() - RGV->getLinkage())
606 return L;
607
608 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
609 auto LT = GV->getLinkage();
610 return !(GlobalValue::isPrivateLinkage(LT) ||
612 };
613
614 // Use the names to distinguish the two values, but only if the
615 // names are semantically important.
616 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
617 return LGV->getName().compare(RGV->getName());
618 }
619
620 // For instructions, compare their loop depth, and their operand count. This
621 // is pretty loose.
622 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
623 const auto *RInst = cast<Instruction>(RV);
624
625 // Compare loop depths.
626 const BasicBlock *LParent = LInst->getParent(),
627 *RParent = RInst->getParent();
628 if (LParent != RParent) {
629 unsigned LDepth = LI->getLoopDepth(LParent),
630 RDepth = LI->getLoopDepth(RParent);
631 if (LDepth != RDepth)
632 return (int)LDepth - (int)RDepth;
633 }
634
635 // Compare the number of operands.
636 unsigned LNumOps = LInst->getNumOperands(),
637 RNumOps = RInst->getNumOperands();
638 if (LNumOps != RNumOps)
639 return (int)LNumOps - (int)RNumOps;
640
641 for (unsigned Idx : seq(LNumOps)) {
642 int Result = CompareValueComplexity(LI, LInst->getOperand(Idx),
643 RInst->getOperand(Idx), Depth + 1);
644 if (Result != 0)
645 return Result;
646 }
647 }
648
649 return 0;
650}
651
652// Return negative, zero, or positive, if LHS is less than, equal to, or greater
653// than RHS, respectively. A three-way result allows recursive comparisons to be
654// more efficient.
655// If the max analysis depth was reached, return std::nullopt, assuming we do
656// not know if they are equivalent for sure.
657static std::optional<int>
658CompareSCEVComplexity(const LoopInfo *const LI, const SCEV *LHS,
659 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
660 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
661 if (LHS == RHS)
662 return 0;
663
664 // Primarily, sort the SCEVs by their getSCEVType().
665 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
666 if (LType != RType)
667 return (int)LType - (int)RType;
668
670 return std::nullopt;
671
672 // Aside from the getSCEVType() ordering, the particular ordering
673 // isn't very important except that it's beneficial to be consistent,
674 // so that (a + b) and (b + a) don't end up as different expressions.
675 switch (LType) {
676 case scUnknown: {
677 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
678 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
679
680 int X =
681 CompareValueComplexity(LI, LU->getValue(), RU->getValue(), Depth + 1);
682 return X;
683 }
684
685 case scConstant: {
688
689 // Compare constant values.
690 const APInt &LA = LC->getAPInt();
691 const APInt &RA = RC->getAPInt();
692 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
693 if (LBitWidth != RBitWidth)
694 return (int)LBitWidth - (int)RBitWidth;
695 return LA.ult(RA) ? -1 : 1;
696 }
697
698 case scVScale: {
699 const auto *LTy = cast<IntegerType>(cast<SCEVVScale>(LHS)->getType());
700 const auto *RTy = cast<IntegerType>(cast<SCEVVScale>(RHS)->getType());
701 return LTy->getBitWidth() - RTy->getBitWidth();
702 }
703
704 case scAddRecExpr: {
707
708 // There is always a dominance between two recs that are used by one SCEV,
709 // so we can safely sort recs by loop header dominance. We require such
710 // order in getAddExpr.
711 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
712 if (LLoop != RLoop) {
713 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
714 assert(LHead != RHead && "Two loops share the same header?");
715 if (DT.dominates(LHead, RHead))
716 return 1;
717 assert(DT.dominates(RHead, LHead) &&
718 "No dominance between recurrences used by one SCEV?");
719 return -1;
720 }
721
722 [[fallthrough]];
723 }
724
725 case scTruncate:
726 case scZeroExtend:
727 case scSignExtend:
728 case scPtrToAddr:
729 case scAddExpr:
730 case scMulExpr:
731 case scUDivExpr:
732 case scSMaxExpr:
733 case scUMaxExpr:
734 case scSMinExpr:
735 case scUMinExpr:
737 ArrayRef<SCEVUse> LOps = LHS->operands();
738 ArrayRef<SCEVUse> ROps = RHS->operands();
739
740 // Lexicographically compare n-ary-like expressions.
741 unsigned LNumOps = LOps.size(), RNumOps = ROps.size();
742 if (LNumOps != RNumOps)
743 return (int)LNumOps - (int)RNumOps;
744
745 for (unsigned i = 0; i != LNumOps; ++i) {
746 auto X = CompareSCEVComplexity(LI, LOps[i].getPointer(),
747 ROps[i].getPointer(), DT, Depth + 1);
748 if (X != 0)
749 return X;
750 }
751 return 0;
752 }
753
755 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
756 }
757 llvm_unreachable("Unknown SCEV kind!");
758}
759
760/// Given a list of SCEV objects, order them by their complexity, and group
761/// objects of the same complexity together by value. When this routine is
762/// finished, we know that any duplicates in the vector are consecutive and that
763/// complexity is monotonically increasing.
764///
765/// Note that we go take special precautions to ensure that we get deterministic
766/// results from this routine. In other words, we don't want the results of
767/// this to depend on where the addresses of various SCEV objects happened to
768/// land in memory.
770 DominatorTree &DT) {
771 if (Ops.size() < 2) return; // Noop
772
773 // Whether LHS has provably less complexity than RHS.
774 auto IsLessComplex = [&](SCEVUse LHS, SCEVUse RHS) {
775 auto Complexity = CompareSCEVComplexity(LI, LHS, RHS, DT);
776 return Complexity && *Complexity < 0;
777 };
778 if (Ops.size() == 2) {
779 // This is the common case, which also happens to be trivially simple.
780 // Special case it.
781 SCEVUse &LHS = Ops[0], &RHS = Ops[1];
782 if (IsLessComplex(RHS, LHS))
783 std::swap(LHS, RHS);
784 return;
785 }
786
787 // Do the rough sort by complexity.
789 Ops, [&](SCEVUse LHS, SCEVUse RHS) { return IsLessComplex(LHS, RHS); });
790
791 // Now that we are sorted by complexity, group elements of the same
792 // complexity. Note that this is, at worst, N^2, but the vector is likely to
793 // be extremely short in practice. Note that we take this approach because we
794 // do not want to depend on the addresses of the objects we are grouping.
795 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
796 const SCEV *S = Ops[i];
797 unsigned Complexity = S->getSCEVType();
798
799 // If there are any objects of the same complexity and same value as this
800 // one, group them.
801 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
802 if (Ops[j] == S) { // Found a duplicate.
803 // Move it to immediately after i'th element.
804 std::swap(Ops[i+1], Ops[j]);
805 ++i; // no need to rescan it.
806 if (i == e-2) return; // Done!
807 }
808 }
809 }
810}
811
812/// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
813/// least HugeExprThreshold nodes).
815 return any_of(Ops, [](const SCEV *S) {
817 });
818}
819
820/// Performs a number of common optimizations on the passed \p Ops. If the
821/// whole expression reduces down to a single operand, it will be returned.
822///
823/// The following optimizations are performed:
824/// * Fold constants using the \p Fold function.
825/// * Remove identity constants satisfying \p IsIdentity.
826/// * If a constant satisfies \p IsAbsorber, return it.
827/// * Sort operands by complexity.
828template <typename FoldT, typename IsIdentityT, typename IsAbsorberT>
829static const SCEV *
831 SmallVectorImpl<SCEVUse> &Ops, FoldT Fold,
832 IsIdentityT IsIdentity, IsAbsorberT IsAbsorber) {
833 const SCEVConstant *Folded = nullptr;
834 for (unsigned Idx = 0; Idx < Ops.size();) {
835 const SCEV *Op = Ops[Idx];
836 if (const auto *C = dyn_cast<SCEVConstant>(Op)) {
837 if (!Folded)
838 Folded = C;
839 else
840 Folded = cast<SCEVConstant>(
841 SE.getConstant(Fold(Folded->getAPInt(), C->getAPInt())));
842 Ops.erase(Ops.begin() + Idx);
843 continue;
844 }
845 ++Idx;
846 }
847
848 if (Ops.empty()) {
849 assert(Folded && "Must have folded value");
850 return Folded;
851 }
852
853 if (Folded && IsAbsorber(Folded->getAPInt()))
854 return Folded;
855
856 GroupByComplexity(Ops, &LI, DT);
857 if (Folded && !IsIdentity(Folded->getAPInt()))
858 Ops.insert(Ops.begin(), Folded);
859
860 return Ops.size() == 1 ? Ops[0] : nullptr;
861}
862
863//===----------------------------------------------------------------------===//
864// Simple SCEV method implementations
865//===----------------------------------------------------------------------===//
866
867/// Compute BC(It, K). The result has width W. Assume, K > 0.
868static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
869 ScalarEvolution &SE,
870 Type *ResultTy) {
871 // Handle the simplest case efficiently.
872 if (K == 1)
873 return SE.getTruncateOrZeroExtend(It, ResultTy);
874
875 // We are using the following formula for BC(It, K):
876 //
877 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
878 //
879 // Suppose, W is the bitwidth of the return value. We must be prepared for
880 // overflow. Hence, we must assure that the result of our computation is
881 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
882 // safe in modular arithmetic.
883 //
884 // However, this code doesn't use exactly that formula; the formula it uses
885 // is something like the following, where T is the number of factors of 2 in
886 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
887 // exponentiation:
888 //
889 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
890 //
891 // This formula is trivially equivalent to the previous formula. However,
892 // this formula can be implemented much more efficiently. The trick is that
893 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
894 // arithmetic. To do exact division in modular arithmetic, all we have
895 // to do is multiply by the inverse. Therefore, this step can be done at
896 // width W.
897 //
898 // The next issue is how to safely do the division by 2^T. The way this
899 // is done is by doing the multiplication step at a width of at least W + T
900 // bits. This way, the bottom W+T bits of the product are accurate. Then,
901 // when we perform the division by 2^T (which is equivalent to a right shift
902 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
903 // truncated out after the division by 2^T.
904 //
905 // In comparison to just directly using the first formula, this technique
906 // is much more efficient; using the first formula requires W * K bits,
907 // but this formula less than W + K bits. Also, the first formula requires
908 // a division step, whereas this formula only requires multiplies and shifts.
909 //
910 // It doesn't matter whether the subtraction step is done in the calculation
911 // width or the input iteration count's width; if the subtraction overflows,
912 // the result must be zero anyway. We prefer here to do it in the width of
913 // the induction variable because it helps a lot for certain cases; CodeGen
914 // isn't smart enough to ignore the overflow, which leads to much less
915 // efficient code if the width of the subtraction is wider than the native
916 // register width.
917 //
918 // (It's possible to not widen at all by pulling out factors of 2 before
919 // the multiplication; for example, K=2 can be calculated as
920 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
921 // extra arithmetic, so it's not an obvious win, and it gets
922 // much more complicated for K > 3.)
923
924 // Protection from insane SCEVs; this bound is conservative,
925 // but it probably doesn't matter.
926 if (K > 1000)
927 return SE.getCouldNotCompute();
928
929 unsigned W = SE.getTypeSizeInBits(ResultTy);
930
931 // Calculate K! / 2^T and T; we divide out the factors of two before
932 // multiplying for calculating K! / 2^T to avoid overflow.
933 // Other overflow doesn't matter because we only care about the bottom
934 // W bits of the result.
935 APInt OddFactorial(W, 1);
936 unsigned T = 1;
937 for (unsigned i = 3; i <= K; ++i) {
938 unsigned TwoFactors = countr_zero(i);
939 T += TwoFactors;
940 OddFactorial *= (i >> TwoFactors);
941 }
942
943 // We need at least W + T bits for the multiplication step
944 unsigned CalculationBits = W + T;
945
946 // Calculate 2^T, at width T+W.
947 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
948
949 // Calculate the multiplicative inverse of K! / 2^T;
950 // this multiplication factor will perform the exact division by
951 // K! / 2^T.
952 APInt MultiplyFactor = OddFactorial.multiplicativeInverse();
953
954 // Calculate the product, at width T+W
955 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
956 CalculationBits);
957 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
958 for (unsigned i = 1; i != K; ++i) {
959 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
960 Dividend = SE.getMulExpr(Dividend,
961 SE.getTruncateOrZeroExtend(S, CalculationTy));
962 }
963
964 // Divide by 2^T
965 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
966
967 // Truncate the result, and divide by K! / 2^T.
968
969 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
970 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
971}
972
973/// Return the value of this chain of recurrences at the specified iteration
974/// number. We can evaluate this recurrence by multiplying each element in the
975/// chain by the binomial coefficient corresponding to it. In other words, we
976/// can evaluate {A,+,B,+,C,+,D} as:
977///
978/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
979///
980/// where BC(It, k) stands for binomial coefficient.
982 ScalarEvolution &SE) const {
983 return evaluateAtIteration(operands(), It, SE);
984}
985
987 const SCEV *It,
988 ScalarEvolution &SE) {
989 assert(Operands.size() > 0);
990 const SCEV *Result = Operands[0].getPointer();
991 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
992 // The computation is correct in the face of overflow provided that the
993 // multiplication is performed _after_ the evaluation of the binomial
994 // coefficient.
995 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
996 if (isa<SCEVCouldNotCompute>(Coeff))
997 return Coeff;
998
999 Result =
1000 SE.getAddExpr(Result, SE.getMulExpr(Operands[i].getPointer(), Coeff));
1001 }
1002 return Result;
1003}
1004
1005//===----------------------------------------------------------------------===//
1006// SCEV Expression folder implementations
1007//===----------------------------------------------------------------------===//
1008
1009/// The SCEVCastSinkingRewriter takes a scalar evolution expression,
1010/// which computes a pointer-typed value, and rewrites the whole expression
1011/// tree so that *all* the computations are done on integers, and the only
1012/// pointer-typed operands in the expression are SCEVUnknown.
1013/// The CreatePtrCast callback is invoked to create the actual conversion
1014/// (ptrtoint or ptrtoaddr) at the SCEVUnknown leaves.
1016 : public SCEVRewriteVisitor<SCEVCastSinkingRewriter> {
1018 using ConversionFn = function_ref<const SCEV *(const SCEVUnknown *)>;
1019 Type *TargetTy;
1020 ConversionFn CreatePtrCast;
1021
1022public:
1024 ConversionFn CreatePtrCast)
1025 : Base(SE), TargetTy(TargetTy), CreatePtrCast(std::move(CreatePtrCast)) {}
1026
1027 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
1028 Type *TargetTy, ConversionFn CreatePtrCast) {
1029 SCEVCastSinkingRewriter Rewriter(SE, TargetTy, std::move(CreatePtrCast));
1030 return Rewriter.visit(Scev);
1031 }
1032
1033 const SCEV *visit(const SCEV *S) {
1034 Type *STy = S->getType();
1035 // If the expression is not pointer-typed, just keep it as-is.
1036 if (!STy->isPointerTy())
1037 return S;
1038 // Else, recursively sink the cast down into it.
1039 return Base::visit(S);
1040 }
1041
1042 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1043 // Preserve wrap flags on rewritten SCEVAddExpr, which the default
1044 // implementation drops.
1046 bool Changed = false;
1047 for (SCEVUse Op : Expr->operands()) {
1048 Operands.push_back(visit(Op.getPointer()));
1049 Changed |= Op.getPointer() != Operands.back();
1050 }
1051 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1052 }
1053
1054 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1055 assert(Expr->getType()->isPointerTy() &&
1056 "Should only reach pointer-typed SCEVUnknown's.");
1057 // Perform some basic constant folding. If the operand of the cast is a
1058 // null pointer, don't create a cast SCEV expression (that will be left
1059 // as-is), but produce a zero constant.
1061 return SE.getZero(TargetTy);
1062 return CreatePtrCast(Expr);
1063 }
1064};
1065
1067 assert(Op->getType()->isPointerTy() && "Op must be a pointer");
1068
1069 // Treat pointers with unstable representation conservatively, since the
1070 // address bits may change.
1071 if (DL.hasUnstableRepresentation(Op->getType()))
1072 return getCouldNotCompute();
1073
1074 Type *Ty = DL.getAddressType(Op->getType());
1075
1076 // Use the rewriter to sink the cast down to SCEVUnknown leaves.
1077 // The rewriter handles null pointer constant folding.
1079 Op, *this, Ty, [this, Ty](const SCEVUnknown *U) {
1082 ID.AddPointer(U);
1083 ID.AddPointer(Ty);
1085 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1086 return S;
1087 SCEV *S = new (SCEVAllocator)
1088 SCEVPtrToAddrExpr(ID.Intern(SCEVAllocator), U, Ty);
1089 UniqueSCEVs.insert(S, Token);
1090 S->computeAndSetCanonical(*this);
1091 registerUser(S, U);
1092 return static_cast<const SCEV *>(S);
1093 });
1094 assert(IntOp->getType()->isIntegerTy() &&
1095 "We must have succeeded in sinking the cast, "
1096 "and ending up with an integer-typed expression!");
1097 return IntOp;
1098}
1099
1101 unsigned Depth) {
1102 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1103 "This is not a truncating conversion!");
1104 assert(isSCEVable(Ty) &&
1105 "This is not a conversion to a SCEVable type!");
1106 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1107 Ty = getEffectiveSCEVType(Ty);
1108
1111 ID.AddPointer(Op.getOpaqueValue());
1112 ID.AddPointer(Ty);
1114 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1115 return S;
1116
1117 // Fold if the operand is constant.
1118 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1119 return getConstant(
1120 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1121
1122 // trunc(trunc(x)) --> trunc(x)
1124 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1125
1126 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1128 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1129
1130 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1132 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1133
1134 if (Depth > MaxCastDepth) {
1135 SCEV *S =
1136 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1137 UniqueSCEVs.insert(S, Token);
1138 S->computeAndSetCanonical(*this);
1139 registerUser(S, Op);
1140 return S;
1141 }
1142
1143 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1144 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1145 // if after transforming we have at most one truncate, not counting truncates
1146 // that replace other casts.
1148 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1150 unsigned numTruncs = 0;
1151 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1152 ++i) {
1153 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1154 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1156 numTruncs++;
1157 Operands.push_back(S);
1158 }
1159 if (numTruncs < 2) {
1160 if (isa<SCEVAddExpr>(Op))
1161 return getAddExpr(Operands);
1162 if (isa<SCEVMulExpr>(Op))
1163 return getMulExpr(Operands);
1164 llvm_unreachable("Unexpected SCEV type for Op.");
1165 }
1166 // Although we checked in the beginning that ID is not in the cache, it is
1167 // possible that during recursion and different modification ID was inserted
1168 // into the cache. So if we find it, just return it.
1169 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1170 return S;
1171 }
1172
1173 // If the input value is a chrec scev, truncate the chrec's operands.
1174 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1176 for (const SCEV *Op : AddRec->operands())
1177 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1178 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1179 }
1180
1181 // Return zero if truncating to known zeros.
1182 uint32_t MinTrailingZeros = getMinTrailingZeros(Op);
1183 if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1184 return getZero(Ty);
1185
1186 // The cast wasn't folded; create an explicit cast node. We can reuse
1187 // the existing insert position since if we get here, we won't have
1188 // made any changes which would invalidate it.
1189 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1190 Op, Ty);
1191 UniqueSCEVs.insert(S, Token);
1192 S->computeAndSetCanonical(*this);
1193 registerUser(S, Op);
1194 return S;
1195}
1196
1197// Get the limit of a recurrence such that incrementing by Step cannot cause
1198// signed overflow as long as the value of the recurrence within the
1199// loop does not exceed this limit before incrementing.
1200static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1201 ICmpInst::Predicate *Pred,
1202 ScalarEvolution *SE) {
1203 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1204 if (SE->isKnownPositive(Step)) {
1205 *Pred = ICmpInst::ICMP_SLT;
1207 SE->getSignedRangeMax(Step));
1208 }
1209 if (SE->isKnownNegative(Step)) {
1210 *Pred = ICmpInst::ICMP_SGT;
1212 SE->getSignedRangeMin(Step));
1213 }
1214 return nullptr;
1215}
1216
1217// Get the limit of a recurrence such that incrementing by Step cannot cause
1218// unsigned overflow as long as the value of the recurrence within the loop does
1219// not exceed this limit before incrementing.
1221 ICmpInst::Predicate *Pred,
1222 ScalarEvolution *SE) {
1223 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1224 *Pred = ICmpInst::ICMP_ULT;
1225
1227 SE->getUnsignedRangeMax(Step));
1228}
1229
1230namespace {
1231
1232struct ExtendOpTraitsBase {
1233 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(SCEVUse, Type *,
1234 unsigned);
1235};
1236
1237// Used to make code generic over signed and unsigned overflow.
1238template <typename ExtendOp> struct ExtendOpTraits {
1239 // Members present:
1240 //
1241 // static const SCEV::NoWrapFlags WrapType;
1242 //
1243 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1244 //
1245 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1246 // ICmpInst::Predicate *Pred,
1247 // ScalarEvolution *SE);
1248};
1249
1250template <>
1251struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1252 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1253
1254 static const GetExtendExprTy GetExtendExpr;
1255
1256 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1257 ICmpInst::Predicate *Pred,
1258 ScalarEvolution *SE) {
1259 return getSignedOverflowLimitForStep(Step, Pred, SE);
1260 }
1261};
1262
1263const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1265
1266template <>
1267struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1268 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1269
1270 static const GetExtendExprTy GetExtendExpr;
1271
1272 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1273 ICmpInst::Predicate *Pred,
1274 ScalarEvolution *SE) {
1275 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1276 }
1277};
1278
1279const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1281
1282} // end anonymous namespace
1283
1284// The recurrence AR has been shown to have no signed/unsigned wrap or something
1285// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1286// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1287// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1288// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1289// expression "Step + sext/zext(PreIncAR)" is congruent with
1290// "sext/zext(PostIncAR)"
1291template <typename ExtendOpTy>
1293 ScalarEvolution *SE, unsigned Depth) {
1294 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1295 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1296
1297 const Loop *L = AR->getLoop();
1298 const SCEV *Start = AR->getStart();
1299 const SCEV *Step = AR->getStepRecurrence(*SE);
1300
1301 // Check for a simple looking step prior to loop entry.
1302 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1303 if (!SA)
1304 return nullptr;
1305
1306 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1307 // subtraction is expensive. For this purpose, perform a quick and dirty
1308 // difference, by checking for Step in the operand list. Note, that
1309 // SA might have repeated ops, like %a + %a + ..., so only remove one.
1310 SmallVector<SCEVUse, 4> DiffOps(SA->operands());
1311 for (auto It = DiffOps.begin(); It != DiffOps.end(); ++It)
1312 if (*It == Step) {
1313 DiffOps.erase(It);
1314 break;
1315 }
1316
1317 if (DiffOps.size() == SA->getNumOperands())
1318 return nullptr;
1319
1320 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1321 // `Step`:
1322
1323 // 1. NSW/NUW flags on the step increment.
1324 auto PreStartFlags =
1326 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1328 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1329
1330 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1331 // "S+X does not sign/unsign-overflow".
1332 //
1333
1334 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1335 if (PreAR && any(PreAR->getNoWrapFlags(WrapType)) &&
1336 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1337 return PreStart;
1338
1339 // 2. Direct overflow check on the step operation's expression.
1340 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1341 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1342 const SCEV *OperandExtendedStart =
1343 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1344 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1345 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1346 if (PreAR && any(AR->getNoWrapFlags(WrapType))) {
1347 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1348 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1349 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1350 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1351 }
1352 return PreStart;
1353 }
1354
1355 // 3. Loop precondition.
1357 const SCEV *OverflowLimit =
1358 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1359
1360 if (OverflowLimit &&
1361 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1362 return PreStart;
1363
1364 return nullptr;
1365}
1366
1367// Get the normalized zero or sign extended expression for this AddRec's Start.
1368template <typename ExtendOpTy>
1369static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1370 ScalarEvolution *SE,
1371 unsigned Depth) {
1372 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1373
1374 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, SE, Depth);
1375 if (!PreStart)
1376 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1377
1378 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1379 Depth),
1380 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1381}
1382
1383// Try to prove away overflow by looking at "nearby" add recurrences. A
1384// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1385// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1386//
1387// Formally:
1388//
1389// {S,+,X} == {S-T,+,X} + T
1390// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1391//
1392// If ({S-T,+,X} + T) does not overflow ... (1)
1393//
1394// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1395//
1396// If {S-T,+,X} does not overflow ... (2)
1397//
1398// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1399// == {Ext(S-T)+Ext(T),+,Ext(X)}
1400//
1401// If (S-T)+T does not overflow ... (3)
1402//
1403// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1404// == {Ext(S),+,Ext(X)} == LHS
1405//
1406// Thus, if (1), (2) and (3) are true for some T, then
1407// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1408//
1409// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1410// does not overflow" restricted to the 0th iteration. Therefore we only need
1411// to check for (1) and (2).
1412//
1413// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1414// is `Delta` (defined below).
1415template <typename ExtendOpTy>
1416bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1417 const SCEV *Step,
1418 const Loop *L) {
1419 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1420
1421 // We restrict `Start` to a constant to prevent SCEV from spending too much
1422 // time here. It is correct (but more expensive) to continue with a
1423 // non-constant `Start` and do a general SCEV subtraction to compute
1424 // `PreStart` below.
1425 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1426 if (!StartC)
1427 return false;
1428
1429 APInt StartAI = StartC->getAPInt();
1430
1431 for (unsigned Delta : {-2, -1, 1, 2}) {
1432 const SCEV *PreStart = getConstant(StartAI - Delta);
1433
1434 FoldingSetNodeID ID;
1435 ID.AddInteger(scAddRecExpr);
1436 ID.AddPointer(PreStart);
1437 ID.AddPointer(Step);
1438 ID.AddPointer(L);
1439 FoldingSetInsertToken Token;
1440 const auto *PreAR =
1441 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.lookup(ID, Token));
1442
1443 // Give up if we don't already have the add recurrence we need because
1444 // actually constructing an add recurrence is relatively expensive.
1445 if (PreAR && any(PreAR->getNoWrapFlags(WrapType))) { // proves (2)
1446 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1448 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1449 DeltaS, &Pred, this);
1450 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1451 return true;
1452 }
1453 }
1454
1455 return false;
1456}
1457
1458// Finds an integer D for an expression (C + x + y + ...) such that the top
1459// level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1460// unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1461// maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1462// the (C + x + y + ...) expression is \p WholeAddExpr.
1464 const SCEVConstant *ConstantTerm,
1465 const SCEVAddExpr *WholeAddExpr) {
1466 const APInt &C = ConstantTerm->getAPInt();
1467 const unsigned BitWidth = C.getBitWidth();
1468 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1469 uint32_t TZ = BitWidth;
1470 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1471 TZ = std::min(TZ, SE.getMinTrailingZeros(WholeAddExpr->getOperand(I)));
1472 if (TZ) {
1473 // Set D to be as many least significant bits of C as possible while still
1474 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1475 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1476 }
1477 return APInt(BitWidth, 0);
1478}
1479
1480// Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1481// level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1482// number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1483// ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1485 const APInt &ConstantStart,
1486 const SCEV *Step) {
1487 const unsigned BitWidth = ConstantStart.getBitWidth();
1488 const uint32_t TZ = SE.getMinTrailingZeros(Step);
1489 if (TZ)
1490 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1491 : ConstantStart;
1492 return APInt(BitWidth, 0);
1493}
1494
1496 const ScalarEvolution::FoldID &ID, const SCEV *S,
1499 &FoldCacheUser) {
1500 auto I = FoldCache.insert({ID, S});
1501 if (!I.second) {
1502 // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1503 // entry.
1504 auto &UserIDs = FoldCacheUser[I.first->second];
1505 assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
1506 for (unsigned I = 0; I != UserIDs.size(); ++I)
1507 if (UserIDs[I] == ID) {
1508 std::swap(UserIDs[I], UserIDs.back());
1509 break;
1510 }
1511 UserIDs.pop_back();
1512 I.first->second = S;
1513 }
1514 FoldCacheUser[S].push_back(ID);
1515}
1516
1518 unsigned Depth) {
1519 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1520 "This is not an extending conversion!");
1521 assert(isSCEVable(Ty) &&
1522 "This is not a conversion to a SCEVable type!");
1523 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1524 Ty = getEffectiveSCEVType(Ty);
1525
1526 FoldID ID(scZeroExtend, Op, Ty);
1527 if (const SCEV *S = FoldCache.lookup(ID))
1528 return S;
1529
1530 const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1532 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1533 return S;
1534}
1535
1537 unsigned Depth) {
1538 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1539 "This is not an extending conversion!");
1540 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1541 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1542
1543 // Fold if the operand is constant.
1544 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1545 return getConstant(SC->getAPInt().zext(getTypeSizeInBits(Ty)));
1546
1547 // zext(zext(x)) --> zext(x)
1549 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1550
1551 // If the operand is an affine AddRec with the no-unsigned-wrap flag, the
1552 // zero-extension distributes over the recurrence.
1553 const SCEV *Start, *Step;
1554 const Loop *L;
1555 if (Depth <= MaxCastDepth &&
1556 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1557 const auto *AR = cast<SCEVAddRecExpr>(Op);
1558 if (AR->hasNoUnsignedWrap()) {
1559 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1560 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1561 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1562 }
1563 }
1564
1565 // Before doing any expensive analysis, check to see if we've already
1566 // computed a SCEV for this Op and Ty.
1569 ID.AddPointer(Op.getOpaqueValue());
1570 ID.AddPointer(Ty);
1572 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1573 return S;
1574 if (Depth > MaxCastDepth) {
1575 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1576 Op, Ty);
1577 UniqueSCEVs.insert(S, Token);
1578 S->computeAndSetCanonical(*this);
1579 registerUser(S, Op);
1580 return S;
1581 }
1582
1583 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1585 // It's possible the bits taken off by the truncate were all zero bits. If
1586 // so, we should be able to simplify this further.
1587 const SCEV *X = ST->getOperand();
1589 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1590 unsigned NewBits = getTypeSizeInBits(Ty);
1591 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1592 CR.zextOrTrunc(NewBits)))
1593 return getTruncateOrZeroExtend(X, Ty, Depth);
1594 }
1595
1596 // If the input value is a chrec scev, and we can prove that the value
1597 // did not overflow the old, smaller, value, we can zero extend all of the
1598 // operands (often constants). This allows analysis of something like
1599 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1600 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1601 const auto *AR = cast<SCEVAddRecExpr>(Op);
1602 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1603
1604 // The no-unsigned-wrap case is handled before the uniquing lookup above.
1605
1606 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1607 // Note that this serves two purposes: It filters out loops that are
1608 // simply not analyzable, and it covers the case where this code is
1609 // being called from within backedge-taken count analysis, such that
1610 // attempting to ask for the backedge-taken count would likely result
1611 // in infinite recursion. In the later case, the analysis code will
1612 // cope with a conservative value, and it will take care to purge
1613 // that value once it has finished.
1614 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1615 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1616 // Manually compute the final value for AR, checking for overflow.
1617
1618 // Check whether the backedge-taken count can be losslessly casted to
1619 // the addrec's type. The count is always unsigned.
1620 const SCEV *CastedMaxBECount =
1621 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1622 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1623 CastedMaxBECount, MaxBECount->getType(), Depth);
1624 if (MaxBECount == RecastedMaxBECount) {
1625 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1626 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1627 const SCEV *ZMul =
1628 getMulExpr(CastedMaxBECount, Step, SCEV::FlagAnyWrap, Depth + 1);
1629 const SCEV *ZAdd = getZeroExtendExpr(
1630 getAddExpr(Start, ZMul, SCEV::FlagAnyWrap, Depth + 1), WideTy,
1631 Depth + 1);
1632 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1633 const SCEV *WideMaxBECount =
1634 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1635 const SCEV *OperandExtendedAdd =
1636 getAddExpr(WideStart,
1637 getMulExpr(WideMaxBECount,
1638 getZeroExtendExpr(Step, WideTy, Depth + 1),
1641 if (ZAdd == OperandExtendedAdd) {
1642 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1643 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1644 // Return the expression with the addrec on the outside.
1645 Start =
1647 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1648 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1649 }
1650 // Similar to above, only this time treat the step value as signed.
1651 // This covers loops that count down.
1652 OperandExtendedAdd =
1653 getAddExpr(WideStart,
1654 getMulExpr(WideMaxBECount,
1655 getSignExtendExpr(Step, WideTy, Depth + 1),
1658 if (ZAdd == OperandExtendedAdd) {
1659 // Cache knowledge of AR NW, which is propagated to this AddRec.
1660 // Negative step causes unsigned wrap, but it still can't self-wrap.
1661 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1662 // Return the expression with the addrec on the outside.
1663 Start =
1665 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1666 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1667 }
1668 }
1669 }
1670
1671 // Normally, in the cases we can prove no-overflow via a
1672 // backedge guarding condition, we can also compute a backedge
1673 // taken count for the loop. The exceptions are assumptions and
1674 // guards present in the loop -- SCEV is not great at exploiting
1675 // these to compute max backedge taken counts, but can still use
1676 // these to prove lack of overflow. Use this fact to avoid
1677 // doing extra work that may not pay off.
1678 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1679 !AC.assumptions().empty()) {
1680
1681 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1682 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1683 if (AR->hasNoUnsignedWrap()) {
1684 // Same as nuw case above - duplicated here to avoid a compile time
1685 // issue. It's not clear that the order of checks does matter, but
1686 // it's one of two issue possible causes for a change which was
1687 // reverted. Be conservative for the moment.
1688 Start =
1690 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1691 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1692 }
1693
1694 // For a negative step, we can extend the operands iff doing so only
1695 // traverses values in the range zext([0,UINT_MAX]).
1696 if (isKnownNegative(Step)) {
1697 const SCEV *N =
1701 // Cache knowledge of AR NW, which is propagated to this
1702 // AddRec. Negative step causes unsigned wrap, but it
1703 // still can't self-wrap.
1704 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1705 // Return the expression with the addrec on the outside.
1706 Start =
1708 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1709 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1710 }
1711 }
1712 }
1713
1714 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1715 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1716 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1717 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1718 const APInt &C = SC->getAPInt();
1719 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1720 if (D != 0) {
1721 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1722 const SCEV *SResidual =
1723 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1724 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1725 return getAddExpr(SZExtD, SZExtR, SCEV::FlagNSW | SCEV::FlagNUW,
1726 Depth + 1);
1727 }
1728 }
1729
1730 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1731 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1732 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1733 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1734 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1735 }
1736 }
1737
1738 // zext(A % B) --> zext(A) % zext(B)
1739 {
1740 const SCEV *LHS;
1741 const SCEV *RHS;
1742 if (match(Op, m_scev_URem(m_SCEV(LHS), m_SCEV(RHS), *this)))
1743 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1744 getZeroExtendExpr(RHS, Ty, Depth + 1));
1745 }
1746
1747 // zext(A / B) --> zext(A) / zext(B).
1748 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1749 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1750 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1751
1752 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1753 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1754 if (SA->hasNoUnsignedWrap()) {
1755 // If the addition does not unsign overflow then we can, by definition,
1756 // commute the zero extension with the addition operation.
1758 for (SCEVUse Op : SA->operands())
1759 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1760 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1761 }
1762
1763 const APInt *C, *C2;
1764 // zext (C + A)<nsw> -> (sext(C) + sext(A))<nsw> if zext (C + A)<nsw> >=s 0.
1765 // Currently the non-negative check is done manually, as isKnownNonNegative
1766 // is too expensive.
1767 if (SA->hasNoSignedWrap() &&
1769 m_scev_SMax(m_scev_APInt(C2), m_SCEV()))) &&
1770 C->isNegative() && !C->isMinSignedValue() && C2->sge(C->abs())) {
1771 assert(isKnownNonNegative(SA) && "incorrectly determined non-negative");
1772 return getAddExpr(getSignExtendExpr(SA->getOperand(0), Ty, Depth + 1),
1773 getSignExtendExpr(SA->getOperand(1), Ty, Depth + 1),
1774 SCEV::FlagNSW, Depth + 1);
1775 }
1776
1777 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1778 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1779 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1780 //
1781 // Often address arithmetics contain expressions like
1782 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1783 // This transformation is useful while proving that such expressions are
1784 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1785 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1786 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1787 if (D != 0) {
1788 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1789 const SCEV *SResidual =
1791 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1792 return getAddExpr(SZExtD, SZExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1793 Depth + 1);
1794 }
1795 }
1796 }
1797
1798 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1799 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1800 if (SM->hasNoUnsignedWrap()) {
1801 // If the multiply does not unsign overflow then we can, by definition,
1802 // commute the zero extension with the multiply operation.
1804 for (SCEVUse Op : SM->operands())
1805 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1806 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1807 }
1808
1809 // zext(2^K * (trunc X to iN)) to iM ->
1810 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1811 //
1812 // Proof:
1813 //
1814 // zext(2^K * (trunc X to iN)) to iM
1815 // = zext((trunc X to iN) << K) to iM
1816 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1817 // (because shl removes the top K bits)
1818 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1819 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1820 //
1821 const APInt *C;
1822 const SCEV *TruncRHS;
1823 if (match(SM,
1824 m_scev_Mul(m_scev_APInt(C), m_scev_Trunc(m_SCEV(TruncRHS)))) &&
1825 C->isPowerOf2()) {
1826 int NewTruncBits =
1827 getTypeSizeInBits(SM->getOperand(1)->getType()) - C->logBase2();
1828 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1829 return getMulExpr(
1830 getZeroExtendExpr(SM->getOperand(0), Ty),
1831 getZeroExtendExpr(getTruncateExpr(TruncRHS, NewTruncTy), Ty),
1832 SCEV::FlagNUW, Depth + 1);
1833 }
1834 }
1835
1836 // zext(umin(x, y)) -> umin(zext(x), zext(y))
1837 // zext(umax(x, y)) -> umax(zext(x), zext(y))
1841 for (SCEVUse Operand : MinMax->operands())
1842 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1844 return getUMinExpr(Operands);
1845 return getUMaxExpr(Operands);
1846 }
1847
1848 // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
1850 assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!");
1852 for (SCEVUse Operand : MinMax->operands())
1853 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1854 return getUMinExpr(Operands, /*Sequential*/ true);
1855 }
1856
1857 // The cast wasn't folded; create an explicit cast node.
1858 // Recompute the insert position, as it may have been invalidated.
1859 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1860 return S;
1861 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1862 Op, Ty);
1863 UniqueSCEVs.insert(S, Token);
1864 S->computeAndSetCanonical(*this);
1865 registerUser(S, Op);
1866 return S;
1867}
1868
1870 unsigned Depth) {
1871 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1872 "This is not an extending conversion!");
1873 assert(isSCEVable(Ty) &&
1874 "This is not a conversion to a SCEVable type!");
1875 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1876 Ty = getEffectiveSCEVType(Ty);
1877
1878 FoldID ID(scSignExtend, Op, Ty);
1879 if (const SCEV *S = FoldCache.lookup(ID))
1880 return S;
1881
1882 const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
1884 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1885 return S;
1886}
1887
1889 unsigned Depth) {
1890 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1891 "This is not an extending conversion!");
1892 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1893 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1894 Ty = getEffectiveSCEVType(Ty);
1895
1896 // Fold if the operand is constant.
1897 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1898 return getConstant(SC->getAPInt().sext(getTypeSizeInBits(Ty)));
1899
1900 // sext(sext(x)) --> sext(x)
1902 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1903
1904 // sext(zext(x)) --> zext(x)
1906 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1907
1908 // If the operand is an affine AddRec with the no-signed-wrap flag, the
1909 // sign-extension distributes over the recurrence.
1910 const SCEV *Start, *Step;
1911 const Loop *L;
1912 if (Depth <= MaxCastDepth &&
1913 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1914 const auto *AR = cast<SCEVAddRecExpr>(Op);
1915 if (AR->hasNoSignedWrap()) {
1916 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
1917 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1918 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1919 }
1920 }
1921
1922 // Before doing any expensive analysis, check to see if we've already
1923 // computed a SCEV for this Op and Ty.
1926 ID.AddPointer(Op.getOpaqueValue());
1927 ID.AddPointer(Ty);
1929 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1930 return S;
1931 // Limit recursion depth.
1932 if (Depth > MaxCastDepth) {
1933 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1934 Op, Ty);
1935 UniqueSCEVs.insert(S, Token);
1936 S->computeAndSetCanonical(*this);
1937 registerUser(S, Op);
1938 return S;
1939 }
1940
1941 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1943 // It's possible the bits taken off by the truncate were all sign bits. If
1944 // so, we should be able to simplify this further.
1945 const SCEV *X = ST->getOperand();
1947 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1948 unsigned NewBits = getTypeSizeInBits(Ty);
1949 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1950 CR.sextOrTrunc(NewBits)))
1951 return getTruncateOrSignExtend(X, Ty, Depth);
1952 }
1953
1954 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1955 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1956 if (SA->hasNoSignedWrap()) {
1957 // If the addition does not sign overflow then we can, by definition,
1958 // commute the sign extension with the addition operation.
1960 for (SCEVUse Op : SA->operands())
1961 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1962 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1963 }
1964
1965 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1966 // if D + (C - D + x + y + ...) could be proven to not signed wrap
1967 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1968 //
1969 // For instance, this will bring two seemingly different expressions:
1970 // 1 + sext(5 + 20 * %x + 24 * %y) and
1971 // sext(6 + 20 * %x + 24 * %y)
1972 // to the same form:
1973 // 2 + sext(4 + 20 * %x + 24 * %y)
1974 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1975 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1976 if (D != 0) {
1977 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1978 const SCEV *SResidual =
1980 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1981 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1982 Depth + 1);
1983 }
1984 }
1985 }
1986 // If the input value is a chrec scev, and we can prove that the value
1987 // did not overflow the old, smaller, value, we can sign extend all of the
1988 // operands (often constants). This allows analysis of something like
1989 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1990 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1991 const auto *AR = cast<SCEVAddRecExpr>(Op);
1992 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1993
1994 // The no-signed-wrap case is handled before the uniquing lookup above.
1995
1996 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1997 // Note that this serves two purposes: It filters out loops that are
1998 // simply not analyzable, and it covers the case where this code is
1999 // being called from within backedge-taken count analysis, such that
2000 // attempting to ask for the backedge-taken count would likely result
2001 // in infinite recursion. In the later case, the analysis code will
2002 // cope with a conservative value, and it will take care to purge
2003 // that value once it has finished.
2004 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2005 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2006 // Manually compute the final value for AR, checking for
2007 // overflow.
2008
2009 // Check whether the backedge-taken count can be losslessly casted to
2010 // the addrec's type. The count is always unsigned.
2011 const SCEV *CastedMaxBECount =
2012 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2013 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2014 CastedMaxBECount, MaxBECount->getType(), Depth);
2015 if (MaxBECount == RecastedMaxBECount) {
2016 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2017 // Check whether Start+Step*MaxBECount has no signed overflow.
2018 const SCEV *SMul =
2019 getMulExpr(CastedMaxBECount, Step, SCEV::FlagAnyWrap, Depth + 1);
2020 const SCEV *SAdd = getSignExtendExpr(
2021 getAddExpr(Start, SMul, SCEV::FlagAnyWrap, Depth + 1), WideTy,
2022 Depth + 1);
2023 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2024 const SCEV *WideMaxBECount =
2025 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2026 const SCEV *OperandExtendedAdd =
2027 getAddExpr(WideStart,
2028 getMulExpr(WideMaxBECount,
2029 getSignExtendExpr(Step, WideTy, Depth + 1),
2032 if (SAdd == OperandExtendedAdd) {
2033 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2034 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2035 // Return the expression with the addrec on the outside.
2036 Start =
2038 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2039 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2040 }
2041 // Similar to above, only this time treat the step value as unsigned.
2042 // This covers loops that count up with an unsigned step.
2043 OperandExtendedAdd =
2044 getAddExpr(WideStart,
2045 getMulExpr(WideMaxBECount,
2046 getZeroExtendExpr(Step, WideTy, Depth + 1),
2049 if (SAdd == OperandExtendedAdd) {
2050 // If AR wraps around then
2051 //
2052 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2053 // => SAdd != OperandExtendedAdd
2054 //
2055 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2056 // (SAdd == OperandExtendedAdd => AR is NW)
2057
2058 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2059
2060 // Return the expression with the addrec on the outside.
2061 Start =
2063 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
2064 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2065 }
2066 }
2067 }
2068
2069 auto NewFlags = proveNoSignedWrapViaInduction(AR);
2070 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2071 if (AR->hasNoSignedWrap()) {
2072 // Same as nsw case above - duplicated here to avoid a compile time
2073 // issue. It's not clear that the order of checks does matter, but
2074 // it's one of two issue possible causes for a change which was
2075 // reverted. Be conservative for the moment.
2076 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2077 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2078 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2079 }
2080
2081 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2082 // if D + (C - D + Step * n) could be proven to not signed wrap
2083 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2084 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2085 const APInt &C = SC->getAPInt();
2086 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2087 if (D != 0) {
2088 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2089 const SCEV *SResidual =
2090 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2091 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2092 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
2093 Depth + 1);
2094 }
2095 }
2096
2097 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2098 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2099 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2100 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2101 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2102 }
2103 }
2104
2105 // If the input value is provably positive and we could not simplify
2106 // away the sext build a zext instead.
2108 return getZeroExtendExpr(Op, Ty, Depth + 1);
2109
2110 // sext(smin(x, y)) -> smin(sext(x), sext(y))
2111 // sext(smax(x, y)) -> smax(sext(x), sext(y))
2115 for (SCEVUse Operand : MinMax->operands())
2116 Operands.push_back(getSignExtendExpr(Operand, Ty));
2118 return getSMinExpr(Operands);
2119 return getSMaxExpr(Operands);
2120 }
2121
2122 // The cast wasn't folded; create an explicit cast node.
2123 // Recompute the insert position, as it may have been invalidated.
2124 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
2125 return S;
2126 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2127 Op, Ty);
2128 UniqueSCEVs.insert(S, Token);
2129 S->computeAndSetCanonical(*this);
2130 registerUser(S, Op);
2131 return S;
2132}
2133
2135 switch (Kind) {
2136 case scTruncate:
2137 return getTruncateExpr(Op, Ty);
2138 case scZeroExtend:
2139 return getZeroExtendExpr(Op, Ty);
2140 case scSignExtend:
2141 return getSignExtendExpr(Op, Ty);
2142 case scPtrToAddr: {
2143 const SCEV *Expr = getPtrToAddrExpr(Op);
2144 assert(Expr->getType() == Ty && "requested type must match");
2145 return Expr;
2146 }
2147 default:
2148 llvm_unreachable("Not a SCEV cast expression!");
2149 }
2150}
2151
2152/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2153/// unspecified bits out to the given type.
2155 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2156 "This is not an extending conversion!");
2157 assert(isSCEVable(Ty) &&
2158 "This is not a conversion to a SCEVable type!");
2159 Ty = getEffectiveSCEVType(Ty);
2160
2161 // Sign-extend negative constants.
2162 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2163 if (SC->getAPInt().isNegative())
2164 return getSignExtendExpr(Op, Ty);
2165
2166 // Peel off a truncate cast.
2168 const SCEV *NewOp = T->getOperand();
2169 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2170 return getAnyExtendExpr(NewOp, Ty);
2171 return getTruncateOrNoop(NewOp, Ty);
2172 }
2173
2174 // Next try a zext cast. If the cast is folded, use it.
2175 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2176 if (!isa<SCEVZeroExtendExpr>(ZExt))
2177 return ZExt;
2178
2179 // Next try a sext cast. If the cast is folded, use it.
2180 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2181 if (!isa<SCEVSignExtendExpr>(SExt))
2182 return SExt;
2183
2184 // Force the cast to be folded into the operands of an addrec.
2185 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2187 for (const SCEV *Op : AR->operands())
2188 Ops.push_back(getAnyExtendExpr(Op, Ty));
2189 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2190 }
2191
2192 // If the expression is obviously signed, use the sext cast value.
2193 if (isa<SCEVSMaxExpr>(Op))
2194 return SExt;
2195
2196 // Absent any other information, use the zext cast value.
2197 return ZExt;
2198}
2199
2200/// Process the given Ops list, which is a list of operands to be added under
2201/// the given scale, update the given map. This is a helper function for
2202/// getAddRecExpr. As an example of what it does, given a sequence of operands
2203/// that would form an add expression like this:
2204///
2205/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2206///
2207/// where A and B are constants, update the map with these values:
2208///
2209/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2210///
2211/// and add 13 + A*B*29 to AccumulatedConstant.
2212/// This will allow getAddRecExpr to produce this:
2213///
2214/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2215///
2216/// This form often exposes folding opportunities that are hidden in
2217/// the original operand list.
2218///
2219/// Return true iff it appears that any interesting folding opportunities
2220/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2221/// the common case where no interesting opportunities are present, and
2222/// is also used as a check to avoid infinite recursion.
2225 APInt &AccumulatedConstant,
2227 const APInt &Scale,
2228 ScalarEvolution &SE) {
2229 bool Interesting = false;
2230
2231 // Iterate over the add operands. They are sorted, with constants first.
2232 unsigned i = 0;
2233 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2234 ++i;
2235 // Pull a buried constant out to the outside.
2236 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2237 Interesting = true;
2238 AccumulatedConstant += Scale * C->getAPInt();
2239 }
2240
2241 // Next comes everything else. We're especially interested in multiplies
2242 // here, but they're in the middle, so just visit the rest with one loop.
2243 for (; i != Ops.size(); ++i) {
2245 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2246 APInt NewScale =
2247 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2248 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2249 // A multiplication of a constant with another add; recurse.
2250 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2251 Interesting |= CollectAddOperandsWithScales(
2252 M, NewOps, AccumulatedConstant, Add->operands(), NewScale, SE);
2253 } else {
2254 // A multiplication of a constant with some other value. Update
2255 // the map.
2256 SmallVector<SCEVUse, 4> MulOps(drop_begin(Mul->operands()));
2257 const SCEV *Key = SE.getMulExpr(MulOps);
2258 auto Pair = M.insert({Key, NewScale});
2259 if (Pair.second) {
2260 NewOps.push_back(Pair.first->first);
2261 } else {
2262 Pair.first->second += NewScale;
2263 // The map already had an entry for this value, which may indicate
2264 // a folding opportunity.
2265 Interesting = true;
2266 }
2267 }
2268 } else {
2269 // An ordinary operand. Update the map.
2270 auto Pair = M.insert({Ops[i], Scale});
2271 if (Pair.second) {
2272 NewOps.push_back(Pair.first->first);
2273 } else {
2274 Pair.first->second += Scale;
2275 // The map already had an entry for this value, which may indicate
2276 // a folding opportunity.
2277 Interesting = true;
2278 }
2279 }
2280 }
2281
2282 return Interesting;
2283}
2284
2286 const SCEV *LHS, const SCEV *RHS,
2287 const Instruction *CtxI) {
2289 unsigned);
2290 switch (BinOp) {
2291 default:
2292 llvm_unreachable("Unsupported binary op");
2293 case Instruction::Add:
2295 break;
2296 case Instruction::Sub:
2298 break;
2299 case Instruction::Mul:
2301 break;
2302 }
2303
2304 const SCEV *(ScalarEvolution::*Extension)(SCEVUse, Type *, unsigned) =
2307
2308 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2309 auto *NarrowTy = cast<IntegerType>(LHS->getType());
2310 auto *WideTy =
2311 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2312
2313 const SCEV *A = (this->*Extension)(
2314 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2315 const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2316 const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2317 const SCEV *B = (this->*Operation)(LHSB, RHSB, SCEV::FlagAnyWrap, 0);
2318 if (A == B)
2319 return true;
2320 // Can we use context to prove the fact we need?
2321 if (!CtxI)
2322 return false;
2323 // TODO: Support mul.
2324 if (BinOp == Instruction::Mul)
2325 return false;
2326 auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2327 // TODO: Lift this limitation.
2328 if (!RHSC)
2329 return false;
2330 APInt C = RHSC->getAPInt();
2331 unsigned NumBits = C.getBitWidth();
2332 bool IsSub = (BinOp == Instruction::Sub);
2333 bool IsNegativeConst = (Signed && C.isNegative());
2334 // Compute the direction and magnitude by which we need to check overflow.
2335 bool OverflowDown = IsSub ^ IsNegativeConst;
2336 APInt Magnitude = C;
2337 if (IsNegativeConst) {
2338 if (C == APInt::getSignedMinValue(NumBits))
2339 // TODO: SINT_MIN on inversion gives the same negative value, we don't
2340 // want to deal with that.
2341 return false;
2342 Magnitude = -C;
2343 }
2344
2346 if (OverflowDown) {
2347 // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2348 APInt Min = Signed ? APInt::getSignedMinValue(NumBits)
2349 : APInt::getMinValue(NumBits);
2350 APInt Limit = Min + Magnitude;
2351 return isKnownPredicateAt(Pred, getConstant(Limit), LHS, CtxI);
2352 } else {
2353 // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2354 APInt Max = Signed ? APInt::getSignedMaxValue(NumBits)
2355 : APInt::getMaxValue(NumBits);
2356 APInt Limit = Max - Magnitude;
2357 return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2358 }
2359}
2360
2361std::optional<SCEV::NoWrapFlags>
2363 const OverflowingBinaryOperator *OBO) {
2364 // It cannot be done any better.
2365 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2366 return std::nullopt;
2367
2368 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2369
2370 if (OBO->hasNoUnsignedWrap())
2372 if (OBO->hasNoSignedWrap())
2374
2375 bool Deduced = false;
2376
2378 const SCEV *LHS = getSCEV(OBO->getOperand(0));
2379 const SCEV *RHS = getSCEV(OBO->getOperand(1));
2380
2381 bool CanUseNSW = true;
2382 const APInt *ShiftAmt;
2383 // Treat `shl %a, C` as `mul %a, 1 << C`.
2384 if (match(OBO, m_Shl(m_Value(), m_APInt(ShiftAmt)))) {
2385 unsigned BitWidth = ShiftAmt->getBitWidth();
2386 if (ShiftAmt->uge(BitWidth))
2387 return std::nullopt;
2388 // NSW only transfers if the shift amount is < BitWidth - 1, as INT_MIN * -1
2389 // overflows.
2390 CanUseNSW = ShiftAmt->ult(BitWidth - 1);
2391 Opcode = Instruction::Mul;
2393 } else if (Opcode != Instruction::Add && Opcode != Instruction::Sub &&
2394 Opcode != Instruction::Mul) {
2395 return std::nullopt;
2396 }
2397
2398 const Instruction *CtxI =
2400 if (!OBO->hasNoUnsignedWrap() &&
2401 willNotOverflow(Opcode, /* Signed */ false, LHS, RHS, CtxI)) {
2403 Deduced = true;
2404 }
2405
2406 if (CanUseNSW && !OBO->hasNoSignedWrap() &&
2407 willNotOverflow(Opcode, /* Signed */ true, LHS, RHS, CtxI)) {
2409 Deduced = true;
2410 }
2411
2412 if (Deduced)
2413 return Flags;
2414 return std::nullopt;
2415}
2416
2417// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2418// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2419// can't-overflow flags for the operation if possible.
2423 SCEV::NoWrapFlags Flags) {
2424 using namespace std::placeholders;
2425
2426 using OBO = OverflowingBinaryOperator;
2427
2428 bool CanAnalyze =
2430 (void)CanAnalyze;
2431 assert(CanAnalyze && "don't call from other places!");
2432
2433 SCEV::NoWrapFlags SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2434 SCEV::NoWrapFlags SignOrUnsignWrap =
2435 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2436
2437 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2438 auto IsKnownNonNegative = [&](SCEVUse U) {
2439 return SE->isKnownNonNegative(U);
2440 };
2441
2442 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2443 Flags = ScalarEvolution::setFlags(Flags, SignOrUnsignMask);
2444
2445 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2446
2447 if (SignOrUnsignWrap != SignOrUnsignMask &&
2448 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2449 isa<SCEVConstant>(Ops[0])) {
2450
2451 auto Opcode = [&] {
2452 switch (Type) {
2453 case scAddExpr:
2454 return Instruction::Add;
2455 case scMulExpr:
2456 return Instruction::Mul;
2457 default:
2458 llvm_unreachable("Unexpected SCEV op.");
2459 }
2460 }();
2461
2462 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2463
2464 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2465 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2467 Opcode, C, OBO::NoSignedWrap);
2468 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2470 }
2471
2472 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2473 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2475 Opcode, C, OBO::NoUnsignedWrap);
2476 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2478 }
2479 }
2480
2481 // <0,+,nonnegative><nw> is also nuw
2482 // TODO: Add corresponding nsw case
2484 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2485 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2487
2488 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2490 Ops.size() == 2) {
2491 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2492 if (UDiv->getOperand(1) == Ops[1])
2494 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2495 if (UDiv->getOperand(1) == Ops[0])
2497 }
2498
2499 return Flags;
2500}
2501
2503 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2504}
2505
2506/// Get a canonical add expression, or something simpler if possible.
2508 SCEV::NoWrapFlags OrigFlags,
2509 unsigned Depth) {
2510 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2511 "only nuw or nsw allowed");
2512 assert(!Ops.empty() && "Cannot get empty add!");
2513 if (Ops.size() == 1) return Ops[0];
2514#ifndef NDEBUG
2515 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2516 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2517 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2518 "SCEVAddExpr operand types don't match!");
2519 unsigned NumPtrs = count_if(
2520 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2521 assert(NumPtrs <= 1 && "add has at most one pointer operand");
2522#endif
2523
2524 const SCEV *Folded = constantFoldAndGroupOps(
2525 *this, LI, DT, Ops,
2526 [](const APInt &C1, const APInt &C2) { return C1 + C2; },
2527 [](const APInt &C) { return C.isZero(); }, // identity
2528 [](const APInt &C) { return false; }); // absorber
2529 if (Folded)
2530 return Folded;
2531
2532 unsigned Idx = isa<SCEVConstant>(Ops[0]) ? 1 : 0;
2533
2534 // Delay expensive flag strengthening until necessary.
2535 auto ComputeFlags = [this, OrigFlags](ArrayRef<SCEVUse> Ops) {
2536 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2537 };
2538
2539 // Limit recursion calls depth.
2541 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2542
2543 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2544 // Don't strengthen flags if we have no new information.
2545 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2546 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2547 Add->setNoWrapFlags(ComputeFlags(Ops));
2548 return S;
2549 }
2550
2551 // Okay, check to see if the same value occurs in the operand list more than
2552 // once. If so, merge them together into an multiply expression. Since we
2553 // sorted the list, these values are required to be adjacent.
2554 Type *Ty = Ops[0]->getType();
2555 bool FoundMatch = false;
2556 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2557 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2558 // Scan ahead to count how many equal operands there are.
2559 unsigned Count = 2;
2560 while (i+Count != e && Ops[i+Count] == Ops[i])
2561 ++Count;
2562 // Merge the values into a multiply.
2563 SCEVUse Scale = getConstant(Ty, Count);
2564 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2565 if (Ops.size() == Count)
2566 return Mul;
2567 Ops[i] = Mul;
2568 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2569 --i; e -= Count - 1;
2570 FoundMatch = true;
2571 }
2572 if (FoundMatch)
2573 return getAddExpr(Ops, OrigFlags, Depth + 1);
2574
2575 // Check for truncates. If all the operands are truncated from the same
2576 // type, see if factoring out the truncate would permit the result to be
2577 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2578 // if the contents of the resulting outer trunc fold to something simple.
2579 auto FindTruncSrcType = [&]() -> Type * {
2580 // We're ultimately looking to fold an addrec of truncs and muls of only
2581 // constants and truncs, so if we find any other types of SCEV
2582 // as operands of the addrec then we bail and return nullptr here.
2583 // Otherwise, we return the type of the operand of a trunc that we find.
2584 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2585 return T->getOperand()->getType();
2586 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2587 SCEVUse LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2588 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2589 return T->getOperand()->getType();
2590 }
2591 return nullptr;
2592 };
2593 if (auto *SrcType = FindTruncSrcType()) {
2594 SmallVector<SCEVUse, 8> LargeOps;
2595 bool Ok = true;
2596 // Check all the operands to see if they can be represented in the
2597 // source type of the truncate.
2598 for (const SCEV *Op : Ops) {
2600 if (T->getOperand()->getType() != SrcType) {
2601 Ok = false;
2602 break;
2603 }
2604 LargeOps.push_back(T->getOperand());
2605 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Op)) {
2606 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2607 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Op)) {
2608 SmallVector<SCEVUse, 8> LargeMulOps;
2609 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2610 if (const SCEVTruncateExpr *T =
2611 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2612 if (T->getOperand()->getType() != SrcType) {
2613 Ok = false;
2614 break;
2615 }
2616 LargeMulOps.push_back(T->getOperand());
2617 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2618 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2619 } else {
2620 Ok = false;
2621 break;
2622 }
2623 }
2624 if (Ok)
2625 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2626 } else {
2627 Ok = false;
2628 break;
2629 }
2630 }
2631 if (Ok) {
2632 // Evaluate the expression in the larger type.
2633 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2634 // If it folds to something simple, use it. Otherwise, don't.
2635 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2636 return getTruncateExpr(Fold, Ty);
2637 }
2638 }
2639
2640 if (Ops.size() == 2) {
2641 // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2642 // C2 can be folded in a way that allows retaining wrapping flags of (X +
2643 // C1).
2644 const SCEV *A = Ops[0];
2645 const SCEV *B = Ops[1];
2646 auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2647 auto *C = dyn_cast<SCEVConstant>(A);
2648 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2649 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2650 auto C2 = C->getAPInt();
2651 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2652
2653 APInt ConstAdd = C1 + C2;
2654 auto AddFlags = AddExpr->getNoWrapFlags();
2655 // Adding a smaller constant is NUW if the original AddExpr was NUW.
2657 ConstAdd.ule(C1)) {
2658 PreservedFlags =
2660 }
2661
2662 // Adding a constant with the same sign and small magnitude is NSW, if the
2663 // original AddExpr was NSW.
2665 C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2666 ConstAdd.abs().ule(C1.abs())) {
2667 PreservedFlags =
2669 }
2670
2671 if (PreservedFlags != SCEV::FlagAnyWrap) {
2672 SmallVector<SCEVUse, 4> NewOps(AddExpr->operands());
2673 NewOps[0] = getConstant(ConstAdd);
2674 return getAddExpr(NewOps, PreservedFlags);
2675 }
2676 }
2677
2678 // Try to push the constant operand into a ZExt: A + zext (-A + B) -> zext
2679 // (B), if trunc (A) + -A + B does not unsigned-wrap.
2680 const SCEVAddExpr *InnerAdd;
2681 if (match(B, m_scev_ZExt(m_scev_Add(InnerAdd)))) {
2682 const SCEV *NarrowA = getTruncateExpr(A, InnerAdd->getType());
2683 if (NarrowA == getNegativeSCEV(InnerAdd->getOperand(0)) &&
2684 getZeroExtendExpr(NarrowA, B->getType()) == A &&
2685 hasFlags(StrengthenNoWrapFlags(this, scAddExpr, {NarrowA, InnerAdd},
2687 SCEV::FlagNUW)) {
2688 return getZeroExtendExpr(getAddExpr(NarrowA, InnerAdd), B->getType());
2689 }
2690 }
2691 }
2692
2693 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2694 const SCEV *Y;
2695 if (Ops.size() == 2 &&
2696 match(Ops[0],
2698 m_scev_URem(m_scev_Specific(Ops[1]), m_SCEV(Y), *this))))
2699 return getMulExpr(Y, getUDivExpr(Ops[1], Y));
2700
2701 // Skip past any other cast SCEVs.
2702 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2703 ++Idx;
2704
2705 // If there are add operands they would be next.
2706 if (Idx < Ops.size()) {
2707 bool DeletedAdd = false;
2708 // If the original flags and all inlined SCEVAddExprs are NUW, use the
2709 // common NUW flag for expression after inlining. Other flags cannot be
2710 // preserved, because they may depend on the original order of operations.
2711 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2712 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2713 if (Ops.size() > AddOpsInlineThreshold ||
2714 Add->getNumOperands() > AddOpsInlineThreshold)
2715 break;
2716 // If we have an add, expand the add operands onto the end of the operands
2717 // list.
2718 Ops.erase(Ops.begin()+Idx);
2719 append_range(Ops, Add->operands());
2720 DeletedAdd = true;
2721 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2722 }
2723
2724 // If we deleted at least one add, we added operands to the end of the list,
2725 // and they are not necessarily sorted. Recurse to resort and resimplify
2726 // any operands we just acquired.
2727 if (DeletedAdd)
2728 return getAddExpr(Ops, CommonFlags, Depth + 1);
2729 }
2730
2731 // Skip over the add expression until we get to a multiply.
2732 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2733 ++Idx;
2734
2735 // Check to see if there are any folding opportunities present with
2736 // operands multiplied by constant values.
2737 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2738 uint64_t BitWidth = getTypeSizeInBits(Ty);
2741 APInt AccumulatedConstant(BitWidth, 0);
2742 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2743 Ops, APInt(BitWidth, 1), *this)) {
2744 struct APIntCompare {
2745 bool operator()(const APInt &LHS, const APInt &RHS) const {
2746 return LHS.ult(RHS);
2747 }
2748 };
2749
2750 // Some interesting folding opportunity is present, so its worthwhile to
2751 // re-generate the operands list. Group the operands by constant scale,
2752 // to avoid multiplying by the same constant scale multiple times.
2753 std::map<APInt, SmallVector<SCEVUse, 4>, APIntCompare> MulOpLists;
2754 for (const SCEV *NewOp : NewOps)
2755 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2756 // Re-generate the operands list.
2757 Ops.clear();
2758 if (AccumulatedConstant != 0)
2759 Ops.push_back(getConstant(AccumulatedConstant));
2760 for (auto &MulOp : MulOpLists) {
2761 if (MulOp.first == 1) {
2762 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2763 } else if (MulOp.first != 0) {
2764 Ops.push_back(getMulExpr(
2765 getConstant(MulOp.first),
2766 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2767 SCEV::FlagAnyWrap, Depth + 1));
2768 }
2769 }
2770 if (Ops.empty())
2771 return getZero(Ty);
2772 if (Ops.size() == 1)
2773 return Ops[0];
2774 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2775 }
2776 }
2777
2778 // Given a SCEVMulExpr and an operand index, return the product of all
2779 // operands except the one at OpIdx.
2780 auto StripFactor = [&](const SCEVMulExpr *M, unsigned OpIdx) -> SCEVUse {
2781 if (M->getNumOperands() == 2)
2782 return M->getOperand(OpIdx == 0);
2783 SmallVector<SCEVUse, 4> Remaining(M->operands().take_front(OpIdx));
2784 append_range(Remaining, M->operands().drop_front(OpIdx + 1));
2785 return getMulExpr(Remaining, SCEV::FlagAnyWrap, Depth + 1);
2786 };
2787
2788 // If we are adding something to a multiply expression, make sure the
2789 // something is not already an operand of the multiply. If so, merge it into
2790 // the multiply.
2791 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2792 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2793 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2794 // Scan all terms to find every occurrence of common factor MulOpSCEV
2795 // and fold them in one shot:
2796 // A1*X + A2*X + ... + An*X --> X * (A1 + A2 + ... + An)
2797 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2798 if (isa<SCEVConstant>(MulOpSCEV))
2799 continue;
2800
2801 // Cofactors: 1 for bare addends matching MulOpSCEV, or the
2802 // remaining product for multiply terms containing MulOpSCEV.
2803 SmallVector<SCEVUse, 4> Cofactors;
2804 SmallVector<unsigned, 4> DeadIndices;
2805 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) {
2806 if (MulOpSCEV == Ops[AddOp]) {
2807 // W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2808 Cofactors.push_back(getOne(Ty));
2809 DeadIndices.push_back(AddOp);
2810 continue;
2811 }
2812
2813 if (AddOp <= Idx || !isa<SCEVMulExpr>(Ops[AddOp]))
2814 continue;
2815
2816 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[AddOp]);
2817 for (unsigned OMulOp = 0, OE = OtherMul->getNumOperands(); OMulOp != OE;
2818 ++OMulOp) {
2819 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2820 // (A*B*C) + (A*D*E) --> A * (B*C + D*E)
2821 Cofactors.push_back(StripFactor(OtherMul, OMulOp));
2822 DeadIndices.push_back(AddOp);
2823 break;
2824 }
2825 }
2826 }
2827
2828 // Fold all collected cofactors with the anchor multiply's cofactor:
2829 // MulOpSCEV * (Cofactor_1 + ... + Cofactor_n + AnchorCofactor)
2830 if (!Cofactors.empty()) {
2831 Cofactors.push_back(StripFactor(Mul, MulOp));
2832
2833 SCEVUse InnerSum = getAddExpr(Cofactors, SCEV::FlagAnyWrap, Depth + 1);
2834 SCEVUse OuterMul =
2835 getMulExpr(MulOpSCEV, InnerSum, SCEV::FlagAnyWrap, Depth + 1);
2836
2837 // DeadIndices does not include Idx (the anchor), hence +1.
2838 if (Ops.size() == DeadIndices.size() + 1)
2839 return OuterMul;
2840
2841 // Erase Ops[Idx] first, then erase DeadIndices in reverse order.
2842 // The -1 adjustment accounts for the shift from removing Idx;
2843 // reverse order means each erasure only shifts later positions,
2844 // which have already been processed.
2845 Ops.erase(Ops.begin() + Idx);
2846 for (unsigned Dead : reverse(DeadIndices))
2847 Ops.erase(Ops.begin() + (Dead > Idx ? Dead - 1 : Dead));
2848
2849 Ops.push_back(OuterMul);
2850 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2851 }
2852 }
2853 }
2854
2855 // If there are any add recurrences in the operands list, see if any other
2856 // added values are loop invariant. If so, we can fold them into the
2857 // recurrence.
2858 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2859 ++Idx;
2860
2861 // Scan over all recurrences, trying to fold loop invariants into them.
2862 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2863 // Scan all of the other operands to this add and add them to the vector if
2864 // they are loop invariant w.r.t. the recurrence.
2866 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2867 const Loop *AddRecLoop = AddRec->getLoop();
2868 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2869 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2870 LIOps.push_back(Ops[i]);
2871 Ops.erase(Ops.begin()+i);
2872 --i; --e;
2873 }
2874
2875 // If we found some loop invariants, fold them into the recurrence.
2876 if (!LIOps.empty()) {
2877 // Compute nowrap flags for the addition of the loop-invariant ops and
2878 // the addrec. Temporarily push it as an operand for that purpose. These
2879 // flags are valid in the scope of the addrec only.
2880 LIOps.push_back(AddRec);
2881 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2882 LIOps.pop_back();
2883
2884 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2885 LIOps.push_back(AddRec->getStart());
2886
2887 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2888
2889 // It is not in general safe to propagate flags valid on an add within
2890 // the addrec scope to one outside it. We must prove that the inner
2891 // scope is guaranteed to execute if the outer one does to be able to
2892 // safely propagate. We know the program is undefined if poison is
2893 // produced on the inner scoped addrec. We also know that *for this use*
2894 // the outer scoped add can't overflow (because of the flags we just
2895 // computed for the inner scoped add) without the program being undefined.
2896 // Proving that entry to the outer scope neccesitates entry to the inner
2897 // scope, thus proves the program undefined if the flags would be violated
2898 // in the outer scope.
2899 SCEV::NoWrapFlags AddFlags = Flags;
2900 if (AddFlags != SCEV::FlagAnyWrap) {
2901 auto *DefI = getDefiningScopeBound(LIOps);
2902 auto *ReachI = &*AddRecLoop->getHeader()->begin();
2903 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2904 AddFlags = SCEV::FlagAnyWrap;
2905 }
2906 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2907
2908 // Build the new addrec. Propagate the NUW and NSW flags if both the
2909 // outer add and the inner addrec are guaranteed to have no overflow.
2910 // Always propagate NW.
2911 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2912 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2913
2914 // If all of the other operands were loop invariant, we are done.
2915 if (Ops.size() == 1) return NewRec;
2916
2917 // Otherwise, add the folded AddRec by the non-invariant parts.
2918 for (unsigned i = 0;; ++i)
2919 if (Ops[i] == AddRec) {
2920 Ops[i] = NewRec;
2921 break;
2922 }
2923 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2924 }
2925
2926 // Okay, if there weren't any loop invariants to be folded, check to see if
2927 // there are multiple AddRec's with the same loop induction variable being
2928 // added together. If so, we can fold them.
2929 for (unsigned OtherIdx = Idx+1;
2930 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2931 ++OtherIdx) {
2932 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2933 // so that the 1st found AddRecExpr is dominated by all others.
2934 assert(DT.dominates(
2935 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2936 AddRec->getLoop()->getHeader()) &&
2937 "AddRecExprs are not sorted in reverse dominance order?");
2938 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2939 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2940 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2941 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2942 ++OtherIdx) {
2943 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2944 if (OtherAddRec->getLoop() == AddRecLoop) {
2945 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2946 i != e; ++i) {
2947 if (i >= AddRecOps.size()) {
2948 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
2949 break;
2950 }
2951 AddRecOps[i] =
2952 getAddExpr(AddRecOps[i], OtherAddRec->getOperand(i),
2954 }
2955 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2956 }
2957 }
2958 // Step size has changed, so we cannot guarantee no self-wraparound.
2959 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2960 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2961 }
2962 }
2963
2964 // Otherwise couldn't fold anything into this recurrence. Move onto the
2965 // next one.
2966 }
2967
2968 // Okay, it looks like we really DO need an add expr. Check to see if we
2969 // already have one, otherwise create a new one.
2970 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2971}
2972
2973const SCEV *ScalarEvolution::getOrCreateAddExpr(ArrayRef<SCEVUse> Ops,
2974 SCEV::NoWrapFlags Flags) {
2977 for (SCEVUse Op : Ops)
2978 ID.AddPointer(Op.getOpaqueValue());
2980 SCEVAddExpr *S = static_cast<SCEVAddExpr *>(UniqueSCEVs.lookup(ID, Token));
2981 if (!S) {
2982 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
2984 S = new (SCEVAllocator)
2985 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2986 UniqueSCEVs.insert(S, Token);
2987 S->computeAndSetCanonical(*this);
2988 registerUser(S, Ops);
2989 }
2990 S->setNoWrapFlags(Flags);
2991 return S;
2992}
2993
2994const SCEV *ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<SCEVUse> Ops,
2995 const Loop *L,
2996 SCEV::NoWrapFlags Flags) {
2997 FoldingSetNodeID ID;
2998 ID.AddInteger(scAddRecExpr);
2999 for (SCEVUse Op : Ops)
3000 ID.AddPointer(Op.getOpaqueValue());
3001 ID.AddPointer(L);
3002 FoldingSetInsertToken Token;
3003 SCEVAddRecExpr *S =
3004 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.lookup(ID, Token));
3005 if (!S) {
3006 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3008 S = new (SCEVAllocator)
3009 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
3010 UniqueSCEVs.insert(S, Token);
3011 S->computeAndSetCanonical(*this);
3012 LoopUsers[L].push_back(S);
3013 registerUser(S, Ops);
3014 }
3015 setNoWrapFlags(S, Flags);
3016 return S;
3017}
3018
3019const SCEV *ScalarEvolution::getOrCreateMulExpr(ArrayRef<SCEVUse> Ops,
3020 SCEV::NoWrapFlags Flags) {
3021 FoldingSetNodeID ID;
3022 ID.AddInteger(scMulExpr);
3023 for (SCEVUse Op : Ops)
3024 ID.AddPointer(Op.getOpaqueValue());
3025 FoldingSetInsertToken Token;
3026 SCEVMulExpr *S = static_cast<SCEVMulExpr *>(UniqueSCEVs.lookup(ID, Token));
3027 if (!S) {
3028 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3030 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
3031 O, Ops.size());
3032 UniqueSCEVs.insert(S, Token);
3033 S->computeAndSetCanonical(*this);
3034 registerUser(S, Ops);
3035 }
3036 S->setNoWrapFlags(Flags);
3037 return S;
3038}
3039
3040const SCEV *ScalarEvolution::getOrCreateUDivExpr(SCEVUse LHS, SCEVUse RHS) {
3041 FoldingSetNodeID ID;
3042 ID.AddInteger(scUDivExpr);
3043 ID.AddPointer(LHS.getOpaqueValue());
3044 ID.AddPointer(RHS.getOpaqueValue());
3045 FoldingSetInsertToken Token;
3046 SCEV *S = UniqueSCEVs.lookup(ID, Token);
3047 if (!S) {
3048 S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), LHS, RHS);
3049 UniqueSCEVs.insert(S, Token);
3050 S->computeAndSetCanonical(*this);
3052 }
3053 return S;
3054}
3055
3056static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
3057 uint64_t k = i*j;
3058 if (j > 1 && k / j != i) Overflow = true;
3059 return k;
3060}
3061
3062/// Compute the result of "n choose k", the binomial coefficient. If an
3063/// intermediate computation overflows, Overflow will be set and the return will
3064/// be garbage. Overflow is not cleared on absence of overflow.
3065static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3066 // We use the multiplicative formula:
3067 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3068 // At each iteration, we take the n-th term of the numeral and divide by the
3069 // (k-n)th term of the denominator. This division will always produce an
3070 // integral result, and helps reduce the chance of overflow in the
3071 // intermediate computations. However, we can still overflow even when the
3072 // final result would fit.
3073
3074 if (n == 0 || n == k) return 1;
3075 if (k > n) return 0;
3076
3077 if (k > n/2)
3078 k = n-k;
3079
3080 uint64_t r = 1;
3081 for (uint64_t i = 1; i <= k; ++i) {
3082 r = umul_ov(r, n-(i-1), Overflow);
3083 r /= i;
3084 }
3085 return r;
3086}
3087
3088/// Determine if any of the operands in this SCEV are a constant or if
3089/// any of the add or multiply expressions in this SCEV contain a constant.
3090static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3091 struct FindConstantInAddMulChain {
3092 bool FoundConstant = false;
3093
3094 bool follow(const SCEV *S) {
3095 FoundConstant |= isa<SCEVConstant>(S);
3096 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3097 }
3098
3099 bool isDone() const {
3100 return FoundConstant;
3101 }
3102 };
3103
3104 FindConstantInAddMulChain F;
3106 ST.visitAll(StartExpr);
3107 return F.FoundConstant;
3108}
3109
3110/// Get a canonical multiply expression, or something simpler if possible.
3112 SCEV::NoWrapFlags OrigFlags,
3113 unsigned Depth) {
3114 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3115 "only nuw or nsw allowed");
3116 assert(!Ops.empty() && "Cannot get empty mul!");
3117 if (Ops.size() == 1) return Ops[0];
3118#ifndef NDEBUG
3119 Type *ETy = Ops[0]->getType();
3120 assert(!ETy->isPointerTy());
3121 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3122 assert(Ops[i]->getType() == ETy &&
3123 "SCEVMulExpr operand types don't match!");
3124#endif
3125
3126 const SCEV *Folded = constantFoldAndGroupOps(
3127 *this, LI, DT, Ops,
3128 [](const APInt &C1, const APInt &C2) { return C1 * C2; },
3129 [](const APInt &C) { return C.isOne(); }, // identity
3130 [](const APInt &C) { return C.isZero(); }); // absorber
3131 if (Folded)
3132 return Folded;
3133
3134 // Delay expensive flag strengthening until necessary.
3135 auto ComputeFlags = [this, OrigFlags](const ArrayRef<SCEVUse> Ops) {
3136 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3137 };
3138
3139 // Limit recursion calls depth.
3141 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3142
3143 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3144 // Don't strengthen flags if we have no new information.
3145 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3146 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3147 Mul->setNoWrapFlags(ComputeFlags(Ops));
3148 return S;
3149 }
3150
3151 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3152 if (Ops.size() == 2) {
3153 // C1*(C2+V) -> C1*C2 + C1*V
3154 // If any of Add's ops are Adds or Muls with a constant, apply this
3155 // transformation as well.
3156 //
3157 // TODO: There are some cases where this transformation is not
3158 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
3159 // this transformation should be narrowed down.
3160 const SCEV *Op0, *Op1;
3161 if (match(Ops[1], m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))) &&
3163 const SCEV *LHS = getMulExpr(LHSC, Op0, SCEV::FlagAnyWrap, Depth + 1);
3164 const SCEV *RHS = getMulExpr(LHSC, Op1, SCEV::FlagAnyWrap, Depth + 1);
3165 return getAddExpr(LHS, RHS, SCEV::FlagAnyWrap, Depth + 1);
3166 }
3167
3168 if (Ops[0]->isAllOnesValue()) {
3169 // If we have a mul by -1 of an add, try distributing the -1 among the
3170 // add operands.
3171 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3173 bool AnyFolded = false;
3174 for (const SCEV *AddOp : Add->operands()) {
3175 const SCEV *Mul = getMulExpr(Ops[0], SCEVUse(AddOp),
3177 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3178 NewOps.push_back(Mul);
3179 }
3180 if (AnyFolded)
3181 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3182 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3183 // Negation preserves a recurrence's no self-wrap property.
3185 for (const SCEV *AddRecOp : AddRec->operands())
3186 Operands.push_back(getMulExpr(Ops[0], SCEVUse(AddRecOp),
3187 SCEV::FlagAnyWrap, Depth + 1));
3188 // Let M be the minimum representable signed value. AddRec with nsw
3189 // multiplied by -1 can have signed overflow if and only if it takes a
3190 // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3191 // maximum signed value. In all other cases signed overflow is
3192 // impossible.
3193 auto FlagsMask = SCEV::FlagNW;
3194 if (AddRec->hasNoSignedWrap()) {
3195 auto MinInt =
3196 APInt::getSignedMinValue(getTypeSizeInBits(AddRec->getType()));
3197 if (getSignedRangeMin(AddRec) != MinInt)
3198 FlagsMask = setFlags(FlagsMask, SCEV::FlagNSW);
3199 }
3200 return getAddRecExpr(Operands, AddRec->getLoop(),
3201 AddRec->getNoWrapFlags(FlagsMask));
3202 }
3203 }
3204
3205 // Try to push the constant operand into a ZExt: C * zext (A + B) ->
3206 // zext (C*A + C*B) if trunc (C) * (A + B) does not unsigned-wrap.
3207 const SCEVAddExpr *InnerAdd;
3208 if (match(Ops[1], m_scev_ZExt(m_scev_Add(InnerAdd)))) {
3209 const SCEV *NarrowC = getTruncateExpr(LHSC, InnerAdd->getType());
3210 if (isa<SCEVConstant>(InnerAdd->getOperand(0)) &&
3211 getZeroExtendExpr(NarrowC, Ops[1]->getType()) == LHSC &&
3212 hasFlags(StrengthenNoWrapFlags(this, scMulExpr, {NarrowC, InnerAdd},
3214 SCEV::FlagNUW)) {
3215 auto *Res = getMulExpr(NarrowC, InnerAdd, SCEV::FlagNUW, Depth + 1);
3216 return getZeroExtendExpr(Res, Ops[1]->getType(), Depth + 1);
3217 };
3218 }
3219
3220 // Try to fold (C1 * D /u C2) -> C1/C2 * D, if C1 and C2 are powers-of-2,
3221 // D is a multiple of C2, and C1 is a multiple of C2. If C2 is a multiple
3222 // of C1, fold to (D /u (C2 /u C1)).
3223 const SCEV *D;
3224 APInt C1V = LHSC->getAPInt();
3225 // (C1 * D /u C2) == -1 * -C1 * D /u C2 when C1 != INT_MIN. Don't treat -1
3226 // as -1 * 1, as it won't enable additional folds.
3227 if (C1V.isNegative() && !C1V.isMinSignedValue() && !C1V.isAllOnes())
3228 C1V = C1V.abs();
3229 const SCEVConstant *C2;
3230 if (C1V.isPowerOf2() &&
3232 C2->getAPInt().isPowerOf2() &&
3233 C1V.logBase2() <= getMinTrailingZeros(D)) {
3234 const SCEV *NewMul = nullptr;
3235 if (C1V.uge(C2->getAPInt())) {
3236 NewMul = getMulExpr(getUDivExpr(getConstant(C1V), C2), D);
3237 } else if (C2->getAPInt().logBase2() <= getMinTrailingZeros(D)) {
3238 assert(C1V.ugt(1) && "C1 <= 1 should have been folded earlier");
3239 NewMul = getUDivExpr(D, getUDivExpr(C2, getConstant(C1V)));
3240 }
3241 if (NewMul)
3242 return C1V == LHSC->getAPInt() ? NewMul : getNegativeSCEV(NewMul);
3243 }
3244 }
3245 }
3246
3247 // Skip over the add expression until we get to a multiply.
3248 unsigned Idx = 0;
3249 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3250 ++Idx;
3251
3252 // If there are mul operands inline them all into this expression.
3253 if (Idx < Ops.size()) {
3254 bool DeletedMul = false;
3255 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3256 if (Ops.size() > MulOpsInlineThreshold)
3257 break;
3258 // If we have an mul, expand the mul operands onto the end of the
3259 // operands list.
3260 Ops.erase(Ops.begin()+Idx);
3261 append_range(Ops, Mul->operands());
3262 DeletedMul = true;
3263 }
3264
3265 // If we deleted at least one mul, we added operands to the end of the
3266 // list, and they are not necessarily sorted. Recurse to resort and
3267 // resimplify any operands we just acquired.
3268 if (DeletedMul)
3269 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3270 }
3271
3272 // If there are any add recurrences in the operands list, see if any other
3273 // added values are loop invariant. If so, we can fold them into the
3274 // recurrence.
3275 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3276 ++Idx;
3277
3278 // Scan over all recurrences, trying to fold loop invariants into them.
3279 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3280 // Scan all of the other operands to this mul and add them to the vector
3281 // if they are loop invariant w.r.t. the recurrence.
3283 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3284 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3285 if (isAvailableAtLoopEntry(Ops[i], AddRec->getLoop())) {
3286 LIOps.push_back(Ops[i]);
3287 Ops.erase(Ops.begin()+i);
3288 --i; --e;
3289 }
3290
3291 // If we found some loop invariants, fold them into the recurrence.
3292 if (!LIOps.empty()) {
3293 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3295 NewOps.reserve(AddRec->getNumOperands());
3296 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3297
3298 // If both the mul and addrec are nuw, we can preserve nuw.
3299 // If both the mul and addrec are nsw, we can only preserve nsw if either
3300 // a) they are also nuw, or
3301 // b) all multiplications of addrec operands with scale are nsw.
3302 SCEV::NoWrapFlags Flags =
3303 AddRec->getNoWrapFlags(ComputeFlags({Scale, AddRec}));
3304
3305 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3306 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3307 SCEV::FlagAnyWrap, Depth + 1));
3308
3309 if (hasFlags(Flags, SCEV::FlagNSW) && !hasFlags(Flags, SCEV::FlagNUW)) {
3311 Instruction::Mul, getSignedRange(Scale),
3313 if (!NSWRegion.contains(getSignedRange(AddRec->getOperand(i))))
3314 Flags = clearFlags(Flags, SCEV::FlagNSW);
3315 }
3316 }
3317
3318 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(), Flags);
3319
3320 // If all of the other operands were loop invariant, we are done.
3321 if (Ops.size() == 1) return NewRec;
3322
3323 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3324 for (unsigned i = 0;; ++i)
3325 if (Ops[i] == AddRec) {
3326 Ops[i] = NewRec;
3327 break;
3328 }
3329 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3330 }
3331
3332 // Okay, if there weren't any loop invariants to be folded, check to see
3333 // if there are multiple AddRec's with the same loop induction variable
3334 // being multiplied together. If so, we can fold them.
3335
3336 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3337 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3338 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3339 // ]]],+,...up to x=2n}.
3340 // Note that the arguments to choose() are always integers with values
3341 // known at compile time, never SCEV objects.
3342 //
3343 // The implementation avoids pointless extra computations when the two
3344 // addrec's are of different length (mathematically, it's equivalent to
3345 // an infinite stream of zeros on the right).
3346 bool OpsModified = false;
3347 for (unsigned OtherIdx = Idx+1;
3348 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3349 ++OtherIdx) {
3350 const SCEVAddRecExpr *OtherAddRec =
3351 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3352 if (!OtherAddRec || OtherAddRec->getLoop() != AddRec->getLoop())
3353 continue;
3354
3355 // Limit max number of arguments to avoid creation of unreasonably big
3356 // SCEVAddRecs with very complex operands.
3357 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3358 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3359 continue;
3360
3361 bool Overflow = false;
3362 Type *Ty = AddRec->getType();
3363 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3364 SmallVector<SCEVUse, 7> AddRecOps;
3365 for (int x = 0, xe = AddRec->getNumOperands() +
3366 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3368 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3369 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3370 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3371 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3372 z < ze && !Overflow; ++z) {
3373 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3374 uint64_t Coeff;
3375 if (LargerThan64Bits)
3376 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3377 else
3378 Coeff = Coeff1*Coeff2;
3379 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3380 const SCEV *Term1 = AddRec->getOperand(y-z);
3381 const SCEV *Term2 = OtherAddRec->getOperand(z);
3382 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3383 SCEV::FlagAnyWrap, Depth + 1));
3384 }
3385 }
3386 if (SumOps.empty())
3387 SumOps.push_back(getZero(Ty));
3388 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3389 }
3390 if (!Overflow) {
3391 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
3393 if (Ops.size() == 2) return NewAddRec;
3394 Ops[Idx] = NewAddRec;
3395 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3396 OpsModified = true;
3397 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3398 if (!AddRec)
3399 break;
3400 }
3401 }
3402 if (OpsModified)
3403 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3404
3405 // Otherwise couldn't fold anything into this recurrence. Move onto the
3406 // next one.
3407 }
3408
3409 // Okay, it looks like we really DO need an mul expr. Check to see if we
3410 // already have one, otherwise create a new one.
3411 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3412}
3413
3414/// Represents an unsigned remainder expression based on unsigned division.
3416 assert(getEffectiveSCEVType(LHS->getType()) ==
3417 getEffectiveSCEVType(RHS->getType()) &&
3418 "SCEVURemExpr operand types don't match!");
3419
3420 // Short-circuit easy cases
3421 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3422 // If constant is one, the result is trivial
3423 if (RHSC->getValue()->isOne())
3424 return getZero(LHS->getType()); // X urem 1 --> 0
3425
3426 // If constant is a power of two, fold into a zext(trunc(LHS)).
3427 if (RHSC->getAPInt().isPowerOf2()) {
3428 Type *FullTy = LHS->getType();
3429 Type *TruncTy =
3430 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3431 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3432 }
3433 }
3434
3435 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3436 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3437 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3438 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3439}
3440
3441/// Get a canonical unsigned division expression, or something simpler if
3442/// possible.
3444 assert(!LHS->getType()->isPointerTy() &&
3445 "SCEVUDivExpr operand can't be pointer!");
3446 assert(LHS->getType() == RHS->getType() &&
3447 "SCEVUDivExpr operand types don't match!");
3448
3449 if (SCEV *S =
3450 findExistingSCEVInCache(scUDivExpr, ArrayRef<SCEVUse>({LHS, RHS})))
3451 return S;
3452
3453 // 0 udiv Y == 0
3454 if (match(LHS, m_scev_Zero()))
3455 return LHS;
3456
3457 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3458 if (RHSC->getValue()->isOne())
3459 return LHS; // X udiv 1 --> x
3460 // If the denominator is zero, the result of the udiv is undefined. Don't
3461 // try to analyze it, because the resolution chosen here may differ from
3462 // the resolution chosen in other parts of the compiler.
3463 if (!RHSC->getValue()->isZero()) {
3464 // Determine if the division can be folded into the operands of
3465 // its operands.
3466 // TODO: Generalize this to non-constants by using known-bits information.
3467 Type *Ty = LHS->getType();
3468 unsigned LZ = RHSC->getAPInt().countl_zero();
3469 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3470 // For non-power-of-two values, effectively round the value up to the
3471 // nearest power of two.
3472 if (!RHSC->getAPInt().isPowerOf2())
3473 ++MaxShiftAmt;
3474 IntegerType *ExtTy =
3475 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3476 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3477 if (const SCEVConstant *Step =
3478 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3479 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3480 const APInt &StepInt = Step->getAPInt();
3481 const APInt &DivInt = RHSC->getAPInt();
3482 if (!StepInt.urem(DivInt) &&
3483 getZeroExtendExpr(AR, ExtTy) ==
3484 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3485 getZeroExtendExpr(Step, ExtTy),
3486 AR->getLoop(), SCEV::FlagAnyWrap)) {
3488 for (const SCEV *Op : AR->operands())
3489 Operands.push_back(getUDivExpr(Op, RHS));
3490 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3491 }
3492 /// Get a canonical UDivExpr for a recurrence.
3493 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3494 const APInt *StartRem;
3495 if (!DivInt.urem(StepInt) && match(getURemExpr(AR->getStart(), Step),
3496 m_scev_APInt(StartRem))) {
3497 bool NoWrap =
3498 getZeroExtendExpr(AR, ExtTy) ==
3499 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3500 getZeroExtendExpr(Step, ExtTy), AR->getLoop(),
3502
3503 // With N <= C and both N, C as powers-of-2, the transformation
3504 // {X,+,N}/C => {(X - X%N),+,N}/C preserves division results even
3505 // if wrapping occurs, as the division results remain equivalent for
3506 // all offsets in [[(X - X%N), X).
3507 bool CanFoldWithWrap = StepInt.ule(DivInt) && // N <= C
3508 StepInt.isPowerOf2() && DivInt.isPowerOf2();
3509 // Only fold if the subtraction can be folded in the start
3510 // expression.
3511 const SCEV *NewStart =
3512 getMinusSCEV(AR->getStart(), getConstant(*StartRem));
3513 if (*StartRem != 0 && (NoWrap || CanFoldWithWrap) &&
3514 !isa<SCEVAddExpr>(NewStart)) {
3515 const SCEV *NewLHS =
3516 getAddRecExpr(NewStart, Step, AR->getLoop(),
3517 NoWrap ? SCEV::FlagNW : SCEV::FlagAnyWrap);
3518 if (LHS != NewLHS)
3519 return getUDivExpr(NewLHS, RHS);
3520 }
3521 }
3522 }
3523 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3524 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3525 if (M->hasNoUnsignedWrap()) {
3526 // Find an operand that's safely divisible.
3527 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3528 const SCEV *Op = M->getOperand(i);
3529 const SCEV *Div = getUDivExpr(Op, RHSC);
3530 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3531 SmallVector<SCEVUse, 4> Operands(M->operands());
3532 Operands[i] = Div;
3533 return getMulExpr(Operands);
3534 }
3535 }
3536
3537 // Even if it's not divisible, try to remove a common factor.
3538 if (const auto *LHSC = dyn_cast<SCEVConstant>(M->getOperand(0))) {
3539 APInt Factor = APIntOps::GreatestCommonDivisor(LHSC->getAPInt(),
3540 RHSC->getAPInt());
3541 if (!Factor.isIntN(1)) {
3542 SmallVector<SCEVUse, 2> NewOperands;
3543 NewOperands.push_back(getConstant(LHSC->getAPInt().udiv(Factor)));
3544 append_range(NewOperands, M->operands().drop_front());
3545 const SCEV *NewMul = getMulExpr(NewOperands);
3546 return getUDivExpr(NewMul,
3547 getConstant(RHSC->getAPInt().udiv(Factor)));
3548 }
3549 }
3550 }
3551 }
3552
3553 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3554 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3555 if (auto *DivisorConstant =
3556 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3557 bool Overflow = false;
3558 APInt NewRHS =
3559 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3560 if (Overflow) {
3561 return getConstant(RHSC->getType(), 0, false);
3562 }
3563 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3564 }
3565 }
3566
3567 // (A+B)/C --> (A/C + B/C) if the add does not unsigned wrap and A/C and
3568 // B/C can be folded.
3569 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3570 if (A->hasNoUnsignedWrap()) {
3572 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3573 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3574 if (isa<SCEVUDivExpr>(Op) ||
3575 getMulExpr(Op, RHS) != A->getOperand(i))
3576 break;
3577 Operands.push_back(Op);
3578 }
3579 if (Operands.size() == A->getNumOperands())
3580 return getAddExpr(Operands);
3581 }
3582 }
3583
3584 // ((N - M) + (M * A)) / N --> ((N - 1) + (M * A)) / N
3585 // This is an idiom for rounding A up to the next multiple of N, where A
3586 // is aready known to be a multiple of M. In this case, instcombine can
3587 // see that some low bits of the added constant are unused, so can clear
3588 // them, but we want to canonicalise to set the low bits. This makes the
3589 // pattern easier to match, without needing to check for known bits in
3590 // A*M.
3591 const APInt &N = RHSC->getAPInt();
3592 const APInt *NMinusM, *M;
3593 const SCEV *A;
3594 if (match(LHS, m_scev_Add(m_scev_APInt(NMinusM),
3595 m_scev_Mul(m_scev_APInt(M), m_SCEV(A))))) {
3596 if (N.isPowerOf2() && M->isPowerOf2() && M->ult(N) &&
3597 *NMinusM == N - *M) {
3598 return getUDivExpr(
3600 RHS);
3601 }
3602 }
3603
3604 // Fold if both operands are constant.
3605 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3606 return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3607 }
3608 }
3609
3610 // ((-C + (C smax %x)) /u %x) evaluates to zero, for any positive constant C.
3611 const APInt *NegC, *C;
3612 if (match(LHS,
3615 NegC->isNegative() && !NegC->isMinSignedValue() && *C == -*NegC)
3616 return getZero(LHS->getType());
3617
3618 // (%a * %b)<nuw> / %b -> %a
3619 const auto *Mul = dyn_cast<SCEVMulExpr>(LHS);
3620 if (Mul && Mul->hasNoUnsignedWrap()) {
3621 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3622 if (Mul->getOperand(i) == RHS) {
3624 append_range(Operands, Mul->operands().take_front(i));
3625 append_range(Operands, Mul->operands().drop_front(i + 1));
3626 return getMulExpr(Operands);
3627 }
3628 }
3629 }
3630
3631 // TODO: Generalize to handle any common factors.
3632 // udiv (mul nuw a, vscale), (mul nuw b, vscale) --> udiv a, b
3633 const SCEV *NewLHS, *NewRHS;
3634 if (match(LHS, m_scev_c_NUWMul(m_SCEV(NewLHS), m_SCEVVScale())) &&
3635 match(RHS, m_scev_c_NUWMul(m_SCEV(NewRHS), m_SCEVVScale())))
3636 return getUDivExpr(NewLHS, NewRHS);
3637
3638 return getOrCreateUDivExpr(LHS, RHS);
3639}
3640
3641/// Get a canonical unsigned division expression, or something simpler if
3642/// possible. There is no representation for an exact udiv in SCEV IR, but we
3643/// can attempt to optimize it prior to construction.
3645 // Currently there is no exact specific logic.
3646
3647 return getUDivExpr(LHS, RHS);
3648}
3649
3650/// Get an add recurrence expression for the specified loop. Simplify the
3651/// expression as much as possible.
3653 const Loop *L,
3654 SCEV::NoWrapFlags Flags) {
3656 Operands.push_back(Start);
3657 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3658 if (StepChrec->getLoop() == L) {
3659 append_range(Operands, StepChrec->operands());
3660 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3661 }
3662
3663 Operands.push_back(Step);
3664 return getAddRecExpr(Operands, L, Flags);
3665}
3666
3667/// Get an add recurrence expression for the specified loop. Simplify the
3668/// expression as much as possible.
3670 const Loop *L,
3671 SCEV::NoWrapFlags Flags) {
3672 if (Operands.size() == 1) return Operands[0];
3673#ifndef NDEBUG
3675 for (const SCEV *Op : llvm::drop_begin(Operands)) {
3676 assert(getEffectiveSCEVType(Op->getType()) == ETy &&
3677 "SCEVAddRecExpr operand types don't match!");
3678 assert(!Op->getType()->isPointerTy() && "Step must be integer");
3679 }
3680 for (const SCEV *Op : Operands)
3682 "SCEVAddRecExpr operand is not available at loop entry!");
3683#endif
3684
3685 if (Operands.back()->isZero()) {
3686 Operands.pop_back();
3687 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3688 }
3689
3690 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3691 // use that information to infer NUW and NSW flags. However, computing a
3692 // BE count requires calling getAddRecExpr, so we may not yet have a
3693 // meaningful BE count at this point (and if we don't, we'd be stuck
3694 // with a SCEVCouldNotCompute as the cached BE count).
3695
3696 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3697
3698 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3699 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3700 const Loop *NestedLoop = NestedAR->getLoop();
3701 if (L->contains(NestedLoop)
3702 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3703 : (!NestedLoop->contains(L) &&
3704 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3705 SmallVector<SCEVUse, 4> NestedOperands(NestedAR->operands());
3706 Operands[0] = NestedAR->getStart();
3707 // AddRecs require their operands be loop-invariant with respect to their
3708 // loops. Don't perform this transformation if it would break this
3709 // requirement.
3710 bool AllInvariant = all_of(
3711 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3712
3713 if (AllInvariant) {
3714 // Create a recurrence for the outer loop with the same step size.
3715 //
3716 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3717 // inner recurrence has the same property.
3718 SCEV::NoWrapFlags OuterFlags =
3719 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3720
3721 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3722 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3723 return isLoopInvariant(Op, NestedLoop);
3724 });
3725
3726 if (AllInvariant) {
3727 // Ok, both add recurrences are valid after the transformation.
3728 //
3729 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3730 // the outer recurrence has the same property.
3731 SCEV::NoWrapFlags InnerFlags =
3732 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3733 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3734 }
3735 }
3736 // Reset Operands to its original state.
3737 Operands[0] = NestedAR;
3738 }
3739 }
3740
3741 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3742 // already have one, otherwise create a new one.
3743 return getOrCreateAddRecExpr(Operands, L, Flags);
3744}
3745
3747 ArrayRef<SCEVUse> IndexExprs) {
3748 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3749 // getSCEV(Base)->getType() has the same address space as Base->getType()
3750 // because SCEV::getType() preserves the address space.
3751 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
3752 if (NW != GEPNoWrapFlags::none()) {
3753 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3754 // but to do that, we have to ensure that said flag is valid in the entire
3755 // defined scope of the SCEV.
3756 // TODO: non-instructions have global scope. We might be able to prove
3757 // some global scope cases
3758 auto *GEPI = dyn_cast<Instruction>(GEP);
3759 if (!GEPI || !isSCEVExprNeverPoison(GEPI))
3760 NW = GEPNoWrapFlags::none();
3761 }
3762
3763 return getGEPExpr(BaseExpr, IndexExprs, GEP->getSourceElementType(), NW);
3764}
3765
3767 ArrayRef<SCEVUse> IndexExprs,
3768 Type *SrcElementTy, GEPNoWrapFlags NW) {
3770 if (NW.hasNoUnsignedSignedWrap())
3771 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNSW);
3772 if (NW.hasNoUnsignedWrap())
3773 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNUW);
3774
3775 Type *CurTy = BaseExpr->getType();
3776 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3777 bool FirstIter = true;
3779 for (SCEVUse IndexExpr : IndexExprs) {
3780 // Compute the (potentially symbolic) offset in bytes for this index.
3781 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3782 // For a struct, add the member offset.
3783 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3784 unsigned FieldNo = Index->getZExtValue();
3785 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3786 Offsets.push_back(FieldOffset);
3787
3788 // Update CurTy to the type of the field at Index.
3789 CurTy = STy->getTypeAtIndex(Index);
3790 } else {
3791 // Update CurTy to its element type.
3792 if (FirstIter) {
3793 assert(isa<PointerType>(CurTy) &&
3794 "The first index of a GEP indexes a pointer");
3795 CurTy = SrcElementTy;
3796 FirstIter = false;
3797 } else {
3798 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3799 }
3800 // For an array, add the element offset, explicitly scaled.
3801 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3802 // Getelementptr indices are signed.
3803 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3804
3805 // Multiply the index by the element size to compute the element offset.
3806 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3807 Offsets.push_back(LocalOffset);
3808 }
3809 }
3810
3811 // Handle degenerate case of GEP without offsets.
3812 if (Offsets.empty())
3813 return BaseExpr;
3814
3815 // Add the offsets together, assuming nsw if inbounds.
3816 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3817 // Add the base address and the offset. We cannot use the nsw flag, as the
3818 // base address is unsigned. However, if we know that the offset is
3819 // non-negative, we can use nuw.
3820 bool NUW = NW.hasNoUnsignedWrap() ||
3823 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3824 assert(BaseExpr->getType() == GEPExpr->getType() &&
3825 "GEP should not change type mid-flight.");
3826 return GEPExpr;
3827}
3828
3829SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3832 ID.AddInteger(SCEVType);
3833 for (SCEVUse Op : Ops)
3834 ID.AddPointer(Op.getOpaqueValue());
3836 return UniqueSCEVs.lookup(ID, Token);
3837}
3838
3839const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3841 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3842}
3843
3846 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3847 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3848 if (Ops.size() == 1) return Ops[0];
3849#ifndef NDEBUG
3850 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3851 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3852 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3853 "Operand types don't match!");
3854 assert(Ops[0]->getType()->isPointerTy() ==
3855 Ops[i]->getType()->isPointerTy() &&
3856 "min/max should be consistently pointerish");
3857 }
3858#endif
3859
3860 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3861 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3862
3863 const SCEV *Folded = constantFoldAndGroupOps(
3864 *this, LI, DT, Ops,
3865 [&](const APInt &C1, const APInt &C2) {
3866 switch (Kind) {
3867 case scSMaxExpr:
3868 return APIntOps::smax(C1, C2);
3869 case scSMinExpr:
3870 return APIntOps::smin(C1, C2);
3871 case scUMaxExpr:
3872 return APIntOps::umax(C1, C2);
3873 case scUMinExpr:
3874 return APIntOps::umin(C1, C2);
3875 default:
3876 llvm_unreachable("Unknown SCEV min/max opcode");
3877 }
3878 },
3879 [&](const APInt &C) {
3880 // identity
3881 if (IsMax)
3882 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3883 else
3884 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3885 },
3886 [&](const APInt &C) {
3887 // absorber
3888 if (IsMax)
3889 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3890 else
3891 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3892 });
3893 if (Folded)
3894 return Folded;
3895
3896 // Check if we have created the same expression before.
3897 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3898 return S;
3899 }
3900
3901 // Find the first operation of the same kind
3902 unsigned Idx = 0;
3903 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3904 ++Idx;
3905
3906 // Check to see if one of the operands is of the same kind. If so, expand its
3907 // operands onto our operand list, and recurse to simplify.
3908 if (Idx < Ops.size()) {
3909 bool DeletedAny = false;
3910 while (Ops[Idx]->getSCEVType() == Kind) {
3911 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3912 Ops.erase(Ops.begin()+Idx);
3913 append_range(Ops, SMME->operands());
3914 DeletedAny = true;
3915 }
3916
3917 if (DeletedAny)
3918 return getMinMaxExpr(Kind, Ops);
3919 }
3920
3921 // Okay, check to see if the same value occurs in the operand list twice. If
3922 // so, delete one. Since we sorted the list, these values are required to
3923 // be adjacent.
3928 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3929 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3930 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3931 if (Ops[i] == Ops[i + 1] ||
3932 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3933 // X op Y op Y --> X op Y
3934 // X op Y --> X, if we know X, Y are ordered appropriately
3935 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3936 --i;
3937 --e;
3938 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3939 Ops[i + 1])) {
3940 // X op Y --> Y, if we know X, Y are ordered appropriately
3941 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3942 --i;
3943 --e;
3944 }
3945 }
3946
3947 if (Ops.size() == 1) return Ops[0];
3948
3949 assert(!Ops.empty() && "Reduced smax down to nothing!");
3950
3951 // Okay, it looks like we really DO need an expr. Check to see if we
3952 // already have one, otherwise create a new one.
3954 ID.AddInteger(Kind);
3955 for (SCEVUse Op : Ops)
3956 ID.AddPointer(Op.getOpaqueValue());
3958 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
3959 if (ExistingSCEV)
3960 return ExistingSCEV;
3961 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3963 SCEV *S = new (SCEVAllocator)
3964 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3965
3966 UniqueSCEVs.insert(S, Token);
3967 S->computeAndSetCanonical(*this);
3968 registerUser(S, Ops);
3969 return S;
3970}
3971
3972namespace {
3973
3974class SCEVSequentialMinMaxDeduplicatingVisitor final
3975 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
3976 std::optional<const SCEV *>> {
3977 using RetVal = std::optional<const SCEV *>;
3978
3979 ScalarEvolution &SE;
3980 const SCEVTypes RootKind; // Must be a sequential min/max expression.
3981 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
3983
3984 bool canRecurseInto(SCEVTypes Kind) const {
3985 // We can only recurse into the SCEV expression of the same effective type
3986 // as the type of our root SCEV expression.
3987 return RootKind == Kind || NonSequentialRootKind == Kind;
3988 };
3989
3990 RetVal visit(const SCEV *S) {
3991 // Has the whole operand been seen already?
3992 if (!SeenOps.insert(S).second)
3993 return std::nullopt;
3995 SCEVTypes Kind = S->getSCEVType();
3996
3997 if (!canRecurseInto(Kind))
3998 return S;
3999
4000 auto *NAry = cast<SCEVNAryExpr>(S);
4001 SmallVector<SCEVUse> NewOps;
4002 bool Changed = visit(Kind, NAry->operands(), NewOps);
4003
4004 if (!Changed)
4005 return S;
4006 if (NewOps.empty())
4007 return std::nullopt;
4008
4010 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
4011 : SE.getMinMaxExpr(Kind, NewOps);
4012 }
4013 return S;
4014 }
4015
4016public:
4017 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
4018 SCEVTypes RootKind)
4019 : SE(SE), RootKind(RootKind),
4020 NonSequentialRootKind(
4021 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4022 RootKind)) {}
4023
4024 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<SCEVUse> OrigOps,
4025 SmallVectorImpl<SCEVUse> &NewOps) {
4026 bool Changed = false;
4028 Ops.reserve(OrigOps.size());
4029
4030 for (const SCEV *Op : OrigOps) {
4031 RetVal NewOp = visit(Op);
4032 if (NewOp != Op)
4033 Changed = true;
4034 if (NewOp)
4035 Ops.emplace_back(*NewOp);
4036 }
4037
4038 if (Changed)
4039 NewOps = std::move(Ops);
4040 return Changed;
4041 }
4042};
4043
4044} // namespace
4045
4047 switch (Kind) {
4048 case scConstant:
4049 case scVScale:
4050 case scTruncate:
4051 case scZeroExtend:
4052 case scSignExtend:
4053 case scPtrToAddr:
4054 case scAddExpr:
4055 case scMulExpr:
4056 case scUDivExpr:
4057 case scAddRecExpr:
4058 case scUMaxExpr:
4059 case scSMaxExpr:
4060 case scUMinExpr:
4061 case scSMinExpr:
4062 case scUnknown:
4063 // If any operand is poison, the whole expression is poison.
4064 return true;
4066 // FIXME: if the *first* operand is poison, the whole expression is poison.
4067 return false; // Pessimistically, say that it does not propagate poison.
4068 case scCouldNotCompute:
4069 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4070 }
4071 llvm_unreachable("Unknown SCEV kind!");
4072}
4073
4074namespace {
4075// The only way poison may be introduced in a SCEV expression is from a
4076// poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4077// not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not*
4078// introduce poison -- they encode guaranteed, non-speculated knowledge.
4079//
4080// Additionally, all SCEV nodes propagate poison from inputs to outputs,
4081// with the notable exception of umin_seq, where only poison from the first
4082// operand is (unconditionally) propagated.
4083struct SCEVPoisonCollector {
4084 bool LookThroughMaybePoisonBlocking;
4085 SmallPtrSet<const SCEVUnknown *, 4> MaybePoison;
4086 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4087 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4088
4089 bool follow(const SCEV *S) {
4090 if (!LookThroughMaybePoisonBlocking &&
4092 return false;
4093
4094 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4095 if (!isGuaranteedNotToBePoison(SU->getValue()))
4096 MaybePoison.insert(SU);
4097 }
4098 return true;
4099 }
4100 bool isDone() const { return false; }
4101};
4102} // namespace
4103
4104/// Return true if V is poison given that AssumedPoison is already poison.
4105static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4106 // First collect all SCEVs that might result in AssumedPoison to be poison.
4107 // We need to look through potentially poison-blocking operations here,
4108 // because we want to find all SCEVs that *might* result in poison, not only
4109 // those that are *required* to.
4110 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4111 visitAll(AssumedPoison, PC1);
4112
4113 // AssumedPoison is never poison. As the assumption is false, the implication
4114 // is true. Don't bother walking the other SCEV in this case.
4115 if (PC1.MaybePoison.empty())
4116 return true;
4117
4118 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4119 // as well. We cannot look through potentially poison-blocking operations
4120 // here, as their arguments only *may* make the result poison.
4121 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4122 visitAll(S, PC2);
4123
4124 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4125 // it will also make S poison by being part of PC2.MaybePoison.
4126 return llvm::set_is_subset(PC1.MaybePoison, PC2.MaybePoison);
4127}
4128
4130 SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4131 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4132 visitAll(S, PC);
4133 for (const SCEVUnknown *SU : PC.MaybePoison)
4134 Result.insert(SU->getValue());
4135}
4136
4138 const SCEV *S, Instruction *I,
4139 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
4140 // If the instruction cannot be poison, it's always safe to reuse.
4142 return true;
4143
4144 // Otherwise, it is possible that I is more poisonous that S. Collect the
4145 // poison-contributors of S, and then check whether I has any additional
4146 // poison-contributors. Poison that is contributed through poison-generating
4147 // flags is handled by dropping those flags instead.
4149 getPoisonGeneratingValues(PoisonVals, S);
4150
4151 SmallVector<Value *> Worklist;
4153 Worklist.push_back(I);
4154 while (!Worklist.empty()) {
4155 Value *V = Worklist.pop_back_val();
4156 if (!Visited.insert(V).second)
4157 continue;
4158
4159 // Avoid walking large instruction graphs.
4160 if (Visited.size() > 16)
4161 return false;
4162
4163 // Either the value can't be poison, or the S would also be poison if it
4164 // is.
4165 if (PoisonVals.contains(V) || ::isGuaranteedNotToBePoison(V))
4166 continue;
4167
4168 auto *I = dyn_cast<Instruction>(V);
4169 if (!I)
4170 return false;
4171
4172 // Disjoint or instructions are interpreted as adds by SCEV. However, we
4173 // can't replace an arbitrary add with disjoint or, even if we drop the
4174 // flag. We would need to convert the or into an add.
4175 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
4176 if (PDI->isDisjoint())
4177 return false;
4178
4179 // FIXME: Ignore vscale, even though it technically could be poison. Do this
4180 // because SCEV currently assumes it can't be poison. Remove this special
4181 // case once we proper model when vscale can be poison.
4182 if (auto *II = dyn_cast<IntrinsicInst>(I);
4183 II && II->getIntrinsicID() == Intrinsic::vscale)
4184 continue;
4185
4186 if (canCreatePoison(cast<Operator>(I), /*ConsiderFlagsAndMetadata*/ false))
4187 return false;
4188
4189 // If the instruction can't create poison, we can recurse to its operands.
4190 if (I->hasPoisonGeneratingAnnotations())
4191 DropPoisonGeneratingInsts.push_back(I);
4192
4193 llvm::append_range(Worklist, I->operands());
4194 }
4195 return true;
4196}
4197
4198const SCEV *
4201 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4202 "Not a SCEVSequentialMinMaxExpr!");
4203 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4204 if (Ops.size() == 1)
4205 return Ops[0];
4206#ifndef NDEBUG
4207 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4208 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4209 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4210 "Operand types don't match!");
4211 assert(Ops[0]->getType()->isPointerTy() ==
4212 Ops[i]->getType()->isPointerTy() &&
4213 "min/max should be consistently pointerish");
4214 }
4215#endif
4216
4217 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4218 // so we can *NOT* do any kind of sorting of the expressions!
4219
4220 // Check if we have created the same expression before.
4221 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4222 return S;
4223
4224 // FIXME: there are *some* simplifications that we can do here.
4225
4226 // Keep only the first instance of an operand.
4227 {
4228 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4229 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4230 if (Changed)
4231 return getSequentialMinMaxExpr(Kind, Ops);
4232 }
4233
4234 // Check to see if one of the operands is of the same kind. If so, expand its
4235 // operands onto our operand list, and recurse to simplify.
4236 {
4237 unsigned Idx = 0;
4238 bool DeletedAny = false;
4239 while (Idx < Ops.size()) {
4240 if (Ops[Idx]->getSCEVType() != Kind) {
4241 ++Idx;
4242 continue;
4243 }
4244 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4245 Ops.erase(Ops.begin() + Idx);
4246 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4247 SMME->operands().end());
4248 DeletedAny = true;
4249 }
4250
4251 if (DeletedAny)
4252 return getSequentialMinMaxExpr(Kind, Ops);
4253 }
4254
4255 const SCEV *SaturationPoint;
4257 switch (Kind) {
4259 SaturationPoint = getZero(Ops[0]->getType());
4260 Pred = ICmpInst::ICMP_ULE;
4261 break;
4262 default:
4263 llvm_unreachable("Not a sequential min/max type.");
4264 }
4265
4266 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4267 if (!isGuaranteedNotToCauseUB(Ops[i]))
4268 continue;
4269 // We can replace %x umin_seq %y with %x umin %y if either:
4270 // * %y being poison implies %x is also poison.
4271 // * %x cannot be the saturating value (e.g. zero for umin).
4272 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4273 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4274 SaturationPoint)) {
4275 SmallVector<SCEVUse, 2> SeqOps = {Ops[i - 1], Ops[i]};
4276 Ops[i - 1] = getMinMaxExpr(
4278 SeqOps);
4279 Ops.erase(Ops.begin() + i);
4280 return getSequentialMinMaxExpr(Kind, Ops);
4281 }
4282 // Fold %x umin_seq %y to %x if %x ule %y.
4283 // TODO: We might be able to prove the predicate for a later operand.
4284 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4285 Ops.erase(Ops.begin() + i);
4286 return getSequentialMinMaxExpr(Kind, Ops);
4287 }
4288 }
4289
4290 // Okay, it looks like we really DO need an expr. Check to see if we
4291 // already have one, otherwise create a new one.
4293 ID.AddInteger(Kind);
4294 for (SCEVUse Op : Ops)
4295 ID.AddPointer(Op.getOpaqueValue());
4297 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
4298 if (ExistingSCEV)
4299 return ExistingSCEV;
4300
4301 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4303 SCEV *S = new (SCEVAllocator)
4304 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4305
4306 UniqueSCEVs.insert(S, Token);
4307 S->computeAndSetCanonical(*this);
4308 registerUser(S, Ops);
4309 return S;
4310}
4311
4316
4320
4325
4329
4334
4338
4340 bool Sequential) {
4341 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4342 return getUMinExpr(Ops, Sequential);
4343}
4344
4350
4351const SCEV *
4353 const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4354 if (Size.isScalable())
4355 Res = getMulExpr(Res, getVScale(IntTy));
4356 return Res;
4357}
4358
4360 return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4361}
4362
4364 return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4365}
4366
4368 StructType *STy,
4369 unsigned FieldNo) {
4370 // We can bypass creating a target-independent constant expression and then
4371 // folding it back into a ConstantInt. This is just a compile-time
4372 // optimization.
4373 const StructLayout *SL = getDataLayout().getStructLayout(STy);
4374 assert(!SL->getSizeInBits().isScalable() &&
4375 "Cannot get offset for structure containing scalable vector types");
4376 return getConstant(IntTy, SL->getElementOffset(FieldNo));
4377}
4378
4380 // Don't attempt to do anything other than create a SCEVUnknown object
4381 // here. createSCEV only calls getUnknown after checking for all other
4382 // interesting possibilities, and any other code that calls getUnknown
4383 // is doing so in order to hide a value from SCEV canonicalization.
4384
4387 ID.AddPointer(V);
4389 if (SCEV *S = UniqueSCEVs.lookup(ID, Token)) {
4390 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4391 "Stale SCEVUnknown in uniquing map!");
4392 return S;
4393 }
4394 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4395 FirstUnknown);
4396 FirstUnknown = cast<SCEVUnknown>(S);
4397 UniqueSCEVs.insert(S, Token);
4398 S->computeAndSetCanonical(*this);
4399 return S;
4400}
4401
4402//===----------------------------------------------------------------------===//
4403// Basic SCEV Analysis and PHI Idiom Recognition Code
4404//
4405
4406/// Test if values of the given type are analyzable within the SCEV
4407/// framework. This primarily includes integer types, and it can optionally
4408/// include pointer types if the ScalarEvolution class has access to
4409/// target-specific information.
4411 // Integers and pointers are always SCEVable.
4412 return Ty->isIntOrPtrTy();
4413}
4414
4415/// Return the size in bits of the specified type, for which isSCEVable must
4416/// return true.
4418 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4419 if (Ty->isPointerTy())
4421 return getDataLayout().getTypeSizeInBits(Ty);
4422}
4423
4424/// Return a type with the same bitwidth as the given type and which represents
4425/// how SCEV will treat the given type, for which isSCEVable must return
4426/// true. For pointer types, this is the pointer index sized integer type.
4428 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4429
4430 if (Ty->isIntegerTy())
4431 return Ty;
4432
4433 // The only other support type is pointer.
4434 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4435 return getDataLayout().getIndexType(Ty);
4436}
4437
4439 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4440}
4441
4443 const SCEV *B) {
4444 /// For a valid use point to exist, the defining scope of one operand
4445 /// must dominate the other.
4446 bool PreciseA, PreciseB;
4447 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4448 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4449 if (!PreciseA || !PreciseB)
4450 // Can't tell.
4451 return false;
4452 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4453 DT.dominates(ScopeB, ScopeA);
4454}
4455
4457 return CouldNotCompute.get();
4458}
4459
4460bool ScalarEvolution::checkValidity(const SCEV *S) const {
4461 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4462 auto *SU = dyn_cast<SCEVUnknown>(S);
4463 return SU && SU->getValue() == nullptr;
4464 });
4465
4466 return !ContainsNulls;
4467}
4468
4470 HasRecMapType::iterator I = HasRecMap.find(S);
4471 if (I != HasRecMap.end())
4472 return I->second;
4473
4474 bool FoundAddRec =
4475 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4476 HasRecMap.insert({S, FoundAddRec});
4477 return FoundAddRec;
4478}
4479
4480/// Return the ValueOffsetPair set for \p S. \p S can be represented
4481/// by the value and offset from any ValueOffsetPair in the set.
4482ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4483 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4484 if (SI == ExprValueMap.end())
4485 return {};
4486 return SI->second.getArrayRef();
4487}
4488
4489/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4490/// cannot be used separately. eraseValueFromMap should be used to remove
4491/// V from ValueExprMap and ExprValueMap at the same time.
4492void ScalarEvolution::eraseValueFromMap(Value *V) {
4493 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4494 if (I != ValueExprMap.end()) {
4495 auto EVIt = ExprValueMap.find(I->second);
4496 bool Removed = EVIt->second.remove(V);
4497 (void) Removed;
4498 assert(Removed && "Value not in ExprValueMap?");
4499 ValueExprMap.erase(I);
4500 }
4501}
4502
4503void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4504 // A recursive query may have already computed the SCEV. It should be
4505 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4506 // inferred nowrap flags.
4507 auto It = ValueExprMap.find_as(V);
4508 if (It == ValueExprMap.end()) {
4509 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4510 ExprValueMap[S].insert(V);
4511 }
4512}
4513
4514/// Return an existing SCEV if it exists, otherwise analyze the expression and
4515/// create a new one.
4517 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4518
4519 if (const SCEV *S = getExistingSCEV(V))
4520 return S;
4521 return createSCEVIter(V);
4522}
4523
4525 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4526
4527 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4528 if (I != ValueExprMap.end()) {
4529 const SCEV *S = I->second;
4530 assert(checkValidity(S) &&
4531 "existing SCEV has not been properly invalidated");
4532 return S;
4533 }
4534 return nullptr;
4535}
4536
4537/// Return a SCEV corresponding to -V = -1*V
4539 SCEV::NoWrapFlags Flags) {
4540 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4541 return getConstant(
4542 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4543
4544 Type *Ty = V->getType();
4545 Ty = getEffectiveSCEVType(Ty);
4546 return getMulExpr(V, getMinusOne(Ty), Flags);
4547}
4548
4549/// If Expr computes ~A, return A else return nullptr
4550static const SCEV *MatchNotExpr(const SCEV *Expr) {
4551 const SCEV *MulOp;
4552 if (match(Expr, m_scev_Add(m_scev_AllOnes(),
4553 m_scev_Mul(m_scev_AllOnes(), m_SCEV(MulOp)))))
4554 return MulOp;
4555 return nullptr;
4556}
4557
4558/// Return a SCEV corresponding to ~V = -1-V
4560 assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4561
4562 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4563 return getConstant(
4564 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4565
4566 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4567 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4568 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4569 SmallVector<SCEVUse, 2> MatchedOperands;
4570 for (const SCEV *Operand : MME->operands()) {
4571 const SCEV *Matched = MatchNotExpr(Operand);
4572 if (!Matched)
4573 return (const SCEV *)nullptr;
4574 MatchedOperands.push_back(Matched);
4575 }
4576 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4577 MatchedOperands);
4578 };
4579 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4580 return Replaced;
4581 }
4582
4583 Type *Ty = V->getType();
4584 Ty = getEffectiveSCEVType(Ty);
4585 return getMinusSCEV(getMinusOne(Ty), V);
4586}
4587
4589 assert(P->getType()->isPointerTy());
4590
4591 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4592 // The base of an AddRec is the first operand.
4593 SmallVector<SCEVUse> Ops{AddRec->operands()};
4594 Ops[0] = removePointerBase(Ops[0]);
4595 // Don't try to transfer nowrap flags for now. We could in some cases
4596 // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4597 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
4598 }
4599 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4600 // The base of an Add is the pointer operand.
4601 SmallVector<SCEVUse> Ops{Add->operands()};
4602 SCEVUse *PtrOp = nullptr;
4603 for (SCEVUse &AddOp : Ops) {
4604 if (AddOp->getType()->isPointerTy()) {
4605 assert(!PtrOp && "Cannot have multiple pointer ops");
4606 PtrOp = &AddOp;
4607 }
4608 }
4609 *PtrOp = removePointerBase(*PtrOp);
4610 // Don't try to transfer nowrap flags for now. We could in some cases
4611 // (for example, if the pointer operand of the Add is a SCEVUnknown).
4612 return getAddExpr(Ops);
4613 }
4614 // Any other expression must be a pointer base.
4615 return getZero(P->getType());
4616}
4617
4619 SCEV::NoWrapFlags Flags,
4620 unsigned Depth) {
4621 // Fast path: X - X --> 0.
4622 if (LHS == RHS)
4623 return getZero(LHS->getType());
4624
4625 // If we subtract two pointers with different pointer bases, bail.
4626 // Eventually, we're going to add an assertion to getMulExpr that we
4627 // can't multiply by a pointer.
4628 if (RHS->getType()->isPointerTy()) {
4629 if (!LHS->getType()->isPointerTy() ||
4630 getPointerBase(LHS) != getPointerBase(RHS))
4631 return getCouldNotCompute();
4632 LHS = removePointerBase(LHS);
4633 RHS = removePointerBase(RHS);
4634 }
4635
4636 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4637 // makes it so that we cannot make much use of NUW.
4638 auto AddFlags = SCEV::FlagAnyWrap;
4639 const bool RHSIsNotMinSigned =
4641 if (hasFlags(Flags, SCEV::FlagNSW)) {
4642 // Let M be the minimum representable signed value. Then (-1)*RHS
4643 // signed-wraps if and only if RHS is M. That can happen even for
4644 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4645 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4646 // (-1)*RHS, we need to prove that RHS != M.
4647 //
4648 // If LHS is non-negative and we know that LHS - RHS does not
4649 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4650 // either by proving that RHS > M or that LHS >= 0.
4651 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4652 AddFlags = SCEV::FlagNSW;
4653 }
4654 }
4655
4656 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4657 // RHS is NSW and LHS >= 0.
4658 //
4659 // The difficulty here is that the NSW flag may have been proven
4660 // relative to a loop that is to be found in a recurrence in LHS and
4661 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4662 // larger scope than intended.
4663 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4664
4665 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4666}
4667
4669 unsigned Depth) {
4670 Type *SrcTy = V->getType();
4671 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4672 "Cannot truncate or zero extend with non-integer arguments!");
4673 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4674 return V; // No conversion
4675 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4676 return getTruncateExpr(V, Ty, Depth);
4677 return getZeroExtendExpr(V, Ty, Depth);
4678}
4679
4681 unsigned Depth) {
4682 Type *SrcTy = V->getType();
4683 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4684 "Cannot truncate or zero extend with non-integer arguments!");
4685 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4686 return V; // No conversion
4687 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4688 return getTruncateExpr(V, Ty, Depth);
4689 return getSignExtendExpr(V, Ty, Depth);
4690}
4691
4693 Type *SrcTy = V->getType();
4694 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4695 "Cannot noop or zero extend with non-integer arguments!");
4697 "getNoopOrZeroExtend cannot truncate!");
4698 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4699 return V; // No conversion
4700 return getZeroExtendExpr(V, Ty);
4701}
4702
4704 Type *SrcTy = V->getType();
4705 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4706 "Cannot noop or sign extend with non-integer arguments!");
4708 "getNoopOrSignExtend cannot truncate!");
4709 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4710 return V; // No conversion
4711 return getSignExtendExpr(V, Ty);
4712}
4713
4715 Type *SrcTy = V->getType();
4716 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4717 "Cannot noop or any extend with non-integer arguments!");
4719 "getNoopOrAnyExtend cannot truncate!");
4720 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4721 return V; // No conversion
4722 return getAnyExtendExpr(V, Ty);
4723}
4724
4726 Type *SrcTy = V->getType();
4727 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4728 "Cannot truncate or noop with non-integer arguments!");
4730 "getTruncateOrNoop cannot extend!");
4731 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4732 return V; // No conversion
4733 return getTruncateExpr(V, Ty);
4734}
4735
4737 const SCEV *RHS) {
4738 const SCEV *PromotedLHS = LHS;
4739 const SCEV *PromotedRHS = RHS;
4740
4741 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4742 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4743 else
4744 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4745
4746 return getUMaxExpr(PromotedLHS, PromotedRHS);
4747}
4748
4750 const SCEV *RHS,
4751 bool Sequential) {
4752 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4753 return getUMinFromMismatchedTypes(Ops, Sequential);
4754}
4755
4756const SCEV *
4758 bool Sequential) {
4759 assert(!Ops.empty() && "At least one operand must be!");
4760 // Trivial case.
4761 if (Ops.size() == 1)
4762 return Ops[0];
4763
4764 // Find the max type first.
4765 Type *MaxType = nullptr;
4766 for (SCEVUse S : Ops)
4767 if (MaxType)
4768 MaxType = getWiderType(MaxType, S->getType());
4769 else
4770 MaxType = S->getType();
4771 assert(MaxType && "Failed to find maximum type!");
4772
4773 // Extend all ops to max type.
4774 SmallVector<SCEVUse, 2> PromotedOps;
4775 for (SCEVUse S : Ops)
4776 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4777
4778 // Generate umin.
4779 return getUMinExpr(PromotedOps, Sequential);
4780}
4781
4783 // A pointer operand may evaluate to a nonpointer expression, such as null.
4784 if (!V->getType()->isPointerTy())
4785 return V;
4786
4787 while (true) {
4788 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4789 V = AddRec->getStart();
4790 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4791 const SCEV *PtrOp = nullptr;
4792 for (const SCEV *AddOp : Add->operands()) {
4793 if (AddOp->getType()->isPointerTy()) {
4794 assert(!PtrOp && "Cannot have multiple pointer ops");
4795 PtrOp = AddOp;
4796 }
4797 }
4798 assert(PtrOp && "Must have pointer op");
4799 V = PtrOp;
4800 } else // Not something we can look further into.
4801 return V;
4802 }
4803}
4804
4805/// Push users of the given Instruction onto the given Worklist.
4809 // Push the def-use children onto the Worklist stack.
4810 for (User *U : I->users()) {
4811 auto *UserInsn = cast<Instruction>(U);
4812 if (Visited.insert(UserInsn).second)
4813 Worklist.push_back(UserInsn);
4814 }
4815}
4816
4817namespace {
4818
4819/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4820/// expression in case its Loop is L. If it is not L then
4821/// if IgnoreOtherLoops is true then use AddRec itself
4822/// otherwise rewrite cannot be done.
4823/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4824class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4825public:
4826 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4827 bool IgnoreOtherLoops = true) {
4828 SCEVInitRewriter Rewriter(L, SE);
4829 const SCEV *Result = Rewriter.visit(S);
4830 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4831 return SE.getCouldNotCompute();
4832 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4833 ? SE.getCouldNotCompute()
4834 : Result;
4835 }
4836
4837 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4838 if (!SE.isLoopInvariant(Expr, L))
4839 SeenLoopVariantSCEVUnknown = true;
4840 return Expr;
4841 }
4842
4843 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4844 // Only re-write AddRecExprs for this loop.
4845 if (Expr->getLoop() == L)
4846 return Expr->getStart();
4847 SeenOtherLoops = true;
4848 return Expr;
4849 }
4850
4851 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4852
4853 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4854
4855private:
4856 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4857 : SCEVRewriteVisitor(SE), L(L) {}
4858
4859 const Loop *L;
4860 bool SeenLoopVariantSCEVUnknown = false;
4861 bool SeenOtherLoops = false;
4862};
4863
4864/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4865/// increment expression in case its Loop is L. If it is not L then
4866/// use AddRec itself.
4867/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4868class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4869public:
4870 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4871 SCEVPostIncRewriter Rewriter(L, SE);
4872 const SCEV *Result = Rewriter.visit(S);
4873 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4874 ? SE.getCouldNotCompute()
4875 : Result;
4876 }
4877
4878 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4879 if (!SE.isLoopInvariant(Expr, L))
4880 SeenLoopVariantSCEVUnknown = true;
4881 return Expr;
4882 }
4883
4884 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4885 // Only re-write AddRecExprs for this loop.
4886 if (Expr->getLoop() == L)
4887 return Expr->getPostIncExpr(SE);
4888 SeenOtherLoops = true;
4889 return Expr;
4890 }
4891
4892 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4893
4894 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4895
4896private:
4897 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4898 : SCEVRewriteVisitor(SE), L(L) {}
4899
4900 const Loop *L;
4901 bool SeenLoopVariantSCEVUnknown = false;
4902 bool SeenOtherLoops = false;
4903};
4904
4905/// This class evaluates the compare condition by matching it against the
4906/// condition of loop latch. If there is a match we assume a true value
4907/// for the condition while building SCEV nodes.
4908class SCEVBackedgeConditionFolder
4909 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4910public:
4911 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4912 ScalarEvolution &SE) {
4913 bool IsPosBECond = false;
4914 Value *BECond = nullptr;
4915 if (BasicBlock *Latch = L->getLoopLatch()) {
4916 if (CondBrInst *BI = dyn_cast<CondBrInst>(Latch->getTerminator())) {
4917 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4918 "Both outgoing branches should not target same header!");
4919 BECond = BI->getCondition();
4920 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4921 } else {
4922 return S;
4923 }
4924 }
4925 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4926 return Rewriter.visit(S);
4927 }
4928
4929 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4930 const SCEV *Result = Expr;
4931 bool InvariantF = SE.isLoopInvariant(Expr, L);
4932
4933 if (!InvariantF) {
4935 switch (I->getOpcode()) {
4936 case Instruction::Select: {
4937 SelectInst *SI = cast<SelectInst>(I);
4938 std::optional<const SCEV *> Res =
4939 compareWithBackedgeCondition(SI->getCondition());
4940 if (Res) {
4941 bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
4942 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4943 }
4944 break;
4945 }
4946 default: {
4947 std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4948 if (Res)
4949 Result = *Res;
4950 break;
4951 }
4952 }
4953 }
4954 return Result;
4955 }
4956
4957private:
4958 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4959 bool IsPosBECond, ScalarEvolution &SE)
4960 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4961 IsPositiveBECond(IsPosBECond) {}
4962
4963 std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4964
4965 const Loop *L;
4966 /// Loop back condition.
4967 Value *BackedgeCond = nullptr;
4968 /// Set to true if loop back is on positive branch condition.
4969 bool IsPositiveBECond;
4970};
4971
4972std::optional<const SCEV *>
4973SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4974
4975 // If value matches the backedge condition for loop latch,
4976 // then return a constant evolution node based on loopback
4977 // branch taken.
4978 if (BackedgeCond == IC)
4979 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4981 return std::nullopt;
4982}
4983
4984class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4985public:
4986 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4987 ScalarEvolution &SE) {
4988 SCEVShiftRewriter Rewriter(L, SE);
4989 const SCEV *Result = Rewriter.visit(S);
4990 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4991 }
4992
4993 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4994 // Only allow AddRecExprs for this loop.
4995 if (!SE.isLoopInvariant(Expr, L))
4996 Valid = false;
4997 return Expr;
4998 }
4999
5000 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5001 if (Expr->getLoop() == L && Expr->isAffine())
5002 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
5003 Valid = false;
5004 return Expr;
5005 }
5006
5007 bool isValid() { return Valid; }
5008
5009private:
5010 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
5011 : SCEVRewriteVisitor(SE), L(L) {}
5012
5013 const Loop *L;
5014 bool Valid = true;
5015};
5016
5017} // end anonymous namespace
5018
5019void ScalarEvolution::inferNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
5020 if (!AR->isAffine())
5021 return;
5022
5023 // Force computation of ranges, which will also perform range-based flag
5024 // inference.
5025 if (!AR->hasNoSignedWrap())
5026 (void)getSignedRange(AR);
5027
5028 if (!AR->hasNoUnsignedWrap())
5029 (void)getUnsignedRange(AR);
5030
5031 if (!AR->hasNoSelfWrap()) {
5032 const SCEV *BECount = getConstantMaxBackedgeTakenCount(AR->getLoop());
5033 if (const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(BECount)) {
5034 ConstantRange StepCR = getSignedRange(AR->getStepRecurrence(*this));
5035 const APInt &BECountAP = BECountMax->getAPInt();
5036 unsigned NoOverflowBitWidth =
5037 BECountAP.getActiveBits() + StepCR.getMinSignedBits();
5038 if (NoOverflowBitWidth <= getTypeSizeInBits(AR->getType()))
5039 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
5040 }
5041 }
5042}
5043
5045ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5047
5048 if (AR->hasNoSignedWrap())
5049 return Result;
5050
5051 if (!AR->isAffine())
5052 return Result;
5053
5054 // This function can be expensive, only try to prove NSW once per AddRec.
5055 if (!SignedWrapViaInductionTried.insert(AR).second)
5056 return Result;
5057
5058 const SCEV *Step = AR->getStepRecurrence(*this);
5059 const Loop *L = AR->getLoop();
5060
5061 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5062 // Note that this serves two purposes: It filters out loops that are
5063 // simply not analyzable, and it covers the case where this code is
5064 // being called from within backedge-taken count analysis, such that
5065 // attempting to ask for the backedge-taken count would likely result
5066 // in infinite recursion. In the later case, the analysis code will
5067 // cope with a conservative value, and it will take care to purge
5068 // that value once it has finished.
5069 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5070
5071 // Normally, in the cases we can prove no-overflow via a
5072 // backedge guarding condition, we can also compute a backedge
5073 // taken count for the loop. The exceptions are assumptions and
5074 // guards present in the loop -- SCEV is not great at exploiting
5075 // these to compute max backedge taken counts, but can still use
5076 // these to prove lack of overflow. Use this fact to avoid
5077 // doing extra work that may not pay off.
5078
5079 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5080 AC.assumptions().empty())
5081 return Result;
5082
5083 // If the backedge is guarded by a comparison with the pre-inc value the
5084 // addrec is safe. Also, if the entry is guarded by a comparison with the
5085 // start value and the backedge is guarded by a comparison with the post-inc
5086 // value, the addrec is safe.
5088 const SCEV *OverflowLimit =
5089 getSignedOverflowLimitForStep(Step, &Pred, this);
5090 if (OverflowLimit &&
5091 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5092 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
5093 Result = setFlags(Result, SCEV::FlagNSW);
5094 }
5095 return Result;
5096}
5098ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5100
5101 if (AR->hasNoUnsignedWrap())
5102 return Result;
5103
5104 if (!AR->isAffine())
5105 return Result;
5106
5107 // This function can be expensive, only try to prove NUW once per AddRec.
5108 if (!UnsignedWrapViaInductionTried.insert(AR).second)
5109 return Result;
5110
5111 const SCEV *Step = AR->getStepRecurrence(*this);
5112 const Loop *L = AR->getLoop();
5113
5114 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5115 // Note that this serves two purposes: It filters out loops that are
5116 // simply not analyzable, and it covers the case where this code is
5117 // being called from within backedge-taken count analysis, such that
5118 // attempting to ask for the backedge-taken count would likely result
5119 // in infinite recursion. In the later case, the analysis code will
5120 // cope with a conservative value, and it will take care to purge
5121 // that value once it has finished.
5122 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5123
5124 // Normally, in the cases we can prove no-overflow via a
5125 // backedge guarding condition, we can also compute a backedge
5126 // taken count for the loop. The exceptions are assumptions and
5127 // guards present in the loop -- SCEV is not great at exploiting
5128 // these to compute max backedge taken counts, but can still use
5129 // these to prove lack of overflow. Use this fact to avoid
5130 // doing extra work that may not pay off.
5131
5132 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5133 AC.assumptions().empty())
5134 return Result;
5135
5136 // If the backedge is guarded by a comparison with the pre-inc value the
5137 // addrec is safe. Also, if the entry is guarded by a comparison with the
5138 // start value and the backedge is guarded by a comparison with the post-inc
5139 // value, the addrec is safe.
5140 if (isKnownPositive(Step)) {
5142 const SCEV *OverflowLimit =
5143 getUnsignedOverflowLimitForStep(Step, &Pred, this);
5144 if (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5145 isKnownOnEveryIteration(Pred, AR, OverflowLimit))
5146 Result = setFlags(Result, SCEV::FlagNUW);
5147 }
5148 return Result;
5149}
5150
5151namespace {
5152
5153/// Represents an abstract binary operation. This may exist as a
5154/// normal instruction or constant expression, or may have been
5155/// derived from an expression tree.
5156struct BinaryOp {
5157 unsigned Opcode;
5158 Value *LHS;
5159 Value *RHS;
5160 bool IsNSW = false;
5161 bool IsNUW = false;
5162
5163 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5164 /// constant expression.
5165 Operator *Op = nullptr;
5166
5167 explicit BinaryOp(Operator *Op)
5168 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5169 Op(Op) {
5170 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5171 IsNSW = OBO->hasNoSignedWrap();
5172 IsNUW = OBO->hasNoUnsignedWrap();
5173 }
5174 }
5175
5176 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5177 bool IsNUW = false)
5178 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5179};
5180
5181} // end anonymous namespace
5182
5183/// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
5184static std::optional<BinaryOp> MatchBinaryOp(Value *V, const DataLayout &DL,
5185 AssumptionCache &AC,
5186 const DominatorTree &DT,
5187 const Instruction *CxtI) {
5188 auto *Op = dyn_cast<Operator>(V);
5189 if (!Op)
5190 return std::nullopt;
5191
5192 // Implementation detail: all the cleverness here should happen without
5193 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5194 // SCEV expressions when possible, and we should not break that.
5195
5196 switch (Op->getOpcode()) {
5197 case Instruction::Add:
5198 case Instruction::Sub:
5199 case Instruction::Mul:
5200 case Instruction::UDiv:
5201 case Instruction::URem:
5202 case Instruction::And:
5203 case Instruction::AShr:
5204 case Instruction::Shl:
5205 return BinaryOp(Op);
5206
5207 case Instruction::Or: {
5208 // Convert or disjoint into add nuw nsw.
5209 if (cast<PossiblyDisjointInst>(Op)->isDisjoint()) {
5210 BinaryOp BinOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
5211 /*IsNSW=*/true, /*IsNUW=*/true);
5212 // Keep the reference to the original instruction so that we can later
5213 // check whether it can produce poison value or not.
5214 BinOp.Op = Op;
5215 return BinOp;
5216 }
5217 return BinaryOp(Op);
5218 }
5219
5220 case Instruction::Xor:
5221 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5222 // If the RHS of the xor is a signmask, then this is just an add.
5223 // Instcombine turns add of signmask into xor as a strength reduction step.
5224 if (RHSC->getValue().isSignMask())
5225 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5226 // Binary `xor` is a bit-wise `add`.
5227 if (V->getType()->isIntegerTy(1))
5228 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5229 return BinaryOp(Op);
5230
5231 case Instruction::LShr:
5232 // Turn logical shift right of a constant into a unsigned divide.
5233 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5234 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5235
5236 // If the shift count is not less than the bitwidth, the result of
5237 // the shift is undefined. Don't try to analyze it, because the
5238 // resolution chosen here may differ from the resolution chosen in
5239 // other parts of the compiler.
5240 if (SA->getValue().ult(BitWidth)) {
5241 Constant *X =
5242 ConstantInt::get(SA->getContext(),
5243 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5244 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5245 }
5246 }
5247 return BinaryOp(Op);
5248
5249 case Instruction::ExtractValue: {
5250 auto *EVI = cast<ExtractValueInst>(Op);
5251 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5252 break;
5253
5254 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5255 if (!WO)
5256 break;
5257
5258 Instruction::BinaryOps BinOp = WO->getBinaryOp();
5259 bool Signed = WO->isSigned();
5260 // TODO: Should add nuw/nsw flags for mul as well.
5261 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5262 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5263
5264 // Now that we know that all uses of the arithmetic-result component of
5265 // CI are guarded by the overflow check, we can go ahead and pretend
5266 // that the arithmetic is non-overflowing.
5267 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5268 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5269 }
5270
5271 default:
5272 break;
5273 }
5274
5275 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5276 // semantics as a Sub, return a binary sub expression.
5277 if (auto *II = dyn_cast<IntrinsicInst>(V))
5278 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5279 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5280
5281 return std::nullopt;
5282}
5283
5284/// Helper function to createAddRecFromPHIWithCasts. We have a phi
5285/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5286/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5287/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5288/// follows one of the following patterns:
5289/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5290/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5291/// If the SCEV expression of \p Op conforms with one of the expected patterns
5292/// we return the type of the truncation operation, and indicate whether the
5293/// truncated type should be treated as signed/unsigned by setting
5294/// \p Signed to true/false, respectively.
5295static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5296 bool &Signed, ScalarEvolution &SE) {
5297 // The case where Op == SymbolicPHI (that is, with no type conversions on
5298 // the way) is handled by the regular add recurrence creating logic and
5299 // would have already been triggered in createAddRecForPHI. Reaching it here
5300 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5301 // because one of the other operands of the SCEVAddExpr updating this PHI is
5302 // not invariant).
5303 //
5304 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5305 // this case predicates that allow us to prove that Op == SymbolicPHI will
5306 // be added.
5307 if (Op == SymbolicPHI)
5308 return nullptr;
5309
5310 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5311 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5312 if (SourceBits != NewBits)
5313 return nullptr;
5314
5315 if (match(Op, m_scev_SExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5316 Signed = true;
5317 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5318 }
5319 if (match(Op, m_scev_ZExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5320 Signed = false;
5321 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5322 }
5323 return nullptr;
5324}
5325
5326static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5327 if (!PN->getType()->isIntegerTy())
5328 return nullptr;
5329 const Loop *L = LI.getLoopFor(PN->getParent());
5330 if (!L || L->getHeader() != PN->getParent())
5331 return nullptr;
5332 return L;
5333}
5334
5335// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5336// computation that updates the phi follows the following pattern:
5337// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5338// which correspond to a phi->trunc->sext/zext->add->phi update chain.
5339// If so, try to see if it can be rewritten as an AddRecExpr under some
5340// Predicates. If successful, return them as a pair. Also cache the results
5341// of the analysis.
5342//
5343// Example usage scenario:
5344// Say the Rewriter is called for the following SCEV:
5345// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5346// where:
5347// %X = phi i64 (%Start, %BEValue)
5348// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5349// and call this function with %SymbolicPHI = %X.
5350//
5351// The analysis will find that the value coming around the backedge has
5352// the following SCEV:
5353// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5354// Upon concluding that this matches the desired pattern, the function
5355// will return the pair {NewAddRec, SmallPredsVec} where:
5356// NewAddRec = {%Start,+,%Step}
5357// SmallPredsVec = {P1, P2, P3} as follows:
5358// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5359// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5360// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5361// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5362// under the predicates {P1,P2,P3}.
5363// This predicated rewrite will be cached in PredicatedSCEVRewrites:
5364// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5365//
5366// TODO's:
5367//
5368// 1) Extend the Induction descriptor to also support inductions that involve
5369// casts: When needed (namely, when we are called in the context of the
5370// vectorizer induction analysis), a Set of cast instructions will be
5371// populated by this method, and provided back to isInductionPHI. This is
5372// needed to allow the vectorizer to properly record them to be ignored by
5373// the cost model and to avoid vectorizing them (otherwise these casts,
5374// which are redundant under the runtime overflow checks, will be
5375// vectorized, which can be costly).
5376//
5377// 2) Support additional induction/PHISCEV patterns: We also want to support
5378// inductions where the sext-trunc / zext-trunc operations (partly) occur
5379// after the induction update operation (the induction increment):
5380//
5381// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5382// which correspond to a phi->add->trunc->sext/zext->phi update chain.
5383//
5384// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5385// which correspond to a phi->trunc->add->sext/zext->phi update chain.
5386//
5387// 3) Outline common code with createAddRecFromPHI to avoid duplication.
5388std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5389ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5391
5392 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5393 // return an AddRec expression under some predicate.
5394
5395 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5396 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5397 assert(L && "Expecting an integer loop header phi");
5398
5399 // The loop may have multiple entrances or multiple exits; we can analyze
5400 // this phi as an addrec if it has a unique entry value and a unique
5401 // backedge value.
5402 Value *BEValueV = nullptr, *StartValueV = nullptr;
5403 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5404 Value *V = PN->getIncomingValue(i);
5405 if (L->contains(PN->getIncomingBlock(i))) {
5406 if (!BEValueV) {
5407 BEValueV = V;
5408 } else if (BEValueV != V) {
5409 BEValueV = nullptr;
5410 break;
5411 }
5412 } else if (!StartValueV) {
5413 StartValueV = V;
5414 } else if (StartValueV != V) {
5415 StartValueV = nullptr;
5416 break;
5417 }
5418 }
5419 if (!BEValueV || !StartValueV)
5420 return std::nullopt;
5421
5422 const SCEV *BEValue = getSCEV(BEValueV);
5423
5424 // If the value coming around the backedge is an add with the symbolic
5425 // value we just inserted, possibly with casts that we can ignore under
5426 // an appropriate runtime guard, then we found a simple induction variable!
5427 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5428 if (!Add)
5429 return std::nullopt;
5430
5431 // If there is a single occurrence of the symbolic value, possibly
5432 // casted, replace it with a recurrence.
5433 unsigned FoundIndex = Add->getNumOperands();
5434 Type *TruncTy = nullptr;
5435 bool Signed;
5436 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5437 if ((TruncTy =
5438 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5439 if (FoundIndex == e) {
5440 FoundIndex = i;
5441 break;
5442 }
5443
5444 if (FoundIndex == Add->getNumOperands())
5445 return std::nullopt;
5446
5447 // Create an add with everything but the specified operand.
5449 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5450 if (i != FoundIndex)
5451 Ops.push_back(Add->getOperand(i));
5452 const SCEV *Accum = getAddExpr(Ops);
5453
5454 // The runtime checks will not be valid if the step amount is
5455 // varying inside the loop.
5456 if (!isLoopInvariant(Accum, L))
5457 return std::nullopt;
5458
5459 // *** Part2: Create the predicates
5460
5461 // Analysis was successful: we have a phi-with-cast pattern for which we
5462 // can return an AddRec expression under the following predicates:
5463 //
5464 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5465 // fits within the truncated type (does not overflow) for i = 0 to n-1.
5466 // P2: An Equal predicate that guarantees that
5467 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5468 // P3: An Equal predicate that guarantees that
5469 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5470 //
5471 // As we next prove, the above predicates guarantee that:
5472 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5473 //
5474 //
5475 // More formally, we want to prove that:
5476 // Expr(i+1) = Start + (i+1) * Accum
5477 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5478 //
5479 // Given that:
5480 // 1) Expr(0) = Start
5481 // 2) Expr(1) = Start + Accum
5482 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5483 // 3) Induction hypothesis (step i):
5484 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5485 //
5486 // Proof:
5487 // Expr(i+1) =
5488 // = Start + (i+1)*Accum
5489 // = (Start + i*Accum) + Accum
5490 // = Expr(i) + Accum
5491 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5492 // :: from step i
5493 //
5494 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5495 //
5496 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5497 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
5498 // + Accum :: from P3
5499 //
5500 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5501 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5502 //
5503 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5504 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5505 //
5506 // By induction, the same applies to all iterations 1<=i<n:
5507 //
5508
5509 // Create a truncated addrec for which we will add a no overflow check (P1).
5510 const SCEV *StartVal = getSCEV(StartValueV);
5511 const SCEV *PHISCEV =
5512 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5513 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5514
5515 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5516 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5517 // will be constant.
5518 //
5519 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5520 // add P1.
5521 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5525 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5526 Predicates.push_back(AddRecPred);
5527 }
5528
5529 // Create the Equal Predicates P2,P3:
5530
5531 // It is possible that the predicates P2 and/or P3 are computable at
5532 // compile time due to StartVal and/or Accum being constants.
5533 // If either one is, then we can check that now and escape if either P2
5534 // or P3 is false.
5535
5536 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5537 // for each of StartVal and Accum
5538 auto getExtendedExpr = [&](const SCEV *Expr,
5539 bool CreateSignExtend) -> const SCEV * {
5540 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5541 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5542 const SCEV *ExtendedExpr =
5543 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5544 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5545 return ExtendedExpr;
5546 };
5547
5548 // Given:
5549 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5550 // = getExtendedExpr(Expr)
5551 // Determine whether the predicate P: Expr == ExtendedExpr
5552 // is known to be false at compile time
5553 auto PredIsKnownFalse = [&](const SCEV *Expr,
5554 const SCEV *ExtendedExpr) -> bool {
5555 return Expr != ExtendedExpr &&
5556 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5557 };
5558
5559 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5560 if (PredIsKnownFalse(StartVal, StartExtended)) {
5561 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5562 return std::nullopt;
5563 }
5564
5565 // The Step is always Signed (because the overflow checks are either
5566 // NSSW or NUSW)
5567 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5568 if (PredIsKnownFalse(Accum, AccumExtended)) {
5569 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5570 return std::nullopt;
5571 }
5572
5573 auto AppendPredicate = [&](const SCEV *Expr,
5574 const SCEV *ExtendedExpr) -> void {
5575 if (Expr != ExtendedExpr &&
5576 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5577 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5578 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5579 Predicates.push_back(Pred);
5580 }
5581 };
5582
5583 AppendPredicate(StartVal, StartExtended);
5584 AppendPredicate(Accum, AccumExtended);
5585
5586 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5587 // which the casts had been folded away. The caller can rewrite SymbolicPHI
5588 // into NewAR if it will also add the runtime overflow checks specified in
5589 // Predicates.
5590 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5591
5592 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5593 std::make_pair(NewAR, Predicates);
5594 // Remember the result of the analysis for this SCEV at this locayyytion.
5595 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5596 return PredRewrite;
5597}
5598
5599std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5601 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5602 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5603 if (!L)
5604 return std::nullopt;
5605
5606 // Check to see if we already analyzed this PHI.
5607 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5608 if (I != PredicatedSCEVRewrites.end()) {
5609 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5610 I->second;
5611 // Analysis was done before and failed to create an AddRec:
5612 if (Rewrite.first == SymbolicPHI)
5613 return std::nullopt;
5614 // Analysis was done before and succeeded to create an AddRec under
5615 // a predicate:
5616 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5617 assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5618 return Rewrite;
5619 }
5620
5621 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5622 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5623
5624 // Record in the cache that the analysis failed
5625 if (!Rewrite) {
5627 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5628 return std::nullopt;
5629 }
5630
5631 return Rewrite;
5632}
5633
5634// FIXME: This utility is currently required because the Rewriter currently
5635// does not rewrite this expression:
5636// {0, +, (sext ix (trunc iy to ix) to iy)}
5637// into {0, +, %step},
5638// even when the following Equal predicate exists:
5639// "%step == (sext ix (trunc iy to ix) to iy)".
5641 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2,
5642 ArrayRef<const SCEVPredicate *> NoWrapPreds) const {
5643 if (AR1 == AR2)
5644 return true;
5645
5646 SCEVUnionPredicate NoWrapUnionPred(NoWrapPreds, SE);
5647 SCEVUnionPredicate AllPreds = Preds->getUnionWith(&NoWrapUnionPred, SE);
5648 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5649 if (Expr1 != Expr2 &&
5650 !AllPreds.implies(SE.getEqualPredicate(Expr1, Expr2), SE) &&
5651 !AllPreds.implies(SE.getEqualPredicate(Expr2, Expr1), SE))
5652 return false;
5653 return true;
5654 };
5655
5656 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5657 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5658 return false;
5659 return true;
5660}
5661
5662/// A helper function for createAddRecFromPHI to handle simple cases.
5663///
5664/// This function tries to find an AddRec expression for the simplest (yet most
5665/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5666/// If it fails, createAddRecFromPHI will use a more general, but slow,
5667/// technique for finding the AddRec expression.
5668const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5669 Value *BEValueV,
5670 Value *StartValueV) {
5671 const Loop *L = LI.getLoopFor(PN->getParent());
5672 assert(L && L->getHeader() == PN->getParent());
5673 assert(BEValueV && StartValueV);
5674
5675 auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN);
5676 if (!BO)
5677 return nullptr;
5678
5679 if (BO->Opcode != Instruction::Add)
5680 return nullptr;
5681
5682 const SCEV *Accum = nullptr;
5683 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5684 Accum = getSCEV(BO->RHS);
5685 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5686 Accum = getSCEV(BO->LHS);
5687
5688 if (!Accum)
5689 return nullptr;
5690
5692 if (BO->IsNUW)
5693 Flags = setFlags(Flags, SCEV::FlagNUW);
5694 if (BO->IsNSW)
5695 Flags = setFlags(Flags, SCEV::FlagNSW);
5696
5697 const SCEV *StartVal = getSCEV(StartValueV);
5698 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5699 insertValueToMap(PN, PHISCEV);
5700
5701 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5702 inferNoWrapViaConstantRanges(AR);
5703
5704 // We can add Flags to the post-inc expression only if we
5705 // know that it is *undefined behavior* for BEValueV to
5706 // overflow.
5707 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5708 assert(isLoopInvariant(Accum, L) &&
5709 "Accum is defined outside L, but is not invariant?");
5710 if (isAddRecNeverPoison(BEInst, L))
5711 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5712 }
5713
5714 return PHISCEV;
5715}
5716
5717const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5718 const Loop *L = LI.getLoopFor(PN->getParent());
5719 if (!L || L->getHeader() != PN->getParent())
5720 return nullptr;
5721
5722 // The loop may have multiple entrances or multiple exits; we can analyze
5723 // this phi as an addrec if it has a unique entry value and a unique
5724 // backedge value.
5725 Value *BEValueV = nullptr, *StartValueV = nullptr;
5726 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5727 Value *V = PN->getIncomingValue(i);
5728 if (L->contains(PN->getIncomingBlock(i))) {
5729 if (!BEValueV) {
5730 BEValueV = V;
5731 } else if (BEValueV != V) {
5732 BEValueV = nullptr;
5733 break;
5734 }
5735 } else if (!StartValueV) {
5736 StartValueV = V;
5737 } else if (StartValueV != V) {
5738 StartValueV = nullptr;
5739 break;
5740 }
5741 }
5742 if (!BEValueV || !StartValueV)
5743 return nullptr;
5744
5745 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5746 "PHI node already processed?");
5747
5748 // First, try to find AddRec expression without creating a fictituos symbolic
5749 // value for PN.
5750 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5751 return S;
5752
5753 // Handle PHI node value symbolically.
5754 const SCEV *SymbolicName = getUnknown(PN);
5755 insertValueToMap(PN, SymbolicName);
5756
5757 // Using this symbolic name for the PHI, analyze the value coming around
5758 // the back-edge.
5759 const SCEV *BEValue = getSCEV(BEValueV);
5760
5761 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5762 // has a special value for the first iteration of the loop.
5763
5764 // If the value coming around the backedge is an add with the symbolic
5765 // value we just inserted, then we found a simple induction variable!
5766 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5767 // If there is a single occurrence of the symbolic value, replace it
5768 // with a recurrence.
5769 unsigned FoundIndex = Add->getNumOperands();
5770 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5771 if (Add->getOperand(i) == SymbolicName)
5772 if (FoundIndex == e) {
5773 FoundIndex = i;
5774 break;
5775 }
5776
5777 if (FoundIndex != Add->getNumOperands()) {
5778 // Create an add with everything but the specified operand.
5780 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5781 if (i != FoundIndex)
5782 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5783 L, *this));
5784 const SCEV *Accum = getAddExpr(Ops);
5785
5786 // This is not a valid addrec if the step amount is varying each
5787 // loop iteration, but is not itself an addrec in this loop.
5788 if (isLoopInvariant(Accum, L) ||
5789 (isa<SCEVAddRecExpr>(Accum) &&
5790 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5792
5793 if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
5794 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5795 if (BO->IsNUW)
5796 Flags = setFlags(Flags, SCEV::FlagNUW);
5797 if (BO->IsNSW)
5798 Flags = setFlags(Flags, SCEV::FlagNSW);
5799 }
5800 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5801 if (GEP->getOperand(0) == PN) {
5802 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
5803 // If the increment has any nowrap flags, then we know the address
5804 // space cannot be wrapped around.
5805 if (NW != GEPNoWrapFlags::none())
5806 Flags = setFlags(Flags, SCEV::FlagNW);
5807 // If the GEP is nuw or nusw with non-negative offset, we know that
5808 // no unsigned wrap occurs. We cannot set the nsw flag as only the
5809 // offset is treated as signed, while the base is unsigned.
5810 if (NW.hasNoUnsignedWrap() ||
5812 Flags = setFlags(Flags, SCEV::FlagNUW);
5813 }
5814
5815 // We cannot transfer nuw and nsw flags from subtraction
5816 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5817 // for instance.
5818 }
5819
5820 const SCEV *StartVal = getSCEV(StartValueV);
5821 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5822
5823 // Okay, for the entire analysis of this edge we assumed the PHI
5824 // to be symbolic. We now need to go back and purge all of the
5825 // entries for the scalars that use the symbolic expression.
5826 forgetMemoizedResults({SymbolicName});
5827 insertValueToMap(PN, PHISCEV);
5828
5829 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5830 inferNoWrapViaConstantRanges(AR);
5831
5832 // We can add Flags to the post-inc expression only if we
5833 // know that it is *undefined behavior* for BEValueV to
5834 // overflow.
5835 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5836 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5837 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5838
5839 return PHISCEV;
5840 }
5841 }
5842 } else {
5843 // Otherwise, this could be a loop like this:
5844 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5845 // In this case, j = {1,+,1} and BEValue is j.
5846 // Because the other in-value of i (0) fits the evolution of BEValue
5847 // i really is an addrec evolution.
5848 //
5849 // We can generalize this saying that i is the shifted value of BEValue
5850 // by one iteration:
5851 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5852
5853 // Do not allow refinement in rewriting of BEValue.
5854 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5855 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5856 if (Shifted != getCouldNotCompute() && Start != getCouldNotCompute() &&
5857 isGuaranteedNotToCauseUB(Shifted) && ::impliesPoison(Shifted, Start)) {
5858 const SCEV *StartVal = getSCEV(StartValueV);
5859 if (Start == StartVal) {
5860 // Okay, for the entire analysis of this edge we assumed the PHI
5861 // to be symbolic. We now need to go back and purge all of the
5862 // entries for the scalars that use the symbolic expression.
5863 forgetMemoizedResults({SymbolicName});
5864 insertValueToMap(PN, Shifted);
5865 return Shifted;
5866 }
5867 }
5868 }
5869
5870 // Remove the temporary PHI node SCEV that has been inserted while intending
5871 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5872 // as it will prevent later (possibly simpler) SCEV expressions to be added
5873 // to the ValueExprMap.
5874 eraseValueFromMap(PN);
5875
5876 return nullptr;
5877}
5878
5879// Try to match a control flow sequence that branches out at BI and merges back
5880// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5881// match.
5883 Value *&C, Value *&LHS, Value *&RHS) {
5884 C = BI->getCondition();
5885
5886 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5887 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5888
5889 Use &LeftUse = Merge->getOperandUse(0);
5890 Use &RightUse = Merge->getOperandUse(1);
5891
5892 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5893 LHS = LeftUse;
5894 RHS = RightUse;
5895 return true;
5896 }
5897
5898 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5899 LHS = RightUse;
5900 RHS = LeftUse;
5901 return true;
5902 }
5903
5904 return false;
5905}
5906
5908 Value *&Cond, Value *&LHS,
5909 Value *&RHS) {
5910 auto IsReachable =
5911 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5912 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5913 // Try to match
5914 //
5915 // br %cond, label %left, label %right
5916 // left:
5917 // br label %merge
5918 // right:
5919 // br label %merge
5920 // merge:
5921 // V = phi [ %x, %left ], [ %y, %right ]
5922 //
5923 // as "select %cond, %x, %y"
5924
5925 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5926 assert(IDom && "At least the entry block should dominate PN");
5927
5928 auto *BI = dyn_cast<CondBrInst>(IDom->getTerminator());
5929 return BI && BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS);
5930 }
5931 return false;
5932}
5933
5934const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5935 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5936 if (getOperandsForSelectLikePHI(DT, PN, Cond, LHS, RHS) &&
5939 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5940
5941 return nullptr;
5942}
5943
5945 BinaryOperator *CommonInst = nullptr;
5946 // Check if instructions are identical.
5947 for (Value *Incoming : PN->incoming_values()) {
5948 auto *IncomingInst = dyn_cast<BinaryOperator>(Incoming);
5949 if (!IncomingInst)
5950 return nullptr;
5951 if (CommonInst) {
5952 if (!CommonInst->isIdenticalToWhenDefined(IncomingInst))
5953 return nullptr; // Not identical, give up
5954 } else {
5955 // Remember binary operator
5956 CommonInst = IncomingInst;
5957 }
5958 }
5959 return CommonInst;
5960}
5961
5962/// Returns SCEV for the first operand of a phi if all phi operands have
5963/// identical opcodes and operands
5964/// eg.
5965/// a: %add = %a + %b
5966/// br %c
5967/// b: %add1 = %a + %b
5968/// br %c
5969/// c: %phi = phi [%add, a], [%add1, b]
5970/// scev(%phi) => scev(%add)
5971const SCEV *
5972ScalarEvolution::createNodeForPHIWithIdenticalOperands(PHINode *PN) {
5973 BinaryOperator *CommonInst = getCommonInstForPHI(PN);
5974 if (!CommonInst)
5975 return nullptr;
5976
5977 // Check if SCEV exprs for instructions are identical.
5978 const SCEV *CommonSCEV = getSCEV(CommonInst);
5979 bool SCEVExprsIdentical =
5981 [this, CommonSCEV](Value *V) { return CommonSCEV == getSCEV(V); });
5982 return SCEVExprsIdentical ? CommonSCEV : nullptr;
5983}
5984
5985const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5986 if (const SCEV *S = createAddRecFromPHI(PN))
5987 return S;
5988
5989 // We do not allow simplifying phi (undef, X) to X here, to avoid reusing the
5990 // phi node for X.
5991 if (Value *V = simplifyInstruction(
5992 PN, {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
5993 /*UseInstrInfo=*/true, /*CanUseUndef=*/false}))
5994 return getSCEV(V);
5995
5996 if (const SCEV *S = createNodeForPHIWithIdenticalOperands(PN))
5997 return S;
5998
5999 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
6000 return S;
6001
6002 // If it's not a loop phi, we can't handle it yet.
6003 return getUnknown(PN);
6004}
6005
6006bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
6007 SCEVTypes RootKind) {
6008 struct FindClosure {
6009 const SCEV *OperandToFind;
6010 const SCEVTypes RootKind; // Must be a sequential min/max expression.
6011 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
6012
6013 bool Found = false;
6014
6015 bool canRecurseInto(SCEVTypes Kind) const {
6016 // We can only recurse into the SCEV expression of the same effective type
6017 // as the type of our root SCEV expression, and into zero-extensions.
6018 return RootKind == Kind || NonSequentialRootKind == Kind ||
6019 scZeroExtend == Kind;
6020 };
6021
6022 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
6023 : OperandToFind(OperandToFind), RootKind(RootKind),
6024 NonSequentialRootKind(
6026 RootKind)) {}
6027
6028 bool follow(const SCEV *S) {
6029 Found = S == OperandToFind;
6030
6031 return !isDone() && canRecurseInto(S->getSCEVType());
6032 }
6033
6034 bool isDone() const { return Found; }
6035 };
6036
6037 FindClosure FC(OperandToFind, RootKind);
6038 visitAll(Root, FC);
6039 return FC.Found;
6040}
6041
6042std::optional<const SCEV *>
6043ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
6044 ICmpInst *Cond,
6045 Value *TrueVal,
6046 Value *FalseVal) {
6047 // Try to match some simple smax or umax patterns.
6048 auto *ICI = Cond;
6049
6050 Value *LHS = ICI->getOperand(0);
6051 Value *RHS = ICI->getOperand(1);
6052
6053 switch (ICI->getPredicate()) {
6054 case ICmpInst::ICMP_SLT:
6055 case ICmpInst::ICMP_SLE:
6056 case ICmpInst::ICMP_ULT:
6057 case ICmpInst::ICMP_ULE:
6058 std::swap(LHS, RHS);
6059 [[fallthrough]];
6060 case ICmpInst::ICMP_SGT:
6061 case ICmpInst::ICMP_SGE:
6062 case ICmpInst::ICMP_UGT:
6063 case ICmpInst::ICMP_UGE:
6064 // a > b ? a+x : b+x -> max(a, b)+x
6065 // a > b ? b+x : a+x -> min(a, b)+x
6067 bool Signed = ICI->isSigned();
6068 const SCEV *LA = getSCEV(TrueVal);
6069 const SCEV *RA = getSCEV(FalseVal);
6070 const SCEV *LS = getSCEV(LHS);
6071 const SCEV *RS = getSCEV(RHS);
6072 if (LA->getType()->isPointerTy()) {
6073 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6074 // Need to make sure we can't produce weird expressions involving
6075 // negated pointers.
6076 if (LA == LS && RA == RS)
6077 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6078 if (LA == RS && RA == LS)
6079 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6080 }
6081 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6082 if (Op->getType()->isPointerTy()) {
6085 return Op;
6086 }
6087 if (Signed)
6088 Op = getNoopOrSignExtend(Op, Ty);
6089 else
6090 Op = getNoopOrZeroExtend(Op, Ty);
6091 return Op;
6092 };
6093 LS = CoerceOperand(LS);
6094 RS = CoerceOperand(RS);
6096 break;
6097 const SCEV *LDiff = getMinusSCEV(LA, LS);
6098 const SCEV *RDiff = getMinusSCEV(RA, RS);
6099 if (LDiff == RDiff)
6100 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6101 LDiff);
6102 LDiff = getMinusSCEV(LA, RS);
6103 RDiff = getMinusSCEV(RA, LS);
6104 if (LDiff == RDiff)
6105 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6106 LDiff);
6107 }
6108 break;
6109 case ICmpInst::ICMP_NE:
6110 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
6111 std::swap(TrueVal, FalseVal);
6112 [[fallthrough]];
6113 case ICmpInst::ICMP_EQ:
6114 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
6117 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6118 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y
6119 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y
6120 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6121 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y
6122 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6123 return getAddExpr(getUMaxExpr(X, C), Y);
6124 }
6125 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
6126 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
6127 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
6128 // -> umin_seq(x, umin (..., umin_seq(...), ...))
6130 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6131 const SCEV *X = getSCEV(LHS);
6132 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6133 X = ZExt->getOperand();
6134 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6135 const SCEV *FalseValExpr = getSCEV(FalseVal);
6136 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6137 return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6138 /*Sequential=*/true);
6139 }
6140 }
6141 break;
6142 default:
6143 break;
6144 }
6145
6146 return std::nullopt;
6147}
6148
6149static std::optional<const SCEV *>
6151 const SCEV *TrueExpr, const SCEV *FalseExpr) {
6152 assert(CondExpr->getType()->isIntegerTy(1) &&
6153 TrueExpr->getType() == FalseExpr->getType() &&
6154 TrueExpr->getType()->isIntegerTy(1) &&
6155 "Unexpected operands of a select.");
6156
6157 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
6158 // --> C + (umin_seq cond, x - C)
6159 //
6160 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
6161 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6162 // --> C + (umin_seq ~cond, x - C)
6163
6164 // FIXME: while we can't legally model the case where both of the hands
6165 // are fully variable, we only require that the *difference* is constant.
6166 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6167 return std::nullopt;
6168
6169 const SCEV *X, *C;
6170 if (isa<SCEVConstant>(TrueExpr)) {
6171 CondExpr = SE->getNotSCEV(CondExpr);
6172 X = FalseExpr;
6173 C = TrueExpr;
6174 } else {
6175 X = TrueExpr;
6176 C = FalseExpr;
6177 }
6178 return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6179 /*Sequential=*/true));
6180}
6181
6182static std::optional<const SCEV *>
6184 Value *FalseVal) {
6185 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6186 return std::nullopt;
6187
6188 const auto *SECond = SE->getSCEV(Cond);
6189 const auto *SETrue = SE->getSCEV(TrueVal);
6190 const auto *SEFalse = SE->getSCEV(FalseVal);
6191 return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6192}
6193
6194const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6195 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6196 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6197 assert(TrueVal->getType() == FalseVal->getType() &&
6198 V->getType() == TrueVal->getType() &&
6199 "Types of select hands and of the result must match.");
6200
6201 // For now, only deal with i1-typed `select`s.
6202 if (!V->getType()->isIntegerTy(1))
6203 return getUnknown(V);
6204
6205 if (std::optional<const SCEV *> S =
6206 createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6207 return *S;
6208
6209 return getUnknown(V);
6210}
6211
6212const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6213 Value *TrueVal,
6214 Value *FalseVal) {
6215 // Handle "constant" branch or select. This can occur for instance when a
6216 // loop pass transforms an inner loop and moves on to process the outer loop.
6217 if (auto *CI = dyn_cast<ConstantInt>(Cond))
6218 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6219
6220 if (auto *I = dyn_cast<Instruction>(V)) {
6221 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6222 if (std::optional<const SCEV *> S =
6223 createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6224 TrueVal, FalseVal))
6225 return *S;
6226 }
6227 }
6228
6229 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6230}
6231
6232/// Expand GEP instructions into add and multiply operations. This allows them
6233/// to be analyzed by regular SCEV code.
6234const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6235 assert(GEP->getSourceElementType()->isSized() &&
6236 "GEP source element type must be sized");
6237
6238 SmallVector<SCEVUse, 4> IndexExprs;
6239 for (Value *Index : GEP->indices())
6240 IndexExprs.push_back(getSCEV(Index));
6241 return getGEPExpr(GEP, IndexExprs);
6242}
6243
6244APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S,
6245 const Instruction *CtxI) {
6247 auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6248 return TrailingZeros >= BitWidth
6250 : APInt::getOneBitSet(BitWidth, TrailingZeros);
6251 };
6252 auto GetGCDMultiple = [this, CtxI](const SCEVNAryExpr *N) {
6253 // The result is GCD of all operands results.
6254 APInt Res = getConstantMultiple(N->getOperand(0), CtxI);
6255 for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6257 Res, getConstantMultiple(N->getOperand(I), CtxI));
6258 return Res;
6259 };
6260
6261 switch (S->getSCEVType()) {
6262 case scConstant:
6263 return cast<SCEVConstant>(S)->getAPInt();
6264 case scPtrToAddr:
6265 return getConstantMultiple(cast<SCEVCastExpr>(S)->getOperand());
6266 case scUDivExpr:
6267 case scVScale:
6268 return APInt(BitWidth, 1);
6269 case scTruncate: {
6270 // Only multiples that are a power of 2 will hold after truncation.
6271 const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6272 uint32_t TZ = getMinTrailingZeros(T->getOperand(), CtxI);
6273 return GetShiftedByZeros(TZ);
6274 }
6275 case scZeroExtend: {
6276 const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(S);
6277 return getConstantMultiple(Z->getOperand(), CtxI).zext(BitWidth);
6278 }
6279 case scSignExtend: {
6280 // Only multiples that are a power of 2 will hold after sext.
6281 const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6282 uint32_t TZ = getMinTrailingZeros(E->getOperand(), CtxI);
6283 return GetShiftedByZeros(TZ);
6284 }
6285 case scMulExpr: {
6286 const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6287 if (M->hasNoUnsignedWrap()) {
6288 // The result is the product of all operand results.
6289 APInt Res = getConstantMultiple(M->getOperand(0), CtxI);
6290 for (const SCEV *Operand : M->operands().drop_front())
6291 Res = Res * getConstantMultiple(Operand, CtxI);
6292 return Res;
6293 }
6294
6295 // If there are no wrap guarentees, find the trailing zeros, which is the
6296 // sum of trailing zeros for all its operands.
6297 uint32_t TZ = 0;
6298 for (const SCEV *Operand : M->operands())
6299 TZ += getMinTrailingZeros(Operand, CtxI);
6300 return GetShiftedByZeros(TZ);
6301 }
6302 case scAddExpr:
6303 case scAddRecExpr: {
6304 const SCEVNAryExpr *N = cast<SCEVNAryExpr>(S);
6305 if (N->hasNoUnsignedWrap())
6306 return GetGCDMultiple(N);
6307 // Find the trailing bits, which is the minimum of its operands.
6308 uint32_t TZ = getMinTrailingZeros(N->getOperand(0), CtxI);
6309 for (const SCEV *Operand : N->operands().drop_front())
6310 TZ = std::min(TZ, getMinTrailingZeros(Operand, CtxI));
6311 return GetShiftedByZeros(TZ);
6312 }
6313 case scUMaxExpr:
6314 case scSMaxExpr:
6315 case scUMinExpr:
6316 case scSMinExpr:
6318 return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6319 case scUnknown: {
6320 // Ask ValueTracking for known bits. SCEVUnknown only become available at
6321 // the point their underlying IR instruction has been defined. If CtxI was
6322 // not provided, use:
6323 // * the first instruction in the entry block if it is an argument
6324 // * the instruction itself otherwise.
6325 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6326 if (!CtxI) {
6327 if (isa<Argument>(U->getValue()))
6328 CtxI = &*F.getEntryBlock().begin();
6329 else if (auto *I = dyn_cast<Instruction>(U->getValue()))
6330 CtxI = I;
6331 }
6332 unsigned Known =
6333 computeKnownBits(U->getValue(),
6334 SimplifyQuery(getDataLayout(), &DT, &AC, CtxI)
6335 .allowEphemerals(true))
6336 .countMinTrailingZeros();
6337 return GetShiftedByZeros(Known);
6338 }
6339 case scCouldNotCompute:
6340 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6341 }
6342 llvm_unreachable("Unknown SCEV kind!");
6343}
6344
6346 const Instruction *CtxI) {
6347 // Skip looking up and updating the cache if there is a context instruction,
6348 // as the result will only be valid in the specified context.
6349 if (CtxI)
6350 return getConstantMultipleImpl(S, CtxI);
6351
6352 auto I = ConstantMultipleCache.find(S);
6353 if (I != ConstantMultipleCache.end())
6354 return I->second;
6355
6356 APInt Result = getConstantMultipleImpl(S, CtxI);
6357 auto InsertPair = ConstantMultipleCache.insert({S, Result});
6358 assert(InsertPair.second && "Should insert a new key");
6359 return InsertPair.first->second;
6360}
6361
6363 APInt Multiple = getConstantMultiple(S);
6364 return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6365}
6366
6368 const Instruction *CtxI) {
6369 return std::min(getConstantMultiple(S, CtxI).countTrailingZeros(),
6370 (unsigned)getTypeSizeInBits(S->getType()));
6371}
6372
6373/// Helper method to assign a range to V from metadata present in the IR.
6374static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6376 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6377 return getConstantRangeFromMetadata(*MD);
6378 if (const auto *CB = dyn_cast<CallBase>(V))
6379 if (std::optional<ConstantRange> Range = CB->getRange())
6380 return Range;
6381 }
6382 if (auto *A = dyn_cast<Argument>(V))
6383 if (std::optional<ConstantRange> Range = A->getRange())
6384 return Range;
6385
6386 return std::nullopt;
6387}
6388
6390 SCEV::NoWrapFlags Flags) {
6391 if (AddRec->getNoWrapFlags(Flags) != Flags) {
6392 AddRec->setNoWrapFlags(Flags);
6393 UnsignedRanges.erase(AddRec);
6394 SignedRanges.erase(AddRec);
6395 ConstantMultipleCache.erase(AddRec);
6396 }
6397}
6398
6399ConstantRange ScalarEvolution::
6400getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6401 const DataLayout &DL = getDataLayout();
6402
6403 unsigned BitWidth = getTypeSizeInBits(U->getType());
6404 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6405
6406 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6407 // use information about the trip count to improve our available range. Note
6408 // that the trip count independent cases are already handled by known bits.
6409 // WARNING: The definition of recurrence used here is subtly different than
6410 // the one used by AddRec (and thus most of this file). Step is allowed to
6411 // be arbitrarily loop varying here, where AddRec allows only loop invariant
6412 // and other addrecs in the same loop (for non-affine addrecs). The code
6413 // below intentionally handles the case where step is not loop invariant.
6414 auto *P = dyn_cast<PHINode>(U->getValue());
6415 if (!P)
6416 return FullSet;
6417
6418 // Make sure that no Phi input comes from an unreachable block. Otherwise,
6419 // even the values that are not available in these blocks may come from them,
6420 // and this leads to false-positive recurrence test.
6421 for (auto *Pred : predecessors(P->getParent()))
6422 if (!DT.isReachableFromEntry(Pred))
6423 return FullSet;
6424
6425 BinaryOperator *BO;
6426 Value *Start, *Step;
6427 if (!matchSimpleRecurrence(P, BO, Start, Step))
6428 return FullSet;
6429
6430 // If we found a recurrence in reachable code, we must be in a loop. Note
6431 // that BO might be in some subloop of L, and that's completely okay.
6432 auto *L = LI.getLoopFor(P->getParent());
6433 assert(L && L->getHeader() == P->getParent());
6434 if (!L->contains(BO->getParent()))
6435 // NOTE: This bailout should be an assert instead. However, asserting
6436 // the condition here exposes a case where LoopFusion is querying SCEV
6437 // with malformed loop information during the midst of the transform.
6438 // There doesn't appear to be an obvious fix, so for the moment bailout
6439 // until the caller issue can be fixed. PR49566 tracks the bug.
6440 return FullSet;
6441
6442 // TODO: Extend to other opcodes such as mul, and div
6443 switch (BO->getOpcode()) {
6444 default:
6445 return FullSet;
6446 case Instruction::AShr:
6447 case Instruction::LShr:
6448 case Instruction::Shl:
6449 break;
6450 };
6451
6452 if (BO->getOperand(0) != P)
6453 // TODO: Handle the power function forms some day.
6454 return FullSet;
6455
6456 unsigned TC = getSmallConstantMaxTripCount(L);
6457 if (!TC || TC >= BitWidth)
6458 return FullSet;
6459
6460 auto KnownStart = computeKnownBits(Start, DL, &AC, nullptr, &DT);
6461 auto KnownStep = computeKnownBits(Step, DL, &AC, nullptr, &DT);
6462 assert(KnownStart.getBitWidth() == BitWidth &&
6463 KnownStep.getBitWidth() == BitWidth);
6464
6465 // Compute total shift amount, being careful of overflow and bitwidths.
6466 auto MaxShiftAmt = KnownStep.getMaxValue();
6467 APInt TCAP(BitWidth, TC-1);
6468 bool Overflow = false;
6469 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6470 if (Overflow)
6471 return FullSet;
6472
6473 switch (BO->getOpcode()) {
6474 default:
6475 llvm_unreachable("filtered out above");
6476 case Instruction::AShr: {
6477 // For each ashr, three cases:
6478 // shift = 0 => unchanged value
6479 // saturation => 0 or -1
6480 // other => a value closer to zero (of the same sign)
6481 // Thus, the end value is closer to zero than the start.
6482 auto KnownEnd = KnownBits::ashr(KnownStart,
6483 KnownBits::makeConstant(TotalShift));
6484 if (KnownStart.isNonNegative())
6485 // Analogous to lshr (simply not yet canonicalized)
6486 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6487 KnownStart.getMaxValue() + 1);
6488 if (KnownStart.isNegative())
6489 // End >=u Start && End <=s Start
6490 return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6491 KnownEnd.getMaxValue() + 1);
6492 break;
6493 }
6494 case Instruction::LShr: {
6495 // For each lshr, three cases:
6496 // shift = 0 => unchanged value
6497 // saturation => 0
6498 // other => a smaller positive number
6499 // Thus, the low end of the unsigned range is the last value produced.
6500 auto KnownEnd = KnownBits::lshr(KnownStart,
6501 KnownBits::makeConstant(TotalShift));
6502 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6503 KnownStart.getMaxValue() + 1);
6504 }
6505 case Instruction::Shl: {
6506 // Iff no bits are shifted out, value increases on every shift.
6507 auto KnownEnd = KnownBits::shl(KnownStart,
6508 KnownBits::makeConstant(TotalShift));
6509 if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6510 return ConstantRange(KnownStart.getMinValue(),
6511 KnownEnd.getMaxValue() + 1);
6512 break;
6513 }
6514 };
6515 return FullSet;
6516}
6517
6518// The goal of this function is to check if recursively visiting the operands
6519// of this PHI might lead to an infinite loop. If we do see such a loop,
6520// there's no good way to break it, so we avoid analyzing such cases.
6521//
6522// getRangeRef previously used a visited set to avoid infinite loops, but this
6523// caused other issues: the result was dependent on the order of getRangeRef
6524// calls, and the interaction with createSCEVIter could cause a stack overflow
6525// in some cases (see issue #148253).
6526//
6527// FIXME: The way this is implemented is overly conservative; this checks
6528// for a few obviously safe patterns, but anything that doesn't lead to
6529// recursion is fine.
6531 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6533 return true;
6534
6535 if (all_of(PHI->operands(),
6536 [&](Value *Operand) { return DT.dominates(Operand, PHI); }))
6537 return true;
6538
6539 return false;
6540}
6541
6542const ConstantRange &
6543ScalarEvolution::getRangeRefIter(const SCEV *S,
6544 ScalarEvolution::RangeSignHint SignHint) {
6545 DenseMap<const SCEV *, ConstantRange> &Cache =
6546 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6547 : SignedRanges;
6548 SmallVector<SCEVUse> WorkList;
6549 SmallPtrSet<const SCEV *, 8> Seen;
6550
6551 // Add Expr to the worklist, if Expr is either an N-ary expression or a
6552 // SCEVUnknown PHI node.
6553 auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6554 if (!Seen.insert(Expr).second)
6555 return;
6556 if (Cache.contains(Expr))
6557 return;
6558 switch (Expr->getSCEVType()) {
6559 case scUnknown:
6561 break;
6562 [[fallthrough]];
6563 case scConstant:
6564 case scVScale:
6565 case scTruncate:
6566 case scZeroExtend:
6567 case scSignExtend:
6568 case scPtrToAddr:
6569 case scAddExpr:
6570 case scMulExpr:
6571 case scUDivExpr:
6572 case scAddRecExpr:
6573 case scUMaxExpr:
6574 case scSMaxExpr:
6575 case scUMinExpr:
6576 case scSMinExpr:
6578 WorkList.push_back(Expr);
6579 break;
6580 case scCouldNotCompute:
6581 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6582 }
6583 };
6584 AddToWorklist(S);
6585
6586 // Build worklist by queuing operands of N-ary expressions and phi nodes.
6587 for (unsigned I = 0; I != WorkList.size(); ++I) {
6588 const SCEV *P = WorkList[I];
6589 auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6590 // If it is not a `SCEVUnknown`, just recurse into operands.
6591 if (!UnknownS) {
6592 for (const SCEV *Op : P->operands())
6593 AddToWorklist(Op);
6594 continue;
6595 }
6596 // `SCEVUnknown`'s require special treatment.
6597 if (PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6598 if (!RangeRefPHIAllowedOperands(DT, P))
6599 continue;
6600 for (auto &Op : reverse(P->operands()))
6601 AddToWorklist(getSCEV(Op));
6602 }
6603 }
6604
6605 if (!WorkList.empty()) {
6606 // Use getRangeRef to compute ranges for items in the worklist in reverse
6607 // order. This will force ranges for earlier operands to be computed before
6608 // their users in most cases.
6609 for (const SCEV *P : reverse(drop_begin(WorkList))) {
6610 getRangeRef(P, SignHint);
6611 }
6612 }
6613
6614 return getRangeRef(S, SignHint, 0);
6615}
6616
6617const APInt *ScalarEvolution::getConstantAPIntOrNull(const SCEV *S) {
6618 if (const auto *C = dyn_cast<SCEVConstant>(S))
6619 return &C->getAPInt();
6620 return nullptr;
6621}
6622
6623/// Determine the range for a particular SCEV. If SignHint is
6624/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6625/// with a "cleaner" unsigned (resp. signed) representation.
6626const ConstantRange &ScalarEvolution::getRangeRef(
6627 const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6628 DenseMap<const SCEV *, ConstantRange> &Cache =
6629 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6630 : SignedRanges;
6632 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6634
6635 // See if we've computed this range already.
6636 auto I = Cache.find(S);
6637 if (I != Cache.end())
6638 return I->second;
6639
6640 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6641 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6642
6643 // Switch to iteratively computing the range for S, if it is part of a deeply
6644 // nested expression.
6646 return getRangeRefIter(S, SignHint);
6647
6648 unsigned BitWidth = getTypeSizeInBits(S->getType());
6649 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6650 using OBO = OverflowingBinaryOperator;
6651
6652 // If the value has known zeros, the maximum value will have those known zeros
6653 // as well.
6654 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6655 APInt Multiple = getNonZeroConstantMultiple(S);
6656 APInt Remainder = APInt::getMaxValue(BitWidth).urem(Multiple);
6657 if (!Remainder.isZero())
6658 ConservativeResult =
6659 ConstantRange(APInt::getMinValue(BitWidth),
6660 APInt::getMaxValue(BitWidth) - Remainder + 1);
6661 }
6662 else {
6663 uint32_t TZ = getMinTrailingZeros(S);
6664 if (TZ != 0) {
6665 ConservativeResult = ConstantRange(
6667 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6668 }
6669 }
6670
6671 switch (S->getSCEVType()) {
6672 case scConstant:
6673 llvm_unreachable("Already handled above.");
6674 case scVScale:
6675 return setRange(S, SignHint, getVScaleRange(&F, BitWidth));
6676 case scTruncate: {
6677 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6678 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6679 return setRange(
6680 Trunc, SignHint,
6681 ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6682 }
6683 case scZeroExtend: {
6684 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6685 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6686 return setRange(
6687 ZExt, SignHint,
6688 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6689 }
6690 case scSignExtend: {
6691 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6692 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6693 return setRange(
6694 SExt, SignHint,
6695 ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6696 }
6697 case scPtrToAddr: {
6698 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6699 ConstantRange X = getRangeRef(Cast->getOperand(), SignHint, Depth + 1);
6700 return setRange(Cast, SignHint, X);
6701 }
6702 case scAddExpr: {
6703 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6704 // Check if this is a URem pattern: A - (A / B) * B, which is always < B.
6705 const SCEV *URemLHS = nullptr, *URemRHS = nullptr;
6706 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED &&
6707 match(S, m_scev_URem(m_SCEV(URemLHS), m_SCEV(URemRHS), *this))) {
6708 ConstantRange LHSRange = getRangeRef(URemLHS, SignHint, Depth + 1);
6709 ConstantRange RHSRange = getRangeRef(URemRHS, SignHint, Depth + 1);
6710 ConservativeResult =
6711 ConservativeResult.intersectWith(LHSRange.urem(RHSRange), RangeType);
6712 }
6713 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6714 unsigned WrapType = OBO::AnyWrap;
6715 if (Add->hasNoSignedWrap())
6716 WrapType |= OBO::NoSignedWrap;
6717 if (Add->hasNoUnsignedWrap())
6718 WrapType |= OBO::NoUnsignedWrap;
6719 for (const SCEV *Op : drop_begin(Add->operands()))
6720 X = X.addWithNoWrap(getRangeRef(Op, SignHint, Depth + 1), WrapType,
6721 RangeType);
6722 return setRange(Add, SignHint,
6723 ConservativeResult.intersectWith(X, RangeType));
6724 }
6725 case scMulExpr: {
6726 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6727 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6728 for (const SCEV *Op : drop_begin(Mul->operands()))
6729 X = X.multiply(getRangeRef(Op, SignHint, Depth + 1));
6730 return setRange(Mul, SignHint,
6731 ConservativeResult.intersectWith(X, RangeType));
6732 }
6733 case scUDivExpr: {
6734 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6735 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6736 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6737 return setRange(UDiv, SignHint,
6738 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6739 }
6740 case scAddRecExpr: {
6741 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6742 // If there's no unsigned wrap, the value will never be less than its
6743 // initial value.
6744 if (AddRec->hasNoUnsignedWrap()) {
6745 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6746 if (!UnsignedMinValue.isZero())
6747 ConservativeResult = ConservativeResult.intersectWith(
6748 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6749 }
6750
6751 // If there's no signed wrap, and all the operands except initial value have
6752 // the same sign or zero, the value won't ever be:
6753 // 1: smaller than initial value if operands are non negative,
6754 // 2: bigger than initial value if operands are non positive.
6755 // For both cases, value can not cross signed min/max boundary.
6756 if (AddRec->hasNoSignedWrap()) {
6757 bool AllNonNeg = true;
6758 bool AllNonPos = true;
6759 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6760 if (!isKnownNonNegative(AddRec->getOperand(i)))
6761 AllNonNeg = false;
6762 if (!isKnownNonPositive(AddRec->getOperand(i)))
6763 AllNonPos = false;
6764 }
6765 if (AllNonNeg)
6766 ConservativeResult = ConservativeResult.intersectWith(
6769 RangeType);
6770 else if (AllNonPos)
6771 ConservativeResult = ConservativeResult.intersectWith(
6773 getSignedRangeMax(AddRec->getStart()) +
6774 1),
6775 RangeType);
6776 }
6777
6778 // TODO: non-affine addrec
6779 if (AddRec->isAffine()) {
6780 const SCEV *MaxBEScev =
6782 if (!isa<SCEVCouldNotCompute>(MaxBEScev)) {
6783 APInt MaxBECount = cast<SCEVConstant>(MaxBEScev)->getAPInt();
6784
6785 // Adjust MaxBECount to the same bitwidth as AddRec. We can truncate if
6786 // MaxBECount's active bits are all <= AddRec's bit width.
6787 if (MaxBECount.getBitWidth() > BitWidth &&
6788 MaxBECount.getActiveBits() <= BitWidth)
6789 MaxBECount = MaxBECount.trunc(BitWidth);
6790 else if (MaxBECount.getBitWidth() < BitWidth)
6791 MaxBECount = MaxBECount.zext(BitWidth);
6792
6793 if (MaxBECount.getBitWidth() == BitWidth) {
6794 auto [RangeFromAffine, Flags] = getRangeForAffineAR(
6795 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6796 ConservativeResult =
6797 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6798 const_cast<SCEVAddRecExpr *>(AddRec)->setNoWrapFlags(Flags);
6799
6800 auto RangeFromFactoring = getRangeViaFactoring(
6801 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6802 ConservativeResult =
6803 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6804 }
6805 }
6806
6807 // Now try symbolic BE count and more powerful methods.
6809 const SCEV *SymbolicMaxBECount =
6811 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6812 getTypeSizeInBits(MaxBEScev->getType()) <= BitWidth &&
6813 AddRec->hasNoSelfWrap()) {
6814 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6815 AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6816 ConservativeResult =
6817 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6818 }
6819 }
6820 }
6821
6822 return setRange(AddRec, SignHint, std::move(ConservativeResult));
6823 }
6824 case scUMaxExpr:
6825 case scSMaxExpr:
6826 case scUMinExpr:
6827 case scSMinExpr:
6828 case scSequentialUMinExpr: {
6830 switch (S->getSCEVType()) {
6831 case scUMaxExpr:
6832 ID = Intrinsic::umax;
6833 break;
6834 case scSMaxExpr:
6835 ID = Intrinsic::smax;
6836 break;
6837 case scUMinExpr:
6839 ID = Intrinsic::umin;
6840 break;
6841 case scSMinExpr:
6842 ID = Intrinsic::smin;
6843 break;
6844 default:
6845 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6846 }
6847
6848 const auto *NAry = cast<SCEVNAryExpr>(S);
6849 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
6850 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6851 X = X.intrinsic(
6852 ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
6853 return setRange(S, SignHint,
6854 ConservativeResult.intersectWith(X, RangeType));
6855 }
6856 case scUnknown: {
6857 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6858 Value *V = U->getValue();
6859
6860 // Check if the IR explicitly contains !range metadata.
6861 std::optional<ConstantRange> MDRange = GetRangeFromMetadata(V);
6862 if (MDRange)
6863 ConservativeResult =
6864 ConservativeResult.intersectWith(*MDRange, RangeType);
6865
6866 // Use facts about recurrences in the underlying IR. Note that add
6867 // recurrences are AddRecExprs and thus don't hit this path. This
6868 // primarily handles shift recurrences.
6869 auto CR = getRangeForUnknownRecurrence(U);
6870 ConservativeResult = ConservativeResult.intersectWith(CR);
6871
6872 // See if ValueTracking can give us a useful range.
6873 const DataLayout &DL = getDataLayout();
6874 KnownBits Known = computeKnownBits(V, DL, &AC, nullptr, &DT);
6875 if (Known.getBitWidth() != BitWidth)
6876 Known = Known.zextOrTrunc(BitWidth);
6877
6878 // ValueTracking may be able to compute a tighter result for the number of
6879 // sign bits than for the value of those sign bits.
6880 unsigned NS = ComputeNumSignBits(V, DL, &AC, nullptr, &DT);
6881 if (U->getType()->isPointerTy()) {
6882 // If the pointer size is larger than the index size type, this can cause
6883 // NS to be larger than BitWidth. So compensate for this.
6884 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
6885 int ptrIdxDiff = ptrSize - BitWidth;
6886 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
6887 NS -= ptrIdxDiff;
6888 }
6889
6890 if (NS > 1) {
6891 // If we know any of the sign bits, we know all of the sign bits.
6892 if (!Known.Zero.getHiBits(NS).isZero())
6893 Known.Zero.setHighBits(NS);
6894 if (!Known.One.getHiBits(NS).isZero())
6895 Known.One.setHighBits(NS);
6896 }
6897
6898 if (Known.getMinValue() != Known.getMaxValue() + 1)
6899 ConservativeResult = ConservativeResult.intersectWith(
6900 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6901 RangeType);
6902 if (NS > 1)
6903 ConservativeResult = ConservativeResult.intersectWith(
6904 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6905 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6906 RangeType);
6907
6908 if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
6909 // Strengthen the range if the underlying IR value is a
6910 // global/alloca/heap allocation using the size of the object.
6911 bool CanBeNull;
6912 uint64_t DerefBytes = V->getPointerDereferenceableBytes(
6913 DL, CanBeNull, /*CanBeFreed=*/nullptr);
6914 if (DerefBytes > 1 && isUIntN(BitWidth, DerefBytes)) {
6915 // The highest address the object can start is DerefBytes bytes before
6916 // the end (unsigned max value). If this value is not a multiple of the
6917 // alignment, the last possible start value is the next lowest multiple
6918 // of the alignment. Note: The computations below cannot overflow,
6919 // because if they would there's no possible start address for the
6920 // object.
6921 APInt MaxVal =
6922 APInt::getMaxValue(BitWidth) - APInt(BitWidth, DerefBytes);
6923 uint64_t Align = U->getValue()->getPointerAlignment(DL).value();
6924 uint64_t Rem = MaxVal.urem(Align);
6925 MaxVal -= APInt(BitWidth, Rem);
6926 APInt MinVal = APInt::getZero(BitWidth);
6927 if (llvm::isKnownNonZero(V, DL))
6928 MinVal = Align;
6929 ConservativeResult = ConservativeResult.intersectWith(
6930 ConstantRange::getNonEmpty(MinVal, MaxVal + 1), RangeType);
6931 }
6932 }
6933
6934 // A range of Phi is a subset of union of all ranges of its input.
6935 if (PHINode *Phi = dyn_cast<PHINode>(V)) {
6936 // SCEVExpander sometimes creates SCEVUnknowns that are secretly
6937 // AddRecs; return the range for the corresponding AddRec.
6938 if (auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V)))
6939 return getRangeRef(AR, SignHint, Depth + 1);
6940
6941 // Make sure that we do not run over cycled Phis.
6942 if (RangeRefPHIAllowedOperands(DT, Phi)) {
6943 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6944
6945 for (const auto &Op : Phi->operands()) {
6946 auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
6947 RangeFromOps = RangeFromOps.unionWith(OpRange);
6948 // No point to continue if we already have a full set.
6949 if (RangeFromOps.isFullSet())
6950 break;
6951 }
6952 ConservativeResult =
6953 ConservativeResult.intersectWith(RangeFromOps, RangeType);
6954 }
6955 }
6956
6957 // vscale can't be equal to zero
6958 if (const auto *II = dyn_cast<IntrinsicInst>(V))
6959 if (II->getIntrinsicID() == Intrinsic::vscale) {
6960 ConstantRange Disallowed = APInt::getZero(BitWidth);
6961 ConservativeResult = ConservativeResult.difference(Disallowed);
6962 }
6963
6964 return setRange(U, SignHint, std::move(ConservativeResult));
6965 }
6966 case scCouldNotCompute:
6967 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6968 }
6969
6970 return setRange(S, SignHint, std::move(ConservativeResult));
6971}
6972
6973// Given a StartRange, Step and MaxBECount for an expression compute a range of
6974// values that the expression can take. Initially, the expression has a value
6975// from StartRange and then is changed by Step up to MaxBECount times. Signed
6976// argument defines if we treat Step as signed or unsigned. The second return
6977// value indicates that no wrapping occurred.
6978static std::pair<ConstantRange, bool>
6980 const APInt &MaxBECount, bool Signed) {
6981 unsigned BitWidth = Step.getBitWidth();
6982 assert(BitWidth == StartRange.getBitWidth() &&
6983 BitWidth == MaxBECount.getBitWidth() && "mismatched bit widths");
6984 // If either Step or MaxBECount is 0, then the expression won't change, and we
6985 // just need to return the initial range.
6986 if (Step == 0 || MaxBECount == 0)
6987 return {StartRange, true};
6988
6989 // If we don't know anything about the initial value (i.e. StartRange is
6990 // FullRange), then we don't know anything about the final range either.
6991 // Return FullRange.
6992 if (StartRange.isFullSet())
6993 return {ConstantRange::getFull(BitWidth), false};
6994
6995 // If Step is signed and negative, then we use its absolute value, but we also
6996 // note that we're moving in the opposite direction.
6997 bool Descending = Signed && Step.isNegative();
6998
6999 if (Signed)
7000 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
7001 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
7002 // This equations hold true due to the well-defined wrap-around behavior of
7003 // APInt.
7004 Step = Step.abs();
7005
7006 // Check if Offset is more than full span of BitWidth. If it is, the
7007 // expression is guaranteed to overflow.
7008 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
7009 return {ConstantRange::getFull(BitWidth), false};
7010
7011 // Offset is by how much the expression can change. Checks above guarantee no
7012 // overflow here.
7013 APInt Offset = Step * MaxBECount;
7014
7015 // Minimum value of the final range will match the minimal value of StartRange
7016 // if the expression is increasing and will be decreased by Offset otherwise.
7017 // Maximum value of the final range will match the maximal value of StartRange
7018 // if the expression is decreasing and will be increased by Offset otherwise.
7019 APInt StartLower = StartRange.getLower();
7020 APInt StartUpper = StartRange.getUpper() - 1;
7021 bool Overflow;
7022 APInt MovedBoundary;
7023 if (Signed) {
7024 // This does not use sadd_ov, as we want to check overflow for a signed
7025 // start with an unsigned offset.
7026 if (Descending) {
7027 MovedBoundary = StartLower - std::move(Offset);
7028 Overflow = MovedBoundary.sgt(StartLower) || StartRange.isSignWrappedSet();
7029 } else {
7030 MovedBoundary = StartUpper + std::move(Offset);
7031 Overflow = MovedBoundary.slt(StartUpper) || StartRange.isSignWrappedSet();
7032 }
7033 } else {
7034 MovedBoundary = StartUpper.uadd_ov(std::move(Offset), Overflow);
7035 Overflow |= StartRange.isWrappedSet();
7036 }
7037
7038 // It's possible that the new minimum/maximum value will fall into the initial
7039 // range (due to wrap around). This means that the expression can take any
7040 // value in this bitwidth, and we have to return full range.
7041 if (StartRange.contains(MovedBoundary))
7042 return {ConstantRange::getFull(BitWidth), false};
7043
7044 APInt NewLower =
7045 Descending ? std::move(MovedBoundary) : std::move(StartLower);
7046 APInt NewUpper =
7047 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
7048 NewUpper += 1;
7049
7050 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
7051 return {ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)),
7052 !Overflow};
7053}
7054
7055std::pair<ConstantRange, SCEV::NoWrapFlags>
7056ScalarEvolution::getRangeForAffineAR(const SCEV *Start, const SCEV *Step,
7057 const APInt &MaxBECount) {
7058 assert(getTypeSizeInBits(Start->getType()) ==
7059 getTypeSizeInBits(Step->getType()) &&
7060 getTypeSizeInBits(Start->getType()) == MaxBECount.getBitWidth() &&
7061 "mismatched bit widths");
7062
7063 // First, consider step signed.
7064 ConstantRange StartSRange = getSignedRange(Start);
7065 ConstantRange StepSRange = getSignedRange(Step);
7066
7067 // If Step can be both positive and negative, we need to find ranges for the
7068 // maximum absolute step values in both directions and union them.
7069 auto [SR1, NSW1] = getRangeForAffineARHelper(
7070 StepSRange.getSignedMin(), StartSRange, MaxBECount, /*Signed=*/true);
7071 auto [SR2, NSW2] = getRangeForAffineARHelper(StepSRange.getSignedMax(),
7072 StartSRange, MaxBECount,
7073 /*Signed=*/true);
7074 ConstantRange SR = SR1.unionWith(SR2);
7075
7076 // Next, consider step unsigned.
7077 auto [UR, NUW] = getRangeForAffineARHelper(
7078 getUnsignedRangeMax(Step), getUnsignedRange(Start), MaxBECount,
7079 /*Signed=*/false);
7080
7082 if (NUW)
7084 if (NSW1 && NSW2)
7086
7087 // Finally, intersect signed and unsigned ranges.
7089}
7090
7091ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
7092 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
7093 ScalarEvolution::RangeSignHint SignHint) {
7094 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
7095 assert(AddRec->hasNoSelfWrap() &&
7096 "This only works for non-self-wrapping AddRecs!");
7097 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
7098 const SCEV *Step = AddRec->getStepRecurrence(*this);
7099 // Only deal with constant step to save compile time.
7100 if (!isa<SCEVConstant>(Step))
7101 return ConstantRange::getFull(BitWidth);
7102 // Let's make sure that we can prove that we do not self-wrap during
7103 // MaxBECount iterations. We need this because MaxBECount is a maximum
7104 // iteration count estimate, and we might infer nw from some exit for which we
7105 // do not know max exit count (or any other side reasoning).
7106 // TODO: Turn into assert at some point.
7107 if (getTypeSizeInBits(MaxBECount->getType()) >
7108 getTypeSizeInBits(AddRec->getType()))
7109 return ConstantRange::getFull(BitWidth);
7110 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
7111 const SCEV *RangeWidth = getMinusOne(AddRec->getType());
7112 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
7113 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
7114 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
7115 MaxItersWithoutWrap))
7116 return ConstantRange::getFull(BitWidth);
7117
7118 ICmpInst::Predicate LEPred =
7120 ICmpInst::Predicate GEPred =
7122 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7123
7124 // We know that there is no self-wrap. Let's take Start and End values and
7125 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7126 // the iteration. They either lie inside the range [Min(Start, End),
7127 // Max(Start, End)] or outside it:
7128 //
7129 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
7130 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
7131 //
7132 // No self wrap flag guarantees that the intermediate values cannot be BOTH
7133 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7134 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7135 // Start <= End and step is positive, or Start >= End and step is negative.
7136 const SCEV *Start = applyLoopGuards(AddRec->getStart(), AddRec->getLoop());
7137 ConstantRange StartRange = getRangeRef(Start, SignHint);
7138 ConstantRange EndRange = getRangeRef(End, SignHint);
7139 ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7140 // If they already cover full iteration space, we will know nothing useful
7141 // even if we prove what we want to prove.
7142 if (RangeBetween.isFullSet())
7143 return RangeBetween;
7144 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7145 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7146 : RangeBetween.isWrappedSet();
7147 if (IsWrappedSet)
7148 return ConstantRange::getFull(BitWidth);
7149
7150 if (isKnownPositive(Step) &&
7151 isKnownPredicateViaConstantRanges(LEPred, Start, End))
7152 return RangeBetween;
7153 if (isKnownNegative(Step) &&
7154 isKnownPredicateViaConstantRanges(GEPred, Start, End))
7155 return RangeBetween;
7156 return ConstantRange::getFull(BitWidth);
7157}
7158
7159ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7160 const SCEV *Step,
7161 const APInt &MaxBECount) {
7162 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7163 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7164
7165 unsigned BitWidth = MaxBECount.getBitWidth();
7166 assert(getTypeSizeInBits(Start->getType()) == BitWidth &&
7167 getTypeSizeInBits(Step->getType()) == BitWidth &&
7168 "mismatched bit widths");
7169
7170 struct SelectPattern {
7171 Value *Condition = nullptr;
7172 APInt TrueValue;
7173 APInt FalseValue;
7174
7175 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7176 const SCEV *S) {
7177 std::optional<unsigned> CastOp;
7178 APInt Offset(BitWidth, 0);
7179
7181 "Should be!");
7182
7183 // Peel off a constant offset. In the future we could consider being
7184 // smarter here and handle {Start+Step,+,Step} too.
7185 const APInt *Off;
7186 if (match(S, m_scev_Add(m_scev_APInt(Off), m_SCEV(S))))
7187 Offset = *Off;
7188
7189 // Peel off a cast operation
7190 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7191 CastOp = SCast->getSCEVType();
7192 S = SCast->getOperand();
7193 }
7194
7195 using namespace llvm::PatternMatch;
7196
7197 auto *SU = dyn_cast<SCEVUnknown>(S);
7198 const APInt *TrueVal, *FalseVal;
7199 if (!SU ||
7200 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7201 m_APInt(FalseVal)))) {
7202 Condition = nullptr;
7203 return;
7204 }
7205
7206 TrueValue = *TrueVal;
7207 FalseValue = *FalseVal;
7208
7209 // Re-apply the cast we peeled off earlier
7210 if (CastOp)
7211 switch (*CastOp) {
7212 default:
7213 llvm_unreachable("Unknown SCEV cast type!");
7214
7215 case scTruncate:
7216 TrueValue = TrueValue.trunc(BitWidth);
7217 FalseValue = FalseValue.trunc(BitWidth);
7218 break;
7219 case scZeroExtend:
7220 TrueValue = TrueValue.zext(BitWidth);
7221 FalseValue = FalseValue.zext(BitWidth);
7222 break;
7223 case scSignExtend:
7224 TrueValue = TrueValue.sext(BitWidth);
7225 FalseValue = FalseValue.sext(BitWidth);
7226 break;
7227 }
7228
7229 // Re-apply the constant offset we peeled off earlier
7230 TrueValue += Offset;
7231 FalseValue += Offset;
7232 }
7233
7234 bool isRecognized() { return Condition != nullptr; }
7235 };
7236
7237 SelectPattern StartPattern(*this, BitWidth, Start);
7238 if (!StartPattern.isRecognized())
7239 return ConstantRange::getFull(BitWidth);
7240
7241 SelectPattern StepPattern(*this, BitWidth, Step);
7242 if (!StepPattern.isRecognized())
7243 return ConstantRange::getFull(BitWidth);
7244
7245 if (StartPattern.Condition != StepPattern.Condition) {
7246 // We don't handle this case today; but we could, by considering four
7247 // possibilities below instead of two. I'm not sure if there are cases where
7248 // that will help over what getRange already does, though.
7249 return ConstantRange::getFull(BitWidth);
7250 }
7251
7252 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7253 // construct arbitrary general SCEV expressions here. This function is called
7254 // from deep in the call stack, and calling getSCEV (on a sext instruction,
7255 // say) can end up caching a suboptimal value.
7256
7257 // FIXME: without the explicit `this` receiver below, MSVC errors out with
7258 // C2352 and C2512 (otherwise it isn't needed).
7259
7260 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7261 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7262 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7263 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7264
7265 ConstantRange TrueRange =
7266 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount).first;
7267 ConstantRange FalseRange =
7268 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount).first;
7269
7270 return TrueRange.unionWith(FalseRange);
7271}
7272
7273SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7274 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
7275 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7276
7277 // Return early if there are no flags to propagate to the SCEV.
7279 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(BinOp);
7280 PDI && PDI->isDisjoint()) {
7282 } else {
7283 if (BinOp->hasNoUnsignedWrap())
7285 if (BinOp->hasNoSignedWrap())
7287 }
7288 if (Flags == SCEV::FlagAnyWrap)
7289 return SCEV::FlagAnyWrap;
7290
7291 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
7292}
7293
7294const Instruction *
7295ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7296 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7297 return &*AddRec->getLoop()->getHeader()->begin();
7298 if (auto *U = dyn_cast<SCEVUnknown>(S))
7299 if (auto *I = dyn_cast<Instruction>(U->getValue()))
7300 return I;
7301 return nullptr;
7302}
7303
7304const Instruction *ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops,
7305 bool &Precise) {
7306 Precise = true;
7307 // Do a bounded search of the def relation of the requested SCEVs.
7308 SmallPtrSet<const SCEV *, 16> Visited;
7309 SmallVector<SCEVUse> Worklist;
7310 auto pushOp = [&](const SCEV *S) {
7311 if (!Visited.insert(S).second)
7312 return;
7313 // Threshold of 30 here is arbitrary.
7314 if (Visited.size() > 30) {
7315 Precise = false;
7316 return;
7317 }
7318 Worklist.push_back(S);
7319 };
7320
7321 for (SCEVUse S : Ops)
7322 pushOp(S);
7323
7324 const Instruction *Bound = nullptr;
7325 while (!Worklist.empty()) {
7326 SCEVUse S = Worklist.pop_back_val();
7327 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7328 if (!Bound || DT.dominates(Bound, DefI))
7329 Bound = DefI;
7330 } else {
7331 for (SCEVUse Op : S->operands())
7332 pushOp(Op);
7333 }
7334 }
7335 return Bound ? Bound : &*F.getEntryBlock().begin();
7336}
7337
7338const Instruction *
7339ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops) {
7340 bool Discard;
7341 return getDefiningScopeBound(Ops, Discard);
7342}
7343
7344bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7345 const Instruction *B) {
7346 if (A->getParent() == B->getParent() &&
7348 B->getIterator()))
7349 return true;
7350
7351 auto *BLoop = LI.getLoopFor(B->getParent());
7352 if (BLoop && BLoop->getHeader() == B->getParent() &&
7353 BLoop->getLoopPreheader() == A->getParent() &&
7355 A->getParent()->end()) &&
7356 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7357 B->getIterator()))
7358 return true;
7359 return false;
7360}
7361
7363 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ true);
7364 visitAll(Op, PC);
7365 return PC.MaybePoison.empty();
7366}
7367
7368bool ScalarEvolution::isGuaranteedNotToCauseUB(const SCEV *Op) {
7369 return !SCEVExprContains(Op, [this](const SCEV *S) {
7370 const SCEV *Op1;
7371 bool M = match(S, m_scev_UDiv(m_SCEV(), m_SCEV(Op1)));
7372 // The UDiv may be UB if the divisor is poison or zero. Unless the divisor
7373 // is a non-zero constant, we have to assume the UDiv may be UB.
7374 return M && (!isKnownNonZero(Op1) || !isGuaranteedNotToBePoison(Op1));
7375 });
7376}
7377
7378bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7379 // Only proceed if we can prove that I does not yield poison.
7381 return false;
7382
7383 // At this point we know that if I is executed, then it does not wrap
7384 // according to at least one of NSW or NUW. If I is not executed, then we do
7385 // not know if the calculation that I represents would wrap. Multiple
7386 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7387 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7388 // derived from other instructions that map to the same SCEV. We cannot make
7389 // that guarantee for cases where I is not executed. So we need to find a
7390 // upper bound on the defining scope for the SCEV, and prove that I is
7391 // executed every time we enter that scope. When the bounding scope is a
7392 // loop (the common case), this is equivalent to proving I executes on every
7393 // iteration of that loop.
7394 SmallVector<SCEVUse> SCEVOps;
7395 for (const Use &Op : I->operands()) {
7396 // I could be an extractvalue from a call to an overflow intrinsic.
7397 // TODO: We can do better here in some cases.
7398 if (isSCEVable(Op->getType()))
7399 SCEVOps.push_back(getSCEV(Op));
7400 }
7401 auto *DefI = getDefiningScopeBound(SCEVOps);
7402 return isGuaranteedToTransferExecutionTo(DefI, I);
7403}
7404
7405bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7406 // If we know that \c I can never be poison period, then that's enough.
7407 if (isSCEVExprNeverPoison(I))
7408 return true;
7409
7410 // If the loop only has one exit, then we know that, if the loop is entered,
7411 // any instruction dominating that exit will be executed. If any such
7412 // instruction would result in UB, the addrec cannot be poison.
7413 //
7414 // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7415 // also handles uses outside the loop header (they just need to dominate the
7416 // single exit).
7417
7418 auto *ExitingBB = L->getExitingBlock();
7419 if (!ExitingBB || !loopHasNoAbnormalExits(L))
7420 return false;
7421
7422 SmallPtrSet<const Value *, 16> KnownPoison;
7424
7425 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
7426 // things that are known to be poison under that assumption go on the
7427 // Worklist.
7428 KnownPoison.insert(I);
7429 Worklist.push_back(I);
7430
7431 while (!Worklist.empty()) {
7432 const Instruction *Poison = Worklist.pop_back_val();
7433
7434 for (const Use &U : Poison->uses()) {
7435 const Instruction *PoisonUser = cast<Instruction>(U.getUser());
7436 if (mustTriggerUB(PoisonUser, KnownPoison) &&
7437 DT.dominates(PoisonUser->getParent(), ExitingBB))
7438 return true;
7439
7440 if (propagatesPoison(U) && L->contains(PoisonUser))
7441 if (KnownPoison.insert(PoisonUser).second)
7442 Worklist.push_back(PoisonUser);
7443 }
7444 }
7445
7446 return false;
7447}
7448
7449ScalarEvolution::LoopProperties
7450ScalarEvolution::getLoopProperties(const Loop *L) {
7451 using LoopProperties = ScalarEvolution::LoopProperties;
7452
7453 auto Itr = LoopPropertiesCache.find(L);
7454 if (Itr == LoopPropertiesCache.end()) {
7455 auto HasSideEffects = [](Instruction *I) {
7456 if (auto *SI = dyn_cast<StoreInst>(I))
7457 return !SI->isSimple();
7458
7459 if (I->mayThrow())
7460 return true;
7461
7462 // Non-volatile memset / memcpy do not count as side-effect for forward
7463 // progress.
7464 if (isa<MemIntrinsic>(I) && !I->isVolatile())
7465 return false;
7466
7467 return I->mayWriteToMemory();
7468 };
7469
7470 LoopProperties LP = {/* HasNoAbnormalExits */ true,
7471 /*HasNoSideEffects*/ true};
7472
7473 for (auto *BB : L->getBlocks())
7474 for (auto &I : *BB) {
7476 LP.HasNoAbnormalExits = false;
7477 if (HasSideEffects(&I))
7478 LP.HasNoSideEffects = false;
7479 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7480 break; // We're already as pessimistic as we can get.
7481 }
7482
7483 auto InsertPair = LoopPropertiesCache.insert({L, LP});
7484 assert(InsertPair.second && "We just checked!");
7485 Itr = InsertPair.first;
7486 }
7487
7488 return Itr->second;
7489}
7490
7492 // A mustprogress loop without side effects must be finite.
7493 // TODO: The check used here is very conservative. It's only *specific*
7494 // side effects which are well defined in infinite loops.
7495 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7496}
7497
7498const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7499 // Worklist item with a Value and a bool indicating whether all operands have
7500 // been visited already.
7503
7504 Stack.emplace_back(V, false);
7505 while (!Stack.empty()) {
7506 auto E = Stack.back();
7507 Value *CurV = E.getPointer();
7508
7509 if (getExistingSCEV(CurV)) {
7510 Stack.pop_back();
7511 continue;
7512 }
7513
7515 const SCEV *CreatedSCEV = nullptr;
7516 // If all operands have been visited already, create the SCEV.
7517 if (E.getInt()) {
7518 CreatedSCEV = createSCEV(CurV);
7519 } else {
7520 // Otherwise get the operands we need to create SCEV's for before creating
7521 // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7522 // just use it.
7523 CreatedSCEV = getOperandsToCreate(CurV, Ops);
7524 }
7525
7526 if (CreatedSCEV) {
7527 insertValueToMap(CurV, CreatedSCEV);
7528 Stack.pop_back();
7529 } else {
7530 Stack.back().setInt(true);
7531 // Queue its operands which need to be constructed.
7532 for (Value *Op : Ops)
7533 Stack.emplace_back(Op, false);
7534 }
7535 }
7536
7537 return getExistingSCEV(V);
7538}
7539
7540const SCEV *
7541ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7542 if (!isSCEVable(V->getType()))
7543 return getUnknown(V);
7544
7545 if (Instruction *I = dyn_cast<Instruction>(V)) {
7546 // Don't attempt to analyze instructions in blocks that aren't
7547 // reachable. Such instructions don't matter, and they aren't required
7548 // to obey basic rules for definitions dominating uses which this
7549 // analysis depends on.
7550 if (!DT.isReachableFromEntry(I->getParent()))
7551 return getUnknown(PoisonValue::get(V->getType()));
7552 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7553 return getConstant(CI);
7554 else if (isa<GlobalAlias>(V))
7555 return getUnknown(V);
7556 else if (!isa<ConstantExpr>(V))
7557 return getUnknown(V);
7558
7560 if (auto BO =
7562 bool IsConstArg = isa<ConstantInt>(BO->RHS);
7563 switch (BO->Opcode) {
7564 case Instruction::Add:
7565 case Instruction::Mul: {
7566 // For additions and multiplications, traverse add/mul chains for which we
7567 // can potentially create a single SCEV, to reduce the number of
7568 // get{Add,Mul}Expr calls.
7569 do {
7570 if (BO->Op) {
7571 if (BO->Op != V && getExistingSCEV(BO->Op)) {
7572 Ops.push_back(BO->Op);
7573 break;
7574 }
7575 }
7576 Ops.push_back(BO->RHS);
7577 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7579 if (!NewBO ||
7580 (BO->Opcode == Instruction::Add &&
7581 (NewBO->Opcode != Instruction::Add &&
7582 NewBO->Opcode != Instruction::Sub)) ||
7583 (BO->Opcode == Instruction::Mul &&
7584 NewBO->Opcode != Instruction::Mul)) {
7585 Ops.push_back(BO->LHS);
7586 break;
7587 }
7588 // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7589 // requires a SCEV for the LHS.
7590 if (BO->Op && (BO->IsNSW || BO->IsNUW)) {
7591 auto *I = dyn_cast<Instruction>(BO->Op);
7592 if (I && programUndefinedIfPoison(I)) {
7593 Ops.push_back(BO->LHS);
7594 break;
7595 }
7596 }
7597 BO = NewBO;
7598 } while (true);
7599 return nullptr;
7600 }
7601 case Instruction::Sub:
7602 case Instruction::UDiv:
7603 case Instruction::URem:
7604 break;
7605 case Instruction::AShr:
7606 case Instruction::Shl:
7607 case Instruction::Xor:
7608 if (!IsConstArg)
7609 return nullptr;
7610 break;
7611 case Instruction::And:
7612 case Instruction::Or:
7613 if (!IsConstArg && !BO->LHS->getType()->isIntegerTy(1))
7614 return nullptr;
7615 break;
7616 case Instruction::LShr:
7617 return getUnknown(V);
7618 default:
7619 llvm_unreachable("Unhandled binop");
7620 break;
7621 }
7622
7623 Ops.push_back(BO->LHS);
7624 Ops.push_back(BO->RHS);
7625 return nullptr;
7626 }
7627
7628 switch (U->getOpcode()) {
7629 case Instruction::Trunc:
7630 case Instruction::ZExt:
7631 case Instruction::SExt:
7632 case Instruction::PtrToAddr:
7633 case Instruction::PtrToInt:
7634 Ops.push_back(U->getOperand(0));
7635 return nullptr;
7636
7637 case Instruction::BitCast:
7638 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
7639 Ops.push_back(U->getOperand(0));
7640 return nullptr;
7641 }
7642 return getUnknown(V);
7643
7644 case Instruction::SDiv:
7645 case Instruction::SRem:
7646 Ops.push_back(U->getOperand(0));
7647 Ops.push_back(U->getOperand(1));
7648 return nullptr;
7649
7650 case Instruction::GetElementPtr:
7651 assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7652 "GEP source element type must be sized");
7653 llvm::append_range(Ops, U->operands());
7654 return nullptr;
7655
7656 case Instruction::IntToPtr:
7657 return getUnknown(V);
7658
7659 case Instruction::PHI:
7660 // getNodeForPHI has four ways to turn a PHI into a SCEV; retrieve the
7661 // relevant nodes for each of them.
7662 //
7663 // The first is just to call simplifyInstruction, and get something back
7664 // that isn't a PHI.
7665 if (Value *V = simplifyInstruction(
7666 cast<PHINode>(U),
7667 {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
7668 /*UseInstrInfo=*/true, /*CanUseUndef=*/false})) {
7669 assert(V);
7670 Ops.push_back(V);
7671 return nullptr;
7672 }
7673 // The second is createNodeForPHIWithIdenticalOperands: this looks for
7674 // operands which all perform the same operation, but haven't been
7675 // CSE'ed for whatever reason.
7676 if (BinaryOperator *BO = getCommonInstForPHI(cast<PHINode>(U))) {
7677 assert(BO);
7678 Ops.push_back(BO);
7679 return nullptr;
7680 }
7681 // The third is createNodeFromSelectLikePHI; this takes a PHI which
7682 // is equivalent to a select, and analyzes it like a select.
7683 {
7684 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
7686 assert(Cond);
7687 assert(LHS);
7688 assert(RHS);
7689 if (auto *CondICmp = dyn_cast<ICmpInst>(Cond)) {
7690 Ops.push_back(CondICmp->getOperand(0));
7691 Ops.push_back(CondICmp->getOperand(1));
7692 }
7693 Ops.push_back(Cond);
7694 Ops.push_back(LHS);
7695 Ops.push_back(RHS);
7696 return nullptr;
7697 }
7698 }
7699 // The fourth way is createAddRecFromPHI. It's complicated to handle here,
7700 // so just construct it recursively.
7701 //
7702 // In addition to getNodeForPHI, also construct nodes which might be needed
7703 // by getRangeRef.
7705 for (Value *V : cast<PHINode>(U)->operands())
7706 Ops.push_back(V);
7707 return nullptr;
7708 }
7709 return nullptr;
7710
7711 case Instruction::Select: {
7712 // Check if U is a select that can be simplified to a SCEVUnknown.
7713 auto CanSimplifyToUnknown = [this, U]() {
7714 if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
7715 return false;
7716
7717 auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
7718 if (!ICI)
7719 return false;
7720 Value *LHS = ICI->getOperand(0);
7721 Value *RHS = ICI->getOperand(1);
7722 if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7723 ICI->getPredicate() == CmpInst::ICMP_NE) {
7725 return true;
7726 } else if (getTypeSizeInBits(LHS->getType()) >
7727 getTypeSizeInBits(U->getType()))
7728 return true;
7729 return false;
7730 };
7731 if (CanSimplifyToUnknown())
7732 return getUnknown(U);
7733
7734 llvm::append_range(Ops, U->operands());
7735 return nullptr;
7736 break;
7737 }
7738 case Instruction::Call:
7739 case Instruction::Invoke:
7740 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7741 Ops.push_back(RV);
7742 return nullptr;
7743 }
7744
7745 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7746 switch (II->getIntrinsicID()) {
7747 case Intrinsic::abs:
7748 Ops.push_back(II->getArgOperand(0));
7749 return nullptr;
7750 case Intrinsic::umax:
7751 case Intrinsic::umin:
7752 case Intrinsic::smax:
7753 case Intrinsic::smin:
7754 case Intrinsic::usub_sat:
7755 case Intrinsic::uadd_sat:
7756 Ops.push_back(II->getArgOperand(0));
7757 Ops.push_back(II->getArgOperand(1));
7758 return nullptr;
7759 case Intrinsic::start_loop_iterations:
7760 case Intrinsic::annotation:
7761 case Intrinsic::ptr_annotation:
7762 Ops.push_back(II->getArgOperand(0));
7763 return nullptr;
7764 default:
7765 break;
7766 }
7767 }
7768 break;
7769 }
7770
7771 return nullptr;
7772}
7773
7774const SCEV *ScalarEvolution::createSCEV(Value *V) {
7775 if (!isSCEVable(V->getType()))
7776 return getUnknown(V);
7777
7778 if (Instruction *I = dyn_cast<Instruction>(V)) {
7779 // Don't attempt to analyze instructions in blocks that aren't
7780 // reachable. Such instructions don't matter, and they aren't required
7781 // to obey basic rules for definitions dominating uses which this
7782 // analysis depends on.
7783 if (!DT.isReachableFromEntry(I->getParent()))
7784 return getUnknown(PoisonValue::get(V->getType()));
7785 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7786 return getConstant(CI);
7787 else if (isa<GlobalAlias>(V))
7788 return getUnknown(V);
7789 else if (!isa<ConstantExpr>(V))
7790 return getUnknown(V);
7791
7792 const SCEV *LHS;
7793 const SCEV *RHS;
7794
7796 if (auto BO =
7798 switch (BO->Opcode) {
7799 case Instruction::Add: {
7800 // The simple thing to do would be to just call getSCEV on both operands
7801 // and call getAddExpr with the result. However if we're looking at a
7802 // bunch of things all added together, this can be quite inefficient,
7803 // because it leads to N-1 getAddExpr calls for N ultimate operands.
7804 // Instead, gather up all the operands and make a single getAddExpr call.
7805 // LLVM IR canonical form means we need only traverse the left operands.
7807 do {
7808 if (BO->Op) {
7809 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7810 AddOps.push_back(OpSCEV);
7811 break;
7812 }
7813
7814 // If a NUW or NSW flag can be applied to the SCEV for this
7815 // addition, then compute the SCEV for this addition by itself
7816 // with a separate call to getAddExpr. We need to do that
7817 // instead of pushing the operands of the addition onto AddOps,
7818 // since the flags are only known to apply to this particular
7819 // addition - they may not apply to other additions that can be
7820 // formed with operands from AddOps.
7821 const SCEV *RHS = getSCEV(BO->RHS);
7822 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7823 if (Flags != SCEV::FlagAnyWrap) {
7824 const SCEV *LHS = getSCEV(BO->LHS);
7825 if (BO->Opcode == Instruction::Sub)
7826 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7827 else
7828 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7829 break;
7830 }
7831 }
7832
7833 if (BO->Opcode == Instruction::Sub)
7834 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7835 else
7836 AddOps.push_back(getSCEV(BO->RHS));
7837
7838 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7840 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7841 NewBO->Opcode != Instruction::Sub)) {
7842 AddOps.push_back(getSCEV(BO->LHS));
7843 break;
7844 }
7845 BO = NewBO;
7846 } while (true);
7847
7848 return getAddExpr(AddOps);
7849 }
7850
7851 case Instruction::Mul: {
7853 do {
7854 if (BO->Op) {
7855 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7856 MulOps.push_back(OpSCEV);
7857 break;
7858 }
7859
7860 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7861 if (Flags != SCEV::FlagAnyWrap) {
7862 LHS = getSCEV(BO->LHS);
7863 RHS = getSCEV(BO->RHS);
7864 MulOps.push_back(getMulExpr(LHS, RHS, Flags));
7865 break;
7866 }
7867 }
7868
7869 MulOps.push_back(getSCEV(BO->RHS));
7870 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7872 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7873 MulOps.push_back(getSCEV(BO->LHS));
7874 break;
7875 }
7876 BO = NewBO;
7877 } while (true);
7878
7879 return getMulExpr(MulOps);
7880 }
7881 case Instruction::UDiv:
7882 LHS = getSCEV(BO->LHS);
7883 RHS = getSCEV(BO->RHS);
7884 return getUDivExpr(LHS, RHS);
7885 case Instruction::URem:
7886 LHS = getSCEV(BO->LHS);
7887 RHS = getSCEV(BO->RHS);
7888 return getURemExpr(LHS, RHS);
7889 case Instruction::Sub: {
7891 if (BO->Op)
7892 Flags = getNoWrapFlagsFromUB(BO->Op);
7893
7894 // Try to use ptrtoaddr for subtracts with at least one ptrtoint
7895 // operand. While we don't model ptrtoint directly in SCEV, the
7896 // difference between two pointer addresses is well-defined.
7897 Value *PtrLHS = nullptr, *PtrRHS = nullptr;
7898 bool HasPtrLHS = match(BO->LHS, m_PtrToInt(m_Value(PtrLHS)));
7899 bool HasPtrRHS = match(BO->RHS, m_PtrToInt(m_Value(PtrRHS)));
7900 if (HasPtrLHS || HasPtrRHS) {
7901 // Convert a ptrtoint operand (OrigOp) to ptrtoaddr of its pointer
7902 // PtrOp. When only one side is ptrtoint (BothPtr is false), skip
7903 // SCEVUnknown pointers since wrapping them in ptrtoaddr adds no
7904 // useful structure.
7905 auto GetOp = [&](bool HasPtr, Value *PtrOp, Value *OrigOp,
7906 bool BothPtr) -> const SCEV * {
7907 if (!HasPtr)
7908 return getSCEV(OrigOp);
7909 const SCEV *PtrSCEV = getSCEV(PtrOp);
7910 if (BothPtr || !isa<SCEVUnknown>(PtrSCEV)) {
7911 const SCEV *Addr = getPtrToAddrExpr(PtrSCEV);
7912 if (!isa<SCEVCouldNotCompute>(Addr) &&
7913 getTypeSizeInBits(OrigOp->getType()) <=
7914 getTypeSizeInBits(Addr->getType()))
7915 return getTruncateOrNoop(Addr, OrigOp->getType());
7916 }
7917 return getSCEV(OrigOp);
7918 };
7919 const SCEV *L = GetOp(HasPtrLHS, PtrLHS, BO->LHS, HasPtrRHS);
7920 const SCEV *R = GetOp(HasPtrRHS, PtrRHS, BO->RHS, HasPtrLHS);
7921 return getMinusSCEV(L, R, Flags);
7922 }
7923
7924 LHS = getSCEV(BO->LHS);
7925 RHS = getSCEV(BO->RHS);
7926 return getMinusSCEV(LHS, RHS, Flags);
7927 }
7928 case Instruction::And:
7929 // For an expression like x&255 that merely masks off the high bits,
7930 // use zext(trunc(x)) as the SCEV expression.
7931 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7932 if (CI->isZero())
7933 return getSCEV(BO->RHS);
7934 if (CI->isMinusOne())
7935 return getSCEV(BO->LHS);
7936 const APInt &A = CI->getValue();
7937
7938 // Instcombine's ShrinkDemandedConstant may strip bits out of
7939 // constants, obscuring what would otherwise be a low-bits mask.
7940 // Use computeKnownBits to compute what ShrinkDemandedConstant
7941 // knew about to reconstruct a low-bits mask value.
7942 unsigned LZ = A.countl_zero();
7943 unsigned TZ = A.countr_zero();
7944 unsigned BitWidth = A.getBitWidth();
7945 KnownBits Known(BitWidth);
7946 computeKnownBits(BO->LHS, Known, getDataLayout(), &AC, nullptr, &DT);
7947
7948 APInt EffectiveMask =
7949 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
7950 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
7951 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
7952 const SCEV *LHS = getSCEV(BO->LHS);
7953 const SCEV *ShiftedLHS = nullptr;
7954 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
7955 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
7956 // For an expression like (x * 8) & 8, simplify the multiply.
7957 unsigned MulZeros = OpC->getAPInt().countr_zero();
7958 unsigned GCD = std::min(MulZeros, TZ);
7959 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
7961 MulOps.push_back(getConstant(OpC->getAPInt().ashr(GCD)));
7962 append_range(MulOps, LHSMul->operands().drop_front());
7963 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
7964 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
7965 }
7966 }
7967 if (!ShiftedLHS)
7968 ShiftedLHS = getUDivExpr(LHS, MulCount);
7969 return getMulExpr(
7971 getTruncateExpr(ShiftedLHS,
7972 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
7973 BO->LHS->getType()),
7974 MulCount);
7975 }
7976 }
7977 // Binary `and` is a bit-wise `umin`.
7978 if (BO->LHS->getType()->isIntegerTy(1)) {
7979 LHS = getSCEV(BO->LHS);
7980 RHS = getSCEV(BO->RHS);
7981 return getUMinExpr(LHS, RHS);
7982 }
7983 break;
7984
7985 case Instruction::Or:
7986 // Binary `or` is a bit-wise `umax`.
7987 if (BO->LHS->getType()->isIntegerTy(1)) {
7988 LHS = getSCEV(BO->LHS);
7989 RHS = getSCEV(BO->RHS);
7990 return getUMaxExpr(LHS, RHS);
7991 }
7992 break;
7993
7994 case Instruction::Xor:
7995 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7996 // If the RHS of xor is -1, then this is a not operation.
7997 if (CI->isMinusOne())
7998 return getNotSCEV(getSCEV(BO->LHS));
7999
8000 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
8001 // This is a variant of the check for xor with -1, and it handles
8002 // the case where instcombine has trimmed non-demanded bits out
8003 // of an xor with -1.
8004 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
8005 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
8006 if (LBO->getOpcode() == Instruction::And &&
8007 LCI->getValue() == CI->getValue())
8008 if (const SCEVZeroExtendExpr *Z =
8010 Type *UTy = BO->LHS->getType();
8011 const SCEV *Z0 = Z->getOperand();
8012 Type *Z0Ty = Z0->getType();
8013 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
8014
8015 // If C is a low-bits mask, the zero extend is serving to
8016 // mask off the high bits. Complement the operand and
8017 // re-apply the zext.
8018 if (CI->getValue().isMask(Z0TySize))
8019 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
8020
8021 // If C is a single bit, it may be in the sign-bit position
8022 // before the zero-extend. In this case, represent the xor
8023 // using an add, which is equivalent, and re-apply the zext.
8024 APInt Trunc = CI->getValue().trunc(Z0TySize);
8025 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
8026 Trunc.isSignMask())
8027 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
8028 UTy);
8029 }
8030 }
8031 break;
8032
8033 case Instruction::Shl:
8034 // Turn shift left of a constant amount into a multiply.
8035 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
8036 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
8037
8038 // If the shift count is not less than the bitwidth, the result of
8039 // the shift is undefined. Don't try to analyze it, because the
8040 // resolution chosen here may differ from the resolution chosen in
8041 // other parts of the compiler.
8042 if (SA->getValue().uge(BitWidth))
8043 break;
8044
8045 // We can safely preserve the nuw flag in all cases. It's also safe to
8046 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
8047 // requires special handling. It can be preserved as long as we're not
8048 // left shifting by bitwidth - 1.
8049 auto Flags = SCEV::FlagAnyWrap;
8050 if (BO->Op) {
8051 auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
8052 if (any(MulFlags & SCEV::FlagNSW) &&
8053 (any(MulFlags & SCEV::FlagNUW) ||
8054 SA->getValue().ult(BitWidth - 1)))
8056 if (any(MulFlags & SCEV::FlagNUW))
8058 }
8059
8060 ConstantInt *X = ConstantInt::get(
8061 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
8062 return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
8063 }
8064 break;
8065
8066 case Instruction::AShr:
8067 // AShr X, C, where C is a constant.
8068 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
8069 if (!CI)
8070 break;
8071
8072 Type *OuterTy = BO->LHS->getType();
8074 // If the shift count is not less than the bitwidth, the result of
8075 // the shift is undefined. Don't try to analyze it, because the
8076 // resolution chosen here may differ from the resolution chosen in
8077 // other parts of the compiler.
8078 if (CI->getValue().uge(BitWidth))
8079 break;
8080
8081 if (CI->isZero())
8082 return getSCEV(BO->LHS); // shift by zero --> noop
8083
8084 uint64_t AShrAmt = CI->getZExtValue();
8085 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
8086
8087 Operator *L = dyn_cast<Operator>(BO->LHS);
8088 const SCEV *AddTruncateExpr = nullptr;
8089 ConstantInt *ShlAmtCI = nullptr;
8090 const SCEV *AddConstant = nullptr;
8091
8092 if (L && L->getOpcode() == Instruction::Add) {
8093 // X = Shl A, n
8094 // Y = Add X, c
8095 // Z = AShr Y, m
8096 // n, c and m are constants.
8097
8098 Operator *LShift = dyn_cast<Operator>(L->getOperand(0));
8099 ConstantInt *AddOperandCI = dyn_cast<ConstantInt>(L->getOperand(1));
8100 if (LShift && LShift->getOpcode() == Instruction::Shl) {
8101 if (AddOperandCI) {
8102 const SCEV *ShlOp0SCEV = getSCEV(LShift->getOperand(0));
8103 ShlAmtCI = dyn_cast<ConstantInt>(LShift->getOperand(1));
8104 // since we truncate to TruncTy, the AddConstant should be of the
8105 // same type, so create a new Constant with type same as TruncTy.
8106 // Also, the Add constant should be shifted right by AShr amount.
8107 APInt AddOperand = AddOperandCI->getValue().ashr(AShrAmt);
8108 AddConstant = getConstant(AddOperand.trunc(BitWidth - AShrAmt));
8109 // we model the expression as sext(add(trunc(A), c << n)), since the
8110 // sext(trunc) part is already handled below, we create a
8111 // AddExpr(TruncExp) which will be used later.
8112 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8113 }
8114 }
8115 } else if (L && L->getOpcode() == Instruction::Shl) {
8116 // X = Shl A, n
8117 // Y = AShr X, m
8118 // Both n and m are constant.
8119
8120 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
8121 ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
8122 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8123 }
8124
8125 if (AddTruncateExpr && ShlAmtCI) {
8126 // We can merge the two given cases into a single SCEV statement,
8127 // incase n = m, the mul expression will be 2^0, so it gets resolved to
8128 // a simpler case. The following code handles the two cases:
8129 //
8130 // 1) For a two-shift sext-inreg, i.e. n = m,
8131 // use sext(trunc(x)) as the SCEV expression.
8132 //
8133 // 2) When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
8134 // expression. We already checked that ShlAmt < BitWidth, so
8135 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
8136 // ShlAmt - AShrAmt < Amt.
8137 const APInt &ShlAmt = ShlAmtCI->getValue();
8138 if (ShlAmt.ult(BitWidth) && ShlAmt.uge(AShrAmt)) {
8139 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
8140 ShlAmtCI->getZExtValue() - AShrAmt);
8141 const SCEV *CompositeExpr =
8142 getMulExpr(AddTruncateExpr, getConstant(Mul));
8143 if (L->getOpcode() != Instruction::Shl)
8144 CompositeExpr = getAddExpr(CompositeExpr, AddConstant);
8145
8146 return getSignExtendExpr(CompositeExpr, OuterTy);
8147 }
8148 }
8149 break;
8150 }
8151 }
8152
8153 switch (U->getOpcode()) {
8154 case Instruction::Trunc:
8155 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
8156
8157 case Instruction::ZExt:
8158 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8159
8160 case Instruction::SExt:
8161 if (auto BO = MatchBinaryOp(U->getOperand(0), getDataLayout(), AC, DT,
8163 // The NSW flag of a subtract does not always survive the conversion to
8164 // A + (-1)*B. By pushing sign extension onto its operands we are much
8165 // more likely to preserve NSW and allow later AddRec optimisations.
8166 //
8167 // NOTE: This is effectively duplicating this logic from getSignExtend:
8168 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
8169 // but by that point the NSW information has potentially been lost.
8170 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
8171 Type *Ty = U->getType();
8172 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
8173 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
8174 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
8175 }
8176 }
8177 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8178
8179 case Instruction::BitCast:
8180 // BitCasts are no-op casts so we just eliminate the cast.
8181 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
8182 return getSCEV(U->getOperand(0));
8183 break;
8184
8185 case Instruction::PtrToAddr: {
8186 const SCEV *IntOp = getPtrToAddrExpr(getSCEV(U->getOperand(0)));
8187 if (isa<SCEVCouldNotCompute>(IntOp))
8188 return getUnknown(V);
8189 return IntOp;
8190 }
8191
8192 case Instruction::PtrToInt:
8193 // SCEV only models ptrtoaddr.
8194 return getUnknown(V);
8195
8196 case Instruction::IntToPtr:
8197 // Just don't deal with inttoptr casts.
8198 return getUnknown(V);
8199
8200 case Instruction::SDiv:
8201 // If both operands are non-negative, this is just an udiv.
8202 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8203 isKnownNonNegative(getSCEV(U->getOperand(1))))
8204 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8205 break;
8206
8207 case Instruction::SRem:
8208 // If both operands are non-negative, this is just an urem.
8209 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8210 isKnownNonNegative(getSCEV(U->getOperand(1))))
8211 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8212 break;
8213
8214 case Instruction::GetElementPtr:
8215 return createNodeForGEP(cast<GEPOperator>(U));
8216
8217 case Instruction::PHI:
8218 return createNodeForPHI(cast<PHINode>(U));
8219
8220 case Instruction::Select:
8221 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
8222 U->getOperand(2));
8223
8224 case Instruction::Call:
8225 case Instruction::Invoke:
8226 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
8227 return getSCEV(RV);
8228
8229 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
8230 switch (II->getIntrinsicID()) {
8231 case Intrinsic::abs:
8232 return getAbsExpr(
8233 getSCEV(II->getArgOperand(0)),
8234 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
8235 case Intrinsic::umax:
8236 LHS = getSCEV(II->getArgOperand(0));
8237 RHS = getSCEV(II->getArgOperand(1));
8238 return getUMaxExpr(LHS, RHS);
8239 case Intrinsic::umin:
8240 LHS = getSCEV(II->getArgOperand(0));
8241 RHS = getSCEV(II->getArgOperand(1));
8242 return getUMinExpr(LHS, RHS);
8243 case Intrinsic::smax:
8244 LHS = getSCEV(II->getArgOperand(0));
8245 RHS = getSCEV(II->getArgOperand(1));
8246 return getSMaxExpr(LHS, RHS);
8247 case Intrinsic::smin:
8248 LHS = getSCEV(II->getArgOperand(0));
8249 RHS = getSCEV(II->getArgOperand(1));
8250 return getSMinExpr(LHS, RHS);
8251 case Intrinsic::usub_sat: {
8252 const SCEV *X = getSCEV(II->getArgOperand(0));
8253 const SCEV *Y = getSCEV(II->getArgOperand(1));
8254 const SCEV *ClampedY = getUMinExpr(X, Y);
8255 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
8256 }
8257 case Intrinsic::uadd_sat: {
8258 const SCEV *X = getSCEV(II->getArgOperand(0));
8259 const SCEV *Y = getSCEV(II->getArgOperand(1));
8260 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
8261 return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
8262 }
8263 case Intrinsic::start_loop_iterations:
8264 case Intrinsic::annotation:
8265 case Intrinsic::ptr_annotation:
8266 // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8267 // just eqivalent to the first operand for SCEV purposes.
8268 return getSCEV(II->getArgOperand(0));
8269 case Intrinsic::vscale:
8270 return getVScale(II->getType());
8271 default:
8272 break;
8273 }
8274 }
8275 break;
8276 }
8277
8278 return getUnknown(V);
8279}
8280
8281//===----------------------------------------------------------------------===//
8282// Iteration Count Computation Code
8283//
8284
8286 if (isa<SCEVCouldNotCompute>(ExitCount))
8287 return getCouldNotCompute();
8288
8289 auto *ExitCountType = ExitCount->getType();
8290 assert(ExitCountType->isIntegerTy());
8291 auto *EvalTy = Type::getIntNTy(ExitCountType->getContext(),
8292 1 + ExitCountType->getScalarSizeInBits());
8293 return getTripCountFromExitCount(ExitCount, EvalTy, nullptr);
8294}
8295
8297 Type *EvalTy,
8298 const Loop *L) {
8299 if (isa<SCEVCouldNotCompute>(ExitCount))
8300 return getCouldNotCompute();
8301
8302 unsigned ExitCountSize = getTypeSizeInBits(ExitCount->getType());
8303 unsigned EvalSize = EvalTy->getPrimitiveSizeInBits();
8304
8305 auto CanAddOneWithoutOverflow = [&]() {
8306 ConstantRange ExitCountRange =
8307 getRangeRef(ExitCount, RangeSignHint::HINT_RANGE_UNSIGNED);
8308 if (!ExitCountRange.contains(APInt::getMaxValue(ExitCountSize)))
8309 return true;
8310
8311 return L && isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
8312 getMinusOne(ExitCount->getType()));
8313 };
8314
8315 // If we need to zero extend the backedge count, check if we can add one to
8316 // it prior to zero extending without overflow. Provided this is safe, it
8317 // allows better simplification of the +1.
8318 if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8319 return getZeroExtendExpr(
8320 getAddExpr(ExitCount, getOne(ExitCount->getType())), EvalTy);
8321
8322 // Get the total trip count from the count by adding 1. This may wrap.
8323 return getAddExpr(getTruncateOrZeroExtend(ExitCount, EvalTy), getOne(EvalTy));
8324}
8325
8326static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8327 if (!ExitCount)
8328 return 0;
8329
8330 ConstantInt *ExitConst = ExitCount->getValue();
8331
8332 // Guard against huge trip counts.
8333 if (ExitConst->getValue().getActiveBits() > 32)
8334 return 0;
8335
8336 // In case of integer overflow, this returns 0, which is correct.
8337 return ((unsigned)ExitConst->getZExtValue()) + 1;
8338}
8339
8341 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
8342 return getConstantTripCount(ExitCount);
8343}
8344
8345unsigned
8347 const BasicBlock *ExitingBlock) {
8348 assert(ExitingBlock && "Must pass a non-null exiting block!");
8349 assert(L->isLoopExiting(ExitingBlock) &&
8350 "Exiting block must actually branch out of the loop!");
8351 const SCEVConstant *ExitCount =
8352 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
8353 return getConstantTripCount(ExitCount);
8354}
8355
8357 const Loop *L, SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8358
8359 const auto *MaxExitCount =
8360 Predicates ? getPredicatedConstantMaxBackedgeTakenCount(L, *Predicates)
8362 return getConstantTripCount(dyn_cast<SCEVConstant>(MaxExitCount));
8363}
8364
8366 SmallVector<BasicBlock *, 8> ExitingBlocks;
8367 L->getExitingBlocks(ExitingBlocks);
8368
8369 // An exit with an uncomputable exit count makes the result 1.
8370 if (ExitingBlocks.empty() ||
8371 any_of(ExitingBlocks, [this, L](BasicBlock *ExitingBB) {
8372 return isa<SCEVCouldNotCompute>(getExitCount(L, ExitingBB));
8373 }))
8374 return 1;
8375
8376 LoopGuards Guards = LoopGuards::collect(L, *this);
8377 unsigned Res = 0;
8378 for (BasicBlock *ExitingBB : ExitingBlocks)
8379 Res = std::gcd(
8380 Res, getSmallConstantTripMultiple(getExitCount(L, ExitingBB), Guards));
8381 return Res;
8382}
8383
8384unsigned
8386 const LoopGuards &Guards) {
8387 assert(!isa<SCEVCouldNotCompute>(ExitCount) && "Must be computable!");
8388
8389 // Get the trip count
8390 const SCEV *TCExpr =
8391 getTripCountFromExitCount(applyLoopGuards(ExitCount, Guards));
8392
8393 APInt Multiple = getNonZeroConstantMultiple(TCExpr);
8394 // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8395 // the greatest power of 2 divisor less than 2^32.
8396 return Multiple.getActiveBits() > 32
8397 ? 1U << std::min(31U, Multiple.countTrailingZeros())
8398 : (unsigned)Multiple.getZExtValue();
8399}
8400
8402 const SCEV *ExitCount) {
8403 if (isa<SCEVCouldNotCompute>(ExitCount))
8404 return 1;
8405
8406 return getSmallConstantTripMultiple(ExitCount, LoopGuards::collect(L, *this));
8407}
8408
8409/// Returns the largest constant divisor of the trip count of this loop as a
8410/// normal unsigned value, if possible. This means that the actual trip count is
8411/// always a multiple of the returned value (don't forget the trip count could
8412/// very well be zero as well!).
8413///
8414/// Returns 1 if the trip count is unknown or not guaranteed to be the
8415/// multiple of a constant (which is also the case if the trip count is simply
8416/// constant, use getSmallConstantTripCount for that case), Will also return 1
8417/// if the trip count is very large (>= 2^32).
8418///
8419/// As explained in the comments for getSmallConstantTripCount, this assumes
8420/// that control exits the loop via ExitingBlock.
8421unsigned
8423 const BasicBlock *ExitingBlock) {
8424 assert(ExitingBlock && "Must pass a non-null exiting block!");
8425 assert(L->isLoopExiting(ExitingBlock) &&
8426 "Exiting block must actually branch out of the loop!");
8427 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8428 return getSmallConstantTripMultiple(L, ExitCount);
8429}
8430
8432 const BasicBlock *ExitingBlock,
8433 ExitCountKind Kind) {
8434 switch (Kind) {
8435 case Exact:
8436 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8437 case SymbolicMaximum:
8438 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8439 case ConstantMaximum:
8440 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8441 };
8442 llvm_unreachable("Invalid ExitCountKind!");
8443}
8444
8446 const Loop *L, const BasicBlock *ExitingBlock,
8448 switch (Kind) {
8449 case Exact:
8450 return getPredicatedBackedgeTakenInfo(L).getExact(ExitingBlock, this,
8451 Predicates);
8452 case SymbolicMaximum:
8453 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this,
8454 Predicates);
8455 case ConstantMaximum:
8456 return getPredicatedBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this,
8457 Predicates);
8458 };
8459 llvm_unreachable("Invalid ExitCountKind!");
8460}
8461
8464 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8465}
8466
8468 ExitCountKind Kind) {
8469 switch (Kind) {
8470 case Exact:
8471 return getBackedgeTakenInfo(L).getExact(L, this);
8472 case ConstantMaximum:
8473 return getBackedgeTakenInfo(L).getConstantMax(this);
8474 case SymbolicMaximum:
8475 return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8476 };
8477 llvm_unreachable("Invalid ExitCountKind!");
8478}
8479
8482 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(L, this, &Preds);
8483}
8484
8487 return getPredicatedBackedgeTakenInfo(L).getConstantMax(this, &Preds);
8488}
8489
8491 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8492}
8493
8494/// Push PHI nodes in the header of the given loop onto the given Worklist.
8495static void PushLoopPHIs(const Loop *L,
8498 BasicBlock *Header = L->getHeader();
8499
8500 // Push all Loop-header PHIs onto the Worklist stack.
8501 for (PHINode &PN : Header->phis())
8502 if (Visited.insert(&PN).second)
8503 Worklist.push_back(&PN);
8504}
8505
8506ScalarEvolution::BackedgeTakenInfo &
8507ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8508 auto &BTI = getBackedgeTakenInfo(L);
8509 if (BTI.hasFullInfo())
8510 return BTI;
8511
8512 auto Pair = PredicatedBackedgeTakenCounts.try_emplace(L);
8513
8514 if (!Pair.second)
8515 return Pair.first->second;
8516
8517 BackedgeTakenInfo Result =
8518 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8519
8520 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8521}
8522
8523ScalarEvolution::BackedgeTakenInfo &
8524ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8525 // Initially insert an invalid entry for this loop. If the insertion
8526 // succeeds, proceed to actually compute a backedge-taken count and
8527 // update the value. The temporary CouldNotCompute value tells SCEV
8528 // code elsewhere that it shouldn't attempt to request a new
8529 // backedge-taken count, which could result in infinite recursion.
8530 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8531 BackedgeTakenCounts.try_emplace(L);
8532 if (!Pair.second)
8533 return Pair.first->second;
8534
8535 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8536 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8537 // must be cleared in this scope.
8538 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8539
8540 // Now that we know more about the trip count for this loop, forget any
8541 // existing SCEV values for PHI nodes in this loop since they are only
8542 // conservative estimates made without the benefit of trip count
8543 // information. This invalidation is not necessary for correctness, and is
8544 // only done to produce more precise results.
8545 if (Result.hasAnyInfo()) {
8546 // Invalidate any expression using an addrec in this loop.
8547 SmallVector<SCEVUse, 8> ToForget;
8548 auto LoopUsersIt = LoopUsers.find(L);
8549 if (LoopUsersIt != LoopUsers.end())
8550 append_range(ToForget, LoopUsersIt->second);
8551 forgetMemoizedResults(ToForget);
8552
8553 // Invalidate constant-evolved loop header phis.
8554 for (PHINode &PN : L->getHeader()->phis())
8555 ConstantEvolutionLoopExitValue.erase(&PN);
8556 }
8557
8558 // Re-lookup the insert position, since the call to
8559 // computeBackedgeTakenCount above could result in a
8560 // recusive call to getBackedgeTakenInfo (on a different
8561 // loop), which would invalidate the iterator computed
8562 // earlier.
8563 return BackedgeTakenCounts.find(L)->second = std::move(Result);
8564}
8565
8567 // This method is intended to forget all info about loops. It should
8568 // invalidate caches as if the following happened:
8569 // - The trip counts of all loops have changed arbitrarily
8570 // - Every llvm::Value has been updated in place to produce a different
8571 // result.
8572 BackedgeTakenCounts.clear();
8573 PredicatedBackedgeTakenCounts.clear();
8574 BECountUsers.clear();
8575 LoopPropertiesCache.clear();
8576 ConstantEvolutionLoopExitValue.clear();
8577 ValueExprMap.clear();
8578 ValuesAtScopes.clear();
8579 ValuesAtScopesUsers.clear();
8580 LoopDispositions.clear();
8581 BlockDispositions.clear();
8582 UnsignedRanges.clear();
8583 SignedRanges.clear();
8584 ExprValueMap.clear();
8585 HasRecMap.clear();
8586 ConstantMultipleCache.clear();
8587 PredicatedSCEVRewrites.clear();
8588 FoldCache.clear();
8589 FoldCacheUser.clear();
8590}
8591void ScalarEvolution::visitAndClearUsers(
8594 SmallVectorImpl<SCEVUse> &ToForget) {
8595 while (!Worklist.empty()) {
8596 Instruction *I = Worklist.pop_back_val();
8597 if (!isSCEVable(I->getType()) && !isa<WithOverflowInst>(I))
8598 continue;
8599
8601 ValueExprMap.find_as(static_cast<Value *>(I));
8602 if (It != ValueExprMap.end()) {
8603 ToForget.push_back(It->second);
8604 eraseValueFromMap(It->first);
8605 if (PHINode *PN = dyn_cast<PHINode>(I))
8606 ConstantEvolutionLoopExitValue.erase(PN);
8607 }
8608
8609 PushDefUseChildren(I, Worklist, Visited);
8610 }
8611}
8612
8614 SmallVector<const Loop *, 16> LoopWorklist(1, L);
8617 SmallVector<SCEVUse, 16> ToForget;
8618
8619 // Iterate over all the loops and sub-loops to drop SCEV information.
8620 while (!LoopWorklist.empty()) {
8621 auto *CurrL = LoopWorklist.pop_back_val();
8622
8623 // Drop any stored trip count value.
8624 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8625 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8626
8627 // Drop information about predicated SCEV rewrites for this loop.
8628 PredicatedSCEVRewrites.remove_if(
8629 [&](const auto &Entry) { return Entry.first.second == CurrL; });
8630
8631 auto LoopUsersItr = LoopUsers.find(CurrL);
8632 if (LoopUsersItr != LoopUsers.end())
8633 llvm::append_range(ToForget, LoopUsersItr->second);
8634
8635 // Drop information about expressions based on loop-header PHIs.
8636 PushLoopPHIs(CurrL, Worklist, Visited);
8637 visitAndClearUsers(Worklist, Visited, ToForget);
8638
8639 LoopPropertiesCache.erase(CurrL);
8640 // Forget all contained loops too, to avoid dangling entries in the
8641 // ValuesAtScopes map.
8642 LoopWorklist.append(CurrL->begin(), CurrL->end());
8643 }
8644 forgetMemoizedResults(ToForget);
8645}
8646
8648 forgetLoop(L->getOutermostLoop());
8649}
8650
8653 if (!I) return;
8654
8655 // Drop information about expressions based on loop-header PHIs.
8658 SmallVector<SCEVUse, 8> ToForget;
8659 Worklist.push_back(I);
8660 Visited.insert(I);
8661 visitAndClearUsers(Worklist, Visited, ToForget);
8662
8663 forgetMemoizedResults(ToForget);
8664}
8665
8667 // If SCEV looked through a trivial LCSSA phi node, we might have SCEV's
8668 // directly using a SCEVUnknown/SCEVAddRec defined in the loop. After an
8669 // extra predecessor is added, this is no longer valid. Find all Unknowns and
8670 // AddRecs defined in the loop and invalidate any SCEV's making use of them.
8671 auto InvalidateValue = [&](Value *Val) {
8672 if (!isSCEVable(Val->getType()))
8673 return;
8674 if (const SCEV *S = getExistingSCEV(Val)) {
8675 struct InvalidationRootCollector {
8676 Loop *L;
8678
8679 InvalidationRootCollector(Loop *L) : L(L) {}
8680
8681 bool follow(const SCEV *S) {
8682 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
8683 if (auto *I = dyn_cast<Instruction>(SU->getValue()))
8684 if (L->contains(I))
8685 Roots.push_back(S);
8686 } else if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
8687 if (L->contains(AddRec->getLoop()))
8688 Roots.push_back(S);
8689 }
8690 return true;
8691 }
8692 bool isDone() const { return false; }
8693 };
8694
8695 InvalidationRootCollector C(L);
8696 visitAll(S, C);
8697 forgetMemoizedResults(C.Roots);
8698 }
8699 };
8700
8701 InvalidateValue(V);
8702
8703 // If V has a non-SCEV-able type (e.g. {i64, i1} from a with.overflow
8704 // intrinsic), its users (e.g. extractvalue) may have stale SCEV
8705 // expressions referencing loop-internal values.
8706 if (!isSCEVable(V->getType()) &&
8707 any_of(V->incoming_values(), IsaPred<WithOverflowInst>))
8708 for (User *U : V->users())
8709 InvalidateValue(U);
8710 // Also perform the normal invalidation.
8711 forgetValue(V);
8712}
8713
8714void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8715
8717 // Unless a specific value is passed to invalidation, completely clear both
8718 // caches.
8719 if (!V) {
8720 BlockDispositions.clear();
8721 LoopDispositions.clear();
8722 return;
8723 }
8724
8725 if (!isSCEVable(V->getType()))
8726 return;
8727
8728 const SCEV *S = getExistingSCEV(V);
8729 if (!S)
8730 return;
8731
8732 // Invalidate the block and loop dispositions cached for S. Dispositions of
8733 // S's users may change if S's disposition changes (i.e. a user may change to
8734 // loop-invariant, if S changes to loop invariant), so also invalidate
8735 // dispositions of S's users recursively.
8736 SmallVector<SCEVUse, 8> Worklist = {S};
8738 while (!Worklist.empty()) {
8739 const SCEV *Curr = Worklist.pop_back_val();
8740 bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8741 bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8742 if (!LoopDispoRemoved && !BlockDispoRemoved)
8743 continue;
8744 auto Users = SCEVUsers.find(Curr);
8745 if (Users != SCEVUsers.end())
8746 for (const auto *User : Users->second)
8747 if (Seen.insert(User).second)
8748 Worklist.push_back(User);
8749 }
8750}
8751
8752/// Get the exact loop backedge taken count considering all loop exits. A
8753/// computable result can only be returned for loops with all exiting blocks
8754/// dominating the latch. howFarToZero assumes that the limit of each loop test
8755/// is never skipped. This is a valid assumption as long as the loop exits via
8756/// that test. For precise results, it is the caller's responsibility to specify
8757/// the relevant loop exiting block using getExact(ExitingBlock, SE).
8758const SCEV *ScalarEvolution::BackedgeTakenInfo::getExact(
8759 const Loop *L, ScalarEvolution *SE,
8761 // If any exits were not computable, the loop is not computable.
8762 if (!isComplete() || ExitNotTaken.empty())
8763 return SE->getCouldNotCompute();
8764
8765 const BasicBlock *Latch = L->getLoopLatch();
8766 // All exiting blocks we have collected must dominate the only backedge.
8767 if (!Latch)
8768 return SE->getCouldNotCompute();
8769
8770 // All exiting blocks we have gathered dominate loop's latch, so exact trip
8771 // count is simply a minimum out of all these calculated exit counts.
8773 for (const auto &ENT : ExitNotTaken) {
8774 const SCEV *BECount = ENT.ExactNotTaken;
8775 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8776 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8777 "We should only have known counts for exiting blocks that dominate "
8778 "latch!");
8779
8780 Ops.push_back(BECount);
8781
8782 if (Preds)
8783 append_range(*Preds, ENT.Predicates);
8784
8785 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8786 "Predicate should be always true!");
8787 }
8788
8789 // If an earlier exit exits on the first iteration (exit count zero), then
8790 // a later poison exit count should not propagate into the result. This are
8791 // exactly the semantics provided by umin_seq.
8792 return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8793}
8794
8795const ScalarEvolution::ExitNotTakenInfo *
8796ScalarEvolution::BackedgeTakenInfo::getExitNotTaken(
8797 const BasicBlock *ExitingBlock,
8798 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8799 for (const auto &ENT : ExitNotTaken)
8800 if (ENT.ExitingBlock == ExitingBlock) {
8801 if (ENT.hasAlwaysTruePredicate())
8802 return &ENT;
8803 else if (Predicates) {
8804 append_range(*Predicates, ENT.Predicates);
8805 return &ENT;
8806 }
8807 }
8808
8809 return nullptr;
8810}
8811
8812/// getConstantMax - Get the constant max backedge taken count for the loop.
8813const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8814 ScalarEvolution *SE,
8815 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8816 if (!getConstantMax())
8817 return SE->getCouldNotCompute();
8818
8819 for (const auto &ENT : ExitNotTaken)
8820 if (!ENT.hasAlwaysTruePredicate()) {
8821 if (!Predicates)
8822 return SE->getCouldNotCompute();
8823 append_range(*Predicates, ENT.Predicates);
8824 }
8825
8826 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8827 isa<SCEVConstant>(getConstantMax())) &&
8828 "No point in having a non-constant max backedge taken count!");
8829 return getConstantMax();
8830}
8831
8832const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8833 const Loop *L, ScalarEvolution *SE,
8834 SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8835 if (!SymbolicMax) {
8836 // Form an expression for the maximum exit count possible for this loop. We
8837 // merge the max and exact information to approximate a version of
8838 // getConstantMaxBackedgeTakenCount which isn't restricted to just
8839 // constants.
8840 SmallVector<SCEVUse, 4> ExitCounts;
8841
8842 for (const auto &ENT : ExitNotTaken) {
8843 const SCEV *ExitCount = ENT.SymbolicMaxNotTaken;
8844 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
8845 assert(SE->DT.dominates(ENT.ExitingBlock, L->getLoopLatch()) &&
8846 "We should only have known counts for exiting blocks that "
8847 "dominate latch!");
8848 ExitCounts.push_back(ExitCount);
8849 if (Predicates)
8850 append_range(*Predicates, ENT.Predicates);
8851
8852 assert((Predicates || ENT.hasAlwaysTruePredicate()) &&
8853 "Predicate should be always true!");
8854 }
8855 }
8856 if (ExitCounts.empty())
8857 SymbolicMax = SE->getCouldNotCompute();
8858 else
8859 SymbolicMax =
8860 SE->getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
8861 }
8862 return SymbolicMax;
8863}
8864
8865bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8866 ScalarEvolution *SE) const {
8867 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8868 return !ENT.hasAlwaysTruePredicate();
8869 };
8870 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8871}
8872
8875
8877 const SCEV *E, const SCEV *ConstantMaxNotTaken,
8878 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8882 // If we prove the max count is zero, so is the symbolic bound. This happens
8883 // in practice due to differences in a) how context sensitive we've chosen
8884 // to be and b) how we reason about bounds implied by UB.
8885 if (ConstantMaxNotTaken->isZero()) {
8886 this->ExactNotTaken = E = ConstantMaxNotTaken;
8887 this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
8888 }
8889
8892 "Exact is not allowed to be less precise than Constant Max");
8895 "Exact is not allowed to be less precise than Symbolic Max");
8898 "Symbolic Max is not allowed to be less precise than Constant Max");
8901 "No point in having a non-constant max backedge taken count!");
8903 for (const auto PredList : PredLists)
8904 for (const auto *P : PredList) {
8905 if (SeenPreds.contains(P))
8906 continue;
8907 assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!");
8908 SeenPreds.insert(P);
8909 Predicates.push_back(P);
8910 }
8911 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8912 "Backedge count should be int");
8914 !ConstantMaxNotTaken->getType()->isPointerTy()) &&
8915 "Max backedge count should be int");
8916}
8917
8925
8926/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8927/// computable exit into a persistent ExitNotTakenInfo array.
8928ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8930 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
8931 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8932 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8933
8934 ExitNotTaken.reserve(ExitCounts.size());
8935 std::transform(ExitCounts.begin(), ExitCounts.end(),
8936 std::back_inserter(ExitNotTaken),
8937 [&](const EdgeExitInfo &EEI) {
8938 BasicBlock *ExitBB = EEI.first;
8939 const ExitLimit &EL = EEI.second;
8940 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
8941 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
8942 EL.Predicates);
8943 });
8944 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
8945 isa<SCEVConstant>(ConstantMax)) &&
8946 "No point in having a non-constant max backedge taken count!");
8947}
8948
8949/// Compute the number of times the backedge of the specified loop will execute.
8950ScalarEvolution::BackedgeTakenInfo
8951ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
8952 bool AllowPredicates) {
8953 SmallVector<BasicBlock *, 8> ExitingBlocks;
8954 L->getExitingBlocks(ExitingBlocks);
8955
8956 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8957
8959 bool CouldComputeBECount = true;
8960 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
8961 const SCEV *MustExitMaxBECount = nullptr;
8962 const SCEV *MayExitMaxBECount = nullptr;
8963 bool MustExitMaxOrZero = false;
8964 bool IsOnlyExit = ExitingBlocks.size() == 1;
8965
8966 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
8967 // and compute maxBECount.
8968 // Do a union of all the predicates here.
8969 for (BasicBlock *ExitBB : ExitingBlocks) {
8970 // We canonicalize untaken exits to br (constant), ignore them so that
8971 // proving an exit untaken doesn't negatively impact our ability to reason
8972 // about the loop as whole.
8973 if (auto *BI = dyn_cast<CondBrInst>(ExitBB->getTerminator()))
8974 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
8975 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8976 if (ExitIfTrue == CI->isZero())
8977 continue;
8978 }
8979
8980 ExitLimit EL = computeExitLimit(L, ExitBB, IsOnlyExit, AllowPredicates);
8981
8982 assert((AllowPredicates || EL.Predicates.empty()) &&
8983 "Predicated exit limit when predicates are not allowed!");
8984
8985 // 1. For each exit that can be computed, add an entry to ExitCounts.
8986 // CouldComputeBECount is true only if all exits can be computed.
8987 if (EL.ExactNotTaken != getCouldNotCompute())
8988 ++NumExitCountsComputed;
8989 else
8990 // We couldn't compute an exact value for this exit, so
8991 // we won't be able to compute an exact value for the loop.
8992 CouldComputeBECount = false;
8993 // Remember exit count if either exact or symbolic is known. Because
8994 // Exact always implies symbolic, only check symbolic.
8995 if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
8996 ExitCounts.emplace_back(ExitBB, EL);
8997 else {
8998 assert(EL.ExactNotTaken == getCouldNotCompute() &&
8999 "Exact is known but symbolic isn't?");
9000 ++NumExitCountsNotComputed;
9001 }
9002
9003 // 2. Derive the loop's MaxBECount from each exit's max number of
9004 // non-exiting iterations. Partition the loop exits into two kinds:
9005 // LoopMustExits and LoopMayExits.
9006 //
9007 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
9008 // is a LoopMayExit. If any computable LoopMustExit is found, then
9009 // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
9010 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
9011 // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
9012 // any
9013 // computable EL.ConstantMaxNotTaken.
9014 if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
9015 DT.dominates(ExitBB, Latch)) {
9016 if (!MustExitMaxBECount) {
9017 MustExitMaxBECount = EL.ConstantMaxNotTaken;
9018 MustExitMaxOrZero = EL.MaxOrZero;
9019 } else {
9020 MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
9021 EL.ConstantMaxNotTaken);
9022 }
9023 } else if (MayExitMaxBECount != getCouldNotCompute()) {
9024 if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
9025 MayExitMaxBECount = EL.ConstantMaxNotTaken;
9026 else {
9027 MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
9028 EL.ConstantMaxNotTaken);
9029 }
9030 }
9031 }
9032 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
9033 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
9034 // The loop backedge will be taken the maximum or zero times if there's
9035 // a single exit that must be taken the maximum or zero times.
9036 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
9037
9038 // Remember which SCEVs are used in exit limits for invalidation purposes.
9039 // We only care about non-constant SCEVs here, so we can ignore
9040 // EL.ConstantMaxNotTaken
9041 // and MaxBECount, which must be SCEVConstant.
9042 for (const auto &Pair : ExitCounts) {
9043 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
9044 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
9045 if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
9046 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
9047 {L, AllowPredicates});
9048 }
9049 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
9050 MaxBECount, MaxOrZero);
9051}
9052
9053ScalarEvolution::ExitLimit
9054ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
9055 bool IsOnlyExit, bool AllowPredicates) {
9056 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
9057 // If our exiting block does not dominate the latch, then its connection with
9058 // loop's exit limit may be far from trivial.
9059 const BasicBlock *Latch = L->getLoopLatch();
9060 if (!Latch || !DT.dominates(ExitingBlock, Latch))
9061 return getCouldNotCompute();
9062
9063 Instruction *Term = ExitingBlock->getTerminator();
9064 if (CondBrInst *BI = dyn_cast<CondBrInst>(Term)) {
9065 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9066 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
9067 "It should have one successor in loop and one exit block!");
9068 // Proceed to the next level to examine the exit condition expression.
9069 return computeExitLimitFromCond(L, BI->getCondition(), ExitIfTrue,
9070 /*ControlsOnlyExit=*/IsOnlyExit,
9071 AllowPredicates);
9072 }
9073
9074 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
9075 // For switch, make sure that there is a single exit from the loop.
9076 BasicBlock *Exit = nullptr;
9077 for (auto *SBB : successors(ExitingBlock))
9078 if (!L->contains(SBB)) {
9079 if (Exit) // Multiple exit successors.
9080 return getCouldNotCompute();
9081 Exit = SBB;
9082 }
9083 assert(Exit && "Exiting block must have at least one exit");
9084 return computeExitLimitFromSingleExitSwitch(
9085 L, SI, Exit, /*ControlsOnlyExit=*/IsOnlyExit);
9086 }
9087
9088 return getCouldNotCompute();
9089}
9090
9092 const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9093 bool AllowPredicates) {
9094 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
9095 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
9096 ControlsOnlyExit, AllowPredicates);
9097}
9098
9099std::optional<ScalarEvolution::ExitLimit>
9100ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
9101 bool ExitIfTrue, bool ControlsOnlyExit,
9102 bool AllowPredicates) {
9103 (void)this->L;
9104 (void)this->ExitIfTrue;
9105 (void)this->AllowPredicates;
9106
9107 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9108 this->AllowPredicates == AllowPredicates &&
9109 "Variance in assumed invariant key components!");
9110 auto Itr = TripCountMap.find({ExitCond, ControlsOnlyExit});
9111 if (Itr == TripCountMap.end())