LLVM 24.0.0git
ScalarEvolution.cpp
Go to the documentation of this file.
1//===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the implementation of the scalar evolution analysis
10// engine, which is used primarily to analyze expressions involving induction
11// variables in loops.
12//
13// There are several aspects to this library. First is the representation of
14// scalar expressions, which are represented as subclasses of the SCEV class.
15// These classes are used to represent certain types of subexpressions that we
16// can handle. We only create one SCEV of a particular shape, so
17// pointer-comparisons for equality are legal.
18//
19// One important aspect of the SCEV objects is that they are never cyclic, even
20// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
21// the PHI node is one of the idioms that we can represent (e.g., a polynomial
22// recurrence) then we represent it directly as a recurrence node, otherwise we
23// represent it as a SCEVUnknown node.
24//
25// In addition to being able to represent expressions of various types, we also
26// have folders that are used to build the *canonical* representation for a
27// particular expression. These folders are capable of using a variety of
28// rewrite rules to simplify the expressions.
29//
30// Once the folders are defined, we can implement the more interesting
31// higher-level code, such as the code that recognizes PHI nodes of various
32// types, computes the execution count of a loop, etc.
33//
34// TODO: We should use these routines and value representations to implement
35// dependence analysis!
36//
37//===----------------------------------------------------------------------===//
38//
39// There are several good references for the techniques used in this analysis.
40//
41// Chains of recurrences -- a method to expedite the evaluation
42// of closed-form functions
43// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
44//
45// On computational properties of chains of recurrences
46// Eugene V. Zima
47//
48// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
49// Robert A. van Engelen
50//
51// Efficient Symbolic Analysis for Optimizing Compilers
52// Robert A. van Engelen
53//
54// Using the chains of recurrences algebra for data dependence testing and
55// induction variable substitution
56// MS Thesis, Johnie Birch
57//
58//===----------------------------------------------------------------------===//
59
61#include "llvm/ADT/APInt.h"
62#include "llvm/ADT/ArrayRef.h"
63#include "llvm/ADT/DenseMap.h"
65#include "llvm/ADT/FoldingSet.h"
66#include "llvm/ADT/STLExtras.h"
67#include "llvm/ADT/ScopeExit.h"
68#include "llvm/ADT/Sequence.h"
71#include "llvm/ADT/Statistic.h"
73#include "llvm/ADT/StringRef.h"
83#include "llvm/Config/llvm-config.h"
84#include "llvm/IR/Argument.h"
85#include "llvm/IR/BasicBlock.h"
86#include "llvm/IR/CFG.h"
87#include "llvm/IR/Constant.h"
89#include "llvm/IR/Constants.h"
90#include "llvm/IR/DataLayout.h"
92#include "llvm/IR/Dominators.h"
93#include "llvm/IR/Function.h"
94#include "llvm/IR/GlobalAlias.h"
95#include "llvm/IR/GlobalValue.h"
97#include "llvm/IR/InstrTypes.h"
98#include "llvm/IR/Instruction.h"
101#include "llvm/IR/Intrinsics.h"
102#include "llvm/IR/LLVMContext.h"
103#include "llvm/IR/Operator.h"
104#include "llvm/IR/PatternMatch.h"
105#include "llvm/IR/Type.h"
106#include "llvm/IR/Use.h"
107#include "llvm/IR/User.h"
108#include "llvm/IR/Value.h"
109#include "llvm/IR/Verifier.h"
111#include "llvm/Pass.h"
112#include "llvm/Support/Casting.h"
115#include "llvm/Support/Debug.h"
121#include <algorithm>
122#include <cassert>
123#include <climits>
124#include <cstdint>
125#include <cstdlib>
126#include <map>
127#include <memory>
128#include <numeric>
129#include <optional>
130#include <tuple>
131#include <utility>
132#include <vector>
133
134using namespace llvm;
135using namespace PatternMatch;
136using namespace SCEVPatternMatch;
137
138#define DEBUG_TYPE "scalar-evolution"
139
140STATISTIC(NumExitCountsComputed,
141 "Number of loop exits with predictable exit counts");
142STATISTIC(NumExitCountsNotComputed,
143 "Number of loop exits without predictable exit counts");
144STATISTIC(NumBruteForceTripCountsComputed,
145 "Number of loops with trip counts computed by force");
146
147#ifdef EXPENSIVE_CHECKS
148bool llvm::VerifySCEV = true;
149#else
150bool llvm::VerifySCEV = false;
151#endif
152
154 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
155 cl::desc("Maximum number of iterations SCEV will "
156 "symbolically execute a constant "
157 "derived loop"),
158 cl::init(100));
159
161 "verify-scev", cl::Hidden, cl::location(VerifySCEV),
162 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
164 "verify-scev-strict", cl::Hidden,
165 cl::desc("Enable stricter verification with -verify-scev is passed"));
166
168 "scev-verify-ir", cl::Hidden,
169 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
170 cl::init(false));
171
173 "scev-mulops-inline-threshold", cl::Hidden,
174 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
175 cl::init(32));
176
178 "scev-addops-inline-threshold", cl::Hidden,
179 cl::desc("Threshold for inlining addition operands into a SCEV"),
180 cl::init(500));
181
183 "scalar-evolution-max-scev-compare-depth", cl::Hidden,
184 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
185 cl::init(32));
186
188 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
189 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
190 cl::init(2));
191
193 "scalar-evolution-max-value-compare-depth", cl::Hidden,
194 cl::desc("Maximum depth of recursive value complexity comparisons"),
195 cl::init(2));
196
198 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
199 cl::desc("Maximum depth of recursive arithmetics"),
200 cl::init(32));
201
203 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
204 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
205
207 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
208 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
209 cl::init(8));
210
212 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
213 cl::desc("Max coefficients in AddRec during evolving"),
214 cl::init(8));
215
217 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
218 cl::desc("Size of the expression which is considered huge"),
219 cl::init(4096));
220
222 "scev-range-iter-threshold", cl::Hidden,
223 cl::desc("Threshold for switching to iteratively computing SCEV ranges"),
224 cl::init(32));
225
227 "scalar-evolution-max-loop-guard-collection-depth", cl::Hidden,
228 cl::desc("Maximum depth for recursive loop guard collection"), cl::init(1));
229
230static cl::opt<bool>
231ClassifyExpressions("scalar-evolution-classify-expressions",
232 cl::Hidden, cl::init(true),
233 cl::desc("When printing analysis, include information on every instruction"));
234
236 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
237 cl::init(false),
238 cl::desc("Use more powerful methods of sharpening expression ranges. May "
239 "be costly in terms of compile time"));
240
242 "scalar-evolution-max-scc-analysis-depth", cl::Hidden,
243 cl::desc("Maximum amount of nodes to process while searching SCEVUnknown "
244 "Phi strongly connected components"),
245 cl::init(8));
246
247static cl::opt<bool>
248 EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
249 cl::desc("Handle <= and >= in finite loops"),
250 cl::init(true));
251
253 "scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden,
254 cl::desc("Infer nuw/nsw flags using context where suitable"),
255 cl::init(true));
256
257//===----------------------------------------------------------------------===//
258// SCEV class definitions
259//===----------------------------------------------------------------------===//
260
262 // Leaf nodes are always their own canonical.
263 switch (getSCEVType()) {
264 case scConstant:
265 case scVScale:
266 case scUnknown:
267 CanonicalSCEV = this;
268 return;
269 default:
270 break;
271 }
272
273 // For all other expressions, check whether any immediate operand has a
274 // different canonical. Since operands are always created before their parent,
275 // their canonical pointers are already set — no recursion needed.
276 bool Changed = false;
278 for (SCEVUse Op : operands()) {
279 CanonOps.push_back(Op->getCanonical());
280 Changed |= CanonOps.back() != Op.getPointer();
281 }
282
283 if (!Changed) {
284 CanonicalSCEV = this;
285 return;
286 }
287
288 auto *NAry = dyn_cast<SCEVNAryExpr>(this);
289 SCEV::NoWrapFlags Flags = NAry ? NAry->getNoWrapFlags() : SCEV::FlagAnyWrap;
290 switch (getSCEVType()) {
291 case scPtrToAddr:
292 CanonicalSCEV = SE.getPtrToAddrExpr(CanonOps[0]);
293 return;
294 case scPtrToInt:
295 CanonicalSCEV = SE.getPtrToIntExpr(CanonOps[0], getType());
296 return;
297 case scTruncate:
298 CanonicalSCEV = SE.getTruncateExpr(CanonOps[0], getType());
299 return;
300 case scZeroExtend:
301 CanonicalSCEV = SE.getZeroExtendExpr(CanonOps[0], getType());
302 return;
303 case scSignExtend:
304 CanonicalSCEV = SE.getSignExtendExpr(CanonOps[0], getType());
305 return;
306 case scUDivExpr:
307 CanonicalSCEV = SE.getUDivExpr(CanonOps[0], CanonOps[1]);
308 return;
309 case scAddExpr:
310 CanonicalSCEV = SE.getAddExpr(CanonOps, Flags);
311 return;
312 case scMulExpr:
313 CanonicalSCEV = SE.getMulExpr(CanonOps, Flags);
314 return;
315 case scAddRecExpr:
317 CanonOps, cast<SCEVAddRecExpr>(this)->getLoop(), Flags);
318 return;
319 case scSMaxExpr:
320 CanonicalSCEV = SE.getSMaxExpr(CanonOps);
321 return;
322 case scUMaxExpr:
323 CanonicalSCEV = SE.getUMaxExpr(CanonOps);
324 return;
325 case scSMinExpr:
326 CanonicalSCEV = SE.getSMinExpr(CanonOps);
327 return;
328 case scUMinExpr:
329 CanonicalSCEV = SE.getUMinExpr(CanonOps);
330 return;
332 CanonicalSCEV = SE.getUMinExpr(CanonOps, /*Sequential=*/true);
333 return;
334 default:
335 llvm_unreachable("Unknown SCEV type");
336 }
337}
338
339//===----------------------------------------------------------------------===//
340// Implementation of the SCEV class.
341//
342
343#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
345 print(dbgs());
346 dbgs() << '\n';
347}
348#endif
349
350void SCEV::print(raw_ostream &OS) const {
351 switch (getSCEVType()) {
352 case scConstant:
353 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
354 return;
355 case scVScale:
356 OS << "vscale";
357 return;
358 case scPtrToAddr:
359 case scPtrToInt: {
360 const SCEVCastExpr *PtrCast = cast<SCEVCastExpr>(this);
361 const SCEV *Op = PtrCast->getOperand();
362 StringRef OpS = getSCEVType() == scPtrToAddr ? "addr" : "int";
363 OS << "(ptrto" << OpS << " " << *Op->getType() << " " << *Op << " to "
364 << *PtrCast->getType() << ")";
365 return;
366 }
367 case scTruncate: {
368 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
369 const SCEV *Op = Trunc->getOperand();
370 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
371 << *Trunc->getType() << ")";
372 return;
373 }
374 case scZeroExtend: {
376 const SCEV *Op = ZExt->getOperand();
377 OS << "(zext " << *Op->getType() << " " << *Op << " to "
378 << *ZExt->getType() << ")";
379 return;
380 }
381 case scSignExtend: {
383 const SCEV *Op = SExt->getOperand();
384 OS << "(sext " << *Op->getType() << " " << *Op << " to "
385 << *SExt->getType() << ")";
386 return;
387 }
388 case scAddRecExpr: {
389 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
390 OS << "{" << *AR->getOperand(0);
391 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
392 OS << ",+," << *AR->getOperand(i);
393 OS << "}<";
394 if (AR->hasNoUnsignedWrap())
395 OS << "nuw><";
396 if (AR->hasNoSignedWrap())
397 OS << "nsw><";
398 if (AR->hasNoSelfWrap() && !AR->hasNoUnsignedWrap() &&
399 !AR->hasNoSignedWrap())
400 OS << "nw><";
401 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
402 OS << ">";
403 return;
404 }
405 case scAddExpr:
406 case scMulExpr:
407 case scUMaxExpr:
408 case scSMaxExpr:
409 case scUMinExpr:
410 case scSMinExpr:
412 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
413 const char *OpStr = nullptr;
414 switch (NAry->getSCEVType()) {
415 case scAddExpr: OpStr = " + "; break;
416 case scMulExpr: OpStr = " * "; break;
417 case scUMaxExpr: OpStr = " umax "; break;
418 case scSMaxExpr: OpStr = " smax "; break;
419 case scUMinExpr:
420 OpStr = " umin ";
421 break;
422 case scSMinExpr:
423 OpStr = " smin ";
424 break;
426 OpStr = " umin_seq ";
427 break;
428 default:
429 llvm_unreachable("There are no other nary expression types.");
430 }
431 OS << "("
433 << ")";
434 switch (NAry->getSCEVType()) {
435 case scAddExpr:
436 case scMulExpr:
437 if (NAry->hasNoUnsignedWrap())
438 OS << "<nuw>";
439 if (NAry->hasNoSignedWrap())
440 OS << "<nsw>";
441 break;
442 default:
443 // Nothing to print for other nary expressions.
444 break;
445 }
446 return;
447 }
448 case scUDivExpr: {
449 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
450 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
451 return;
452 }
453 case scUnknown:
454 cast<SCEVUnknown>(this)->getValue()->printAsOperand(OS, false);
455 return;
457 OS << "***COULDNOTCOMPUTE***";
458 return;
459 }
460 llvm_unreachable("Unknown SCEV kind!");
461}
462
464 switch (getSCEVType()) {
465 case scConstant:
466 return cast<SCEVConstant>(this)->getType();
467 case scVScale:
468 return cast<SCEVVScale>(this)->getType();
469 case scPtrToAddr:
470 case scPtrToInt:
471 case scTruncate:
472 case scZeroExtend:
473 case scSignExtend:
474 return cast<SCEVCastExpr>(this)->getType();
475 case scAddRecExpr:
476 return cast<SCEVAddRecExpr>(this)->getType();
477 case scMulExpr:
478 return cast<SCEVMulExpr>(this)->getType();
479 case scUMaxExpr:
480 case scSMaxExpr:
481 case scUMinExpr:
482 case scSMinExpr:
483 return cast<SCEVMinMaxExpr>(this)->getType();
485 return cast<SCEVSequentialMinMaxExpr>(this)->getType();
486 case scAddExpr:
487 return cast<SCEVAddExpr>(this)->getType();
488 case scUDivExpr:
489 return cast<SCEVUDivExpr>(this)->getType();
490 case scUnknown:
491 return cast<SCEVUnknown>(this)->getType();
493 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
494 }
495 llvm_unreachable("Unknown SCEV kind!");
496}
497
499 switch (getSCEVType()) {
500 case scConstant:
501 case scVScale:
502 case scUnknown:
503 return {};
504 case scPtrToAddr:
505 case scPtrToInt:
506 case scTruncate:
507 case scZeroExtend:
508 case scSignExtend:
509 return cast<SCEVCastExpr>(this)->operands();
510 case scAddRecExpr:
511 case scAddExpr:
512 case scMulExpr:
513 case scUMaxExpr:
514 case scSMaxExpr:
515 case scUMinExpr:
516 case scSMinExpr:
518 return cast<SCEVNAryExpr>(this)->operands();
519 case scUDivExpr:
520 return cast<SCEVUDivExpr>(this)->operands();
522 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
523 }
524 llvm_unreachable("Unknown SCEV kind!");
525}
526
527bool SCEV::isZero() const { return match(this, m_scev_Zero()); }
528
529bool SCEV::isOne() const { return match(this, m_scev_One()); }
530
531bool SCEV::isAllOnesValue() const { return match(this, m_scev_AllOnes()); }
532
535 if (!Mul) return false;
536
537 // If there is a constant factor, it will be first.
538 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
539 if (!SC) return false;
540
541 // Return true if the value is negative, this matches things like (-42 * V).
542 return SC->getAPInt().isNegative();
543}
544
547
549 return S->getSCEVType() == scCouldNotCompute;
550}
551
554 ID.AddInteger(scConstant);
555 ID.AddPointer(V);
556 void *IP = nullptr;
557 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
558 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
559 UniqueSCEVs.InsertNode(S, IP);
560 S->computeAndSetCanonical(*this);
561 return S;
562}
563
565 return getConstant(ConstantInt::get(getContext(), Val));
566}
567
568const SCEV *
571 // TODO: Avoid implicit trunc?
572 // See https://github.com/llvm/llvm-project/issues/112510.
573 return getConstant(
574 ConstantInt::get(ITy, V, isSigned, /*ImplicitTrunc=*/true));
575}
576
579 ID.AddInteger(scVScale);
580 ID.AddPointer(Ty);
581 void *IP = nullptr;
582 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
583 return S;
584 SCEV *S = new (SCEVAllocator) SCEVVScale(ID.Intern(SCEVAllocator), Ty);
585 UniqueSCEVs.InsertNode(S, IP);
586 S->computeAndSetCanonical(*this);
587 return S;
588}
589
591 SCEV::NoWrapFlags Flags) {
592 const SCEV *Res = getConstant(Ty, EC.getKnownMinValue());
593 if (EC.isScalable())
594 Res = getMulExpr(Res, getVScale(Ty), Flags);
595 return Res;
596}
597
601
602SCEVPtrToAddrExpr::SCEVPtrToAddrExpr(const FoldingSetNodeIDRef ID,
603 const SCEV *Op, Type *ITy)
604 : SCEVCastExpr(ID, scPtrToAddr, Op, ITy) {
605 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
606 "Must be a non-bit-width-changing pointer-to-integer cast!");
607}
608
609SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, SCEVUse Op,
610 Type *ITy)
611 : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
612 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
613 "Must be a non-bit-width-changing pointer-to-integer cast!");
614}
615
620
621SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
622 Type *ty)
624 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
625 "Cannot truncate non-integer value!");
626}
627
628SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
629 Type *ty)
631 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
632 "Cannot zero extend non-integer value!");
633}
634
635SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
636 Type *ty)
638 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
639 "Cannot sign extend non-integer value!");
640}
641
643 // Clear this SCEVUnknown from various maps.
644 SE->forgetMemoizedResults({this});
645
646 // Remove this SCEVUnknown from the uniquing map.
647 SE->UniqueSCEVs.RemoveNode(this);
648
649 // Release the value.
650 setValPtr(nullptr);
651}
652
653void SCEVUnknown::allUsesReplacedWith(Value *New) {
654 // Clear this SCEVUnknown from various maps.
655 SE->forgetMemoizedResults({this});
656
657 // Remove this SCEVUnknown from the uniquing map.
658 SE->UniqueSCEVs.RemoveNode(this);
659
660 // Replace the value pointer in case someone is still using this SCEVUnknown.
661 setValPtr(New);
662}
663
664//===----------------------------------------------------------------------===//
665// SCEV Utilities
666//===----------------------------------------------------------------------===//
667
668/// Compare the two values \p LV and \p RV in terms of their "complexity" where
669/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
670/// operands in SCEV expressions.
671static int CompareValueComplexity(const LoopInfo *const LI, Value *LV,
672 Value *RV, unsigned Depth) {
674 return 0;
675
676 // Order pointer values after integer values. This helps SCEVExpander form
677 // GEPs.
678 bool LIsPointer = LV->getType()->isPointerTy(),
679 RIsPointer = RV->getType()->isPointerTy();
680 if (LIsPointer != RIsPointer)
681 return (int)LIsPointer - (int)RIsPointer;
682
683 // Compare getValueID values.
684 unsigned LID = LV->getValueID(), RID = RV->getValueID();
685 if (LID != RID)
686 return (int)LID - (int)RID;
687
688 // Sort arguments by their position.
689 if (const auto *LA = dyn_cast<Argument>(LV)) {
690 const auto *RA = cast<Argument>(RV);
691 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
692 return (int)LArgNo - (int)RArgNo;
693 }
694
695 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
696 const auto *RGV = cast<GlobalValue>(RV);
697
698 if (auto L = LGV->getLinkage() - RGV->getLinkage())
699 return L;
700
701 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
702 auto LT = GV->getLinkage();
703 return !(GlobalValue::isPrivateLinkage(LT) ||
705 };
706
707 // Use the names to distinguish the two values, but only if the
708 // names are semantically important.
709 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
710 return LGV->getName().compare(RGV->getName());
711 }
712
713 // For instructions, compare their loop depth, and their operand count. This
714 // is pretty loose.
715 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
716 const auto *RInst = cast<Instruction>(RV);
717
718 // Compare loop depths.
719 const BasicBlock *LParent = LInst->getParent(),
720 *RParent = RInst->getParent();
721 if (LParent != RParent) {
722 unsigned LDepth = LI->getLoopDepth(LParent),
723 RDepth = LI->getLoopDepth(RParent);
724 if (LDepth != RDepth)
725 return (int)LDepth - (int)RDepth;
726 }
727
728 // Compare the number of operands.
729 unsigned LNumOps = LInst->getNumOperands(),
730 RNumOps = RInst->getNumOperands();
731 if (LNumOps != RNumOps)
732 return (int)LNumOps - (int)RNumOps;
733
734 for (unsigned Idx : seq(LNumOps)) {
735 int Result = CompareValueComplexity(LI, LInst->getOperand(Idx),
736 RInst->getOperand(Idx), Depth + 1);
737 if (Result != 0)
738 return Result;
739 }
740 }
741
742 return 0;
743}
744
745// Return negative, zero, or positive, if LHS is less than, equal to, or greater
746// than RHS, respectively. A three-way result allows recursive comparisons to be
747// more efficient.
748// If the max analysis depth was reached, return std::nullopt, assuming we do
749// not know if they are equivalent for sure.
750static std::optional<int>
751CompareSCEVComplexity(const LoopInfo *const LI, const SCEV *LHS,
752 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
753 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
754 if (LHS == RHS)
755 return 0;
756
757 // Primarily, sort the SCEVs by their getSCEVType().
758 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
759 if (LType != RType)
760 return (int)LType - (int)RType;
761
763 return std::nullopt;
764
765 // Aside from the getSCEVType() ordering, the particular ordering
766 // isn't very important except that it's beneficial to be consistent,
767 // so that (a + b) and (b + a) don't end up as different expressions.
768 switch (LType) {
769 case scUnknown: {
770 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
771 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
772
773 int X =
774 CompareValueComplexity(LI, LU->getValue(), RU->getValue(), Depth + 1);
775 return X;
776 }
777
778 case scConstant: {
781
782 // Compare constant values.
783 const APInt &LA = LC->getAPInt();
784 const APInt &RA = RC->getAPInt();
785 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
786 if (LBitWidth != RBitWidth)
787 return (int)LBitWidth - (int)RBitWidth;
788 return LA.ult(RA) ? -1 : 1;
789 }
790
791 case scVScale: {
792 const auto *LTy = cast<IntegerType>(cast<SCEVVScale>(LHS)->getType());
793 const auto *RTy = cast<IntegerType>(cast<SCEVVScale>(RHS)->getType());
794 return LTy->getBitWidth() - RTy->getBitWidth();
795 }
796
797 case scAddRecExpr: {
800
801 // There is always a dominance between two recs that are used by one SCEV,
802 // so we can safely sort recs by loop header dominance. We require such
803 // order in getAddExpr.
804 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
805 if (LLoop != RLoop) {
806 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
807 assert(LHead != RHead && "Two loops share the same header?");
808 if (DT.dominates(LHead, RHead))
809 return 1;
810 assert(DT.dominates(RHead, LHead) &&
811 "No dominance between recurrences used by one SCEV?");
812 return -1;
813 }
814
815 [[fallthrough]];
816 }
817
818 case scTruncate:
819 case scZeroExtend:
820 case scSignExtend:
821 case scPtrToAddr:
822 case scPtrToInt:
823 case scAddExpr:
824 case scMulExpr:
825 case scUDivExpr:
826 case scSMaxExpr:
827 case scUMaxExpr:
828 case scSMinExpr:
829 case scUMinExpr:
831 ArrayRef<SCEVUse> LOps = LHS->operands();
832 ArrayRef<SCEVUse> ROps = RHS->operands();
833
834 // Lexicographically compare n-ary-like expressions.
835 unsigned LNumOps = LOps.size(), RNumOps = ROps.size();
836 if (LNumOps != RNumOps)
837 return (int)LNumOps - (int)RNumOps;
838
839 for (unsigned i = 0; i != LNumOps; ++i) {
840 auto X = CompareSCEVComplexity(LI, LOps[i].getPointer(),
841 ROps[i].getPointer(), DT, Depth + 1);
842 if (X != 0)
843 return X;
844 }
845 return 0;
846 }
847
849 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
850 }
851 llvm_unreachable("Unknown SCEV kind!");
852}
853
854/// Given a list of SCEV objects, order them by their complexity, and group
855/// objects of the same complexity together by value. When this routine is
856/// finished, we know that any duplicates in the vector are consecutive and that
857/// complexity is monotonically increasing.
858///
859/// Note that we go take special precautions to ensure that we get deterministic
860/// results from this routine. In other words, we don't want the results of
861/// this to depend on where the addresses of various SCEV objects happened to
862/// land in memory.
864 DominatorTree &DT) {
865 if (Ops.size() < 2) return; // Noop
866
867 // Whether LHS has provably less complexity than RHS.
868 auto IsLessComplex = [&](SCEVUse LHS, SCEVUse RHS) {
869 auto Complexity = CompareSCEVComplexity(LI, LHS, RHS, DT);
870 return Complexity && *Complexity < 0;
871 };
872 if (Ops.size() == 2) {
873 // This is the common case, which also happens to be trivially simple.
874 // Special case it.
875 SCEVUse &LHS = Ops[0], &RHS = Ops[1];
876 if (IsLessComplex(RHS, LHS))
877 std::swap(LHS, RHS);
878 return;
879 }
880
881 // Do the rough sort by complexity.
883 Ops, [&](SCEVUse LHS, SCEVUse RHS) { return IsLessComplex(LHS, RHS); });
884
885 // Now that we are sorted by complexity, group elements of the same
886 // complexity. Note that this is, at worst, N^2, but the vector is likely to
887 // be extremely short in practice. Note that we take this approach because we
888 // do not want to depend on the addresses of the objects we are grouping.
889 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
890 const SCEV *S = Ops[i];
891 unsigned Complexity = S->getSCEVType();
892
893 // If there are any objects of the same complexity and same value as this
894 // one, group them.
895 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
896 if (Ops[j] == S) { // Found a duplicate.
897 // Move it to immediately after i'th element.
898 std::swap(Ops[i+1], Ops[j]);
899 ++i; // no need to rescan it.
900 if (i == e-2) return; // Done!
901 }
902 }
903 }
904}
905
906/// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
907/// least HugeExprThreshold nodes).
909 return any_of(Ops, [](const SCEV *S) {
911 });
912}
913
914/// Performs a number of common optimizations on the passed \p Ops. If the
915/// whole expression reduces down to a single operand, it will be returned.
916///
917/// The following optimizations are performed:
918/// * Fold constants using the \p Fold function.
919/// * Remove identity constants satisfying \p IsIdentity.
920/// * If a constant satisfies \p IsAbsorber, return it.
921/// * Sort operands by complexity.
922template <typename FoldT, typename IsIdentityT, typename IsAbsorberT>
923static const SCEV *
925 SmallVectorImpl<SCEVUse> &Ops, FoldT Fold,
926 IsIdentityT IsIdentity, IsAbsorberT IsAbsorber) {
927 const SCEVConstant *Folded = nullptr;
928 for (unsigned Idx = 0; Idx < Ops.size();) {
929 const SCEV *Op = Ops[Idx];
930 if (const auto *C = dyn_cast<SCEVConstant>(Op)) {
931 if (!Folded)
932 Folded = C;
933 else
934 Folded = cast<SCEVConstant>(
935 SE.getConstant(Fold(Folded->getAPInt(), C->getAPInt())));
936 Ops.erase(Ops.begin() + Idx);
937 continue;
938 }
939 ++Idx;
940 }
941
942 if (Ops.empty()) {
943 assert(Folded && "Must have folded value");
944 return Folded;
945 }
946
947 if (Folded && IsAbsorber(Folded->getAPInt()))
948 return Folded;
949
950 GroupByComplexity(Ops, &LI, DT);
951 if (Folded && !IsIdentity(Folded->getAPInt()))
952 Ops.insert(Ops.begin(), Folded);
953
954 return Ops.size() == 1 ? Ops[0] : nullptr;
955}
956
957//===----------------------------------------------------------------------===//
958// Simple SCEV method implementations
959//===----------------------------------------------------------------------===//
960
961/// Compute BC(It, K). The result has width W. Assume, K > 0.
962static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
963 ScalarEvolution &SE,
964 Type *ResultTy) {
965 // Handle the simplest case efficiently.
966 if (K == 1)
967 return SE.getTruncateOrZeroExtend(It, ResultTy);
968
969 // We are using the following formula for BC(It, K):
970 //
971 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
972 //
973 // Suppose, W is the bitwidth of the return value. We must be prepared for
974 // overflow. Hence, we must assure that the result of our computation is
975 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
976 // safe in modular arithmetic.
977 //
978 // However, this code doesn't use exactly that formula; the formula it uses
979 // is something like the following, where T is the number of factors of 2 in
980 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
981 // exponentiation:
982 //
983 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
984 //
985 // This formula is trivially equivalent to the previous formula. However,
986 // this formula can be implemented much more efficiently. The trick is that
987 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
988 // arithmetic. To do exact division in modular arithmetic, all we have
989 // to do is multiply by the inverse. Therefore, this step can be done at
990 // width W.
991 //
992 // The next issue is how to safely do the division by 2^T. The way this
993 // is done is by doing the multiplication step at a width of at least W + T
994 // bits. This way, the bottom W+T bits of the product are accurate. Then,
995 // when we perform the division by 2^T (which is equivalent to a right shift
996 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
997 // truncated out after the division by 2^T.
998 //
999 // In comparison to just directly using the first formula, this technique
1000 // is much more efficient; using the first formula requires W * K bits,
1001 // but this formula less than W + K bits. Also, the first formula requires
1002 // a division step, whereas this formula only requires multiplies and shifts.
1003 //
1004 // It doesn't matter whether the subtraction step is done in the calculation
1005 // width or the input iteration count's width; if the subtraction overflows,
1006 // the result must be zero anyway. We prefer here to do it in the width of
1007 // the induction variable because it helps a lot for certain cases; CodeGen
1008 // isn't smart enough to ignore the overflow, which leads to much less
1009 // efficient code if the width of the subtraction is wider than the native
1010 // register width.
1011 //
1012 // (It's possible to not widen at all by pulling out factors of 2 before
1013 // the multiplication; for example, K=2 can be calculated as
1014 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1015 // extra arithmetic, so it's not an obvious win, and it gets
1016 // much more complicated for K > 3.)
1017
1018 // Protection from insane SCEVs; this bound is conservative,
1019 // but it probably doesn't matter.
1020 if (K > 1000)
1021 return SE.getCouldNotCompute();
1022
1023 unsigned W = SE.getTypeSizeInBits(ResultTy);
1024
1025 // Calculate K! / 2^T and T; we divide out the factors of two before
1026 // multiplying for calculating K! / 2^T to avoid overflow.
1027 // Other overflow doesn't matter because we only care about the bottom
1028 // W bits of the result.
1029 APInt OddFactorial(W, 1);
1030 unsigned T = 1;
1031 for (unsigned i = 3; i <= K; ++i) {
1032 unsigned TwoFactors = countr_zero(i);
1033 T += TwoFactors;
1034 OddFactorial *= (i >> TwoFactors);
1035 }
1036
1037 // We need at least W + T bits for the multiplication step
1038 unsigned CalculationBits = W + T;
1039
1040 // Calculate 2^T, at width T+W.
1041 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1042
1043 // Calculate the multiplicative inverse of K! / 2^T;
1044 // this multiplication factor will perform the exact division by
1045 // K! / 2^T.
1046 APInt MultiplyFactor = OddFactorial.multiplicativeInverse();
1047
1048 // Calculate the product, at width T+W
1049 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1050 CalculationBits);
1051 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1052 for (unsigned i = 1; i != K; ++i) {
1053 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1054 Dividend = SE.getMulExpr(Dividend,
1055 SE.getTruncateOrZeroExtend(S, CalculationTy));
1056 }
1057
1058 // Divide by 2^T
1059 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1060
1061 // Truncate the result, and divide by K! / 2^T.
1062
1063 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1064 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1065}
1066
1067/// Return the value of this chain of recurrences at the specified iteration
1068/// number. We can evaluate this recurrence by multiplying each element in the
1069/// chain by the binomial coefficient corresponding to it. In other words, we
1070/// can evaluate {A,+,B,+,C,+,D} as:
1071///
1072/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1073///
1074/// where BC(It, k) stands for binomial coefficient.
1076 ScalarEvolution &SE) const {
1077 return evaluateAtIteration(operands(), It, SE);
1078}
1079
1081 const SCEV *It,
1082 ScalarEvolution &SE) {
1083 assert(Operands.size() > 0);
1084 const SCEV *Result = Operands[0].getPointer();
1085 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1086 // The computation is correct in the face of overflow provided that the
1087 // multiplication is performed _after_ the evaluation of the binomial
1088 // coefficient.
1089 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
1090 if (isa<SCEVCouldNotCompute>(Coeff))
1091 return Coeff;
1092
1093 Result =
1094 SE.getAddExpr(Result, SE.getMulExpr(Operands[i].getPointer(), Coeff));
1095 }
1096 return Result;
1097}
1098
1099//===----------------------------------------------------------------------===//
1100// SCEV Expression folder implementations
1101//===----------------------------------------------------------------------===//
1102
1103/// The SCEVCastSinkingRewriter takes a scalar evolution expression,
1104/// which computes a pointer-typed value, and rewrites the whole expression
1105/// tree so that *all* the computations are done on integers, and the only
1106/// pointer-typed operands in the expression are SCEVUnknown.
1107/// The CreatePtrCast callback is invoked to create the actual conversion
1108/// (ptrtoint or ptrtoaddr) at the SCEVUnknown leaves.
1110 : public SCEVRewriteVisitor<SCEVCastSinkingRewriter> {
1112 using ConversionFn = function_ref<const SCEV *(const SCEVUnknown *)>;
1113 Type *TargetTy;
1114 ConversionFn CreatePtrCast;
1115
1116public:
1118 ConversionFn CreatePtrCast)
1119 : Base(SE), TargetTy(TargetTy), CreatePtrCast(std::move(CreatePtrCast)) {}
1120
1121 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
1122 Type *TargetTy, ConversionFn CreatePtrCast) {
1123 SCEVCastSinkingRewriter Rewriter(SE, TargetTy, std::move(CreatePtrCast));
1124 return Rewriter.visit(Scev);
1125 }
1126
1127 const SCEV *visit(const SCEV *S) {
1128 Type *STy = S->getType();
1129 // If the expression is not pointer-typed, just keep it as-is.
1130 if (!STy->isPointerTy())
1131 return S;
1132 // Else, recursively sink the cast down into it.
1133 return Base::visit(S);
1134 }
1135
1136 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1137 // Preserve wrap flags on rewritten SCEVAddExpr, which the default
1138 // implementation drops.
1139 SmallVector<SCEVUse, 2> Operands;
1140 bool Changed = false;
1141 for (SCEVUse Op : Expr->operands()) {
1142 Operands.push_back(visit(Op.getPointer()));
1143 Changed |= Op.getPointer() != Operands.back();
1144 }
1145 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1146 }
1147
1148 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1149 SmallVector<SCEVUse, 2> Operands;
1150 bool Changed = false;
1151 for (SCEVUse Op : Expr->operands()) {
1152 Operands.push_back(visit(Op.getPointer()));
1153 Changed |= Op.getPointer() != Operands.back();
1154 }
1155 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1156 }
1157
1158 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1159 assert(Expr->getType()->isPointerTy() &&
1160 "Should only reach pointer-typed SCEVUnknown's.");
1161 // Perform some basic constant folding. If the operand of the cast is a
1162 // null pointer, don't create a cast SCEV expression (that will be left
1163 // as-is), but produce a zero constant.
1165 return SE.getZero(TargetTy);
1166 return CreatePtrCast(Expr);
1167 }
1168};
1169
1171 assert(Op->getType()->isPointerTy() && "Op must be a pointer");
1172
1173 // It isn't legal for optimizations to construct new ptrtoint expressions
1174 // for non-integral pointers.
1175 if (getDataLayout().isNonIntegralPointerType(Op->getType()))
1176 return getCouldNotCompute();
1177
1178 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1179
1180 // We can only trivially model ptrtoint if SCEV's effective (integer) type
1181 // is sufficiently wide to represent all possible pointer values.
1182 // We could theoretically teach SCEV to truncate wider pointers, but
1183 // that isn't implemented for now.
1186 return getCouldNotCompute();
1187
1188 // Use the rewriter to sink the cast down to SCEVUnknown leaves.
1190 Op, *this, IntPtrTy, [this, IntPtrTy](const SCEVUnknown *U) {
1192 ID.AddInteger(scPtrToInt);
1193 ID.AddPointer(U);
1194 void *IP = nullptr;
1195 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1196 return S;
1197 SCEV *S = new (SCEVAllocator)
1198 SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), U, IntPtrTy);
1199 UniqueSCEVs.InsertNode(S, IP);
1200 S->computeAndSetCanonical(*this);
1201 registerUser(S, U);
1202 return static_cast<const SCEV *>(S);
1203 });
1204 assert(IntOp->getType()->isIntegerTy() &&
1205 "We must have succeeded in sinking the cast, "
1206 "and ending up with an integer-typed expression!");
1207 return IntOp;
1208}
1209
1211 assert(Op->getType()->isPointerTy() && "Op must be a pointer");
1212
1213 // Treat pointers with unstable representation conservatively, since the
1214 // address bits may change.
1215 if (DL.hasUnstableRepresentation(Op->getType()))
1216 return getCouldNotCompute();
1217
1218 Type *Ty = DL.getAddressType(Op->getType());
1219
1220 // Use the rewriter to sink the cast down to SCEVUnknown leaves.
1221 // The rewriter handles null pointer constant folding.
1223 Op, *this, Ty, [this, Ty](const SCEVUnknown *U) {
1225 ID.AddInteger(scPtrToAddr);
1226 ID.AddPointer(U);
1227 ID.AddPointer(Ty);
1228 void *IP = nullptr;
1229 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1230 return S;
1231 SCEV *S = new (SCEVAllocator)
1232 SCEVPtrToAddrExpr(ID.Intern(SCEVAllocator), U, Ty);
1233 UniqueSCEVs.InsertNode(S, IP);
1234 S->computeAndSetCanonical(*this);
1235 registerUser(S, U);
1236 return static_cast<const SCEV *>(S);
1237 });
1238 assert(IntOp->getType()->isIntegerTy() &&
1239 "We must have succeeded in sinking the cast, "
1240 "and ending up with an integer-typed expression!");
1241 return IntOp;
1242}
1243
1245 assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1246
1247 const SCEV *IntOp = getLosslessPtrToIntExpr(Op);
1248 if (isa<SCEVCouldNotCompute>(IntOp))
1249 return IntOp;
1250
1251 return getTruncateOrZeroExtend(IntOp, Ty);
1252}
1253
1255 unsigned Depth) {
1256 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1257 "This is not a truncating conversion!");
1258 assert(isSCEVable(Ty) &&
1259 "This is not a conversion to a SCEVable type!");
1260 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1261 Ty = getEffectiveSCEVType(Ty);
1262
1264 ID.AddInteger(scTruncate);
1265 ID.AddPointer(Op);
1266 ID.AddPointer(Ty);
1267 void *IP = nullptr;
1268 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1269
1270 // Fold if the operand is constant.
1271 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1272 return getConstant(
1273 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1274
1275 // trunc(trunc(x)) --> trunc(x)
1277 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1278
1279 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1281 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1282
1283 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1285 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1286
1287 if (Depth > MaxCastDepth) {
1288 SCEV *S =
1289 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1290 UniqueSCEVs.InsertNode(S, IP);
1291 S->computeAndSetCanonical(*this);
1292 registerUser(S, Op);
1293 return S;
1294 }
1295
1296 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1297 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1298 // if after transforming we have at most one truncate, not counting truncates
1299 // that replace other casts.
1301 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1302 SmallVector<SCEVUse, 4> Operands;
1303 unsigned numTruncs = 0;
1304 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1305 ++i) {
1306 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1307 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1309 numTruncs++;
1310 Operands.push_back(S);
1311 }
1312 if (numTruncs < 2) {
1313 if (isa<SCEVAddExpr>(Op))
1314 return getAddExpr(Operands);
1315 if (isa<SCEVMulExpr>(Op))
1316 return getMulExpr(Operands);
1317 llvm_unreachable("Unexpected SCEV type for Op.");
1318 }
1319 // Although we checked in the beginning that ID is not in the cache, it is
1320 // possible that during recursion and different modification ID was inserted
1321 // into the cache. So if we find it, just return it.
1322 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1323 return S;
1324 }
1325
1326 // If the input value is a chrec scev, truncate the chrec's operands.
1327 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1328 SmallVector<SCEVUse, 4> Operands;
1329 for (const SCEV *Op : AddRec->operands())
1330 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1331 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1332 }
1333
1334 // Return zero if truncating to known zeros.
1335 uint32_t MinTrailingZeros = getMinTrailingZeros(Op);
1336 if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1337 return getZero(Ty);
1338
1339 // The cast wasn't folded; create an explicit cast node. We can reuse
1340 // the existing insert position since if we get here, we won't have
1341 // made any changes which would invalidate it.
1342 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1343 Op, Ty);
1344 UniqueSCEVs.InsertNode(S, IP);
1345 S->computeAndSetCanonical(*this);
1346 registerUser(S, Op);
1347 return S;
1348}
1349
1350// Get the limit of a recurrence such that incrementing by Step cannot cause
1351// signed overflow as long as the value of the recurrence within the
1352// loop does not exceed this limit before incrementing.
1353static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1354 ICmpInst::Predicate *Pred,
1355 ScalarEvolution *SE) {
1356 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1357 if (SE->isKnownPositive(Step)) {
1358 *Pred = ICmpInst::ICMP_SLT;
1360 SE->getSignedRangeMax(Step));
1361 }
1362 if (SE->isKnownNegative(Step)) {
1363 *Pred = ICmpInst::ICMP_SGT;
1365 SE->getSignedRangeMin(Step));
1366 }
1367 return nullptr;
1368}
1369
1370// Get the limit of a recurrence such that incrementing by Step cannot cause
1371// unsigned overflow as long as the value of the recurrence within the loop does
1372// not exceed this limit before incrementing.
1374 ICmpInst::Predicate *Pred,
1375 ScalarEvolution *SE) {
1376 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1377 *Pred = ICmpInst::ICMP_ULT;
1378
1380 SE->getUnsignedRangeMax(Step));
1381}
1382
1383namespace {
1384
1385struct ExtendOpTraitsBase {
1386 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1387 unsigned);
1388};
1389
1390// Used to make code generic over signed and unsigned overflow.
1391template <typename ExtendOp> struct ExtendOpTraits {
1392 // Members present:
1393 //
1394 // static const SCEV::NoWrapFlags WrapType;
1395 //
1396 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1397 //
1398 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1399 // ICmpInst::Predicate *Pred,
1400 // ScalarEvolution *SE);
1401};
1402
1403template <>
1404struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1405 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1406
1407 static const GetExtendExprTy GetExtendExpr;
1408
1409 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1410 ICmpInst::Predicate *Pred,
1411 ScalarEvolution *SE) {
1412 return getSignedOverflowLimitForStep(Step, Pred, SE);
1413 }
1414};
1415
1416const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1418
1419template <>
1420struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1421 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1422
1423 static const GetExtendExprTy GetExtendExpr;
1424
1425 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1426 ICmpInst::Predicate *Pred,
1427 ScalarEvolution *SE) {
1428 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1429 }
1430};
1431
1432const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1434
1435} // end anonymous namespace
1436
1437// The recurrence AR has been shown to have no signed/unsigned wrap or something
1438// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1439// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1440// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1441// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1442// expression "Step + sext/zext(PreIncAR)" is congruent with
1443// "sext/zext(PostIncAR)"
1444template <typename ExtendOpTy>
1445static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1446 ScalarEvolution *SE, unsigned Depth) {
1447 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1448 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1449
1450 const Loop *L = AR->getLoop();
1451 const SCEV *Start = AR->getStart();
1452 const SCEV *Step = AR->getStepRecurrence(*SE);
1453
1454 // Check for a simple looking step prior to loop entry.
1455 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1456 if (!SA)
1457 return nullptr;
1458
1459 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1460 // subtraction is expensive. For this purpose, perform a quick and dirty
1461 // difference, by checking for Step in the operand list. Note, that
1462 // SA might have repeated ops, like %a + %a + ..., so only remove one.
1463 SmallVector<SCEVUse, 4> DiffOps(SA->operands());
1464 for (auto It = DiffOps.begin(); It != DiffOps.end(); ++It)
1465 if (*It == Step) {
1466 DiffOps.erase(It);
1467 break;
1468 }
1469
1470 if (DiffOps.size() == SA->getNumOperands())
1471 return nullptr;
1472
1473 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1474 // `Step`:
1475
1476 // 1. NSW/NUW flags on the step increment.
1477 auto PreStartFlags =
1479 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1481 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1482
1483 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1484 // "S+X does not sign/unsign-overflow".
1485 //
1486
1487 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1488 if (PreAR && any(PreAR->getNoWrapFlags(WrapType)) &&
1489 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1490 return PreStart;
1491
1492 // 2. Direct overflow check on the step operation's expression.
1493 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1494 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1495 const SCEV *OperandExtendedStart =
1496 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1497 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1498 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1499 if (PreAR && any(AR->getNoWrapFlags(WrapType))) {
1500 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1501 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1502 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1503 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1504 }
1505 return PreStart;
1506 }
1507
1508 // 3. Loop precondition.
1510 const SCEV *OverflowLimit =
1511 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1512
1513 if (OverflowLimit &&
1514 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1515 return PreStart;
1516
1517 return nullptr;
1518}
1519
1520// Get the normalized zero or sign extended expression for this AddRec's Start.
1521template <typename ExtendOpTy>
1522static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1523 ScalarEvolution *SE,
1524 unsigned Depth) {
1525 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1526
1527 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1528 if (!PreStart)
1529 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1530
1531 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1532 Depth),
1533 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1534}
1535
1536// Try to prove away overflow by looking at "nearby" add recurrences. A
1537// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1538// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1539//
1540// Formally:
1541//
1542// {S,+,X} == {S-T,+,X} + T
1543// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1544//
1545// If ({S-T,+,X} + T) does not overflow ... (1)
1546//
1547// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1548//
1549// If {S-T,+,X} does not overflow ... (2)
1550//
1551// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1552// == {Ext(S-T)+Ext(T),+,Ext(X)}
1553//
1554// If (S-T)+T does not overflow ... (3)
1555//
1556// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1557// == {Ext(S),+,Ext(X)} == LHS
1558//
1559// Thus, if (1), (2) and (3) are true for some T, then
1560// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1561//
1562// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1563// does not overflow" restricted to the 0th iteration. Therefore we only need
1564// to check for (1) and (2).
1565//
1566// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1567// is `Delta` (defined below).
1568template <typename ExtendOpTy>
1569bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1570 const SCEV *Step,
1571 const Loop *L) {
1572 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1573
1574 // We restrict `Start` to a constant to prevent SCEV from spending too much
1575 // time here. It is correct (but more expensive) to continue with a
1576 // non-constant `Start` and do a general SCEV subtraction to compute
1577 // `PreStart` below.
1578 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1579 if (!StartC)
1580 return false;
1581
1582 APInt StartAI = StartC->getAPInt();
1583
1584 for (unsigned Delta : {-2, -1, 1, 2}) {
1585 const SCEV *PreStart = getConstant(StartAI - Delta);
1586
1587 FoldingSetNodeID ID;
1588 ID.AddInteger(scAddRecExpr);
1589 ID.AddPointer(PreStart);
1590 ID.AddPointer(Step);
1591 ID.AddPointer(L);
1592 void *IP = nullptr;
1593 const auto *PreAR =
1594 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1595
1596 // Give up if we don't already have the add recurrence we need because
1597 // actually constructing an add recurrence is relatively expensive.
1598 if (PreAR && any(PreAR->getNoWrapFlags(WrapType))) { // proves (2)
1599 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1601 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1602 DeltaS, &Pred, this);
1603 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1604 return true;
1605 }
1606 }
1607
1608 return false;
1609}
1610
1611// Finds an integer D for an expression (C + x + y + ...) such that the top
1612// level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1613// unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1614// maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1615// the (C + x + y + ...) expression is \p WholeAddExpr.
1617 const SCEVConstant *ConstantTerm,
1618 const SCEVAddExpr *WholeAddExpr) {
1619 const APInt &C = ConstantTerm->getAPInt();
1620 const unsigned BitWidth = C.getBitWidth();
1621 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1622 uint32_t TZ = BitWidth;
1623 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1624 TZ = std::min(TZ, SE.getMinTrailingZeros(WholeAddExpr->getOperand(I)));
1625 if (TZ) {
1626 // Set D to be as many least significant bits of C as possible while still
1627 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1628 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1629 }
1630 return APInt(BitWidth, 0);
1631}
1632
1633// Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1634// level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1635// number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1636// ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1638 const APInt &ConstantStart,
1639 const SCEV *Step) {
1640 const unsigned BitWidth = ConstantStart.getBitWidth();
1641 const uint32_t TZ = SE.getMinTrailingZeros(Step);
1642 if (TZ)
1643 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1644 : ConstantStart;
1645 return APInt(BitWidth, 0);
1646}
1647
1649 const ScalarEvolution::FoldID &ID, const SCEV *S,
1652 &FoldCacheUser) {
1653 auto I = FoldCache.insert({ID, S});
1654 if (!I.second) {
1655 // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1656 // entry.
1657 auto &UserIDs = FoldCacheUser[I.first->second];
1658 assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
1659 for (unsigned I = 0; I != UserIDs.size(); ++I)
1660 if (UserIDs[I] == ID) {
1661 std::swap(UserIDs[I], UserIDs.back());
1662 break;
1663 }
1664 UserIDs.pop_back();
1665 I.first->second = S;
1666 }
1667 FoldCacheUser[S].push_back(ID);
1668}
1669
1670const SCEV *
1672 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1673 "This is not an extending conversion!");
1674 assert(isSCEVable(Ty) &&
1675 "This is not a conversion to a SCEVable type!");
1676 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1677 Ty = getEffectiveSCEVType(Ty);
1678
1679 FoldID ID(scZeroExtend, Op, Ty);
1680 if (const SCEV *S = FoldCache.lookup(ID))
1681 return S;
1682
1683 const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1685 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1686 return S;
1687}
1688
1690 unsigned Depth) {
1691 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1692 "This is not an extending conversion!");
1693 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1694 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1695
1696 // Fold if the operand is constant.
1697 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1698 return getConstant(SC->getAPInt().zext(getTypeSizeInBits(Ty)));
1699
1700 // zext(zext(x)) --> zext(x)
1702 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1703
1704 // If the operand is an affine AddRec with the no-unsigned-wrap flag, the
1705 // zero-extension distributes over the recurrence.
1706 if (Depth <= MaxCastDepth)
1707 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(Op))
1708 if (AR->isAffine() && AR->hasNoUnsignedWrap()) {
1709 const SCEV *Start =
1711 const SCEV *Step =
1712 getZeroExtendExpr(AR->getStepRecurrence(*this), Ty, Depth + 1);
1713 return getAddRecExpr(Start, Step, AR->getLoop(), AR->getNoWrapFlags());
1714 }
1715
1716 // Before doing any expensive analysis, check to see if we've already
1717 // computed a SCEV for this Op and Ty.
1719 ID.AddInteger(scZeroExtend);
1720 ID.AddPointer(Op);
1721 ID.AddPointer(Ty);
1722 void *IP = nullptr;
1723 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1724 if (Depth > MaxCastDepth) {
1725 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1726 Op, Ty);
1727 UniqueSCEVs.InsertNode(S, IP);
1728 S->computeAndSetCanonical(*this);
1729 registerUser(S, Op);
1730 return S;
1731 }
1732
1733 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1735 // It's possible the bits taken off by the truncate were all zero bits. If
1736 // so, we should be able to simplify this further.
1737 const SCEV *X = ST->getOperand();
1739 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1740 unsigned NewBits = getTypeSizeInBits(Ty);
1741 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1742 CR.zextOrTrunc(NewBits)))
1743 return getTruncateOrZeroExtend(X, Ty, Depth);
1744 }
1745
1746 // If the input value is a chrec scev, and we can prove that the value
1747 // did not overflow the old, smaller, value, we can zero extend all of the
1748 // operands (often constants). This allows analysis of something like
1749 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1751 if (AR->isAffine()) {
1752 const SCEV *Start = AR->getStart();
1753 const SCEV *Step = AR->getStepRecurrence(*this);
1754 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1755 const Loop *L = AR->getLoop();
1756
1757 // The no-unsigned-wrap case is handled before the uniquing lookup above.
1758
1759 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1760 // Note that this serves two purposes: It filters out loops that are
1761 // simply not analyzable, and it covers the case where this code is
1762 // being called from within backedge-taken count analysis, such that
1763 // attempting to ask for the backedge-taken count would likely result
1764 // in infinite recursion. In the later case, the analysis code will
1765 // cope with a conservative value, and it will take care to purge
1766 // that value once it has finished.
1767 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1768 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1769 // Manually compute the final value for AR, checking for overflow.
1770
1771 // Check whether the backedge-taken count can be losslessly casted to
1772 // the addrec's type. The count is always unsigned.
1773 const SCEV *CastedMaxBECount =
1774 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1775 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1776 CastedMaxBECount, MaxBECount->getType(), Depth);
1777 if (MaxBECount == RecastedMaxBECount) {
1778 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1779 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1780 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1782 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1784 Depth + 1),
1785 WideTy, Depth + 1);
1786 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1787 const SCEV *WideMaxBECount =
1788 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1789 const SCEV *OperandExtendedAdd =
1790 getAddExpr(WideStart,
1791 getMulExpr(WideMaxBECount,
1792 getZeroExtendExpr(Step, WideTy, Depth + 1),
1795 if (ZAdd == OperandExtendedAdd) {
1796 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1797 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1798 // Return the expression with the addrec on the outside.
1799 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1800 Depth + 1);
1801 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1802 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1803 }
1804 // Similar to above, only this time treat the step value as signed.
1805 // This covers loops that count down.
1806 OperandExtendedAdd =
1807 getAddExpr(WideStart,
1808 getMulExpr(WideMaxBECount,
1809 getSignExtendExpr(Step, WideTy, Depth + 1),
1812 if (ZAdd == OperandExtendedAdd) {
1813 // Cache knowledge of AR NW, which is propagated to this AddRec.
1814 // Negative step causes unsigned wrap, but it still can't self-wrap.
1815 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1816 // Return the expression with the addrec on the outside.
1817 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1818 Depth + 1);
1819 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1820 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1821 }
1822 }
1823 }
1824
1825 // Normally, in the cases we can prove no-overflow via a
1826 // backedge guarding condition, we can also compute a backedge
1827 // taken count for the loop. The exceptions are assumptions and
1828 // guards present in the loop -- SCEV is not great at exploiting
1829 // these to compute max backedge taken counts, but can still use
1830 // these to prove lack of overflow. Use this fact to avoid
1831 // doing extra work that may not pay off.
1832 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1833 !AC.assumptions().empty()) {
1834
1835 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1836 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1837 if (AR->hasNoUnsignedWrap()) {
1838 // Same as nuw case above - duplicated here to avoid a compile time
1839 // issue. It's not clear that the order of checks does matter, but
1840 // it's one of two issue possible causes for a change which was
1841 // reverted. Be conservative for the moment.
1842 Start =
1844 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1845 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1846 }
1847
1848 // For a negative step, we can extend the operands iff doing so only
1849 // traverses values in the range zext([0,UINT_MAX]).
1850 if (isKnownNegative(Step)) {
1852 getSignedRangeMin(Step));
1855 // Cache knowledge of AR NW, which is propagated to this
1856 // AddRec. Negative step causes unsigned wrap, but it
1857 // still can't self-wrap.
1858 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1859 // Return the expression with the addrec on the outside.
1860 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1861 Depth + 1);
1862 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1863 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1864 }
1865 }
1866 }
1867
1868 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1869 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1870 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1871 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1872 const APInt &C = SC->getAPInt();
1873 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1874 if (D != 0) {
1875 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1876 const SCEV *SResidual =
1877 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1878 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1879 return getAddExpr(SZExtD, SZExtR, SCEV::FlagNSW | SCEV::FlagNUW,
1880 Depth + 1);
1881 }
1882 }
1883
1884 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1885 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1886 Start =
1888 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1889 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1890 }
1891 }
1892
1893 // zext(A % B) --> zext(A) % zext(B)
1894 {
1895 const SCEV *LHS;
1896 const SCEV *RHS;
1897 if (match(Op, m_scev_URem(m_SCEV(LHS), m_SCEV(RHS), *this)))
1898 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1899 getZeroExtendExpr(RHS, Ty, Depth + 1));
1900 }
1901
1902 // zext(A / B) --> zext(A) / zext(B).
1903 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1904 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1905 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1906
1907 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1908 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1909 if (SA->hasNoUnsignedWrap()) {
1910 // If the addition does not unsign overflow then we can, by definition,
1911 // commute the zero extension with the addition operation.
1913 for (SCEVUse Op : SA->operands())
1914 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1915 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1916 }
1917
1918 const APInt *C, *C2;
1919 // zext (C + A)<nsw> -> (sext(C) + sext(A))<nsw> if zext (C + A)<nsw> >=s 0.
1920 // Currently the non-negative check is done manually, as isKnownNonNegative
1921 // is too expensive.
1922 if (SA->hasNoSignedWrap() &&
1924 m_scev_SMax(m_scev_APInt(C2), m_SCEV()))) &&
1925 C->isNegative() && !C->isMinSignedValue() && C2->sge(C->abs())) {
1926 assert(isKnownNonNegative(SA) && "incorrectly determined non-negative");
1927 return getAddExpr(getSignExtendExpr(SA->getOperand(0), Ty, Depth + 1),
1928 getSignExtendExpr(SA->getOperand(1), Ty, Depth + 1),
1929 SCEV::FlagNSW, Depth + 1);
1930 }
1931
1932 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1933 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1934 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1935 //
1936 // Often address arithmetics contain expressions like
1937 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1938 // This transformation is useful while proving that such expressions are
1939 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1940 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1941 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1942 if (D != 0) {
1943 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1944 const SCEV *SResidual =
1946 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1947 return getAddExpr(SZExtD, SZExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1948 Depth + 1);
1949 }
1950 }
1951 }
1952
1953 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1954 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1955 if (SM->hasNoUnsignedWrap()) {
1956 // If the multiply does not unsign overflow then we can, by definition,
1957 // commute the zero extension with the multiply operation.
1959 for (SCEVUse Op : SM->operands())
1960 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1961 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1962 }
1963
1964 // zext(2^K * (trunc X to iN)) to iM ->
1965 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1966 //
1967 // Proof:
1968 //
1969 // zext(2^K * (trunc X to iN)) to iM
1970 // = zext((trunc X to iN) << K) to iM
1971 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1972 // (because shl removes the top K bits)
1973 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1974 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1975 //
1976 const APInt *C;
1977 const SCEV *TruncRHS;
1978 if (match(SM,
1979 m_scev_Mul(m_scev_APInt(C), m_scev_Trunc(m_SCEV(TruncRHS)))) &&
1980 C->isPowerOf2()) {
1981 int NewTruncBits =
1982 getTypeSizeInBits(SM->getOperand(1)->getType()) - C->logBase2();
1983 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1984 return getMulExpr(
1985 getZeroExtendExpr(SM->getOperand(0), Ty),
1986 getZeroExtendExpr(getTruncateExpr(TruncRHS, NewTruncTy), Ty),
1987 SCEV::FlagNUW, Depth + 1);
1988 }
1989 }
1990
1991 // zext(umin(x, y)) -> umin(zext(x), zext(y))
1992 // zext(umax(x, y)) -> umax(zext(x), zext(y))
1995 SmallVector<SCEVUse, 4> Operands;
1996 for (SCEVUse Operand : MinMax->operands())
1997 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1999 return getUMinExpr(Operands);
2000 return getUMaxExpr(Operands);
2001 }
2002
2003 // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
2005 assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!");
2006 SmallVector<SCEVUse, 4> Operands;
2007 for (SCEVUse Operand : MinMax->operands())
2008 Operands.push_back(getZeroExtendExpr(Operand, Ty));
2009 return getUMinExpr(Operands, /*Sequential*/ true);
2010 }
2011
2012 // The cast wasn't folded; create an explicit cast node.
2013 // Recompute the insert position, as it may have been invalidated.
2014 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2015 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
2016 Op, Ty);
2017 UniqueSCEVs.InsertNode(S, IP);
2018 S->computeAndSetCanonical(*this);
2019 registerUser(S, Op);
2020 return S;
2021}
2022
2023const SCEV *
2025 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2026 "This is not an extending conversion!");
2027 assert(isSCEVable(Ty) &&
2028 "This is not a conversion to a SCEVable type!");
2029 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
2030 Ty = getEffectiveSCEVType(Ty);
2031
2032 FoldID ID(scSignExtend, Op, Ty);
2033 if (const SCEV *S = FoldCache.lookup(ID))
2034 return S;
2035
2036 const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
2038 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
2039 return S;
2040}
2041
2043 unsigned Depth) {
2044 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2045 "This is not an extending conversion!");
2046 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
2047 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
2048 Ty = getEffectiveSCEVType(Ty);
2049
2050 // Fold if the operand is constant.
2051 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2052 return getConstant(SC->getAPInt().sext(getTypeSizeInBits(Ty)));
2053
2054 // sext(sext(x)) --> sext(x)
2056 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
2057
2058 // sext(zext(x)) --> zext(x)
2060 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
2061
2062 // If the operand is an affine AddRec with the no-signed-wrap flag, the
2063 // sign-extension distributes over the recurrence.
2064 if (Depth <= MaxCastDepth)
2065 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(Op))
2066 if (AR->isAffine() && AR->hasNoSignedWrap()) {
2067 const SCEV *Start =
2069 const SCEV *Step =
2070 getSignExtendExpr(AR->getStepRecurrence(*this), Ty, Depth + 1);
2071 return getAddRecExpr(Start, Step, AR->getLoop(), SCEV::FlagNSW);
2072 }
2073
2074 // Before doing any expensive analysis, check to see if we've already
2075 // computed a SCEV for this Op and Ty.
2077 ID.AddInteger(scSignExtend);
2078 ID.AddPointer(Op);
2079 ID.AddPointer(Ty);
2080 void *IP = nullptr;
2081 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2082 // Limit recursion depth.
2083 if (Depth > MaxCastDepth) {
2084 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2085 Op, Ty);
2086 UniqueSCEVs.InsertNode(S, IP);
2087 S->computeAndSetCanonical(*this);
2088 registerUser(S, Op);
2089 return S;
2090 }
2091
2092 // sext(trunc(x)) --> sext(x) or x or trunc(x)
2094 // It's possible the bits taken off by the truncate were all sign bits. If
2095 // so, we should be able to simplify this further.
2096 const SCEV *X = ST->getOperand();
2098 unsigned TruncBits = getTypeSizeInBits(ST->getType());
2099 unsigned NewBits = getTypeSizeInBits(Ty);
2100 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
2101 CR.sextOrTrunc(NewBits)))
2102 return getTruncateOrSignExtend(X, Ty, Depth);
2103 }
2104
2105 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
2106 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
2107 if (SA->hasNoSignedWrap()) {
2108 // If the addition does not sign overflow then we can, by definition,
2109 // commute the sign extension with the addition operation.
2111 for (SCEVUse Op : SA->operands())
2112 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
2113 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
2114 }
2115
2116 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
2117 // if D + (C - D + x + y + ...) could be proven to not signed wrap
2118 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
2119 //
2120 // For instance, this will bring two seemingly different expressions:
2121 // 1 + sext(5 + 20 * %x + 24 * %y) and
2122 // sext(6 + 20 * %x + 24 * %y)
2123 // to the same form:
2124 // 2 + sext(4 + 20 * %x + 24 * %y)
2125 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
2126 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
2127 if (D != 0) {
2128 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2129 const SCEV *SResidual =
2131 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2132 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
2133 Depth + 1);
2134 }
2135 }
2136 }
2137 // If the input value is a chrec scev, and we can prove that the value
2138 // did not overflow the old, smaller, value, we can sign extend all of the
2139 // operands (often constants). This allows analysis of something like
2140 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
2142 if (AR->isAffine()) {
2143 const SCEV *Start = AR->getStart();
2144 const SCEV *Step = AR->getStepRecurrence(*this);
2145 unsigned BitWidth = getTypeSizeInBits(AR->getType());
2146 const Loop *L = AR->getLoop();
2147
2148 // The no-signed-wrap case is handled before the uniquing lookup above.
2149
2150 // Check whether the backedge-taken count is SCEVCouldNotCompute.
2151 // Note that this serves two purposes: It filters out loops that are
2152 // simply not analyzable, and it covers the case where this code is
2153 // being called from within backedge-taken count analysis, such that
2154 // attempting to ask for the backedge-taken count would likely result
2155 // in infinite recursion. In the later case, the analysis code will
2156 // cope with a conservative value, and it will take care to purge
2157 // that value once it has finished.
2158 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2159 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2160 // Manually compute the final value for AR, checking for
2161 // overflow.
2162
2163 // Check whether the backedge-taken count can be losslessly casted to
2164 // the addrec's type. The count is always unsigned.
2165 const SCEV *CastedMaxBECount =
2166 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2167 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2168 CastedMaxBECount, MaxBECount->getType(), Depth);
2169 if (MaxBECount == RecastedMaxBECount) {
2170 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2171 // Check whether Start+Step*MaxBECount has no signed overflow.
2172 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2174 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2176 Depth + 1),
2177 WideTy, Depth + 1);
2178 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2179 const SCEV *WideMaxBECount =
2180 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2181 const SCEV *OperandExtendedAdd =
2182 getAddExpr(WideStart,
2183 getMulExpr(WideMaxBECount,
2184 getSignExtendExpr(Step, WideTy, Depth + 1),
2187 if (SAdd == OperandExtendedAdd) {
2188 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2189 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2190 // Return the expression with the addrec on the outside.
2191 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2192 Depth + 1);
2193 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2194 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2195 }
2196 // Similar to above, only this time treat the step value as unsigned.
2197 // This covers loops that count up with an unsigned step.
2198 OperandExtendedAdd =
2199 getAddExpr(WideStart,
2200 getMulExpr(WideMaxBECount,
2201 getZeroExtendExpr(Step, WideTy, Depth + 1),
2204 if (SAdd == OperandExtendedAdd) {
2205 // If AR wraps around then
2206 //
2207 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2208 // => SAdd != OperandExtendedAdd
2209 //
2210 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2211 // (SAdd == OperandExtendedAdd => AR is NW)
2212
2213 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2214
2215 // Return the expression with the addrec on the outside.
2216 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2217 Depth + 1);
2218 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
2219 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2220 }
2221 }
2222 }
2223
2224 auto NewFlags = proveNoSignedWrapViaInduction(AR);
2225 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2226 if (AR->hasNoSignedWrap()) {
2227 // Same as nsw case above - duplicated here to avoid a compile time
2228 // issue. It's not clear that the order of checks does matter, but
2229 // it's one of two issue possible causes for a change which was
2230 // reverted. Be conservative for the moment.
2231 Start =
2233 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2234 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2235 }
2236
2237 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2238 // if D + (C - D + Step * n) could be proven to not signed wrap
2239 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2240 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2241 const APInt &C = SC->getAPInt();
2242 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2243 if (D != 0) {
2244 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2245 const SCEV *SResidual =
2246 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2247 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2248 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
2249 Depth + 1);
2250 }
2251 }
2252
2253 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2254 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2255 Start =
2257 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2258 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2259 }
2260 }
2261
2262 // If the input value is provably positive and we could not simplify
2263 // away the sext build a zext instead.
2265 return getZeroExtendExpr(Op, Ty, Depth + 1);
2266
2267 // sext(smin(x, y)) -> smin(sext(x), sext(y))
2268 // sext(smax(x, y)) -> smax(sext(x), sext(y))
2271 SmallVector<SCEVUse, 4> Operands;
2272 for (SCEVUse Operand : MinMax->operands())
2273 Operands.push_back(getSignExtendExpr(Operand, Ty));
2275 return getSMinExpr(Operands);
2276 return getSMaxExpr(Operands);
2277 }
2278
2279 // The cast wasn't folded; create an explicit cast node.
2280 // Recompute the insert position, as it may have been invalidated.
2281 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2282 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2283 Op, Ty);
2284 UniqueSCEVs.InsertNode(S, IP);
2285 S->computeAndSetCanonical(*this);
2286 registerUser(S, Op);
2287 return S;
2288}
2289
2291 Type *Ty) {
2292 switch (Kind) {
2293 case scTruncate:
2294 return getTruncateExpr(Op, Ty);
2295 case scZeroExtend:
2296 return getZeroExtendExpr(Op, Ty);
2297 case scSignExtend:
2298 return getSignExtendExpr(Op, Ty);
2299 case scPtrToInt:
2300 return getPtrToIntExpr(Op, Ty);
2301 default:
2302 llvm_unreachable("Not a SCEV cast expression!");
2303 }
2304}
2305
2306/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2307/// unspecified bits out to the given type.
2309 Type *Ty) {
2310 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2311 "This is not an extending conversion!");
2312 assert(isSCEVable(Ty) &&
2313 "This is not a conversion to a SCEVable type!");
2314 Ty = getEffectiveSCEVType(Ty);
2315
2316 // Sign-extend negative constants.
2317 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2318 if (SC->getAPInt().isNegative())
2319 return getSignExtendExpr(Op, Ty);
2320
2321 // Peel off a truncate cast.
2323 const SCEV *NewOp = T->getOperand();
2324 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2325 return getAnyExtendExpr(NewOp, Ty);
2326 return getTruncateOrNoop(NewOp, Ty);
2327 }
2328
2329 // Next try a zext cast. If the cast is folded, use it.
2330 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2331 if (!isa<SCEVZeroExtendExpr>(ZExt))
2332 return ZExt;
2333
2334 // Next try a sext cast. If the cast is folded, use it.
2335 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2336 if (!isa<SCEVSignExtendExpr>(SExt))
2337 return SExt;
2338
2339 // Force the cast to be folded into the operands of an addrec.
2340 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2342 for (const SCEV *Op : AR->operands())
2343 Ops.push_back(getAnyExtendExpr(Op, Ty));
2344 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2345 }
2346
2347 // If the expression is obviously signed, use the sext cast value.
2348 if (isa<SCEVSMaxExpr>(Op))
2349 return SExt;
2350
2351 // Absent any other information, use the zext cast value.
2352 return ZExt;
2353}
2354
2355/// Process the given Ops list, which is a list of operands to be added under
2356/// the given scale, update the given map. This is a helper function for
2357/// getAddRecExpr. As an example of what it does, given a sequence of operands
2358/// that would form an add expression like this:
2359///
2360/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2361///
2362/// where A and B are constants, update the map with these values:
2363///
2364/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2365///
2366/// and add 13 + A*B*29 to AccumulatedConstant.
2367/// This will allow getAddRecExpr to produce this:
2368///
2369/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2370///
2371/// This form often exposes folding opportunities that are hidden in
2372/// the original operand list.
2373///
2374/// Return true iff it appears that any interesting folding opportunities
2375/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2376/// the common case where no interesting opportunities are present, and
2377/// is also used as a check to avoid infinite recursion.
2380 APInt &AccumulatedConstant,
2382 const APInt &Scale,
2383 ScalarEvolution &SE) {
2384 bool Interesting = false;
2385
2386 // Iterate over the add operands. They are sorted, with constants first.
2387 unsigned i = 0;
2388 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2389 ++i;
2390 // Pull a buried constant out to the outside.
2391 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2392 Interesting = true;
2393 AccumulatedConstant += Scale * C->getAPInt();
2394 }
2395
2396 // Next comes everything else. We're especially interested in multiplies
2397 // here, but they're in the middle, so just visit the rest with one loop.
2398 for (; i != Ops.size(); ++i) {
2400 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2401 APInt NewScale =
2402 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2403 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2404 // A multiplication of a constant with another add; recurse.
2405 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2406 Interesting |= CollectAddOperandsWithScales(
2407 M, NewOps, AccumulatedConstant, Add->operands(), NewScale, SE);
2408 } else {
2409 // A multiplication of a constant with some other value. Update
2410 // the map.
2411 SmallVector<SCEVUse, 4> MulOps(drop_begin(Mul->operands()));
2412 const SCEV *Key = SE.getMulExpr(MulOps);
2413 auto Pair = M.insert({Key, NewScale});
2414 if (Pair.second) {
2415 NewOps.push_back(Pair.first->first);
2416 } else {
2417 Pair.first->second += NewScale;
2418 // The map already had an entry for this value, which may indicate
2419 // a folding opportunity.
2420 Interesting = true;
2421 }
2422 }
2423 } else {
2424 // An ordinary operand. Update the map.
2425 auto Pair = M.insert({Ops[i], Scale});
2426 if (Pair.second) {
2427 NewOps.push_back(Pair.first->first);
2428 } else {
2429 Pair.first->second += Scale;
2430 // The map already had an entry for this value, which may indicate
2431 // a folding opportunity.
2432 Interesting = true;
2433 }
2434 }
2435 }
2436
2437 return Interesting;
2438}
2439
2441 const SCEV *LHS, const SCEV *RHS,
2442 const Instruction *CtxI) {
2444 unsigned);
2445 switch (BinOp) {
2446 default:
2447 llvm_unreachable("Unsupported binary op");
2448 case Instruction::Add:
2450 break;
2451 case Instruction::Sub:
2453 break;
2454 case Instruction::Mul:
2456 break;
2457 }
2458
2459 const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
2462
2463 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2464 auto *NarrowTy = cast<IntegerType>(LHS->getType());
2465 auto *WideTy =
2466 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2467
2468 const SCEV *A = (this->*Extension)(
2469 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2470 const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2471 const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2472 const SCEV *B = (this->*Operation)(LHSB, RHSB, SCEV::FlagAnyWrap, 0);
2473 if (A == B)
2474 return true;
2475 // Can we use context to prove the fact we need?
2476 if (!CtxI)
2477 return false;
2478 // TODO: Support mul.
2479 if (BinOp == Instruction::Mul)
2480 return false;
2481 auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2482 // TODO: Lift this limitation.
2483 if (!RHSC)
2484 return false;
2485 APInt C = RHSC->getAPInt();
2486 unsigned NumBits = C.getBitWidth();
2487 bool IsSub = (BinOp == Instruction::Sub);
2488 bool IsNegativeConst = (Signed && C.isNegative());
2489 // Compute the direction and magnitude by which we need to check overflow.
2490 bool OverflowDown = IsSub ^ IsNegativeConst;
2491 APInt Magnitude = C;
2492 if (IsNegativeConst) {
2493 if (C == APInt::getSignedMinValue(NumBits))
2494 // TODO: SINT_MIN on inversion gives the same negative value, we don't
2495 // want to deal with that.
2496 return false;
2497 Magnitude = -C;
2498 }
2499
2501 if (OverflowDown) {
2502 // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2503 APInt Min = Signed ? APInt::getSignedMinValue(NumBits)
2504 : APInt::getMinValue(NumBits);
2505 APInt Limit = Min + Magnitude;
2506 return isKnownPredicateAt(Pred, getConstant(Limit), LHS, CtxI);
2507 } else {
2508 // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2509 APInt Max = Signed ? APInt::getSignedMaxValue(NumBits)
2510 : APInt::getMaxValue(NumBits);
2511 APInt Limit = Max - Magnitude;
2512 return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2513 }
2514}
2515
2516std::optional<SCEV::NoWrapFlags>
2518 const OverflowingBinaryOperator *OBO) {
2519 // It cannot be done any better.
2520 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2521 return std::nullopt;
2522
2523 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2524
2525 if (OBO->hasNoUnsignedWrap())
2527 if (OBO->hasNoSignedWrap())
2529
2530 bool Deduced = false;
2531
2532 if (OBO->getOpcode() != Instruction::Add &&
2533 OBO->getOpcode() != Instruction::Sub &&
2534 OBO->getOpcode() != Instruction::Mul)
2535 return std::nullopt;
2536
2537 const SCEV *LHS = getSCEV(OBO->getOperand(0));
2538 const SCEV *RHS = getSCEV(OBO->getOperand(1));
2539
2540 const Instruction *CtxI =
2542 if (!OBO->hasNoUnsignedWrap() &&
2544 /* Signed */ false, LHS, RHS, CtxI)) {
2546 Deduced = true;
2547 }
2548
2549 if (!OBO->hasNoSignedWrap() &&
2551 /* Signed */ true, LHS, RHS, CtxI)) {
2553 Deduced = true;
2554 }
2555
2556 if (Deduced)
2557 return Flags;
2558 return std::nullopt;
2559}
2560
2561// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2562// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2563// can't-overflow flags for the operation if possible.
2567 SCEV::NoWrapFlags Flags) {
2568 using namespace std::placeholders;
2569
2570 using OBO = OverflowingBinaryOperator;
2571
2572 bool CanAnalyze =
2574 (void)CanAnalyze;
2575 assert(CanAnalyze && "don't call from other places!");
2576
2577 SCEV::NoWrapFlags SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2578 SCEV::NoWrapFlags SignOrUnsignWrap =
2579 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2580
2581 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2582 auto IsKnownNonNegative = [&](SCEVUse U) {
2583 return SE->isKnownNonNegative(U);
2584 };
2585
2586 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2587 Flags = ScalarEvolution::setFlags(Flags, SignOrUnsignMask);
2588
2589 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2590
2591 if (SignOrUnsignWrap != SignOrUnsignMask &&
2592 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2593 isa<SCEVConstant>(Ops[0])) {
2594
2595 auto Opcode = [&] {
2596 switch (Type) {
2597 case scAddExpr:
2598 return Instruction::Add;
2599 case scMulExpr:
2600 return Instruction::Mul;
2601 default:
2602 llvm_unreachable("Unexpected SCEV op.");
2603 }
2604 }();
2605
2606 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2607
2608 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2609 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2611 Opcode, C, OBO::NoSignedWrap);
2612 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2614 }
2615
2616 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2617 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2619 Opcode, C, OBO::NoUnsignedWrap);
2620 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2622 }
2623 }
2624
2625 // <0,+,nonnegative><nw> is also nuw
2626 // TODO: Add corresponding nsw case
2628 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2629 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2631
2632 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2634 Ops.size() == 2) {
2635 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2636 if (UDiv->getOperand(1) == Ops[1])
2638 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2639 if (UDiv->getOperand(1) == Ops[0])
2641 }
2642
2643 return Flags;
2644}
2645
2647 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2648}
2649
2650/// Get a canonical add expression, or something simpler if possible.
2652 SCEV::NoWrapFlags OrigFlags,
2653 unsigned Depth) {
2654 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2655 "only nuw or nsw allowed");
2656 assert(!Ops.empty() && "Cannot get empty add!");
2657 if (Ops.size() == 1) return Ops[0];
2658#ifndef NDEBUG
2659 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2660 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2661 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2662 "SCEVAddExpr operand types don't match!");
2663 unsigned NumPtrs = count_if(
2664 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2665 assert(NumPtrs <= 1 && "add has at most one pointer operand");
2666#endif
2667
2668 const SCEV *Folded = constantFoldAndGroupOps(
2669 *this, LI, DT, Ops,
2670 [](const APInt &C1, const APInt &C2) { return C1 + C2; },
2671 [](const APInt &C) { return C.isZero(); }, // identity
2672 [](const APInt &C) { return false; }); // absorber
2673 if (Folded)
2674 return Folded;
2675
2676 unsigned Idx = isa<SCEVConstant>(Ops[0]) ? 1 : 0;
2677
2678 // Delay expensive flag strengthening until necessary.
2679 auto ComputeFlags = [this, OrigFlags](ArrayRef<SCEVUse> Ops) {
2680 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2681 };
2682
2683 // Limit recursion calls depth.
2685 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2686
2687 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2688 // Don't strengthen flags if we have no new information.
2689 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2690 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2691 Add->setNoWrapFlags(ComputeFlags(Ops));
2692 return S;
2693 }
2694
2695 // Okay, check to see if the same value occurs in the operand list more than
2696 // once. If so, merge them together into an multiply expression. Since we
2697 // sorted the list, these values are required to be adjacent.
2698 Type *Ty = Ops[0]->getType();
2699 bool FoundMatch = false;
2700 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2701 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2702 // Scan ahead to count how many equal operands there are.
2703 unsigned Count = 2;
2704 while (i+Count != e && Ops[i+Count] == Ops[i])
2705 ++Count;
2706 // Merge the values into a multiply.
2707 SCEVUse Scale = getConstant(Ty, Count);
2708 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2709 if (Ops.size() == Count)
2710 return Mul;
2711 Ops[i] = Mul;
2712 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2713 --i; e -= Count - 1;
2714 FoundMatch = true;
2715 }
2716 if (FoundMatch)
2717 return getAddExpr(Ops, OrigFlags, Depth + 1);
2718
2719 // Check for truncates. If all the operands are truncated from the same
2720 // type, see if factoring out the truncate would permit the result to be
2721 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2722 // if the contents of the resulting outer trunc fold to something simple.
2723 auto FindTruncSrcType = [&]() -> Type * {
2724 // We're ultimately looking to fold an addrec of truncs and muls of only
2725 // constants and truncs, so if we find any other types of SCEV
2726 // as operands of the addrec then we bail and return nullptr here.
2727 // Otherwise, we return the type of the operand of a trunc that we find.
2728 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2729 return T->getOperand()->getType();
2730 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2731 SCEVUse LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2732 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2733 return T->getOperand()->getType();
2734 }
2735 return nullptr;
2736 };
2737 if (auto *SrcType = FindTruncSrcType()) {
2738 SmallVector<SCEVUse, 8> LargeOps;
2739 bool Ok = true;
2740 // Check all the operands to see if they can be represented in the
2741 // source type of the truncate.
2742 for (const SCEV *Op : Ops) {
2744 if (T->getOperand()->getType() != SrcType) {
2745 Ok = false;
2746 break;
2747 }
2748 LargeOps.push_back(T->getOperand());
2749 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Op)) {
2750 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2751 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Op)) {
2752 SmallVector<SCEVUse, 8> LargeMulOps;
2753 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2754 if (const SCEVTruncateExpr *T =
2755 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2756 if (T->getOperand()->getType() != SrcType) {
2757 Ok = false;
2758 break;
2759 }
2760 LargeMulOps.push_back(T->getOperand());
2761 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2762 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2763 } else {
2764 Ok = false;
2765 break;
2766 }
2767 }
2768 if (Ok)
2769 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2770 } else {
2771 Ok = false;
2772 break;
2773 }
2774 }
2775 if (Ok) {
2776 // Evaluate the expression in the larger type.
2777 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2778 // If it folds to something simple, use it. Otherwise, don't.
2779 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2780 return getTruncateExpr(Fold, Ty);
2781 }
2782 }
2783
2784 if (Ops.size() == 2) {
2785 // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2786 // C2 can be folded in a way that allows retaining wrapping flags of (X +
2787 // C1).
2788 const SCEV *A = Ops[0];
2789 const SCEV *B = Ops[1];
2790 auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2791 auto *C = dyn_cast<SCEVConstant>(A);
2792 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2793 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2794 auto C2 = C->getAPInt();
2795 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2796
2797 APInt ConstAdd = C1 + C2;
2798 auto AddFlags = AddExpr->getNoWrapFlags();
2799 // Adding a smaller constant is NUW if the original AddExpr was NUW.
2801 ConstAdd.ule(C1)) {
2802 PreservedFlags =
2804 }
2805
2806 // Adding a constant with the same sign and small magnitude is NSW, if the
2807 // original AddExpr was NSW.
2809 C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2810 ConstAdd.abs().ule(C1.abs())) {
2811 PreservedFlags =
2813 }
2814
2815 if (PreservedFlags != SCEV::FlagAnyWrap) {
2816 SmallVector<SCEVUse, 4> NewOps(AddExpr->operands());
2817 NewOps[0] = getConstant(ConstAdd);
2818 return getAddExpr(NewOps, PreservedFlags);
2819 }
2820 }
2821
2822 // Try to push the constant operand into a ZExt: A + zext (-A + B) -> zext
2823 // (B), if trunc (A) + -A + B does not unsigned-wrap.
2824 const SCEVAddExpr *InnerAdd;
2825 if (match(B, m_scev_ZExt(m_scev_Add(InnerAdd)))) {
2826 const SCEV *NarrowA = getTruncateExpr(A, InnerAdd->getType());
2827 if (NarrowA == getNegativeSCEV(InnerAdd->getOperand(0)) &&
2828 getZeroExtendExpr(NarrowA, B->getType()) == A &&
2829 hasFlags(StrengthenNoWrapFlags(this, scAddExpr, {NarrowA, InnerAdd},
2831 SCEV::FlagNUW)) {
2832 return getZeroExtendExpr(getAddExpr(NarrowA, InnerAdd), B->getType());
2833 }
2834 }
2835 }
2836
2837 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2838 const SCEV *Y;
2839 if (Ops.size() == 2 &&
2840 match(Ops[0],
2842 m_scev_URem(m_scev_Specific(Ops[1]), m_SCEV(Y), *this))))
2843 return getMulExpr(Y, getUDivExpr(Ops[1], Y));
2844
2845 // Skip past any other cast SCEVs.
2846 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2847 ++Idx;
2848
2849 // If there are add operands they would be next.
2850 if (Idx < Ops.size()) {
2851 bool DeletedAdd = false;
2852 // If the original flags and all inlined SCEVAddExprs are NUW, use the
2853 // common NUW flag for expression after inlining. Other flags cannot be
2854 // preserved, because they may depend on the original order of operations.
2855 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2856 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2857 if (Ops.size() > AddOpsInlineThreshold ||
2858 Add->getNumOperands() > AddOpsInlineThreshold)
2859 break;
2860 // If we have an add, expand the add operands onto the end of the operands
2861 // list.
2862 Ops.erase(Ops.begin()+Idx);
2863 append_range(Ops, Add->operands());
2864 DeletedAdd = true;
2865 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2866 }
2867
2868 // If we deleted at least one add, we added operands to the end of the list,
2869 // and they are not necessarily sorted. Recurse to resort and resimplify
2870 // any operands we just acquired.
2871 if (DeletedAdd)
2872 return getAddExpr(Ops, CommonFlags, Depth + 1);
2873 }
2874
2875 // Skip over the add expression until we get to a multiply.
2876 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2877 ++Idx;
2878
2879 // Check to see if there are any folding opportunities present with
2880 // operands multiplied by constant values.
2881 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2885 APInt AccumulatedConstant(BitWidth, 0);
2886 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2887 Ops, APInt(BitWidth, 1), *this)) {
2888 struct APIntCompare {
2889 bool operator()(const APInt &LHS, const APInt &RHS) const {
2890 return LHS.ult(RHS);
2891 }
2892 };
2893
2894 // Some interesting folding opportunity is present, so its worthwhile to
2895 // re-generate the operands list. Group the operands by constant scale,
2896 // to avoid multiplying by the same constant scale multiple times.
2897 std::map<APInt, SmallVector<SCEVUse, 4>, APIntCompare> MulOpLists;
2898 for (const SCEV *NewOp : NewOps)
2899 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2900 // Re-generate the operands list.
2901 Ops.clear();
2902 if (AccumulatedConstant != 0)
2903 Ops.push_back(getConstant(AccumulatedConstant));
2904 for (auto &MulOp : MulOpLists) {
2905 if (MulOp.first == 1) {
2906 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2907 } else if (MulOp.first != 0) {
2908 Ops.push_back(getMulExpr(
2909 getConstant(MulOp.first),
2910 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2911 SCEV::FlagAnyWrap, Depth + 1));
2912 }
2913 }
2914 if (Ops.empty())
2915 return getZero(Ty);
2916 if (Ops.size() == 1)
2917 return Ops[0];
2918 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2919 }
2920 }
2921
2922 // Given a SCEVMulExpr and an operand index, return the product of all
2923 // operands except the one at OpIdx.
2924 auto StripFactor = [&](const SCEVMulExpr *M, unsigned OpIdx) -> SCEVUse {
2925 if (M->getNumOperands() == 2)
2926 return M->getOperand(OpIdx == 0);
2927 SmallVector<SCEVUse, 4> Remaining(M->operands().take_front(OpIdx));
2928 append_range(Remaining, M->operands().drop_front(OpIdx + 1));
2929 return getMulExpr(Remaining, SCEV::FlagAnyWrap, Depth + 1);
2930 };
2931
2932 // If we are adding something to a multiply expression, make sure the
2933 // something is not already an operand of the multiply. If so, merge it into
2934 // the multiply.
2935 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2936 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2937 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2938 // Scan all terms to find every occurrence of common factor MulOpSCEV
2939 // and fold them in one shot:
2940 // A1*X + A2*X + ... + An*X --> X * (A1 + A2 + ... + An)
2941 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2942 if (isa<SCEVConstant>(MulOpSCEV))
2943 continue;
2944
2945 // Cofactors: 1 for bare addends matching MulOpSCEV, or the
2946 // remaining product for multiply terms containing MulOpSCEV.
2947 SmallVector<SCEVUse, 4> Cofactors;
2948 SmallVector<unsigned, 4> DeadIndices;
2949 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) {
2950 if (MulOpSCEV == Ops[AddOp]) {
2951 // W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2952 Cofactors.push_back(getOne(Ty));
2953 DeadIndices.push_back(AddOp);
2954 continue;
2955 }
2956
2957 if (AddOp <= Idx || !isa<SCEVMulExpr>(Ops[AddOp]))
2958 continue;
2959
2960 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[AddOp]);
2961 for (unsigned OMulOp = 0, OE = OtherMul->getNumOperands(); OMulOp != OE;
2962 ++OMulOp) {
2963 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2964 // (A*B*C) + (A*D*E) --> A * (B*C + D*E)
2965 Cofactors.push_back(StripFactor(OtherMul, OMulOp));
2966 DeadIndices.push_back(AddOp);
2967 break;
2968 }
2969 }
2970 }
2971
2972 // Fold all collected cofactors with the anchor multiply's cofactor:
2973 // MulOpSCEV * (Cofactor_1 + ... + Cofactor_n + AnchorCofactor)
2974 if (!Cofactors.empty()) {
2975 Cofactors.push_back(StripFactor(Mul, MulOp));
2976
2977 SCEVUse InnerSum = getAddExpr(Cofactors, SCEV::FlagAnyWrap, Depth + 1);
2978 SCEVUse OuterMul =
2979 getMulExpr(MulOpSCEV, InnerSum, SCEV::FlagAnyWrap, Depth + 1);
2980
2981 // DeadIndices does not include Idx (the anchor), hence +1.
2982 if (Ops.size() == DeadIndices.size() + 1)
2983 return OuterMul;
2984
2985 // Erase Ops[Idx] first, then erase DeadIndices in reverse order.
2986 // The -1 adjustment accounts for the shift from removing Idx;
2987 // reverse order means each erasure only shifts later positions,
2988 // which have already been processed.
2989 Ops.erase(Ops.begin() + Idx);
2990 for (unsigned Dead : reverse(DeadIndices))
2991 Ops.erase(Ops.begin() + (Dead > Idx ? Dead - 1 : Dead));
2992
2993 Ops.push_back(OuterMul);
2994 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2995 }
2996 }
2997 }
2998
2999 // If there are any add recurrences in the operands list, see if any other
3000 // added values are loop invariant. If so, we can fold them into the
3001 // recurrence.
3002 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3003 ++Idx;
3004
3005 // Scan over all recurrences, trying to fold loop invariants into them.
3006 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3007 // Scan all of the other operands to this add and add them to the vector if
3008 // they are loop invariant w.r.t. the recurrence.
3010 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3011 const Loop *AddRecLoop = AddRec->getLoop();
3012 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3013 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
3014 LIOps.push_back(Ops[i]);
3015 Ops.erase(Ops.begin()+i);
3016 --i; --e;
3017 }
3018
3019 // If we found some loop invariants, fold them into the recurrence.
3020 if (!LIOps.empty()) {
3021 // Compute nowrap flags for the addition of the loop-invariant ops and
3022 // the addrec. Temporarily push it as an operand for that purpose. These
3023 // flags are valid in the scope of the addrec only.
3024 LIOps.push_back(AddRec);
3025 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
3026 LIOps.pop_back();
3027
3028 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
3029 LIOps.push_back(AddRec->getStart());
3030
3031 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
3032
3033 // It is not in general safe to propagate flags valid on an add within
3034 // the addrec scope to one outside it. We must prove that the inner
3035 // scope is guaranteed to execute if the outer one does to be able to
3036 // safely propagate. We know the program is undefined if poison is
3037 // produced on the inner scoped addrec. We also know that *for this use*
3038 // the outer scoped add can't overflow (because of the flags we just
3039 // computed for the inner scoped add) without the program being undefined.
3040 // Proving that entry to the outer scope neccesitates entry to the inner
3041 // scope, thus proves the program undefined if the flags would be violated
3042 // in the outer scope.
3043 SCEV::NoWrapFlags AddFlags = Flags;
3044 if (AddFlags != SCEV::FlagAnyWrap) {
3045 auto *DefI = getDefiningScopeBound(LIOps);
3046 auto *ReachI = &*AddRecLoop->getHeader()->begin();
3047 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
3048 AddFlags = SCEV::FlagAnyWrap;
3049 }
3050 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
3051
3052 // Build the new addrec. Propagate the NUW and NSW flags if both the
3053 // outer add and the inner addrec are guaranteed to have no overflow.
3054 // Always propagate NW.
3055 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
3056 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
3057
3058 // If all of the other operands were loop invariant, we are done.
3059 if (Ops.size() == 1) return NewRec;
3060
3061 // Otherwise, add the folded AddRec by the non-invariant parts.
3062 for (unsigned i = 0;; ++i)
3063 if (Ops[i] == AddRec) {
3064 Ops[i] = NewRec;
3065 break;
3066 }
3067 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3068 }
3069
3070 // Okay, if there weren't any loop invariants to be folded, check to see if
3071 // there are multiple AddRec's with the same loop induction variable being
3072 // added together. If so, we can fold them.
3073 for (unsigned OtherIdx = Idx+1;
3074 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3075 ++OtherIdx) {
3076 // We expect the AddRecExpr's to be sorted in reverse dominance order,
3077 // so that the 1st found AddRecExpr is dominated by all others.
3078 assert(DT.dominates(
3079 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
3080 AddRec->getLoop()->getHeader()) &&
3081 "AddRecExprs are not sorted in reverse dominance order?");
3082 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
3083 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
3084 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
3085 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3086 ++OtherIdx) {
3087 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3088 if (OtherAddRec->getLoop() == AddRecLoop) {
3089 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
3090 i != e; ++i) {
3091 if (i >= AddRecOps.size()) {
3092 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
3093 break;
3094 }
3095 AddRecOps[i] =
3096 getAddExpr(AddRecOps[i], OtherAddRec->getOperand(i),
3098 }
3099 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3100 }
3101 }
3102 // Step size has changed, so we cannot guarantee no self-wraparound.
3103 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
3104 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3105 }
3106 }
3107
3108 // Otherwise couldn't fold anything into this recurrence. Move onto the
3109 // next one.
3110 }
3111
3112 // Okay, it looks like we really DO need an add expr. Check to see if we
3113 // already have one, otherwise create a new one.
3114 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
3115}
3116
3117const SCEV *ScalarEvolution::getOrCreateAddExpr(ArrayRef<SCEVUse> Ops,
3118 SCEV::NoWrapFlags Flags) {
3120 ID.AddInteger(scAddExpr);
3121 for (const SCEV *Op : Ops)
3122 ID.AddPointer(Op);
3123 void *IP = nullptr;
3124 SCEVAddExpr *S =
3125 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3126 if (!S) {
3127 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3129 S = new (SCEVAllocator)
3130 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
3131 UniqueSCEVs.InsertNode(S, IP);
3132 S->computeAndSetCanonical(*this);
3133 registerUser(S, Ops);
3134 }
3135 S->setNoWrapFlags(Flags);
3136 return S;
3137}
3138
3139const SCEV *ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<SCEVUse> Ops,
3140 const Loop *L,
3141 SCEV::NoWrapFlags Flags) {
3142 FoldingSetNodeID ID;
3143 ID.AddInteger(scAddRecExpr);
3144 for (const SCEV *Op : Ops)
3145 ID.AddPointer(Op);
3146 ID.AddPointer(L);
3147 void *IP = nullptr;
3148 SCEVAddRecExpr *S =
3149 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3150 if (!S) {
3151 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3153 S = new (SCEVAllocator)
3154 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
3155 UniqueSCEVs.InsertNode(S, IP);
3156 S->computeAndSetCanonical(*this);
3157 LoopUsers[L].push_back(S);
3158 registerUser(S, Ops);
3159 }
3160 setNoWrapFlags(S, Flags);
3161 return S;
3162}
3163
3164const SCEV *ScalarEvolution::getOrCreateMulExpr(ArrayRef<SCEVUse> Ops,
3165 SCEV::NoWrapFlags Flags) {
3166 FoldingSetNodeID ID;
3167 ID.AddInteger(scMulExpr);
3168 for (const SCEV *Op : Ops)
3169 ID.AddPointer(Op);
3170 void *IP = nullptr;
3171 SCEVMulExpr *S =
3172 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3173 if (!S) {
3174 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3176 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
3177 O, Ops.size());
3178 UniqueSCEVs.InsertNode(S, IP);
3179 S->computeAndSetCanonical(*this);
3180 registerUser(S, Ops);
3181 }
3182 S->setNoWrapFlags(Flags);
3183 return S;
3184}
3185
3186static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
3187 uint64_t k = i*j;
3188 if (j > 1 && k / j != i) Overflow = true;
3189 return k;
3190}
3191
3192/// Compute the result of "n choose k", the binomial coefficient. If an
3193/// intermediate computation overflows, Overflow will be set and the return will
3194/// be garbage. Overflow is not cleared on absence of overflow.
3195static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3196 // We use the multiplicative formula:
3197 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3198 // At each iteration, we take the n-th term of the numeral and divide by the
3199 // (k-n)th term of the denominator. This division will always produce an
3200 // integral result, and helps reduce the chance of overflow in the
3201 // intermediate computations. However, we can still overflow even when the
3202 // final result would fit.
3203
3204 if (n == 0 || n == k) return 1;
3205 if (k > n) return 0;
3206
3207 if (k > n/2)
3208 k = n-k;
3209
3210 uint64_t r = 1;
3211 for (uint64_t i = 1; i <= k; ++i) {
3212 r = umul_ov(r, n-(i-1), Overflow);
3213 r /= i;
3214 }
3215 return r;
3216}
3217
3218/// Determine if any of the operands in this SCEV are a constant or if
3219/// any of the add or multiply expressions in this SCEV contain a constant.
3220static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3221 struct FindConstantInAddMulChain {
3222 bool FoundConstant = false;
3223
3224 bool follow(const SCEV *S) {
3225 FoundConstant |= isa<SCEVConstant>(S);
3226 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3227 }
3228
3229 bool isDone() const {
3230 return FoundConstant;
3231 }
3232 };
3233
3234 FindConstantInAddMulChain F;
3236 ST.visitAll(StartExpr);
3237 return F.FoundConstant;
3238}
3239
3240/// Get a canonical multiply expression, or something simpler if possible.
3242 SCEV::NoWrapFlags OrigFlags,
3243 unsigned Depth) {
3244 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3245 "only nuw or nsw allowed");
3246 assert(!Ops.empty() && "Cannot get empty mul!");
3247 if (Ops.size() == 1) return Ops[0];
3248#ifndef NDEBUG
3249 Type *ETy = Ops[0]->getType();
3250 assert(!ETy->isPointerTy());
3251 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3252 assert(Ops[i]->getType() == ETy &&
3253 "SCEVMulExpr operand types don't match!");
3254#endif
3255
3256 const SCEV *Folded = constantFoldAndGroupOps(
3257 *this, LI, DT, Ops,
3258 [](const APInt &C1, const APInt &C2) { return C1 * C2; },
3259 [](const APInt &C) { return C.isOne(); }, // identity
3260 [](const APInt &C) { return C.isZero(); }); // absorber
3261 if (Folded)
3262 return Folded;
3263
3264 // Delay expensive flag strengthening until necessary.
3265 auto ComputeFlags = [this, OrigFlags](const ArrayRef<SCEVUse> Ops) {
3266 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3267 };
3268
3269 // Limit recursion calls depth.
3271 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3272
3273 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3274 // Don't strengthen flags if we have no new information.
3275 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3276 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3277 Mul->setNoWrapFlags(ComputeFlags(Ops));
3278 return S;
3279 }
3280
3281 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3282 if (Ops.size() == 2) {
3283 // C1*(C2+V) -> C1*C2 + C1*V
3284 // If any of Add's ops are Adds or Muls with a constant, apply this
3285 // transformation as well.
3286 //
3287 // TODO: There are some cases where this transformation is not
3288 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
3289 // this transformation should be narrowed down.
3290 const SCEV *Op0, *Op1;
3291 if (match(Ops[1], m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))) &&
3293 const SCEV *LHS = getMulExpr(LHSC, Op0, SCEV::FlagAnyWrap, Depth + 1);
3294 const SCEV *RHS = getMulExpr(LHSC, Op1, SCEV::FlagAnyWrap, Depth + 1);
3295 return getAddExpr(LHS, RHS, SCEV::FlagAnyWrap, Depth + 1);
3296 }
3297
3298 if (Ops[0]->isAllOnesValue()) {
3299 // If we have a mul by -1 of an add, try distributing the -1 among the
3300 // add operands.
3301 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3303 bool AnyFolded = false;
3304 for (const SCEV *AddOp : Add->operands()) {
3305 const SCEV *Mul = getMulExpr(Ops[0], SCEVUse(AddOp),
3307 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3308 NewOps.push_back(Mul);
3309 }
3310 if (AnyFolded)
3311 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3312 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3313 // Negation preserves a recurrence's no self-wrap property.
3314 SmallVector<SCEVUse, 4> Operands;
3315 for (const SCEV *AddRecOp : AddRec->operands())
3316 Operands.push_back(getMulExpr(Ops[0], SCEVUse(AddRecOp),
3317 SCEV::FlagAnyWrap, Depth + 1));
3318 // Let M be the minimum representable signed value. AddRec with nsw
3319 // multiplied by -1 can have signed overflow if and only if it takes a
3320 // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3321 // maximum signed value. In all other cases signed overflow is
3322 // impossible.
3323 auto FlagsMask = SCEV::FlagNW;
3324 if (AddRec->hasNoSignedWrap()) {
3325 auto MinInt =
3326 APInt::getSignedMinValue(getTypeSizeInBits(AddRec->getType()));
3327 if (getSignedRangeMin(AddRec) != MinInt)
3328 FlagsMask = setFlags(FlagsMask, SCEV::FlagNSW);
3329 }
3330 return getAddRecExpr(Operands, AddRec->getLoop(),
3331 AddRec->getNoWrapFlags(FlagsMask));
3332 }
3333 }
3334
3335 // Try to push the constant operand into a ZExt: C * zext (A + B) ->
3336 // zext (C*A + C*B) if trunc (C) * (A + B) does not unsigned-wrap.
3337 const SCEVAddExpr *InnerAdd;
3338 if (match(Ops[1], m_scev_ZExt(m_scev_Add(InnerAdd)))) {
3339 const SCEV *NarrowC = getTruncateExpr(LHSC, InnerAdd->getType());
3340 if (isa<SCEVConstant>(InnerAdd->getOperand(0)) &&
3341 getZeroExtendExpr(NarrowC, Ops[1]->getType()) == LHSC &&
3342 hasFlags(StrengthenNoWrapFlags(this, scMulExpr, {NarrowC, InnerAdd},
3344 SCEV::FlagNUW)) {
3345 auto *Res = getMulExpr(NarrowC, InnerAdd, SCEV::FlagNUW, Depth + 1);
3346 return getZeroExtendExpr(Res, Ops[1]->getType(), Depth + 1);
3347 };
3348 }
3349
3350 // Try to fold (C1 * D /u C2) -> C1/C2 * D, if C1 and C2 are powers-of-2,
3351 // D is a multiple of C2, and C1 is a multiple of C2. If C2 is a multiple
3352 // of C1, fold to (D /u (C2 /u C1)).
3353 const SCEV *D;
3354 APInt C1V = LHSC->getAPInt();
3355 // (C1 * D /u C2) == -1 * -C1 * D /u C2 when C1 != INT_MIN. Don't treat -1
3356 // as -1 * 1, as it won't enable additional folds.
3357 if (C1V.isNegative() && !C1V.isMinSignedValue() && !C1V.isAllOnes())
3358 C1V = C1V.abs();
3359 const SCEVConstant *C2;
3360 if (C1V.isPowerOf2() &&
3362 C2->getAPInt().isPowerOf2() &&
3363 C1V.logBase2() <= getMinTrailingZeros(D)) {
3364 const SCEV *NewMul = nullptr;
3365 if (C1V.uge(C2->getAPInt())) {
3366 NewMul = getMulExpr(getUDivExpr(getConstant(C1V), C2), D);
3367 } else if (C2->getAPInt().logBase2() <= getMinTrailingZeros(D)) {
3368 assert(C1V.ugt(1) && "C1 <= 1 should have been folded earlier");
3369 NewMul = getUDivExpr(D, getUDivExpr(C2, getConstant(C1V)));
3370 }
3371 if (NewMul)
3372 return C1V == LHSC->getAPInt() ? NewMul : getNegativeSCEV(NewMul);
3373 }
3374 }
3375 }
3376
3377 // Skip over the add expression until we get to a multiply.
3378 unsigned Idx = 0;
3379 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3380 ++Idx;
3381
3382 // If there are mul operands inline them all into this expression.
3383 if (Idx < Ops.size()) {
3384 bool DeletedMul = false;
3385 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3386 if (Ops.size() > MulOpsInlineThreshold)
3387 break;
3388 // If we have an mul, expand the mul operands onto the end of the
3389 // operands list.
3390 Ops.erase(Ops.begin()+Idx);
3391 append_range(Ops, Mul->operands());
3392 DeletedMul = true;
3393 }
3394
3395 // If we deleted at least one mul, we added operands to the end of the
3396 // list, and they are not necessarily sorted. Recurse to resort and
3397 // resimplify any operands we just acquired.
3398 if (DeletedMul)
3399 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3400 }
3401
3402 // If there are any add recurrences in the operands list, see if any other
3403 // added values are loop invariant. If so, we can fold them into the
3404 // recurrence.
3405 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3406 ++Idx;
3407
3408 // Scan over all recurrences, trying to fold loop invariants into them.
3409 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3410 // Scan all of the other operands to this mul and add them to the vector
3411 // if they are loop invariant w.r.t. the recurrence.
3413 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3414 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3415 if (isAvailableAtLoopEntry(Ops[i], AddRec->getLoop())) {
3416 LIOps.push_back(Ops[i]);
3417 Ops.erase(Ops.begin()+i);
3418 --i; --e;
3419 }
3420
3421 // If we found some loop invariants, fold them into the recurrence.
3422 if (!LIOps.empty()) {
3423 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3425 NewOps.reserve(AddRec->getNumOperands());
3426 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3427
3428 // If both the mul and addrec are nuw, we can preserve nuw.
3429 // If both the mul and addrec are nsw, we can only preserve nsw if either
3430 // a) they are also nuw, or
3431 // b) all multiplications of addrec operands with scale are nsw.
3432 SCEV::NoWrapFlags Flags =
3433 AddRec->getNoWrapFlags(ComputeFlags({Scale, AddRec}));
3434
3435 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3436 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3437 SCEV::FlagAnyWrap, Depth + 1));
3438
3439 if (hasFlags(Flags, SCEV::FlagNSW) && !hasFlags(Flags, SCEV::FlagNUW)) {
3441 Instruction::Mul, getSignedRange(Scale),
3443 if (!NSWRegion.contains(getSignedRange(AddRec->getOperand(i))))
3444 Flags = clearFlags(Flags, SCEV::FlagNSW);
3445 }
3446 }
3447
3448 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(), Flags);
3449
3450 // If all of the other operands were loop invariant, we are done.
3451 if (Ops.size() == 1) return NewRec;
3452
3453 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3454 for (unsigned i = 0;; ++i)
3455 if (Ops[i] == AddRec) {
3456 Ops[i] = NewRec;
3457 break;
3458 }
3459 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3460 }
3461
3462 // Okay, if there weren't any loop invariants to be folded, check to see
3463 // if there are multiple AddRec's with the same loop induction variable
3464 // being multiplied together. If so, we can fold them.
3465
3466 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3467 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3468 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3469 // ]]],+,...up to x=2n}.
3470 // Note that the arguments to choose() are always integers with values
3471 // known at compile time, never SCEV objects.
3472 //
3473 // The implementation avoids pointless extra computations when the two
3474 // addrec's are of different length (mathematically, it's equivalent to
3475 // an infinite stream of zeros on the right).
3476 bool OpsModified = false;
3477 for (unsigned OtherIdx = Idx+1;
3478 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3479 ++OtherIdx) {
3480 const SCEVAddRecExpr *OtherAddRec =
3481 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3482 if (!OtherAddRec || OtherAddRec->getLoop() != AddRec->getLoop())
3483 continue;
3484
3485 // Limit max number of arguments to avoid creation of unreasonably big
3486 // SCEVAddRecs with very complex operands.
3487 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3488 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3489 continue;
3490
3491 bool Overflow = false;
3492 Type *Ty = AddRec->getType();
3493 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3494 SmallVector<SCEVUse, 7> AddRecOps;
3495 for (int x = 0, xe = AddRec->getNumOperands() +
3496 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3498 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3499 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3500 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3501 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3502 z < ze && !Overflow; ++z) {
3503 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3504 uint64_t Coeff;
3505 if (LargerThan64Bits)
3506 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3507 else
3508 Coeff = Coeff1*Coeff2;
3509 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3510 const SCEV *Term1 = AddRec->getOperand(y-z);
3511 const SCEV *Term2 = OtherAddRec->getOperand(z);
3512 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3513 SCEV::FlagAnyWrap, Depth + 1));
3514 }
3515 }
3516 if (SumOps.empty())
3517 SumOps.push_back(getZero(Ty));
3518 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3519 }
3520 if (!Overflow) {
3521 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
3523 if (Ops.size() == 2) return NewAddRec;
3524 Ops[Idx] = NewAddRec;
3525 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3526 OpsModified = true;
3527 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3528 if (!AddRec)
3529 break;
3530 }
3531 }
3532 if (OpsModified)
3533 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3534
3535 // Otherwise couldn't fold anything into this recurrence. Move onto the
3536 // next one.
3537 }
3538
3539 // Okay, it looks like we really DO need an mul expr. Check to see if we
3540 // already have one, otherwise create a new one.
3541 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3542}
3543
3544/// Represents an unsigned remainder expression based on unsigned division.
3546 assert(getEffectiveSCEVType(LHS->getType()) ==
3547 getEffectiveSCEVType(RHS->getType()) &&
3548 "SCEVURemExpr operand types don't match!");
3549
3550 // Short-circuit easy cases
3551 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3552 // If constant is one, the result is trivial
3553 if (RHSC->getValue()->isOne())
3554 return getZero(LHS->getType()); // X urem 1 --> 0
3555
3556 // If constant is a power of two, fold into a zext(trunc(LHS)).
3557 if (RHSC->getAPInt().isPowerOf2()) {
3558 Type *FullTy = LHS->getType();
3559 Type *TruncTy =
3560 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3561 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3562 }
3563 }
3564
3565 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3566 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3567 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3568 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3569}
3570
3571/// Get a canonical unsigned division expression, or something simpler if
3572/// possible.
3574 assert(!LHS->getType()->isPointerTy() &&
3575 "SCEVUDivExpr operand can't be pointer!");
3576 assert(LHS->getType() == RHS->getType() &&
3577 "SCEVUDivExpr operand types don't match!");
3578
3580 ID.AddInteger(scUDivExpr);
3581 ID.AddPointer(LHS);
3582 ID.AddPointer(RHS);
3583 void *IP = nullptr;
3584 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3585 return S;
3586
3587 // 0 udiv Y == 0
3588 if (match(LHS, m_scev_Zero()))
3589 return LHS;
3590
3591 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3592 if (RHSC->getValue()->isOne())
3593 return LHS; // X udiv 1 --> x
3594 // If the denominator is zero, the result of the udiv is undefined. Don't
3595 // try to analyze it, because the resolution chosen here may differ from
3596 // the resolution chosen in other parts of the compiler.
3597 if (!RHSC->getValue()->isZero()) {
3598 // Determine if the division can be folded into the operands of
3599 // its operands.
3600 // TODO: Generalize this to non-constants by using known-bits information.
3601 Type *Ty = LHS->getType();
3602 unsigned LZ = RHSC->getAPInt().countl_zero();
3603 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3604 // For non-power-of-two values, effectively round the value up to the
3605 // nearest power of two.
3606 if (!RHSC->getAPInt().isPowerOf2())
3607 ++MaxShiftAmt;
3608 IntegerType *ExtTy =
3609 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3610 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3611 if (const SCEVConstant *Step =
3612 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3613 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3614 const APInt &StepInt = Step->getAPInt();
3615 const APInt &DivInt = RHSC->getAPInt();
3616 if (!StepInt.urem(DivInt) &&
3617 getZeroExtendExpr(AR, ExtTy) ==
3618 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3619 getZeroExtendExpr(Step, ExtTy),
3620 AR->getLoop(), SCEV::FlagAnyWrap)) {
3621 SmallVector<SCEVUse, 4> Operands;
3622 for (const SCEV *Op : AR->operands())
3623 Operands.push_back(getUDivExpr(Op, RHS));
3624 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3625 }
3626 /// Get a canonical UDivExpr for a recurrence.
3627 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3628 const APInt *StartRem;
3629 if (!DivInt.urem(StepInt) && match(getURemExpr(AR->getStart(), Step),
3630 m_scev_APInt(StartRem))) {
3631 bool NoWrap =
3632 getZeroExtendExpr(AR, ExtTy) ==
3633 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3634 getZeroExtendExpr(Step, ExtTy), AR->getLoop(),
3636
3637 // With N <= C and both N, C as powers-of-2, the transformation
3638 // {X,+,N}/C => {(X - X%N),+,N}/C preserves division results even
3639 // if wrapping occurs, as the division results remain equivalent for
3640 // all offsets in [[(X - X%N), X).
3641 bool CanFoldWithWrap = StepInt.ule(DivInt) && // N <= C
3642 StepInt.isPowerOf2() && DivInt.isPowerOf2();
3643 // Only fold if the subtraction can be folded in the start
3644 // expression.
3645 const SCEV *NewStart =
3646 getMinusSCEV(AR->getStart(), getConstant(*StartRem));
3647 if (*StartRem != 0 && (NoWrap || CanFoldWithWrap) &&
3648 !isa<SCEVAddExpr>(NewStart)) {
3649 const SCEV *NewLHS =
3650 getAddRecExpr(NewStart, Step, AR->getLoop(),
3651 NoWrap ? SCEV::FlagNW : SCEV::FlagAnyWrap);
3652 if (LHS != NewLHS) {
3653 LHS = NewLHS;
3654
3655 // Reset the ID to include the new LHS, and check if it is
3656 // already cached.
3657 ID.clear();
3658 ID.AddInteger(scUDivExpr);
3659 ID.AddPointer(LHS);
3660 ID.AddPointer(RHS);
3661 IP = nullptr;
3662 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3663 return S;
3664 }
3665 }
3666 }
3667 }
3668 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3669 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3670 SmallVector<SCEVUse, 4> Operands;
3671 for (const SCEV *Op : M->operands())
3672 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3673 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) {
3674 // Find an operand that's safely divisible.
3675 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3676 const SCEV *Op = M->getOperand(i);
3677 const SCEV *Div = getUDivExpr(Op, RHSC);
3678 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3679 Operands = SmallVector<SCEVUse, 4>(M->operands());
3680 Operands[i] = Div;
3681 return getMulExpr(Operands);
3682 }
3683 }
3684
3685 // Even if it's not divisible, try to remove a common factor.
3686 if (const auto *LHSC = dyn_cast<SCEVConstant>(M->getOperand(0))) {
3687 APInt Factor = APIntOps::GreatestCommonDivisor(LHSC->getAPInt(),
3688 RHSC->getAPInt());
3689 if (!Factor.isIntN(1)) {
3690 SmallVector<SCEVUse, 2> NewOperands;
3691 NewOperands.push_back(getConstant(LHSC->getAPInt().udiv(Factor)));
3692 append_range(NewOperands, M->operands().drop_front());
3693 const SCEV *NewMul = getMulExpr(NewOperands);
3694 return getUDivExpr(NewMul,
3695 getConstant(RHSC->getAPInt().udiv(Factor)));
3696 }
3697 }
3698 }
3699 }
3700
3701 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3702 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3703 if (auto *DivisorConstant =
3704 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3705 bool Overflow = false;
3706 APInt NewRHS =
3707 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3708 if (Overflow) {
3709 return getConstant(RHSC->getType(), 0, false);
3710 }
3711 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3712 }
3713 }
3714
3715 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3716 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3717 SmallVector<SCEVUse, 4> Operands;
3718 for (const SCEV *Op : A->operands())
3719 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3720 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3721 Operands.clear();
3722 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3723 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3724 if (isa<SCEVUDivExpr>(Op) ||
3725 getMulExpr(Op, RHS) != A->getOperand(i))
3726 break;
3727 Operands.push_back(Op);
3728 }
3729 if (Operands.size() == A->getNumOperands())
3730 return getAddExpr(Operands);
3731 }
3732 }
3733
3734 // ((N - M) + (M * A)) / N --> ((N - 1) + (M * A)) / N
3735 // This is an idiom for rounding A up to the next multiple of N, where A
3736 // is aready known to be a multiple of M. In this case, instcombine can
3737 // see that some low bits of the added constant are unused, so can clear
3738 // them, but we want to canonicalise to set the low bits. This makes the
3739 // pattern easier to match, without needing to check for known bits in
3740 // A*M.
3741 const APInt &N = RHSC->getAPInt();
3742 const APInt *NMinusM, *M;
3743 const SCEV *A;
3744 if (match(LHS, m_scev_Add(m_scev_APInt(NMinusM),
3745 m_scev_Mul(m_scev_APInt(M), m_SCEV(A))))) {
3746 if (N.isPowerOf2() && M->isPowerOf2() && M->ult(N) &&
3747 *NMinusM == N - *M) {
3748 return getUDivExpr(
3750 RHS);
3751 }
3752 }
3753
3754 // Fold if both operands are constant.
3755 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3756 return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3757 }
3758 }
3759
3760 // ((-C + (C smax %x)) /u %x) evaluates to zero, for any positive constant C.
3761 const APInt *NegC, *C;
3762 if (match(LHS,
3765 NegC->isNegative() && !NegC->isMinSignedValue() && *C == -*NegC)
3766 return getZero(LHS->getType());
3767
3768 // (%a * %b)<nuw> / %b -> %a
3769 const auto *Mul = dyn_cast<SCEVMulExpr>(LHS);
3770 if (Mul && Mul->hasNoUnsignedWrap()) {
3771 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3772 if (Mul->getOperand(i) == RHS) {
3773 SmallVector<SCEVUse, 2> Operands;
3774 append_range(Operands, Mul->operands().take_front(i));
3775 append_range(Operands, Mul->operands().drop_front(i + 1));
3776 return getMulExpr(Operands);
3777 }
3778 }
3779 }
3780
3781 // TODO: Generalize to handle any common factors.
3782 // udiv (mul nuw a, vscale), (mul nuw b, vscale) --> udiv a, b
3783 const SCEV *NewLHS, *NewRHS;
3784 if (match(LHS, m_scev_c_NUWMul(m_SCEV(NewLHS), m_SCEVVScale())) &&
3785 match(RHS, m_scev_c_NUWMul(m_SCEV(NewRHS), m_SCEVVScale())))
3786 return getUDivExpr(NewLHS, NewRHS);
3787
3788 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3789 // changes). Make sure we get a new one.
3790 IP = nullptr;
3791 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3792 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3793 LHS, RHS);
3794 UniqueSCEVs.InsertNode(S, IP);
3795 S->computeAndSetCanonical(*this);
3796 registerUser(S, ArrayRef<SCEVUse>({LHS, RHS}));
3797 return S;
3798}
3799
3800APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3801 APInt A = C1->getAPInt().abs();
3802 APInt B = C2->getAPInt().abs();
3803 uint32_t ABW = A.getBitWidth();
3804 uint32_t BBW = B.getBitWidth();
3805
3806 if (ABW > BBW)
3807 B = B.zext(ABW);
3808 else if (ABW < BBW)
3809 A = A.zext(BBW);
3810
3811 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3812}
3813
3814/// Get a canonical unsigned division expression, or something simpler if
3815/// possible. There is no representation for an exact udiv in SCEV IR, but we
3816/// can attempt to optimize it prior to construction.
3818 // Currently there is no exact specific logic.
3819
3820 return getUDivExpr(LHS, RHS);
3821}
3822
3823/// Get an add recurrence expression for the specified loop. Simplify the
3824/// expression as much as possible.
3826 const Loop *L,
3827 SCEV::NoWrapFlags Flags) {
3828 SmallVector<SCEVUse, 4> Operands;
3829 Operands.push_back(Start);
3830 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3831 if (StepChrec->getLoop() == L) {
3832 append_range(Operands, StepChrec->operands());
3833 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3834 }
3835
3836 Operands.push_back(Step);
3837 return getAddRecExpr(Operands, L, Flags);
3838}
3839
3840/// Get an add recurrence expression for the specified loop. Simplify the
3841/// expression as much as possible.
3843 const Loop *L,
3844 SCEV::NoWrapFlags Flags) {
3845 if (Operands.size() == 1) return Operands[0];
3846#ifndef NDEBUG
3847 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3848 for (const SCEV *Op : llvm::drop_begin(Operands)) {
3849 assert(getEffectiveSCEVType(Op->getType()) == ETy &&
3850 "SCEVAddRecExpr operand types don't match!");
3851 assert(!Op->getType()->isPointerTy() && "Step must be integer");
3852 }
3853 for (const SCEV *Op : Operands)
3855 "SCEVAddRecExpr operand is not available at loop entry!");
3856#endif
3857
3858 if (Operands.back()->isZero()) {
3859 Operands.pop_back();
3860 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3861 }
3862
3863 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3864 // use that information to infer NUW and NSW flags. However, computing a
3865 // BE count requires calling getAddRecExpr, so we may not yet have a
3866 // meaningful BE count at this point (and if we don't, we'd be stuck
3867 // with a SCEVCouldNotCompute as the cached BE count).
3868
3869 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3870
3871 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3872 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3873 const Loop *NestedLoop = NestedAR->getLoop();
3874 if (L->contains(NestedLoop)
3875 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3876 : (!NestedLoop->contains(L) &&
3877 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3878 SmallVector<SCEVUse, 4> NestedOperands(NestedAR->operands());
3879 Operands[0] = NestedAR->getStart();
3880 // AddRecs require their operands be loop-invariant with respect to their
3881 // loops. Don't perform this transformation if it would break this
3882 // requirement.
3883 bool AllInvariant = all_of(
3884 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3885
3886 if (AllInvariant) {
3887 // Create a recurrence for the outer loop with the same step size.
3888 //
3889 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3890 // inner recurrence has the same property.
3891 SCEV::NoWrapFlags OuterFlags =
3892 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3893
3894 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3895 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3896 return isLoopInvariant(Op, NestedLoop);
3897 });
3898
3899 if (AllInvariant) {
3900 // Ok, both add recurrences are valid after the transformation.
3901 //
3902 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3903 // the outer recurrence has the same property.
3904 SCEV::NoWrapFlags InnerFlags =
3905 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3906 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3907 }
3908 }
3909 // Reset Operands to its original state.
3910 Operands[0] = NestedAR;
3911 }
3912 }
3913
3914 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3915 // already have one, otherwise create a new one.
3916 return getOrCreateAddRecExpr(Operands, L, Flags);
3917}
3918
3920 ArrayRef<SCEVUse> IndexExprs) {
3921 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3922 // getSCEV(Base)->getType() has the same address space as Base->getType()
3923 // because SCEV::getType() preserves the address space.
3924 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
3925 if (NW != GEPNoWrapFlags::none()) {
3926 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3927 // but to do that, we have to ensure that said flag is valid in the entire
3928 // defined scope of the SCEV.
3929 // TODO: non-instructions have global scope. We might be able to prove
3930 // some global scope cases
3931 auto *GEPI = dyn_cast<Instruction>(GEP);
3932 if (!GEPI || !isSCEVExprNeverPoison(GEPI))
3933 NW = GEPNoWrapFlags::none();
3934 }
3935
3936 return getGEPExpr(BaseExpr, IndexExprs, GEP->getSourceElementType(), NW);
3937}
3938
3940 ArrayRef<SCEVUse> IndexExprs,
3941 Type *SrcElementTy, GEPNoWrapFlags NW) {
3943 if (NW.hasNoUnsignedSignedWrap())
3944 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNSW);
3945 if (NW.hasNoUnsignedWrap())
3946 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNUW);
3947
3948 Type *CurTy = BaseExpr->getType();
3949 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3950 bool FirstIter = true;
3952 for (SCEVUse IndexExpr : IndexExprs) {
3953 // Compute the (potentially symbolic) offset in bytes for this index.
3954 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3955 // For a struct, add the member offset.
3956 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3957 unsigned FieldNo = Index->getZExtValue();
3958 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3959 Offsets.push_back(FieldOffset);
3960
3961 // Update CurTy to the type of the field at Index.
3962 CurTy = STy->getTypeAtIndex(Index);
3963 } else {
3964 // Update CurTy to its element type.
3965 if (FirstIter) {
3966 assert(isa<PointerType>(CurTy) &&
3967 "The first index of a GEP indexes a pointer");
3968 CurTy = SrcElementTy;
3969 FirstIter = false;
3970 } else {
3972 }
3973 // For an array, add the element offset, explicitly scaled.
3974 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3975 // Getelementptr indices are signed.
3976 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3977
3978 // Multiply the index by the element size to compute the element offset.
3979 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3980 Offsets.push_back(LocalOffset);
3981 }
3982 }
3983
3984 // Handle degenerate case of GEP without offsets.
3985 if (Offsets.empty())
3986 return BaseExpr;
3987
3988 // Add the offsets together, assuming nsw if inbounds.
3989 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3990 // Add the base address and the offset. We cannot use the nsw flag, as the
3991 // base address is unsigned. However, if we know that the offset is
3992 // non-negative, we can use nuw.
3993 bool NUW = NW.hasNoUnsignedWrap() ||
3996 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3997 assert(BaseExpr->getType() == GEPExpr->getType() &&
3998 "GEP should not change type mid-flight.");
3999 return GEPExpr;
4000}
4001
4002SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
4005 ID.AddInteger(SCEVType);
4006 for (const SCEV *Op : Ops)
4007 ID.AddPointer(Op);
4008 void *IP = nullptr;
4009 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4010}
4011
4012SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
4015 ID.AddInteger(SCEVType);
4016 for (const SCEV *Op : Ops)
4017 ID.AddPointer(Op);
4018 void *IP = nullptr;
4019 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4020}
4021
4022const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
4024 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
4025}
4026
4029 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
4030 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4031 if (Ops.size() == 1) return Ops[0];
4032#ifndef NDEBUG
4033 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4034 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4035 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4036 "Operand types don't match!");
4037 assert(Ops[0]->getType()->isPointerTy() ==
4038 Ops[i]->getType()->isPointerTy() &&
4039 "min/max should be consistently pointerish");
4040 }
4041#endif
4042
4043 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
4044 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
4045
4046 const SCEV *Folded = constantFoldAndGroupOps(
4047 *this, LI, DT, Ops,
4048 [&](const APInt &C1, const APInt &C2) {
4049 switch (Kind) {
4050 case scSMaxExpr:
4051 return APIntOps::smax(C1, C2);
4052 case scSMinExpr:
4053 return APIntOps::smin(C1, C2);
4054 case scUMaxExpr:
4055 return APIntOps::umax(C1, C2);
4056 case scUMinExpr:
4057 return APIntOps::umin(C1, C2);
4058 default:
4059 llvm_unreachable("Unknown SCEV min/max opcode");
4060 }
4061 },
4062 [&](const APInt &C) {
4063 // identity
4064 if (IsMax)
4065 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
4066 else
4067 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
4068 },
4069 [&](const APInt &C) {
4070 // absorber
4071 if (IsMax)
4072 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
4073 else
4074 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
4075 });
4076 if (Folded)
4077 return Folded;
4078
4079 // Check if we have created the same expression before.
4080 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
4081 return S;
4082 }
4083
4084 // Find the first operation of the same kind
4085 unsigned Idx = 0;
4086 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
4087 ++Idx;
4088
4089 // Check to see if one of the operands is of the same kind. If so, expand its
4090 // operands onto our operand list, and recurse to simplify.
4091 if (Idx < Ops.size()) {
4092 bool DeletedAny = false;
4093 while (Ops[Idx]->getSCEVType() == Kind) {
4094 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
4095 Ops.erase(Ops.begin()+Idx);
4096 append_range(Ops, SMME->operands());
4097 DeletedAny = true;
4098 }
4099
4100 if (DeletedAny)
4101 return getMinMaxExpr(Kind, Ops);
4102 }
4103
4104 // Okay, check to see if the same value occurs in the operand list twice. If
4105 // so, delete one. Since we sorted the list, these values are required to
4106 // be adjacent.
4111 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
4112 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
4113 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
4114 if (Ops[i] == Ops[i + 1] ||
4115 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
4116 // X op Y op Y --> X op Y
4117 // X op Y --> X, if we know X, Y are ordered appropriately
4118 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
4119 --i;
4120 --e;
4121 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
4122 Ops[i + 1])) {
4123 // X op Y --> Y, if we know X, Y are ordered appropriately
4124 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
4125 --i;
4126 --e;
4127 }
4128 }
4129
4130 if (Ops.size() == 1) return Ops[0];
4131
4132 assert(!Ops.empty() && "Reduced smax down to nothing!");
4133
4134 // Okay, it looks like we really DO need an expr. Check to see if we
4135 // already have one, otherwise create a new one.
4137 ID.AddInteger(Kind);
4138 for (const SCEV *Op : Ops)
4139 ID.AddPointer(Op);
4140 void *IP = nullptr;
4141 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4142 if (ExistingSCEV)
4143 return ExistingSCEV;
4144 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4146 SCEV *S = new (SCEVAllocator)
4147 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4148
4149 UniqueSCEVs.InsertNode(S, IP);
4150 S->computeAndSetCanonical(*this);
4151 registerUser(S, Ops);
4152 return S;
4153}
4154
4155namespace {
4156
4157class SCEVSequentialMinMaxDeduplicatingVisitor final
4158 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
4159 std::optional<const SCEV *>> {
4160 using RetVal = std::optional<const SCEV *>;
4162
4163 ScalarEvolution &SE;
4164 const SCEVTypes RootKind; // Must be a sequential min/max expression.
4165 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
4167
4168 bool canRecurseInto(SCEVTypes Kind) const {
4169 // We can only recurse into the SCEV expression of the same effective type
4170 // as the type of our root SCEV expression.
4171 return RootKind == Kind || NonSequentialRootKind == Kind;
4172 };
4173
4174 RetVal visitAnyMinMaxExpr(const SCEV *S) {
4176 "Only for min/max expressions.");
4177 SCEVTypes Kind = S->getSCEVType();
4178
4179 if (!canRecurseInto(Kind))
4180 return S;
4181
4182 auto *NAry = cast<SCEVNAryExpr>(S);
4183 SmallVector<SCEVUse> NewOps;
4184 bool Changed = visit(Kind, NAry->operands(), NewOps);
4185
4186 if (!Changed)
4187 return S;
4188 if (NewOps.empty())
4189 return std::nullopt;
4190
4192 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
4193 : SE.getMinMaxExpr(Kind, NewOps);
4194 }
4195
4196 RetVal visit(const SCEV *S) {
4197 // Has the whole operand been seen already?
4198 if (!SeenOps.insert(S).second)
4199 return std::nullopt;
4200 return Base::visit(S);
4201 }
4202
4203public:
4204 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
4205 SCEVTypes RootKind)
4206 : SE(SE), RootKind(RootKind),
4207 NonSequentialRootKind(
4208 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4209 RootKind)) {}
4210
4211 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<SCEVUse> OrigOps,
4212 SmallVectorImpl<SCEVUse> &NewOps) {
4213 bool Changed = false;
4215 Ops.reserve(OrigOps.size());
4216
4217 for (const SCEV *Op : OrigOps) {
4218 RetVal NewOp = visit(Op);
4219 if (NewOp != Op)
4220 Changed = true;
4221 if (NewOp)
4222 Ops.emplace_back(*NewOp);
4223 }
4224
4225 if (Changed)
4226 NewOps = std::move(Ops);
4227 return Changed;
4228 }
4229
4230 RetVal visitConstant(const SCEVConstant *Constant) { return Constant; }
4231
4232 RetVal visitVScale(const SCEVVScale *VScale) { return VScale; }
4233
4234 RetVal visitPtrToAddrExpr(const SCEVPtrToAddrExpr *Expr) { return Expr; }
4235
4236 RetVal visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) { return Expr; }
4237
4238 RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
4239
4240 RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; }
4241
4242 RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; }
4243
4244 RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; }
4245
4246 RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; }
4247
4248 RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
4249
4250 RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
4251
4252 RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) {
4253 return visitAnyMinMaxExpr(Expr);
4254 }
4255
4256 RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) {
4257 return visitAnyMinMaxExpr(Expr);
4258 }
4259
4260 RetVal visitSMinExpr(const SCEVSMinExpr *Expr) {
4261 return visitAnyMinMaxExpr(Expr);
4262 }
4263
4264 RetVal visitUMinExpr(const SCEVUMinExpr *Expr) {
4265 return visitAnyMinMaxExpr(Expr);
4266 }
4267
4268 RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
4269 return visitAnyMinMaxExpr(Expr);
4270 }
4271
4272 RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; }
4273
4274 RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; }
4275};
4276
4277} // namespace
4278
4280 switch (Kind) {
4281 case scConstant:
4282 case scVScale:
4283 case scTruncate:
4284 case scZeroExtend:
4285 case scSignExtend:
4286 case scPtrToAddr:
4287 case scPtrToInt:
4288 case scAddExpr:
4289 case scMulExpr:
4290 case scUDivExpr:
4291 case scAddRecExpr:
4292 case scUMaxExpr:
4293 case scSMaxExpr:
4294 case scUMinExpr:
4295 case scSMinExpr:
4296 case scUnknown:
4297 // If any operand is poison, the whole expression is poison.
4298 return true;
4300 // FIXME: if the *first* operand is poison, the whole expression is poison.
4301 return false; // Pessimistically, say that it does not propagate poison.
4302 case scCouldNotCompute:
4303 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4304 }
4305 llvm_unreachable("Unknown SCEV kind!");
4306}
4307
4308namespace {
4309// The only way poison may be introduced in a SCEV expression is from a
4310// poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4311// not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not*
4312// introduce poison -- they encode guaranteed, non-speculated knowledge.
4313//
4314// Additionally, all SCEV nodes propagate poison from inputs to outputs,
4315// with the notable exception of umin_seq, where only poison from the first
4316// operand is (unconditionally) propagated.
4317struct SCEVPoisonCollector {
4318 bool LookThroughMaybePoisonBlocking;
4319 SmallPtrSet<const SCEVUnknown *, 4> MaybePoison;
4320 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4321 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4322
4323 bool follow(const SCEV *S) {
4324 if (!LookThroughMaybePoisonBlocking &&
4326 return false;
4327
4328 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4329 if (!isGuaranteedNotToBePoison(SU->getValue()))
4330 MaybePoison.insert(SU);
4331 }
4332 return true;
4333 }
4334 bool isDone() const { return false; }
4335};
4336} // namespace
4337
4338/// Return true if V is poison given that AssumedPoison is already poison.
4339static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4340 // First collect all SCEVs that might result in AssumedPoison to be poison.
4341 // We need to look through potentially poison-blocking operations here,
4342 // because we want to find all SCEVs that *might* result in poison, not only
4343 // those that are *required* to.
4344 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4345 visitAll(AssumedPoison, PC1);
4346
4347 // AssumedPoison is never poison. As the assumption is false, the implication
4348 // is true. Don't bother walking the other SCEV in this case.
4349 if (PC1.MaybePoison.empty())
4350 return true;
4351
4352 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4353 // as well. We cannot look through potentially poison-blocking operations
4354 // here, as their arguments only *may* make the result poison.
4355 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4356 visitAll(S, PC2);
4357
4358 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4359 // it will also make S poison by being part of PC2.MaybePoison.
4360 return llvm::set_is_subset(PC1.MaybePoison, PC2.MaybePoison);
4361}
4362
4364 SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4365 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4366 visitAll(S, PC);
4367 for (const SCEVUnknown *SU : PC.MaybePoison)
4368 Result.insert(SU->getValue());
4369}
4370
4372 const SCEV *S, Instruction *I,
4373 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
4374 // If the instruction cannot be poison, it's always safe to reuse.
4376 return true;
4377
4378 // Otherwise, it is possible that I is more poisonous that S. Collect the
4379 // poison-contributors of S, and then check whether I has any additional
4380 // poison-contributors. Poison that is contributed through poison-generating
4381 // flags is handled by dropping those flags instead.
4383 getPoisonGeneratingValues(PoisonVals, S);
4384
4385 SmallVector<Value *> Worklist;
4387 Worklist.push_back(I);
4388 while (!Worklist.empty()) {
4389 Value *V = Worklist.pop_back_val();
4390 if (!Visited.insert(V).second)
4391 continue;
4392
4393 // Avoid walking large instruction graphs.
4394 if (Visited.size() > 16)
4395 return false;
4396
4397 // Either the value can't be poison, or the S would also be poison if it
4398 // is.
4399 if (PoisonVals.contains(V) || ::isGuaranteedNotToBePoison(V))
4400 continue;
4401
4402 auto *I = dyn_cast<Instruction>(V);
4403 if (!I)
4404 return false;
4405
4406 // Disjoint or instructions are interpreted as adds by SCEV. However, we
4407 // can't replace an arbitrary add with disjoint or, even if we drop the
4408 // flag. We would need to convert the or into an add.
4409 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
4410 if (PDI->isDisjoint())
4411 return false;
4412
4413 // FIXME: Ignore vscale, even though it technically could be poison. Do this
4414 // because SCEV currently assumes it can't be poison. Remove this special
4415 // case once we proper model when vscale can be poison.
4416 if (auto *II = dyn_cast<IntrinsicInst>(I);
4417 II && II->getIntrinsicID() == Intrinsic::vscale)
4418 continue;
4419
4420 if (canCreatePoison(cast<Operator>(I), /*ConsiderFlagsAndMetadata*/ false))
4421 return false;
4422
4423 // If the instruction can't create poison, we can recurse to its operands.
4424 if (I->hasPoisonGeneratingAnnotations())
4425 DropPoisonGeneratingInsts.push_back(I);
4426
4427 llvm::append_range(Worklist, I->operands());
4428 }
4429 return true;
4430}
4431
4432const SCEV *
4435 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4436 "Not a SCEVSequentialMinMaxExpr!");
4437 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4438 if (Ops.size() == 1)
4439 return Ops[0];
4440#ifndef NDEBUG
4441 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4442 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4443 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4444 "Operand types don't match!");
4445 assert(Ops[0]->getType()->isPointerTy() ==
4446 Ops[i]->getType()->isPointerTy() &&
4447 "min/max should be consistently pointerish");
4448 }
4449#endif
4450
4451 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4452 // so we can *NOT* do any kind of sorting of the expressions!
4453
4454 // Check if we have created the same expression before.
4455 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4456 return S;
4457
4458 // FIXME: there are *some* simplifications that we can do here.
4459
4460 // Keep only the first instance of an operand.
4461 {
4462 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4463 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4464 if (Changed)
4465 return getSequentialMinMaxExpr(Kind, Ops);
4466 }
4467
4468 // Check to see if one of the operands is of the same kind. If so, expand its
4469 // operands onto our operand list, and recurse to simplify.
4470 {
4471 unsigned Idx = 0;
4472 bool DeletedAny = false;
4473 while (Idx < Ops.size()) {
4474 if (Ops[Idx]->getSCEVType() != Kind) {
4475 ++Idx;
4476 continue;
4477 }
4478 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4479 Ops.erase(Ops.begin() + Idx);
4480 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4481 SMME->operands().end());
4482 DeletedAny = true;
4483 }
4484
4485 if (DeletedAny)
4486 return getSequentialMinMaxExpr(Kind, Ops);
4487 }
4488
4489 const SCEV *SaturationPoint;
4491 switch (Kind) {
4493 SaturationPoint = getZero(Ops[0]->getType());
4494 Pred = ICmpInst::ICMP_ULE;
4495 break;
4496 default:
4497 llvm_unreachable("Not a sequential min/max type.");
4498 }
4499
4500 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4501 if (!isGuaranteedNotToCauseUB(Ops[i]))
4502 continue;
4503 // We can replace %x umin_seq %y with %x umin %y if either:
4504 // * %y being poison implies %x is also poison.
4505 // * %x cannot be the saturating value (e.g. zero for umin).
4506 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4507 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4508 SaturationPoint)) {
4509 SmallVector<SCEVUse, 2> SeqOps = {Ops[i - 1], Ops[i]};
4510 Ops[i - 1] = getMinMaxExpr(
4512 SeqOps);
4513 Ops.erase(Ops.begin() + i);
4514 return getSequentialMinMaxExpr(Kind, Ops);
4515 }
4516 // Fold %x umin_seq %y to %x if %x ule %y.
4517 // TODO: We might be able to prove the predicate for a later operand.
4518 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4519 Ops.erase(Ops.begin() + i);
4520 return getSequentialMinMaxExpr(Kind, Ops);
4521 }
4522 }
4523
4524 // Okay, it looks like we really DO need an expr. Check to see if we
4525 // already have one, otherwise create a new one.
4527 ID.AddInteger(Kind);
4528 for (const SCEV *Op : Ops)
4529 ID.AddPointer(Op);
4530 void *IP = nullptr;
4531 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4532 if (ExistingSCEV)
4533 return ExistingSCEV;
4534
4535 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4537 SCEV *S = new (SCEVAllocator)
4538 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4539
4540 UniqueSCEVs.InsertNode(S, IP);
4541 S->computeAndSetCanonical(*this);
4542 registerUser(S, Ops);
4543 return S;
4544}
4545
4550
4554
4559
4563
4568
4572
4574 bool Sequential) {
4575 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4576 return getUMinExpr(Ops, Sequential);
4577}
4578
4584
4585const SCEV *
4587 const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4588 if (Size.isScalable())
4589 Res = getMulExpr(Res, getVScale(IntTy));
4590 return Res;
4591}
4592
4594 return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4595}
4596
4598 return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4599}
4600
4602 StructType *STy,
4603 unsigned FieldNo) {
4604 // We can bypass creating a target-independent constant expression and then
4605 // folding it back into a ConstantInt. This is just a compile-time
4606 // optimization.
4607 const StructLayout *SL = getDataLayout().getStructLayout(STy);
4608 assert(!SL->getSizeInBits().isScalable() &&
4609 "Cannot get offset for structure containing scalable vector types");
4610 return getConstant(IntTy, SL->getElementOffset(FieldNo));
4611}
4612
4614 // Don't attempt to do anything other than create a SCEVUnknown object
4615 // here. createSCEV only calls getUnknown after checking for all other
4616 // interesting possibilities, and any other code that calls getUnknown
4617 // is doing so in order to hide a value from SCEV canonicalization.
4618
4620 ID.AddInteger(scUnknown);
4621 ID.AddPointer(V);
4622 void *IP = nullptr;
4623 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
4624 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4625 "Stale SCEVUnknown in uniquing map!");
4626 return S;
4627 }
4628 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4629 FirstUnknown);
4630 FirstUnknown = cast<SCEVUnknown>(S);
4631 UniqueSCEVs.InsertNode(S, IP);
4632 S->computeAndSetCanonical(*this);
4633 return S;
4634}
4635
4636//===----------------------------------------------------------------------===//
4637// Basic SCEV Analysis and PHI Idiom Recognition Code
4638//
4639
4640/// Test if values of the given type are analyzable within the SCEV
4641/// framework. This primarily includes integer types, and it can optionally
4642/// include pointer types if the ScalarEvolution class has access to
4643/// target-specific information.
4645 // Integers and pointers are always SCEVable.
4646 return Ty->isIntOrPtrTy();
4647}
4648
4649/// Return the size in bits of the specified type, for which isSCEVable must
4650/// return true.
4652 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4653 if (Ty->isPointerTy())
4655 return getDataLayout().getTypeSizeInBits(Ty);
4656}
4657
4658/// Return a type with the same bitwidth as the given type and which represents
4659/// how SCEV will treat the given type, for which isSCEVable must return
4660/// true. For pointer types, this is the pointer index sized integer type.
4662 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4663
4664 if (Ty->isIntegerTy())
4665 return Ty;
4666
4667 // The only other support type is pointer.
4668 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4669 return getDataLayout().getIndexType(Ty);
4670}
4671
4673 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4674}
4675
4677 const SCEV *B) {
4678 /// For a valid use point to exist, the defining scope of one operand
4679 /// must dominate the other.
4680 bool PreciseA, PreciseB;
4681 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4682 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4683 if (!PreciseA || !PreciseB)
4684 // Can't tell.
4685 return false;
4686 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4687 DT.dominates(ScopeB, ScopeA);
4688}
4689
4691 return CouldNotCompute.get();
4692}
4693
4694bool ScalarEvolution::checkValidity(const SCEV *S) const {
4695 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4696 auto *SU = dyn_cast<SCEVUnknown>(S);
4697 return SU && SU->getValue() == nullptr;
4698 });
4699
4700 return !ContainsNulls;
4701}
4702
4704 HasRecMapType::iterator I = HasRecMap.find(S);
4705 if (I != HasRecMap.end())
4706 return I->second;
4707
4708 bool FoundAddRec =
4709 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4710 HasRecMap.insert({S, FoundAddRec});
4711 return FoundAddRec;
4712}
4713
4714/// Return the ValueOffsetPair set for \p S. \p S can be represented
4715/// by the value and offset from any ValueOffsetPair in the set.
4716ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4717 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4718 if (SI == ExprValueMap.end())
4719 return {};
4720 return SI->second.getArrayRef();
4721}
4722
4723/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4724/// cannot be used separately. eraseValueFromMap should be used to remove
4725/// V from ValueExprMap and ExprValueMap at the same time.
4726void ScalarEvolution::eraseValueFromMap(Value *V) {
4727 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4728 if (I != ValueExprMap.end()) {
4729 auto EVIt = ExprValueMap.find(I->second);
4730 bool Removed = EVIt->second.remove(V);
4731 (void) Removed;
4732 assert(Removed && "Value not in ExprValueMap?");
4733 ValueExprMap.erase(I);
4734 }
4735}
4736
4737void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4738 // A recursive query may have already computed the SCEV. It should be
4739 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4740 // inferred nowrap flags.
4741 auto It = ValueExprMap.find_as(V);
4742 if (It == ValueExprMap.end()) {
4743 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4744 ExprValueMap[S].insert(V);
4745 }
4746}
4747
4748/// Return an existing SCEV if it exists, otherwise analyze the expression and
4749/// create a new one.
4751 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4752
4753 if (const SCEV *S = getExistingSCEV(V))
4754 return S;
4755 return createSCEVIter(V);
4756}
4757
4759 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4760
4761 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4762 if (I != ValueExprMap.end()) {
4763 const SCEV *S = I->second;
4764 assert(checkValidity(S) &&
4765 "existing SCEV has not been properly invalidated");
4766 return S;
4767 }
4768 return nullptr;
4769}
4770
4771/// Return a SCEV corresponding to -V = -1*V
4773 SCEV::NoWrapFlags Flags) {
4774 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4775 return getConstant(
4776 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4777
4778 Type *Ty = V->getType();
4779 Ty = getEffectiveSCEVType(Ty);
4780 return getMulExpr(V, getMinusOne(Ty), Flags);
4781}
4782
4783/// If Expr computes ~A, return A else return nullptr
4784static const SCEV *MatchNotExpr(const SCEV *Expr) {
4785 const SCEV *MulOp;
4786 if (match(Expr, m_scev_Add(m_scev_AllOnes(),
4787 m_scev_Mul(m_scev_AllOnes(), m_SCEV(MulOp)))))
4788 return MulOp;
4789 return nullptr;
4790}
4791
4792/// Return a SCEV corresponding to ~V = -1-V
4794 assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4795
4796 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4797 return getConstant(
4798 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4799
4800 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4801 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4802 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4803 SmallVector<SCEVUse, 2> MatchedOperands;
4804 for (const SCEV *Operand : MME->operands()) {
4805 const SCEV *Matched = MatchNotExpr(Operand);
4806 if (!Matched)
4807 return (const SCEV *)nullptr;
4808 MatchedOperands.push_back(Matched);
4809 }
4810 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4811 MatchedOperands);
4812 };
4813 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4814 return Replaced;
4815 }
4816
4817 Type *Ty = V->getType();
4818 Ty = getEffectiveSCEVType(Ty);
4819 return getMinusSCEV(getMinusOne(Ty), V);
4820}
4821
4823 assert(P->getType()->isPointerTy());
4824
4825 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4826 // The base of an AddRec is the first operand.
4827 SmallVector<SCEVUse> Ops{AddRec->operands()};
4828 Ops[0] = removePointerBase(Ops[0]);
4829 // Don't try to transfer nowrap flags for now. We could in some cases
4830 // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4831 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
4832 }
4833 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4834 // The base of an Add is the pointer operand.
4835 SmallVector<SCEVUse> Ops{Add->operands()};
4836 SCEVUse *PtrOp = nullptr;
4837 for (SCEVUse &AddOp : Ops) {
4838 if (AddOp->getType()->isPointerTy()) {
4839 assert(!PtrOp && "Cannot have multiple pointer ops");
4840 PtrOp = &AddOp;
4841 }
4842 }
4843 *PtrOp = removePointerBase(*PtrOp);
4844 // Don't try to transfer nowrap flags for now. We could in some cases
4845 // (for example, if the pointer operand of the Add is a SCEVUnknown).
4846 return getAddExpr(Ops);
4847 }
4848 // Any other expression must be a pointer base.
4849 return getZero(P->getType());
4850}
4851
4853 SCEV::NoWrapFlags Flags,
4854 unsigned Depth) {
4855 // Fast path: X - X --> 0.
4856 if (LHS == RHS)
4857 return getZero(LHS->getType());
4858
4859 // If we subtract two pointers with different pointer bases, bail.
4860 // Eventually, we're going to add an assertion to getMulExpr that we
4861 // can't multiply by a pointer.
4862 if (RHS->getType()->isPointerTy()) {
4863 if (!LHS->getType()->isPointerTy() ||
4864 getPointerBase(LHS) != getPointerBase(RHS))
4865 return getCouldNotCompute();
4866 LHS = removePointerBase(LHS);
4867 RHS = removePointerBase(RHS);
4868 }
4869
4870 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4871 // makes it so that we cannot make much use of NUW.
4872 auto AddFlags = SCEV::FlagAnyWrap;
4873 const bool RHSIsNotMinSigned =
4875 if (hasFlags(Flags, SCEV::FlagNSW)) {
4876 // Let M be the minimum representable signed value. Then (-1)*RHS
4877 // signed-wraps if and only if RHS is M. That can happen even for
4878 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4879 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4880 // (-1)*RHS, we need to prove that RHS != M.
4881 //
4882 // If LHS is non-negative and we know that LHS - RHS does not
4883 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4884 // either by proving that RHS > M or that LHS >= 0.
4885 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4886 AddFlags = SCEV::FlagNSW;
4887 }
4888 }
4889
4890 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4891 // RHS is NSW and LHS >= 0.
4892 //
4893 // The difficulty here is that the NSW flag may have been proven
4894 // relative to a loop that is to be found in a recurrence in LHS and
4895 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4896 // larger scope than intended.
4897 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4898
4899 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4900}
4901
4903 unsigned Depth) {
4904 Type *SrcTy = V->getType();
4905 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4906 "Cannot truncate or zero extend with non-integer arguments!");
4907 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4908 return V; // No conversion
4909 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4910 return getTruncateExpr(V, Ty, Depth);
4911 return getZeroExtendExpr(V, Ty, Depth);
4912}
4913
4915 unsigned Depth) {
4916 Type *SrcTy = V->getType();
4917 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4918 "Cannot truncate or zero extend with non-integer arguments!");
4919 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4920 return V; // No conversion
4921 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4922 return getTruncateExpr(V, Ty, Depth);
4923 return getSignExtendExpr(V, Ty, Depth);
4924}
4925
4926const SCEV *
4928 Type *SrcTy = V->getType();
4929 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4930 "Cannot noop or zero extend with non-integer arguments!");
4932 "getNoopOrZeroExtend cannot truncate!");
4933 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4934 return V; // No conversion
4935 return getZeroExtendExpr(V, Ty);
4936}
4937
4938const SCEV *
4940 Type *SrcTy = V->getType();
4941 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4942 "Cannot noop or sign extend with non-integer arguments!");
4944 "getNoopOrSignExtend cannot truncate!");
4945 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4946 return V; // No conversion
4947 return getSignExtendExpr(V, Ty);
4948}
4949
4950const SCEV *
4952 Type *SrcTy = V->getType();
4953 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4954 "Cannot noop or any extend with non-integer arguments!");
4956 "getNoopOrAnyExtend cannot truncate!");
4957 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4958 return V; // No conversion
4959 return getAnyExtendExpr(V, Ty);
4960}
4961
4962const SCEV *
4964 Type *SrcTy = V->getType();
4965 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4966 "Cannot truncate or noop with non-integer arguments!");
4968 "getTruncateOrNoop cannot extend!");
4969 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4970 return V; // No conversion
4971 return getTruncateExpr(V, Ty);
4972}
4973
4975 const SCEV *RHS) {
4976 const SCEV *PromotedLHS = LHS;
4977 const SCEV *PromotedRHS = RHS;
4978
4979 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4980 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4981 else
4982 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4983
4984 return getUMaxExpr(PromotedLHS, PromotedRHS);
4985}
4986
4988 const SCEV *RHS,
4989 bool Sequential) {
4990 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4991 return getUMinFromMismatchedTypes(Ops, Sequential);
4992}
4993
4994const SCEV *
4996 bool Sequential) {
4997 assert(!Ops.empty() && "At least one operand must be!");
4998 // Trivial case.
4999 if (Ops.size() == 1)
5000 return Ops[0];
5001
5002 // Find the max type first.
5003 Type *MaxType = nullptr;
5004 for (SCEVUse S : Ops)
5005 if (MaxType)
5006 MaxType = getWiderType(MaxType, S->getType());
5007 else
5008 MaxType = S->getType();
5009 assert(MaxType && "Failed to find maximum type!");
5010
5011 // Extend all ops to max type.
5012 SmallVector<SCEVUse, 2> PromotedOps;
5013 for (SCEVUse S : Ops)
5014 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
5015
5016 // Generate umin.
5017 return getUMinExpr(PromotedOps, Sequential);
5018}
5019
5021 // A pointer operand may evaluate to a nonpointer expression, such as null.
5022 if (!V->getType()->isPointerTy())
5023 return V;
5024
5025 while (true) {
5026 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
5027 V = AddRec->getStart();
5028 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
5029 const SCEV *PtrOp = nullptr;
5030 for (const SCEV *AddOp : Add->operands()) {
5031 if (AddOp->getType()->isPointerTy()) {
5032 assert(!PtrOp && "Cannot have multiple pointer ops");
5033 PtrOp = AddOp;
5034 }
5035 }
5036 assert(PtrOp && "Must have pointer op");
5037 V = PtrOp;
5038 } else // Not something we can look further into.
5039 return V;
5040 }
5041}
5042
5043/// Push users of the given Instruction onto the given Worklist.
5047 // Push the def-use children onto the Worklist stack.
5048 for (User *U : I->users()) {
5049 auto *UserInsn = cast<Instruction>(U);
5050 if (Visited.insert(UserInsn).second)
5051 Worklist.push_back(UserInsn);
5052 }
5053}
5054
5055namespace {
5056
5057/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
5058/// expression in case its Loop is L. If it is not L then
5059/// if IgnoreOtherLoops is true then use AddRec itself
5060/// otherwise rewrite cannot be done.
5061/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
5062class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
5063public:
5064 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
5065 bool IgnoreOtherLoops = true) {
5066 SCEVInitRewriter Rewriter(L, SE);
5067 const SCEV *Result = Rewriter.visit(S);
5068 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
5069 return SE.getCouldNotCompute();
5070 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
5071 ? SE.getCouldNotCompute()
5072 : Result;
5073 }
5074
5075 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5076 if (!SE.isLoopInvariant(Expr, L))
5077 SeenLoopVariantSCEVUnknown = true;
5078 return Expr;
5079 }
5080
5081 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5082 // Only re-write AddRecExprs for this loop.
5083 if (Expr->getLoop() == L)
5084 return Expr->getStart();
5085 SeenOtherLoops = true;
5086 return Expr;
5087 }
5088
5089 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
5090
5091 bool hasSeenOtherLoops() { return SeenOtherLoops; }
5092
5093private:
5094 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
5095 : SCEVRewriteVisitor(SE), L(L) {}
5096
5097 const Loop *L;
5098 bool SeenLoopVariantSCEVUnknown = false;
5099 bool SeenOtherLoops = false;
5100};
5101
5102/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
5103/// increment expression in case its Loop is L. If it is not L then
5104/// use AddRec itself.
5105/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
5106class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
5107public:
5108 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
5109 SCEVPostIncRewriter Rewriter(L, SE);
5110 const SCEV *Result = Rewriter.visit(S);
5111 return Rewriter.hasSeenLoopVariantSCEVUnknown()
5112 ? SE.getCouldNotCompute()
5113 : Result;
5114 }
5115
5116 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5117 if (!SE.isLoopInvariant(Expr, L))
5118 SeenLoopVariantSCEVUnknown = true;
5119 return Expr;
5120 }
5121
5122 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5123 // Only re-write AddRecExprs for this loop.
5124 if (Expr->getLoop() == L)
5125 return Expr->getPostIncExpr(SE);
5126 SeenOtherLoops = true;
5127 return Expr;
5128 }
5129
5130 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
5131
5132 bool hasSeenOtherLoops() { return SeenOtherLoops; }
5133
5134private:
5135 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
5136 : SCEVRewriteVisitor(SE), L(L) {}
5137
5138 const Loop *L;
5139 bool SeenLoopVariantSCEVUnknown = false;
5140 bool SeenOtherLoops = false;
5141};
5142
5143/// This class evaluates the compare condition by matching it against the
5144/// condition of loop latch. If there is a match we assume a true value
5145/// for the condition while building SCEV nodes.
5146class SCEVBackedgeConditionFolder
5147 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
5148public:
5149 static const SCEV *rewrite(const SCEV *S, const Loop *L,
5150 ScalarEvolution &SE) {
5151 bool IsPosBECond = false;
5152 Value *BECond = nullptr;
5153 if (BasicBlock *Latch = L->getLoopLatch()) {
5154 if (CondBrInst *BI = dyn_cast<CondBrInst>(Latch->getTerminator())) {
5155 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
5156 "Both outgoing branches should not target same header!");
5157 BECond = BI->getCondition();
5158 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
5159 } else {
5160 return S;
5161 }
5162 }
5163 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
5164 return Rewriter.visit(S);
5165 }
5166
5167 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5168 const SCEV *Result = Expr;
5169 bool InvariantF = SE.isLoopInvariant(Expr, L);
5170
5171 if (!InvariantF) {
5173 switch (I->getOpcode()) {
5174 case Instruction::Select: {
5175 SelectInst *SI = cast<SelectInst>(I);
5176 std::optional<const SCEV *> Res =
5177 compareWithBackedgeCondition(SI->getCondition());
5178 if (Res) {
5179 bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
5180 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
5181 }
5182 break;
5183 }
5184 default: {
5185 std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
5186 if (Res)
5187 Result = *Res;
5188 break;
5189 }
5190 }
5191 }
5192 return Result;
5193 }
5194
5195private:
5196 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
5197 bool IsPosBECond, ScalarEvolution &SE)
5198 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
5199 IsPositiveBECond(IsPosBECond) {}
5200
5201 std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
5202
5203 const Loop *L;
5204 /// Loop back condition.
5205 Value *BackedgeCond = nullptr;
5206 /// Set to true if loop back is on positive branch condition.
5207 bool IsPositiveBECond;
5208};
5209
5210std::optional<const SCEV *>
5211SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
5212
5213 // If value matches the backedge condition for loop latch,
5214 // then return a constant evolution node based on loopback
5215 // branch taken.
5216 if (BackedgeCond == IC)
5217 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
5219 return std::nullopt;
5220}
5221
5222class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
5223public:
5224 static const SCEV *rewrite(const SCEV *S, const Loop *L,
5225 ScalarEvolution &SE) {
5226 SCEVShiftRewriter Rewriter(L, SE);
5227 const SCEV *Result = Rewriter.visit(S);
5228 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
5229 }
5230
5231 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5232 // Only allow AddRecExprs for this loop.
5233 if (!SE.isLoopInvariant(Expr, L))
5234 Valid = false;
5235 return Expr;
5236 }
5237
5238 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5239 if (Expr->getLoop() == L && Expr->isAffine())
5240 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
5241 Valid = false;
5242 return Expr;
5243 }
5244
5245 bool isValid() { return Valid; }
5246
5247private:
5248 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
5249 : SCEVRewriteVisitor(SE), L(L) {}
5250
5251 const Loop *L;
5252 bool Valid = true;
5253};
5254
5255} // end anonymous namespace
5256
5257void ScalarEvolution::inferNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
5258 if (!AR->isAffine())
5259 return;
5260
5261 // Force computation of ranges, which will also perform range-based flag
5262 // inference.
5263 if (!AR->hasNoSignedWrap())
5264 (void)getSignedRange(AR);
5265
5266 if (!AR->hasNoUnsignedWrap())
5267 (void)getUnsignedRange(AR);
5268
5269 if (!AR->hasNoSelfWrap()) {
5270 const SCEV *BECount = getConstantMaxBackedgeTakenCount(AR->getLoop());
5271 if (const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(BECount)) {
5272 ConstantRange StepCR = getSignedRange(AR->getStepRecurrence(*this));
5273 const APInt &BECountAP = BECountMax->getAPInt();
5274 unsigned NoOverflowBitWidth =
5275 BECountAP.getActiveBits() + StepCR.getMinSignedBits();
5276 if (NoOverflowBitWidth <= getTypeSizeInBits(AR->getType()))
5277 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
5278 }
5279 }
5280}
5281
5283ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5285
5286 if (AR->hasNoSignedWrap())
5287 return Result;
5288
5289 if (!AR->isAffine())
5290 return Result;
5291
5292 // This function can be expensive, only try to prove NSW once per AddRec.
5293 if (!SignedWrapViaInductionTried.insert(AR).second)
5294 return Result;
5295
5296 const SCEV *Step = AR->getStepRecurrence(*this);
5297 const Loop *L = AR->getLoop();
5298
5299 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5300 // Note that this serves two purposes: It filters out loops that are
5301 // simply not analyzable, and it covers the case where this code is
5302 // being called from within backedge-taken count analysis, such that
5303 // attempting to ask for the backedge-taken count would likely result
5304 // in infinite recursion. In the later case, the analysis code will
5305 // cope with a conservative value, and it will take care to purge
5306 // that value once it has finished.
5307 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5308
5309 // Normally, in the cases we can prove no-overflow via a
5310 // backedge guarding condition, we can also compute a backedge
5311 // taken count for the loop. The exceptions are assumptions and
5312 // guards present in the loop -- SCEV is not great at exploiting
5313 // these to compute max backedge taken counts, but can still use
5314 // these to prove lack of overflow. Use this fact to avoid
5315 // doing extra work that may not pay off.
5316
5317 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5318 AC.assumptions().empty())
5319 return Result;
5320
5321 // If the backedge is guarded by a comparison with the pre-inc value the
5322 // addrec is safe. Also, if the entry is guarded by a comparison with the
5323 // start value and the backedge is guarded by a comparison with the post-inc
5324 // value, the addrec is safe.
5326 const SCEV *OverflowLimit =
5327 getSignedOverflowLimitForStep(Step, &Pred, this);
5328 if (OverflowLimit &&
5329 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5330 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
5331 Result = setFlags(Result, SCEV::FlagNSW);
5332 }
5333 return Result;
5334}
5336ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5338
5339 if (AR->hasNoUnsignedWrap())
5340 return Result;
5341
5342 if (!AR->isAffine())
5343 return Result;
5344
5345 // This function can be expensive, only try to prove NUW once per AddRec.
5346 if (!UnsignedWrapViaInductionTried.insert(AR).second)
5347 return Result;
5348
5349 const SCEV *Step = AR->getStepRecurrence(*this);
5350 unsigned BitWidth = getTypeSizeInBits(AR->getType());
5351 const Loop *L = AR->getLoop();
5352
5353 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5354 // Note that this serves two purposes: It filters out loops that are
5355 // simply not analyzable, and it covers the case where this code is
5356 // being called from within backedge-taken count analysis, such that
5357 // attempting to ask for the backedge-taken count would likely result
5358 // in infinite recursion. In the later case, the analysis code will
5359 // cope with a conservative value, and it will take care to purge
5360 // that value once it has finished.
5361 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5362
5363 // Normally, in the cases we can prove no-overflow via a
5364 // backedge guarding condition, we can also compute a backedge
5365 // taken count for the loop. The exceptions are assumptions and
5366 // guards present in the loop -- SCEV is not great at exploiting
5367 // these to compute max backedge taken counts, but can still use
5368 // these to prove lack of overflow. Use this fact to avoid
5369 // doing extra work that may not pay off.
5370
5371 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5372 AC.assumptions().empty())
5373 return Result;
5374
5375 // If the backedge is guarded by a comparison with the pre-inc value the
5376 // addrec is safe. Also, if the entry is guarded by a comparison with the
5377 // start value and the backedge is guarded by a comparison with the post-inc
5378 // value, the addrec is safe.
5379 if (isKnownPositive(Step)) {
5380 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
5381 getUnsignedRangeMax(Step));
5384 Result = setFlags(Result, SCEV::FlagNUW);
5385 }
5386 }
5387
5388 return Result;
5389}
5390
5391namespace {
5392
5393/// Represents an abstract binary operation. This may exist as a
5394/// normal instruction or constant expression, or may have been
5395/// derived from an expression tree.
5396struct BinaryOp {
5397 unsigned Opcode;
5398 Value *LHS;
5399 Value *RHS;
5400 bool IsNSW = false;
5401 bool IsNUW = false;
5402
5403 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5404 /// constant expression.
5405 Operator *Op = nullptr;
5406
5407 explicit BinaryOp(Operator *Op)
5408 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5409 Op(Op) {
5410 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5411 IsNSW = OBO->hasNoSignedWrap();
5412 IsNUW = OBO->hasNoUnsignedWrap();
5413 }
5414 }
5415
5416 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5417 bool IsNUW = false)
5418 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5419};
5420
5421} // end anonymous namespace
5422
5423/// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
5424static std::optional<BinaryOp> MatchBinaryOp(Value *V, const DataLayout &DL,
5425 AssumptionCache &AC,
5426 const DominatorTree &DT,
5427 const Instruction *CxtI) {
5428 auto *Op = dyn_cast<Operator>(V);
5429 if (!Op)
5430 return std::nullopt;
5431
5432 // Implementation detail: all the cleverness here should happen without
5433 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5434 // SCEV expressions when possible, and we should not break that.
5435
5436 switch (Op->getOpcode()) {
5437 case Instruction::Add:
5438 case Instruction::Sub:
5439 case Instruction::Mul:
5440 case Instruction::UDiv:
5441 case Instruction::URem:
5442 case Instruction::And:
5443 case Instruction::AShr:
5444 case Instruction::Shl:
5445 return BinaryOp(Op);
5446
5447 case Instruction::Or: {
5448 // Convert or disjoint into add nuw nsw.
5449 if (cast<PossiblyDisjointInst>(Op)->isDisjoint()) {
5450 BinaryOp BinOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
5451 /*IsNSW=*/true, /*IsNUW=*/true);
5452 // Keep the reference to the original instruction so that we can later
5453 // check whether it can produce poison value or not.
5454 BinOp.Op = Op;
5455 return BinOp;
5456 }
5457 return BinaryOp(Op);
5458 }
5459
5460 case Instruction::Xor:
5461 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5462 // If the RHS of the xor is a signmask, then this is just an add.
5463 // Instcombine turns add of signmask into xor as a strength reduction step.
5464 if (RHSC->getValue().isSignMask())
5465 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5466 // Binary `xor` is a bit-wise `add`.
5467 if (V->getType()->isIntegerTy(1))
5468 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5469 return BinaryOp(Op);
5470
5471 case Instruction::LShr:
5472 // Turn logical shift right of a constant into a unsigned divide.
5473 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5474 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5475
5476 // If the shift count is not less than the bitwidth, the result of
5477 // the shift is undefined. Don't try to analyze it, because the
5478 // resolution chosen here may differ from the resolution chosen in
5479 // other parts of the compiler.
5480 if (SA->getValue().ult(BitWidth)) {
5481 Constant *X =
5482 ConstantInt::get(SA->getContext(),
5483 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5484 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5485 }
5486 }
5487 return BinaryOp(Op);
5488
5489 case Instruction::ExtractValue: {
5490 auto *EVI = cast<ExtractValueInst>(Op);
5491 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5492 break;
5493
5494 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5495 if (!WO)
5496 break;
5497
5498 Instruction::BinaryOps BinOp = WO->getBinaryOp();
5499 bool Signed = WO->isSigned();
5500 // TODO: Should add nuw/nsw flags for mul as well.
5501 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5502 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5503
5504 // Now that we know that all uses of the arithmetic-result component of
5505 // CI are guarded by the overflow check, we can go ahead and pretend
5506 // that the arithmetic is non-overflowing.
5507 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5508 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5509 }
5510
5511 default:
5512 break;
5513 }
5514
5515 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5516 // semantics as a Sub, return a binary sub expression.
5517 if (auto *II = dyn_cast<IntrinsicInst>(V))
5518 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5519 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5520
5521 return std::nullopt;
5522}
5523
5524/// Helper function to createAddRecFromPHIWithCasts. We have a phi
5525/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5526/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5527/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5528/// follows one of the following patterns:
5529/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5530/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5531/// If the SCEV expression of \p Op conforms with one of the expected patterns
5532/// we return the type of the truncation operation, and indicate whether the
5533/// truncated type should be treated as signed/unsigned by setting
5534/// \p Signed to true/false, respectively.
5535static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5536 bool &Signed, ScalarEvolution &SE) {
5537 // The case where Op == SymbolicPHI (that is, with no type conversions on
5538 // the way) is handled by the regular add recurrence creating logic and
5539 // would have already been triggered in createAddRecForPHI. Reaching it here
5540 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5541 // because one of the other operands of the SCEVAddExpr updating this PHI is
5542 // not invariant).
5543 //
5544 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5545 // this case predicates that allow us to prove that Op == SymbolicPHI will
5546 // be added.
5547 if (Op == SymbolicPHI)
5548 return nullptr;
5549
5550 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5551 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5552 if (SourceBits != NewBits)
5553 return nullptr;
5554
5555 if (match(Op, m_scev_SExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5556 Signed = true;
5557 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5558 }
5559 if (match(Op, m_scev_ZExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5560 Signed = false;
5561 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5562 }
5563 return nullptr;
5564}
5565
5566static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5567 if (!PN->getType()->isIntegerTy())
5568 return nullptr;
5569 const Loop *L = LI.getLoopFor(PN->getParent());
5570 if (!L || L->getHeader() != PN->getParent())
5571 return nullptr;
5572 return L;
5573}
5574
5575// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5576// computation that updates the phi follows the following pattern:
5577// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5578// which correspond to a phi->trunc->sext/zext->add->phi update chain.
5579// If so, try to see if it can be rewritten as an AddRecExpr under some
5580// Predicates. If successful, return them as a pair. Also cache the results
5581// of the analysis.
5582//
5583// Example usage scenario:
5584// Say the Rewriter is called for the following SCEV:
5585// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5586// where:
5587// %X = phi i64 (%Start, %BEValue)
5588// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5589// and call this function with %SymbolicPHI = %X.
5590//
5591// The analysis will find that the value coming around the backedge has
5592// the following SCEV:
5593// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5594// Upon concluding that this matches the desired pattern, the function
5595// will return the pair {NewAddRec, SmallPredsVec} where:
5596// NewAddRec = {%Start,+,%Step}
5597// SmallPredsVec = {P1, P2, P3} as follows:
5598// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5599// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5600// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5601// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5602// under the predicates {P1,P2,P3}.
5603// This predicated rewrite will be cached in PredicatedSCEVRewrites:
5604// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5605//
5606// TODO's:
5607//
5608// 1) Extend the Induction descriptor to also support inductions that involve
5609// casts: When needed (namely, when we are called in the context of the
5610// vectorizer induction analysis), a Set of cast instructions will be
5611// populated by this method, and provided back to isInductionPHI. This is
5612// needed to allow the vectorizer to properly record them to be ignored by
5613// the cost model and to avoid vectorizing them (otherwise these casts,
5614// which are redundant under the runtime overflow checks, will be
5615// vectorized, which can be costly).
5616//
5617// 2) Support additional induction/PHISCEV patterns: We also want to support
5618// inductions where the sext-trunc / zext-trunc operations (partly) occur
5619// after the induction update operation (the induction increment):
5620//
5621// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5622// which correspond to a phi->add->trunc->sext/zext->phi update chain.
5623//
5624// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5625// which correspond to a phi->trunc->add->sext/zext->phi update chain.
5626//
5627// 3) Outline common code with createAddRecFromPHI to avoid duplication.
5628std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5629ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5631
5632 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5633 // return an AddRec expression under some predicate.
5634
5635 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5636 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5637 assert(L && "Expecting an integer loop header phi");
5638
5639 // The loop may have multiple entrances or multiple exits; we can analyze
5640 // this phi as an addrec if it has a unique entry value and a unique
5641 // backedge value.
5642 Value *BEValueV = nullptr, *StartValueV = nullptr;
5643 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5644 Value *V = PN->getIncomingValue(i);
5645 if (L->contains(PN->getIncomingBlock(i))) {
5646 if (!BEValueV) {
5647 BEValueV = V;
5648 } else if (BEValueV != V) {
5649 BEValueV = nullptr;
5650 break;
5651 }
5652 } else if (!StartValueV) {
5653 StartValueV = V;
5654 } else if (StartValueV != V) {
5655 StartValueV = nullptr;
5656 break;
5657 }
5658 }
5659 if (!BEValueV || !StartValueV)
5660 return std::nullopt;
5661
5662 const SCEV *BEValue = getSCEV(BEValueV);
5663
5664 // If the value coming around the backedge is an add with the symbolic
5665 // value we just inserted, possibly with casts that we can ignore under
5666 // an appropriate runtime guard, then we found a simple induction variable!
5667 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5668 if (!Add)
5669 return std::nullopt;
5670
5671 // If there is a single occurrence of the symbolic value, possibly
5672 // casted, replace it with a recurrence.
5673 unsigned FoundIndex = Add->getNumOperands();
5674 Type *TruncTy = nullptr;
5675 bool Signed;
5676 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5677 if ((TruncTy =
5678 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5679 if (FoundIndex == e) {
5680 FoundIndex = i;
5681 break;
5682 }
5683
5684 if (FoundIndex == Add->getNumOperands())
5685 return std::nullopt;
5686
5687 // Create an add with everything but the specified operand.
5689 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5690 if (i != FoundIndex)
5691 Ops.push_back(Add->getOperand(i));
5692 const SCEV *Accum = getAddExpr(Ops);
5693
5694 // The runtime checks will not be valid if the step amount is
5695 // varying inside the loop.
5696 if (!isLoopInvariant(Accum, L))
5697 return std::nullopt;
5698
5699 // *** Part2: Create the predicates
5700
5701 // Analysis was successful: we have a phi-with-cast pattern for which we
5702 // can return an AddRec expression under the following predicates:
5703 //
5704 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5705 // fits within the truncated type (does not overflow) for i = 0 to n-1.
5706 // P2: An Equal predicate that guarantees that
5707 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5708 // P3: An Equal predicate that guarantees that
5709 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5710 //
5711 // As we next prove, the above predicates guarantee that:
5712 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5713 //
5714 //
5715 // More formally, we want to prove that:
5716 // Expr(i+1) = Start + (i+1) * Accum
5717 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5718 //
5719 // Given that:
5720 // 1) Expr(0) = Start
5721 // 2) Expr(1) = Start + Accum
5722 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5723 // 3) Induction hypothesis (step i):
5724 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5725 //
5726 // Proof:
5727 // Expr(i+1) =
5728 // = Start + (i+1)*Accum
5729 // = (Start + i*Accum) + Accum
5730 // = Expr(i) + Accum
5731 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5732 // :: from step i
5733 //
5734 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5735 //
5736 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5737 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
5738 // + Accum :: from P3
5739 //
5740 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5741 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5742 //
5743 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5744 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5745 //
5746 // By induction, the same applies to all iterations 1<=i<n:
5747 //
5748
5749 // Create a truncated addrec for which we will add a no overflow check (P1).
5750 const SCEV *StartVal = getSCEV(StartValueV);
5751 const SCEV *PHISCEV =
5752 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5753 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5754
5755 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5756 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5757 // will be constant.
5758 //
5759 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5760 // add P1.
5761 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5765 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5766 Predicates.push_back(AddRecPred);
5767 }
5768
5769 // Create the Equal Predicates P2,P3:
5770
5771 // It is possible that the predicates P2 and/or P3 are computable at
5772 // compile time due to StartVal and/or Accum being constants.
5773 // If either one is, then we can check that now and escape if either P2
5774 // or P3 is false.
5775
5776 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5777 // for each of StartVal and Accum
5778 auto getExtendedExpr = [&](const SCEV *Expr,
5779 bool CreateSignExtend) -> const SCEV * {
5780 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5781 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5782 const SCEV *ExtendedExpr =
5783 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5784 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5785 return ExtendedExpr;
5786 };
5787
5788 // Given:
5789 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5790 // = getExtendedExpr(Expr)
5791 // Determine whether the predicate P: Expr == ExtendedExpr
5792 // is known to be false at compile time
5793 auto PredIsKnownFalse = [&](const SCEV *Expr,
5794 const SCEV *ExtendedExpr) -> bool {
5795 return Expr != ExtendedExpr &&
5796 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5797 };
5798
5799 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5800 if (PredIsKnownFalse(StartVal, StartExtended)) {
5801 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5802 return std::nullopt;
5803 }
5804
5805 // The Step is always Signed (because the overflow checks are either
5806 // NSSW or NUSW)
5807 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5808 if (PredIsKnownFalse(Accum, AccumExtended)) {
5809 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5810 return std::nullopt;
5811 }
5812
5813 auto AppendPredicate = [&](const SCEV *Expr,
5814 const SCEV *ExtendedExpr) -> void {
5815 if (Expr != ExtendedExpr &&
5816 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5817 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5818 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5819 Predicates.push_back(Pred);
5820 }
5821 };
5822
5823 AppendPredicate(StartVal, StartExtended);
5824 AppendPredicate(Accum, AccumExtended);
5825
5826 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5827 // which the casts had been folded away. The caller can rewrite SymbolicPHI
5828 // into NewAR if it will also add the runtime overflow checks specified in
5829 // Predicates.
5830 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5831
5832 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5833 std::make_pair(NewAR, Predicates);
5834 // Remember the result of the analysis for this SCEV at this locayyytion.
5835 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5836 return PredRewrite;
5837}
5838
5839std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5841 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5842 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5843 if (!L)
5844 return std::nullopt;
5845
5846 // Check to see if we already analyzed this PHI.
5847 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5848 if (I != PredicatedSCEVRewrites.end()) {
5849 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5850 I->second;
5851 // Analysis was done before and failed to create an AddRec:
5852 if (Rewrite.first == SymbolicPHI)
5853 return std::nullopt;
5854 // Analysis was done before and succeeded to create an AddRec under
5855 // a predicate:
5856 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5857 assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5858 return Rewrite;
5859 }
5860
5861 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5862 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5863
5864 // Record in the cache that the analysis failed
5865 if (!Rewrite) {
5867 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5868 return std::nullopt;
5869 }
5870
5871 return Rewrite;
5872}
5873
5874// FIXME: This utility is currently required because the Rewriter currently
5875// does not rewrite this expression:
5876// {0, +, (sext ix (trunc iy to ix) to iy)}
5877// into {0, +, %step},
5878// even when the following Equal predicate exists:
5879// "%step == (sext ix (trunc iy to ix) to iy)".
5881 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2,
5882 ArrayRef<const SCEVPredicate *> NoWrapPreds) const {
5883 if (AR1 == AR2)
5884 return true;
5885
5886 SCEVUnionPredicate NoWrapUnionPred(NoWrapPreds, SE);
5887 SCEVUnionPredicate AllPreds = Preds->getUnionWith(&NoWrapUnionPred, SE);
5888 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5889 if (Expr1 != Expr2 &&
5890 !AllPreds.implies(SE.getEqualPredicate(Expr1, Expr2), SE) &&
5891 !AllPreds.implies(SE.getEqualPredicate(Expr2, Expr1), SE))
5892 return false;
5893 return true;
5894 };
5895
5896 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5897 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5898 return false;
5899 return true;
5900}
5901
5902/// A helper function for createAddRecFromPHI to handle simple cases.
5903///
5904/// This function tries to find an AddRec expression for the simplest (yet most
5905/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5906/// If it fails, createAddRecFromPHI will use a more general, but slow,
5907/// technique for finding the AddRec expression.
5908const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5909 Value *BEValueV,
5910 Value *StartValueV) {
5911 const Loop *L = LI.getLoopFor(PN->getParent());
5912 assert(L && L->getHeader() == PN->getParent());
5913 assert(BEValueV && StartValueV);
5914
5915 auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN);
5916 if (!BO)
5917 return nullptr;
5918
5919 if (BO->Opcode != Instruction::Add)
5920 return nullptr;
5921
5922 const SCEV *Accum = nullptr;
5923 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5924 Accum = getSCEV(BO->RHS);
5925 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5926 Accum = getSCEV(BO->LHS);
5927
5928 if (!Accum)
5929 return nullptr;
5930
5932 if (BO->IsNUW)
5933 Flags = setFlags(Flags, SCEV::FlagNUW);
5934 if (BO->IsNSW)
5935 Flags = setFlags(Flags, SCEV::FlagNSW);
5936
5937 const SCEV *StartVal = getSCEV(StartValueV);
5938 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5939 insertValueToMap(PN, PHISCEV);
5940
5941 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5942 inferNoWrapViaConstantRanges(AR);
5943
5944 // We can add Flags to the post-inc expression only if we
5945 // know that it is *undefined behavior* for BEValueV to
5946 // overflow.
5947 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5948 assert(isLoopInvariant(Accum, L) &&
5949 "Accum is defined outside L, but is not invariant?");
5950 if (isAddRecNeverPoison(BEInst, L))
5951 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5952 }
5953
5954 return PHISCEV;
5955}
5956
5957const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5958 const Loop *L = LI.getLoopFor(PN->getParent());
5959 if (!L || L->getHeader() != PN->getParent())
5960 return nullptr;
5961
5962 // The loop may have multiple entrances or multiple exits; we can analyze
5963 // this phi as an addrec if it has a unique entry value and a unique
5964 // backedge value.
5965 Value *BEValueV = nullptr, *StartValueV = nullptr;
5966 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5967 Value *V = PN->getIncomingValue(i);
5968 if (L->contains(PN->getIncomingBlock(i))) {
5969 if (!BEValueV) {
5970 BEValueV = V;
5971 } else if (BEValueV != V) {
5972 BEValueV = nullptr;
5973 break;
5974 }
5975 } else if (!StartValueV) {
5976 StartValueV = V;
5977 } else if (StartValueV != V) {
5978 StartValueV = nullptr;
5979 break;
5980 }
5981 }
5982 if (!BEValueV || !StartValueV)
5983 return nullptr;
5984
5985 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5986 "PHI node already processed?");
5987
5988 // First, try to find AddRec expression without creating a fictituos symbolic
5989 // value for PN.
5990 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5991 return S;
5992
5993 // Handle PHI node value symbolically.
5994 const SCEV *SymbolicName = getUnknown(PN);
5995 insertValueToMap(PN, SymbolicName);
5996
5997 // Using this symbolic name for the PHI, analyze the value coming around
5998 // the back-edge.
5999 const SCEV *BEValue = getSCEV(BEValueV);
6000
6001 // NOTE: If BEValue is loop invariant, we know that the PHI node just
6002 // has a special value for the first iteration of the loop.
6003
6004 // If the value coming around the backedge is an add with the symbolic
6005 // value we just inserted, then we found a simple induction variable!
6006 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
6007 // If there is a single occurrence of the symbolic value, replace it
6008 // with a recurrence.
6009 unsigned FoundIndex = Add->getNumOperands();
6010 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
6011 if (Add->getOperand(i) == SymbolicName)
6012 if (FoundIndex == e) {
6013 FoundIndex = i;
6014 break;
6015 }
6016
6017 if (FoundIndex != Add->getNumOperands()) {
6018 // Create an add with everything but the specified operand.
6020 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
6021 if (i != FoundIndex)
6022 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
6023 L, *this));
6024 const SCEV *Accum = getAddExpr(Ops);
6025
6026 // This is not a valid addrec if the step amount is varying each
6027 // loop iteration, but is not itself an addrec in this loop.
6028 if (isLoopInvariant(Accum, L) ||
6029 (isa<SCEVAddRecExpr>(Accum) &&
6030 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
6032
6033 if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
6034 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
6035 if (BO->IsNUW)
6036 Flags = setFlags(Flags, SCEV::FlagNUW);
6037 if (BO->IsNSW)
6038 Flags = setFlags(Flags, SCEV::FlagNSW);
6039 }
6040 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
6041 if (GEP->getOperand(0) == PN) {
6042 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
6043 // If the increment has any nowrap flags, then we know the address
6044 // space cannot be wrapped around.
6045 if (NW != GEPNoWrapFlags::none())
6046 Flags = setFlags(Flags, SCEV::FlagNW);
6047 // If the GEP is nuw or nusw with non-negative offset, we know that
6048 // no unsigned wrap occurs. We cannot set the nsw flag as only the
6049 // offset is treated as signed, while the base is unsigned.
6050 if (NW.hasNoUnsignedWrap() ||
6052 Flags = setFlags(Flags, SCEV::FlagNUW);
6053 }
6054
6055 // We cannot transfer nuw and nsw flags from subtraction
6056 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
6057 // for instance.
6058 }
6059
6060 const SCEV *StartVal = getSCEV(StartValueV);
6061 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
6062
6063 // Okay, for the entire analysis of this edge we assumed the PHI
6064 // to be symbolic. We now need to go back and purge all of the
6065 // entries for the scalars that use the symbolic expression.
6066 forgetMemoizedResults({SymbolicName});
6067 insertValueToMap(PN, PHISCEV);
6068
6069 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
6070 inferNoWrapViaConstantRanges(AR);
6071
6072 // We can add Flags to the post-inc expression only if we
6073 // know that it is *undefined behavior* for BEValueV to
6074 // overflow.
6075 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
6076 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
6077 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
6078
6079 return PHISCEV;
6080 }
6081 }
6082 } else {
6083 // Otherwise, this could be a loop like this:
6084 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
6085 // In this case, j = {1,+,1} and BEValue is j.
6086 // Because the other in-value of i (0) fits the evolution of BEValue
6087 // i really is an addrec evolution.
6088 //
6089 // We can generalize this saying that i is the shifted value of BEValue
6090 // by one iteration:
6091 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
6092
6093 // Do not allow refinement in rewriting of BEValue.
6094 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
6095 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
6096 if (Shifted != getCouldNotCompute() && Start != getCouldNotCompute() &&
6097 isGuaranteedNotToCauseUB(Shifted) && ::impliesPoison(Shifted, Start)) {
6098 const SCEV *StartVal = getSCEV(StartValueV);
6099 if (Start == StartVal) {
6100 // Okay, for the entire analysis of this edge we assumed the PHI
6101 // to be symbolic. We now need to go back and purge all of the
6102 // entries for the scalars that use the symbolic expression.
6103 forgetMemoizedResults({SymbolicName});
6104 insertValueToMap(PN, Shifted);
6105 return Shifted;
6106 }
6107 }
6108 }
6109
6110 // Remove the temporary PHI node SCEV that has been inserted while intending
6111 // to create an AddRecExpr for this PHI node. We can not keep this temporary
6112 // as it will prevent later (possibly simpler) SCEV expressions to be added
6113 // to the ValueExprMap.
6114 eraseValueFromMap(PN);
6115
6116 return nullptr;
6117}
6118
6119// Try to match a control flow sequence that branches out at BI and merges back
6120// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
6121// match.
6123 Value *&C, Value *&LHS, Value *&RHS) {
6124 C = BI->getCondition();
6125
6126 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
6127 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
6128
6129 Use &LeftUse = Merge->getOperandUse(0);
6130 Use &RightUse = Merge->getOperandUse(1);
6131
6132 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
6133 LHS = LeftUse;
6134 RHS = RightUse;
6135 return true;
6136 }
6137
6138 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
6139 LHS = RightUse;
6140 RHS = LeftUse;
6141 return true;
6142 }
6143
6144 return false;
6145}
6146
6148 Value *&Cond, Value *&LHS,
6149 Value *&RHS) {
6150 auto IsReachable =
6151 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
6152 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
6153 // Try to match
6154 //
6155 // br %cond, label %left, label %right
6156 // left:
6157 // br label %merge
6158 // right:
6159 // br label %merge
6160 // merge:
6161 // V = phi [ %x, %left ], [ %y, %right ]
6162 //
6163 // as "select %cond, %x, %y"
6164
6165 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
6166 assert(IDom && "At least the entry block should dominate PN");
6167
6168 auto *BI = dyn_cast<CondBrInst>(IDom->getTerminator());
6169 return BI && BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS);
6170 }
6171 return false;
6172}
6173
6174const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
6175 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6176 if (getOperandsForSelectLikePHI(DT, PN, Cond, LHS, RHS) &&
6179 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
6180
6181 return nullptr;
6182}
6183
6185 BinaryOperator *CommonInst = nullptr;
6186 // Check if instructions are identical.
6187 for (Value *Incoming : PN->incoming_values()) {
6188 auto *IncomingInst = dyn_cast<BinaryOperator>(Incoming);
6189 if (!IncomingInst)
6190 return nullptr;
6191 if (CommonInst) {
6192 if (!CommonInst->isIdenticalToWhenDefined(IncomingInst))
6193 return nullptr; // Not identical, give up
6194 } else {
6195 // Remember binary operator
6196 CommonInst = IncomingInst;
6197 }
6198 }
6199 return CommonInst;
6200}
6201
6202/// Returns SCEV for the first operand of a phi if all phi operands have
6203/// identical opcodes and operands
6204/// eg.
6205/// a: %add = %a + %b
6206/// br %c
6207/// b: %add1 = %a + %b
6208/// br %c
6209/// c: %phi = phi [%add, a], [%add1, b]
6210/// scev(%phi) => scev(%add)
6211const SCEV *
6212ScalarEvolution::createNodeForPHIWithIdenticalOperands(PHINode *PN) {
6213 BinaryOperator *CommonInst = getCommonInstForPHI(PN);
6214 if (!CommonInst)
6215 return nullptr;
6216
6217 // Check if SCEV exprs for instructions are identical.
6218 const SCEV *CommonSCEV = getSCEV(CommonInst);
6219 bool SCEVExprsIdentical =
6221 [this, CommonSCEV](Value *V) { return CommonSCEV == getSCEV(V); });
6222 return SCEVExprsIdentical ? CommonSCEV : nullptr;
6223}
6224
6225const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
6226 if (const SCEV *S = createAddRecFromPHI(PN))
6227 return S;
6228
6229 // We do not allow simplifying phi (undef, X) to X here, to avoid reusing the
6230 // phi node for X.
6231 if (Value *V = simplifyInstruction(
6232 PN, {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
6233 /*UseInstrInfo=*/true, /*CanUseUndef=*/false}))
6234 return getSCEV(V);
6235
6236 if (const SCEV *S = createNodeForPHIWithIdenticalOperands(PN))
6237 return S;
6238
6239 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
6240 return S;
6241
6242 // If it's not a loop phi, we can't handle it yet.
6243 return getUnknown(PN);
6244}
6245
6246bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
6247 SCEVTypes RootKind) {
6248 struct FindClosure {
6249 const SCEV *OperandToFind;
6250 const SCEVTypes RootKind; // Must be a sequential min/max expression.
6251 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
6252
6253 bool Found = false;
6254
6255 bool canRecurseInto(SCEVTypes Kind) const {
6256 // We can only recurse into the SCEV expression of the same effective type
6257 // as the type of our root SCEV expression, and into zero-extensions.
6258 return RootKind == Kind || NonSequentialRootKind == Kind ||
6259 scZeroExtend == Kind;
6260 };
6261
6262 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
6263 : OperandToFind(OperandToFind), RootKind(RootKind),
6264 NonSequentialRootKind(
6266 RootKind)) {}
6267
6268 bool follow(const SCEV *S) {
6269 Found = S == OperandToFind;
6270
6271 return !isDone() && canRecurseInto(S->getSCEVType());
6272 }
6273
6274 bool isDone() const { return Found; }
6275 };
6276
6277 FindClosure FC(OperandToFind, RootKind);
6278 visitAll(Root, FC);
6279 return FC.Found;
6280}
6281
6282std::optional<const SCEV *>
6283ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
6284 ICmpInst *Cond,
6285 Value *TrueVal,
6286 Value *FalseVal) {
6287 // Try to match some simple smax or umax patterns.
6288 auto *ICI = Cond;
6289
6290 Value *LHS = ICI->getOperand(0);
6291 Value *RHS = ICI->getOperand(1);
6292
6293 switch (ICI->getPredicate()) {
6294 case ICmpInst::ICMP_SLT:
6295 case ICmpInst::ICMP_SLE:
6296 case ICmpInst::ICMP_ULT:
6297 case ICmpInst::ICMP_ULE:
6298 std::swap(LHS, RHS);
6299 [[fallthrough]];
6300 case ICmpInst::ICMP_SGT:
6301 case ICmpInst::ICMP_SGE:
6302 case ICmpInst::ICMP_UGT:
6303 case ICmpInst::ICMP_UGE:
6304 // a > b ? a+x : b+x -> max(a, b)+x
6305 // a > b ? b+x : a+x -> min(a, b)+x
6307 bool Signed = ICI->isSigned();
6308 const SCEV *LA = getSCEV(TrueVal);
6309 const SCEV *RA = getSCEV(FalseVal);
6310 const SCEV *LS = getSCEV(LHS);
6311 const SCEV *RS = getSCEV(RHS);
6312 if (LA->getType()->isPointerTy()) {
6313 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6314 // Need to make sure we can't produce weird expressions involving
6315 // negated pointers.
6316 if (LA == LS && RA == RS)
6317 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6318 if (LA == RS && RA == LS)
6319 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6320 }
6321 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6322 if (Op->getType()->isPointerTy()) {
6325 return Op;
6326 }
6327 if (Signed)
6328 Op = getNoopOrSignExtend(Op, Ty);
6329 else
6330 Op = getNoopOrZeroExtend(Op, Ty);
6331 return Op;
6332 };
6333 LS = CoerceOperand(LS);
6334 RS = CoerceOperand(RS);
6336 break;
6337 const SCEV *LDiff = getMinusSCEV(LA, LS);
6338 const SCEV *RDiff = getMinusSCEV(RA, RS);
6339 if (LDiff == RDiff)
6340 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6341 LDiff);
6342 LDiff = getMinusSCEV(LA, RS);
6343 RDiff = getMinusSCEV(RA, LS);
6344 if (LDiff == RDiff)
6345 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6346 LDiff);
6347 }
6348 break;
6349 case ICmpInst::ICMP_NE:
6350 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
6351 std::swap(TrueVal, FalseVal);
6352 [[fallthrough]];
6353 case ICmpInst::ICMP_EQ:
6354 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
6357 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6358 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y
6359 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y
6360 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6361 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y
6362 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6363 return getAddExpr(getUMaxExpr(X, C), Y);
6364 }
6365 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
6366 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
6367 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
6368 // -> umin_seq(x, umin (..., umin_seq(...), ...))
6370 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6371 const SCEV *X = getSCEV(LHS);
6372 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6373 X = ZExt->getOperand();
6374 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6375 const SCEV *FalseValExpr = getSCEV(FalseVal);
6376 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6377 return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6378 /*Sequential=*/true);
6379 }
6380 }
6381 break;
6382 default:
6383 break;
6384 }
6385
6386 return std::nullopt;
6387}
6388
6389static std::optional<const SCEV *>
6391 const SCEV *TrueExpr, const SCEV *FalseExpr) {
6392 assert(CondExpr->getType()->isIntegerTy(1) &&
6393 TrueExpr->getType() == FalseExpr->getType() &&
6394 TrueExpr->getType()->isIntegerTy(1) &&
6395 "Unexpected operands of a select.");
6396
6397 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
6398 // --> C + (umin_seq cond, x - C)
6399 //
6400 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
6401 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6402 // --> C + (umin_seq ~cond, x - C)
6403
6404 // FIXME: while we can't legally model the case where both of the hands
6405 // are fully variable, we only require that the *difference* is constant.
6406 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6407 return std::nullopt;
6408
6409 const SCEV *X, *C;
6410 if (isa<SCEVConstant>(TrueExpr)) {
6411 CondExpr = SE->getNotSCEV(CondExpr);
6412 X = FalseExpr;
6413 C = TrueExpr;
6414 } else {
6415 X = TrueExpr;
6416 C = FalseExpr;
6417 }
6418 return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6419 /*Sequential=*/true));
6420}
6421
6422static std::optional<const SCEV *>
6424 Value *FalseVal) {
6425 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6426 return std::nullopt;
6427
6428 const auto *SECond = SE->getSCEV(Cond);
6429 const auto *SETrue = SE->getSCEV(TrueVal);
6430 const auto *SEFalse = SE->getSCEV(FalseVal);
6431 return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6432}
6433
6434const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6435 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6436 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6437 assert(TrueVal->getType() == FalseVal->getType() &&
6438 V->getType() == TrueVal->getType() &&
6439 "Types of select hands and of the result must match.");
6440
6441 // For now, only deal with i1-typed `select`s.
6442 if (!V->getType()->isIntegerTy(1))
6443 return getUnknown(V);
6444
6445 if (std::optional<const SCEV *> S =
6446 createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6447 return *S;
6448
6449 return getUnknown(V);
6450}
6451
6452const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6453 Value *TrueVal,
6454 Value *FalseVal) {
6455 // Handle "constant" branch or select. This can occur for instance when a
6456 // loop pass transforms an inner loop and moves on to process the outer loop.
6457 if (auto *CI = dyn_cast<ConstantInt>(Cond))
6458 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6459
6460 if (auto *I = dyn_cast<Instruction>(V)) {
6461 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6462 if (std::optional<const SCEV *> S =
6463 createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6464 TrueVal, FalseVal))
6465 return *S;
6466 }
6467 }
6468
6469 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6470}
6471
6472/// Expand GEP instructions into add and multiply operations. This allows them
6473/// to be analyzed by regular SCEV code.
6474const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6475 assert(GEP->getSourceElementType()->isSized() &&
6476 "GEP source element type must be sized");
6477
6478 SmallVector<SCEVUse, 4> IndexExprs;
6479 for (Value *Index : GEP->indices())
6480 IndexExprs.push_back(getSCEV(Index));
6481 return getGEPExpr(GEP, IndexExprs);
6482}
6483
6484APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S,
6485 const Instruction *CtxI) {
6486 uint64_t BitWidth = getTypeSizeInBits(S->getType());
6487 auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6488 return TrailingZeros >= BitWidth
6490 : APInt::getOneBitSet(BitWidth, TrailingZeros);
6491 };
6492 auto GetGCDMultiple = [this, CtxI](const SCEVNAryExpr *N) {
6493 // The result is GCD of all operands results.
6494 APInt Res = getConstantMultiple(N->getOperand(0), CtxI);
6495 for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6497 Res, getConstantMultiple(N->getOperand(I), CtxI));
6498 return Res;
6499 };
6500
6501 switch (S->getSCEVType()) {
6502 case scConstant:
6503 return cast<SCEVConstant>(S)->getAPInt();
6504 case scPtrToAddr:
6505 case scPtrToInt:
6506 return getConstantMultiple(cast<SCEVCastExpr>(S)->getOperand());
6507 case scUDivExpr:
6508 case scVScale:
6509 return APInt(BitWidth, 1);
6510 case scTruncate: {
6511 // Only multiples that are a power of 2 will hold after truncation.
6512 const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6513 uint32_t TZ = getMinTrailingZeros(T->getOperand(), CtxI);
6514 return GetShiftedByZeros(TZ);
6515 }
6516 case scZeroExtend: {
6517 const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(S);
6518 return getConstantMultiple(Z->getOperand(), CtxI).zext(BitWidth);
6519 }
6520 case scSignExtend: {
6521 // Only multiples that are a power of 2 will hold after sext.
6522 const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6523 uint32_t TZ = getMinTrailingZeros(E->getOperand(), CtxI);
6524 return GetShiftedByZeros(TZ);
6525 }
6526 case scMulExpr: {
6527 const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6528 if (M->hasNoUnsignedWrap()) {
6529 // The result is the product of all operand results.
6530 APInt Res = getConstantMultiple(M->getOperand(0), CtxI);
6531 for (const SCEV *Operand : M->operands().drop_front())
6532 Res = Res * getConstantMultiple(Operand, CtxI);
6533 return Res;
6534 }
6535
6536 // If there are no wrap guarentees, find the trailing zeros, which is the
6537 // sum of trailing zeros for all its operands.
6538 uint32_t TZ = 0;
6539 for (const SCEV *Operand : M->operands())
6540 TZ += getMinTrailingZeros(Operand, CtxI);
6541 return GetShiftedByZeros(TZ);
6542 }
6543 case scAddExpr:
6544 case scAddRecExpr: {
6545 const SCEVNAryExpr *N = cast<SCEVNAryExpr>(S);
6546 if (N->hasNoUnsignedWrap())
6547 return GetGCDMultiple(N);
6548 // Find the trailing bits, which is the minimum of its operands.
6549 uint32_t TZ = getMinTrailingZeros(N->getOperand(0), CtxI);
6550 for (const SCEV *Operand : N->operands().drop_front())
6551 TZ = std::min(TZ, getMinTrailingZeros(Operand, CtxI));
6552 return GetShiftedByZeros(TZ);
6553 }
6554 case scUMaxExpr:
6555 case scSMaxExpr:
6556 case scUMinExpr:
6557 case scSMinExpr:
6559 return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6560 case scUnknown: {
6561 // Ask ValueTracking for known bits. SCEVUnknown only become available at
6562 // the point their underlying IR instruction has been defined. If CtxI was
6563 // not provided, use:
6564 // * the first instruction in the entry block if it is an argument
6565 // * the instruction itself otherwise.
6566 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6567 if (!CtxI) {
6568 if (isa<Argument>(U->getValue()))
6569 CtxI = &*F.getEntryBlock().begin();
6570 else if (auto *I = dyn_cast<Instruction>(U->getValue()))
6571 CtxI = I;
6572 }
6573 unsigned Known =
6574 computeKnownBits(U->getValue(),
6575 SimplifyQuery(getDataLayout(), &DT, &AC, CtxI)
6576 .allowEphemerals(true))
6577 .countMinTrailingZeros();
6578 return GetShiftedByZeros(Known);
6579 }
6580 case scCouldNotCompute:
6581 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6582 }
6583 llvm_unreachable("Unknown SCEV kind!");
6584}
6585
6587 const Instruction *CtxI) {
6588 // Skip looking up and updating the cache if there is a context instruction,
6589 // as the result will only be valid in the specified context.
6590 if (CtxI)
6591 return getConstantMultipleImpl(S, CtxI);
6592
6593 auto I = ConstantMultipleCache.find(S);
6594 if (I != ConstantMultipleCache.end())
6595 return I->second;
6596
6597 APInt Result = getConstantMultipleImpl(S, CtxI);
6598 auto InsertPair = ConstantMultipleCache.insert({S, Result});
6599 assert(InsertPair.second && "Should insert a new key");
6600 return InsertPair.first->second;
6601}
6602
6604 APInt Multiple = getConstantMultiple(S);
6605 return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6606}
6607
6609 const Instruction *CtxI) {
6610 return std::min(getConstantMultiple(S, CtxI).countTrailingZeros(),
6611 (unsigned)getTypeSizeInBits(S->getType()));
6612}
6613
6614/// Helper method to assign a range to V from metadata present in the IR.
6615static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6617 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6618 return getConstantRangeFromMetadata(*MD);
6619 if (const auto *CB = dyn_cast<CallBase>(V))
6620 if (std::optional<ConstantRange> Range = CB->getRange())
6621 return Range;
6622 }
6623 if (auto *A = dyn_cast<Argument>(V))
6624 if (std::optional<ConstantRange> Range = A->getRange())
6625 return Range;
6626
6627 return std::nullopt;
6628}
6629
6631 SCEV::NoWrapFlags Flags) {
6632 if (AddRec->getNoWrapFlags(Flags) != Flags) {
6633 AddRec->setNoWrapFlags(Flags);
6634 UnsignedRanges.erase(AddRec);
6635 SignedRanges.erase(AddRec);
6636 ConstantMultipleCache.erase(AddRec);
6637 }
6638}
6639
6640ConstantRange ScalarEvolution::
6641getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6642 const DataLayout &DL = getDataLayout();
6643
6644 unsigned BitWidth = getTypeSizeInBits(U->getType());
6645 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6646
6647 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6648 // use information about the trip count to improve our available range. Note
6649 // that the trip count independent cases are already handled by known bits.
6650 // WARNING: The definition of recurrence used here is subtly different than
6651 // the one used by AddRec (and thus most of this file). Step is allowed to
6652 // be arbitrarily loop varying here, where AddRec allows only loop invariant
6653 // and other addrecs in the same loop (for non-affine addrecs). The code
6654 // below intentionally handles the case where step is not loop invariant.
6655 auto *P = dyn_cast<PHINode>(U->getValue());
6656 if (!P)
6657 return FullSet;
6658
6659 // Make sure that no Phi input comes from an unreachable block. Otherwise,
6660 // even the values that are not available in these blocks may come from them,
6661 // and this leads to false-positive recurrence test.
6662 for (auto *Pred : predecessors(P->getParent()))
6663 if (!DT.isReachableFromEntry(Pred))
6664 return FullSet;
6665
6666 BinaryOperator *BO;
6667 Value *Start, *Step;
6668 if (!matchSimpleRecurrence(P, BO, Start, Step))
6669 return FullSet;
6670
6671 // If we found a recurrence in reachable code, we must be in a loop. Note
6672 // that BO might be in some subloop of L, and that's completely okay.
6673 auto *L = LI.getLoopFor(P->getParent());
6674 assert(L && L->getHeader() == P->getParent());
6675 if (!L->contains(BO->getParent()))
6676 // NOTE: This bailout should be an assert instead. However, asserting
6677 // the condition here exposes a case where LoopFusion is querying SCEV
6678 // with malformed loop information during the midst of the transform.
6679 // There doesn't appear to be an obvious fix, so for the moment bailout
6680 // until the caller issue can be fixed. PR49566 tracks the bug.
6681 return FullSet;
6682
6683 // TODO: Extend to other opcodes such as mul, and div
6684 switch (BO->getOpcode()) {
6685 default:
6686 return FullSet;
6687 case Instruction::AShr:
6688 case Instruction::LShr:
6689 case Instruction::Shl:
6690 break;
6691 };
6692
6693 if (BO->getOperand(0) != P)
6694 // TODO: Handle the power function forms some day.
6695 return FullSet;
6696
6697 unsigned TC = getSmallConstantMaxTripCount(L);
6698 if (!TC || TC >= BitWidth)
6699 return FullSet;
6700
6701 auto KnownStart = computeKnownBits(Start, DL, &AC, nullptr, &DT);
6702 auto KnownStep = computeKnownBits(Step, DL, &AC, nullptr, &DT);
6703 assert(KnownStart.getBitWidth() == BitWidth &&
6704 KnownStep.getBitWidth() == BitWidth);
6705
6706 // Compute total shift amount, being careful of overflow and bitwidths.
6707 auto MaxShiftAmt = KnownStep.getMaxValue();
6708 APInt TCAP(BitWidth, TC-1);
6709 bool Overflow = false;
6710 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6711 if (Overflow)
6712 return FullSet;
6713
6714 switch (BO->getOpcode()) {
6715 default:
6716 llvm_unreachable("filtered out above");
6717 case Instruction::AShr: {
6718 // For each ashr, three cases:
6719 // shift = 0 => unchanged value
6720 // saturation => 0 or -1
6721 // other => a value closer to zero (of the same sign)
6722 // Thus, the end value is closer to zero than the start.
6723 auto KnownEnd = KnownBits::ashr(KnownStart,
6724 KnownBits::makeConstant(TotalShift));
6725 if (KnownStart.isNonNegative())
6726 // Analogous to lshr (simply not yet canonicalized)
6727 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6728 KnownStart.getMaxValue() + 1);
6729 if (KnownStart.isNegative())
6730 // End >=u Start && End <=s Start
6731 return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6732 KnownEnd.getMaxValue() + 1);
6733 break;
6734 }
6735 case Instruction::LShr: {
6736 // For each lshr, three cases:
6737 // shift = 0 => unchanged value
6738 // saturation => 0
6739 // other => a smaller positive number
6740 // Thus, the low end of the unsigned range is the last value produced.
6741 auto KnownEnd = KnownBits::lshr(KnownStart,
6742 KnownBits::makeConstant(TotalShift));
6743 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6744 KnownStart.getMaxValue() + 1);
6745 }
6746 case Instruction::Shl: {
6747 // Iff no bits are shifted out, value increases on every shift.
6748 auto KnownEnd = KnownBits::shl(KnownStart,
6749 KnownBits::makeConstant(TotalShift));
6750 if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6751 return ConstantRange(KnownStart.getMinValue(),
6752 KnownEnd.getMaxValue() + 1);
6753 break;
6754 }
6755 };
6756 return FullSet;
6757}
6758
6759// The goal of this function is to check if recursively visiting the operands
6760// of this PHI might lead to an infinite loop. If we do see such a loop,
6761// there's no good way to break it, so we avoid analyzing such cases.
6762//
6763// getRangeRef previously used a visited set to avoid infinite loops, but this
6764// caused other issues: the result was dependent on the order of getRangeRef
6765// calls, and the interaction with createSCEVIter could cause a stack overflow
6766// in some cases (see issue #148253).
6767//
6768// FIXME: The way this is implemented is overly conservative; this checks
6769// for a few obviously safe patterns, but anything that doesn't lead to
6770// recursion is fine.
6772 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6774 return true;
6775
6776 if (all_of(PHI->operands(),
6777 [&](Value *Operand) { return DT.dominates(Operand, PHI); }))
6778 return true;
6779
6780 return false;
6781}
6782
6783const ConstantRange &
6784ScalarEvolution::getRangeRefIter(const SCEV *S,
6785 ScalarEvolution::RangeSignHint SignHint) {
6786 DenseMap<const SCEV *, ConstantRange> &Cache =
6787 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6788 : SignedRanges;
6789 SmallVector<SCEVUse> WorkList;
6790 SmallPtrSet<const SCEV *, 8> Seen;
6791
6792 // Add Expr to the worklist, if Expr is either an N-ary expression or a
6793 // SCEVUnknown PHI node.
6794 auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6795 if (!Seen.insert(Expr).second)
6796 return;
6797 if (Cache.contains(Expr))
6798 return;
6799 switch (Expr->getSCEVType()) {
6800 case scUnknown:
6802 break;
6803 [[fallthrough]];
6804 case scConstant:
6805 case scVScale:
6806 case scTruncate:
6807 case scZeroExtend:
6808 case scSignExtend:
6809 case scPtrToAddr:
6810 case scPtrToInt:
6811 case scAddExpr:
6812 case scMulExpr:
6813 case scUDivExpr:
6814 case scAddRecExpr:
6815 case scUMaxExpr:
6816 case scSMaxExpr:
6817 case scUMinExpr:
6818 case scSMinExpr:
6820 WorkList.push_back(Expr);
6821 break;
6822 case scCouldNotCompute:
6823 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6824 }
6825 };
6826 AddToWorklist(S);
6827
6828 // Build worklist by queuing operands of N-ary expressions and phi nodes.
6829 for (unsigned I = 0; I != WorkList.size(); ++I) {
6830 const SCEV *P = WorkList[I];
6831 auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6832 // If it is not a `SCEVUnknown`, just recurse into operands.
6833 if (!UnknownS) {
6834 for (const SCEV *Op : P->operands())
6835 AddToWorklist(Op);
6836 continue;
6837 }
6838 // `SCEVUnknown`'s require special treatment.
6839 if (PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6840 if (!RangeRefPHIAllowedOperands(DT, P))
6841 continue;
6842 for (auto &Op : reverse(P->operands()))
6843 AddToWorklist(getSCEV(Op));
6844 }
6845 }
6846
6847 if (!WorkList.empty()) {
6848 // Use getRangeRef to compute ranges for items in the worklist in reverse
6849 // order. This will force ranges for earlier operands to be computed before
6850 // their users in most cases.
6851 for (const SCEV *P : reverse(drop_begin(WorkList))) {
6852 getRangeRef(P, SignHint);
6853 }
6854 }
6855
6856 return getRangeRef(S, SignHint, 0);
6857}
6858
6859/// Determine the range for a particular SCEV. If SignHint is
6860/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6861/// with a "cleaner" unsigned (resp. signed) representation.
6862const ConstantRange &ScalarEvolution::getRangeRef(
6863 const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6864 DenseMap<const SCEV *, ConstantRange> &Cache =
6865 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6866 : SignedRanges;
6868 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6870
6871 // See if we've computed this range already.
6872 auto I = Cache.find(S);
6873 if (I != Cache.end())
6874 return I->second;
6875
6876 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6877 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6878
6879 // Switch to iteratively computing the range for S, if it is part of a deeply
6880 // nested expression.
6882 return getRangeRefIter(S, SignHint);
6883
6884 unsigned BitWidth = getTypeSizeInBits(S->getType());
6885 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6886 using OBO = OverflowingBinaryOperator;
6887
6888 // If the value has known zeros, the maximum value will have those known zeros
6889 // as well.
6890 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6891 APInt Multiple = getNonZeroConstantMultiple(S);
6892 APInt Remainder = APInt::getMaxValue(BitWidth).urem(Multiple);
6893 if (!Remainder.isZero())
6894 ConservativeResult =
6895 ConstantRange(APInt::getMinValue(BitWidth),
6896 APInt::getMaxValue(BitWidth) - Remainder + 1);
6897 }
6898 else {
6899 uint32_t TZ = getMinTrailingZeros(S);
6900 if (TZ != 0) {
6901 ConservativeResult = ConstantRange(
6903 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6904 }
6905 }
6906
6907 switch (S->getSCEVType()) {
6908 case scConstant:
6909 llvm_unreachable("Already handled above.");
6910 case scVScale:
6911 return setRange(S, SignHint, getVScaleRange(&F, BitWidth));
6912 case scTruncate: {
6913 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6914 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6915 return setRange(
6916 Trunc, SignHint,
6917 ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6918 }
6919 case scZeroExtend: {
6920 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6921 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6922 return setRange(
6923 ZExt, SignHint,
6924 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6925 }
6926 case scSignExtend: {
6927 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6928 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6929 return setRange(
6930 SExt, SignHint,
6931 ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6932 }
6933 case scPtrToAddr:
6934 case scPtrToInt: {
6935 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6936 ConstantRange X = getRangeRef(Cast->getOperand(), SignHint, Depth + 1);
6937 return setRange(Cast, SignHint, X);
6938 }
6939 case scAddExpr: {
6940 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6941 // Check if this is a URem pattern: A - (A / B) * B, which is always < B.
6942 const SCEV *URemLHS = nullptr, *URemRHS = nullptr;
6943 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED &&
6944 match(S, m_scev_URem(m_SCEV(URemLHS), m_SCEV(URemRHS), *this))) {
6945 ConstantRange LHSRange = getRangeRef(URemLHS, SignHint, Depth + 1);
6946 ConstantRange RHSRange = getRangeRef(URemRHS, SignHint, Depth + 1);
6947 ConservativeResult =
6948 ConservativeResult.intersectWith(LHSRange.urem(RHSRange), RangeType);
6949 }
6950 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6951 unsigned WrapType = OBO::AnyWrap;
6952 if (Add->hasNoSignedWrap())
6953 WrapType |= OBO::NoSignedWrap;
6954 if (Add->hasNoUnsignedWrap())
6955 WrapType |= OBO::NoUnsignedWrap;
6956 for (const SCEV *Op : drop_begin(Add->operands()))
6957 X = X.addWithNoWrap(getRangeRef(Op, SignHint, Depth + 1), WrapType,
6958 RangeType);
6959 return setRange(Add, SignHint,
6960 ConservativeResult.intersectWith(X, RangeType));
6961 }
6962 case scMulExpr: {
6963 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6964 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6965 for (const SCEV *Op : drop_begin(Mul->operands()))
6966 X = X.multiply(getRangeRef(Op, SignHint, Depth + 1));
6967 return setRange(Mul, SignHint,
6968 ConservativeResult.intersectWith(X, RangeType));
6969 }
6970 case scUDivExpr: {
6971 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6972 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6973 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6974 return setRange(UDiv, SignHint,
6975 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6976 }
6977 case scAddRecExpr: {
6978 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6979 // If there's no unsigned wrap, the value will never be less than its
6980 // initial value.
6981 if (AddRec->hasNoUnsignedWrap()) {
6982 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6983 if (!UnsignedMinValue.isZero())
6984 ConservativeResult = ConservativeResult.intersectWith(
6985 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6986 }
6987
6988 // If there's no signed wrap, and all the operands except initial value have
6989 // the same sign or zero, the value won't ever be:
6990 // 1: smaller than initial value if operands are non negative,
6991 // 2: bigger than initial value if operands are non positive.
6992 // For both cases, value can not cross signed min/max boundary.
6993 if (AddRec->hasNoSignedWrap()) {
6994 bool AllNonNeg = true;
6995 bool AllNonPos = true;
6996 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6997 if (!isKnownNonNegative(AddRec->getOperand(i)))
6998 AllNonNeg = false;
6999 if (!isKnownNonPositive(AddRec->getOperand(i)))
7000 AllNonPos = false;
7001 }
7002 if (AllNonNeg)
7003 ConservativeResult = ConservativeResult.intersectWith(
7006 RangeType);
7007 else if (AllNonPos)
7008 ConservativeResult = ConservativeResult.intersectWith(
7010 getSignedRangeMax(AddRec->getStart()) +
7011 1),
7012 RangeType);
7013 }
7014
7015 // TODO: non-affine addrec
7016 if (AddRec->isAffine()) {
7017 const SCEV *MaxBEScev =
7019 if (!isa<SCEVCouldNotCompute>(MaxBEScev)) {
7020 APInt MaxBECount = cast<SCEVConstant>(MaxBEScev)->getAPInt();
7021
7022 // Adjust MaxBECount to the same bitwidth as AddRec. We can truncate if
7023 // MaxBECount's active bits are all <= AddRec's bit width.
7024 if (MaxBECount.getBitWidth() > BitWidth &&
7025 MaxBECount.getActiveBits() <= BitWidth)
7026 MaxBECount = MaxBECount.trunc(BitWidth);
7027 else if (MaxBECount.getBitWidth() < BitWidth)
7028 MaxBECount = MaxBECount.zext(BitWidth);
7029
7030 if (MaxBECount.getBitWidth() == BitWidth) {
7031 auto [RangeFromAffine, Flags] = getRangeForAffineAR(
7032 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
7033 ConservativeResult =
7034 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
7035 const_cast<SCEVAddRecExpr *>(AddRec)->setNoWrapFlags(Flags);
7036
7037 auto RangeFromFactoring = getRangeViaFactoring(
7038 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
7039 ConservativeResult =
7040 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
7041 }
7042 }
7043
7044 // Now try symbolic BE count and more powerful methods.
7046 const SCEV *SymbolicMaxBECount =
7048 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
7049 getTypeSizeInBits(MaxBEScev->getType()) <= BitWidth &&
7050 AddRec->hasNoSelfWrap()) {
7051 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
7052 AddRec, SymbolicMaxBECount, BitWidth, SignHint);
7053 ConservativeResult =
7054 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
7055 }
7056 }
7057 }
7058
7059 return setRange(AddRec, SignHint, std::move(ConservativeResult));
7060 }
7061 case scUMaxExpr:
7062 case scSMaxExpr:
7063 case scUMinExpr:
7064 case scSMinExpr:
7065 case scSequentialUMinExpr: {
7067 switch (S->getSCEVType()) {
7068 case scUMaxExpr:
7069 ID = Intrinsic::umax;
7070 break;
7071 case scSMaxExpr:
7072 ID = Intrinsic::smax;
7073 break;
7074 case scUMinExpr:
7076 ID = Intrinsic::umin;
7077 break;
7078 case scSMinExpr:
7079 ID = Intrinsic::smin;
7080 break;
7081 default:
7082 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
7083 }
7084
7085 const auto *NAry = cast<SCEVNAryExpr>(S);
7086 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
7087 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
7088 X = X.intrinsic(
7089 ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
7090 return setRange(S, SignHint,
7091 ConservativeResult.intersectWith(X, RangeType));
7092 }
7093 case scUnknown: {
7094 const SCEVUnknown *U = cast<SCEVUnknown>(S);
7095 Value *V = U->getValue();
7096
7097 // Check if the IR explicitly contains !range metadata.
7098 std::optional<ConstantRange> MDRange = GetRangeFromMetadata(V);
7099 if (MDRange)
7100 ConservativeResult =
7101 ConservativeResult.intersectWith(*MDRange, RangeType);
7102
7103 // Use facts about recurrences in the underlying IR. Note that add
7104 // recurrences are AddRecExprs and thus don't hit this path. This
7105 // primarily handles shift recurrences.
7106 auto CR = getRangeForUnknownRecurrence(U);
7107 ConservativeResult = ConservativeResult.intersectWith(CR);
7108
7109 // See if ValueTracking can give us a useful range.
7110 const DataLayout &DL = getDataLayout();
7111 KnownBits Known = computeKnownBits(V, DL, &AC, nullptr, &DT);
7112 if (Known.getBitWidth() != BitWidth)
7113 Known = Known.zextOrTrunc(BitWidth);
7114
7115 // ValueTracking may be able to compute a tighter result for the number of
7116 // sign bits than for the value of those sign bits.
7117 unsigned NS = ComputeNumSignBits(V, DL, &AC, nullptr, &DT);
7118 if (U->getType()->isPointerTy()) {
7119 // If the pointer size is larger than the index size type, this can cause
7120 // NS to be larger than BitWidth. So compensate for this.
7121 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
7122 int ptrIdxDiff = ptrSize - BitWidth;
7123 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
7124 NS -= ptrIdxDiff;
7125 }
7126
7127 if (NS > 1) {
7128 // If we know any of the sign bits, we know all of the sign bits.
7129 if (!Known.Zero.getHiBits(NS).isZero())
7130 Known.Zero.setHighBits(NS);
7131 if (!Known.One.getHiBits(NS).isZero())
7132 Known.One.setHighBits(NS);
7133 }
7134
7135 if (Known.getMinValue() != Known.getMaxValue() + 1)
7136 ConservativeResult = ConservativeResult.intersectWith(
7137 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
7138 RangeType);
7139 if (NS > 1)
7140 ConservativeResult = ConservativeResult.intersectWith(
7141 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
7142 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
7143 RangeType);
7144
7145 if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
7146 // Strengthen the range if the underlying IR value is a
7147 // global/alloca/heap allocation using the size of the object.
7148 bool CanBeNull;
7149 uint64_t DerefBytes = V->getPointerDereferenceableBytes(
7150 DL, CanBeNull, /*CanBeFreed=*/nullptr);
7151 if (DerefBytes > 1 && isUIntN(BitWidth, DerefBytes)) {
7152 // The highest address the object can start is DerefBytes bytes before
7153 // the end (unsigned max value). If this value is not a multiple of the
7154 // alignment, the last possible start value is the next lowest multiple
7155 // of the alignment. Note: The computations below cannot overflow,
7156 // because if they would there's no possible start address for the
7157 // object.
7158 APInt MaxVal =
7159 APInt::getMaxValue(BitWidth) - APInt(BitWidth, DerefBytes);
7160 uint64_t Align = U->getValue()->getPointerAlignment(DL).value();
7161 uint64_t Rem = MaxVal.urem(Align);
7162 MaxVal -= APInt(BitWidth, Rem);
7163 APInt MinVal = APInt::getZero(BitWidth);
7164 if (llvm::isKnownNonZero(V, DL))
7165 MinVal = Align;
7166 ConservativeResult = ConservativeResult.intersectWith(
7167 ConstantRange::getNonEmpty(MinVal, MaxVal + 1), RangeType);
7168 }
7169 }
7170
7171 // A range of Phi is a subset of union of all ranges of its input.
7172 if (PHINode *Phi = dyn_cast<PHINode>(V)) {
7173 // SCEVExpander sometimes creates SCEVUnknowns that are secretly
7174 // AddRecs; return the range for the corresponding AddRec.
7175 if (auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V)))
7176 return getRangeRef(AR, SignHint, Depth + 1);
7177
7178 // Make sure that we do not run over cycled Phis.
7179 if (RangeRefPHIAllowedOperands(DT, Phi)) {
7180 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
7181
7182 for (const auto &Op : Phi->operands()) {
7183 auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
7184 RangeFromOps = RangeFromOps.unionWith(OpRange);
7185 // No point to continue if we already have a full set.
7186 if (RangeFromOps.isFullSet())
7187 break;
7188 }
7189 ConservativeResult =
7190 ConservativeResult.intersectWith(RangeFromOps, RangeType);
7191 }
7192 }
7193
7194 // vscale can't be equal to zero
7195 if (const auto *II = dyn_cast<IntrinsicInst>(V))
7196 if (II->getIntrinsicID() == Intrinsic::vscale) {
7197 ConstantRange Disallowed = APInt::getZero(BitWidth);
7198 ConservativeResult = ConservativeResult.difference(Disallowed);
7199 }
7200
7201 return setRange(U, SignHint, std::move(ConservativeResult));
7202 }
7203 case scCouldNotCompute:
7204 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
7205 }
7206
7207 return setRange(S, SignHint, std::move(ConservativeResult));
7208}
7209
7210// Given a StartRange, Step and MaxBECount for an expression compute a range of
7211// values that the expression can take. Initially, the expression has a value
7212// from StartRange and then is changed by Step up to MaxBECount times. Signed
7213// argument defines if we treat Step as signed or unsigned. The second return
7214// value indicates that no wrapping occurred.
7215static std::pair<ConstantRange, bool>
7217 const APInt &MaxBECount, bool Signed) {
7218 unsigned BitWidth = Step.getBitWidth();
7219 assert(BitWidth == StartRange.getBitWidth() &&
7220 BitWidth == MaxBECount.getBitWidth() && "mismatched bit widths");
7221 // If either Step or MaxBECount is 0, then the expression won't change, and we
7222 // just need to return the initial range.
7223 if (Step == 0 || MaxBECount == 0)
7224 return {StartRange, true};
7225
7226 // If we don't know anything about the initial value (i.e. StartRange is
7227 // FullRange), then we don't know anything about the final range either.
7228 // Return FullRange.
7229 if (StartRange.isFullSet())
7230 return {ConstantRange::getFull(BitWidth), false};
7231
7232 // If Step is signed and negative, then we use its absolute value, but we also
7233 // note that we're moving in the opposite direction.
7234 bool Descending = Signed && Step.isNegative();
7235
7236 if (Signed)
7237 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
7238 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
7239 // This equations hold true due to the well-defined wrap-around behavior of
7240 // APInt.
7241 Step = Step.abs();
7242
7243 // Check if Offset is more than full span of BitWidth. If it is, the
7244 // expression is guaranteed to overflow.
7245 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
7246 return {ConstantRange::getFull(BitWidth), false};
7247
7248 // Offset is by how much the expression can change. Checks above guarantee no
7249 // overflow here.
7250 APInt Offset = Step * MaxBECount;
7251
7252 // Minimum value of the final range will match the minimal value of StartRange
7253 // if the expression is increasing and will be decreased by Offset otherwise.
7254 // Maximum value of the final range will match the maximal value of StartRange
7255 // if the expression is decreasing and will be increased by Offset otherwise.
7256 APInt StartLower = StartRange.getLower();
7257 APInt StartUpper = StartRange.getUpper() - 1;
7258 bool Overflow;
7259 APInt MovedBoundary;
7260 if (Signed) {
7261 // This does not use sadd_ov, as we want to check overflow for a signed
7262 // start with an unsigned offset.
7263 if (Descending) {
7264 MovedBoundary = StartLower - std::move(Offset);
7265 Overflow = MovedBoundary.sgt(StartLower) || StartRange.isSignWrappedSet();
7266 } else {
7267 MovedBoundary = StartUpper + std::move(Offset);
7268 Overflow = MovedBoundary.slt(StartUpper) || StartRange.isSignWrappedSet();
7269 }
7270 } else {
7271 MovedBoundary = StartUpper.uadd_ov(std::move(Offset), Overflow);
7272 Overflow |= StartRange.isWrappedSet();
7273 }
7274
7275 // It's possible that the new minimum/maximum value will fall into the initial
7276 // range (due to wrap around). This means that the expression can take any
7277 // value in this bitwidth, and we have to return full range.
7278 if (StartRange.contains(MovedBoundary))
7279 return {ConstantRange::getFull(BitWidth), false};
7280
7281 APInt NewLower =
7282 Descending ? std::move(MovedBoundary) : std::move(StartLower);
7283 APInt NewUpper =
7284 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
7285 NewUpper += 1;
7286
7287 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
7288 return {ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)),
7289 !Overflow};
7290}
7291
7292std::pair<ConstantRange, SCEV::NoWrapFlags>
7293ScalarEvolution::getRangeForAffineAR(const SCEV *Start, const SCEV *Step,
7294 const APInt &MaxBECount) {
7295 assert(getTypeSizeInBits(Start->getType()) ==
7296 getTypeSizeInBits(Step->getType()) &&
7297 getTypeSizeInBits(Start->getType()) == MaxBECount.getBitWidth() &&
7298 "mismatched bit widths");
7299
7300 // First, consider step signed.
7301 ConstantRange StartSRange = getSignedRange(Start);
7302 ConstantRange StepSRange = getSignedRange(Step);
7303
7304 // If Step can be both positive and negative, we need to find ranges for the
7305 // maximum absolute step values in both directions and union them.
7306 auto [SR1, NSW1] = getRangeForAffineARHelper(
7307 StepSRange.getSignedMin(), StartSRange, MaxBECount, /*Signed=*/true);
7308 auto [SR2, NSW2] = getRangeForAffineARHelper(StepSRange.getSignedMax(),
7309 StartSRange, MaxBECount,
7310 /*Signed=*/true);
7311 ConstantRange SR = SR1.unionWith(SR2);
7312
7313 // Next, consider step unsigned.
7314 auto [UR, NUW] = getRangeForAffineARHelper(
7315 getUnsignedRangeMax(Step), getUnsignedRange(Start), MaxBECount,
7316 /*Signed=*/false);
7317
7319 if (NUW)
7321 if (NSW1 && NSW2)
7323
7324 // Finally, intersect signed and unsigned ranges.
7326}
7327
7328ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
7329 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
7330 ScalarEvolution::RangeSignHint SignHint) {
7331 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
7332 assert(AddRec->hasNoSelfWrap() &&
7333 "This only works for non-self-wrapping AddRecs!");
7334 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
7335 const SCEV *Step = AddRec->getStepRecurrence(*this);
7336 // Only deal with constant step to save compile time.
7337 if (!isa<SCEVConstant>(Step))
7338 return ConstantRange::getFull(BitWidth);
7339 // Let's make sure that we can prove that we do not self-wrap during
7340 // MaxBECount iterations. We need this because MaxBECount is a maximum
7341 // iteration count estimate, and we might infer nw from some exit for which we
7342 // do not know max exit count (or any other side reasoning).
7343 // TODO: Turn into assert at some point.
7344 if (getTypeSizeInBits(MaxBECount->getType()) >
7345 getTypeSizeInBits(AddRec->getType()))
7346 return ConstantRange::getFull(BitWidth);
7347 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
7348 const SCEV *RangeWidth = getMinusOne(AddRec->getType());
7349 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
7350 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
7351 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
7352 MaxItersWithoutWrap))
7353 return ConstantRange::getFull(BitWidth);
7354
7355 ICmpInst::Predicate LEPred =
7357 ICmpInst::Predicate GEPred =
7359 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7360
7361 // We know that there is no self-wrap. Let's take Start and End values and
7362 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7363 // the iteration. They either lie inside the range [Min(Start, End),
7364 // Max(Start, End)] or outside it:
7365 //
7366 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
7367 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
7368 //
7369 // No self wrap flag guarantees that the intermediate values cannot be BOTH
7370 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7371 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7372 // Start <= End and step is positive, or Start >= End and step is negative.
7373 const SCEV *Start = applyLoopGuards(AddRec->getStart(), AddRec->getLoop());
7374 ConstantRange StartRange = getRangeRef(Start, SignHint);
7375 ConstantRange EndRange = getRangeRef(End, SignHint);
7376 ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7377 // If they already cover full iteration space, we will know nothing useful
7378 // even if we prove what we want to prove.
7379 if (RangeBetween.isFullSet())
7380 return RangeBetween;
7381 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7382 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7383 : RangeBetween.isWrappedSet();
7384 if (IsWrappedSet)
7385 return ConstantRange::getFull(BitWidth);
7386
7387 if (isKnownPositive(Step) &&
7388 isKnownPredicateViaConstantRanges(LEPred, Start, End))
7389 return RangeBetween;
7390 if (isKnownNegative(Step) &&
7391 isKnownPredicateViaConstantRanges(GEPred, Start, End))
7392 return RangeBetween;
7393 return ConstantRange::getFull(BitWidth);
7394}
7395
7396ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7397 const SCEV *Step,
7398 const APInt &MaxBECount) {
7399 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7400 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7401
7402 unsigned BitWidth = MaxBECount.getBitWidth();
7403 assert(getTypeSizeInBits(Start->getType()) == BitWidth &&
7404 getTypeSizeInBits(Step->getType()) == BitWidth &&
7405 "mismatched bit widths");
7406
7407 struct SelectPattern {
7408 Value *Condition = nullptr;
7409 APInt TrueValue;
7410 APInt FalseValue;
7411
7412 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7413 const SCEV *S) {
7414 std::optional<unsigned> CastOp;
7415 APInt Offset(BitWidth, 0);
7416
7418 "Should be!");
7419
7420 // Peel off a constant offset. In the future we could consider being
7421 // smarter here and handle {Start+Step,+,Step} too.
7422 const APInt *Off;
7423 if (match(S, m_scev_Add(m_scev_APInt(Off), m_SCEV(S))))
7424 Offset = *Off;
7425
7426 // Peel off a cast operation
7427 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7428 CastOp = SCast->getSCEVType();
7429 S = SCast->getOperand();
7430 }
7431
7432 using namespace llvm::PatternMatch;
7433
7434 auto *SU = dyn_cast<SCEVUnknown>(S);
7435 const APInt *TrueVal, *FalseVal;
7436 if (!SU ||
7437 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7438 m_APInt(FalseVal)))) {
7439 Condition = nullptr;
7440 return;
7441 }
7442
7443 TrueValue = *TrueVal;
7444 FalseValue = *FalseVal;
7445
7446 // Re-apply the cast we peeled off earlier
7447 if (CastOp)
7448 switch (*CastOp) {
7449 default:
7450 llvm_unreachable("Unknown SCEV cast type!");
7451
7452 case scTruncate:
7453 TrueValue = TrueValue.trunc(BitWidth);
7454 FalseValue = FalseValue.trunc(BitWidth);
7455 break;
7456 case scZeroExtend:
7457 TrueValue = TrueValue.zext(BitWidth);
7458 FalseValue = FalseValue.zext(BitWidth);
7459 break;
7460 case scSignExtend:
7461 TrueValue = TrueValue.sext(BitWidth);
7462 FalseValue = FalseValue.sext(BitWidth);
7463 break;
7464 }
7465
7466 // Re-apply the constant offset we peeled off earlier
7467 TrueValue += Offset;
7468 FalseValue += Offset;
7469 }
7470
7471 bool isRecognized() { return Condition != nullptr; }
7472 };
7473
7474 SelectPattern StartPattern(*this, BitWidth, Start);
7475 if (!StartPattern.isRecognized())
7476 return ConstantRange::getFull(BitWidth);
7477
7478 SelectPattern StepPattern(*this, BitWidth, Step);
7479 if (!StepPattern.isRecognized())
7480 return ConstantRange::getFull(BitWidth);
7481
7482 if (StartPattern.Condition != StepPattern.Condition) {
7483 // We don't handle this case today; but we could, by considering four
7484 // possibilities below instead of two. I'm not sure if there are cases where
7485 // that will help over what getRange already does, though.
7486 return ConstantRange::getFull(BitWidth);
7487 }
7488
7489 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7490 // construct arbitrary general SCEV expressions here. This function is called
7491 // from deep in the call stack, and calling getSCEV (on a sext instruction,
7492 // say) can end up caching a suboptimal value.
7493
7494 // FIXME: without the explicit `this` receiver below, MSVC errors out with
7495 // C2352 and C2512 (otherwise it isn't needed).
7496
7497 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7498 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7499 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7500 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7501
7502 ConstantRange TrueRange =
7503 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount).first;
7504 ConstantRange FalseRange =
7505 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount).first;
7506
7507 return TrueRange.unionWith(FalseRange);
7508}
7509
7510SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7511 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
7512 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7513
7514 // Return early if there are no flags to propagate to the SCEV.
7516 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(BinOp);
7517 PDI && PDI->isDisjoint()) {
7519 } else {
7520 if (BinOp->hasNoUnsignedWrap())
7522 if (BinOp->hasNoSignedWrap())
7524 }
7525 if (Flags == SCEV::FlagAnyWrap)
7526 return SCEV::FlagAnyWrap;
7527
7528 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
7529}
7530
7531const Instruction *
7532ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7533 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7534 return &*AddRec->getLoop()->getHeader()->begin();
7535 if (auto *U = dyn_cast<SCEVUnknown>(S))
7536 if (auto *I = dyn_cast<Instruction>(U->getValue()))
7537 return I;
7538 return nullptr;
7539}
7540
7541const Instruction *ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops,
7542 bool &Precise) {
7543 Precise = true;
7544 // Do a bounded search of the def relation of the requested SCEVs.
7545 SmallPtrSet<const SCEV *, 16> Visited;
7546 SmallVector<SCEVUse> Worklist;
7547 auto pushOp = [&](const SCEV *S) {
7548 if (!Visited.insert(S).second)
7549 return;
7550 // Threshold of 30 here is arbitrary.
7551 if (Visited.size() > 30) {
7552 Precise = false;
7553 return;
7554 }
7555 Worklist.push_back(S);
7556 };
7557
7558 for (SCEVUse S : Ops)
7559 pushOp(S);
7560
7561 const Instruction *Bound = nullptr;
7562 while (!Worklist.empty()) {
7563 SCEVUse S = Worklist.pop_back_val();
7564 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7565 if (!Bound || DT.dominates(Bound, DefI))
7566 Bound = DefI;
7567 } else {
7568 for (SCEVUse Op : S->operands())
7569 pushOp(Op);
7570 }
7571 }
7572 return Bound ? Bound : &*F.getEntryBlock().begin();
7573}
7574
7575const Instruction *
7576ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops) {
7577 bool Discard;
7578 return getDefiningScopeBound(Ops, Discard);
7579}
7580
7581bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7582 const Instruction *B) {
7583 if (A->getParent() == B->getParent() &&
7585 B->getIterator()))
7586 return true;
7587
7588 auto *BLoop = LI.getLoopFor(B->getParent());
7589 if (BLoop && BLoop->getHeader() == B->getParent() &&
7590 BLoop->getLoopPreheader() == A->getParent() &&
7592 A->getParent()->end()) &&
7593 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7594 B->getIterator()))
7595 return true;
7596 return false;
7597}
7598
7600 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ true);
7601 visitAll(Op, PC);
7602 return PC.MaybePoison.empty();
7603}
7604
7605bool ScalarEvolution::isGuaranteedNotToCauseUB(const SCEV *Op) {
7606 return !SCEVExprContains(Op, [this](const SCEV *S) {
7607 const SCEV *Op1;
7608 bool M = match(S, m_scev_UDiv(m_SCEV(), m_SCEV(Op1)));
7609 // The UDiv may be UB if the divisor is poison or zero. Unless the divisor
7610 // is a non-zero constant, we have to assume the UDiv may be UB.
7611 return M && (!isKnownNonZero(Op1) || !isGuaranteedNotToBePoison(Op1));
7612 });
7613}
7614
7615bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7616 // Only proceed if we can prove that I does not yield poison.
7618 return false;
7619
7620 // At this point we know that if I is executed, then it does not wrap
7621 // according to at least one of NSW or NUW. If I is not executed, then we do
7622 // not know if the calculation that I represents would wrap. Multiple
7623 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7624 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7625 // derived from other instructions that map to the same SCEV. We cannot make
7626 // that guarantee for cases where I is not executed. So we need to find a
7627 // upper bound on the defining scope for the SCEV, and prove that I is
7628 // executed every time we enter that scope. When the bounding scope is a
7629 // loop (the common case), this is equivalent to proving I executes on every
7630 // iteration of that loop.
7631 SmallVector<SCEVUse> SCEVOps;
7632 for (const Use &Op : I->operands()) {
7633 // I could be an extractvalue from a call to an overflow intrinsic.
7634 // TODO: We can do better here in some cases.
7635 if (isSCEVable(Op->getType()))
7636 SCEVOps.push_back(getSCEV(Op));
7637 }
7638 auto *DefI = getDefiningScopeBound(SCEVOps);
7639 return isGuaranteedToTransferExecutionTo(DefI, I);
7640}
7641
7642bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7643 // If we know that \c I can never be poison period, then that's enough.
7644 if (isSCEVExprNeverPoison(I))
7645 return true;
7646
7647 // If the loop only has one exit, then we know that, if the loop is entered,
7648 // any instruction dominating that exit will be executed. If any such
7649 // instruction would result in UB, the addrec cannot be poison.
7650 //
7651 // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7652 // also handles uses outside the loop header (they just need to dominate the
7653 // single exit).
7654
7655 auto *ExitingBB = L->getExitingBlock();
7656 if (!ExitingBB || !loopHasNoAbnormalExits(L))
7657 return false;
7658
7659 SmallPtrSet<const Value *, 16> KnownPoison;
7661
7662 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
7663 // things that are known to be poison under that assumption go on the
7664 // Worklist.
7665 KnownPoison.insert(I);
7666 Worklist.push_back(I);
7667
7668 while (!Worklist.empty()) {
7669 const Instruction *Poison = Worklist.pop_back_val();
7670
7671 for (const Use &U : Poison->uses()) {
7672 const Instruction *PoisonUser = cast<Instruction>(U.getUser());
7673 if (mustTriggerUB(PoisonUser, KnownPoison) &&
7674 DT.dominates(PoisonUser->getParent(), ExitingBB))
7675 return true;
7676
7677 if (propagatesPoison(U) && L->contains(PoisonUser))
7678 if (KnownPoison.insert(PoisonUser).second)
7679 Worklist.push_back(PoisonUser);
7680 }
7681 }
7682
7683 return false;
7684}
7685
7686ScalarEvolution::LoopProperties
7687ScalarEvolution::getLoopProperties(const Loop *L) {
7688 using LoopProperties = ScalarEvolution::LoopProperties;
7689
7690 auto Itr = LoopPropertiesCache.find(L);
7691 if (Itr == LoopPropertiesCache.end()) {
7692 auto HasSideEffects = [](Instruction *I) {
7693 if (auto *SI = dyn_cast<StoreInst>(I))
7694 return !SI->isSimple();
7695
7696 if (I->mayThrow())
7697 return true;
7698
7699 // Non-volatile memset / memcpy do not count as side-effect for forward
7700 // progress.
7701 if (isa<MemIntrinsic>(I) && !I->isVolatile())
7702 return false;
7703
7704 return I->mayWriteToMemory();
7705 };
7706
7707 LoopProperties LP = {/* HasNoAbnormalExits */ true,
7708 /*HasNoSideEffects*/ true};
7709
7710 for (auto *BB : L->getBlocks())
7711 for (auto &I : *BB) {
7713 LP.HasNoAbnormalExits = false;
7714 if (HasSideEffects(&I))
7715 LP.HasNoSideEffects = false;
7716 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7717 break; // We're already as pessimistic as we can get.
7718 }
7719
7720 auto InsertPair = LoopPropertiesCache.insert({L, LP});
7721 assert(InsertPair.second && "We just checked!");
7722 Itr = InsertPair.first;
7723 }
7724
7725 return Itr->second;
7726}
7727
7729 // A mustprogress loop without side effects must be finite.
7730 // TODO: The check used here is very conservative. It's only *specific*
7731 // side effects which are well defined in infinite loops.
7732 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7733}
7734
7735const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7736 // Worklist item with a Value and a bool indicating whether all operands have
7737 // been visited already.
7740
7741 Stack.emplace_back(V, false);
7742 while (!Stack.empty()) {
7743 auto E = Stack.back();
7744 Value *CurV = E.getPointer();
7745
7746 if (getExistingSCEV(CurV)) {
7747 Stack.pop_back();
7748 continue;
7749 }
7750
7752 const SCEV *CreatedSCEV = nullptr;
7753 // If all operands have been visited already, create the SCEV.
7754 if (E.getInt()) {
7755 CreatedSCEV = createSCEV(CurV);
7756 } else {
7757 // Otherwise get the operands we need to create SCEV's for before creating
7758 // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7759 // just use it.
7760 CreatedSCEV = getOperandsToCreate(CurV, Ops);
7761 }
7762
7763 if (CreatedSCEV) {
7764 insertValueToMap(CurV, CreatedSCEV);
7765 Stack.pop_back();
7766 } else {
7767 Stack.back().setInt(true);
7768 // Queue its operands which need to be constructed.
7769 for (Value *Op : Ops)
7770 Stack.emplace_back(Op, false);
7771 }
7772 }
7773
7774 return getExistingSCEV(V);
7775}
7776
7777const SCEV *
7778ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7779 if (!isSCEVable(V->getType()))
7780 return getUnknown(V);
7781
7782 if (Instruction *I = dyn_cast<Instruction>(V)) {
7783 // Don't attempt to analyze instructions in blocks that aren't
7784 // reachable. Such instructions don't matter, and they aren't required
7785 // to obey basic rules for definitions dominating uses which this
7786 // analysis depends on.
7787 if (!DT.isReachableFromEntry(I->getParent()))
7788 return getUnknown(PoisonValue::get(V->getType()));
7789 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7790 return getConstant(CI);
7791 else if (isa<GlobalAlias>(V))
7792 return getUnknown(V);
7793 else if (!isa<ConstantExpr>(V))
7794 return getUnknown(V);
7795
7797 if (auto BO =
7799 bool IsConstArg = isa<ConstantInt>(BO->RHS);
7800 switch (BO->Opcode) {
7801 case Instruction::Add:
7802 case Instruction::Mul: {
7803 // For additions and multiplications, traverse add/mul chains for which we
7804 // can potentially create a single SCEV, to reduce the number of
7805 // get{Add,Mul}Expr calls.
7806 do {
7807 if (BO->Op) {
7808 if (BO->Op != V && getExistingSCEV(BO->Op)) {
7809 Ops.push_back(BO->Op);
7810 break;
7811 }
7812 }
7813 Ops.push_back(BO->RHS);
7814 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7816 if (!NewBO ||
7817 (BO->Opcode == Instruction::Add &&
7818 (NewBO->Opcode != Instruction::Add &&
7819 NewBO->Opcode != Instruction::Sub)) ||
7820 (BO->Opcode == Instruction::Mul &&
7821 NewBO->Opcode != Instruction::Mul)) {
7822 Ops.push_back(BO->LHS);
7823 break;
7824 }
7825 // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7826 // requires a SCEV for the LHS.
7827 if (BO->Op && (BO->IsNSW || BO->IsNUW)) {
7828 auto *I = dyn_cast<Instruction>(BO->Op);
7829 if (I && programUndefinedIfPoison(I)) {
7830 Ops.push_back(BO->LHS);
7831 break;
7832 }
7833 }
7834 BO = NewBO;
7835 } while (true);
7836 return nullptr;
7837 }
7838 case Instruction::Sub:
7839 case Instruction::UDiv:
7840 case Instruction::URem:
7841 break;
7842 case Instruction::AShr:
7843 case Instruction::Shl:
7844 case Instruction::Xor:
7845 if (!IsConstArg)
7846 return nullptr;
7847 break;
7848 case Instruction::And:
7849 case Instruction::Or:
7850 if (!IsConstArg && !BO->LHS->getType()->isIntegerTy(1))
7851 return nullptr;
7852 break;
7853 case Instruction::LShr:
7854 return getUnknown(V);
7855 default:
7856 llvm_unreachable("Unhandled binop");
7857 break;
7858 }
7859
7860 Ops.push_back(BO->LHS);
7861 Ops.push_back(BO->RHS);
7862 return nullptr;
7863 }
7864
7865 switch (U->getOpcode()) {
7866 case Instruction::Trunc:
7867 case Instruction::ZExt:
7868 case Instruction::SExt:
7869 case Instruction::PtrToAddr:
7870 case Instruction::PtrToInt:
7871 Ops.push_back(U->getOperand(0));
7872 return nullptr;
7873
7874 case Instruction::BitCast:
7875 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
7876 Ops.push_back(U->getOperand(0));
7877 return nullptr;
7878 }
7879 return getUnknown(V);
7880
7881 case Instruction::SDiv:
7882 case Instruction::SRem:
7883 Ops.push_back(U->getOperand(0));
7884 Ops.push_back(U->getOperand(1));
7885 return nullptr;
7886
7887 case Instruction::GetElementPtr:
7888 assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7889 "GEP source element type must be sized");
7890 llvm::append_range(Ops, U->operands());
7891 return nullptr;
7892
7893 case Instruction::IntToPtr:
7894 return getUnknown(V);
7895
7896 case Instruction::PHI:
7897 // getNodeForPHI has four ways to turn a PHI into a SCEV; retrieve the
7898 // relevant nodes for each of them.
7899 //
7900 // The first is just to call simplifyInstruction, and get something back
7901 // that isn't a PHI.
7902 if (Value *V = simplifyInstruction(
7903 cast<PHINode>(U),
7904 {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
7905 /*UseInstrInfo=*/true, /*CanUseUndef=*/false})) {
7906 assert(V);
7907 Ops.push_back(V);
7908 return nullptr;
7909 }
7910 // The second is createNodeForPHIWithIdenticalOperands: this looks for
7911 // operands which all perform the same operation, but haven't been
7912 // CSE'ed for whatever reason.
7913 if (BinaryOperator *BO = getCommonInstForPHI(cast<PHINode>(U))) {
7914 assert(BO);
7915 Ops.push_back(BO);
7916 return nullptr;
7917 }
7918 // The third is createNodeFromSelectLikePHI; this takes a PHI which
7919 // is equivalent to a select, and analyzes it like a select.
7920 {
7921 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
7923 assert(Cond);
7924 assert(LHS);
7925 assert(RHS);
7926 if (auto *CondICmp = dyn_cast<ICmpInst>(Cond)) {
7927 Ops.push_back(CondICmp->getOperand(0));
7928 Ops.push_back(CondICmp->getOperand(1));
7929 }
7930 Ops.push_back(Cond);
7931 Ops.push_back(LHS);
7932 Ops.push_back(RHS);
7933 return nullptr;
7934 }
7935 }
7936 // The fourth way is createAddRecFromPHI. It's complicated to handle here,
7937 // so just construct it recursively.
7938 //
7939 // In addition to getNodeForPHI, also construct nodes which might be needed
7940 // by getRangeRef.
7942 for (Value *V : cast<PHINode>(U)->operands())
7943 Ops.push_back(V);
7944 return nullptr;
7945 }
7946 return nullptr;
7947
7948 case Instruction::Select: {
7949 // Check if U is a select that can be simplified to a SCEVUnknown.
7950 auto CanSimplifyToUnknown = [this, U]() {
7951 if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
7952 return false;
7953
7954 auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
7955 if (!ICI)
7956 return false;
7957 Value *LHS = ICI->getOperand(0);
7958 Value *RHS = ICI->getOperand(1);
7959 if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7960 ICI->getPredicate() == CmpInst::ICMP_NE) {
7962 return true;
7963 } else if (getTypeSizeInBits(LHS->getType()) >
7964 getTypeSizeInBits(U->getType()))
7965 return true;
7966 return false;
7967 };
7968 if (CanSimplifyToUnknown())
7969 return getUnknown(U);
7970
7971 llvm::append_range(Ops, U->operands());
7972 return nullptr;
7973 break;
7974 }
7975 case Instruction::Call:
7976 case Instruction::Invoke:
7977 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7978 Ops.push_back(RV);
7979 return nullptr;
7980 }
7981
7982 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7983 switch (II->getIntrinsicID()) {
7984 case Intrinsic::abs:
7985 Ops.push_back(II->getArgOperand(0));
7986 return nullptr;
7987 case Intrinsic::umax:
7988 case Intrinsic::umin:
7989 case Intrinsic::smax:
7990 case Intrinsic::smin:
7991 case Intrinsic::usub_sat:
7992 case Intrinsic::uadd_sat:
7993 Ops.push_back(II->getArgOperand(0));
7994 Ops.push_back(II->getArgOperand(1));
7995 return nullptr;
7996 case Intrinsic::start_loop_iterations:
7997 case Intrinsic::annotation:
7998 case Intrinsic::ptr_annotation:
7999 Ops.push_back(II->getArgOperand(0));
8000 return nullptr;
8001 default:
8002 break;
8003 }
8004 }
8005 break;
8006 }
8007
8008 return nullptr;
8009}
8010
8011const SCEV *ScalarEvolution::createSCEV(Value *V) {
8012 if (!isSCEVable(V->getType()))
8013 return getUnknown(V);
8014
8015 if (Instruction *I = dyn_cast<Instruction>(V)) {
8016 // Don't attempt to analyze instructions in blocks that aren't
8017 // reachable. Such instructions don't matter, and they aren't required
8018 // to obey basic rules for definitions dominating uses which this
8019 // analysis depends on.
8020 if (!DT.isReachableFromEntry(I->getParent()))
8021 return getUnknown(PoisonValue::get(V->getType()));
8022 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
8023 return getConstant(CI);
8024 else if (isa<GlobalAlias>(V))
8025 return getUnknown(V);
8026 else if (!isa<ConstantExpr>(V))
8027 return getUnknown(V);
8028
8029 const SCEV *LHS;
8030 const SCEV *RHS;
8031
8033 if (auto BO =
8035 switch (BO->Opcode) {
8036 case Instruction::Add: {
8037 // The simple thing to do would be to just call getSCEV on both operands
8038 // and call getAddExpr with the result. However if we're looking at a
8039 // bunch of things all added together, this can be quite inefficient,
8040 // because it leads to N-1 getAddExpr calls for N ultimate operands.
8041 // Instead, gather up all the operands and make a single getAddExpr call.
8042 // LLVM IR canonical form means we need only traverse the left operands.
8044 do {
8045 if (BO->Op) {
8046 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
8047 AddOps.push_back(OpSCEV);
8048 break;
8049 }
8050
8051 // If a NUW or NSW flag can be applied to the SCEV for this
8052 // addition, then compute the SCEV for this addition by itself
8053 // with a separate call to getAddExpr. We need to do that
8054 // instead of pushing the operands of the addition onto AddOps,
8055 // since the flags are only known to apply to this particular
8056 // addition - they may not apply to other additions that can be
8057 // formed with operands from AddOps.
8058 const SCEV *RHS = getSCEV(BO->RHS);
8059 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
8060 if (Flags != SCEV::FlagAnyWrap) {
8061 const SCEV *LHS = getSCEV(BO->LHS);
8062 if (BO->Opcode == Instruction::Sub)
8063 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
8064 else
8065 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
8066 break;
8067 }
8068 }
8069
8070 if (BO->Opcode == Instruction::Sub)
8071 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
8072 else
8073 AddOps.push_back(getSCEV(BO->RHS));
8074
8075 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
8077 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
8078 NewBO->Opcode != Instruction::Sub)) {
8079 AddOps.push_back(getSCEV(BO->LHS));
8080 break;
8081 }
8082 BO = NewBO;
8083 } while (true);
8084
8085 return getAddExpr(AddOps);
8086 }
8087
8088 case Instruction::Mul: {
8090 do {
8091 if (BO->Op) {
8092 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
8093 MulOps.push_back(OpSCEV);
8094 break;
8095 }
8096
8097 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
8098 if (Flags != SCEV::FlagAnyWrap) {
8099 LHS = getSCEV(BO->LHS);
8100 RHS = getSCEV(BO->RHS);
8101 MulOps.push_back(getMulExpr(LHS, RHS, Flags));
8102 break;
8103 }
8104 }
8105
8106 MulOps.push_back(getSCEV(BO->RHS));
8107 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
8109 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
8110 MulOps.push_back(getSCEV(BO->LHS));
8111 break;
8112 }
8113 BO = NewBO;
8114 } while (true);
8115
8116 return getMulExpr(MulOps);
8117 }
8118 case Instruction::UDiv:
8119 LHS = getSCEV(BO->LHS);
8120 RHS = getSCEV(BO->RHS);
8121 return getUDivExpr(LHS, RHS);
8122 case Instruction::URem:
8123 LHS = getSCEV(BO->LHS);
8124 RHS = getSCEV(BO->RHS);
8125 return getURemExpr(LHS, RHS);
8126 case Instruction::Sub: {
8128 if (BO->Op)
8129 Flags = getNoWrapFlagsFromUB(BO->Op);
8130 LHS = getSCEV(BO->LHS);
8131 RHS = getSCEV(BO->RHS);
8132 return getMinusSCEV(LHS, RHS, Flags);
8133 }
8134 case Instruction::And:
8135 // For an expression like x&255 that merely masks off the high bits,
8136 // use zext(trunc(x)) as the SCEV expression.
8137 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
8138 if (CI->isZero())
8139 return getSCEV(BO->RHS);
8140 if (CI->isMinusOne())
8141 return getSCEV(BO->LHS);
8142 const APInt &A = CI->getValue();
8143
8144 // Instcombine's ShrinkDemandedConstant may strip bits out of
8145 // constants, obscuring what would otherwise be a low-bits mask.
8146 // Use computeKnownBits to compute what ShrinkDemandedConstant
8147 // knew about to reconstruct a low-bits mask value.
8148 unsigned LZ = A.countl_zero();
8149 unsigned TZ = A.countr_zero();
8150 unsigned BitWidth = A.getBitWidth();
8151 KnownBits Known(BitWidth);
8152 computeKnownBits(BO->LHS, Known, getDataLayout(), &AC, nullptr, &DT);
8153
8154 APInt EffectiveMask =
8155 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
8156 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
8157 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
8158 const SCEV *LHS = getSCEV(BO->LHS);
8159 const SCEV *ShiftedLHS = nullptr;
8160 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
8161 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
8162 // For an expression like (x * 8) & 8, simplify the multiply.
8163 unsigned MulZeros = OpC->getAPInt().countr_zero();
8164 unsigned GCD = std::min(MulZeros, TZ);
8165 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
8167 MulOps.push_back(getConstant(OpC->getAPInt().ashr(GCD)));
8168 append_range(MulOps, LHSMul->operands().drop_front());
8169 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
8170 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
8171 }
8172 }
8173 if (!ShiftedLHS)
8174 ShiftedLHS = getUDivExpr(LHS, MulCount);
8175 return getMulExpr(
8177 getTruncateExpr(ShiftedLHS,
8178 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
8179 BO->LHS->getType()),
8180 MulCount);
8181 }
8182 }
8183 // Binary `and` is a bit-wise `umin`.
8184 if (BO->LHS->getType()->isIntegerTy(1)) {
8185 LHS = getSCEV(BO->LHS);
8186 RHS = getSCEV(BO->RHS);
8187 return getUMinExpr(LHS, RHS);
8188 }
8189 break;
8190
8191 case Instruction::Or:
8192 // Binary `or` is a bit-wise `umax`.
8193 if (BO->LHS->getType()->isIntegerTy(1)) {
8194 LHS = getSCEV(BO->LHS);
8195 RHS = getSCEV(BO->RHS);
8196 return getUMaxExpr(LHS, RHS);
8197 }
8198 break;
8199
8200 case Instruction::Xor:
8201 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
8202 // If the RHS of xor is -1, then this is a not operation.
8203 if (CI->isMinusOne())
8204 return getNotSCEV(getSCEV(BO->LHS));
8205
8206 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
8207 // This is a variant of the check for xor with -1, and it handles
8208 // the case where instcombine has trimmed non-demanded bits out
8209 // of an xor with -1.
8210 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
8211 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
8212 if (LBO->getOpcode() == Instruction::And &&
8213 LCI->getValue() == CI->getValue())
8214 if (const SCEVZeroExtendExpr *Z =
8216 Type *UTy = BO->LHS->getType();
8217 const SCEV *Z0 = Z->getOperand();
8218 Type *Z0Ty = Z0->getType();
8219 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
8220
8221 // If C is a low-bits mask, the zero extend is serving to
8222 // mask off the high bits. Complement the operand and
8223 // re-apply the zext.
8224 if (CI->getValue().isMask(Z0TySize))
8225 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
8226
8227 // If C is a single bit, it may be in the sign-bit position
8228 // before the zero-extend. In this case, represent the xor
8229 // using an add, which is equivalent, and re-apply the zext.
8230 APInt Trunc = CI->getValue().trunc(Z0TySize);
8231 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
8232 Trunc.isSignMask())
8233 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
8234 UTy);
8235 }
8236 }
8237 break;
8238
8239 case Instruction::Shl:
8240 // Turn shift left of a constant amount into a multiply.
8241 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
8242 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
8243
8244 // If the shift count is not less than the bitwidth, the result of
8245 // the shift is undefined. Don't try to analyze it, because the
8246 // resolution chosen here may differ from the resolution chosen in
8247 // other parts of the compiler.
8248 if (SA->getValue().uge(BitWidth))
8249 break;
8250
8251 // We can safely preserve the nuw flag in all cases. It's also safe to
8252 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
8253 // requires special handling. It can be preserved as long as we're not
8254 // left shifting by bitwidth - 1.
8255 auto Flags = SCEV::FlagAnyWrap;
8256 if (BO->Op) {
8257 auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
8258 if (any(MulFlags & SCEV::FlagNSW) &&
8259 (any(MulFlags & SCEV::FlagNUW) ||
8260 SA->getValue().ult(BitWidth - 1)))
8262 if (any(MulFlags & SCEV::FlagNUW))
8264 }
8265
8266 ConstantInt *X = ConstantInt::get(
8267 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
8268 return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
8269 }
8270 break;
8271
8272 case Instruction::AShr:
8273 // AShr X, C, where C is a constant.
8274 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
8275 if (!CI)
8276 break;
8277
8278 Type *OuterTy = BO->LHS->getType();
8279 uint64_t BitWidth = getTypeSizeInBits(OuterTy);
8280 // If the shift count is not less than the bitwidth, the result of
8281 // the shift is undefined. Don't try to analyze it, because the
8282 // resolution chosen here may differ from the resolution chosen in
8283 // other parts of the compiler.
8284 if (CI->getValue().uge(BitWidth))
8285 break;
8286
8287 if (CI->isZero())
8288 return getSCEV(BO->LHS); // shift by zero --> noop
8289
8290 uint64_t AShrAmt = CI->getZExtValue();
8291 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
8292
8293 Operator *L = dyn_cast<Operator>(BO->LHS);
8294 const SCEV *AddTruncateExpr = nullptr;
8295 ConstantInt *ShlAmtCI = nullptr;
8296 const SCEV *AddConstant = nullptr;
8297
8298 if (L && L->getOpcode() == Instruction::Add) {
8299 // X = Shl A, n
8300 // Y = Add X, c
8301 // Z = AShr Y, m
8302 // n, c and m are constants.
8303
8304 Operator *LShift = dyn_cast<Operator>(L->getOperand(0));
8305 ConstantInt *AddOperandCI = dyn_cast<ConstantInt>(L->getOperand(1));
8306 if (LShift && LShift->getOpcode() == Instruction::Shl) {
8307 if (AddOperandCI) {
8308 const SCEV *ShlOp0SCEV = getSCEV(LShift->getOperand(0));
8309 ShlAmtCI = dyn_cast<ConstantInt>(LShift->getOperand(1));
8310 // since we truncate to TruncTy, the AddConstant should be of the
8311 // same type, so create a new Constant with type same as TruncTy.
8312 // Also, the Add constant should be shifted right by AShr amount.
8313 APInt AddOperand = AddOperandCI->getValue().ashr(AShrAmt);
8314 AddConstant = getConstant(AddOperand.trunc(BitWidth - AShrAmt));
8315 // we model the expression as sext(add(trunc(A), c << n)), since the
8316 // sext(trunc) part is already handled below, we create a
8317 // AddExpr(TruncExp) which will be used later.
8318 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8319 }
8320 }
8321 } else if (L && L->getOpcode() == Instruction::Shl) {
8322 // X = Shl A, n
8323 // Y = AShr X, m
8324 // Both n and m are constant.
8325
8326 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
8327 ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
8328 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8329 }
8330
8331 if (AddTruncateExpr && ShlAmtCI) {
8332 // We can merge the two given cases into a single SCEV statement,
8333 // incase n = m, the mul expression will be 2^0, so it gets resolved to
8334 // a simpler case. The following code handles the two cases:
8335 //
8336 // 1) For a two-shift sext-inreg, i.e. n = m,
8337 // use sext(trunc(x)) as the SCEV expression.
8338 //
8339 // 2) When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
8340 // expression. We already checked that ShlAmt < BitWidth, so
8341 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
8342 // ShlAmt - AShrAmt < Amt.
8343 const APInt &ShlAmt = ShlAmtCI->getValue();
8344 if (ShlAmt.ult(BitWidth) && ShlAmt.uge(AShrAmt)) {
8345 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
8346 ShlAmtCI->getZExtValue() - AShrAmt);
8347 const SCEV *CompositeExpr =
8348 getMulExpr(AddTruncateExpr, getConstant(Mul));
8349 if (L->getOpcode() != Instruction::Shl)
8350 CompositeExpr = getAddExpr(CompositeExpr, AddConstant);
8351
8352 return getSignExtendExpr(CompositeExpr, OuterTy);
8353 }
8354 }
8355 break;
8356 }
8357 }
8358
8359 switch (U->getOpcode()) {
8360 case Instruction::Trunc:
8361 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
8362
8363 case Instruction::ZExt:
8364 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8365
8366 case Instruction::SExt:
8367 if (auto BO = MatchBinaryOp(U->getOperand(0), getDataLayout(), AC, DT,
8369 // The NSW flag of a subtract does not always survive the conversion to
8370 // A + (-1)*B. By pushing sign extension onto its operands we are much
8371 // more likely to preserve NSW and allow later AddRec optimisations.
8372 //
8373 // NOTE: This is effectively duplicating this logic from getSignExtend:
8374 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
8375 // but by that point the NSW information has potentially been lost.
8376 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
8377 Type *Ty = U->getType();
8378 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
8379 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
8380 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
8381 }
8382 }
8383 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8384
8385 case Instruction::BitCast:
8386 // BitCasts are no-op casts so we just eliminate the cast.
8387 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
8388 return getSCEV(U->getOperand(0));
8389 break;
8390
8391 case Instruction::PtrToAddr: {
8392 const SCEV *IntOp = getPtrToAddrExpr(getSCEV(U->getOperand(0)));
8393 if (isa<SCEVCouldNotCompute>(IntOp))
8394 return getUnknown(V);
8395 return IntOp;
8396 }
8397
8398 case Instruction::PtrToInt: {
8399 // Pointer to integer cast is straight-forward, so do model it.
8400 const SCEV *Op = getSCEV(U->getOperand(0));
8401 Type *DstIntTy = U->getType();
8402 // But only if effective SCEV (integer) type is wide enough to represent
8403 // all possible pointer values.
8404 const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy);
8405 if (isa<SCEVCouldNotCompute>(IntOp))
8406 return getUnknown(V);
8407 return IntOp;
8408 }
8409 case Instruction::IntToPtr:
8410 // Just don't deal with inttoptr casts.
8411 return getUnknown(V);
8412
8413 case Instruction::SDiv:
8414 // If both operands are non-negative, this is just an udiv.
8415 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8416 isKnownNonNegative(getSCEV(U->getOperand(1))))
8417 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8418 break;
8419
8420 case Instruction::SRem:
8421 // If both operands are non-negative, this is just an urem.
8422 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8423 isKnownNonNegative(getSCEV(U->getOperand(1))))
8424 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8425 break;
8426
8427 case Instruction::GetElementPtr:
8428 return createNodeForGEP(cast<GEPOperator>(U));
8429
8430 case Instruction::PHI:
8431 return createNodeForPHI(cast<PHINode>(U));
8432
8433 case Instruction::Select:
8434 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
8435 U->getOperand(2));
8436
8437 case Instruction::Call:
8438 case Instruction::Invoke:
8439 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
8440 return getSCEV(RV);
8441
8442 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
8443 switch (II->getIntrinsicID()) {
8444 case Intrinsic::abs:
8445 return getAbsExpr(
8446 getSCEV(II->getArgOperand(0)),
8447 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
8448 case Intrinsic::umax:
8449 LHS = getSCEV(II->getArgOperand(0));
8450 RHS = getSCEV(II->getArgOperand(1));
8451 return getUMaxExpr(LHS, RHS);
8452 case Intrinsic::umin:
8453 LHS = getSCEV(II->getArgOperand(0));
8454 RHS = getSCEV(II->getArgOperand(1));
8455 return getUMinExpr(LHS, RHS);
8456 case Intrinsic::smax:
8457 LHS = getSCEV(II->getArgOperand(0));
8458 RHS = getSCEV(II->getArgOperand(1));
8459 return getSMaxExpr(LHS, RHS);
8460 case Intrinsic::smin:
8461 LHS = getSCEV(II->getArgOperand(0));
8462 RHS = getSCEV(II->getArgOperand(1));
8463 return getSMinExpr(LHS, RHS);
8464 case Intrinsic::usub_sat: {
8465 const SCEV *X = getSCEV(II->getArgOperand(0));
8466 const SCEV *Y = getSCEV(II->getArgOperand(1));
8467 const SCEV *ClampedY = getUMinExpr(X, Y);
8468 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
8469 }
8470 case Intrinsic::uadd_sat: {
8471 const SCEV *X = getSCEV(II->getArgOperand(0));
8472 const SCEV *Y = getSCEV(II->getArgOperand(1));
8473 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
8474 return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
8475 }
8476 case Intrinsic::start_loop_iterations:
8477 case Intrinsic::annotation:
8478 case Intrinsic::ptr_annotation:
8479 // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8480 // just eqivalent to the first operand for SCEV purposes.
8481 return getSCEV(II->getArgOperand(0));
8482 case Intrinsic::vscale:
8483 return getVScale(II->getType());
8484 default:
8485 break;
8486 }
8487 }
8488 break;
8489 }
8490
8491 return getUnknown(V);
8492}
8493
8494//===----------------------------------------------------------------------===//
8495// Iteration Count Computation Code
8496//
8497
8499 if (isa<SCEVCouldNotCompute>(ExitCount))
8500 return getCouldNotCompute();
8501
8502 auto *ExitCountType = ExitCount->getType();
8503 assert(ExitCountType->isIntegerTy());
8504 auto *EvalTy = Type::getIntNTy(ExitCountType->getContext(),
8505 1 + ExitCountType->getScalarSizeInBits());
8506 return getTripCountFromExitCount(ExitCount, EvalTy, nullptr);
8507}
8508
8510 Type *EvalTy,
8511 const Loop *L) {
8512 if (isa<SCEVCouldNotCompute>(ExitCount))
8513 return getCouldNotCompute();
8514
8515 unsigned ExitCountSize = getTypeSizeInBits(ExitCount->getType());
8516 unsigned EvalSize = EvalTy->getPrimitiveSizeInBits();
8517
8518 auto CanAddOneWithoutOverflow = [&]() {
8519 ConstantRange ExitCountRange =
8520 getRangeRef(ExitCount, RangeSignHint::HINT_RANGE_UNSIGNED);
8521 if (!ExitCountRange.contains(APInt::getMaxValue(ExitCountSize)))
8522 return true;
8523
8524 return L && isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
8525 getMinusOne(ExitCount->getType()));
8526 };
8527
8528 // If we need to zero extend the backedge count, check if we can add one to
8529 // it prior to zero extending without overflow. Provided this is safe, it
8530 // allows better simplification of the +1.
8531 if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8532 return getZeroExtendExpr(
8533 getAddExpr(ExitCount, getOne(ExitCount->getType())), EvalTy);
8534
8535 // Get the total trip count from the count by adding 1. This may wrap.
8536 return getAddExpr(getTruncateOrZeroExtend(ExitCount, EvalTy), getOne(EvalTy));
8537}
8538
8539static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8540 if (!ExitCount)
8541 return 0;
8542
8543 ConstantInt *ExitConst = ExitCount->getValue();
8544
8545 // Guard against huge trip counts.
8546 if (ExitConst->getValue().getActiveBits() > 32)
8547 return 0;
8548
8549 // In case of integer overflow, this returns 0, which is correct.
8550 return ((unsigned)ExitConst->getZExtValue()) + 1;
8551}
8552
8554 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
8555 return getConstantTripCount(ExitCount);
8556}
8557
8558unsigned
8560 const BasicBlock *ExitingBlock) {
8561 assert(ExitingBlock && "Must pass a non-null exiting block!");
8562 assert(L->isLoopExiting(ExitingBlock) &&
8563 "Exiting block must actually branch out of the loop!");
8564 const SCEVConstant *ExitCount =
8565 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
8566 return getConstantTripCount(ExitCount);
8567}
8568
8570 const Loop *L, SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8571
8572 const auto *MaxExitCount =
8573 Predicates ? getPredicatedConstantMaxBackedgeTakenCount(L, *Predicates)
8575 return getConstantTripCount(dyn_cast<SCEVConstant>(MaxExitCount));
8576}
8577
8579 SmallVector<BasicBlock *, 8> ExitingBlocks;
8580 L->getExitingBlocks(ExitingBlocks);
8581
8582 std::optional<unsigned> Res;
8583 for (auto *ExitingBB : ExitingBlocks) {
8584 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
8585 if (!Res)
8586 Res = Multiple;
8587 Res = std::gcd(*Res, Multiple);
8588 }
8589 return Res.value_or(1);
8590}
8591
8593 const SCEV *ExitCount) {
8594 if (isa<SCEVCouldNotCompute>(ExitCount))
8595 return 1;
8596
8597 // Get the trip count
8598 const SCEV *TCExpr = getTripCountFromExitCount(applyLoopGuards(ExitCount, L));
8599
8600 APInt Multiple = getNonZeroConstantMultiple(TCExpr);
8601 // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8602 // the greatest power of 2 divisor less than 2^32.
8603 return Multiple.getActiveBits() > 32
8604 ? 1U << std::min(31U, Multiple.countTrailingZeros())
8605 : (unsigned)Multiple.getZExtValue();
8606}
8607
8608/// Returns the largest constant divisor of the trip count of this loop as a
8609/// normal unsigned value, if possible. This means that the actual trip count is
8610/// always a multiple of the returned value (don't forget the trip count could
8611/// very well be zero as well!).
8612///
8613/// Returns 1 if the trip count is unknown or not guaranteed to be the
8614/// multiple of a constant (which is also the case if the trip count is simply
8615/// constant, use getSmallConstantTripCount for that case), Will also return 1
8616/// if the trip count is very large (>= 2^32).
8617///
8618/// As explained in the comments for getSmallConstantTripCount, this assumes
8619/// that control exits the loop via ExitingBlock.
8620unsigned
8622 const BasicBlock *ExitingBlock) {
8623 assert(ExitingBlock && "Must pass a non-null exiting block!");
8624 assert(L->isLoopExiting(ExitingBlock) &&
8625 "Exiting block must actually branch out of the loop!");
8626 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8627 return getSmallConstantTripMultiple(L, ExitCount);
8628}
8629
8631 const BasicBlock *ExitingBlock,
8632 ExitCountKind Kind) {
8633 switch (Kind) {
8634 case Exact:
8635 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8636 case SymbolicMaximum:
8637 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8638 case ConstantMaximum:
8639 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8640 };
8641 llvm_unreachable("Invalid ExitCountKind!");
8642}
8643
8645 const Loop *L, const BasicBlock *ExitingBlock,
8647 switch (Kind) {
8648 case Exact:
8649 return getPredicatedBackedgeTakenInfo(L).getExact(ExitingBlock, this,
8650 Predicates);
8651 case SymbolicMaximum:
8652 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this,
8653 Predicates);
8654 case ConstantMaximum:
8655 return getPredicatedBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this,
8656 Predicates);
8657 };
8658 llvm_unreachable("Invalid ExitCountKind!");
8659}
8660
8663 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8664}
8665
8667 ExitCountKind Kind) {
8668 switch (Kind) {
8669 case Exact:
8670 return getBackedgeTakenInfo(L).getExact(L, this);
8671 case ConstantMaximum:
8672 return getBackedgeTakenInfo(L).getConstantMax(this);
8673 case SymbolicMaximum:
8674 return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8675 };
8676 llvm_unreachable("Invalid ExitCountKind!");
8677}
8678
8681 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(L, this, &Preds);
8682}
8683
8686 return getPredicatedBackedgeTakenInfo(L).getConstantMax(this, &Preds);
8687}
8688
8690 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8691}
8692
8693ScalarEvolution::BackedgeTakenInfo &
8694ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8695 auto &BTI = getBackedgeTakenInfo(L);
8696 if (BTI.hasFullInfo())
8697 return BTI;
8698
8699 auto Pair = PredicatedBackedgeTakenCounts.try_emplace(L);
8700
8701 if (!Pair.second)
8702 return Pair.first->second;
8703
8704 BackedgeTakenInfo Result =
8705 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8706
8707 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8708}
8709
8710ScalarEvolution::BackedgeTakenInfo &
8711ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8712 // Initially insert an invalid entry for this loop. If the insertion
8713 // succeeds, proceed to actually compute a backedge-taken count and
8714 // update the value. The temporary CouldNotCompute value tells SCEV
8715 // code elsewhere that it shouldn't attempt to request a new
8716 // backedge-taken count, which could result in infinite recursion.
8717 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8718 BackedgeTakenCounts.try_emplace(L);
8719 if (!Pair.second)
8720 return Pair.first->second;
8721
8722 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8723 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8724 // must be cleared in this scope.
8725 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8726
8727 // Now that we know more about the trip count for this loop, forget any
8728 // existing SCEV values for PHI nodes in this loop since they are only
8729 // conservative estimates made without the benefit of trip count
8730 // information. This invalidation is not necessary for correctness, and is
8731 // only done to produce more precise results.
8732 if (Result.hasAnyInfo()) {
8733 // Invalidate any expression using an addrec in this loop.
8734 SmallVector<SCEVUse, 8> ToForget;
8735 auto LoopUsersIt = LoopUsers.find(L);
8736 if (LoopUsersIt != LoopUsers.end())
8737 append_range(ToForget, LoopUsersIt->second);
8738 forgetMemoizedResults(ToForget);
8739
8740 // Invalidate constant-evolved loop header phis.
8741 for (PHINode &PN : L->getHeader()->phis())
8742 ConstantEvolutionLoopExitValue.erase(&PN);
8743 }
8744
8745 // Re-lookup the insert position, since the call to
8746 // computeBackedgeTakenCount above could result in a
8747 // recusive call to getBackedgeTakenInfo (on a different
8748 // loop), which would invalidate the iterator computed
8749 // earlier.
8750 return BackedgeTakenCounts.find(L)->second = std::move(Result);
8751}
8752
8754 // This method is intended to forget all info about loops. It should
8755 // invalidate caches as if the following happened:
8756 // - The trip counts of all loops have changed arbitrarily
8757 // - Every llvm::Value has been updated in place to produce a different
8758 // result.
8759 BackedgeTakenCounts.clear();
8760 PredicatedBackedgeTakenCounts.clear();
8761 BECountUsers.clear();
8762 LoopPropertiesCache.clear();
8763 ConstantEvolutionLoopExitValue.clear();
8764 ValueExprMap.clear();
8765 ValuesAtScopes.clear();
8766 ValuesAtScopesUsers.clear();
8767 LoopDispositions.clear();
8768 BlockDispositions.clear();
8769 UnsignedRanges.clear();
8770 SignedRanges.clear();
8771 ExprValueMap.clear();
8772 HasRecMap.clear();
8773 ConstantMultipleCache.clear();
8774 PredicatedSCEVRewrites.clear();
8775 FoldCache.clear();
8776 FoldCacheUser.clear();
8777}
8778void ScalarEvolution::visitAndClearUsers(
8781 SmallVectorImpl<SCEVUse> &ToForget) {
8782 while (!Worklist.empty()) {
8783 Instruction *I = Worklist.pop_back_val();
8784 if (!isSCEVable(I->getType()) && !isa<WithOverflowInst>(I))
8785 continue;
8786
8788 ValueExprMap.find_as(static_cast<Value *>(I));
8789 if (It != ValueExprMap.end()) {
8790 ToForget.push_back(It->second);
8791 eraseValueFromMap(It->first);
8792 if (PHINode *PN = dyn_cast<PHINode>(I))
8793 ConstantEvolutionLoopExitValue.erase(PN);
8794 }
8795
8796 PushDefUseChildren(I, Worklist, Visited);
8797 }
8798}
8799
8801 SmallVector<const Loop *, 16> LoopWorklist(1, L);
8802 SmallVector<SCEVUse, 16> ToForget;
8803
8804 // Iterate over all the loops and sub-loops to drop SCEV information.
8805 while (!LoopWorklist.empty()) {
8806 auto *CurrL = LoopWorklist.pop_back_val();
8807
8808 // Drop any stored trip count value.
8809 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8810 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8811
8812 // Drop information about predicated SCEV rewrites for this loop.
8813 PredicatedSCEVRewrites.remove_if(
8814 [&](const auto &Entry) { return Entry.first.second == CurrL; });
8815
8816 auto LoopUsersItr = LoopUsers.find(CurrL);
8817 if (LoopUsersItr != LoopUsers.end())
8818 llvm::append_range(ToForget, LoopUsersItr->second);
8819
8820 // Drop information about expressions based on loop-header PHIs.
8821 for (PHINode &PN : CurrL->getHeader()->phis()) {
8822 ConstantEvolutionLoopExitValue.erase(&PN);
8823 auto VIt = ValueExprMap.find_as(static_cast<Value *>(&PN));
8824 if (VIt != ValueExprMap.end())
8825 ToForget.push_back(VIt->second);
8826 }
8827
8828 LoopPropertiesCache.erase(CurrL);
8829 // Forget all contained loops too, to avoid dangling entries in the
8830 // ValuesAtScopes map.
8831 LoopWorklist.append(CurrL->begin(), CurrL->end());
8832 }
8833 forgetMemoizedResults(ToForget);
8834}
8835
8837 forgetLoop(L->getOutermostLoop());
8838}
8839
8842 if (!I) return;
8843
8844 // Drop information about expressions based on loop-header PHIs.
8847 SmallVector<SCEVUse, 8> ToForget;
8848 Worklist.push_back(I);
8849 Visited.insert(I);
8850 visitAndClearUsers(Worklist, Visited, ToForget);
8851
8852 forgetMemoizedResults(ToForget);
8853}
8854
8856 if (!isSCEVable(V->getType()))
8857 return;
8858
8859 // If SCEV looked through a trivial LCSSA phi node, we might have SCEV's
8860 // directly using a SCEVUnknown/SCEVAddRec defined in the loop. After an
8861 // extra predecessor is added, this is no longer valid. Find all Unknowns and
8862 // AddRecs defined in the loop and invalidate any SCEV's making use of them.
8863 if (const SCEV *S = getExistingSCEV(V)) {
8864 struct InvalidationRootCollector {
8865 Loop *L;
8867
8868 InvalidationRootCollector(Loop *L) : L(L) {}
8869
8870 bool follow(const SCEV *S) {
8871 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
8872 if (auto *I = dyn_cast<Instruction>(SU->getValue()))
8873 if (L->contains(I))
8874 Roots.push_back(S);
8875 } else if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
8876 if (L->contains(AddRec->getLoop()))
8877 Roots.push_back(S);
8878 }
8879 return true;
8880 }
8881 bool isDone() const { return false; }
8882 };
8883
8884 InvalidationRootCollector C(L);
8885 visitAll(S, C);
8886 forgetMemoizedResults(C.Roots);
8887 }
8888
8889 // Also perform the normal invalidation.
8890 forgetValue(V);
8891}
8892
8893void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8894
8896 // Unless a specific value is passed to invalidation, completely clear both
8897 // caches.
8898 if (!V) {
8899 BlockDispositions.clear();
8900 LoopDispositions.clear();
8901 return;
8902 }
8903
8904 if (!isSCEVable(V->getType()))
8905 return;
8906
8907 const SCEV *S = getExistingSCEV(V);
8908 if (!S)
8909 return;
8910
8911 // Invalidate the block and loop dispositions cached for S. Dispositions of
8912 // S's users may change if S's disposition changes (i.e. a user may change to
8913 // loop-invariant, if S changes to loop invariant), so also invalidate
8914 // dispositions of S's users recursively.
8915 SmallVector<SCEVUse, 8> Worklist = {S};
8917 while (!Worklist.empty()) {
8918 const SCEV *Curr = Worklist.pop_back_val();
8919 bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8920 bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8921 if (!LoopDispoRemoved && !BlockDispoRemoved)
8922 continue;
8923 auto Users = SCEVUsers.find(Curr);
8924 if (Users != SCEVUsers.end())
8925 for (const auto *User : Users->second)
8926 if (Seen.insert(User).second)
8927 Worklist.push_back(User);
8928 }
8929}
8930
8931/// Get the exact loop backedge taken count considering all loop exits. A
8932/// computable result can only be returned for loops with all exiting blocks
8933/// dominating the latch. howFarToZero assumes that the limit of each loop test
8934/// is never skipped. This is a valid assumption as long as the loop exits via
8935/// that test. For precise results, it is the caller's responsibility to specify
8936/// the relevant loop exiting block using getExact(ExitingBlock, SE).
8937const SCEV *ScalarEvolution::BackedgeTakenInfo::getExact(
8938 const Loop *L, ScalarEvolution *SE,
8940 // If any exits were not computable, the loop is not computable.
8941 if (!isComplete() || ExitNotTaken.empty())
8942 return SE->getCouldNotCompute();
8943
8944 const BasicBlock *Latch = L->getLoopLatch();
8945 // All exiting blocks we have collected must dominate the only backedge.
8946 if (!Latch)
8947 return SE->getCouldNotCompute();
8948
8949 // All exiting blocks we have gathered dominate loop's latch, so exact trip
8950 // count is simply a minimum out of all these calculated exit counts.
8952 for (const auto &ENT : ExitNotTaken) {
8953 const SCEV *BECount = ENT.ExactNotTaken;
8954 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8955 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8956 "We should only have known counts for exiting blocks that dominate "
8957 "latch!");
8958
8959 Ops.push_back(BECount);
8960
8961 if (Preds)
8962 append_range(*Preds, ENT.Predicates);
8963
8964 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8965 "Predicate should be always true!");
8966 }
8967
8968 // If an earlier exit exits on the first iteration (exit count zero), then
8969 // a later poison exit count should not propagate into the result. This are
8970 // exactly the semantics provided by umin_seq.
8971 return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8972}
8973
8974const ScalarEvolution::ExitNotTakenInfo *
8975ScalarEvolution::BackedgeTakenInfo::getExitNotTaken(
8976 const BasicBlock *ExitingBlock,
8977 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8978 for (const auto &ENT : ExitNotTaken)
8979 if (ENT.ExitingBlock == ExitingBlock) {
8980 if (ENT.hasAlwaysTruePredicate())
8981 return &ENT;
8982 else if (Predicates) {
8983 append_range(*Predicates, ENT.Predicates);
8984 return &ENT;
8985 }
8986 }
8987
8988 return nullptr;
8989}
8990
8991/// getConstantMax - Get the constant max backedge taken count for the loop.
8992const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8993 ScalarEvolution *SE,
8994 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8995 if (!getConstantMax())
8996 return SE->getCouldNotCompute();
8997
8998 for (const auto &ENT : ExitNotTaken)
8999 if (!ENT.hasAlwaysTruePredicate()) {
9000 if (!Predicates)
9001 return SE->getCouldNotCompute();
9002 append_range(*Predicates, ENT.Predicates);
9003 }
9004
9005 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
9006 isa<SCEVConstant>(getConstantMax())) &&
9007 "No point in having a non-constant max backedge taken count!");
9008 return getConstantMax();
9009}
9010
9011const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
9012 const Loop *L, ScalarEvolution *SE,
9013 SmallVectorImpl<const SCEVPredicate *> *Predicates) {
9014 if (!SymbolicMax) {
9015 // Form an expression for the maximum exit count possible for this loop. We
9016 // merge the max and exact information to approximate a version of
9017 // getConstantMaxBackedgeTakenCount which isn't restricted to just
9018 // constants.
9019 SmallVector<SCEVUse, 4> ExitCounts;
9020
9021 for (const auto &ENT : ExitNotTaken) {
9022 const SCEV *ExitCount = ENT.SymbolicMaxNotTaken;
9023 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
9024 assert(SE->DT.dominates(ENT.ExitingBlock, L->getLoopLatch()) &&
9025 "We should only have known counts for exiting blocks that "
9026 "dominate latch!");
9027 ExitCounts.push_back(ExitCount);
9028 if (Predicates)
9029 append_range(*Predicates, ENT.Predicates);
9030
9031 assert((Predicates || ENT.hasAlwaysTruePredicate()) &&
9032 "Predicate should be always true!");
9033 }
9034 }
9035 if (ExitCounts.empty())
9036 SymbolicMax = SE->getCouldNotCompute();
9037 else
9038 SymbolicMax =
9039 SE->getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
9040 }
9041 return SymbolicMax;
9042}
9043
9044bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
9045 ScalarEvolution *SE) const {
9046 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
9047 return !ENT.hasAlwaysTruePredicate();
9048 };
9049 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
9050}
9051
9054
9056 const SCEV *E, const SCEV *ConstantMaxNotTaken,
9057 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
9061 // If we prove the max count is zero, so is the symbolic bound. This happens
9062 // in practice due to differences in a) how context sensitive we've chosen
9063 // to be and b) how we reason about bounds implied by UB.
9064 if (ConstantMaxNotTaken->isZero()) {
9065 this->ExactNotTaken = E = ConstantMaxNotTaken;
9066 this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
9067 }
9068
9071 "Exact is not allowed to be less precise than Constant Max");
9074 "Exact is not allowed to be less precise than Symbolic Max");
9077 "Symbolic Max is not allowed to be less precise than Constant Max");
9080 "No point in having a non-constant max backedge taken count!");
9082 for (const auto PredList : PredLists)
9083 for (const auto *P : PredList) {
9084 if (SeenPreds.contains(P))
9085 continue;
9086 assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!");
9087 SeenPreds.insert(P);
9088 Predicates.push_back(P);
9089 }
9090 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
9091 "Backedge count should be int");
9093 !ConstantMaxNotTaken->getType()->isPointerTy()) &&
9094 "Max backedge count should be int");
9095}
9096
9104
9105/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
9106/// computable exit into a persistent ExitNotTakenInfo array.
9107ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
9109 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
9110 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
9111 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
9112
9113 ExitNotTaken.reserve(ExitCounts.size());
9114 std::transform(ExitCounts.begin(), ExitCounts.end(),
9115 std::back_inserter(ExitNotTaken),
9116 [&](const EdgeExitInfo &EEI) {
9117 BasicBlock *ExitBB = EEI.first;
9118 const ExitLimit &EL = EEI.second;
9119 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
9120 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
9121 EL.Predicates);
9122 });
9123 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
9124 isa<SCEVConstant>(ConstantMax)) &&
9125 "No point in having a non-constant max backedge taken count!");
9126}
9127
9128/// Compute the number of times the backedge of the specified loop will execute.
9129ScalarEvolution::BackedgeTakenInfo
9130ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
9131 bool AllowPredicates) {
9132 SmallVector<BasicBlock *, 8> ExitingBlocks;
9133 L->getExitingBlocks(ExitingBlocks);
9134
9135 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
9136
9138 bool CouldComputeBECount = true;
9139 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
9140 const SCEV *MustExitMaxBECount = nullptr;
9141 const SCEV *MayExitMaxBECount = nullptr;
9142 bool MustExitMaxOrZero = false;
9143 bool IsOnlyExit = ExitingBlocks.size() == 1;
9144
9145 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
9146 // and compute maxBECount.
9147 // Do a union of all the predicates here.
9148 for (BasicBlock *ExitBB : ExitingBlocks) {
9149 // We canonicalize untaken exits to br (constant), ignore them so that
9150 // proving an exit untaken doesn't negatively impact our ability to reason
9151 // about the loop as whole.
9152 if (auto *BI = dyn_cast<CondBrInst>(ExitBB->getTerminator()))
9153 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
9154 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9155 if (ExitIfTrue == CI->isZero())
9156 continue;
9157 }
9158
9159 ExitLimit EL = computeExitLimit(L, ExitBB, IsOnlyExit, AllowPredicates);
9160
9161 assert((AllowPredicates || EL.Predicates.empty()) &&
9162 "Predicated exit limit when predicates are not allowed!");
9163
9164 // 1. For each exit that can be computed, add an entry to ExitCounts.
9165 // CouldComputeBECount is true only if all exits can be computed.
9166 if (EL.ExactNotTaken != getCouldNotCompute())
9167 ++NumExitCountsComputed;
9168 else
9169 // We couldn't compute an exact value for this exit, so
9170 // we won't be able to compute an exact value for the loop.
9171 CouldComputeBECount = false;
9172 // Remember exit count if either exact or symbolic is known. Because
9173 // Exact always implies symbolic, only check symbolic.
9174 if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
9175 ExitCounts.emplace_back(ExitBB, EL);
9176 else {
9177 assert(EL.ExactNotTaken == getCouldNotCompute() &&
9178 "Exact is known but symbolic isn't?");
9179 ++NumExitCountsNotComputed;
9180 }
9181
9182 // 2. Derive the loop's MaxBECount from each exit's max number of
9183 // non-exiting iterations. Partition the loop exits into two kinds:
9184 // LoopMustExits and LoopMayExits.
9185 //
9186 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
9187 // is a LoopMayExit. If any computable LoopMustExit is found, then
9188 // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
9189 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
9190 // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
9191 // any
9192 // computable EL.ConstantMaxNotTaken.
9193 if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
9194 DT.dominates(ExitBB, Latch)) {
9195 if (!MustExitMaxBECount) {
9196 MustExitMaxBECount = EL.ConstantMaxNotTaken;
9197 MustExitMaxOrZero = EL.MaxOrZero;
9198 } else {
9199 MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
9200 EL.ConstantMaxNotTaken);
9201 }
9202 } else if (MayExitMaxBECount != getCouldNotCompute()) {
9203 if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
9204 MayExitMaxBECount = EL.ConstantMaxNotTaken;
9205 else {
9206 MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
9207 EL.ConstantMaxNotTaken);
9208 }
9209 }
9210 }
9211 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
9212 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
9213 // The loop backedge will be taken the maximum or zero times if there's
9214 // a single exit that must be taken the maximum or zero times.
9215 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
9216
9217 // Remember which SCEVs are used in exit limits for invalidation purposes.
9218 // We only care about non-constant SCEVs here, so we can ignore
9219 // EL.ConstantMaxNotTaken
9220 // and MaxBECount, which must be SCEVConstant.
9221 for (const auto &Pair : ExitCounts) {
9222 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
9223 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
9224 if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
9225 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
9226 {L, AllowPredicates});
9227 }
9228 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
9229 MaxBECount, MaxOrZero);
9230}
9231
9232ScalarEvolution::ExitLimit
9233ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
9234 bool IsOnlyExit, bool AllowPredicates) {
9235 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
9236 // If our exiting block does not dominate the latch, then its connection with
9237 // loop's exit limit may be far from trivial.
9238 const BasicBlock *Latch = L->getLoopLatch();
9239 if (!Latch || !DT.dominates(ExitingBlock, Latch))
9240 return getCouldNotCompute();
9241
9242 Instruction *Term = ExitingBlock->getTerminator();
9243 if (CondBrInst *BI = dyn_cast<CondBrInst>(Term)) {
9244 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9245 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
9246 "It should have one successor in loop and one exit block!");
9247 // Proceed to the next level to examine the exit condition expression.
9248 return computeExitLimitFromCond(L, BI->getCondition(), ExitIfTrue,
9249 /*ControlsOnlyExit=*/IsOnlyExit,
9250 AllowPredicates);
9251 }
9252
9253 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
9254 // For switch, make sure that there is a single exit from the loop.
9255 BasicBlock *Exit = nullptr;
9256 for (auto *SBB : successors(ExitingBlock))
9257 if (!L->contains(SBB)) {
9258 if (Exit) // Multiple exit successors.
9259 return getCouldNotCompute();
9260 Exit = SBB;
9261 }
9262 assert(Exit && "Exiting block must have at least one exit");
9263 return computeExitLimitFromSingleExitSwitch(
9264 L, SI, Exit, /*ControlsOnlyExit=*/IsOnlyExit);
9265 }
9266
9267 return getCouldNotCompute();
9268}
9269
9271 const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9272 bool AllowPredicates) {
9273 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
9274 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
9275 ControlsOnlyExit, AllowPredicates);
9276}
9277
9278std::optional<ScalarEvolution::ExitLimit>
9279ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
9280 bool ExitIfTrue, bool ControlsOnlyExit,
9281 bool AllowPredicates) {
9282 (void)this->L;
9283 (void)this->ExitIfTrue;
9284 (void)this->AllowPredicates;
9285
9286 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9287 this->AllowPredicates == AllowPredicates &&
9288 "Variance in assumed invariant key components!");
9289 auto Itr = TripCountMap.find({ExitCond, ControlsOnlyExit});
9290 if (Itr == TripCountMap.end())
9291 return std::nullopt;
9292 return Itr->second;
9293}
9294
9295void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
9296 bool ExitIfTrue,
9297 bool ControlsOnlyExit,
9298 bool AllowPredicates,
9299 const ExitLimit &EL) {
9300 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9301 this->AllowPredicates == AllowPredicates &&
9302 "Variance in assumed invariant key components!");
9303
9304 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsOnlyExit}, EL});
9305 assert(InsertResult.second && "Expected successful insertion!");
9306 (void)InsertResult;
9307 (void)ExitIfTrue;
9308}
9309
9310ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
9311 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9312 bool ControlsOnlyExit, bool AllowPredicates) {
9313
9314 if (auto MaybeEL = Cache.find(L, ExitCond, ExitIfTrue, ControlsOnlyExit,
9315 AllowPredicates))
9316 return *MaybeEL;
9317
9318 ExitLimit EL = computeExitLimitFromCondImpl(
9319 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates);
9320 Cache.insert(L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates, EL);
9321 return EL;
9322}
9323
9324ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
9325 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9326 bool ControlsOnlyExit, bool AllowPredicates) {
9327 // Handle BinOp conditions (And, Or).
9328 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
9329 Cache, L, ExitCond, ExitIfTrue, AllowPredicates))
9330 return *LimitFromBinOp;
9331
9332 // With an icmp, it may be feasible to compute an exact backedge-taken count.
9333 // Proceed to the next level to examine the icmp.
9334 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
9335 ExitLimit EL =
9336 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsOnlyExit);
9337 if (EL.hasFullInfo() || !AllowPredicates)
9338 return EL;
9339
9340 // Try again, but use SCEV predicates this time.
9341 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue,
9342 ControlsOnlyExit,
9343 /*AllowPredicates=*/true);
9344 }
9345
9346 // Check for a constant condition. These are normally stripped out by
9347 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
9348 // preserve the CFG and is temporarily leaving constant conditions
9349 // in place.
9350 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
9351 if (ExitIfTrue == !CI->getZExtValue())
9352 // The backedge is always taken.
9353 return getCouldNotCompute();
9354 // The backedge is never taken.
9355 return getZero(CI->getType());
9356 }
9357
9358 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
9359 // with a constant step, we can form an equivalent icmp predicate and figure
9360 // out how many iterations will be taken before we exit.
9361 const WithOverflowInst *WO;
9362 const APInt *C;
9363 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
9364 match(WO->getRHS(), m_APInt(C))) {
9365 ConstantRange NWR =
9367 WO->getNoWrapKind());
9368 CmpInst::Predicate Pred;
9369 APInt NewRHSC, Offset;
9370 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
9371 if (!ExitIfTrue)
9372 Pred = ICmpInst::getInversePredicate(Pred);
9373 auto *LHS = getSCEV(WO->getLHS());
9374 if (Offset != 0)
9376 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
9377 ControlsOnlyExit, AllowPredicates);
9378 if (EL.hasAnyInfo())
9379 return EL;
9380 }
9381
9382 // If it's not an integer or pointer comparison then compute it the hard way.
9383 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9384}
9385
9386std::optional<ScalarEvolution::ExitLimit>
9387ScalarEvolution::computeExitLimitFromCondFromBinOp(ExitLimitCacheTy &Cache,
9388 const Loop *L,
9389 Value *ExitCond,
9390 bool ExitIfTrue,
9391 bool AllowPredicates) {
9392 // Check if the controlling expression for this loop is an And or Or.
9393 Value *Op0, *Op1;
9394 bool IsAnd;
9395 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
9396 IsAnd = true;
9397 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
9398 IsAnd = false;
9399 else
9400 return std::nullopt;
9401
9402 // A sub-condition of a non-trivial binop never solely controls the exit,
9403 // whether we exit always depends on both conditions.
9404 ExitLimit EL0 = computeExitLimitFromCondCached(
9405 Cache, L, Op0, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9406 ExitLimit EL1 = computeExitLimitFromCondCached(
9407 Cache, L, Op1, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9408
9409 // EitherMayExit is true in these two cases:
9410 // br (and Op0 Op1), loop, exit
9411 // br (or Op0 Op1), exit, loop
9412 bool EitherMayExit = IsAnd ^ ExitIfTrue;
9413
9414 const SCEV *BECount = getCouldNotCompute();
9415 const SCEV *ConstantMaxBECount = getCouldNotCompute();
9416 const SCEV *SymbolicMaxBECount = getCouldNotCompute();
9417 if (EitherMayExit) {
9418 bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
9419 // Both conditions must be same for the loop to continue executing.
9420 // Choose the less conservative count.
9421 if (EL0.ExactNotTaken != getCouldNotCompute() &&
9422 EL1.ExactNotTaken != getCouldNotCompute()) {
9423 BECount = getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken,
9424 UseSequentialUMin);
9425 }
9426 if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
9427 ConstantMaxBECount = EL1.ConstantMaxNotTaken;
9428 else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
9429 ConstantMaxBECount = EL0.ConstantMaxNotTaken;
9430 else
9431 ConstantMaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
9432 EL1.ConstantMaxNotTaken);
9433 if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
9434 SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
9435 else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
9436 SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
9437 else
9438 SymbolicMaxBECount = getUMinFromMismatchedTypes(
9439 EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
9440 } else {
9441 // Both conditions must be same at the same time for the loop to exit.
9442 // For now, be conservative.
9443 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
9444 BECount = EL0.ExactNotTaken;
9445 }
9446
9447 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
9448 // to be more aggressive when computing BECount than when computing
9449 // ConstantMaxBECount. In these cases it is possible for EL0.ExactNotTaken
9450 // and
9451 // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
9452 // EL1.ConstantMaxNotTaken to not.
9453 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
9454 !isa<SCEVCouldNotCompute>(BECount))
9455 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
9456 if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
9457 SymbolicMaxBECount =
9458 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
9459 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
9460 {ArrayRef(EL0.Predicates), ArrayRef(EL1.Predicates)});
9461}
9462
9463ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9464 const Loop *L, ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9465 bool AllowPredicates) {
9466 // If the condition was exit on true, convert the condition to exit on false
9467 CmpPredicate Pred;
9468 if (!ExitIfTrue)
9469 Pred = ExitCond->getCmpPredicate();
9470 else
9471 Pred = ExitCond->getInverseCmpPredicate();
9472 const ICmpInst::Predicate OriginalPred = Pred;
9473
9474 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
9475 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
9476
9477 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsOnlyExit,
9478 AllowPredicates);
9479 if (EL.hasAnyInfo())
9480 return EL;
9481
9482 auto *ExhaustiveCount =
9483 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9484
9485 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
9486 return ExhaustiveCount;
9487
9488 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
9489 ExitCond->getOperand(1), L, OriginalPred);
9490}
9491ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9492 const Loop *L, CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS,
9493 bool ControlsOnlyExit, bool AllowPredicates) {
9494
9495 // Try to evaluate any dependencies out of the loop.
9496 LHS = getSCEVAtScope(LHS, L);
9497 RHS = getSCEVAtScope(RHS, L);
9498
9499 // At this point, we would like to compute how many iterations of the
9500 // loop the predicate will return true for these inputs.
9501 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
9502 // If there is a loop-invariant, force it into the RHS.
9503 std::swap(LHS, RHS);
9505 }
9506
9507 bool ControllingFiniteLoop = ControlsOnlyExit && loopHasNoAbnormalExits(L) &&
9509 // Simplify the operands before analyzing them.
9510 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0);
9511
9512 // If we have a comparison of a chrec against a constant, try to use value
9513 // ranges to answer this query.
9514 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
9515 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
9516 if (AddRec->getLoop() == L) {
9517 // Form the constant range.
9518 ConstantRange CompRange =
9519 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
9520
9521 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
9522 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
9523 }
9524
9525 // If this loop must exit based on this condition (or execute undefined
9526 // behaviour), see if we can improve wrap flags. This is essentially
9527 // a must execute style proof.
9528 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
9529 // If we can prove the test sequence produced must repeat the same values
9530 // on self-wrap of the IV, then we can infer that IV doesn't self wrap
9531 // because if it did, we'd have an infinite (undefined) loop.
9532 // TODO: We can peel off any functions which are invertible *in L*. Loop
9533 // invariant terms are effectively constants for our purposes here.
9534 SCEVUse InnerLHS = LHS;
9535 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
9536 InnerLHS = ZExt->getOperand();
9537 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS);
9538 AR && !AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
9539 isKnownToBeAPowerOfTwo(AR->getStepRecurrence(*this), /*OrZero=*/true,
9540 /*OrNegative=*/true)) {
9541 auto Flags = AR->getNoWrapFlags();
9542 Flags = setFlags(Flags, SCEV::FlagNW);
9543 SmallVector<SCEVUse> Operands{AR->operands()};
9544 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
9545 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9546 }
9547
9548 // For a slt/ult condition with a positive step, can we prove nsw/nuw?
9549 // From no-self-wrap, this follows trivially from the fact that every
9550 // (un)signed-wrapped, but not self-wrapped value must be LT than the
9551 // last value before (un)signed wrap. Since we know that last value
9552 // didn't exit, nor will any smaller one.
9553 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT) {
9554 auto WrapType = Pred == ICmpInst::ICMP_SLT ? SCEV::FlagNSW : SCEV::FlagNUW;
9555 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9556 AR && AR->getLoop() == L && AR->isAffine() &&
9557 !AR->getNoWrapFlags(WrapType) && AR->hasNoSelfWrap() &&
9558 isKnownPositive(AR->getStepRecurrence(*this))) {
9559 auto Flags = AR->getNoWrapFlags();
9560 Flags = setFlags(Flags, WrapType);
9561 SmallVector<SCEVUse> Operands{AR->operands()};
9562 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
9563 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9564 }
9565 }
9566 }
9567
9568 switch (Pred) {
9569 case ICmpInst::ICMP_NE: { // while (X != Y)
9570 // Convert to: while (X-Y != 0)
9571 if (LHS->getType()->isPointerTy()) {
9574 return LHS;
9575 }
9576 if (RHS->getType()->isPointerTy()) {
9579 return RHS;
9580 }
9581 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit,
9582 AllowPredicates);
9583 if (EL.hasAnyInfo())
9584 return EL;
9585 break;
9586 }
9587 case ICmpInst::ICMP_EQ: { // while (X == Y)
9588 // Convert to: while (X-Y == 0)
9589 if (LHS->getType()->isPointerTy()) {
9592 return LHS;
9593 }
9594 if (RHS->getType()->isPointerTy()) {
9597 return RHS;
9598 }
9599 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
9600 if (EL.hasAnyInfo()) return EL;
9601 break;
9602 }
9603 case ICmpInst::ICMP_SLE:
9604 case ICmpInst::ICMP_ULE:
9605 // Since the loop is finite, an invariant RHS cannot include the boundary
9606 // value, otherwise it would loop forever.
9607 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9608 !isLoopInvariant(RHS, L)) {
9609 // Otherwise, perform the addition in a wider type, to avoid overflow.
9610 // If the LHS is an addrec with the appropriate nowrap flag, the
9611 // extension will be sunk into it and the exit count can be analyzed.
9612 auto *OldType = dyn_cast<IntegerType>(LHS->getType());
9613 if (!OldType)
9614 break;
9615 // Prefer doubling the bitwidth over adding a single bit to make it more
9616 // likely that we use a legal type.
9617 auto *NewType =
9618 Type::getIntNTy(OldType->getContext(), OldType->getBitWidth() * 2);
9619 if (ICmpInst::isSigned(Pred)) {
9620 LHS = getSignExtendExpr(LHS, NewType);
9621 RHS = getSignExtendExpr(RHS, NewType);
9622 } else {
9623 LHS = getZeroExtendExpr(LHS, NewType);
9624 RHS = getZeroExtendExpr(RHS, NewType);
9625 }
9626 }
9628 [[fallthrough]];
9629 case ICmpInst::ICMP_SLT:
9630 case ICmpInst::ICMP_ULT: { // while (X < Y)
9631 bool IsSigned = ICmpInst::isSigned(Pred);
9632 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9633 AllowPredicates);
9634 if (EL.hasAnyInfo())
9635 return EL;
9636 break;
9637 }
9638 case ICmpInst::ICMP_SGE:
9639 case ICmpInst::ICMP_UGE:
9640 // Since the loop is finite, an invariant RHS cannot include the boundary
9641 // value, otherwise it would loop forever.
9642 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9643 !isLoopInvariant(RHS, L))
9644 break;
9646 [[fallthrough]];
9647 case ICmpInst::ICMP_SGT:
9648 case ICmpInst::ICMP_UGT: { // while (X > Y)
9649 bool IsSigned = ICmpInst::isSigned(Pred);
9650 ExitLimit EL = howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9651 AllowPredicates);
9652 if (EL.hasAnyInfo())
9653 return EL;
9654 break;
9655 }
9656 default:
9657 break;
9658 }
9659
9660 return getCouldNotCompute();
9661}
9662
9663ScalarEvolution::ExitLimit
9664ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
9665 SwitchInst *Switch,
9666 BasicBlock *ExitingBlock,
9667 bool ControlsOnlyExit) {
9668 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
9669
9670 // Give up if the exit is the default dest of a switch.
9671 if (Switch->getDefaultDest() == ExitingBlock)
9672 return getCouldNotCompute();
9673
9674 assert(L->contains(Switch->getDefaultDest()) &&
9675 "Default case must not exit the loop!");
9676 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
9677 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
9678
9679 // while (X != Y) --> while (X-Y != 0)
9680 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit);
9681 if (EL.hasAnyInfo())
9682 return EL;
9683
9684 return getCouldNotCompute();
9685}
9686
9687static ConstantInt *
9689 ScalarEvolution &SE) {
9690 const SCEV *InVal = SE.getConstant(C);
9691 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
9693 "Evaluation of SCEV at constant didn't fold correctly?");
9694 return cast<SCEVConstant>(Val)->getValue();
9695}
9696
9697ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
9698 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
9699 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
9700 if (!RHS)
9701 return getCouldNotCompute();
9702
9703 const BasicBlock *Latch = L->getLoopLatch();
9704 if (!Latch)
9705 return getCouldNotCompute();
9706
9707 const BasicBlock *Predecessor = L->getLoopPredecessor();
9708 if (!Predecessor)
9709 return getCouldNotCompute();
9710
9711 // Return true if V is of the form "LHS `shift_op` <positive constant>".
9712 // Return LHS in OutLHS, shift_op in OutOpCode, and the shift amount in
9713 // OutShiftAmt.
9714 auto MatchPositiveShift = [](Value *V, Value *&OutLHS,
9715 Instruction::BinaryOps &OutOpCode,
9716 unsigned &OutShiftAmt) {
9717 using namespace PatternMatch;
9718
9719 ConstantInt *ShiftAmt;
9720 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9721 OutOpCode = Instruction::LShr;
9722 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9723 OutOpCode = Instruction::AShr;
9724 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9725 OutOpCode = Instruction::Shl;
9726 else
9727 return false;
9728
9729 uint64_t Amt = ShiftAmt->getValue().getLimitedValue();
9730 if (Amt == 0 || Amt >= OutLHS->getType()->getScalarSizeInBits())
9731 return false;
9732 OutShiftAmt = Amt;
9733 return true;
9734 };
9735
9736 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
9737 //
9738 // loop:
9739 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
9740 // %iv.shifted = lshr i32 %iv, <positive constant>
9741 //
9742 // Return true on a successful match. Return the corresponding PHI node (%iv
9743 // above) in PNOut, the opcode of the shift operation in OpCodeOut, and the
9744 // shift amount in ShiftAmtOut.
9745 auto MatchShiftRecurrence = [&](Value *V, PHINode *&PNOut,
9746 Instruction::BinaryOps &OpCodeOut,
9747 unsigned &ShiftAmtOut) {
9748 std::optional<Instruction::BinaryOps> PostShiftOpCode;
9749
9750 {
9752 Value *V;
9753 unsigned Amt;
9754
9755 // If we encounter a shift instruction, "peel off" the shift operation,
9756 // and remember that we did so. Later when we inspect %iv's backedge
9757 // value, we will make sure that the backedge value uses the same
9758 // operation.
9759 //
9760 // Note: the peeled shift operation does not have to be the same
9761 // instruction as the one feeding into the PHI's backedge value. We only
9762 // really care about it being the same *kind* of shift instruction --
9763 // that's all that is required for our later inferences to hold.
9764 if (MatchPositiveShift(LHS, V, OpC, Amt)) {
9765 PostShiftOpCode = OpC;
9766 LHS = V;
9767 }
9768 }
9769
9770 PNOut = dyn_cast<PHINode>(LHS);
9771 if (!PNOut || PNOut->getParent() != L->getHeader())
9772 return false;
9773
9774 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
9775 Value *OpLHS;
9776
9777 return
9778 // The backedge value for the PHI node must be a shift by a positive
9779 // amount
9780 MatchPositiveShift(BEValue, OpLHS, OpCodeOut, ShiftAmtOut) &&
9781
9782 // of the PHI node itself
9783 OpLHS == PNOut &&
9784
9785 // and the kind of shift should be match the kind of shift we peeled
9786 // off, if any.
9787 (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9788 };
9789
9790 PHINode *PN;
9792 unsigned ShiftAmt;
9793 if (!MatchShiftRecurrence(LHS, PN, OpCode, ShiftAmt))
9794 return getCouldNotCompute();
9795
9796 const DataLayout &DL = getDataLayout();
9797
9798 // The key rationale for this optimization is that for some kinds of shift
9799 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
9800 // within a finite number of iterations. If the condition guarding the
9801 // backedge (in the sense that the backedge is taken if the condition is true)
9802 // is false for the value the shift recurrence stabilizes to, then we know
9803 // that the backedge is taken only a finite number of times.
9804
9805 ConstantInt *StableValue = nullptr;
9806 switch (OpCode) {
9807 default:
9808 llvm_unreachable("Impossible case!");
9809
9810 case Instruction::AShr: {
9811 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
9812 // bitwidth(K) iterations.
9813 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
9814 KnownBits Known = computeKnownBits(FirstValue, DL, &AC,
9815 Predecessor->getTerminator(), &DT);
9816 auto *Ty = cast<IntegerType>(RHS->getType());
9817 if (Known.isNonNegative())
9818 StableValue = ConstantInt::get(Ty, 0);
9819 else if (Known.isNegative())
9820 StableValue = ConstantInt::get(Ty, -1, true);
9821 else
9822 return getCouldNotCompute();
9823
9824 break;
9825 }
9826 case Instruction::LShr:
9827 case Instruction::Shl:
9828 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
9829 // stabilize to 0 in at most bitwidth(K) iterations.
9830 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
9831 break;
9832 }
9833
9834 auto *Result =
9835 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
9836 assert(Result->getType()->isIntegerTy(1) &&
9837 "Otherwise cannot be an operand to a branch instruction");
9838
9839 if (Result->isNullValue()) {
9840 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9841 unsigned MaxBTC = BitWidth;
9842
9843 // For right-shift recurrences (lshr/ashr with non-negative start), we can
9844 // compute a tighter max backedge-taken count from the range of the start
9845 // value. After k shifts of ShiftAmt, value = start >> (k * ShiftAmt).
9846 // The value reaches 0 (the stable value) when k * ShiftAmt >=
9847 // activeBits(start), so max BTC = ceil(activeBits(maxStart) / ShiftAmt).
9848 if (OpCode == Instruction::LShr || OpCode == Instruction::AShr) {
9849 Value *StartValue = PN->getIncomingValueForBlock(Predecessor);
9850 const SCEV *StartSCEV = getSCEV(StartValue);
9851 APInt MaxStart = getUnsignedRangeMax(StartSCEV);
9852 if (MaxStart.isStrictlyPositive()) {
9853 unsigned ActiveBits = MaxStart.getActiveBits();
9854 unsigned RangeBTC = divideCeil(ActiveBits, ShiftAmt);
9855 MaxBTC = std::min(MaxBTC, RangeBTC);
9856 }
9857 }
9858
9859 const SCEV *UpperBound =
9861 return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
9862 }
9863
9864 return getCouldNotCompute();
9865}
9866
9867/// Return true if we can constant fold an instruction of the specified type,
9868/// assuming that all operands were constants.
9869static bool CanConstantFold(const Instruction *I) {
9873 return true;
9874
9875 if (const CallInst *CI = dyn_cast<CallInst>(I))
9876 if (const Function *F = CI->getCalledFunction())
9877 return canConstantFoldCallTo(CI, F);
9878 return false;
9879}
9880
9881/// Determine whether this instruction can constant evolve within this loop
9882/// assuming its operands can all constant evolve.
9883static bool canConstantEvolve(Instruction *I, const Loop *L) {
9884 // An instruction outside of the loop can't be derived from a loop PHI.
9885 if (!L->contains(I)) return false;
9886
9887 if (isa<PHINode>(I)) {
9888 // We don't currently keep track of the control flow needed to evaluate
9889 // PHIs, so we cannot handle PHIs inside of loops.
9890 return L->getHeader() == I->getParent();
9891 }
9892
9893 // If we won't be able to constant fold this expression even if the operands
9894 // are constants, bail early.
9895 return CanConstantFold(I);
9896}
9897
9898/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
9899/// recursing through each instruction operand until reaching a loop header phi.
9900static PHINode *
9903 unsigned Depth) {
9905 return nullptr;
9906
9907 // Otherwise, we can evaluate this instruction if all of its operands are
9908 // constant or derived from a PHI node themselves.
9909 PHINode *PHI = nullptr;
9910 for (Value *Op : UseInst->operands()) {
9911 if (isa<Constant>(Op)) continue;
9912
9914 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
9915
9916 PHINode *P = dyn_cast<PHINode>(OpInst);
9917 if (!P)
9918 // If this operand is already visited, reuse the prior result.
9919 // We may have P != PHI if this is the deepest point at which the
9920 // inconsistent paths meet.
9921 P = PHIMap.lookup(OpInst);
9922 if (!P) {
9923 // Recurse and memoize the results, whether a phi is found or not.
9924 // This recursive call invalidates pointers into PHIMap.
9925 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
9926 PHIMap[OpInst] = P;
9927 }
9928 if (!P)
9929 return nullptr; // Not evolving from PHI
9930 if (PHI && PHI != P)
9931 return nullptr; // Evolving from multiple different PHIs.
9932 PHI = P;
9933 }
9934 // This is a expression evolving from a constant PHI!
9935 return PHI;
9936}
9937
9938/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9939/// in the loop that V is derived from. We allow arbitrary operations along the
9940/// way, but the operands of an operation must either be constants or a value
9941/// derived from a constant PHI. If this expression does not fit with these
9942/// constraints, return null.
9945 if (!I || !canConstantEvolve(I, L)) return nullptr;
9946
9947 if (PHINode *PN = dyn_cast<PHINode>(I))
9948 return PN;
9949
9950 // Record non-constant instructions contained by the loop.
9952 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
9953}
9954
9955/// EvaluateExpression - Given an expression that passes the
9956/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9957/// in the loop has the value PHIVal. If we can't fold this expression for some
9958/// reason, return null.
9961 const DataLayout &DL,
9962 const TargetLibraryInfo *TLI) {
9963 // Convenient constant check, but redundant for recursive calls.
9964 if (Constant *C = dyn_cast<Constant>(V)) return C;
9966 if (!I) return nullptr;
9967
9968 if (Constant *C = Vals.lookup(I)) return C;
9969
9970 // An instruction inside the loop depends on a value outside the loop that we
9971 // weren't given a mapping for, or a value such as a call inside the loop.
9972 if (!canConstantEvolve(I, L)) return nullptr;
9973
9974 // An unmapped PHI can be due to a branch or another loop inside this loop,
9975 // or due to this not being the initial iteration through a loop where we
9976 // couldn't compute the evolution of this particular PHI last time.
9977 if (isa<PHINode>(I)) return nullptr;
9978
9979 std::vector<Constant*> Operands(I->getNumOperands());
9980
9981 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9982 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9983 if (!Operand) {
9984 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9985 if (!Operands[i]) return nullptr;
9986 continue;
9987 }
9988 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9989 Vals[Operand] = C;
9990 if (!C) return nullptr;
9991 Operands[i] = C;
9992 }
9993
9994 return ConstantFoldInstOperands(I, Operands, DL, TLI,
9995 /*AllowNonDeterministic=*/false);
9996}
9997
9998
9999// If every incoming value to PN except the one for BB is a specific Constant,
10000// return that, else return nullptr.
10002 Constant *IncomingVal = nullptr;
10003
10004 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10005 if (PN->getIncomingBlock(i) == BB)
10006 continue;
10007
10008 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
10009 if (!CurrentVal)
10010 return nullptr;
10011
10012 if (IncomingVal != CurrentVal) {
10013 if (IncomingVal)
10014 return nullptr;
10015 IncomingVal = CurrentVal;
10016 }
10017 }
10018
10019 return IncomingVal;
10020}
10021
10022/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
10023/// in the header of its containing loop, we know the loop executes a
10024/// constant number of times, and the PHI node is just a recurrence
10025/// involving constants, fold it.
10026Constant *
10027ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
10028 const APInt &BEs,
10029 const Loop *L) {
10030 auto [I, Inserted] = ConstantEvolutionLoopExitValue.try_emplace(PN);
10031 if (!Inserted)
10032 return I->second;
10033
10035 return nullptr; // Not going to evaluate it.
10036
10037 Constant *&RetVal = I->second;
10038
10039 DenseMap<Instruction *, Constant *> CurrentIterVals;
10040 BasicBlock *Header = L->getHeader();
10041 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
10042
10043 BasicBlock *Latch = L->getLoopLatch();
10044 if (!Latch)
10045 return nullptr;
10046
10047 for (PHINode &PHI : Header->phis()) {
10048 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
10049 CurrentIterVals[&PHI] = StartCST;
10050 }
10051 if (!CurrentIterVals.count(PN))
10052 return RetVal = nullptr;
10053
10054 Value *BEValue = PN->getIncomingValueForBlock(Latch);
10055
10056 // Execute the loop symbolically to determine the exit value.
10057 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
10058 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
10059
10060 unsigned NumIterations = BEs.getZExtValue(); // must be in range
10061 unsigned IterationNum = 0;
10062 const DataLayout &DL = getDataLayout();
10063 for (; ; ++IterationNum) {
10064 if (IterationNum == NumIterations)
10065 return RetVal = CurrentIterVals[PN]; // Got exit value!
10066
10067 // Compute the value of the PHIs for the next iteration.
10068 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
10069 DenseMap<Instruction *, Constant *> NextIterVals;
10070 Constant *NextPHI =
10071 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
10072 if (!NextPHI)
10073 return nullptr; // Couldn't evaluate!
10074 NextIterVals[PN] = NextPHI;
10075
10076 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
10077
10078 // Also evaluate the other PHI nodes. However, we don't get to stop if we
10079 // cease to be able to evaluate one of them or if they stop evolving,
10080 // because that doesn't necessarily prevent us from computing PN.
10082 for (const auto &I : CurrentIterVals) {
10083 PHINode *PHI = dyn_cast<PHINode>(I.first);
10084 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
10085 PHIsToCompute.emplace_back(PHI, I.second);
10086 }
10087 // We use two distinct loops because EvaluateExpression may invalidate any
10088 // iterators into CurrentIterVals.
10089 for (const auto &I : PHIsToCompute) {
10090 PHINode *PHI = I.first;
10091 Constant *&NextPHI = NextIterVals[PHI];
10092 if (!NextPHI) { // Not already computed.
10093 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
10094 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
10095 }
10096 if (NextPHI != I.second)
10097 StoppedEvolving = false;
10098 }
10099
10100 // If all entries in CurrentIterVals == NextIterVals then we can stop
10101 // iterating, the loop can't continue to change.
10102 if (StoppedEvolving)
10103 return RetVal = CurrentIterVals[PN];
10104
10105 CurrentIterVals.swap(NextIterVals);
10106 }
10107}
10108
10109const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
10110 Value *Cond,
10111 bool ExitWhen) {
10112 PHINode *PN = getConstantEvolvingPHI(Cond, L);
10113 if (!PN) return getCouldNotCompute();
10114
10115 // If the loop is canonicalized, the PHI will have exactly two entries.
10116 // That's the only form we support here.
10117 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
10118
10119 DenseMap<Instruction *, Constant *> CurrentIterVals;
10120 BasicBlock *Header = L->getHeader();
10121 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
10122
10123 BasicBlock *Latch = L->getLoopLatch();
10124 assert(Latch && "Should follow from NumIncomingValues == 2!");
10125
10126 for (PHINode &PHI : Header->phis()) {
10127 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
10128 CurrentIterVals[&PHI] = StartCST;
10129 }
10130 if (!CurrentIterVals.count(PN))
10131 return getCouldNotCompute();
10132
10133 // Okay, we find a PHI node that defines the trip count of this loop. Execute
10134 // the loop symbolically to determine when the condition gets a value of
10135 // "ExitWhen".
10136 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
10137 const DataLayout &DL = getDataLayout();
10138 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
10139 auto *CondVal = dyn_cast_or_null<ConstantInt>(
10140 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
10141
10142 // Couldn't symbolically evaluate.
10143 if (!CondVal) return getCouldNotCompute();
10144
10145 if (CondVal->getValue() == uint64_t(ExitWhen)) {
10146 ++NumBruteForceTripCountsComputed;
10147 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
10148 }
10149
10150 // Update all the PHI nodes for the next iteration.
10151 DenseMap<Instruction *, Constant *> NextIterVals;
10152
10153 // Create a list of which PHIs we need to compute. We want to do this before
10154 // calling EvaluateExpression on them because that may invalidate iterators
10155 // into CurrentIterVals.
10156 SmallVector<PHINode *, 8> PHIsToCompute;
10157 for (const auto &I : CurrentIterVals) {
10158 PHINode *PHI = dyn_cast<PHINode>(I.first);
10159 if (!PHI || PHI->getParent() != Header) continue;
10160 PHIsToCompute.push_back(PHI);
10161 }
10162 for (PHINode *PHI : PHIsToCompute) {
10163 Constant *&NextPHI = NextIterVals[PHI];
10164 if (NextPHI) continue; // Already computed!
10165
10166 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
10167 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
10168 }
10169 CurrentIterVals.swap(NextIterVals);
10170 }
10171
10172 // Too many iterations were needed to evaluate.
10173 return getCouldNotCompute();
10174}
10175
10176const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
10178 ValuesAtScopes[V];
10179 // Check to see if we've folded this expression at this loop before.
10180 for (auto &LS : Values)
10181 if (LS.first == L)
10182 return LS.second ? LS.second : V;
10183
10184 Values.emplace_back(L, nullptr);
10185
10186 // Otherwise compute it.
10187 const SCEV *C = computeSCEVAtScope(V, L);
10188 for (auto &LS : reverse(ValuesAtScopes[V]))
10189 if (LS.first == L) {
10190 LS.second = C;
10191 if (!isa<SCEVConstant>(C))
10192 ValuesAtScopesUsers[C].push_back({L, V});
10193 break;
10194 }
10195 return C;
10196}
10197
10198/// This builds up a Constant using the ConstantExpr interface. That way, we
10199/// will return Constants for objects which aren't represented by a
10200/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
10201/// Returns NULL if the SCEV isn't representable as a Constant.
10203 switch (V->getSCEVType()) {
10204 case scCouldNotCompute:
10205 case scAddRecExpr:
10206 case scVScale:
10207 return nullptr;
10208 case scConstant:
10209 return cast<SCEVConstant>(V)->getValue();
10210 case scUnknown:
10212 case scPtrToAddr: {
10214 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
10215 return ConstantExpr::getPtrToAddr(CastOp, P2I->getType());
10216
10217 return nullptr;
10218 }
10219 case scPtrToInt: {
10221 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
10222 return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
10223
10224 return nullptr;
10225 }
10226 case scTruncate: {
10228 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
10229 return ConstantExpr::getTrunc(CastOp, ST->getType());
10230 return nullptr;
10231 }
10232 case scAddExpr: {
10233 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
10234 Constant *C = nullptr;
10235 for (const SCEV *Op : SA->operands()) {
10237 if (!OpC)
10238 return nullptr;
10239 if (!C) {
10240 C = OpC;
10241 continue;
10242 }
10243 assert(!C->getType()->isPointerTy() &&
10244 "Can only have one pointer, and it must be last");
10245 if (OpC->getType()->isPointerTy()) {
10246 // The offsets have been converted to bytes. We can add bytes using
10247 // an i8 GEP.
10248 C = ConstantExpr::getPtrAdd(OpC, C);
10249 } else {
10250 C = ConstantExpr::getAdd(C, OpC);
10251 }
10252 }
10253 return C;
10254 }
10255 case scMulExpr:
10256 case scSignExtend:
10257 case scZeroExtend:
10258 case scUDivExpr:
10259 case scSMaxExpr:
10260 case scUMaxExpr:
10261 case scSMinExpr:
10262 case scUMinExpr:
10264 return nullptr;
10265 }
10266 llvm_unreachable("Unknown SCEV kind!");
10267}
10268
10269const SCEV *ScalarEvolution::getWithOperands(const SCEV *S,
10270 SmallVectorImpl<SCEVUse> &NewOps) {
10271 switch (S->getSCEVType()) {
10272 case scTruncate:
10273 case scZeroExtend:
10274 case scSignExtend:
10275 case scPtrToAddr:
10276 case scPtrToInt:
10277 return getCastExpr(S->getSCEVType(), NewOps[0], S->getType());
10278 case scAddRecExpr: {
10279 auto *AddRec = cast<SCEVAddRecExpr>(S);
10280 return getAddRecExpr(NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags());
10281 }
10282 case scAddExpr:
10283 return getAddExpr(NewOps, cast<SCEVAddExpr>(S)->getNoWrapFlags());
10284 case scMulExpr:
10285 return getMulExpr(NewOps, cast<SCEVMulExpr>(S)->getNoWrapFlags());
10286 case scUDivExpr:
10287 return getUDivExpr(NewOps[0], NewOps[1]);
10288 case scUMaxExpr:
10289 case scSMaxExpr:
10290 case scUMinExpr:
10291 case scSMinExpr:
10292 return getMinMaxExpr(S->getSCEVType(), NewOps);
10294 return getSequentialMinMaxExpr(S->getSCEVType(), NewOps);
10295 case scConstant:
10296 case scVScale:
10297 case scUnknown:
10298 return S;
10299 case scCouldNotCompute:
10300 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10301 }
10302 llvm_unreachable("Unknown SCEV kind!");
10303}
10304
10305const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
10306 switch (V->getSCEVType()) {
10307 case scConstant:
10308 case scVScale:
10309 return V;
10310 case scAddRecExpr: {
10311 // If this is a loop recurrence for a loop that does not contain L, then we
10312 // are dealing with the final value computed by the loop.
10313 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(V);
10314 // First, attempt to evaluate each operand.
10315 // Avoid performing the look-up in the common case where the specified
10316 // expression has no loop-variant portions.
10317 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
10318 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
10319 if (OpAtScope == AddRec->getOperand(i))
10320 continue;
10321
10322 // Okay, at least one of these operands is loop variant but might be
10323 // foldable. Build a new instance of the folded commutative expression.
10325 NewOps.reserve(AddRec->getNumOperands());
10326 append_range(NewOps, AddRec->operands().take_front(i));
10327 NewOps.push_back(OpAtScope);
10328 for (++i; i != e; ++i)
10329 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
10330
10331 const SCEV *FoldedRec = getAddRecExpr(
10332 NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags(SCEV::FlagNW));
10333 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
10334 // The addrec may be folded to a nonrecurrence, for example, if the
10335 // induction variable is multiplied by zero after constant folding. Go
10336 // ahead and return the folded value.
10337 if (!AddRec)
10338 return FoldedRec;
10339 break;
10340 }
10341
10342 // If the scope is outside the addrec's loop, evaluate it by using the
10343 // loop exit value of the addrec.
10344 if (!AddRec->getLoop()->contains(L)) {
10345 // To evaluate this recurrence, we need to know how many times the AddRec
10346 // loop iterates. Compute this now.
10347 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
10348 if (BackedgeTakenCount == getCouldNotCompute())
10349 return AddRec;
10350
10351 // Then, evaluate the AddRec.
10352 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
10353 }
10354
10355 return AddRec;
10356 }
10357 case scTruncate:
10358 case scZeroExtend:
10359 case scSignExtend:
10360 case scPtrToAddr:
10361 case scPtrToInt:
10362 case scAddExpr:
10363 case scMulExpr:
10364 case scUDivExpr:
10365 case scUMaxExpr:
10366 case scSMaxExpr:
10367 case scUMinExpr:
10368 case scSMinExpr:
10369 case scSequentialUMinExpr: {
10370 ArrayRef<SCEVUse> Ops = V->operands();
10371 // Avoid performing the look-up in the common case where the specified
10372 // expression has no loop-variant portions.
10373 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
10374 const SCEV *OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10375 if (OpAtScope != Ops[i].getPointer()) {
10376 // Okay, at least one of these operands is loop variant but might be
10377 // foldable. Build a new instance of the folded commutative expression.
10379 NewOps.reserve(Ops.size());
10380 append_range(NewOps, Ops.take_front(i));
10381 NewOps.push_back(OpAtScope);
10382
10383 for (++i; i != e; ++i) {
10384 OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10385 NewOps.push_back(OpAtScope);
10386 }
10387
10388 return getWithOperands(V, NewOps);
10389 }
10390 }
10391 // If we got here, all operands are loop invariant.
10392 return V;
10393 }
10394 case scUnknown: {
10395 // If this instruction is evolved from a constant-evolving PHI, compute the
10396 // exit value from the loop without using SCEVs.
10397 const SCEVUnknown *SU = cast<SCEVUnknown>(V);
10399 if (!I)
10400 return V; // This is some other type of SCEVUnknown, just return it.
10401
10402 if (PHINode *PN = dyn_cast<PHINode>(I)) {
10403 const Loop *CurrLoop = this->LI[I->getParent()];
10404 // Looking for loop exit value.
10405 if (CurrLoop && CurrLoop->getParentLoop() == L &&
10406 PN->getParent() == CurrLoop->getHeader()) {
10407 // Okay, there is no closed form solution for the PHI node. Check
10408 // to see if the loop that contains it has a known backedge-taken
10409 // count. If so, we may be able to force computation of the exit
10410 // value.
10411 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
10412 // This trivial case can show up in some degenerate cases where
10413 // the incoming IR has not yet been fully simplified.
10414 if (BackedgeTakenCount->isZero()) {
10415 Value *InitValue = nullptr;
10416 bool MultipleInitValues = false;
10417 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
10418 if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
10419 if (!InitValue)
10420 InitValue = PN->getIncomingValue(i);
10421 else if (InitValue != PN->getIncomingValue(i)) {
10422 MultipleInitValues = true;
10423 break;
10424 }
10425 }
10426 }
10427 if (!MultipleInitValues && InitValue)
10428 return getSCEV(InitValue);
10429 }
10430 // Do we have a loop invariant value flowing around the backedge
10431 // for a loop which must execute the backedge?
10432 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
10433 isKnownNonZero(BackedgeTakenCount) &&
10434 PN->getNumIncomingValues() == 2) {
10435
10436 unsigned InLoopPred =
10437 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
10438 Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
10439 if (CurrLoop->isLoopInvariant(BackedgeVal))
10440 return getSCEV(BackedgeVal);
10441 }
10442 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
10443 // Okay, we know how many times the containing loop executes. If
10444 // this is a constant evolving PHI node, get the final value at
10445 // the specified iteration number.
10446 Constant *RV =
10447 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
10448 if (RV)
10449 return getSCEV(RV);
10450 }
10451 }
10452 }
10453
10454 // Okay, this is an expression that we cannot symbolically evaluate
10455 // into a SCEV. Check to see if it's possible to symbolically evaluate
10456 // the arguments into constants, and if so, try to constant propagate the
10457 // result. This is particularly useful for computing loop exit values.
10458 if (!CanConstantFold(I))
10459 return V; // This is some other type of SCEVUnknown, just return it.
10460
10461 SmallVector<Constant *, 4> Operands;
10462 Operands.reserve(I->getNumOperands());
10463 bool MadeImprovement = false;
10464 for (Value *Op : I->operands()) {
10465 if (Constant *C = dyn_cast<Constant>(Op)) {
10466 Operands.push_back(C);
10467 continue;
10468 }
10469
10470 // If any of the operands is non-constant and if they are
10471 // non-integer and non-pointer, don't even try to analyze them
10472 // with scev techniques.
10473 if (!isSCEVable(Op->getType()))
10474 return V;
10475
10476 const SCEV *OrigV = getSCEV(Op);
10477 const SCEV *OpV = getSCEVAtScope(OrigV, L);
10478 MadeImprovement |= OrigV != OpV;
10479
10481 if (!C)
10482 return V;
10483 assert(C->getType() == Op->getType() && "Type mismatch");
10484 Operands.push_back(C);
10485 }
10486
10487 // Check to see if getSCEVAtScope actually made an improvement.
10488 if (!MadeImprovement)
10489 return V; // This is some other type of SCEVUnknown, just return it.
10490
10491 Constant *C = nullptr;
10492 const DataLayout &DL = getDataLayout();
10493 C = ConstantFoldInstOperands(I, Operands, DL, &TLI,
10494 /*AllowNonDeterministic=*/false);
10495 if (!C)
10496 return V;
10497 return getSCEV(C);
10498 }
10499 case scCouldNotCompute:
10500 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10501 }
10502 llvm_unreachable("Unknown SCEV type!");
10503}
10504
10506 return getSCEVAtScope(getSCEV(V), L);
10507}
10508
10509const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
10511 return stripInjectiveFunctions(ZExt->getOperand());
10513 return stripInjectiveFunctions(SExt->getOperand());
10514 return S;
10515}
10516
10517/// Finds the minimum unsigned root of the following equation:
10518///
10519/// A * X = B (mod N)
10520///
10521/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
10522/// A and B isn't important.
10523///
10524/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
10525static const SCEV *
10528 ScalarEvolution &SE, const Loop *L) {
10529 uint32_t BW = A.getBitWidth();
10530 assert(BW == SE.getTypeSizeInBits(B->getType()));
10531 assert(A != 0 && "A must be non-zero.");
10532
10533 // 1. D = gcd(A, N)
10534 //
10535 // The gcd of A and N may have only one prime factor: 2. The number of
10536 // trailing zeros in A is its multiplicity
10537 uint32_t Mult2 = A.countr_zero();
10538 // D = 2^Mult2
10539
10540 // 2. Check if B is divisible by D.
10541 //
10542 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
10543 // is not less than multiplicity of this prime factor for D.
10544 unsigned MinTZ = SE.getMinTrailingZeros(B);
10545 // Try again with the terminator of the loop predecessor for context-specific
10546 // result, if MinTZ s too small.
10547 if (MinTZ < Mult2 && L->getLoopPredecessor())
10548 MinTZ = SE.getMinTrailingZeros(B, L->getLoopPredecessor()->getTerminator());
10549 if (MinTZ < Mult2) {
10550 // Check if we can prove there's no remainder using URem.
10551 const SCEV *URem =
10552 SE.getURemExpr(B, SE.getConstant(APInt::getOneBitSet(BW, Mult2)));
10553 const SCEV *Zero = SE.getZero(B->getType());
10554 if (!SE.isKnownPredicate(CmpInst::ICMP_EQ, URem, Zero)) {
10555 // Try to add a predicate ensuring B is a multiple of 1 << Mult2.
10556 if (!Predicates)
10557 return SE.getCouldNotCompute();
10558
10559 // Avoid adding a predicate that is known to be false.
10560 if (SE.isKnownPredicate(CmpInst::ICMP_NE, URem, Zero))
10561 return SE.getCouldNotCompute();
10562 Predicates->push_back(SE.getEqualPredicate(URem, Zero));
10563 }
10564 }
10565
10566 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
10567 // modulo (N / D).
10568 //
10569 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
10570 // (N / D) in general. The inverse itself always fits into BW bits, though,
10571 // so we immediately truncate it.
10572 APInt AD = A.lshr(Mult2).trunc(BW - Mult2); // AD = A / D
10573 APInt I = AD.multiplicativeInverse().zext(BW);
10574
10575 // 4. Compute the minimum unsigned root of the equation:
10576 // I * (B / D) mod (N / D)
10577 // To simplify the computation, we factor out the divide by D:
10578 // (I * B mod N) / D
10579 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
10580 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
10581}
10582
10583/// For a given quadratic addrec, generate coefficients of the corresponding
10584/// quadratic equation, multiplied by a common value to ensure that they are
10585/// integers.
10586/// The returned value is a tuple { A, B, C, M, BitWidth }, where
10587/// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
10588/// were multiplied by, and BitWidth is the bit width of the original addrec
10589/// coefficients.
10590/// This function returns std::nullopt if the addrec coefficients are not
10591/// compile- time constants.
10592static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
10594 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
10595 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
10596 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
10597 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
10598 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
10599 << *AddRec << '\n');
10600
10601 // We currently can only solve this if the coefficients are constants.
10602 if (!LC || !MC || !NC) {
10603 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
10604 return std::nullopt;
10605 }
10606
10607 APInt L = LC->getAPInt();
10608 APInt M = MC->getAPInt();
10609 APInt N = NC->getAPInt();
10610 assert(!N.isZero() && "This is not a quadratic addrec");
10611
10612 unsigned BitWidth = LC->getAPInt().getBitWidth();
10613 unsigned NewWidth = BitWidth + 1;
10614 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
10615 << BitWidth << '\n');
10616 // The sign-extension (as opposed to a zero-extension) here matches the
10617 // extension used in SolveQuadraticEquationWrap (with the same motivation).
10618 N = N.sext(NewWidth);
10619 M = M.sext(NewWidth);
10620 L = L.sext(NewWidth);
10621
10622 // The increments are M, M+N, M+2N, ..., so the accumulated values are
10623 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
10624 // L+M, L+2M+N, L+3M+3N, ...
10625 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
10626 //
10627 // The equation Acc = 0 is then
10628 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
10629 // In a quadratic form it becomes:
10630 // N n^2 + (2M-N) n + 2L = 0.
10631
10632 APInt A = N;
10633 APInt B = 2 * M - A;
10634 APInt C = 2 * L;
10635 APInt T = APInt(NewWidth, 2);
10636 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
10637 << "x + " << C << ", coeff bw: " << NewWidth
10638 << ", multiplied by " << T << '\n');
10639 return std::make_tuple(A, B, C, T, BitWidth);
10640}
10641
10642/// Helper function to compare optional APInts:
10643/// (a) if X and Y both exist, return min(X, Y),
10644/// (b) if neither X nor Y exist, return std::nullopt,
10645/// (c) if exactly one of X and Y exists, return that value.
10646static std::optional<APInt> MinOptional(std::optional<APInt> X,
10647 std::optional<APInt> Y) {
10648 if (X && Y) {
10649 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
10650 APInt XW = X->sext(W);
10651 APInt YW = Y->sext(W);
10652 return XW.slt(YW) ? *X : *Y;
10653 }
10654 if (!X && !Y)
10655 return std::nullopt;
10656 return X ? *X : *Y;
10657}
10658
10659/// Helper function to truncate an optional APInt to a given BitWidth.
10660/// When solving addrec-related equations, it is preferable to return a value
10661/// that has the same bit width as the original addrec's coefficients. If the
10662/// solution fits in the original bit width, truncate it (except for i1).
10663/// Returning a value of a different bit width may inhibit some optimizations.
10664///
10665/// In general, a solution to a quadratic equation generated from an addrec
10666/// may require BW+1 bits, where BW is the bit width of the addrec's
10667/// coefficients. The reason is that the coefficients of the quadratic
10668/// equation are BW+1 bits wide (to avoid truncation when converting from
10669/// the addrec to the equation).
10670static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
10671 unsigned BitWidth) {
10672 if (!X)
10673 return std::nullopt;
10674 unsigned W = X->getBitWidth();
10676 return X->trunc(BitWidth);
10677 return X;
10678}
10679
10680/// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
10681/// iterations. The values L, M, N are assumed to be signed, and they
10682/// should all have the same bit widths.
10683/// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
10684/// where BW is the bit width of the addrec's coefficients.
10685/// If the calculated value is a BW-bit integer (for BW > 1), it will be
10686/// returned as such, otherwise the bit width of the returned value may
10687/// be greater than BW.
10688///
10689/// This function returns std::nullopt if
10690/// (a) the addrec coefficients are not constant, or
10691/// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
10692/// like x^2 = 5, no integer solutions exist, in other cases an integer
10693/// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
10694static std::optional<APInt>
10696 APInt A, B, C, M;
10697 unsigned BitWidth;
10698 auto T = GetQuadraticEquation(AddRec);
10699 if (!T)
10700 return std::nullopt;
10701
10702 std::tie(A, B, C, M, BitWidth) = *T;
10703 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
10704 std::optional<APInt> X =
10706 if (!X)
10707 return std::nullopt;
10708
10709 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
10710 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
10711 if (!V->isZero())
10712 return std::nullopt;
10713
10714 return TruncIfPossible(X, BitWidth);
10715}
10716
10717/// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
10718/// iterations. The values M, N are assumed to be signed, and they
10719/// should all have the same bit widths.
10720/// Find the least n such that c(n) does not belong to the given range,
10721/// while c(n-1) does.
10722///
10723/// This function returns std::nullopt if
10724/// (a) the addrec coefficients are not constant, or
10725/// (b) SolveQuadraticEquationWrap was unable to find a solution for the
10726/// bounds of the range.
10727static std::optional<APInt>
10729 const ConstantRange &Range, ScalarEvolution &SE) {
10730 assert(AddRec->getOperand(0)->isZero() &&
10731 "Starting value of addrec should be 0");
10732 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
10733 << Range << ", addrec " << *AddRec << '\n');
10734 // This case is handled in getNumIterationsInRange. Here we can assume that
10735 // we start in the range.
10736 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
10737 "Addrec's initial value should be in range");
10738
10739 APInt A, B, C, M;
10740 unsigned BitWidth;
10741 auto T = GetQuadraticEquation(AddRec);
10742 if (!T)
10743 return std::nullopt;
10744
10745 // Be careful about the return value: there can be two reasons for not
10746 // returning an actual number. First, if no solutions to the equations
10747 // were found, and second, if the solutions don't leave the given range.
10748 // The first case means that the actual solution is "unknown", the second
10749 // means that it's known, but not valid. If the solution is unknown, we
10750 // cannot make any conclusions.
10751 // Return a pair: the optional solution and a flag indicating if the
10752 // solution was found.
10753 auto SolveForBoundary =
10754 [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
10755 // Solve for signed overflow and unsigned overflow, pick the lower
10756 // solution.
10757 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
10758 << Bound << " (before multiplying by " << M << ")\n");
10759 Bound *= M; // The quadratic equation multiplier.
10760
10761 std::optional<APInt> SO;
10762 if (BitWidth > 1) {
10763 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10764 "signed overflow\n");
10766 }
10767 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10768 "unsigned overflow\n");
10769 std::optional<APInt> UO =
10771
10772 auto LeavesRange = [&] (const APInt &X) {
10773 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
10774 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
10775 if (Range.contains(V0->getValue()))
10776 return false;
10777 // X should be at least 1, so X-1 is non-negative.
10778 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
10780 if (Range.contains(V1->getValue()))
10781 return true;
10782 return false;
10783 };
10784
10785 // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
10786 // can be a solution, but the function failed to find it. We cannot treat it
10787 // as "no solution".
10788 if (!SO || !UO)
10789 return {std::nullopt, false};
10790
10791 // Check the smaller value first to see if it leaves the range.
10792 // At this point, both SO and UO must have values.
10793 std::optional<APInt> Min = MinOptional(SO, UO);
10794 if (LeavesRange(*Min))
10795 return { Min, true };
10796 std::optional<APInt> Max = Min == SO ? UO : SO;
10797 if (LeavesRange(*Max))
10798 return { Max, true };
10799
10800 // Solutions were found, but were eliminated, hence the "true".
10801 return {std::nullopt, true};
10802 };
10803
10804 std::tie(A, B, C, M, BitWidth) = *T;
10805 // Lower bound is inclusive, subtract 1 to represent the exiting value.
10806 APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
10807 APInt Upper = Range.getUpper().sext(A.getBitWidth());
10808 auto SL = SolveForBoundary(Lower);
10809 auto SU = SolveForBoundary(Upper);
10810 // If any of the solutions was unknown, no meaninigful conclusions can
10811 // be made.
10812 if (!SL.second || !SU.second)
10813 return std::nullopt;
10814
10815 // Claim: The correct solution is not some value between Min and Max.
10816 //
10817 // Justification: Assuming that Min and Max are different values, one of
10818 // them is when the first signed overflow happens, the other is when the
10819 // first unsigned overflow happens. Crossing the range boundary is only
10820 // possible via an overflow (treating 0 as a special case of it, modeling
10821 // an overflow as crossing k*2^W for some k).
10822 //
10823 // The interesting case here is when Min was eliminated as an invalid
10824 // solution, but Max was not. The argument is that if there was another
10825 // overflow between Min and Max, it would also have been eliminated if
10826 // it was considered.
10827 //
10828 // For a given boundary, it is possible to have two overflows of the same
10829 // type (signed/unsigned) without having the other type in between: this
10830 // can happen when the vertex of the parabola is between the iterations
10831 // corresponding to the overflows. This is only possible when the two
10832 // overflows cross k*2^W for the same k. In such case, if the second one
10833 // left the range (and was the first one to do so), the first overflow
10834 // would have to enter the range, which would mean that either we had left
10835 // the range before or that we started outside of it. Both of these cases
10836 // are contradictions.
10837 //
10838 // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
10839 // solution is not some value between the Max for this boundary and the
10840 // Min of the other boundary.
10841 //
10842 // Justification: Assume that we had such Max_A and Min_B corresponding
10843 // to range boundaries A and B and such that Max_A < Min_B. If there was
10844 // a solution between Max_A and Min_B, it would have to be caused by an
10845 // overflow corresponding to either A or B. It cannot correspond to B,
10846 // since Min_B is the first occurrence of such an overflow. If it
10847 // corresponded to A, it would have to be either a signed or an unsigned
10848 // overflow that is larger than both eliminated overflows for A. But
10849 // between the eliminated overflows and this overflow, the values would
10850 // cover the entire value space, thus crossing the other boundary, which
10851 // is a contradiction.
10852
10853 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
10854}
10855
10856ScalarEvolution::ExitLimit ScalarEvolution::howFarToZero(const SCEV *V,
10857 const Loop *L,
10858 bool ControlsOnlyExit,
10859 bool AllowPredicates) {
10860
10861 // This is only used for loops with a "x != y" exit test. The exit condition
10862 // is now expressed as a single expression, V = x-y. So the exit test is
10863 // effectively V != 0. We know and take advantage of the fact that this
10864 // expression only being used in a comparison by zero context.
10865
10867 // If the value is a constant
10868 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10869 // If the value is already zero, the branch will execute zero times.
10870 if (C->getValue()->isZero()) return C;
10871 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10872 }
10873
10874 const SCEVAddRecExpr *AddRec =
10875 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
10876
10877 if (!AddRec && AllowPredicates)
10878 // Try to make this an AddRec using runtime tests, in the first X
10879 // iterations of this loop, where X is the SCEV expression found by the
10880 // algorithm below.
10881 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
10882
10883 if (!AddRec || AddRec->getLoop() != L)
10884 return getCouldNotCompute();
10885
10886 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
10887 // the quadratic equation to solve it.
10888 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
10889 // We can only use this value if the chrec ends up with an exact zero
10890 // value at this index. When solving for "X*X != 5", for example, we
10891 // should not accept a root of 2.
10892 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
10893 const auto *R = cast<SCEVConstant>(getConstant(*S));
10894 return ExitLimit(R, R, R, false, Predicates);
10895 }
10896 return getCouldNotCompute();
10897 }
10898
10899 // Otherwise we can only handle this if it is affine.
10900 if (!AddRec->isAffine())
10901 return getCouldNotCompute();
10902
10903 // If this is an affine expression, the execution count of this branch is
10904 // the minimum unsigned root of the following equation:
10905 //
10906 // Start + Step*N = 0 (mod 2^BW)
10907 //
10908 // equivalent to:
10909 //
10910 // Step*N = -Start (mod 2^BW)
10911 //
10912 // where BW is the common bit width of Start and Step.
10913
10914 // Get the initial value for the loop.
10915 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
10916 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
10917
10918 if (!isLoopInvariant(Step, L))
10919 return getCouldNotCompute();
10920
10921 LoopGuards Guards = LoopGuards::collect(L, *this);
10922 // Specialize step for this loop so we get context sensitive facts below.
10923 const SCEV *StepWLG = applyLoopGuards(Step, Guards);
10924
10925 // For positive steps (counting up until unsigned overflow):
10926 // N = -Start/Step (as unsigned)
10927 // For negative steps (counting down to zero):
10928 // N = Start/-Step
10929 // First compute the unsigned distance from zero in the direction of Step.
10930 bool CountDown = isKnownNegative(StepWLG);
10931 if (!CountDown && !isKnownNonNegative(StepWLG))
10932 return getCouldNotCompute();
10933
10934 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
10935 // Handle unitary steps, which cannot wraparound.
10936 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10937 // N = Distance (as unsigned)
10938
10939 if (match(Step, m_CombineOr(m_scev_One(), m_scev_AllOnes()))) {
10940 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, Guards));
10941 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
10942
10943 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10944 // we end up with a loop whose backedge-taken count is n - 1. Detect this
10945 // case, and see if we can improve the bound.
10946 //
10947 // Explicitly handling this here is necessary because getUnsignedRange
10948 // isn't context-sensitive; it doesn't know that we only care about the
10949 // range inside the loop.
10950 const SCEV *Zero = getZero(Distance->getType());
10951 const SCEV *One = getOne(Distance->getType());
10952 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
10953 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
10954 // If Distance + 1 doesn't overflow, we can compute the maximum distance
10955 // as "unsigned_max(Distance + 1) - 1".
10956 ConstantRange CR = getUnsignedRange(DistancePlusOne);
10957 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
10958 }
10959 return ExitLimit(Distance, getConstant(MaxBECount), Distance, false,
10960 Predicates);
10961 }
10962
10963 // If the condition controls loop exit (the loop exits only if the expression
10964 // is true) and the addition is no-wrap we can use unsigned divide to
10965 // compute the backedge count. In this case, the step may not divide the
10966 // distance, but we don't care because if the condition is "missed" the loop
10967 // will have undefined behavior due to wrapping.
10968 if (ControlsOnlyExit && AddRec->hasNoSelfWrap() &&
10969 loopHasNoAbnormalExits(AddRec->getLoop())) {
10970
10971 // If the stride is zero and the start is non-zero, the loop must be
10972 // infinite. In C++, most loops are finite by assumption, in which case the
10973 // step being zero implies UB must execute if the loop is entered.
10974 if (!(loopIsFiniteByAssumption(L) && isKnownNonZero(Start)) &&
10975 !isKnownNonZero(StepWLG))
10976 return getCouldNotCompute();
10977
10978 const SCEV *Exact =
10979 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10980 const SCEV *ConstantMax = getCouldNotCompute();
10981 if (Exact != getCouldNotCompute()) {
10982 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, Guards));
10983 ConstantMax =
10985 }
10986 const SCEV *SymbolicMax =
10987 isa<SCEVCouldNotCompute>(Exact) ? ConstantMax : Exact;
10988 return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
10989 }
10990
10991 // Solve the general equation.
10992 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
10993 if (!StepC || StepC->getValue()->isZero())
10994 return getCouldNotCompute();
10995 const SCEV *E = SolveLinEquationWithOverflow(
10996 StepC->getAPInt(), getNegativeSCEV(Start),
10997 AllowPredicates ? &Predicates : nullptr, *this, L);
10998
10999 const SCEV *M = E;
11000 if (E != getCouldNotCompute()) {
11001 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, Guards));
11002 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
11003 }
11004 auto *S = isa<SCEVCouldNotCompute>(E) ? M : E;
11005 return ExitLimit(E, M, S, false, Predicates);
11006}
11007
11008ScalarEvolution::ExitLimit
11009ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
11010 // Loops that look like: while (X == 0) are very strange indeed. We don't
11011 // handle them yet except for the trivial case. This could be expanded in the
11012 // future as needed.
11013
11014 // If the value is a constant, check to see if it is known to be non-zero
11015 // already. If so, the backedge will execute zero times.
11016 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
11017 if (!C->getValue()->isZero())
11018 return getZero(C->getType());
11019 return getCouldNotCompute(); // Otherwise it will loop infinitely.
11020 }
11021
11022 // We could implement others, but I really doubt anyone writes loops like
11023 // this, and if they did, they would already be constant folded.
11024 return getCouldNotCompute();
11025}
11026
11027std::pair<const BasicBlock *, const BasicBlock *>
11028ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
11029 const {
11030 // If the block has a unique predecessor, then there is no path from the
11031 // predecessor to the block that does not go through the direct edge
11032 // from the predecessor to the block.
11033 if (const BasicBlock *Pred = BB->getSinglePredecessor())
11034 return {Pred, BB};
11035
11036 // A loop's header is defined to be a block that dominates the loop.
11037 // If the header has a unique predecessor outside the loop, it must be
11038 // a block that has exactly one successor that can reach the loop.
11039 if (const Loop *L = LI.getLoopFor(BB))
11040 return {L->getLoopPredecessor(), L->getHeader()};
11041
11042 return {nullptr, BB};
11043}
11044
11045/// SCEV structural equivalence is usually sufficient for testing whether two
11046/// expressions are equal, however for the purposes of looking for a condition
11047/// guarding a loop, it can be useful to be a little more general, since a
11048/// front-end may have replicated the controlling expression.
11049static bool HasSameValue(const SCEV *A, const SCEV *B) {
11050 // Quick check to see if they are the same SCEV.
11051 if (A == B) return true;
11052
11053 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
11054 // Not all instructions that are "identical" compute the same value. For
11055 // instance, two distinct alloca instructions allocating the same type are
11056 // identical and do not read memory; but compute distinct values.
11057 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
11058 };
11059
11060 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
11061 // two different instructions with the same value. Check for this case.
11062 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
11063 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
11064 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
11065 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
11066 if (ComputesEqualValues(AI, BI))
11067 return true;
11068
11069 // Otherwise assume they may have a different value.
11070 return false;
11071}
11072
11073static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS) {
11074 const SCEV *Op0, *Op1;
11075 if (!match(S, m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))))
11076 return false;
11077 if (match(Op0, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
11078 LHS = Op1;
11079 return true;
11080 }
11081 if (match(Op1, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
11082 LHS = Op0;
11083 return true;
11084 }
11085 return false;
11086}
11087
11089 SCEVUse &RHS, unsigned Depth) {
11090 bool Changed = false;
11091 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
11092 // '0 != 0'.
11093 auto TrivialCase = [&](bool TriviallyTrue) {
11095 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
11096 return true;
11097 };
11098 // If we hit the max recursion limit bail out.
11099 if (Depth >= 3)
11100 return false;
11101
11102 const SCEV *NewLHS, *NewRHS;
11103 if (match(LHS, m_scev_c_Mul(m_SCEV(NewLHS), m_SCEVVScale())) &&
11104 match(RHS, m_scev_c_Mul(m_SCEV(NewRHS), m_SCEVVScale()))) {
11105 const SCEVMulExpr *LMul = cast<SCEVMulExpr>(LHS);
11106 const SCEVMulExpr *RMul = cast<SCEVMulExpr>(RHS);
11107
11108 // (X * vscale) pred (Y * vscale) ==> X pred Y
11109 // when both multiples are NSW.
11110 // (X * vscale) uicmp/eq/ne (Y * vscale) ==> X uicmp/eq/ne Y
11111 // when both multiples are NUW.
11112 if ((LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap()) ||
11113 (LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap() &&
11114 !ICmpInst::isSigned(Pred))) {
11115 LHS = NewLHS;
11116 RHS = NewRHS;
11117 Changed = true;
11118 }
11119 }
11120
11121 // Canonicalize a constant to the right side.
11122 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
11123 // Check for both operands constant.
11124 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
11125 if (!ICmpInst::compare(LHSC->getAPInt(), RHSC->getAPInt(), Pred))
11126 return TrivialCase(false);
11127 return TrivialCase(true);
11128 }
11129 // Otherwise swap the operands to put the constant on the right.
11130 std::swap(LHS, RHS);
11132 Changed = true;
11133 }
11134
11135 // (K + A) pred (K + B) --> A pred B
11136 // For equality, no flags are needed.
11137 // For signed, both adds must be NSW. For unsigned, both must be NUW.
11138 {
11139 const SCEVConstant *C = nullptr;
11140 if (match(LHS, m_scev_Add(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11141 match(RHS, m_scev_Add(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11142 const auto *LAdd = cast<SCEVAddExpr>(LHS);
11143 const auto *RAdd = cast<SCEVAddExpr>(RHS);
11144 if (ICmpInst::isEquality(Pred) ||
11145 (ICmpInst::isSigned(Pred) && LAdd->hasNoSignedWrap() &&
11146 RAdd->hasNoSignedWrap()) ||
11147 (ICmpInst::isUnsigned(Pred) && LAdd->hasNoUnsignedWrap() &&
11148 RAdd->hasNoUnsignedWrap())) {
11149 LHS = NewLHS;
11150 RHS = NewRHS;
11151 Changed = true;
11152 }
11153 }
11154 }
11155
11156 // (C * A) pred (C * B) --> A pred B
11157 // For equality predicates, both muls must be NUW or both must be NSW
11158 // (either suffices to make multiplication by C injective; C == 0 is
11159 // impossible because SCEV folds 0 * X to 0).
11160 // For signed ordering, C must be positive and both muls must be NSW.
11161 // For unsigned ordering, both muls must be NUW.
11162 {
11163 const SCEVConstant *C = nullptr;
11164 if (match(LHS, m_scev_Mul(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11165 match(RHS, m_scev_Mul(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11166 const auto *LMul = cast<SCEVMulExpr>(LHS);
11167 const auto *RMul = cast<SCEVMulExpr>(RHS);
11168 bool BothNUW = LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap();
11169 bool BothNSW = LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap();
11170 if ((ICmpInst::isEquality(Pred) && (BothNUW || BothNSW)) ||
11171 (ICmpInst::isSigned(Pred) && BothNSW &&
11172 C->getAPInt().isStrictlyPositive()) ||
11173 (ICmpInst::isUnsigned(Pred) && BothNUW)) {
11174 LHS = NewLHS;
11175 RHS = NewRHS;
11176 Changed = true;
11177 }
11178 }
11179 }
11180
11181 // If we're comparing an addrec with a value which is loop-invariant in the
11182 // addrec's loop, put the addrec on the left. Also make a dominance check,
11183 // as both operands could be addrecs loop-invariant in each other's loop.
11184 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
11185 const Loop *L = AR->getLoop();
11186 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
11187 std::swap(LHS, RHS);
11189 Changed = true;
11190 }
11191 }
11192
11193 // If there's a constant operand, canonicalize comparisons with boundary
11194 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
11195 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
11196 const APInt &RA = RC->getAPInt();
11197
11198 bool SimplifiedByConstantRange = false;
11199
11200 if (!ICmpInst::isEquality(Pred)) {
11202 if (ExactCR.isFullSet())
11203 return TrivialCase(true);
11204 if (ExactCR.isEmptySet())
11205 return TrivialCase(false);
11206
11207 APInt NewRHS;
11208 CmpInst::Predicate NewPred;
11209 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
11210 ICmpInst::isEquality(NewPred)) {
11211 // We were able to convert an inequality to an equality.
11212 Pred = NewPred;
11213 RHS = getConstant(NewRHS);
11214 Changed = SimplifiedByConstantRange = true;
11215 }
11216 }
11217
11218 if (!SimplifiedByConstantRange) {
11219 switch (Pred) {
11220 default:
11221 break;
11222 case ICmpInst::ICMP_EQ:
11223 case ICmpInst::ICMP_NE:
11224 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
11225 if (RA.isZero() && MatchBinarySub(LHS, LHS, RHS))
11226 Changed = true;
11227 break;
11228
11229 // The "Should have been caught earlier!" messages refer to the fact
11230 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
11231 // should have fired on the corresponding cases, and canonicalized the
11232 // check to trivial case.
11233
11234 case ICmpInst::ICMP_UGE:
11235 assert(!RA.isMinValue() && "Should have been caught earlier!");
11236 Pred = ICmpInst::ICMP_UGT;
11237 RHS = getConstant(RA - 1);
11238 Changed = true;
11239 break;
11240 case ICmpInst::ICMP_ULE:
11241 assert(!RA.isMaxValue() && "Should have been caught earlier!");
11242 Pred = ICmpInst::ICMP_ULT;
11243 RHS = getConstant(RA + 1);
11244 Changed = true;
11245 break;
11246 case ICmpInst::ICMP_SGE:
11247 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
11248 Pred = ICmpInst::ICMP_SGT;
11249 RHS = getConstant(RA - 1);
11250 Changed = true;
11251 break;
11252 case ICmpInst::ICMP_SLE:
11253 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
11254 Pred = ICmpInst::ICMP_SLT;
11255 RHS = getConstant(RA + 1);
11256 Changed = true;
11257 break;
11258 }
11259 }
11260 }
11261
11262 // Check for obvious equality.
11263 if (HasSameValue(LHS, RHS)) {
11264 if (ICmpInst::isTrueWhenEqual(Pred))
11265 return TrivialCase(true);
11267 return TrivialCase(false);
11268 }
11269
11270 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
11271 // adding or subtracting 1 from one of the operands.
11272 switch (Pred) {
11273 case ICmpInst::ICMP_SLE:
11274 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
11275 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11277 Pred = ICmpInst::ICMP_SLT;
11278 Changed = true;
11279 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
11280 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
11282 Pred = ICmpInst::ICMP_SLT;
11283 Changed = true;
11284 }
11285 break;
11286 case ICmpInst::ICMP_SGE:
11287 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
11288 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
11290 Pred = ICmpInst::ICMP_SGT;
11291 Changed = true;
11292 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
11293 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11295 Pred = ICmpInst::ICMP_SGT;
11296 Changed = true;
11297 }
11298 break;
11299 case ICmpInst::ICMP_ULE:
11300 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
11301 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11303 Pred = ICmpInst::ICMP_ULT;
11304 Changed = true;
11305 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
11306 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
11307 Pred = ICmpInst::ICMP_ULT;
11308 Changed = true;
11309 }
11310 break;
11311 case ICmpInst::ICMP_UGE:
11312 // If RHS is an op we can fold the -1, try that first.
11313 // Otherwise prefer LHS to preserve the nuw flag.
11314 if ((isa<SCEVConstant>(RHS) ||
11316 isa<SCEVConstant>(cast<SCEVNAryExpr>(RHS)->getOperand(0)))) &&
11317 !getUnsignedRangeMin(RHS).isMinValue()) {
11318 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11319 Pred = ICmpInst::ICMP_UGT;
11320 Changed = true;
11321 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
11322 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11324 Pred = ICmpInst::ICMP_UGT;
11325 Changed = true;
11326 } else if (!getUnsignedRangeMin(RHS).isMinValue()) {
11327 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11328 Pred = ICmpInst::ICMP_UGT;
11329 Changed = true;
11330 }
11331 break;
11332 default:
11333 break;
11334 }
11335
11336 // TODO: More simplifications are possible here.
11337
11338 // Recursively simplify until we either hit a recursion limit or nothing
11339 // changes.
11340 if (Changed)
11341 (void)SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1);
11342
11343 return Changed;
11344}
11345
11347 return getSignedRangeMax(S).isNegative();
11348}
11349
11353
11355 return !getSignedRangeMin(S).isNegative();
11356}
11357
11361
11363 // Query push down for cases where the unsigned range is
11364 // less than sufficient.
11365 if (const auto *SExt = dyn_cast<SCEVSignExtendExpr>(S))
11366 return isKnownNonZero(SExt->getOperand(0));
11367 return getUnsignedRangeMin(S) != 0;
11368}
11369
11371 bool OrNegative) {
11372 auto NonRecursive = [OrNegative](const SCEV *S) {
11373 if (auto *C = dyn_cast<SCEVConstant>(S))
11374 return C->getAPInt().isPowerOf2() ||
11375 (OrNegative && C->getAPInt().isNegatedPowerOf2());
11376
11377 // vscale is a power-of-two.
11378 return isa<SCEVVScale>(S);
11379 };
11380
11381 if (NonRecursive(S))
11382 return true;
11383
11384 auto *Mul = dyn_cast<SCEVMulExpr>(S);
11385 if (!Mul)
11386 return false;
11387 return all_of(Mul->operands(), NonRecursive) && (OrZero || isKnownNonZero(S));
11388}
11389
11391 const SCEV *S, uint64_t M,
11393 if (M == 0)
11394 return false;
11395 if (M == 1)
11396 return true;
11397
11398 // Recursively check AddRec operands. An AddRecExpr S is a multiple of M if S
11399 // starts with a multiple of M and at every iteration step S only adds
11400 // multiples of M.
11401 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
11402 return isKnownMultipleOf(AddRec->getStart(), M, Assumptions) &&
11403 isKnownMultipleOf(AddRec->getStepRecurrence(*this), M, Assumptions);
11404
11405 // For a constant, check that "S % M == 0".
11406 if (auto *Cst = dyn_cast<SCEVConstant>(S)) {
11407 APInt C = Cst->getAPInt();
11408 return C.urem(M) == 0;
11409 }
11410
11411 // TODO: Also check other SCEV expressions, i.e., SCEVAddRecExpr, etc.
11412
11413 // Basic tests have failed.
11414 // Check "S % M == 0" at compile time and record runtime Assumptions.
11415 auto *STy = dyn_cast<IntegerType>(S->getType());
11416 const SCEV *SmodM =
11417 getURemExpr(S, getConstant(ConstantInt::get(STy, M, false)));
11418 const SCEV *Zero = getZero(STy);
11419
11420 // Check whether "S % M == 0" is known at compile time.
11421 if (isKnownPredicate(ICmpInst::ICMP_EQ, SmodM, Zero))
11422 return true;
11423
11424 // Check whether "S % M != 0" is known at compile time.
11425 if (isKnownPredicate(ICmpInst::ICMP_NE, SmodM, Zero))
11426 return false;
11427
11429
11430 // Detect redundant predicates.
11431 for (auto *A : Assumptions)
11432 if (A->implies(P, *this))
11433 return true;
11434
11435 // Only record non-redundant predicates.
11436 Assumptions.push_back(P);
11437 return true;
11438}
11439
11441 return ((isKnownNonNegative(S1) && isKnownNonNegative(S2)) ||
11443}
11444
11445std::pair<const SCEV *, const SCEV *>
11447 // Compute SCEV on entry of loop L.
11448 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
11449 if (Start == getCouldNotCompute())
11450 return { Start, Start };
11451 // Compute post increment SCEV for loop L.
11452 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
11453 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
11454 return { Start, PostInc };
11455}
11456
11458 SCEVUse RHS) {
11459 // First collect all loops.
11461 getUsedLoops(LHS, LoopsUsed);
11462 getUsedLoops(RHS, LoopsUsed);
11463
11464 if (LoopsUsed.empty())
11465 return false;
11466
11467 // Domination relationship must be a linear order on collected loops.
11468#ifndef NDEBUG
11469 for (const auto *L1 : LoopsUsed)
11470 for (const auto *L2 : LoopsUsed)
11471 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
11472 DT.dominates(L2->getHeader(), L1->getHeader())) &&
11473 "Domination relationship is not a linear order");
11474#endif
11475
11476 const Loop *MDL =
11477 *llvm::max_element(LoopsUsed, [&](const Loop *L1, const Loop *L2) {
11478 return DT.properlyDominates(L1->getHeader(), L2->getHeader());
11479 });
11480
11481 // Get init and post increment value for LHS.
11482 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
11483 // if LHS contains unknown non-invariant SCEV then bail out.
11484 if (SplitLHS.first == getCouldNotCompute())
11485 return false;
11486 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
11487 // Get init and post increment value for RHS.
11488 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
11489 // if RHS contains unknown non-invariant SCEV then bail out.
11490 if (SplitRHS.first == getCouldNotCompute())
11491 return false;
11492 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
11493 // It is possible that init SCEV contains an invariant load but it does
11494 // not dominate MDL and is not available at MDL loop entry, so we should
11495 // check it here.
11496 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
11497 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
11498 return false;
11499
11500 // It seems backedge guard check is faster than entry one so in some cases
11501 // it can speed up whole estimation by short circuit
11502 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
11503 SplitRHS.second) &&
11504 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
11505}
11506
11508 SCEVUse RHS) {
11509 // Canonicalize the inputs first.
11510 (void)SimplifyICmpOperands(Pred, LHS, RHS);
11511
11512 if (isKnownViaInduction(Pred, LHS, RHS))
11513 return true;
11514
11515 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
11516 return true;
11517
11518 // Otherwise see what can be done with some simple reasoning.
11519 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
11520}
11521
11523 const SCEV *LHS,
11524 const SCEV *RHS) {
11525 if (isKnownPredicate(Pred, LHS, RHS))
11526 return true;
11528 return false;
11529 return std::nullopt;
11530}
11531
11533 const SCEV *RHS,
11534 const Instruction *CtxI) {
11535 // TODO: Analyze guards and assumes from Context's block.
11536 return isKnownPredicate(Pred, LHS, RHS) ||
11537 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
11538}
11539
11540std::optional<bool>
11542 const SCEV *RHS, const Instruction *CtxI) {
11543 std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
11544 if (KnownWithoutContext)
11545 return KnownWithoutContext;
11546
11547 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
11548 return true;
11550 CtxI->getParent(), ICmpInst::getInverseCmpPredicate(Pred), LHS, RHS))
11551 return false;
11552 return std::nullopt;
11553}
11554
11556 const SCEVAddRecExpr *LHS,
11557 const SCEV *RHS) {
11558 const Loop *L = LHS->getLoop();
11559 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
11560 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
11561}
11562
11563std::optional<ScalarEvolution::MonotonicPredicateType>
11565 ICmpInst::Predicate Pred) {
11566 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
11567
11568#ifndef NDEBUG
11569 // Verify an invariant: inverting the predicate should turn a monotonically
11570 // increasing change to a monotonically decreasing one, and vice versa.
11571 if (Result) {
11572 auto ResultSwapped =
11573 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
11574
11575 assert(*ResultSwapped != *Result &&
11576 "monotonicity should flip as we flip the predicate");
11577 }
11578#endif
11579
11580 return Result;
11581}
11582
11583std::optional<ScalarEvolution::MonotonicPredicateType>
11584ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
11585 ICmpInst::Predicate Pred) {
11586 // A zero step value for LHS means the induction variable is essentially a
11587 // loop invariant value. We don't really depend on the predicate actually
11588 // flipping from false to true (for increasing predicates, and the other way
11589 // around for decreasing predicates), all we care about is that *if* the
11590 // predicate changes then it only changes from false to true.
11591 //
11592 // A zero step value in itself is not very useful, but there may be places
11593 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
11594 // as general as possible.
11595
11596 // Only handle LE/LT/GE/GT predicates.
11597 if (!ICmpInst::isRelational(Pred))
11598 return std::nullopt;
11599
11600 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
11601 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
11602 "Should be greater or less!");
11603
11604 // Check that AR does not wrap.
11605 if (ICmpInst::isUnsigned(Pred)) {
11606 if (!LHS->hasNoUnsignedWrap())
11607 return std::nullopt;
11609 }
11610 assert(ICmpInst::isSigned(Pred) &&
11611 "Relational predicate is either signed or unsigned!");
11612 if (!LHS->hasNoSignedWrap())
11613 return std::nullopt;
11614
11615 const SCEV *Step = LHS->getStepRecurrence(*this);
11616
11617 if (isKnownNonNegative(Step))
11619
11620 if (isKnownNonPositive(Step))
11622
11623 return std::nullopt;
11624}
11625
11626std::optional<ScalarEvolution::LoopInvariantPredicate>
11628 const SCEV *RHS, const Loop *L,
11629 const Instruction *CtxI) {
11630 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11631 if (!isLoopInvariant(RHS, L)) {
11632 if (!isLoopInvariant(LHS, L))
11633 return std::nullopt;
11634
11635 std::swap(LHS, RHS);
11637 }
11638
11639 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11640 if (!ArLHS || ArLHS->getLoop() != L)
11641 return std::nullopt;
11642
11643 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
11644 if (!MonotonicType)
11645 return std::nullopt;
11646 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
11647 // true as the loop iterates, and the backedge is control dependent on
11648 // "ArLHS `Pred` RHS" == true then we can reason as follows:
11649 //
11650 // * if the predicate was false in the first iteration then the predicate
11651 // is never evaluated again, since the loop exits without taking the
11652 // backedge.
11653 // * if the predicate was true in the first iteration then it will
11654 // continue to be true for all future iterations since it is
11655 // monotonically increasing.
11656 //
11657 // For both the above possibilities, we can replace the loop varying
11658 // predicate with its value on the first iteration of the loop (which is
11659 // loop invariant).
11660 //
11661 // A similar reasoning applies for a monotonically decreasing predicate, by
11662 // replacing true with false and false with true in the above two bullets.
11664 auto P = Increasing ? Pred : ICmpInst::getInverseCmpPredicate(Pred);
11665
11666 if (isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
11668 RHS);
11669
11670 if (!CtxI)
11671 return std::nullopt;
11672 // Try to prove via context.
11673 // TODO: Support other cases.
11674 switch (Pred) {
11675 default:
11676 break;
11677 case ICmpInst::ICMP_ULE:
11678 case ICmpInst::ICMP_ULT: {
11679 assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!");
11680 // Given preconditions
11681 // (1) ArLHS does not cross the border of positive and negative parts of
11682 // range because of:
11683 // - Positive step; (TODO: lift this limitation)
11684 // - nuw - does not cross zero boundary;
11685 // - nsw - does not cross SINT_MAX boundary;
11686 // (2) ArLHS <s RHS
11687 // (3) RHS >=s 0
11688 // we can replace the loop variant ArLHS <u RHS condition with loop
11689 // invariant Start(ArLHS) <u RHS.
11690 //
11691 // Because of (1) there are two options:
11692 // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
11693 // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
11694 // It means that ArLHS <s RHS <=> ArLHS <u RHS.
11695 // Because of (2) ArLHS <u RHS is trivially true.
11696 // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
11697 // We can strengthen this to Start(ArLHS) <u RHS.
11698 auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
11699 if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
11700 isKnownPositive(ArLHS->getStepRecurrence(*this)) &&
11701 isKnownNonNegative(RHS) &&
11702 isKnownPredicateAt(SignFlippedPred, ArLHS, RHS, CtxI))
11704 RHS);
11705 }
11706 }
11707
11708 return std::nullopt;
11709}
11710
11711std::optional<ScalarEvolution::LoopInvariantPredicate>
11713 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11714 const Instruction *CtxI, const SCEV *MaxIter) {
11716 Pred, LHS, RHS, L, CtxI, MaxIter))
11717 return LIP;
11718 if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
11719 // Number of iterations expressed as UMIN isn't always great for expressing
11720 // the value on the last iteration. If the straightforward approach didn't
11721 // work, try the following trick: if the a predicate is invariant for X, it
11722 // is also invariant for umin(X, ...). So try to find something that works
11723 // among subexpressions of MaxIter expressed as umin.
11724 for (SCEVUse Op : UMin->operands())
11726 Pred, LHS, RHS, L, CtxI, Op))
11727 return LIP;
11728 return std::nullopt;
11729}
11730
11731std::optional<ScalarEvolution::LoopInvariantPredicate>
11733 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11734 const Instruction *CtxI, const SCEV *MaxIter) {
11735 // Try to prove the following set of facts:
11736 // - The predicate is monotonic in the iteration space.
11737 // - If the check does not fail on the 1st iteration:
11738 // - No overflow will happen during first MaxIter iterations;
11739 // - It will not fail on the MaxIter'th iteration.
11740 // If the check does fail on the 1st iteration, we leave the loop and no
11741 // other checks matter.
11742
11743 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11744 if (!isLoopInvariant(RHS, L)) {
11745 if (!isLoopInvariant(LHS, L))
11746 return std::nullopt;
11747
11748 std::swap(LHS, RHS);
11750 }
11751
11752 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
11753 if (!AR || AR->getLoop() != L)
11754 return std::nullopt;
11755
11756 // Even if both are valid, we need to consistently chose the unsigned or the
11757 // signed predicate below, not mixtures of both. For now, prefer the unsigned
11758 // predicate.
11759 Pred = Pred.dropSameSign();
11760
11761 // The predicate must be relational (i.e. <, <=, >=, >).
11762 if (!ICmpInst::isRelational(Pred))
11763 return std::nullopt;
11764
11765 // TODO: Support steps other than +/- 1.
11766 const SCEV *Step = AR->getStepRecurrence(*this);
11767 auto *One = getOne(Step->getType());
11768 auto *MinusOne = getNegativeSCEV(One);
11769 if (Step != One && Step != MinusOne)
11770 return std::nullopt;
11771
11772 // Type mismatch here means that MaxIter is potentially larger than max
11773 // unsigned value in start type, which mean we cannot prove no wrap for the
11774 // indvar.
11775 if (AR->getType() != MaxIter->getType())
11776 return std::nullopt;
11777
11778 // Value of IV on suggested last iteration.
11779 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
11780 // Does it still meet the requirement?
11781 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
11782 return std::nullopt;
11783 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
11784 // not exceed max unsigned value of this type), this effectively proves
11785 // that there is no wrap during the iteration. To prove that there is no
11786 // signed/unsigned wrap, we need to check that
11787 // Start <= Last for step = 1 or Start >= Last for step = -1.
11788 ICmpInst::Predicate NoOverflowPred =
11790 if (Step == MinusOne)
11791 NoOverflowPred = ICmpInst::getSwappedPredicate(NoOverflowPred);
11792 const SCEV *Start = AR->getStart();
11793 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
11794 return std::nullopt;
11795
11796 // Everything is fine.
11797 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
11798}
11799
11800bool ScalarEvolution::isKnownPredicateViaConstantRanges(CmpPredicate Pred,
11801 SCEVUse LHS,
11802 SCEVUse RHS) {
11803 if (HasSameValue(LHS, RHS))
11804 return ICmpInst::isTrueWhenEqual(Pred);
11805
11806 auto CheckRange = [&](bool IsSigned) {
11807 auto RangeLHS = IsSigned ? getSignedRange(LHS) : getUnsignedRange(LHS);
11808 auto RangeRHS = IsSigned ? getSignedRange(RHS) : getUnsignedRange(RHS);
11809 return RangeLHS.icmp(Pred, RangeRHS);
11810 };
11811
11812 // The check at the top of the function catches the case where the values are
11813 // known to be equal.
11814 if (Pred == CmpInst::ICMP_EQ)
11815 return false;
11816
11817 if (Pred == CmpInst::ICMP_NE) {
11818 if (CheckRange(true) || CheckRange(false))
11819 return true;
11820 auto *Diff = getMinusSCEV(LHS, RHS);
11821 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
11822 }
11823
11824 return CheckRange(CmpInst::isSigned(Pred));
11825}
11826
11827bool ScalarEvolution::isKnownPredicateViaNoOverflow(CmpPredicate Pred,
11829 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
11830 // C1 and C2 are constant integers. If either X or Y are not add expressions,
11831 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
11832 // OutC1 and OutC2.
11833 auto MatchBinaryAddToConst = [this](SCEVUse X, SCEVUse Y, APInt &OutC1,
11834 APInt &OutC2,
11835 SCEV::NoWrapFlags ExpectedFlags) {
11836 SCEVUse XNonConstOp, XConstOp;
11837 SCEVUse YNonConstOp, YConstOp;
11838 SCEV::NoWrapFlags XFlagsPresent;
11839 SCEV::NoWrapFlags YFlagsPresent;
11840
11841 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
11842 XConstOp = getZero(X->getType());
11843 XNonConstOp = X;
11844 XFlagsPresent = ExpectedFlags;
11845 }
11846 if (!isa<SCEVConstant>(XConstOp))
11847 return false;
11848
11849 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
11850 YConstOp = getZero(Y->getType());
11851 YNonConstOp = Y;
11852 YFlagsPresent = ExpectedFlags;
11853 }
11854
11855 if (YNonConstOp != XNonConstOp)
11856 return false;
11857
11858 if (!isa<SCEVConstant>(YConstOp))
11859 return false;
11860
11861 // When matching ADDs with NUW flags (and unsigned predicates), only the
11862 // second ADD (with the larger constant) requires NUW.
11863 if ((YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11864 return false;
11865 if (ExpectedFlags != SCEV::FlagNUW &&
11866 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) {
11867 return false;
11868 }
11869
11870 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
11871 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
11872
11873 return true;
11874 };
11875
11876 APInt C1;
11877 APInt C2;
11878
11879 switch (Pred) {
11880 default:
11881 break;
11882
11883 case ICmpInst::ICMP_SGE:
11884 std::swap(LHS, RHS);
11885 [[fallthrough]];
11886 case ICmpInst::ICMP_SLE:
11887 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
11888 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
11889 return true;
11890
11891 break;
11892
11893 case ICmpInst::ICMP_SGT:
11894 std::swap(LHS, RHS);
11895 [[fallthrough]];
11896 case ICmpInst::ICMP_SLT:
11897 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
11898 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
11899 return true;
11900
11901 break;
11902
11903 case ICmpInst::ICMP_UGE:
11904 std::swap(LHS, RHS);
11905 [[fallthrough]];
11906 case ICmpInst::ICMP_ULE:
11907 // (X + C1) u<= (X + C2)<nuw> for C1 u<= C2.
11908 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ule(C2))
11909 return true;
11910
11911 break;
11912
11913 case ICmpInst::ICMP_UGT:
11914 std::swap(LHS, RHS);
11915 [[fallthrough]];
11916 case ICmpInst::ICMP_ULT:
11917 // (X + C1) u< (X + C2)<nuw> if C1 u< C2.
11918 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ult(C2))
11919 return true;
11920 break;
11921 }
11922
11923 return false;
11924}
11925
11926bool ScalarEvolution::isKnownPredicateViaSplitting(CmpPredicate Pred,
11928 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
11929 return false;
11930
11931 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
11932 // the stack can result in exponential time complexity.
11933 SaveAndRestore Restore(ProvingSplitPredicate, true);
11934
11935 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
11936 //
11937 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
11938 // isKnownPredicate. isKnownPredicate is more powerful, but also more
11939 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
11940 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
11941 // use isKnownPredicate later if needed.
11942 return isKnownNonNegative(RHS) &&
11945}
11946
11947bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, CmpPredicate Pred,
11948 const SCEV *LHS, const SCEV *RHS) {
11949 // No need to even try if we know the module has no guards.
11950 if (!HasGuards)
11951 return false;
11952
11953 return any_of(*BB, [&](const Instruction &I) {
11954 using namespace llvm::PatternMatch;
11955
11956 Value *Condition;
11958 m_Value(Condition))) &&
11959 isImpliedCond(Pred, LHS, RHS, Condition, false);
11960 });
11961}
11962
11963/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
11964/// protected by a conditional between LHS and RHS. This is used to
11965/// to eliminate casts.
11967 CmpPredicate Pred,
11968 const SCEV *LHS,
11969 const SCEV *RHS) {
11970 // Interpret a null as meaning no loop, where there is obviously no guard
11971 // (interprocedural conditions notwithstanding). Do not bother about
11972 // unreachable loops.
11973 if (!L || !DT.isReachableFromEntry(L->getHeader()))
11974 return true;
11975
11976 if (VerifyIR)
11977 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
11978 "This cannot be done on broken IR!");
11979
11980
11981 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11982 return true;
11983
11984 BasicBlock *Latch = L->getLoopLatch();
11985 if (!Latch)
11986 return false;
11987
11988 CondBrInst *LoopContinuePredicate =
11990 if (LoopContinuePredicate &&
11991 isImpliedCond(Pred, LHS, RHS, LoopContinuePredicate->getCondition(),
11992 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
11993 return true;
11994
11995 // We don't want more than one activation of the following loops on the stack
11996 // -- that can lead to O(n!) time complexity.
11997 if (WalkingBEDominatingConds)
11998 return false;
11999
12000 SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
12001
12002 // See if we can exploit a trip count to prove the predicate.
12003 const auto &BETakenInfo = getBackedgeTakenInfo(L);
12004 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
12005 if (LatchBECount != getCouldNotCompute()) {
12006 // We know that Latch branches back to the loop header exactly
12007 // LatchBECount times. This means the backdege condition at Latch is
12008 // equivalent to "{0,+,1} u< LatchBECount".
12009 Type *Ty = LatchBECount->getType();
12010 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
12011 const SCEV *LoopCounter =
12012 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
12013 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
12014 LatchBECount))
12015 return true;
12016 }
12017
12018 // Check conditions due to any @llvm.assume intrinsics.
12019 for (auto &AssumeVH : AC.assumptions()) {
12020 if (!AssumeVH)
12021 continue;
12022 auto *CI = cast<CallInst>(AssumeVH);
12023 if (!DT.dominates(CI, Latch->getTerminator()))
12024 continue;
12025
12026 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
12027 return true;
12028 }
12029
12030 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
12031 return true;
12032
12033 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
12034 DTN != HeaderDTN; DTN = DTN->getIDom()) {
12035 assert(DTN && "should reach the loop header before reaching the root!");
12036
12037 BasicBlock *BB = DTN->getBlock();
12038 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
12039 return true;
12040
12041 BasicBlock *PBB = BB->getSinglePredecessor();
12042 if (!PBB)
12043 continue;
12044
12046 if (!ContBr || ContBr->getSuccessor(0) == ContBr->getSuccessor(1))
12047 continue;
12048
12049 // If we have an edge `E` within the loop body that dominates the only
12050 // latch, the condition guarding `E` also guards the backedge. This
12051 // reasoning works only for loops with a single latch.
12052 // We're constructively (and conservatively) enumerating edges within the
12053 // loop body that dominate the latch. The dominator tree better agree
12054 // with us on this:
12055 assert(DT.dominates(BasicBlockEdge(PBB, BB), Latch) && "should be!");
12056 if (isImpliedCond(Pred, LHS, RHS, ContBr->getCondition(),
12057 BB != ContBr->getSuccessor(0)))
12058 return true;
12059 }
12060
12061 return false;
12062}
12063
12065 CmpPredicate Pred,
12066 const SCEV *LHS,
12067 const SCEV *RHS) {
12068 // Do not bother proving facts for unreachable code.
12069 if (!DT.isReachableFromEntry(BB))
12070 return true;
12071 if (VerifyIR)
12072 assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
12073 "This cannot be done on broken IR!");
12074
12075 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
12076 // the facts (a >= b && a != b) separately. A typical situation is when the
12077 // non-strict comparison is known from ranges and non-equality is known from
12078 // dominating predicates. If we are proving strict comparison, we always try
12079 // to prove non-equality and non-strict comparison separately.
12080 CmpPredicate NonStrictPredicate = ICmpInst::getNonStrictCmpPredicate(Pred);
12081 const bool ProvingStrictComparison =
12082 Pred != NonStrictPredicate.dropSameSign();
12083 bool ProvedNonStrictComparison = false;
12084 bool ProvedNonEquality = false;
12085
12086 auto SplitAndProve = [&](std::function<bool(CmpPredicate)> Fn) -> bool {
12087 if (!ProvedNonStrictComparison)
12088 ProvedNonStrictComparison = Fn(NonStrictPredicate);
12089 if (!ProvedNonEquality)
12090 ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
12091 if (ProvedNonStrictComparison && ProvedNonEquality)
12092 return true;
12093 return false;
12094 };
12095
12096 if (ProvingStrictComparison) {
12097 auto ProofFn = [&](CmpPredicate P) {
12098 return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
12099 };
12100 if (SplitAndProve(ProofFn))
12101 return true;
12102 }
12103
12104 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
12105 auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
12106 const Instruction *CtxI = &BB->front();
12107 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
12108 return true;
12109 if (ProvingStrictComparison) {
12110 auto ProofFn = [&](CmpPredicate P) {
12111 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
12112 };
12113 if (SplitAndProve(ProofFn))
12114 return true;
12115 }
12116 return false;
12117 };
12118
12119 // Starting at the block's predecessor, climb up the predecessor chain, as long
12120 // as there are predecessors that can be found that have unique successors
12121 // leading to the original block.
12122 const Loop *ContainingLoop = LI.getLoopFor(BB);
12123 const BasicBlock *PredBB;
12124 if (ContainingLoop && ContainingLoop->getHeader() == BB)
12125 PredBB = ContainingLoop->getLoopPredecessor();
12126 else
12127 PredBB = BB->getSinglePredecessor();
12128 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
12129 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
12130 const CondBrInst *BlockEntryPredicate =
12131 dyn_cast<CondBrInst>(Pair.first->getTerminator());
12132 if (!BlockEntryPredicate)
12133 continue;
12134
12135 if (ProveViaCond(BlockEntryPredicate->getCondition(),
12136 BlockEntryPredicate->getSuccessor(0) != Pair.second))
12137 return true;
12138 }
12139
12140 // Check conditions due to any @llvm.assume intrinsics.
12141 for (auto &AssumeVH : AC.assumptions()) {
12142 if (!AssumeVH)
12143 continue;
12144 auto *CI = cast<CallInst>(AssumeVH);
12145 if (!DT.dominates(CI, BB))
12146 continue;
12147
12148 if (ProveViaCond(CI->getArgOperand(0), false))
12149 return true;
12150 }
12151
12152 // Check conditions due to any @llvm.experimental.guard intrinsics.
12153 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
12154 F.getParent(), Intrinsic::experimental_guard);
12155 if (GuardDecl)
12156 for (const auto *GU : GuardDecl->users())
12157 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
12158 if (Guard->getFunction() == BB->getParent() && DT.dominates(Guard, BB))
12159 if (ProveViaCond(Guard->getArgOperand(0), false))
12160 return true;
12161 return false;
12162}
12163
12165 const SCEV *LHS,
12166 const SCEV *RHS) {
12167 // Interpret a null as meaning no loop, where there is obviously no guard
12168 // (interprocedural conditions notwithstanding).
12169 if (!L)
12170 return false;
12171
12172 // Both LHS and RHS must be available at loop entry.
12174 "LHS is not available at Loop Entry");
12176 "RHS is not available at Loop Entry");
12177
12178 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
12179 return true;
12180
12181 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
12182}
12183
12184bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12185 const SCEV *RHS,
12186 const Value *FoundCondValue, bool Inverse,
12187 const Instruction *CtxI) {
12188 // False conditions implies anything. Do not bother analyzing it further.
12189 if (FoundCondValue ==
12190 ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
12191 return true;
12192
12193 if (!PendingLoopPredicates.insert(FoundCondValue).second)
12194 return false;
12195
12196 llvm::scope_exit ClearOnExit(
12197 [&]() { PendingLoopPredicates.erase(FoundCondValue); });
12198
12199 // Recursively handle And and Or conditions.
12200 const Value *Op0, *Op1;
12201 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
12202 if (!Inverse)
12203 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12204 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12205 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
12206 if (Inverse)
12207 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12208 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12209 }
12210
12211 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
12212 if (!ICI) return false;
12213
12214 // Now that we found a conditional branch that dominates the loop or controls
12215 // the loop latch. Check to see if it is the comparison we are looking for.
12216 CmpPredicate FoundPred;
12217 if (Inverse)
12218 FoundPred = ICI->getInverseCmpPredicate();
12219 else
12220 FoundPred = ICI->getCmpPredicate();
12221
12222 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
12223 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
12224
12225 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
12226}
12227
12228bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12229 const SCEV *RHS, CmpPredicate FoundPred,
12230 const SCEV *FoundLHS, const SCEV *FoundRHS,
12231 const Instruction *CtxI) {
12232 // Balance the types.
12233 if (getTypeSizeInBits(LHS->getType()) <
12234 getTypeSizeInBits(FoundLHS->getType())) {
12235 // For unsigned and equality predicates, try to prove that both found
12236 // operands fit into narrow unsigned range. If so, try to prove facts in
12237 // narrow types.
12238 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
12239 !FoundRHS->getType()->isPointerTy()) {
12240 auto *NarrowType = LHS->getType();
12241 auto *WideType = FoundLHS->getType();
12242 auto BitWidth = getTypeSizeInBits(NarrowType);
12243 const SCEV *MaxValue = getZeroExtendExpr(
12245 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
12246 MaxValue) &&
12247 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
12248 MaxValue)) {
12249 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
12250 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
12251 // We cannot preserve samesign after truncation.
12252 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred.dropSameSign(),
12253 TruncFoundLHS, TruncFoundRHS, CtxI))
12254 return true;
12255 }
12256 }
12257
12258 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
12259 return false;
12260 if (CmpInst::isSigned(Pred)) {
12261 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
12262 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
12263 } else {
12264 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
12265 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
12266 }
12267 } else if (getTypeSizeInBits(LHS->getType()) >
12268 getTypeSizeInBits(FoundLHS->getType())) {
12269 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
12270 return false;
12271 if (CmpInst::isSigned(FoundPred)) {
12272 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
12273 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
12274 } else {
12275 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
12276 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
12277 }
12278 }
12279 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
12280 FoundRHS, CtxI);
12281}
12282
12283bool ScalarEvolution::isImpliedCondBalancedTypes(
12284 CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, CmpPredicate FoundPred,
12285 SCEVUse FoundLHS, SCEVUse FoundRHS, const Instruction *CtxI) {
12287 getTypeSizeInBits(FoundLHS->getType()) &&
12288 "Types should be balanced!");
12289 // Canonicalize the query to match the way instcombine will have
12290 // canonicalized the comparison.
12291 if (SimplifyICmpOperands(Pred, LHS, RHS))
12292 if (LHS == RHS)
12293 return CmpInst::isTrueWhenEqual(Pred);
12294 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
12295 if (FoundLHS == FoundRHS)
12296 return CmpInst::isFalseWhenEqual(FoundPred);
12297
12298 // Check to see if we can make the LHS or RHS match.
12299 if (LHS == FoundRHS || RHS == FoundLHS) {
12300 if (isa<SCEVConstant>(RHS)) {
12301 std::swap(FoundLHS, FoundRHS);
12302 FoundPred = ICmpInst::getSwappedCmpPredicate(FoundPred);
12303 } else {
12304 std::swap(LHS, RHS);
12306 }
12307 }
12308
12309 // Check whether the found predicate is the same as the desired predicate.
12310 if (auto P = CmpPredicate::getMatching(FoundPred, Pred))
12311 return isImpliedCondOperands(*P, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12312
12313 // Check whether swapping the found predicate makes it the same as the
12314 // desired predicate.
12315 if (auto P = CmpPredicate::getMatching(
12316 ICmpInst::getSwappedCmpPredicate(FoundPred), Pred)) {
12317 // We can write the implication
12318 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS
12319 // using one of the following ways:
12320 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS
12321 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS
12322 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS
12323 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS
12324 // Forms 1. and 2. require swapping the operands of one condition. Don't
12325 // do this if it would break canonical constant/addrec ordering.
12327 return isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P), RHS,
12328 LHS, FoundLHS, FoundRHS, CtxI);
12329 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
12330 return isImpliedCondOperands(*P, LHS, RHS, FoundRHS, FoundLHS, CtxI);
12331
12332 // There's no clear preference between forms 3. and 4., try both. Avoid
12333 // forming getNotSCEV of pointer values as the resulting subtract is
12334 // not legal.
12335 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() &&
12336 isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P),
12337 getNotSCEV(LHS), getNotSCEV(RHS), FoundLHS,
12338 FoundRHS, CtxI))
12339 return true;
12340
12341 if (!FoundLHS->getType()->isPointerTy() &&
12342 !FoundRHS->getType()->isPointerTy() &&
12343 isImpliedCondOperands(*P, LHS, RHS, getNotSCEV(FoundLHS),
12344 getNotSCEV(FoundRHS), CtxI))
12345 return true;
12346
12347 return false;
12348 }
12349
12350 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
12352 assert(P1 != P2 && "Handled earlier!");
12353 return CmpInst::isRelational(P2) &&
12355 };
12356 if (IsSignFlippedPredicate(Pred, FoundPred)) {
12357 // Unsigned comparison is the same as signed comparison when both the
12358 // operands are non-negative or negative.
12359 if (haveSameSign(FoundLHS, FoundRHS))
12360 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12361 // Create local copies that we can freely swap and canonicalize our
12362 // conditions to "le/lt".
12363 CmpPredicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
12364 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
12365 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
12366 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
12367 CanonicalPred = ICmpInst::getSwappedCmpPredicate(CanonicalPred);
12368 CanonicalFoundPred = ICmpInst::getSwappedCmpPredicate(CanonicalFoundPred);
12369 std::swap(CanonicalLHS, CanonicalRHS);
12370 std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
12371 }
12372 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
12373 "Must be!");
12374 assert((ICmpInst::isLT(CanonicalFoundPred) ||
12375 ICmpInst::isLE(CanonicalFoundPred)) &&
12376 "Must be!");
12377 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
12378 // Use implication:
12379 // x <u y && y >=s 0 --> x <s y.
12380 // If we can prove the left part, the right part is also proven.
12381 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
12382 CanonicalRHS, CanonicalFoundLHS,
12383 CanonicalFoundRHS);
12384 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
12385 // Use implication:
12386 // x <s y && y <s 0 --> x <u y.
12387 // If we can prove the left part, the right part is also proven.
12388 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
12389 CanonicalRHS, CanonicalFoundLHS,
12390 CanonicalFoundRHS);
12391 }
12392
12393 // Check if we can make progress by sharpening ranges.
12394 if (FoundPred == ICmpInst::ICMP_NE &&
12395 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
12396
12397 const SCEVConstant *C = nullptr;
12398 const SCEV *V = nullptr;
12399
12400 if (isa<SCEVConstant>(FoundLHS)) {
12401 C = cast<SCEVConstant>(FoundLHS);
12402 V = FoundRHS;
12403 } else {
12404 C = cast<SCEVConstant>(FoundRHS);
12405 V = FoundLHS;
12406 }
12407
12408 // The guarding predicate tells us that C != V. If the known range
12409 // of V is [C, t), we can sharpen the range to [C + 1, t). The
12410 // range we consider has to correspond to same signedness as the
12411 // predicate we're interested in folding.
12412
12413 APInt Min = ICmpInst::isSigned(Pred) ?
12415
12416 if (Min == C->getAPInt()) {
12417 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
12418 // This is true even if (Min + 1) wraps around -- in case of
12419 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
12420
12421 APInt SharperMin = Min + 1;
12422
12423 switch (Pred) {
12424 case ICmpInst::ICMP_SGE:
12425 case ICmpInst::ICMP_UGE:
12426 // We know V `Pred` SharperMin. If this implies LHS `Pred`
12427 // RHS, we're done.
12428 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
12429 CtxI))
12430 return true;
12431 [[fallthrough]];
12432
12433 case ICmpInst::ICMP_SGT:
12434 case ICmpInst::ICMP_UGT:
12435 // We know from the range information that (V `Pred` Min ||
12436 // V == Min). We know from the guarding condition that !(V
12437 // == Min). This gives us
12438 //
12439 // V `Pred` Min || V == Min && !(V == Min)
12440 // => V `Pred` Min
12441 //
12442 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
12443
12444 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
12445 return true;
12446 break;
12447
12448 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
12449 case ICmpInst::ICMP_SLE:
12450 case ICmpInst::ICMP_ULE:
12451 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12452 LHS, V, getConstant(SharperMin), CtxI))
12453 return true;
12454 [[fallthrough]];
12455
12456 case ICmpInst::ICMP_SLT:
12457 case ICmpInst::ICMP_ULT:
12458 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12459 LHS, V, getConstant(Min), CtxI))
12460 return true;
12461 break;
12462
12463 default:
12464 // No change
12465 break;
12466 }
12467 }
12468 }
12469
12470 // Check whether the actual condition is beyond sufficient.
12471 if (FoundPred == ICmpInst::ICMP_EQ)
12472 if (ICmpInst::isTrueWhenEqual(Pred))
12473 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12474 return true;
12475 if (Pred == ICmpInst::ICMP_NE)
12476 if (!ICmpInst::isTrueWhenEqual(FoundPred))
12477 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12478 return true;
12479
12480 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS))
12481 return true;
12482
12483 // Otherwise assume the worst.
12484 return false;
12485}
12486
12487bool ScalarEvolution::splitBinaryAdd(SCEVUse Expr, SCEVUse &L, SCEVUse &R,
12488 SCEV::NoWrapFlags &Flags) {
12489 if (!match(Expr, m_scev_Add(m_SCEV(L), m_SCEV(R))))
12490 return false;
12491
12492 Flags = cast<SCEVAddExpr>(Expr)->getNoWrapFlags();
12493 return true;
12494}
12495
12496std::optional<APInt>
12498 // We avoid subtracting expressions here because this function is usually
12499 // fairly deep in the call stack (i.e. is called many times).
12500
12501 unsigned BW = getTypeSizeInBits(More->getType());
12502 APInt Diff(BW, 0);
12503 APInt DiffMul(BW, 1);
12504 // Try various simplifications to reduce the difference to a constant. Limit
12505 // the number of allowed simplifications to keep compile-time low.
12506 for (unsigned I = 0; I < 8; ++I) {
12507 if (More == Less)
12508 return Diff;
12509
12510 // Reduce addrecs with identical steps to their start value.
12512 const auto *LAR = cast<SCEVAddRecExpr>(Less);
12513 const auto *MAR = cast<SCEVAddRecExpr>(More);
12514
12515 if (LAR->getLoop() != MAR->getLoop())
12516 return std::nullopt;
12517
12518 // We look at affine expressions only; not for correctness but to keep
12519 // getStepRecurrence cheap.
12520 if (!LAR->isAffine() || !MAR->isAffine())
12521 return std::nullopt;
12522
12523 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
12524 return std::nullopt;
12525
12526 Less = LAR->getStart();
12527 More = MAR->getStart();
12528 continue;
12529 }
12530
12531 // Try to match a common constant multiply.
12532 auto MatchConstMul =
12533 [](const SCEV *S) -> std::optional<std::pair<const SCEV *, APInt>> {
12534 const APInt *C;
12535 const SCEV *Op;
12536 if (match(S, m_scev_Mul(m_scev_APInt(C), m_SCEV(Op))))
12537 return {{Op, *C}};
12538 return std::nullopt;
12539 };
12540 if (auto MatchedMore = MatchConstMul(More)) {
12541 if (auto MatchedLess = MatchConstMul(Less)) {
12542 if (MatchedMore->second == MatchedLess->second) {
12543 More = MatchedMore->first;
12544 Less = MatchedLess->first;
12545 DiffMul *= MatchedMore->second;
12546 continue;
12547 }
12548 }
12549 }
12550
12551 // Try to cancel out common factors in two add expressions.
12553 auto Add = [&](const SCEV *S, int Mul) {
12554 if (auto *C = dyn_cast<SCEVConstant>(S)) {
12555 if (Mul == 1) {
12556 Diff += C->getAPInt() * DiffMul;
12557 } else {
12558 assert(Mul == -1);
12559 Diff -= C->getAPInt() * DiffMul;
12560 }
12561 } else
12562 Multiplicity[S] += Mul;
12563 };
12564 auto Decompose = [&](const SCEV *S, int Mul) {
12565 if (isa<SCEVAddExpr>(S)) {
12566 for (const SCEV *Op : S->operands())
12567 Add(Op, Mul);
12568 } else
12569 Add(S, Mul);
12570 };
12571 Decompose(More, 1);
12572 Decompose(Less, -1);
12573
12574 // Check whether all the non-constants cancel out, or reduce to new
12575 // More/Less values.
12576 const SCEV *NewMore = nullptr, *NewLess = nullptr;
12577 for (const auto &[S, Mul] : Multiplicity) {
12578 if (Mul == 0)
12579 continue;
12580 if (Mul == 1) {
12581 if (NewMore)
12582 return std::nullopt;
12583 NewMore = S;
12584 } else if (Mul == -1) {
12585 if (NewLess)
12586 return std::nullopt;
12587 NewLess = S;
12588 } else
12589 return std::nullopt;
12590 }
12591
12592 // Values stayed the same, no point in trying further.
12593 if (NewMore == More || NewLess == Less)
12594 return std::nullopt;
12595
12596 More = NewMore;
12597 Less = NewLess;
12598
12599 // Reduced to constant.
12600 if (!More && !Less)
12601 return Diff;
12602
12603 // Left with variable on only one side, bail out.
12604 if (!More || !Less)
12605 return std::nullopt;
12606 }
12607
12608 // Did not reduce to constant.
12609 return std::nullopt;
12610}
12611
12612bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
12613 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12614 const SCEV *FoundRHS, const Instruction *CtxI) {
12615 // Try to recognize the following pattern:
12616 //
12617 // FoundRHS = ...
12618 // ...
12619 // loop:
12620 // FoundLHS = {Start,+,W}
12621 // context_bb: // Basic block from the same loop
12622 // known(Pred, FoundLHS, FoundRHS)
12623 //
12624 // If some predicate is known in the context of a loop, it is also known on
12625 // each iteration of this loop, including the first iteration. Therefore, in
12626 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
12627 // prove the original pred using this fact.
12628 if (!CtxI)
12629 return false;
12630 const BasicBlock *ContextBB = CtxI->getParent();
12631 // Make sure AR varies in the context block.
12632 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
12633 const Loop *L = AR->getLoop();
12634 const auto *Latch = L->getLoopLatch();
12635 // Make sure that context belongs to the loop and executes on 1st iteration
12636 // (if it ever executes at all).
12637 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12638 return false;
12639 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
12640 return false;
12641 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
12642 }
12643
12644 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
12645 const Loop *L = AR->getLoop();
12646 const auto *Latch = L->getLoopLatch();
12647 // Make sure that context belongs to the loop and executes on 1st iteration
12648 // (if it ever executes at all).
12649 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12650 return false;
12651 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
12652 return false;
12653 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
12654 }
12655
12656 return false;
12657}
12658
12659bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(CmpPredicate Pred,
12660 const SCEV *LHS,
12661 const SCEV *RHS,
12662 const SCEV *FoundLHS,
12663 const SCEV *FoundRHS) {
12664 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
12665 return false;
12666
12667 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
12668 if (!AddRecLHS)
12669 return false;
12670
12671 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12672 if (!AddRecFoundLHS)
12673 return false;
12674
12675 // We'd like to let SCEV reason about control dependencies, so we constrain
12676 // both the inequalities to be about add recurrences on the same loop. This
12677 // way we can use isLoopEntryGuardedByCond later.
12678
12679 const Loop *L = AddRecFoundLHS->getLoop();
12680 if (L != AddRecLHS->getLoop())
12681 return false;
12682
12683 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
12684 //
12685 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
12686 // ... (2)
12687 //
12688 // Informal proof for (2), assuming (1) [*]:
12689 //
12690 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
12691 //
12692 // Then
12693 //
12694 // FoundLHS s< FoundRHS s< INT_MIN - C
12695 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
12696 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
12697 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
12698 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
12699 // <=> FoundLHS + C s< FoundRHS + C
12700 //
12701 // [*]: (1) can be proved by ruling out overflow.
12702 //
12703 // [**]: This can be proved by analyzing all the four possibilities:
12704 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
12705 // (A s>= 0, B s>= 0).
12706 //
12707 // Note:
12708 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
12709 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
12710 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
12711 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
12712 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
12713 // C)".
12714
12715 std::optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
12716 if (!LDiff)
12717 return false;
12718 std::optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
12719 if (!RDiff || *LDiff != *RDiff)
12720 return false;
12721
12722 if (LDiff->isMinValue())
12723 return true;
12724
12725 APInt FoundRHSLimit;
12726
12727 if (Pred == CmpInst::ICMP_ULT) {
12728 FoundRHSLimit = -(*RDiff);
12729 } else {
12730 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
12731 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
12732 }
12733
12734 // Try to prove (1) or (2), as needed.
12735 return isAvailableAtLoopEntry(FoundRHS, L) &&
12736 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
12737 getConstant(FoundRHSLimit));
12738}
12739
12740bool ScalarEvolution::isImpliedViaMerge(CmpPredicate Pred, const SCEV *LHS,
12741 const SCEV *RHS, const SCEV *FoundLHS,
12742 const SCEV *FoundRHS, unsigned Depth) {
12743 const PHINode *LPhi = nullptr, *RPhi = nullptr;
12744
12745 llvm::scope_exit ClearOnExit([&]() {
12746 if (LPhi) {
12747 bool Erased = PendingMerges.erase(LPhi);
12748 assert(Erased && "Failed to erase LPhi!");
12749 (void)Erased;
12750 }
12751 if (RPhi) {
12752 bool Erased = PendingMerges.erase(RPhi);
12753 assert(Erased && "Failed to erase RPhi!");
12754 (void)Erased;
12755 }
12756 });
12757
12758 // Find respective Phis and check that they are not being pending.
12759 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
12760 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
12761 if (!PendingMerges.insert(Phi).second)
12762 return false;
12763 LPhi = Phi;
12764 }
12765 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
12766 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
12767 // If we detect a loop of Phi nodes being processed by this method, for
12768 // example:
12769 //
12770 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
12771 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
12772 //
12773 // we don't want to deal with a case that complex, so return conservative
12774 // answer false.
12775 if (!PendingMerges.insert(Phi).second)
12776 return false;
12777 RPhi = Phi;
12778 }
12779
12780 // If none of LHS, RHS is a Phi, nothing to do here.
12781 if (!LPhi && !RPhi)
12782 return false;
12783
12784 // If there is a SCEVUnknown Phi we are interested in, make it left.
12785 if (!LPhi) {
12786 std::swap(LHS, RHS);
12787 std::swap(FoundLHS, FoundRHS);
12788 std::swap(LPhi, RPhi);
12790 }
12791
12792 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
12793 const BasicBlock *LBB = LPhi->getParent();
12794 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12795
12796 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
12797 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
12798 isImpliedCondOperandsViaRanges(Pred, S1, S2, Pred, FoundLHS, FoundRHS) ||
12799 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
12800 };
12801
12802 if (RPhi && RPhi->getParent() == LBB) {
12803 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
12804 // If we compare two Phis from the same block, and for each entry block
12805 // the predicate is true for incoming values from this block, then the
12806 // predicate is also true for the Phis.
12807 for (const BasicBlock *IncBB : predecessors(LBB)) {
12808 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12809 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
12810 if (!ProvedEasily(L, R))
12811 return false;
12812 }
12813 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
12814 // Case two: RHS is also a Phi from the same basic block, and it is an
12815 // AddRec. It means that there is a loop which has both AddRec and Unknown
12816 // PHIs, for it we can compare incoming values of AddRec from above the loop
12817 // and latch with their respective incoming values of LPhi.
12818 // TODO: Generalize to handle loops with many inputs in a header.
12819 if (LPhi->getNumIncomingValues() != 2) return false;
12820
12821 auto *RLoop = RAR->getLoop();
12822 auto *Predecessor = RLoop->getLoopPredecessor();
12823 assert(Predecessor && "Loop with AddRec with no predecessor?");
12824 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
12825 if (!ProvedEasily(L1, RAR->getStart()))
12826 return false;
12827 auto *Latch = RLoop->getLoopLatch();
12828 assert(Latch && "Loop with AddRec with no latch?");
12829 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
12830 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
12831 return false;
12832 } else {
12833 // In all other cases go over inputs of LHS and compare each of them to RHS,
12834 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
12835 // At this point RHS is either a non-Phi, or it is a Phi from some block
12836 // different from LBB.
12837 for (const BasicBlock *IncBB : predecessors(LBB)) {
12838 // Check that RHS is available in this block.
12839 if (!dominates(RHS, IncBB))
12840 return false;
12841 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12842 // Make sure L does not refer to a value from a potentially previous
12843 // iteration of a loop.
12844 if (!properlyDominates(L, LBB))
12845 return false;
12846 // Addrecs are considered to properly dominate their loop, so are missed
12847 // by the previous check. Discard any values that have computable
12848 // evolution in this loop.
12849 if (auto *Loop = LI.getLoopFor(LBB))
12850 if (hasComputableLoopEvolution(L, Loop))
12851 return false;
12852 if (!ProvedEasily(L, RHS))
12853 return false;
12854 }
12855 }
12856 return true;
12857}
12858
12859bool ScalarEvolution::isImpliedCondOperandsViaShift(CmpPredicate Pred,
12860 const SCEV *LHS,
12861 const SCEV *RHS,
12862 const SCEV *FoundLHS,
12863 const SCEV *FoundRHS) {
12864 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make
12865 // sure that we are dealing with same LHS.
12866 if (RHS == FoundRHS) {
12867 std::swap(LHS, RHS);
12868 std::swap(FoundLHS, FoundRHS);
12870 }
12871 if (LHS != FoundLHS)
12872 return false;
12873
12874 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
12875 if (!SUFoundRHS)
12876 return false;
12877
12878 Value *Shiftee, *ShiftValue;
12879
12880 using namespace PatternMatch;
12881 if (match(SUFoundRHS->getValue(),
12882 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
12883 auto *ShifteeS = getSCEV(Shiftee);
12884 // Prove one of the following:
12885 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
12886 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
12887 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12888 // ---> LHS <s RHS
12889 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12890 // ---> LHS <=s RHS
12891 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
12892 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
12893 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
12894 if (isKnownNonNegative(ShifteeS))
12895 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
12896 }
12897
12898 return false;
12899}
12900
12901bool ScalarEvolution::isImpliedCondOperandsViaMatchingDiff(
12902 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12903 const SCEV *FoundRHS) {
12904 // Only valid for equality predicates: (A == B) implies (C == D) when
12905 // the SCEV difference A - B equals C - D (they check the same
12906 // underlying relationship at every iteration).
12907 if (!ICmpInst::isEquality(Pred))
12908 return false;
12909
12910 // Restrict to cases involving loop recurrences - that's where this
12911 // pattern arises (correlated IV comparisons). This avoids calling
12912 // getMinusSCEV on arbitrary non-loop expressions.
12914 (!isa<SCEVAddRecExpr>(FoundLHS) && !isa<SCEVAddRecExpr>(FoundRHS)))
12915 return false;
12916
12917 // AddRecs from different loops can never produce matching differences.
12918 const SCEVAddRecExpr *QueryAddRec = dyn_cast<SCEVAddRecExpr>(LHS);
12919 if (!QueryAddRec)
12920 QueryAddRec = cast<SCEVAddRecExpr>(RHS);
12921 const SCEVAddRecExpr *FoundAddRec = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12922 if (!FoundAddRec)
12923 FoundAddRec = cast<SCEVAddRecExpr>(FoundRHS);
12924 if (QueryAddRec->getLoop() != FoundAddRec->getLoop())
12925 return false;
12926
12927 // If the strides differ, the differences can never match.
12928 if (QueryAddRec->getStepRecurrence(*this) !=
12929 FoundAddRec->getStepRecurrence(*this))
12930 return false;
12931
12932 // Compute differences. For pointer-typed operands sharing the same base,
12933 // getMinusSCEV strips the common base and returns an integer SCEV.
12934 // For example, {base,+,8} - (base+8*n) = {-8n,+,8}
12935 const SCEV *FoundDiff = getMinusSCEV(FoundLHS, FoundRHS);
12936 if (isa<SCEVCouldNotCompute>(FoundDiff))
12937 return false;
12938
12939 const SCEV *Diff = getMinusSCEV(LHS, RHS);
12940 if (isa<SCEVCouldNotCompute>(Diff))
12941 return false;
12942
12943 return Diff == FoundDiff;
12944}
12945
12946bool ScalarEvolution::isImpliedCondOperands(CmpPredicate Pred, const SCEV *LHS,
12947 const SCEV *RHS,
12948 const SCEV *FoundLHS,
12949 const SCEV *FoundRHS,
12950 const Instruction *CtxI) {
12951 return isImpliedCondOperandsViaRanges(Pred, LHS, RHS, Pred, FoundLHS,
12952 FoundRHS) ||
12953 isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS,
12954 FoundRHS) ||
12955 isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS) ||
12956 isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12957 CtxI) ||
12958 isImpliedCondOperandsViaMatchingDiff(Pred, LHS, RHS, FoundLHS,
12959 FoundRHS) ||
12960 isImpliedCondOperandsHelper(Pred, LHS, RHS, FoundLHS, FoundRHS);
12961}
12962
12963/// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
12964template <typename MinMaxExprType>
12965static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
12966 const SCEV *Candidate) {
12967 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12968 if (!MinMaxExpr)
12969 return false;
12970
12971 return is_contained(MinMaxExpr->operands(), Candidate);
12972}
12973
12975 CmpPredicate Pred, const SCEV *LHS,
12976 const SCEV *RHS) {
12977 // If both sides are affine addrecs for the same loop, with equal
12978 // steps, and we know the recurrences don't wrap, then we only
12979 // need to check the predicate on the starting values.
12980
12981 if (!ICmpInst::isRelational(Pred))
12982 return false;
12983
12984 const SCEV *LStart, *RStart, *Step;
12985 const Loop *L;
12986 if (!match(LHS,
12987 m_scev_AffineAddRec(m_SCEV(LStart), m_SCEV(Step), m_Loop(L))) ||
12989 m_SpecificLoop(L))))
12990 return false;
12995 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
12996 return false;
12997
12998 return SE.isKnownPredicate(Pred, LStart, RStart);
12999}
13000
13001/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
13002/// expression?
13004 const SCEV *LHS, const SCEV *RHS) {
13005 switch (Pred) {
13006 default:
13007 return false;
13008
13009 case ICmpInst::ICMP_SGE:
13010 std::swap(LHS, RHS);
13011 [[fallthrough]];
13012 case ICmpInst::ICMP_SLE:
13013 return
13014 // min(A, ...) <= A
13016 // A <= max(A, ...)
13018
13019 case ICmpInst::ICMP_UGE:
13020 std::swap(LHS, RHS);
13021 [[fallthrough]];
13022 case ICmpInst::ICMP_ULE:
13023 return
13024 // min(A, ...) <= A
13025 // FIXME: what about umin_seq?
13027 // A <= max(A, ...)
13029
13030 case ICmpInst::ICMP_UGT:
13031 std::swap(LHS, RHS);
13032 [[fallthrough]];
13033 case ICmpInst::ICMP_ULT:
13034 // umin(Ops) u<= each Op, so proving Op u< RHS for any Op proves
13035 // umin(Ops) u< RHS.
13036 //
13037 // Use computeConstantDifference instead of the more powerful
13038 // isKnownPredicate to keep this check cheap: isKnownPredicateViaMinOrMax
13039 // is called from isKnownViaNonRecursiveReasoning, so recursing into
13040 // the full predicate prover would be expensive.
13041 if (const auto *Min = dyn_cast<SCEVUMinExpr>(LHS)) {
13042 for (SCEVUse Op : Min->operands()) {
13043 std::optional<APInt> Diff = SE.computeConstantDifference(RHS, Op);
13044 // When Op and RHS share a common base differing by a
13045 // constant offset D (RHS - Op = D), Op u< RHS holds iff D != 0 and
13046 // RHS >= D (unsigned), i.e. the subtraction doesn't underflow.
13047 if (Diff && !Diff->isZero() && SE.getUnsignedRangeMin(RHS).uge(*Diff))
13048 return true;
13049 }
13050 }
13051 return false;
13052 }
13053
13054 llvm_unreachable("covered switch fell through?!");
13055}
13056
13057bool ScalarEvolution::isImpliedViaOperations(CmpPredicate Pred, const SCEV *LHS,
13058 const SCEV *RHS,
13059 const SCEV *FoundLHS,
13060 const SCEV *FoundRHS,
13061 unsigned Depth) {
13064 "LHS and RHS have different sizes?");
13065 assert(getTypeSizeInBits(FoundLHS->getType()) ==
13066 getTypeSizeInBits(FoundRHS->getType()) &&
13067 "FoundLHS and FoundRHS have different sizes?");
13068 // We want to avoid hurting the compile time with analysis of too big trees.
13070 return false;
13071
13072 // We only want to work with GT comparison so far.
13073 if (ICmpInst::isLT(Pred)) {
13075 std::swap(LHS, RHS);
13076 std::swap(FoundLHS, FoundRHS);
13077 }
13078
13080
13081 // For unsigned, try to reduce it to corresponding signed comparison.
13082 if (P == ICmpInst::ICMP_UGT)
13083 // We can replace unsigned predicate with its signed counterpart if all
13084 // involved values are non-negative.
13085 // TODO: We could have better support for unsigned.
13086 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
13087 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
13088 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
13089 // use this fact to prove that LHS and RHS are non-negative.
13090 const SCEV *MinusOne = getMinusOne(LHS->getType());
13091 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
13092 FoundRHS) &&
13093 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
13094 FoundRHS))
13096 }
13097
13098 if (P != ICmpInst::ICMP_SGT)
13099 return false;
13100
13101 auto GetOpFromSExt = [&](const SCEV *S) -> const SCEV * {
13102 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
13103 return Ext->getOperand();
13104 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
13105 // the constant in some cases.
13106 return S;
13107 };
13108
13109 // Acquire values from extensions.
13110 auto *OrigLHS = LHS;
13111 auto *OrigFoundLHS = FoundLHS;
13112 LHS = GetOpFromSExt(LHS);
13113 FoundLHS = GetOpFromSExt(FoundLHS);
13114
13115 // Is the SGT predicate can be proved trivially or using the found context.
13116 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
13117 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
13118 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
13119 FoundRHS, Depth + 1);
13120 };
13121
13122 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
13123 // We want to avoid creation of any new non-constant SCEV. Since we are
13124 // going to compare the operands to RHS, we should be certain that we don't
13125 // need any size extensions for this. So let's decline all cases when the
13126 // sizes of types of LHS and RHS do not match.
13127 // TODO: Maybe try to get RHS from sext to catch more cases?
13129 return false;
13130
13131 // Should not overflow.
13132 if (!LHSAddExpr->hasNoSignedWrap())
13133 return false;
13134
13135 SCEVUse LL = LHSAddExpr->getOperand(0);
13136 SCEVUse LR = LHSAddExpr->getOperand(1);
13137 auto *MinusOne = getMinusOne(RHS->getType());
13138
13139 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
13140 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
13141 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
13142 };
13143 // Try to prove the following rule:
13144 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
13145 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
13146 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
13147 return true;
13148 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
13149 Value *LL, *LR;
13150 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
13151
13152 using namespace llvm::PatternMatch;
13153
13154 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
13155 // Rules for division.
13156 // We are going to perform some comparisons with Denominator and its
13157 // derivative expressions. In general case, creating a SCEV for it may
13158 // lead to a complex analysis of the entire graph, and in particular it
13159 // can request trip count recalculation for the same loop. This would
13160 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
13161 // this, we only want to create SCEVs that are constants in this section.
13162 // So we bail if Denominator is not a constant.
13163 if (!isa<ConstantInt>(LR))
13164 return false;
13165
13166 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
13167
13168 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
13169 // then a SCEV for the numerator already exists and matches with FoundLHS.
13170 auto *Numerator = getExistingSCEV(LL);
13171 if (!Numerator || Numerator->getType() != FoundLHS->getType())
13172 return false;
13173
13174 // Make sure that the numerator matches with FoundLHS and the denominator
13175 // is positive.
13176 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
13177 return false;
13178
13179 auto *DTy = Denominator->getType();
13180 auto *FRHSTy = FoundRHS->getType();
13181 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
13182 // One of types is a pointer and another one is not. We cannot extend
13183 // them properly to a wider type, so let us just reject this case.
13184 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
13185 // to avoid this check.
13186 return false;
13187
13188 // Given that:
13189 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
13190 auto *WTy = getWiderType(DTy, FRHSTy);
13191 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
13192 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
13193
13194 // Try to prove the following rule:
13195 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
13196 // For example, given that FoundLHS > 2. It means that FoundLHS is at
13197 // least 3. If we divide it by Denominator < 4, we will have at least 1.
13198 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
13199 if (isKnownNonPositive(RHS) &&
13200 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
13201 return true;
13202
13203 // Try to prove the following rule:
13204 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
13205 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
13206 // If we divide it by Denominator > 2, then:
13207 // 1. If FoundLHS is negative, then the result is 0.
13208 // 2. If FoundLHS is non-negative, then the result is non-negative.
13209 // Anyways, the result is non-negative.
13210 auto *MinusOne = getMinusOne(WTy);
13211 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
13212 if (isKnownNegative(RHS) &&
13213 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
13214 return true;
13215 }
13216 }
13217
13218 // If our expression contained SCEVUnknown Phis, and we split it down and now
13219 // need to prove something for them, try to prove the predicate for every
13220 // possible incoming values of those Phis.
13221 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
13222 return true;
13223
13224 return false;
13225}
13226
13228 const SCEV *RHS) {
13229 // zext x u<= sext x, sext x s<= zext x
13230 const SCEV *Op;
13231 switch (Pred) {
13232 case ICmpInst::ICMP_SGE:
13233 std::swap(LHS, RHS);
13234 [[fallthrough]];
13235 case ICmpInst::ICMP_SLE: {
13236 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt.
13237 return match(LHS, m_scev_SExt(m_SCEV(Op))) &&
13239 }
13240 case ICmpInst::ICMP_UGE:
13241 std::swap(LHS, RHS);
13242 [[fallthrough]];
13243 case ICmpInst::ICMP_ULE: {
13244 // If operand >=u 0 then ZExt == SExt. If operand <u 0 then ZExt <u SExt.
13245 return match(LHS, m_scev_ZExt(m_SCEV(Op))) &&
13247 }
13248 default:
13249 return false;
13250 };
13251 llvm_unreachable("unhandled case");
13252}
13253
13254bool ScalarEvolution::isKnownViaNonRecursiveReasoning(CmpPredicate Pred,
13255 SCEVUse LHS,
13256 SCEVUse RHS) {
13257 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
13258 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
13259 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
13260 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
13261 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
13262}
13263
13264bool ScalarEvolution::isImpliedCondOperandsHelper(CmpPredicate Pred,
13265 const SCEV *LHS,
13266 const SCEV *RHS,
13267 const SCEV *FoundLHS,
13268 const SCEV *FoundRHS) {
13269 switch (Pred) {
13270 default:
13271 llvm_unreachable("Unexpected CmpPredicate value!");
13272 case ICmpInst::ICMP_EQ:
13273 case ICmpInst::ICMP_NE:
13274 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
13275 return true;
13276 break;
13277 case ICmpInst::ICMP_SLT:
13278 case ICmpInst::ICMP_SLE:
13279 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
13280 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
13281 return true;
13282 break;
13283 case ICmpInst::ICMP_SGT:
13284 case ICmpInst::ICMP_SGE:
13285 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
13286 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
13287 return true;
13288 break;
13289 case ICmpInst::ICMP_ULT:
13290 case ICmpInst::ICMP_ULE:
13291 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
13292 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
13293 return true;
13294 break;
13295 case ICmpInst::ICMP_UGT:
13296 case ICmpInst::ICMP_UGE:
13297 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
13298 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
13299 return true;
13300 break;
13301 }
13302
13303 // Maybe it can be proved via operations?
13304 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
13305 return true;
13306
13307 return false;
13308}
13309
13310bool ScalarEvolution::isImpliedCondOperandsViaRanges(
13311 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, CmpPredicate FoundPred,
13312 const SCEV *FoundLHS, const SCEV *FoundRHS) {
13313 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
13314 // The restriction on `FoundRHS` be lifted easily -- it exists only to
13315 // reduce the compile time impact of this optimization.
13316 return false;
13317
13318 std::optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
13319 if (!Addend)
13320 return false;
13321
13322 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
13323
13324 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
13325 // antecedent "`FoundLHS` `FoundPred` `FoundRHS`".
13326 ConstantRange FoundLHSRange =
13327 ConstantRange::makeExactICmpRegion(FoundPred, ConstFoundRHS);
13328
13329 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
13330 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
13331
13332 // We can also compute the range of values for `LHS` that satisfy the
13333 // consequent, "`LHS` `Pred` `RHS`":
13334 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
13335 // The antecedent implies the consequent if every value of `LHS` that
13336 // satisfies the antecedent also satisfies the consequent.
13337 return LHSRange.icmp(Pred, ConstRHS);
13338}
13339
13340bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
13341 bool IsSigned) {
13342 assert(isKnownPositive(Stride) && "Positive stride expected!");
13343
13344 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13345 const SCEV *One = getOne(Stride->getType());
13346
13347 if (IsSigned) {
13348 APInt MaxRHS = getSignedRangeMax(RHS);
13349 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
13350 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13351
13352 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
13353 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
13354 }
13355
13356 APInt MaxRHS = getUnsignedRangeMax(RHS);
13357 APInt MaxValue = APInt::getMaxValue(BitWidth);
13358 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13359
13360 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
13361 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
13362}
13363
13364bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
13365 bool IsSigned) {
13366
13367 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13368 const SCEV *One = getOne(Stride->getType());
13369
13370 if (IsSigned) {
13371 APInt MinRHS = getSignedRangeMin(RHS);
13372 APInt MinValue = APInt::getSignedMinValue(BitWidth);
13373 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13374
13375 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
13376 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
13377 }
13378
13379 APInt MinRHS = getUnsignedRangeMin(RHS);
13380 APInt MinValue = APInt::getMinValue(BitWidth);
13381 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13382
13383 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
13384 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
13385}
13386
13388 // umin(N, 1) + floor((N - umin(N, 1)) / D)
13389 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
13390 // expression fixes the case of N=0.
13391 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
13392 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
13393 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
13394}
13395
13396const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
13397 const SCEV *Stride,
13398 const SCEV *End,
13399 unsigned BitWidth,
13400 bool IsSigned) {
13401 // The logic in this function assumes we can represent a positive stride.
13402 // If we can't, the backedge-taken count must be zero.
13403 if (IsSigned && BitWidth == 1)
13404 return getZero(Stride->getType());
13405
13406 // This code below only been closely audited for negative strides in the
13407 // unsigned comparison case, it may be correct for signed comparison, but
13408 // that needs to be established.
13409 if (IsSigned && isKnownNegative(Stride))
13410 return getCouldNotCompute();
13411
13412 // Calculate the maximum backedge count based on the range of values
13413 // permitted by Start, End, and Stride.
13414 APInt MinStart =
13415 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
13416
13417 APInt MinStride =
13418 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
13419
13420 // We assume either the stride is positive, or the backedge-taken count
13421 // is zero. So force StrideForMaxBECount to be at least one.
13422 APInt One(BitWidth, 1);
13423 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
13424 : APIntOps::umax(One, MinStride);
13425
13426 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
13427 : APInt::getMaxValue(BitWidth);
13428 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
13429
13430 // Although End can be a MAX expression we estimate MaxEnd considering only
13431 // the case End = RHS of the loop termination condition. This is safe because
13432 // in the other case (End - Start) is zero, leading to a zero maximum backedge
13433 // taken count.
13434 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
13435 : APIntOps::umin(getUnsignedRangeMax(End), Limit);
13436
13437 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
13438 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
13439 : APIntOps::umax(MaxEnd, MinStart);
13440
13441 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */,
13442 getConstant(StrideForMaxBECount) /* Step */);
13443}
13444
13446ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
13447 const Loop *L, bool IsSigned,
13448 bool ControlsOnlyExit, bool AllowPredicates) {
13450
13452 bool PredicatedIV = false;
13453 if (!IV) {
13454 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
13455 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
13456 if (AR && AR->getLoop() == L && AR->isAffine()) {
13457 auto canProveNUW = [&]() {
13458 // We can use the comparison to infer no-wrap flags only if it fully
13459 // controls the loop exit.
13460 if (!ControlsOnlyExit)
13461 return false;
13462
13463 if (!isLoopInvariant(RHS, L))
13464 return false;
13465
13466 if (!isKnownNonZero(AR->getStepRecurrence(*this)))
13467 // We need the sequence defined by AR to strictly increase in the
13468 // unsigned integer domain for the logic below to hold.
13469 return false;
13470
13471 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
13472 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
13473 // If RHS <=u Limit, then there must exist a value V in the sequence
13474 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
13475 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned
13476 // overflow occurs. This limit also implies that a signed comparison
13477 // (in the wide bitwidth) is equivalent to an unsigned comparison as
13478 // the high bits on both sides must be zero.
13479 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
13480 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
13481 Limit = Limit.zext(OuterBitWidth);
13482 return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit);
13483 };
13484 auto Flags = AR->getNoWrapFlags();
13485 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
13486 Flags = setFlags(Flags, SCEV::FlagNUW);
13487
13488 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
13489 if (AR->hasNoUnsignedWrap()) {
13490 // Emulate what getZeroExtendExpr would have done during construction
13491 // if we'd been able to infer the fact just above at that time.
13492 const SCEV *Step = AR->getStepRecurrence(*this);
13493 Type *Ty = ZExt->getType();
13494 auto *S = getAddRecExpr(
13496 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
13498 }
13499 }
13500 }
13501 }
13502
13503
13504 if (!IV && AllowPredicates) {
13505 // Try to make this an AddRec using runtime tests, in the first X
13506 // iterations of this loop, where X is the SCEV expression found by the
13507 // algorithm below.
13508 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13509 PredicatedIV = true;
13510 }
13511
13512 // Avoid weird loops
13513 if (!IV || IV->getLoop() != L || !IV->isAffine())
13514 return getCouldNotCompute();
13515
13516 // A precondition of this method is that the condition being analyzed
13517 // reaches an exiting branch which dominates the latch. Given that, we can
13518 // assume that an increment which violates the nowrap specification and
13519 // produces poison must cause undefined behavior when the resulting poison
13520 // value is branched upon and thus we can conclude that the backedge is
13521 // taken no more often than would be required to produce that poison value.
13522 // Note that a well defined loop can exit on the iteration which violates
13523 // the nowrap specification if there is another exit (either explicit or
13524 // implicit/exceptional) which causes the loop to execute before the
13525 // exiting instruction we're analyzing would trigger UB.
13526 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13527 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13529
13530 const SCEV *Stride = IV->getStepRecurrence(*this);
13531
13532 bool PositiveStride = isKnownPositive(Stride);
13533
13534 // Avoid negative or zero stride values.
13535 if (!PositiveStride) {
13536 // We can compute the correct backedge taken count for loops with unknown
13537 // strides if we can prove that the loop is not an infinite loop with side
13538 // effects. Here's the loop structure we are trying to handle -
13539 //
13540 // i = start
13541 // do {
13542 // A[i] = i;
13543 // i += s;
13544 // } while (i < end);
13545 //
13546 // The backedge taken count for such loops is evaluated as -
13547 // (max(end, start + stride) - start - 1) /u stride
13548 //
13549 // The additional preconditions that we need to check to prove correctness
13550 // of the above formula is as follows -
13551 //
13552 // a) IV is either nuw or nsw depending upon signedness (indicated by the
13553 // NoWrap flag).
13554 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13555 // no side effects within the loop)
13556 // c) loop has a single static exit (with no abnormal exits)
13557 //
13558 // Precondition a) implies that if the stride is negative, this is a single
13559 // trip loop. The backedge taken count formula reduces to zero in this case.
13560 //
13561 // Precondition b) and c) combine to imply that if rhs is invariant in L,
13562 // then a zero stride means the backedge can't be taken without executing
13563 // undefined behavior.
13564 //
13565 // The positive stride case is the same as isKnownPositive(Stride) returning
13566 // true (original behavior of the function).
13567 //
13568 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
13570 return getCouldNotCompute();
13571
13572 if (!isKnownNonZero(Stride)) {
13573 // If we have a step of zero, and RHS isn't invariant in L, we don't know
13574 // if it might eventually be greater than start and if so, on which
13575 // iteration. We can't even produce a useful upper bound.
13576 if (!isLoopInvariant(RHS, L))
13577 return getCouldNotCompute();
13578
13579 // We allow a potentially zero stride, but we need to divide by stride
13580 // below. Since the loop can't be infinite and this check must control
13581 // the sole exit, we can infer the exit must be taken on the first
13582 // iteration (e.g. backedge count = 0) if the stride is zero. Given that,
13583 // we know the numerator in the divides below must be zero, so we can
13584 // pick an arbitrary non-zero value for the denominator (e.g. stride)
13585 // and produce the right result.
13586 // FIXME: Handle the case where Stride is poison?
13587 auto wouldZeroStrideBeUB = [&]() {
13588 // Proof by contradiction. Suppose the stride were zero. If we can
13589 // prove that the backedge *is* taken on the first iteration, then since
13590 // we know this condition controls the sole exit, we must have an
13591 // infinite loop. We can't have a (well defined) infinite loop per
13592 // check just above.
13593 // Note: The (Start - Stride) term is used to get the start' term from
13594 // (start' + stride,+,stride). Remember that we only care about the
13595 // result of this expression when stride == 0 at runtime.
13596 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
13597 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
13598 };
13599 if (!wouldZeroStrideBeUB()) {
13600 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13601 }
13602 }
13603 } else if (!NoWrap) {
13604 // Avoid proven overflow cases: this will ensure that the backedge taken
13605 // count will not generate any unsigned overflow.
13606 if (canIVOverflowOnLT(RHS, Stride, IsSigned))
13607 return getCouldNotCompute();
13608 }
13609
13610 // On all paths just preceeding, we established the following invariant:
13611 // IV can be assumed not to overflow up to and including the exiting
13612 // iteration. We proved this in one of two ways:
13613 // 1) We can show overflow doesn't occur before the exiting iteration
13614 // 1a) canIVOverflowOnLT, and b) step of one
13615 // 2) We can show that if overflow occurs, the loop must execute UB
13616 // before any possible exit.
13617 // Note that we have not yet proved RHS invariant (in general).
13618
13619 const SCEV *Start = IV->getStart();
13620
13621 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
13622 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
13623 // Use integer-typed versions for actual computation; we can't subtract
13624 // pointers in general.
13625 const SCEV *OrigStart = Start;
13626 const SCEV *OrigRHS = RHS;
13627 if (Start->getType()->isPointerTy()) {
13629 if (isa<SCEVCouldNotCompute>(Start))
13630 return Start;
13631 }
13632 if (RHS->getType()->isPointerTy()) {
13635 return RHS;
13636 }
13637
13638 const SCEV *End = nullptr, *BECount = nullptr,
13639 *BECountIfBackedgeTaken = nullptr;
13640 if (!isLoopInvariant(RHS, L)) {
13641 const auto *RHSAddRec = dyn_cast<SCEVAddRecExpr>(RHS);
13642 if (PositiveStride && RHSAddRec != nullptr && RHSAddRec->getLoop() == L &&
13643 any(RHSAddRec->getNoWrapFlags())) {
13644 // The structure of loop we are trying to calculate backedge count of:
13645 //
13646 // left = left_start
13647 // right = right_start
13648 //
13649 // while(left < right){
13650 // ... do something here ...
13651 // left += s1; // stride of left is s1 (s1 > 0)
13652 // right += s2; // stride of right is s2 (s2 < 0)
13653 // }
13654 //
13655
13656 const SCEV *RHSStart = RHSAddRec->getStart();
13657 const SCEV *RHSStride = RHSAddRec->getStepRecurrence(*this);
13658
13659 // If Stride - RHSStride is positive and does not overflow, we can write
13660 // backedge count as ->
13661 // ceil((End - Start) /u (Stride - RHSStride))
13662 // Where, End = max(RHSStart, Start)
13663
13664 // Check if RHSStride < 0 and Stride - RHSStride will not overflow.
13665 if (isKnownNegative(RHSStride) &&
13666 willNotOverflow(Instruction::Sub, /*Signed=*/true, Stride,
13667 RHSStride)) {
13668
13669 const SCEV *Denominator = getMinusSCEV(Stride, RHSStride);
13670 if (isKnownPositive(Denominator)) {
13671 End = IsSigned ? getSMaxExpr(RHSStart, Start)
13672 : getUMaxExpr(RHSStart, Start);
13673
13674 // We can do this because End >= Start, as End = max(RHSStart, Start)
13675 const SCEV *Delta = getMinusSCEV(End, Start);
13676
13677 BECount = getUDivCeilSCEV(Delta, Denominator);
13678 BECountIfBackedgeTaken =
13679 getUDivCeilSCEV(getMinusSCEV(RHSStart, Start), Denominator);
13680 }
13681 }
13682 }
13683 if (BECount == nullptr) {
13684 // If we cannot calculate ExactBECount, we can calculate the MaxBECount,
13685 // given the start, stride and max value for the end bound of the
13686 // loop (RHS), and the fact that IV does not overflow (which is
13687 // checked above).
13688 const SCEV *MaxBECount = computeMaxBECountForLT(
13689 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
13690 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
13691 MaxBECount, false /*MaxOrZero*/, Predicates);
13692 }
13693 } else {
13694 // We use the expression (max(End,Start)-Start)/Stride to describe the
13695 // backedge count, as if the backedge is taken at least once
13696 // max(End,Start) is End and so the result is as above, and if not
13697 // max(End,Start) is Start so we get a backedge count of zero.
13698 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
13699 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!");
13700 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
13701 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
13702 // Can we prove (max(RHS,Start) > Start - Stride?
13703 if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) &&
13704 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
13705 // In this case, we can use a refined formula for computing backedge
13706 // taken count. The general formula remains:
13707 // "End-Start /uceiling Stride" where "End = max(RHS,Start)"
13708 // We want to use the alternate formula:
13709 // "((End - 1) - (Start - Stride)) /u Stride"
13710 // Let's do a quick case analysis to show these are equivalent under
13711 // our precondition that max(RHS,Start) > Start - Stride.
13712 // * For RHS <= Start, the backedge-taken count must be zero.
13713 // "((End - 1) - (Start - Stride)) /u Stride" reduces to
13714 // "((Start - 1) - (Start - Stride)) /u Stride" which simplies to
13715 // "Stride - 1 /u Stride" which is indeed zero for all non-zero values
13716 // of Stride. For 0 stride, we've use umin(1,Stride) above,
13717 // reducing this to the stride of 1 case.
13718 // * For RHS >= Start, the backedge count must be "RHS-Start /uceil
13719 // Stride".
13720 // "((End - 1) - (Start - Stride)) /u Stride" reduces to
13721 // "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to
13722 // "((RHS - (Start - Stride) - 1) /u Stride".
13723 // Our preconditions trivially imply no overflow in that form.
13724 const SCEV *MinusOne = getMinusOne(Stride->getType());
13725 const SCEV *Numerator =
13726 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
13727 BECount = getUDivExpr(Numerator, Stride);
13728 }
13729
13730 if (!BECount) {
13731 auto canProveRHSGreaterThanEqualStart = [&]() {
13732 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
13733 const SCEV *GuardedRHS = applyLoopGuards(OrigRHS, L);
13734 const SCEV *GuardedStart = applyLoopGuards(OrigStart, L);
13735
13736 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart) ||
13737 isKnownPredicate(CondGE, GuardedRHS, GuardedStart))
13738 return true;
13739
13740 // (RHS > Start - 1) implies RHS >= Start.
13741 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
13742 // "Start - 1" doesn't overflow.
13743 // * For signed comparison, if Start - 1 does overflow, it's equal
13744 // to INT_MAX, and "RHS >s INT_MAX" is trivially false.
13745 // * For unsigned comparison, if Start - 1 does overflow, it's equal
13746 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
13747 //
13748 // FIXME: Should isLoopEntryGuardedByCond do this for us?
13749 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13750 auto *StartMinusOne =
13751 getAddExpr(OrigStart, getMinusOne(OrigStart->getType()));
13752 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
13753 };
13754
13755 // If we know that RHS >= Start in the context of loop, then we know
13756 // that max(RHS, Start) = RHS at this point.
13757 if (canProveRHSGreaterThanEqualStart()) {
13758 End = RHS;
13759 } else {
13760 // If RHS < Start, the backedge will be taken zero times. So in
13761 // general, we can write the backedge-taken count as:
13762 //
13763 // RHS >= Start ? ceil(RHS - Start) / Stride : 0
13764 //
13765 // We convert it to the following to make it more convenient for SCEV:
13766 //
13767 // ceil(max(RHS, Start) - Start) / Stride
13768 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
13769
13770 // See what would happen if we assume the backedge is taken. This is
13771 // used to compute MaxBECount.
13772 BECountIfBackedgeTaken =
13773 getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
13774 }
13775
13776 // At this point, we know:
13777 //
13778 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
13779 // 2. The index variable doesn't overflow.
13780 //
13781 // Therefore, we know N exists such that
13782 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
13783 // doesn't overflow.
13784 //
13785 // Using this information, try to prove whether the addition in
13786 // "(Start - End) + (Stride - 1)" has unsigned overflow.
13787 const SCEV *One = getOne(Stride->getType());
13788 bool MayAddOverflow = [&] {
13789 if (isKnownToBeAPowerOfTwo(Stride)) {
13790 // Suppose Stride is a power of two, and Start/End are unsigned
13791 // integers. Let UMAX be the largest representable unsigned
13792 // integer.
13793 //
13794 // By the preconditions of this function, we know
13795 // "(Start + Stride * N) >= End", and this doesn't overflow.
13796 // As a formula:
13797 //
13798 // End <= (Start + Stride * N) <= UMAX
13799 //
13800 // Subtracting Start from all the terms:
13801 //
13802 // End - Start <= Stride * N <= UMAX - Start
13803 //
13804 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore:
13805 //
13806 // End - Start <= Stride * N <= UMAX
13807 //
13808 // Stride * N is a multiple of Stride. Therefore,
13809 //
13810 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
13811 //
13812 // Since Stride is a power of two, UMAX + 1 is divisible by
13813 // Stride. Therefore, UMAX mod Stride == Stride - 1. So we can
13814 // write:
13815 //
13816 // End - Start <= Stride * N <= UMAX - Stride - 1
13817 //
13818 // Dropping the middle term:
13819 //
13820 // End - Start <= UMAX - Stride - 1
13821 //
13822 // Adding Stride - 1 to both sides:
13823 //
13824 // (End - Start) + (Stride - 1) <= UMAX
13825 //
13826 // In other words, the addition doesn't have unsigned overflow.
13827 //
13828 // A similar proof works if we treat Start/End as signed values.
13829 // Just rewrite steps before "End - Start <= Stride * N <= UMAX"
13830 // to use signed max instead of unsigned max. Note that we're
13831 // trying to prove a lack of unsigned overflow in either case.
13832 return false;
13833 }
13834 if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
13835 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End
13836 // - 1. If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1
13837 // <u End. If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End -
13838 // 1 <s End.
13839 //
13840 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 ==
13841 // End.
13842 return false;
13843 }
13844 return true;
13845 }();
13846
13847 const SCEV *Delta = getMinusSCEV(End, Start);
13848 if (!MayAddOverflow) {
13849 // floor((D + (S - 1)) / S)
13850 // We prefer this formulation if it's legal because it's fewer
13851 // operations.
13852 BECount =
13853 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13854 } else {
13855 BECount = getUDivCeilSCEV(Delta, Stride);
13856 }
13857 }
13858 }
13859
13860 const SCEV *ConstantMaxBECount;
13861 bool MaxOrZero = false;
13862 if (isa<SCEVConstant>(BECount)) {
13863 ConstantMaxBECount = BECount;
13864 } else if (BECountIfBackedgeTaken &&
13865 isa<SCEVConstant>(BECountIfBackedgeTaken)) {
13866 // If we know exactly how many times the backedge will be taken if it's
13867 // taken at least once, then the backedge count will either be that or
13868 // zero.
13869 ConstantMaxBECount = BECountIfBackedgeTaken;
13870 MaxOrZero = true;
13871 } else {
13872 ConstantMaxBECount = computeMaxBECountForLT(
13873 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
13874 }
13875
13876 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
13877 !isa<SCEVCouldNotCompute>(BECount))
13878 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
13879
13880 const SCEV *SymbolicMaxBECount =
13881 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13882 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
13883 Predicates);
13884}
13885
13886ScalarEvolution::ExitLimit ScalarEvolution::howManyGreaterThans(
13887 const SCEV *LHS, const SCEV *RHS, const Loop *L, bool IsSigned,
13888 bool ControlsOnlyExit, bool AllowPredicates) {
13890 // We handle only IV > Invariant
13891 if (!isLoopInvariant(RHS, L))
13892 return getCouldNotCompute();
13893
13894 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
13895 if (!IV && AllowPredicates)
13896 // Try to make this an AddRec using runtime tests, in the first X
13897 // iterations of this loop, where X is the SCEV expression found by the
13898 // algorithm below.
13899 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13900
13901 // Avoid weird loops
13902 if (!IV || IV->getLoop() != L || !IV->isAffine())
13903 return getCouldNotCompute();
13904
13905 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13906 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13908
13909 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
13910
13911 // Avoid negative or zero stride values
13912 if (!isKnownPositive(Stride))
13913 return getCouldNotCompute();
13914
13915 // Avoid proven overflow cases: this will ensure that the backedge taken count
13916 // will not generate any unsigned overflow. Relaxed no-overflow conditions
13917 // exploit NoWrapFlags, allowing to optimize in presence of undefined
13918 // behaviors like the case of C language.
13919 if (!Stride->isOne() && !NoWrap)
13920 if (canIVOverflowOnGT(RHS, Stride, IsSigned))
13921 return getCouldNotCompute();
13922
13923 const SCEV *Start = IV->getStart();
13924 const SCEV *End = RHS;
13925 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
13926 // If we know that Start >= RHS in the context of loop, then we know that
13927 // min(RHS, Start) = RHS at this point.
13929 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
13930 End = RHS;
13931 else
13932 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
13933 }
13934
13935 if (Start->getType()->isPointerTy()) {
13937 if (isa<SCEVCouldNotCompute>(Start))
13938 return Start;
13939 }
13940 if (End->getType()->isPointerTy()) {
13941 End = getLosslessPtrToIntExpr(End);
13942 if (isa<SCEVCouldNotCompute>(End))
13943 return End;
13944 }
13945
13946 // Compute ((Start - End) + (Stride - 1)) / Stride.
13947 // FIXME: This can overflow. Holding off on fixing this for now;
13948 // howManyGreaterThans will hopefully be gone soon.
13949 const SCEV *One = getOne(Stride->getType());
13950 const SCEV *BECount = getUDivExpr(
13951 getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride);
13952
13953 APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
13955
13956 APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
13957 : getUnsignedRangeMin(Stride);
13958
13959 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
13960 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
13961 : APInt::getMinValue(BitWidth) + (MinStride - 1);
13962
13963 // Although End can be a MIN expression we estimate MinEnd considering only
13964 // the case End = RHS. This is safe because in the other case (Start - End)
13965 // is zero, leading to a zero maximum backedge taken count.
13966 APInt MinEnd =
13967 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
13968 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
13969
13970 const SCEV *ConstantMaxBECount =
13971 isa<SCEVConstant>(BECount)
13972 ? BECount
13973 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd),
13974 getConstant(MinStride));
13975
13976 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount))
13977 ConstantMaxBECount = BECount;
13978 const SCEV *SymbolicMaxBECount =
13979 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13980
13981 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
13982 Predicates);
13983}
13984
13986 ScalarEvolution &SE) const {
13987 if (Range.isFullSet()) // Infinite loop.
13988 return SE.getCouldNotCompute();
13989
13990 // If the start is a non-zero constant, shift the range to simplify things.
13991 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
13992 if (!SC->getValue()->isZero()) {
13994 Operands[0] = SE.getZero(SC->getType());
13995 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
13997 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
13998 return ShiftedAddRec->getNumIterationsInRange(
13999 Range.subtract(SC->getAPInt()), SE);
14000 // This is strange and shouldn't happen.
14001 return SE.getCouldNotCompute();
14002 }
14003
14004 // The only time we can solve this is when we have all constant indices.
14005 // Otherwise, we cannot determine the overflow conditions.
14006 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
14007 return SE.getCouldNotCompute();
14008
14009 // Okay at this point we know that all elements of the chrec are constants and
14010 // that the start element is zero.
14011
14012 // First check to see if the range contains zero. If not, the first
14013 // iteration exits.
14014 unsigned BitWidth = SE.getTypeSizeInBits(getType());
14015 if (!Range.contains(APInt(BitWidth, 0)))
14016 return SE.getZero(getType());
14017
14018 if (isAffine()) {
14019 // If this is an affine expression then we have this situation:
14020 // Solve {0,+,A} in Range === Ax in Range
14021
14022 // We know that zero is in the range. If A is positive then we know that
14023 // the upper value of the range must be the first possible exit value.
14024 // If A is negative then the lower of the range is the last possible loop
14025 // value. Also note that we already checked for a full range.
14026 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
14027 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
14028
14029 // The exit value should be (End+A)/A.
14030 APInt ExitVal = (End + A).udiv(A);
14031 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
14032
14033 // Evaluate at the exit value. If we really did fall out of the valid
14034 // range, then we computed our trip count, otherwise wrap around or other
14035 // things must have happened.
14036 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
14037 if (Range.contains(Val->getValue()))
14038 return SE.getCouldNotCompute(); // Something strange happened
14039
14040 // Ensure that the previous value is in the range.
14041 assert(Range.contains(
14043 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
14044 "Linear scev computation is off in a bad way!");
14045 return SE.getConstant(ExitValue);
14046 }
14047
14048 if (isQuadratic()) {
14049 if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
14050 return SE.getConstant(*S);
14051 }
14052
14053 return SE.getCouldNotCompute();
14054}
14055
14056const SCEVAddRecExpr *
14058 assert(getNumOperands() > 1 && "AddRec with zero step?");
14059 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
14060 // but in this case we cannot guarantee that the value returned will be an
14061 // AddRec because SCEV does not have a fixed point where it stops
14062 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
14063 // may happen if we reach arithmetic depth limit while simplifying. So we
14064 // construct the returned value explicitly.
14066 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
14067 // (this + Step) is {A+B,+,B+C,+...,+,N}.
14068 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
14069 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
14070 // We know that the last operand is not a constant zero (otherwise it would
14071 // have been popped out earlier). This guarantees us that if the result has
14072 // the same last operand, then it will also not be popped out, meaning that
14073 // the returned value will be an AddRec.
14074 const SCEV *Last = getOperand(getNumOperands() - 1);
14075 assert(!Last->isZero() && "Recurrency with zero step?");
14076 Ops.push_back(Last);
14079}
14080
14081// Return true when S contains at least an undef value.
14083 return SCEVExprContains(
14084 S, [](const SCEV *S) { return match(S, m_scev_UndefOrPoison()); });
14085}
14086
14087// Return true when S contains a value that is a nullptr.
14089 return SCEVExprContains(S, [](const SCEV *S) {
14090 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
14091 return SU->getValue() == nullptr;
14092 return false;
14093 });
14094}
14095
14096/// Return the size of an element read or written by Inst.
14098 Type *Ty;
14099 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
14100 Ty = Store->getValueOperand()->getType();
14101 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
14102 Ty = Load->getType();
14103 else
14104 return nullptr;
14105
14107 return getSizeOfExpr(ETy, Ty);
14108}
14109
14110//===----------------------------------------------------------------------===//
14111// SCEVCallbackVH Class Implementation
14112//===----------------------------------------------------------------------===//
14113
14115 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14116 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
14117 SE->ConstantEvolutionLoopExitValue.erase(PN);
14118 SE->eraseValueFromMap(getValPtr());
14119 // this now dangles!
14120}
14121
14122void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
14123 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14124
14125 // Forget all the expressions associated with users of the old value,
14126 // so that future queries will recompute the expressions using the new
14127 // value.
14128 SE->forgetValue(getValPtr());
14129 // this now dangles!
14130}
14131
14132ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
14133 : CallbackVH(V), SE(se) {}
14134
14135//===----------------------------------------------------------------------===//
14136// ScalarEvolution Class Implementation
14137//===----------------------------------------------------------------------===//
14138
14141 LoopInfo &LI)
14142 : F(F), DL(F.getDataLayout()), TLI(TLI), AC(AC), DT(DT), LI(LI),
14143 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
14144 LoopDispositions(64), BlockDispositions(64) {
14145 // To use guards for proving predicates, we need to scan every instruction in
14146 // relevant basic blocks, and not just terminators. Doing this is a waste of
14147 // time if the IR does not actually contain any calls to
14148 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
14149 //
14150 // This pessimizes the case where a pass that preserves ScalarEvolution wants
14151 // to _add_ guards to the module when there weren't any before, and wants
14152 // ScalarEvolution to optimize based on those guards. For now we prefer to be
14153 // efficient in lieu of being smart in that rather obscure case.
14154
14155 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
14156 F.getParent(), Intrinsic::experimental_guard);
14157 HasGuards = GuardDecl && !GuardDecl->use_empty();
14158}
14159
14161 : F(Arg.F), DL(Arg.DL), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC),
14162 DT(Arg.DT), LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
14163 ValueExprMap(std::move(Arg.ValueExprMap)),
14164 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
14165 PendingMerges(std::move(Arg.PendingMerges)),
14166 ConstantMultipleCache(std::move(Arg.ConstantMultipleCache)),
14167 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
14168 PredicatedBackedgeTakenCounts(
14169 std::move(Arg.PredicatedBackedgeTakenCounts)),
14170 BECountUsers(std::move(Arg.BECountUsers)),
14171 ConstantEvolutionLoopExitValue(
14172 std::move(Arg.ConstantEvolutionLoopExitValue)),
14173 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
14174 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
14175 LoopDispositions(std::move(Arg.LoopDispositions)),
14176 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
14177 BlockDispositions(std::move(Arg.BlockDispositions)),
14178 SCEVUsers(std::move(Arg.SCEVUsers)),
14179 UnsignedRanges(std::move(Arg.UnsignedRanges)),
14180 SignedRanges(std::move(Arg.SignedRanges)),
14181 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
14182 UniquePreds(std::move(Arg.UniquePreds)),
14183 SCEVAllocator(std::move(Arg.SCEVAllocator)),
14184 LoopUsers(std::move(Arg.LoopUsers)),
14185 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
14186 FirstUnknown(Arg.FirstUnknown) {
14187 Arg.FirstUnknown = nullptr;
14188}
14189
14191 // Iterate through all the SCEVUnknown instances and call their
14192 // destructors, so that they release their references to their values.
14193 for (SCEVUnknown *U = FirstUnknown; U;) {
14194 SCEVUnknown *Tmp = U;
14195 U = U->Next;
14196 Tmp->~SCEVUnknown();
14197 }
14198 FirstUnknown = nullptr;
14199
14200 ExprValueMap.clear();
14201 ValueExprMap.clear();
14202 HasRecMap.clear();
14203 BackedgeTakenCounts.clear();
14204 PredicatedBackedgeTakenCounts.clear();
14205
14206 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
14207 assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
14208 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
14209 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
14210}
14211
14215
14216/// When printing a top-level SCEV for trip counts, it's helpful to include
14217/// a type for constants which are otherwise hard to disambiguate.
14218static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV* S) {
14219 if (isa<SCEVConstant>(S))
14220 OS << *S->getType() << " ";
14221 OS << *S;
14222}
14223
14225 const Loop *L) {
14226 // Print all inner loops first
14227 for (Loop *I : *L)
14228 PrintLoopInfo(OS, SE, I);
14229
14230 OS << "Loop ";
14231 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14232 OS << ": ";
14233
14234 SmallVector<BasicBlock *, 8> ExitingBlocks;
14235 L->getExitingBlocks(ExitingBlocks);
14236 if (ExitingBlocks.size() != 1)
14237 OS << "<multiple exits> ";
14238
14239 auto *BTC = SE->getBackedgeTakenCount(L);
14240 if (!isa<SCEVCouldNotCompute>(BTC)) {
14241 OS << "backedge-taken count is ";
14242 PrintSCEVWithTypeHint(OS, BTC);
14243 } else
14244 OS << "Unpredictable backedge-taken count.";
14245 OS << "\n";
14246
14247 if (ExitingBlocks.size() > 1)
14248 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14249 OS << " exit count for " << ExitingBlock->getName() << ": ";
14250 const SCEV *EC = SE->getExitCount(L, ExitingBlock);
14251 PrintSCEVWithTypeHint(OS, EC);
14252 if (isa<SCEVCouldNotCompute>(EC)) {
14253 // Retry with predicates.
14255 EC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates);
14256 if (!isa<SCEVCouldNotCompute>(EC)) {
14257 OS << "\n predicated exit count for " << ExitingBlock->getName()
14258 << ": ";
14259 PrintSCEVWithTypeHint(OS, EC);
14260 OS << "\n Predicates:\n";
14261 for (const auto *P : Predicates)
14262 P->print(OS, 4);
14263 }
14264 }
14265 OS << "\n";
14266 }
14267
14268 OS << "Loop ";
14269 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14270 OS << ": ";
14271
14272 auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
14273 if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
14274 OS << "constant max backedge-taken count is ";
14275 PrintSCEVWithTypeHint(OS, ConstantBTC);
14277 OS << ", actual taken count either this or zero.";
14278 } else {
14279 OS << "Unpredictable constant max backedge-taken count. ";
14280 }
14281
14282 OS << "\n"
14283 "Loop ";
14284 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14285 OS << ": ";
14286
14287 auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
14288 if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
14289 OS << "symbolic max backedge-taken count is ";
14290 PrintSCEVWithTypeHint(OS, SymbolicBTC);
14292 OS << ", actual taken count either this or zero.";
14293 } else {
14294 OS << "Unpredictable symbolic max backedge-taken count. ";
14295 }
14296 OS << "\n";
14297
14298 if (ExitingBlocks.size() > 1)
14299 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14300 OS << " symbolic max exit count for " << ExitingBlock->getName() << ": ";
14301 auto *ExitBTC = SE->getExitCount(L, ExitingBlock,
14303 PrintSCEVWithTypeHint(OS, ExitBTC);
14304 if (isa<SCEVCouldNotCompute>(ExitBTC)) {
14305 // Retry with predicates.
14307 ExitBTC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates,
14309 if (!isa<SCEVCouldNotCompute>(ExitBTC)) {
14310 OS << "\n predicated symbolic max exit count for "
14311 << ExitingBlock->getName() << ": ";
14312 PrintSCEVWithTypeHint(OS, ExitBTC);
14313 OS << "\n Predicates:\n";
14314 for (const auto *P : Predicates)
14315 P->print(OS, 4);
14316 }
14317 }
14318 OS << "\n";
14319 }
14320
14322 auto *PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
14323 if (PBT != BTC) {
14324 OS << "Loop ";
14325 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14326 OS << ": ";
14327 if (!isa<SCEVCouldNotCompute>(PBT)) {
14328 OS << "Predicated backedge-taken count is ";
14329 PrintSCEVWithTypeHint(OS, PBT);
14330 } else
14331 OS << "Unpredictable predicated backedge-taken count.";
14332 OS << "\n";
14333 OS << " Predicates:\n";
14334 for (const auto *P : Preds)
14335 P->print(OS, 4);
14336 }
14337 Preds.clear();
14338
14339 auto *PredConstantMax =
14341 if (PredConstantMax != ConstantBTC) {
14342 OS << "Loop ";
14343 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14344 OS << ": ";
14345 if (!isa<SCEVCouldNotCompute>(PredConstantMax)) {
14346 OS << "Predicated constant max backedge-taken count is ";
14347 PrintSCEVWithTypeHint(OS, PredConstantMax);
14348 } else
14349 OS << "Unpredictable predicated constant max backedge-taken count.";
14350 OS << "\n";
14351 OS << " Predicates:\n";
14352 for (const auto *P : Preds)
14353 P->print(OS, 4);
14354 }
14355 Preds.clear();
14356
14357 auto *PredSymbolicMax =
14359 if (SymbolicBTC != PredSymbolicMax) {
14360 OS << "Loop ";
14361 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14362 OS << ": ";
14363 if (!isa<SCEVCouldNotCompute>(PredSymbolicMax)) {
14364 OS << "Predicated symbolic max backedge-taken count is ";
14365 PrintSCEVWithTypeHint(OS, PredSymbolicMax);
14366 } else
14367 OS << "Unpredictable predicated symbolic max backedge-taken count.";
14368 OS << "\n";
14369 OS << " Predicates:\n";
14370 for (const auto *P : Preds)
14371 P->print(OS, 4);
14372 }
14373
14375 OS << "Loop ";
14376 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14377 OS << ": ";
14378 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
14379 }
14380}
14381
14382namespace llvm {
14383// Note: these overloaded operators need to be in the llvm namespace for them
14384// to be resolved correctly. If we put them outside the llvm namespace, the
14385//
14386// OS << ": " << SE.getLoopDisposition(SV, InnerL);
14387//
14388// code below "breaks" and start printing raw enum values as opposed to the
14389// string values.
14392 switch (LD) {
14394 OS << "Variant";
14395 break;
14397 OS << "Invariant";
14398 break;
14400 OS << "Uniform";
14401 break;
14403 OS << "Computable";
14404 break;
14405 }
14406 return OS;
14407}
14408
14411 switch (BD) {
14413 OS << "DoesNotDominate";
14414 break;
14416 OS << "Dominates";
14417 break;
14419 OS << "ProperlyDominates";
14420 break;
14421 }
14422 return OS;
14423}
14424} // namespace llvm
14425
14427 // ScalarEvolution's implementation of the print method is to print
14428 // out SCEV values of all instructions that are interesting. Doing
14429 // this potentially causes it to create new SCEV objects though,
14430 // which technically conflicts with the const qualifier. This isn't
14431 // observable from outside the class though, so casting away the
14432 // const isn't dangerous.
14433 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14434
14435 if (ClassifyExpressions) {
14436 OS << "Classifying expressions for: ";
14437 F.printAsOperand(OS, /*PrintType=*/false);
14438 OS << "\n";
14439 for (Instruction &I : instructions(F))
14440 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
14441 OS << I << '\n';
14442 OS << " --> ";
14443 const SCEV *SV = SE.getSCEV(&I);
14444 SV->print(OS);
14445 if (!isa<SCEVCouldNotCompute>(SV)) {
14446 OS << " U: ";
14447 SE.getUnsignedRange(SV).print(OS);
14448 OS << " S: ";
14449 SE.getSignedRange(SV).print(OS);
14450 }
14451
14452 const Loop *L = LI.getLoopFor(I.getParent());
14453
14454 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
14455 if (AtUse != SV) {
14456 OS << " --> ";
14457 AtUse->print(OS);
14458 if (!isa<SCEVCouldNotCompute>(AtUse)) {
14459 OS << " U: ";
14460 SE.getUnsignedRange(AtUse).print(OS);
14461 OS << " S: ";
14462 SE.getSignedRange(AtUse).print(OS);
14463 }
14464 }
14465
14466 if (L) {
14467 OS << "\t\t" "Exits: ";
14468 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
14469 if (!SE.isLoopInvariant(ExitValue, L)) {
14470 OS << "<<Unknown>>";
14471 } else {
14472 OS << *ExitValue;
14473 }
14474
14475 ListSeparator LS(", ", "\t\tLoopDispositions: { ");
14476 for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
14477 OS << LS;
14478 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14479 OS << ": " << SE.getLoopDisposition(SV, Iter);
14480 }
14481
14482 for (const auto *InnerL : depth_first(L)) {
14483 if (InnerL == L)
14484 continue;
14485 OS << LS;
14486 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14487 OS << ": " << SE.getLoopDisposition(SV, InnerL);
14488 }
14489
14490 OS << " }";
14491 }
14492
14493 OS << "\n";
14494 }
14495 }
14496
14497 OS << "Determining loop execution counts for: ";
14498 F.printAsOperand(OS, /*PrintType=*/false);
14499 OS << "\n";
14500 for (Loop *I : LI)
14501 PrintLoopInfo(OS, &SE, I);
14502}
14503
14506 auto &Values = LoopDispositions[S];
14507 for (auto &V : Values) {
14508 if (V.getPointer() == L)
14509 return V.getInt();
14510 }
14511 Values.emplace_back(L, LoopVariant);
14512 LoopDisposition D = computeLoopDisposition(S, L);
14513 auto &Values2 = LoopDispositions[S];
14514 for (auto &V : llvm::reverse(Values2)) {
14515 if (V.getPointer() == L) {
14516 V.setInt(D);
14517 break;
14518 }
14519 }
14520 return D;
14521}
14522
14524ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
14525 switch (S->getSCEVType()) {
14526 case scConstant:
14527 case scVScale:
14528 return LoopInvariant;
14529 case scAddRecExpr: {
14530 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14531
14532 // If L is the addrec's loop, it's computable.
14533 if (AR->getLoop() == L)
14534 return LoopComputable;
14535
14536 // Add recurrences are never invariant in the function-body (null loop).
14537 if (!L)
14538 return LoopVariant;
14539
14540 // Everything that is not defined at loop entry is variant.
14541 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) {
14542 if (L->contains(AR->getLoop()) &&
14543 llvm::all_of(AR->operands(),
14544 [&](const SCEV *Op) { return isLoopUniform(Op, L); }))
14545 return LoopUniform;
14546
14547 return LoopVariant;
14548 }
14549 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
14550 " dominate the contained loop's header?");
14551
14552 // This recurrence is invariant w.r.t. L if AR's loop contains L.
14553 if (AR->getLoop()->contains(L))
14554 return LoopInvariant;
14555
14556 // This recurrence is variant w.r.t. L if any of its operands
14557 // are variant.
14558 for (SCEVUse Op : AR->operands())
14559 if (!isLoopInvariant(Op, L))
14560 return LoopVariant;
14561
14562 // Otherwise it's loop-invariant.
14563 return LoopInvariant;
14564 }
14565 case scTruncate:
14566 case scZeroExtend:
14567 case scSignExtend:
14568 case scPtrToAddr:
14569 case scPtrToInt:
14570 case scAddExpr:
14571 case scMulExpr:
14572 case scUDivExpr:
14573 case scUMaxExpr:
14574 case scSMaxExpr:
14575 case scUMinExpr:
14576 case scSMinExpr:
14577 case scSequentialUMinExpr: {
14578 bool HasVarying = false;
14579 bool HasUniform = false;
14580 for (SCEVUse Op : S->operands()) {
14582 if (D == LoopVariant)
14583 return LoopVariant;
14584 if (D == LoopComputable)
14585 HasVarying = true;
14586 if (D == LoopUniform)
14587 HasUniform = true;
14588 }
14589 return HasVarying ? (HasUniform ? LoopVariant : LoopComputable)
14590 : (HasUniform ? LoopUniform : LoopInvariant);
14591 }
14592 case scUnknown:
14593 // All non-instruction values are loop invariant. All instructions are loop
14594 // invariant if they are not contained in the specified loop.
14595 // Instructions are never considered invariant in the function body
14596 // (null loop) because they are defined within the "loop".
14598 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
14599 return LoopInvariant;
14600 case scCouldNotCompute:
14601 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14602 }
14603 llvm_unreachable("Unknown SCEV kind!");
14604}
14605
14606bool ScalarEvolution::isLoopUniform(const SCEV *S, const Loop *L) {
14608 return D == LoopUniform || D == LoopInvariant;
14609}
14610
14612 return getLoopDisposition(S, L) == LoopInvariant;
14613}
14614
14616 return getLoopDisposition(S, L) == LoopComputable;
14617}
14618
14621 auto &Values = BlockDispositions[S];
14622 for (auto &V : Values) {
14623 if (V.getPointer() == BB)
14624 return V.getInt();
14625 }
14626 Values.emplace_back(BB, DoesNotDominateBlock);
14627 BlockDisposition D = computeBlockDisposition(S, BB);
14628 auto &Values2 = BlockDispositions[S];
14629 for (auto &V : llvm::reverse(Values2)) {
14630 if (V.getPointer() == BB) {
14631 V.setInt(D);
14632 break;
14633 }
14634 }
14635 return D;
14636}
14637
14639ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
14640 switch (S->getSCEVType()) {
14641 case scConstant:
14642 case scVScale:
14644 case scAddRecExpr: {
14645 // This uses a "dominates" query instead of "properly dominates" query
14646 // to test for proper dominance too, because the instruction which
14647 // produces the addrec's value is a PHI, and a PHI effectively properly
14648 // dominates its entire containing block.
14649 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14650 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
14651 return DoesNotDominateBlock;
14652
14653 // Fall through into SCEVNAryExpr handling.
14654 [[fallthrough]];
14655 }
14656 case scTruncate:
14657 case scZeroExtend:
14658 case scSignExtend:
14659 case scPtrToAddr:
14660 case scPtrToInt:
14661 case scAddExpr:
14662 case scMulExpr:
14663 case scUDivExpr:
14664 case scUMaxExpr:
14665 case scSMaxExpr:
14666 case scUMinExpr:
14667 case scSMinExpr:
14668 case scSequentialUMinExpr: {
14669 bool Proper = true;
14670 for (const SCEV *NAryOp : S->operands()) {
14672 if (D == DoesNotDominateBlock)
14673 return DoesNotDominateBlock;
14674 if (D == DominatesBlock)
14675 Proper = false;
14676 }
14677 return Proper ? ProperlyDominatesBlock : DominatesBlock;
14678 }
14679 case scUnknown:
14680 if (Instruction *I =
14682 if (I->getParent() == BB)
14683 return DominatesBlock;
14684 if (DT.properlyDominates(I->getParent(), BB))
14686 return DoesNotDominateBlock;
14687 }
14689 case scCouldNotCompute:
14690 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14691 }
14692 llvm_unreachable("Unknown SCEV kind!");
14693}
14694
14695bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
14696 return getBlockDisposition(S, BB) >= DominatesBlock;
14697}
14698
14701}
14702
14703bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
14704 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
14705}
14706
14707void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
14708 bool Predicated) {
14709 auto &BECounts =
14710 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14711 auto It = BECounts.find(L);
14712 if (It != BECounts.end()) {
14713 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
14714 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14715 if (!isa<SCEVConstant>(S)) {
14716 auto UserIt = BECountUsers.find(S);
14717 assert(UserIt != BECountUsers.end());
14718 UserIt->second.erase({L, Predicated});
14719 }
14720 }
14721 }
14722 BECounts.erase(It);
14723 }
14724}
14725
14726void ScalarEvolution::forgetMemoizedResults(ArrayRef<SCEVUse> SCEVs) {
14727 SmallPtrSet<const SCEV *, 8> ToForget(llvm::from_range, SCEVs);
14728 SmallVector<SCEVUse, 8> Worklist(ToForget.begin(), ToForget.end());
14729
14730 while (!Worklist.empty()) {
14731 const SCEV *Curr = Worklist.pop_back_val();
14732 auto Users = SCEVUsers.find(Curr);
14733 if (Users != SCEVUsers.end())
14734 for (const auto *User : Users->second)
14735 if (ToForget.insert(User).second)
14736 Worklist.push_back(User);
14737 }
14738
14739 for (const auto *S : ToForget)
14740 forgetMemoizedResultsImpl(S);
14741
14742 PredicatedSCEVRewrites.remove_if(
14743 [&](const auto &Entry) { return ToForget.count(Entry.first.first); });
14744}
14745
14746void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
14747 LoopDispositions.erase(S);
14748 BlockDispositions.erase(S);
14749 UnsignedRanges.erase(S);
14750 SignedRanges.erase(S);
14751 HasRecMap.erase(S);
14752 ConstantMultipleCache.erase(S);
14753
14754 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
14755 UnsignedWrapViaInductionTried.erase(AR);
14756 SignedWrapViaInductionTried.erase(AR);
14757 }
14758
14759 auto ExprIt = ExprValueMap.find(S);
14760 if (ExprIt != ExprValueMap.end()) {
14761 for (Value *V : ExprIt->second) {
14762 auto ValueIt = ValueExprMap.find_as(V);
14763 if (ValueIt != ValueExprMap.end())
14764 ValueExprMap.erase(ValueIt);
14765 }
14766 ExprValueMap.erase(ExprIt);
14767 }
14768
14769 auto ScopeIt = ValuesAtScopes.find(S);
14770 if (ScopeIt != ValuesAtScopes.end()) {
14771 for (const auto &Pair : ScopeIt->second)
14772 if (!isa_and_nonnull<SCEVConstant>(Pair.second))
14773 llvm::erase(ValuesAtScopesUsers[Pair.second],
14774 std::make_pair(Pair.first, S));
14775 ValuesAtScopes.erase(ScopeIt);
14776 }
14777
14778 auto ScopeUserIt = ValuesAtScopesUsers.find(S);
14779 if (ScopeUserIt != ValuesAtScopesUsers.end()) {
14780 for (const auto &Pair : ScopeUserIt->second)
14781 llvm::erase(ValuesAtScopes[Pair.second], std::make_pair(Pair.first, S));
14782 ValuesAtScopesUsers.erase(ScopeUserIt);
14783 }
14784
14785 auto BEUsersIt = BECountUsers.find(S);
14786 if (BEUsersIt != BECountUsers.end()) {
14787 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
14788 auto Copy = BEUsersIt->second;
14789 for (const auto &Pair : Copy)
14790 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
14791 BECountUsers.erase(BEUsersIt);
14792 }
14793
14794 auto FoldUser = FoldCacheUser.find(S);
14795 if (FoldUser != FoldCacheUser.end())
14796 for (auto &KV : FoldUser->second)
14797 FoldCache.erase(KV);
14798 FoldCacheUser.erase(S);
14799}
14800
14801void
14802ScalarEvolution::getUsedLoops(const SCEV *S,
14803 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
14804 struct FindUsedLoops {
14805 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
14806 : LoopsUsed(LoopsUsed) {}
14807 SmallPtrSetImpl<const Loop *> &LoopsUsed;
14808 bool follow(const SCEV *S) {
14809 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
14810 LoopsUsed.insert(AR->getLoop());
14811 return true;
14812 }
14813
14814 bool isDone() const { return false; }
14815 };
14816
14817 FindUsedLoops F(LoopsUsed);
14818 SCEVTraversal<FindUsedLoops>(F).visitAll(S);
14819}
14820
14821void ScalarEvolution::getReachableBlocks(
14824 Worklist.push_back(&F.getEntryBlock());
14825 while (!Worklist.empty()) {
14826 BasicBlock *BB = Worklist.pop_back_val();
14827 if (!Reachable.insert(BB).second)
14828 continue;
14829
14830 Value *Cond;
14831 BasicBlock *TrueBB, *FalseBB;
14832 if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
14833 m_BasicBlock(FalseBB)))) {
14834 if (auto *C = dyn_cast<ConstantInt>(Cond)) {
14835 Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
14836 continue;
14837 }
14838
14839 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14840 const SCEV *L = getSCEV(Cmp->getOperand(0));
14841 const SCEV *R = getSCEV(Cmp->getOperand(1));
14842 if (isKnownPredicateViaConstantRanges(Cmp->getCmpPredicate(), L, R)) {
14843 Worklist.push_back(TrueBB);
14844 continue;
14845 }
14846 if (isKnownPredicateViaConstantRanges(Cmp->getInverseCmpPredicate(), L,
14847 R)) {
14848 Worklist.push_back(FalseBB);
14849 continue;
14850 }
14851 }
14852 }
14853
14854 append_range(Worklist, successors(BB));
14855 }
14856}
14857
14859 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14860 ScalarEvolution SE2(F, TLI, AC, DT, LI);
14861
14862 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
14863
14864 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
14865 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
14866 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
14867
14868 const SCEV *visitConstant(const SCEVConstant *Constant) {
14869 return SE.getConstant(Constant->getAPInt());
14870 }
14871
14872 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14873 return SE.getUnknown(Expr->getValue());
14874 }
14875
14876 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
14877 return SE.getCouldNotCompute();
14878 }
14879 };
14880
14881 SCEVMapper SCM(SE2);
14882 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
14883 SE2.getReachableBlocks(ReachableBlocks, F);
14884
14885 auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
14886 if (containsUndefs(Old) || containsUndefs(New)) {
14887 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
14888 // not propagate undef aggressively). This means we can (and do) fail
14889 // verification in cases where a transform makes a value go from "undef"
14890 // to "undef+1" (say). The transform is fine, since in both cases the
14891 // result is "undef", but SCEV thinks the value increased by 1.
14892 return nullptr;
14893 }
14894
14895 // Unless VerifySCEVStrict is set, we only compare constant deltas.
14896 const SCEV *Delta = SE2.getMinusSCEV(Old, New);
14897 if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
14898 return nullptr;
14899
14900 return Delta;
14901 };
14902
14903 while (!LoopStack.empty()) {
14904 auto *L = LoopStack.pop_back_val();
14905 llvm::append_range(LoopStack, *L);
14906
14907 // Only verify BECounts in reachable loops. For an unreachable loop,
14908 // any BECount is legal.
14909 if (!ReachableBlocks.contains(L->getHeader()))
14910 continue;
14911
14912 // Only verify cached BECounts. Computing new BECounts may change the
14913 // results of subsequent SCEV uses.
14914 auto It = BackedgeTakenCounts.find(L);
14915 if (It == BackedgeTakenCounts.end())
14916 continue;
14917
14918 auto *CurBECount =
14919 SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
14920 auto *NewBECount = SE2.getBackedgeTakenCount(L);
14921
14922 if (CurBECount == SE2.getCouldNotCompute() ||
14923 NewBECount == SE2.getCouldNotCompute()) {
14924 // NB! This situation is legal, but is very suspicious -- whatever pass
14925 // change the loop to make a trip count go from could not compute to
14926 // computable or vice-versa *should have* invalidated SCEV. However, we
14927 // choose not to assert here (for now) since we don't want false
14928 // positives.
14929 continue;
14930 }
14931
14932 if (SE.getTypeSizeInBits(CurBECount->getType()) >
14933 SE.getTypeSizeInBits(NewBECount->getType()))
14934 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
14935 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
14936 SE.getTypeSizeInBits(NewBECount->getType()))
14937 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
14938
14939 const SCEV *Delta = GetDelta(CurBECount, NewBECount);
14940 if (Delta && !Delta->isZero()) {
14941 dbgs() << "Trip Count for " << *L << " Changed!\n";
14942 dbgs() << "Old: " << *CurBECount << "\n";
14943 dbgs() << "New: " << *NewBECount << "\n";
14944 dbgs() << "Delta: " << *Delta << "\n";
14945 std::abort();
14946 }
14947 }
14948
14949 // Collect all valid loops currently in LoopInfo.
14950 SmallPtrSet<Loop *, 32> ValidLoops;
14951 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
14952 while (!Worklist.empty()) {
14953 Loop *L = Worklist.pop_back_val();
14954 if (ValidLoops.insert(L).second)
14955 Worklist.append(L->begin(), L->end());
14956 }
14957 for (const auto &KV : ValueExprMap) {
14958#ifndef NDEBUG
14959 // Check for SCEV expressions referencing invalid/deleted loops.
14960 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14961 assert(ValidLoops.contains(AR->getLoop()) &&
14962 "AddRec references invalid loop");
14963 }
14964#endif
14965
14966 // Check that the value is also part of the reverse map.
14967 auto It = ExprValueMap.find(KV.second);
14968 if (It == ExprValueMap.end() || !It->second.contains(KV.first)) {
14969 dbgs() << "Value " << *KV.first
14970 << " is in ValueExprMap but not in ExprValueMap\n";
14971 std::abort();
14972 }
14973
14974 if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
14975 if (!ReachableBlocks.contains(I->getParent()))
14976 continue;
14977 const SCEV *OldSCEV = SCM.visit(KV.second);
14978 const SCEV *NewSCEV = SE2.getSCEV(I);
14979 const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14980 if (Delta && !Delta->isZero()) {
14981 dbgs() << "SCEV for value " << *I << " changed!\n"
14982 << "Old: " << *OldSCEV << "\n"
14983 << "New: " << *NewSCEV << "\n"
14984 << "Delta: " << *Delta << "\n";
14985 std::abort();
14986 }
14987 }
14988 }
14989
14990 for (const auto &KV : ExprValueMap) {
14991 for (Value *V : KV.second) {
14992 const SCEV *S = ValueExprMap.lookup(V);
14993 if (!S) {
14994 dbgs() << "Value " << *V
14995 << " is in ExprValueMap but not in ValueExprMap\n";
14996 std::abort();
14997 }
14998 if (S != KV.first) {
14999 dbgs() << "Value " << *V << " mapped to " << *S << " rather than "
15000 << *KV.first << "\n";
15001 std::abort();
15002 }
15003 }
15004 }
15005
15006 // Verify integrity of SCEV users.
15007 for (const auto &S : UniqueSCEVs) {
15008 for (SCEVUse Op : S.operands()) {
15009 // We do not store dependencies of constants.
15010 if (isa<SCEVConstant>(Op))
15011 continue;
15012 auto It = SCEVUsers.find(Op);
15013 if (It != SCEVUsers.end() && It->second.count(&S))
15014 continue;
15015 dbgs() << "Use of operand " << *Op << " by user " << S
15016 << " is not being tracked!\n";
15017 std::abort();
15018 }
15019 }
15020
15021 // Verify integrity of ValuesAtScopes users.
15022 for (const auto &ValueAndVec : ValuesAtScopes) {
15023 const SCEV *Value = ValueAndVec.first;
15024 for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
15025 const Loop *L = LoopAndValueAtScope.first;
15026 const SCEV *ValueAtScope = LoopAndValueAtScope.second;
15027 if (!isa<SCEVConstant>(ValueAtScope)) {
15028 auto It = ValuesAtScopesUsers.find(ValueAtScope);
15029 if (It != ValuesAtScopesUsers.end() &&
15030 is_contained(It->second, std::make_pair(L, Value)))
15031 continue;
15032 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
15033 << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
15034 std::abort();
15035 }
15036 }
15037 }
15038
15039 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
15040 const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
15041 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
15042 const Loop *L = LoopAndValue.first;
15043 const SCEV *Value = LoopAndValue.second;
15045 auto It = ValuesAtScopes.find(Value);
15046 if (It != ValuesAtScopes.end() &&
15047 is_contained(It->second, std::make_pair(L, ValueAtScope)))
15048 continue;
15049 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
15050 << *ValueAtScope << " missing in ValuesAtScopes\n";
15051 std::abort();
15052 }
15053 }
15054
15055 // Verify integrity of BECountUsers.
15056 auto VerifyBECountUsers = [&](bool Predicated) {
15057 auto &BECounts =
15058 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
15059 for (const auto &LoopAndBEInfo : BECounts) {
15060 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
15061 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
15062 if (!isa<SCEVConstant>(S)) {
15063 auto UserIt = BECountUsers.find(S);
15064 if (UserIt != BECountUsers.end() &&
15065 UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
15066 continue;
15067 dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
15068 << " missing from BECountUsers\n";
15069 std::abort();
15070 }
15071 }
15072 }
15073 }
15074 };
15075 VerifyBECountUsers(/* Predicated */ false);
15076 VerifyBECountUsers(/* Predicated */ true);
15077
15078 // Verify intergity of loop disposition cache.
15079 for (auto &[S, Values] : LoopDispositions) {
15080 for (auto [Loop, CachedDisposition] : Values) {
15081 const auto RecomputedDisposition = SE2.getLoopDisposition(S, Loop);
15082 if (CachedDisposition != RecomputedDisposition) {
15083 dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
15084 << " is incorrect: cached " << CachedDisposition << ", actual "
15085 << RecomputedDisposition << "\n";
15086 std::abort();
15087 }
15088 }
15089 }
15090
15091 // Verify integrity of the block disposition cache.
15092 for (auto &[S, Values] : BlockDispositions) {
15093 for (auto [BB, CachedDisposition] : Values) {
15094 const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
15095 if (CachedDisposition != RecomputedDisposition) {
15096 dbgs() << "Cached disposition of " << *S << " for block %"
15097 << BB->getName() << " is incorrect: cached " << CachedDisposition
15098 << ", actual " << RecomputedDisposition << "\n";
15099 std::abort();
15100 }
15101 }
15102 }
15103
15104 // Verify FoldCache/FoldCacheUser caches.
15105 for (auto [FoldID, Expr] : FoldCache) {
15106 auto I = FoldCacheUser.find(Expr);
15107 if (I == FoldCacheUser.end()) {
15108 dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
15109 << "!\n";
15110 std::abort();
15111 }
15112 if (!is_contained(I->second, FoldID)) {
15113 dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
15114 std::abort();
15115 }
15116 }
15117 for (auto [Expr, IDs] : FoldCacheUser) {
15118 for (auto &FoldID : IDs) {
15119 const SCEV *S = FoldCache.lookup(FoldID);
15120 if (!S) {
15121 dbgs() << "Missing entry in FoldCache for expression " << *Expr
15122 << "!\n";
15123 std::abort();
15124 }
15125 if (S != Expr) {
15126 dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: " << *S
15127 << " != " << *Expr << "!\n";
15128 std::abort();
15129 }
15130 }
15131 }
15132
15133 // Verify that ConstantMultipleCache computations are correct. We check that
15134 // cached multiples and recomputed multiples are multiples of each other to
15135 // verify correctness. It is possible that a recomputed multiple is different
15136 // from the cached multiple due to strengthened no wrap flags or changes in
15137 // KnownBits computations.
15138 for (auto [S, Multiple] : ConstantMultipleCache) {
15139 APInt RecomputedMultiple = SE2.getConstantMultiple(S);
15140 if ((Multiple != 0 && RecomputedMultiple != 0 &&
15141 Multiple.urem(RecomputedMultiple) != 0 &&
15142 RecomputedMultiple.urem(Multiple) != 0)) {
15143 dbgs() << "Incorrect cached computation in ConstantMultipleCache for "
15144 << *S << " : Computed " << RecomputedMultiple
15145 << " but cache contains " << Multiple << "!\n";
15146 std::abort();
15147 }
15148 }
15149}
15150
15152 Function &F, const PreservedAnalyses &PA,
15153 FunctionAnalysisManager::Invalidator &Inv) {
15154 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
15155 // of its dependencies is invalidated.
15156 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
15157 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
15158 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
15159 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
15160 Inv.invalidate<LoopAnalysis>(F, PA);
15161}
15162
15163AnalysisKey ScalarEvolutionAnalysis::Key;
15164
15167 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
15168 auto &AC = AM.getResult<AssumptionAnalysis>(F);
15169 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
15170 auto &LI = AM.getResult<LoopAnalysis>(F);
15171 return ScalarEvolution(F, TLI, AC, DT, LI);
15172}
15173
15179
15182 // For compatibility with opt's -analyze feature under legacy pass manager
15183 // which was not ported to NPM. This keeps tests using
15184 // update_analyze_test_checks.py working.
15185 OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
15186 << F.getName() << "':\n";
15188 return PreservedAnalyses::all();
15189}
15190
15192 "Scalar Evolution Analysis", false, true)
15198 "Scalar Evolution Analysis", false, true)
15199
15201
15203
15205 SE.reset(new ScalarEvolution(
15207 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
15209 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
15210 return false;
15211}
15212
15214
15216 SE->print(OS);
15217}
15218
15220 if (!VerifySCEV)
15221 return;
15222
15223 SE->verify();
15224}
15225
15233
15235 const SCEV *RHS) {
15236 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
15237}
15238
15239const SCEVPredicate *
15241 const SCEV *LHS, const SCEV *RHS) {
15243 assert(LHS->getType() == RHS->getType() &&
15244 "Type mismatch between LHS and RHS");
15245 // Unique this node based on the arguments
15246 ID.AddInteger(SCEVPredicate::P_Compare);
15247 ID.AddInteger(Pred);
15248 ID.AddPointer(LHS);
15249 ID.AddPointer(RHS);
15250 void *IP = nullptr;
15251 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
15252 return S;
15253 SCEVComparePredicate *Eq = new (SCEVAllocator)
15254 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
15255 UniquePreds.InsertNode(Eq, IP);
15256 return Eq;
15257}
15258
15260 const SCEVAddRecExpr *AR,
15263 // Unique this node based on the arguments
15264 ID.AddInteger(SCEVPredicate::P_Wrap);
15265 ID.AddPointer(AR);
15266 ID.AddInteger(AddedFlags);
15267 void *IP = nullptr;
15268 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
15269 return S;
15270 auto *OF = new (SCEVAllocator)
15271 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
15272 UniquePreds.InsertNode(OF, IP);
15273 return OF;
15274}
15275
15276namespace {
15277
15278class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
15279public:
15280
15281 /// Rewrites \p S in the context of a loop L and the SCEV predication
15282 /// infrastructure.
15283 ///
15284 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
15285 /// equivalences present in \p Pred.
15286 ///
15287 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
15288 /// \p NewPreds such that the result will be an AddRecExpr.
15289 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
15291 const SCEVPredicate *Pred) {
15292 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
15293 return Rewriter.visit(S);
15294 }
15295
15296 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
15297 if (Pred) {
15298 if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
15299 for (const auto *Pred : U->getPredicates())
15300 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
15301 if (IPred->getLHS() == Expr &&
15302 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15303 return IPred->getRHS();
15304 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
15305 if (IPred->getLHS() == Expr &&
15306 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15307 return IPred->getRHS();
15308 }
15309 }
15310 return convertToAddRecWithPreds(Expr);
15311 }
15312
15313 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
15314 const SCEV *Operand = visit(Expr->getOperand());
15315 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15316 if (AR && AR->getLoop() == L && AR->isAffine()) {
15317 // This couldn't be folded because the operand didn't have the nuw
15318 // flag. Add the nusw flag as an assumption that we could make.
15319 const SCEV *Step = AR->getStepRecurrence(SE);
15320 Type *Ty = Expr->getType();
15321 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
15322 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
15323 SE.getSignExtendExpr(Step, Ty), L,
15324 AR->getNoWrapFlags());
15325 }
15326 return SE.getZeroExtendExpr(Operand, Expr->getType());
15327 }
15328
15329 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
15330 const SCEV *Operand = visit(Expr->getOperand());
15331 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15332 if (AR && AR->getLoop() == L && AR->isAffine()) {
15333 // This couldn't be folded because the operand didn't have the nsw
15334 // flag. Add the nssw flag as an assumption that we could make.
15335 const SCEV *Step = AR->getStepRecurrence(SE);
15336 Type *Ty = Expr->getType();
15337 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
15338 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
15339 SE.getSignExtendExpr(Step, Ty), L,
15340 AR->getNoWrapFlags());
15341 }
15342 return SE.getSignExtendExpr(Operand, Expr->getType());
15343 }
15344
15345private:
15346 explicit SCEVPredicateRewriter(
15347 const Loop *L, ScalarEvolution &SE,
15348 SmallVectorImpl<const SCEVPredicate *> *NewPreds,
15349 const SCEVPredicate *Pred)
15350 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
15351
15352 bool addOverflowAssumption(const SCEVPredicate *P) {
15353 if (!NewPreds) {
15354 // Check if we've already made this assumption.
15355 return Pred && Pred->implies(P, SE);
15356 }
15357 NewPreds->push_back(P);
15358 return true;
15359 }
15360
15361 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
15363 auto *A = SE.getWrapPredicate(AR, AddedFlags);
15364 return addOverflowAssumption(A);
15365 }
15366
15367 // If \p Expr represents a PHINode, we try to see if it can be represented
15368 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
15369 // to add this predicate as a runtime overflow check, we return the AddRec.
15370 // If \p Expr does not meet these conditions (is not a PHI node, or we
15371 // couldn't create an AddRec for it, or couldn't add the predicate), we just
15372 // return \p Expr.
15373 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
15374 if (!isa<PHINode>(Expr->getValue()))
15375 return Expr;
15376 std::optional<
15377 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
15378 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
15379 if (!PredicatedRewrite)
15380 return Expr;
15381 for (const auto *P : PredicatedRewrite->second){
15382 // Wrap predicates from outer loops are not supported.
15383 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
15384 if (L != WP->getExpr()->getLoop())
15385 return Expr;
15386 }
15387 if (!addOverflowAssumption(P))
15388 return Expr;
15389 }
15390 return PredicatedRewrite->first;
15391 }
15392
15393 SmallVectorImpl<const SCEVPredicate *> *NewPreds;
15394 const SCEVPredicate *Pred;
15395 const Loop *L;
15396};
15397
15398} // end anonymous namespace
15399
15400const SCEV *
15402 const SCEVPredicate &Preds) {
15403 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
15404}
15405
15407 const SCEV *S, const Loop *L,
15410 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
15411 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
15412
15413 if (!AddRec)
15414 return nullptr;
15415
15416 // Check if any of the transformed predicates is known to be false. In that
15417 // case, it doesn't make sense to convert to a predicated AddRec, as the
15418 // versioned loop will never execute.
15419 for (const SCEVPredicate *Pred : TransformPreds) {
15420 auto *WrapPred = dyn_cast<SCEVWrapPredicate>(Pred);
15421 if (!WrapPred || WrapPred->getFlags() != SCEVWrapPredicate::IncrementNSSW)
15422 continue;
15423
15424 const SCEVAddRecExpr *AddRecToCheck = WrapPred->getExpr();
15425 const SCEV *ExitCount = getBackedgeTakenCount(AddRecToCheck->getLoop());
15426 if (isa<SCEVCouldNotCompute>(ExitCount))
15427 continue;
15428
15429 const SCEV *Step = AddRecToCheck->getStepRecurrence(*this);
15430 if (!Step->isOne())
15431 continue;
15432
15433 ExitCount = getTruncateOrSignExtend(ExitCount, Step->getType());
15434 const SCEV *Add = getAddExpr(AddRecToCheck->getStart(), ExitCount);
15435 if (isKnownPredicate(CmpInst::ICMP_SLT, Add, AddRecToCheck->getStart()))
15436 return nullptr;
15437 }
15438
15439 // Since the transformation was successful, we can now transfer the SCEV
15440 // predicates.
15441 Preds.append(TransformPreds.begin(), TransformPreds.end());
15442
15443 return AddRec;
15444}
15445
15446/// SCEV predicates
15450
15452 const ICmpInst::Predicate Pred,
15453 const SCEV *LHS, const SCEV *RHS)
15454 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
15455 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
15456 assert(LHS != RHS && "LHS and RHS are the same SCEV");
15457}
15458
15460 ScalarEvolution &SE) const {
15461 const auto *Op = dyn_cast<SCEVComparePredicate>(N);
15462
15463 if (!Op)
15464 return false;
15465
15466 if (Pred != ICmpInst::ICMP_EQ)
15467 return false;
15468
15469 return Op->LHS == LHS && Op->RHS == RHS;
15470}
15471
15472bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
15473
15475 if (Pred == ICmpInst::ICMP_EQ)
15476 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
15477 else
15478 OS.indent(Depth) << "Compare predicate: " << *LHS << " " << Pred << ") "
15479 << *RHS << "\n";
15480
15481}
15482
15484 const SCEVAddRecExpr *AR,
15485 IncrementWrapFlags Flags)
15486 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
15487
15488const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
15489
15491 ScalarEvolution &SE) const {
15492 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
15493 if (!Op || setFlags(Flags, Op->Flags) != Flags)
15494 return false;
15495
15496 if (Op->AR == AR)
15497 return true;
15498
15499 if (Flags != SCEVWrapPredicate::IncrementNSSW &&
15501 return false;
15502
15503 const SCEV *Start = AR->getStart();
15504 const SCEV *OpStart = Op->AR->getStart();
15505 if (Start->getType()->isPointerTy() != OpStart->getType()->isPointerTy())
15506 return false;
15507
15508 // Reject pointers to different address spaces.
15509 if (Start->getType()->isPointerTy() && Start->getType() != OpStart->getType())
15510 return false;
15511
15512 // NUSW/NSSW on a wider-type AddRec does not imply the same on a
15513 // narrower-type AddRec.
15514 if (SE.getTypeSizeInBits(AR->getType()) >
15515 SE.getTypeSizeInBits(Op->AR->getType()))
15516 return false;
15517
15518 const SCEV *Step = AR->getStepRecurrence(SE);
15519 const SCEV *OpStep = Op->AR->getStepRecurrence(SE);
15520 if (!SE.isKnownPositive(Step) || !SE.isKnownPositive(OpStep))
15521 return false;
15522
15523 // If both steps are positive, this implies N, if N's start and step are
15524 // ULE/SLE (for NSUW/NSSW) than this'.
15525 Type *WiderTy = SE.getWiderType(Step->getType(), OpStep->getType());
15526 Step = SE.getNoopOrZeroExtend(Step, WiderTy);
15527 OpStep = SE.getNoopOrZeroExtend(OpStep, WiderTy);
15528
15529 bool IsNUW = Flags == SCEVWrapPredicate::IncrementNUSW;
15530 OpStart = IsNUW ? SE.getNoopOrZeroExtend(OpStart, WiderTy)
15531 : SE.getNoopOrSignExtend(OpStart, WiderTy);
15532 Start = IsNUW ? SE.getNoopOrZeroExtend(Start, WiderTy)
15533 : SE.getNoopOrSignExtend(Start, WiderTy);
15535 return SE.isKnownPredicate(Pred, OpStep, Step) &&
15536 SE.isKnownPredicate(Pred, OpStart, Start);
15537}
15538
15540 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
15541 IncrementWrapFlags IFlags = Flags;
15542
15543 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
15544 IFlags = clearFlags(IFlags, IncrementNSSW);
15545
15546 return IFlags == IncrementAnyWrap;
15547}
15548
15549void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
15550 OS.indent(Depth) << *getExpr() << " Added Flags: ";
15552 OS << "<nusw>";
15554 OS << "<nssw>";
15555 OS << "\n";
15556}
15557
15560 ScalarEvolution &SE) {
15561 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
15562 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
15563
15564 // We can safely transfer the NSW flag as NSSW.
15565 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
15566 ImpliedFlags = IncrementNSSW;
15567
15568 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
15569 // If the increment is positive, the SCEV NUW flag will also imply the
15570 // WrapPredicate NUSW flag.
15571 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
15572 if (Step->getValue()->getValue().isNonNegative())
15573 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
15574 }
15575
15576 return ImpliedFlags;
15577}
15578
15579/// Union predicates don't get cached so create a dummy set ID for it.
15581 ScalarEvolution &SE)
15582 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {
15583 for (const auto *P : Preds)
15584 add(P, SE);
15585}
15586
15588 return all_of(Preds,
15589 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
15590}
15591
15593 ScalarEvolution &SE) const {
15594 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
15595 return all_of(Set->Preds, [this, &SE](const SCEVPredicate *I) {
15596 return this->implies(I, SE);
15597 });
15598
15599 if (any_of(Preds,
15600 [N, &SE](const SCEVPredicate *I) { return I->implies(N, SE); }))
15601 return true;
15602
15603 // A wrap predicate may be implied by a wrap predicate in Preds after applying
15604 // equal predicates.
15605 const auto *NWrap = dyn_cast<SCEVWrapPredicate>(N);
15606 if (!NWrap)
15607 return false;
15608 const Loop *L = NWrap->getExpr()->getLoop();
15609 return any_of(Preds, [&](const SCEVPredicate *I) {
15610 const auto *IWrap = dyn_cast<SCEVWrapPredicate>(I);
15611 if (!IWrap)
15612 return false;
15613 const auto *RewrittenAR = dyn_cast<SCEVAddRecExpr>(
15614 SE.rewriteUsingPredicate(IWrap->getExpr(), L, *this));
15615 return RewrittenAR &&
15616 SE.getWrapPredicate(RewrittenAR, IWrap->getFlags())->implies(N, SE);
15617 });
15618}
15619
15621 for (const auto *Pred : Preds)
15622 Pred->print(OS, Depth);
15623}
15624
15625void SCEVUnionPredicate::add(const SCEVPredicate *N, ScalarEvolution &SE) {
15626 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
15627 for (const auto *Pred : Set->Preds)
15628 add(Pred, SE);
15629 return;
15630 }
15631
15632 // Implication checks are quadratic in the number of predicates. Stop doing
15633 // them if there are many predicates, as they should be too expensive to use
15634 // anyway at that point.
15635 bool CheckImplies = Preds.size() < 16;
15636
15637 // Only add predicate if it is not already implied by this union predicate.
15638 if (CheckImplies && implies(N, SE))
15639 return;
15640
15641 // Build a new vector containing the current predicates, except the ones that
15642 // are implied by the new predicate N.
15644 for (auto *P : Preds) {
15645 if (CheckImplies && N->implies(P, SE))
15646 continue;
15647 PrunedPreds.push_back(P);
15648 }
15649 Preds = std::move(PrunedPreds);
15650 Preds.push_back(N);
15651}
15652
15654 Loop &L)
15655 : SE(SE), L(L) {
15657 Preds = std::make_unique<SCEVUnionPredicate>(Empty, SE);
15658}
15659
15662 for (const auto *Op : Ops)
15663 // We do not expect that forgetting cached data for SCEVConstants will ever
15664 // open any prospects for sharpening or introduce any correctness issues,
15665 // so we don't bother storing their dependencies.
15666 if (!isa<SCEVConstant>(Op))
15667 SCEVUsers[Op].insert(User);
15668}
15669
15671 for (const SCEV *Op : Ops)
15672 // We do not expect that forgetting cached data for SCEVConstants will ever
15673 // open any prospects for sharpening or introduce any correctness issues,
15674 // so we don't bother storing their dependencies.
15675 if (!isa<SCEVConstant>(Op))
15676 SCEVUsers[Op].insert(User);
15677}
15678
15680 const SCEV *Expr = SE.getSCEV(V);
15681 return getPredicatedSCEV(Expr);
15682}
15683
15685 RewriteEntry &Entry = RewriteMap[Expr];
15686
15687 // If we already have an entry and the version matches, return it.
15688 if (Entry.second && Generation == Entry.first)
15689 return Entry.second;
15690
15691 // We found an entry but it's stale. Rewrite the stale entry
15692 // according to the current predicate.
15693 if (Entry.second)
15694 Expr = Entry.second;
15695
15696 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
15697 Entry = {Generation, NewSCEV};
15698
15699 return NewSCEV;
15700}
15701
15703 if (!BackedgeCount) {
15705 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
15706 for (const auto *P : Preds)
15707 addPredicate(*P);
15708 }
15709 return BackedgeCount;
15710}
15711
15713 if (!SymbolicMaxBackedgeCount) {
15715 SymbolicMaxBackedgeCount =
15716 SE.getPredicatedSymbolicMaxBackedgeTakenCount(&L, Preds);
15717 for (const auto *P : Preds)
15718 addPredicate(*P);
15719 }
15720 return SymbolicMaxBackedgeCount;
15721}
15722
15724 if (!SmallConstantMaxTripCount) {
15726 SmallConstantMaxTripCount = SE.getSmallConstantMaxTripCount(&L, &Preds);
15727 for (const auto *P : Preds)
15728 addPredicate(*P);
15729 }
15730 return *SmallConstantMaxTripCount;
15731}
15732
15734 if (Preds->implies(&Pred, SE))
15735 return;
15736
15737 SmallVector<const SCEVPredicate *, 4> NewPreds(Preds->getPredicates());
15738 NewPreds.push_back(&Pred);
15739 Preds = std::make_unique<SCEVUnionPredicate>(NewPreds, SE);
15740 updateGeneration();
15741}
15742
15745 for (const SCEVPredicate *P : Preds)
15746 addPredicate(*P);
15747}
15748
15750 return *Preds;
15751}
15752
15753void PredicatedScalarEvolution::updateGeneration() {
15754 // If the generation number wrapped recompute everything.
15755 if (++Generation == 0) {
15756 for (auto &II : RewriteMap) {
15757 const SCEV *Rewritten = II.second.second;
15758 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
15759 }
15760 }
15761}
15762
15765 const auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V));
15766 if (!AR)
15767 return false;
15768
15770 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
15771
15773}
15774
15777 const SCEV *Expr = this->getSCEV(V);
15779 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
15780
15781 if (!New)
15782 return nullptr;
15783
15784 if (ExtraPreds) {
15785 ExtraPreds->append(NewPreds);
15786 return New;
15787 }
15788
15789 addPredicates(NewPreds);
15790
15791 RewriteMap[SE.getSCEV(V)] = {Generation, New};
15792 return New;
15793}
15794
15797 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
15798 Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates(),
15799 SE)),
15800 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {}
15801
15803 // For each block.
15804 for (auto *BB : L.getBlocks())
15805 for (auto &I : *BB) {
15806 if (!SE.isSCEVable(I.getType()))
15807 continue;
15808
15809 auto *Expr = SE.getSCEV(&I);
15810 auto II = RewriteMap.find(Expr);
15811
15812 if (II == RewriteMap.end())
15813 continue;
15814
15815 // Don't print things that are not interesting.
15816 if (II->second.second == Expr)
15817 continue;
15818
15819 OS.indent(Depth) << "[PSE]" << I << ":\n";
15820 OS.indent(Depth + 2) << *Expr << "\n";
15821 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
15822 }
15823}
15824
15827 BasicBlock *Header = L->getHeader();
15828 BasicBlock *Pred = L->getLoopPredecessor();
15829 LoopGuards Guards(SE);
15830 if (!Pred)
15831 return Guards;
15833 collectFromBlock(SE, Guards, Header, Pred, VisitedBlocks);
15834 return Guards;
15835}
15836
15837void ScalarEvolution::LoopGuards::collectFromPHI(
15841 unsigned Depth) {
15842 if (!SE.isSCEVable(Phi.getType()))
15843 return;
15844
15845 using MinMaxPattern = std::pair<const SCEVConstant *, SCEVTypes>;
15846 auto GetMinMaxConst = [&](unsigned IncomingIdx) -> MinMaxPattern {
15847 const BasicBlock *InBlock = Phi.getIncomingBlock(IncomingIdx);
15848 if (!VisitedBlocks.insert(InBlock).second)
15849 return {nullptr, scCouldNotCompute};
15850
15851 // Avoid analyzing unreachable blocks so that we don't get trapped
15852 // traversing cycles with ill-formed dominance or infinite cycles
15853 if (!SE.DT.isReachableFromEntry(InBlock))
15854 return {nullptr, scCouldNotCompute};
15855
15856 auto [G, Inserted] = IncomingGuards.try_emplace(InBlock, LoopGuards(SE));
15857 if (Inserted)
15858 collectFromBlock(SE, G->second, Phi.getParent(), InBlock, VisitedBlocks,
15859 Depth + 1);
15860 auto &RewriteMap = G->second.RewriteMap;
15861 if (RewriteMap.empty())
15862 return {nullptr, scCouldNotCompute};
15863 auto S = RewriteMap.find(SE.getSCEV(Phi.getIncomingValue(IncomingIdx)));
15864 if (S == RewriteMap.end())
15865 return {nullptr, scCouldNotCompute};
15866 auto *SM = dyn_cast_if_present<SCEVMinMaxExpr>(S->second);
15867 if (!SM)
15868 return {nullptr, scCouldNotCompute};
15869 if (const SCEVConstant *C0 = dyn_cast<SCEVConstant>(SM->getOperand(0)))
15870 return {C0, SM->getSCEVType()};
15871 return {nullptr, scCouldNotCompute};
15872 };
15873 auto MergeMinMaxConst = [](MinMaxPattern P1,
15874 MinMaxPattern P2) -> MinMaxPattern {
15875 auto [C1, T1] = P1;
15876 auto [C2, T2] = P2;
15877 if (!C1 || !C2 || T1 != T2)
15878 return {nullptr, scCouldNotCompute};
15879 switch (T1) {
15880 case scUMaxExpr:
15881 return {C1->getAPInt().ult(C2->getAPInt()) ? C1 : C2, T1};
15882 case scSMaxExpr:
15883 return {C1->getAPInt().slt(C2->getAPInt()) ? C1 : C2, T1};
15884 case scUMinExpr:
15885 return {C1->getAPInt().ugt(C2->getAPInt()) ? C1 : C2, T1};
15886 case scSMinExpr:
15887 return {C1->getAPInt().sgt(C2->getAPInt()) ? C1 : C2, T1};
15888 default:
15889 llvm_unreachable("Trying to merge non-MinMaxExpr SCEVs.");
15890 }
15891 };
15892 auto P = GetMinMaxConst(0);
15893 for (unsigned int In = 1; In < Phi.getNumIncomingValues(); In++) {
15894 if (!P.first)
15895 break;
15896 P = MergeMinMaxConst(P, GetMinMaxConst(In));
15897 }
15898 if (P.first) {
15899 const SCEV *LHS = SE.getSCEV(const_cast<PHINode *>(&Phi));
15900 SmallVector<SCEVUse, 2> Ops({P.first, LHS});
15901 const SCEV *RHS = SE.getMinMaxExpr(P.second, Ops);
15902 Guards.RewriteMap.insert({LHS, RHS});
15903 }
15904}
15905
15906// Return a new SCEV that modifies \p Expr to the closest number divides by
15907// \p Divisor and less or equal than Expr. For now, only handle constant
15908// Expr.
15910 const APInt &DivisorVal,
15911 ScalarEvolution &SE) {
15912 const APInt *ExprVal;
15913 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15914 DivisorVal.isNonPositive())
15915 return Expr;
15916 APInt Rem = ExprVal->urem(DivisorVal);
15917 // return the SCEV: Expr - Expr % Divisor
15918 return SE.getConstant(*ExprVal - Rem);
15919}
15920
15921// Return a new SCEV that modifies \p Expr to the closest number divides by
15922// \p Divisor and greater or equal than Expr. For now, only handle constant
15923// Expr.
15924static const SCEV *getNextSCEVDivisibleByDivisor(const SCEV *Expr,
15925 const APInt &DivisorVal,
15926 ScalarEvolution &SE) {
15927 const APInt *ExprVal;
15928 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15929 DivisorVal.isNonPositive())
15930 return Expr;
15931 APInt Rem = ExprVal->urem(DivisorVal);
15932 if (Rem.isZero())
15933 return Expr;
15934 // return the SCEV: Expr + Divisor - Expr % Divisor
15935 return SE.getConstant(*ExprVal + DivisorVal - Rem);
15936}
15937
15939 ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS,
15942 // If we have LHS == 0, check if LHS is computing a property of some unknown
15943 // SCEV %v which we can rewrite %v to express explicitly.
15945 return false;
15946 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
15947 // explicitly express that.
15948 const SCEVUnknown *URemLHS = nullptr;
15949 const SCEV *URemRHS = nullptr;
15950 if (!match(LHS, m_scev_URem(m_SCEVUnknown(URemLHS), m_SCEV(URemRHS), SE)))
15951 return false;
15952
15953 const SCEV *Multiple =
15954 SE.getMulExpr(SE.getUDivExpr(URemLHS, URemRHS), URemRHS);
15955 DivInfo[URemLHS] = Multiple;
15956 if (auto *C = dyn_cast<SCEVConstant>(URemRHS))
15957 Multiples[URemLHS] = C->getAPInt();
15958 return true;
15959}
15960
15961// Check if the condition is a divisibility guard (A % B == 0).
15962static bool isDivisibilityGuard(const SCEV *LHS, const SCEV *RHS,
15963 ScalarEvolution &SE) {
15964 const SCEV *X, *Y;
15965 return match(LHS, m_scev_URem(m_SCEV(X), m_SCEV(Y), SE)) && RHS->isZero();
15966}
15967
15968// Apply divisibility by \p Divisor on MinMaxExpr with constant values,
15969// recursively. This is done by aligning up/down the constant value to the
15970// Divisor.
15971static const SCEV *applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr,
15972 APInt Divisor,
15973 ScalarEvolution &SE) {
15974 // Return true if \p Expr is a MinMax SCEV expression with a non-negative
15975 // constant operand. If so, return in \p SCTy the SCEV type and in \p RHS
15976 // the non-constant operand and in \p LHS the constant operand.
15977 auto IsMinMaxSCEVWithNonNegativeConstant =
15978 [&](const SCEV *Expr, SCEVTypes &SCTy, const SCEV *&LHS,
15979 const SCEV *&RHS) {
15980 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr)) {
15981 if (MinMax->getNumOperands() != 2)
15982 return false;
15983 if (auto *C = dyn_cast<SCEVConstant>(MinMax->getOperand(0))) {
15984 if (C->getAPInt().isNegative())
15985 return false;
15986 SCTy = MinMax->getSCEVType();
15987 LHS = MinMax->getOperand(0);
15988 RHS = MinMax->getOperand(1);
15989 return true;
15990 }
15991 }
15992 return false;
15993 };
15994
15995 const SCEV *MinMaxLHS = nullptr, *MinMaxRHS = nullptr;
15996 SCEVTypes SCTy;
15997 if (!IsMinMaxSCEVWithNonNegativeConstant(MinMaxExpr, SCTy, MinMaxLHS,
15998 MinMaxRHS))
15999 return MinMaxExpr;
16000 auto IsMin = isa<SCEVSMinExpr>(MinMaxExpr) || isa<SCEVUMinExpr>(MinMaxExpr);
16001 assert(SE.isKnownNonNegative(MinMaxLHS) && "Expected non-negative operand!");
16002 auto *DivisibleExpr =
16003 IsMin ? getPreviousSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE)
16004 : getNextSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE);
16006 applyDivisibilityOnMinMaxExpr(MinMaxRHS, Divisor, SE), DivisibleExpr};
16007 return SE.getMinMaxExpr(SCTy, Ops);
16008}
16009
16010void ScalarEvolution::LoopGuards::collectFromBlock(
16011 ScalarEvolution &SE, ScalarEvolution::LoopGuards &Guards,
16012 const BasicBlock *Block, const BasicBlock *Pred,
16013 SmallPtrSetImpl<const BasicBlock *> &VisitedBlocks, unsigned Depth) {
16014
16016
16017 SmallVector<SCEVUse> ExprsToRewrite;
16018 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
16019 const SCEV *RHS,
16020 DenseMap<const SCEV *, const SCEV *> &RewriteMap,
16021 const LoopGuards &DivGuards) {
16022 // WARNING: It is generally unsound to apply any wrap flags to the proposed
16023 // replacement SCEV which isn't directly implied by the structure of that
16024 // SCEV. In particular, using contextual facts to imply flags is *NOT*
16025 // legal. See the scoping rules for flags in the header to understand why.
16026
16027 // Check for a condition of the form (-C1 + X < C2). InstCombine will
16028 // create this form when combining two checks of the form (X u< C2 + C1) and
16029 // (X >=u C1).
16030 auto MatchRangeCheckIdiom = [&SE, Predicate, LHS, RHS, &RewriteMap,
16031 &ExprsToRewrite]() {
16032 const SCEVConstant *C1;
16033 const SCEVUnknown *LHSUnknown;
16034 auto *C2 = dyn_cast<SCEVConstant>(RHS);
16035 if (!match(LHS,
16036 m_scev_Add(m_SCEVConstant(C1), m_SCEVUnknown(LHSUnknown))) ||
16037 !C2)
16038 return false;
16039
16040 auto ExactRegion =
16041 ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt())
16042 .sub(C1->getAPInt());
16043
16044 // Bail out, unless we have a non-wrapping, monotonic range.
16045 if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet())
16046 return false;
16047 auto [I, Inserted] = RewriteMap.try_emplace(LHSUnknown);
16048 const SCEV *RewrittenLHS = Inserted ? LHSUnknown : I->second;
16049 I->second = SE.getUMaxExpr(
16050 SE.getConstant(ExactRegion.getUnsignedMin()),
16051 SE.getUMinExpr(RewrittenLHS,
16052 SE.getConstant(ExactRegion.getUnsignedMax())));
16053 ExprsToRewrite.push_back(LHSUnknown);
16054 return true;
16055 };
16056 if (MatchRangeCheckIdiom())
16057 return;
16058
16059 // Do not apply information for constants or if RHS contains an AddRec.
16061 return;
16062
16063 // If RHS is SCEVUnknown, make sure the information is applied to it.
16065 std::swap(LHS, RHS);
16067 }
16068
16069 // Puts rewrite rule \p From -> \p To into the rewrite map. Also if \p From
16070 // and \p FromRewritten are the same (i.e. there has been no rewrite
16071 // registered for \p From), then puts this value in the list of rewritten
16072 // expressions.
16073 auto AddRewrite = [&](const SCEV *From, const SCEV *FromRewritten,
16074 const SCEV *To) {
16075 if (From == FromRewritten)
16076 ExprsToRewrite.push_back(From);
16077 RewriteMap[From] = To;
16078 };
16079
16080 // Checks whether \p S has already been rewritten. In that case returns the
16081 // existing rewrite because we want to chain further rewrites onto the
16082 // already rewritten value. Otherwise returns \p S.
16083 auto GetMaybeRewritten = [&](const SCEV *S) {
16084 return RewriteMap.lookup_or(S, S);
16085 };
16086
16087 const SCEV *RewrittenLHS = GetMaybeRewritten(LHS);
16088 // Apply divisibility information when computing the constant multiple.
16089 const APInt &DividesBy =
16090 SE.getConstantMultiple(DivGuards.rewrite(RewrittenLHS));
16091
16092 // Collect rewrites for LHS and its transitive operands based on the
16093 // condition.
16094 // For min/max expressions, also apply the guard to its operands:
16095 // 'min(a, b) >= c' -> '(a >= c) and (b >= c)',
16096 // 'min(a, b) > c' -> '(a > c) and (b > c)',
16097 // 'max(a, b) <= c' -> '(a <= c) and (b <= c)',
16098 // 'max(a, b) < c' -> '(a < c) and (b < c)'.
16099
16100 // We cannot express strict predicates in SCEV, so instead we replace them
16101 // with non-strict ones against plus or minus one of RHS depending on the
16102 // predicate.
16103 const SCEV *One = SE.getOne(RHS->getType());
16104 switch (Predicate) {
16105 case CmpInst::ICMP_ULT:
16106 if (RHS->getType()->isPointerTy())
16107 return;
16108 RHS = SE.getUMaxExpr(RHS, One);
16109 [[fallthrough]];
16110 case CmpInst::ICMP_SLT: {
16111 RHS = SE.getMinusSCEV(RHS, One);
16112 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16113 break;
16114 }
16115 case CmpInst::ICMP_UGT:
16116 case CmpInst::ICMP_SGT:
16117 RHS = SE.getAddExpr(RHS, One);
16118 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16119 break;
16120 case CmpInst::ICMP_ULE:
16121 case CmpInst::ICMP_SLE:
16122 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16123 break;
16124 case CmpInst::ICMP_UGE:
16125 case CmpInst::ICMP_SGE:
16126 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16127 break;
16128 default:
16129 break;
16130 }
16131
16132 SmallVector<SCEVUse, 16> Worklist(1, LHS);
16133 SmallPtrSet<const SCEV *, 16> Visited;
16134
16135 auto EnqueueOperands = [&Worklist](const SCEVNAryExpr *S) {
16136 append_range(Worklist, S->operands());
16137 };
16138
16139 while (!Worklist.empty()) {
16140 const SCEV *From = Worklist.pop_back_val();
16141 if (isa<SCEVConstant>(From))
16142 continue;
16143 if (!Visited.insert(From).second)
16144 continue;
16145 const SCEV *FromRewritten = GetMaybeRewritten(From);
16146 const SCEV *To = nullptr;
16147
16148 switch (Predicate) {
16149 case CmpInst::ICMP_ULT:
16150 case CmpInst::ICMP_ULE:
16151 To = SE.getUMinExpr(FromRewritten, RHS);
16152 if (auto *UMax = dyn_cast<SCEVUMaxExpr>(FromRewritten))
16153 EnqueueOperands(UMax);
16154 break;
16155 case CmpInst::ICMP_SLT:
16156 case CmpInst::ICMP_SLE:
16157 To = SE.getSMinExpr(FromRewritten, RHS);
16158 if (auto *SMax = dyn_cast<SCEVSMaxExpr>(FromRewritten))
16159 EnqueueOperands(SMax);
16160 break;
16161 case CmpInst::ICMP_UGT:
16162 case CmpInst::ICMP_UGE:
16163 To = SE.getUMaxExpr(FromRewritten, RHS);
16164 if (auto *UMin = dyn_cast<SCEVUMinExpr>(FromRewritten))
16165 EnqueueOperands(UMin);
16166 break;
16167 case CmpInst::ICMP_SGT:
16168 case CmpInst::ICMP_SGE:
16169 To = SE.getSMaxExpr(FromRewritten, RHS);
16170 if (auto *SMin = dyn_cast<SCEVSMinExpr>(FromRewritten))
16171 EnqueueOperands(SMin);
16172 break;
16173 case CmpInst::ICMP_EQ:
16175 To = RHS;
16176 break;
16177 case CmpInst::ICMP_NE:
16178 if (match(RHS, m_scev_Zero())) {
16179 const SCEV *OneAlignedUp =
16180 getNextSCEVDivisibleByDivisor(One, DividesBy, SE);
16181 To = SE.getUMaxExpr(FromRewritten, OneAlignedUp);
16182 } else {
16183 // LHS != RHS can be rewritten as (LHS - RHS) = UMax(1, LHS - RHS),
16184 // but creating the subtraction eagerly is expensive. Track the
16185 // inequalities in a separate map, and materialize the rewrite lazily
16186 // when encountering a suitable subtraction while re-writing.
16187 if (LHS->getType()->isPointerTy()) {
16191 break;
16192 }
16193 const SCEVConstant *C;
16194 const SCEV *A, *B;
16197 RHS = A;
16198 LHS = B;
16199 }
16200 if (LHS > RHS)
16201 std::swap(LHS, RHS);
16202 Guards.NotEqual.insert({LHS, RHS});
16203 continue;
16204 }
16205 break;
16206 default:
16207 break;
16208 }
16209
16210 if (To)
16211 AddRewrite(From, FromRewritten, To);
16212 }
16213 };
16214
16216 // First, collect information from assumptions dominating the loop.
16217 for (auto &AssumeVH : SE.AC.assumptions()) {
16218 if (!AssumeVH)
16219 continue;
16220 auto *AssumeI = cast<CallInst>(AssumeVH);
16221 if (!SE.DT.dominates(AssumeI, Block))
16222 continue;
16223 Terms.emplace_back(AssumeI->getOperand(0), true);
16224 }
16225
16226 // Second, collect information from llvm.experimental.guards dominating the loop.
16227 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
16228 SE.F.getParent(), Intrinsic::experimental_guard);
16229 if (GuardDecl)
16230 for (const auto *GU : GuardDecl->users())
16231 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
16232 if (Guard->getFunction() == Block->getParent() &&
16233 SE.DT.dominates(Guard, Block))
16234 Terms.emplace_back(Guard->getArgOperand(0), true);
16235
16236 // Third, collect conditions from dominating branches. Starting at the loop
16237 // predecessor, climb up the predecessor chain, as long as there are
16238 // predecessors that can be found that have unique successors leading to the
16239 // original header.
16240 // TODO: share this logic with isLoopEntryGuardedByCond.
16241 unsigned NumCollectedConditions = 0;
16243 std::pair<const BasicBlock *, const BasicBlock *> Pair(Pred, Block);
16244 for (; Pair.first;
16245 Pair = SE.getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
16246 VisitedBlocks.insert(Pair.second);
16247 const CondBrInst *LoopEntryPredicate =
16248 dyn_cast<CondBrInst>(Pair.first->getTerminator());
16249 if (!LoopEntryPredicate)
16250 continue;
16251
16252 Terms.emplace_back(LoopEntryPredicate->getCondition(),
16253 LoopEntryPredicate->getSuccessor(0) == Pair.second);
16254 NumCollectedConditions++;
16255
16256 // If we are recursively collecting guards stop after 2
16257 // conditions to limit compile-time impact for now.
16258 if (Depth > 0 && NumCollectedConditions == 2)
16259 break;
16260 }
16261 // Finally, if we stopped climbing the predecessor chain because
16262 // there wasn't a unique one to continue, try to collect conditions
16263 // for PHINodes by recursively following all of their incoming
16264 // blocks and try to merge the found conditions to build a new one
16265 // for the Phi.
16266 if (Pair.second->hasNPredecessorsOrMore(2) &&
16268 SmallDenseMap<const BasicBlock *, LoopGuards> IncomingGuards;
16269 for (auto &Phi : Pair.second->phis())
16270 collectFromPHI(SE, Guards, Phi, VisitedBlocks, IncomingGuards, Depth);
16271 }
16272
16273 // Now apply the information from the collected conditions to
16274 // Guards.RewriteMap. Conditions are processed in reverse order, so the
16275 // earliest conditions is processed first, except guards with divisibility
16276 // information, which are moved to the back. This ensures the SCEVs with the
16277 // shortest dependency chains are constructed first.
16279 GuardsToProcess;
16280 for (auto [Term, EnterIfTrue] : reverse(Terms)) {
16281 SmallVector<Value *, 8> Worklist;
16282 SmallPtrSet<Value *, 8> Visited;
16283 Worklist.push_back(Term);
16284 while (!Worklist.empty()) {
16285 Value *Cond = Worklist.pop_back_val();
16286 if (!Visited.insert(Cond).second)
16287 continue;
16288
16289 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
16290 auto Predicate =
16291 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
16292 const auto *LHS = SE.getSCEV(Cmp->getOperand(0));
16293 const auto *RHS = SE.getSCEV(Cmp->getOperand(1));
16294 // If LHS is a constant, apply information to the other expression.
16295 // TODO: If LHS is not a constant, check if using CompareSCEVComplexity
16296 // can improve results.
16297 if (isa<SCEVConstant>(LHS)) {
16298 std::swap(LHS, RHS);
16300 }
16301 GuardsToProcess.emplace_back(Predicate, LHS, RHS);
16302 continue;
16303 }
16304
16305 Value *L, *R;
16306 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
16307 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
16308 Worklist.push_back(L);
16309 Worklist.push_back(R);
16310 }
16311 }
16312 }
16313
16314 // Process divisibility guards in reverse order to populate DivGuards early.
16315 DenseMap<const SCEV *, APInt> Multiples;
16316 LoopGuards DivGuards(SE);
16317 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess) {
16318 if (!isDivisibilityGuard(LHS, RHS, SE))
16319 continue;
16320 collectDivisibilityInformation(Predicate, LHS, RHS, DivGuards.RewriteMap,
16321 Multiples, SE);
16322 }
16323
16324 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess)
16325 CollectCondition(Predicate, LHS, RHS, Guards.RewriteMap, DivGuards);
16326
16327 // Apply divisibility information last. This ensures it is applied to the
16328 // outermost expression after other rewrites for the given value.
16329 for (const auto &[K, Divisor] : Multiples) {
16330 const SCEV *DivisorSCEV = SE.getConstant(Divisor);
16331 Guards.RewriteMap[K] =
16333 Guards.rewrite(K), Divisor, SE),
16334 DivisorSCEV),
16335 DivisorSCEV);
16336 ExprsToRewrite.push_back(K);
16337 }
16338
16339 // Let the rewriter preserve NUW/NSW flags if the unsigned/signed ranges of
16340 // the replacement expressions are contained in the ranges of the replaced
16341 // expressions.
16342 Guards.PreserveNUW = true;
16343 Guards.PreserveNSW = true;
16344 for (const SCEV *Expr : ExprsToRewrite) {
16345 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16346 Guards.PreserveNUW &=
16347 SE.getUnsignedRange(Expr).contains(SE.getUnsignedRange(RewriteTo));
16348 Guards.PreserveNSW &=
16349 SE.getSignedRange(Expr).contains(SE.getSignedRange(RewriteTo));
16350 }
16351
16352 // Now that all rewrite information is collect, rewrite the collected
16353 // expressions with the information in the map. This applies information to
16354 // sub-expressions.
16355 if (ExprsToRewrite.size() > 1) {
16356 for (const SCEV *Expr : ExprsToRewrite) {
16357 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16358 Guards.RewriteMap.erase(Expr);
16359 Guards.RewriteMap.insert({Expr, Guards.rewrite(RewriteTo)});
16360 }
16361 }
16362}
16363
16365 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
16366 /// in the map. It skips AddRecExpr because we cannot guarantee that the
16367 /// replacement is loop invariant in the loop of the AddRec.
16368 class SCEVLoopGuardRewriter
16369 : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
16372
16374
16375 public:
16376 SCEVLoopGuardRewriter(ScalarEvolution &SE,
16377 const ScalarEvolution::LoopGuards &Guards)
16378 : SCEVRewriteVisitor(SE), Map(Guards.RewriteMap),
16379 NotEqual(Guards.NotEqual) {
16380 if (Guards.PreserveNUW)
16381 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNUW);
16382 if (Guards.PreserveNSW)
16383 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNSW);
16384 }
16385
16386 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
16387
16388 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
16389 return Map.lookup_or(Expr, Expr);
16390 }
16391
16392 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
16393 if (const SCEV *S = Map.lookup(Expr))
16394 return S;
16395
16396 // If we didn't find the extact ZExt expr in the map, check if there's
16397 // an entry for a smaller ZExt we can use instead.
16398 Type *Ty = Expr->getType();
16399 const SCEV *Op = Expr->getOperand(0);
16400 unsigned Bitwidth = Ty->getScalarSizeInBits() / 2;
16401 while (Bitwidth % 8 == 0 && Bitwidth >= 8 &&
16402 Bitwidth > Op->getType()->getScalarSizeInBits()) {
16403 Type *NarrowTy = IntegerType::get(SE.getContext(), Bitwidth);
16404 auto *NarrowExt = SE.getZeroExtendExpr(Op, NarrowTy);
16405 if (const SCEV *S = Map.lookup(NarrowExt))
16406 return SE.getZeroExtendExpr(S, Ty);
16407 Bitwidth = Bitwidth / 2;
16408 }
16409
16411 Expr);
16412 }
16413
16414 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
16415 if (const SCEV *S = Map.lookup(Expr))
16416 return S;
16418 Expr);
16419 }
16420
16421 const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
16422 if (const SCEV *S = Map.lookup(Expr))
16423 return S;
16425 }
16426
16427 const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
16428 if (const SCEV *S = Map.lookup(Expr))
16429 return S;
16431 }
16432
16433 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
16434 // Helper to check if S is a subtraction (A - B) where A != B, and if so,
16435 // return UMax(S, 1).
16436 auto RewriteSubtraction = [&](const SCEV *S) -> const SCEV * {
16437 SCEVUse LHS, RHS;
16438 if (MatchBinarySub(S, LHS, RHS)) {
16439 if (LHS > RHS)
16440 std::swap(LHS, RHS);
16441 if (NotEqual.contains({LHS, RHS})) {
16442 const SCEV *OneAlignedUp = getNextSCEVDivisibleByDivisor(
16443 SE.getOne(S->getType()), SE.getConstantMultiple(S), SE);
16444 return SE.getUMaxExpr(OneAlignedUp, S);
16445 }
16446 }
16447 return nullptr;
16448 };
16449
16450 // Check if Expr itself is a subtraction pattern with guard info.
16451 if (const SCEV *Rewritten = RewriteSubtraction(Expr))
16452 return Rewritten;
16453
16454 // Trip count expressions sometimes consist of adding 3 operands, i.e.
16455 // (Const + A + B). There may be guard info for A + B, and if so, apply
16456 // it.
16457 // TODO: Could more generally apply guards to Add sub-expressions.
16458 if (isa<SCEVConstant>(Expr->getOperand(0)) &&
16459 Expr->getNumOperands() == 3) {
16460 const SCEV *Add =
16461 SE.getAddExpr(Expr->getOperand(1), Expr->getOperand(2));
16462 if (const SCEV *Rewritten = RewriteSubtraction(Add))
16463 return SE.getAddExpr(
16464 Expr->getOperand(0), Rewritten,
16465 ScalarEvolution::maskFlags(Expr->getNoWrapFlags(), FlagMask));
16466 if (const SCEV *S = Map.lookup(Add))
16467 return SE.getAddExpr(Expr->getOperand(0), S);
16468 }
16469 SmallVector<SCEVUse, 2> Operands;
16470 bool Changed = false;
16471 for (SCEVUse Op : Expr->operands()) {
16472 Operands.push_back(
16474 Changed |= Op != Operands.back();
16475 }
16476 // We are only replacing operands with equivalent values, so transfer the
16477 // flags from the original expression.
16478 return !Changed ? Expr
16479 : SE.getAddExpr(Operands,
16481 Expr->getNoWrapFlags(), FlagMask));
16482 }
16483
16484 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
16485 SmallVector<SCEVUse, 2> Operands;
16486 bool Changed = false;
16487 for (SCEVUse Op : Expr->operands()) {
16488 Operands.push_back(
16490 Changed |= Op != Operands.back();
16491 }
16492 // We are only replacing operands with equivalent values, so transfer the
16493 // flags from the original expression.
16494 return !Changed ? Expr
16495 : SE.getMulExpr(Operands,
16497 Expr->getNoWrapFlags(), FlagMask));
16498 }
16499 };
16500
16501 if (RewriteMap.empty() && NotEqual.empty())
16502 return Expr;
16503
16504 SCEVLoopGuardRewriter Rewriter(SE, *this);
16505 return Rewriter.visit(Expr);
16506}
16507
16508const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
16509 return applyLoopGuards(Expr, LoopGuards::collect(L, *this));
16510}
16511
16513 const LoopGuards &Guards) {
16514 return Guards.rewrite(Expr);
16515}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
constexpr LLT S1
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
@ PostInc
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:672
This file contains the declarations for the subclasses of Constant, which represent the different fla...
SmallPtrSet< const BasicBlock *, 8 > VisitedBlocks
This file defines the DenseMap class.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
static bool isSigned(unsigned Opcode)
This file defines a hash set that can be used to remove duplication of nodes in a graph.
#define op(i)
Hexagon Common GEP
Value * getPointer(Value *Ptr)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This defines the Use class.
iv Induction Variable Users
Definition IVUsers.cpp:48
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:539
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define T
#define T1
MachineInstr unsigned OpIdx
static constexpr unsigned SM(unsigned Version)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
ppc ctr loops verify
PowerPC Reduce CR logical Operation
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
R600 Clause Merge
const SmallVectorImpl< MachineOperand > & Cond
static DominatorTree getDomTree(Function &F)
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
SI optimize exec mask operations pre RA
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
This file contains some templates that are useful if you are working with the STL at all.
This file provides utility classes that use RAII to save and restore values.
bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind, SCEVTypes RootKind)
static cl::opt< unsigned > MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, cl::desc("Max coefficients in AddRec during evolving"), cl::init(8))
static cl::opt< unsigned > RangeIterThreshold("scev-range-iter-threshold", cl::Hidden, cl::desc("Threshold for switching to iteratively computing SCEV ranges"), cl::init(32))
static const Loop * isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI)
static unsigned getConstantTripCount(const SCEVConstant *ExitCount)
static int CompareValueComplexity(const LoopInfo *const LI, Value *LV, Value *RV, unsigned Depth)
Compare the two values LV and RV in terms of their "complexity" where "complexity" is a partial (and ...
static const SCEV * getNextSCEVDivisibleByDivisor(const SCEV *Expr, const APInt &DivisorVal, ScalarEvolution &SE)
static void insertFoldCacheEntry(const ScalarEvolution::FoldID &ID, const SCEV *S, DenseMap< ScalarEvolution::FoldID, const SCEV * > &FoldCache, DenseMap< const SCEV *, SmallVector< ScalarEvolution::FoldID, 2 > > &FoldCacheUser)
static cl::opt< bool > ClassifyExpressions("scalar-evolution-classify-expressions", cl::Hidden, cl::init(true), cl::desc("When printing analysis, include information on every instruction"))
static bool hasHugeExpression(ArrayRef< SCEVUse > Ops)
Returns true if Ops contains a huge SCEV (the subtree of S contains at least HugeExprThreshold nodes)...
static bool CanConstantFold(const Instruction *I)
Return true if we can constant fold an instruction of the specified type, assuming that all operands ...
static cl::opt< unsigned > AddOpsInlineThreshold("scev-addops-inline-threshold", cl::Hidden, cl::desc("Threshold for inlining addition operands into a SCEV"), cl::init(500))
static cl::opt< unsigned > MaxLoopGuardCollectionDepth("scalar-evolution-max-loop-guard-collection-depth", cl::Hidden, cl::desc("Maximum depth for recursive loop guard collection"), cl::init(1))
static cl::opt< bool > VerifyIR("scev-verify-ir", cl::Hidden, cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), cl::init(false))
static bool RangeRefPHIAllowedOperands(DominatorTree &DT, PHINode *PHI)
static const SCEV * getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, ScalarEvolution *SE, unsigned Depth)
static std::optional< APInt > MinOptional(std::optional< APInt > X, std::optional< APInt > Y)
Helper function to compare optional APInts: (a) if X and Y both exist, return min(X,...
static cl::opt< unsigned > MulOpsInlineThreshold("scev-mulops-inline-threshold", cl::Hidden, cl::desc("Threshold for inlining multiplication operands into a SCEV"), cl::init(32))
static BinaryOperator * getCommonInstForPHI(PHINode *PN)
static bool isDivisibilityGuard(const SCEV *LHS, const SCEV *RHS, ScalarEvolution &SE)
static std::optional< const SCEV * > createNodeForSelectViaUMinSeq(ScalarEvolution *SE, const SCEV *CondExpr, const SCEV *TrueExpr, const SCEV *FalseExpr)
static Constant * BuildConstantFromSCEV(const SCEV *V)
This builds up a Constant using the ConstantExpr interface.
static ConstantInt * EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, ScalarEvolution &SE)
static const SCEV * BinomialCoefficient(const SCEV *It, unsigned K, ScalarEvolution &SE, Type *ResultTy)
Compute BC(It, K). The result has width W. Assume, K > 0.
static cl::opt< unsigned > MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), cl::init(8))
static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, const SCEV *Candidate)
Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
static PHINode * getConstantEvolvingPHI(Value *V, const Loop *L)
getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node in the loop that V is deri...
static const SCEV * SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, SmallVectorImpl< const SCEVPredicate * > *Predicates, ScalarEvolution &SE, const Loop *L)
Finds the minimum unsigned root of the following equation:
static cl::opt< unsigned > MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, cl::desc("Maximum number of iterations SCEV will " "symbolically execute a constant " "derived loop"), cl::init(100))
static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow)
static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV *S)
When printing a top-level SCEV for trip counts, it's helpful to include a type for constants which ar...
static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, const Loop *L)
static SCEV::NoWrapFlags StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, ArrayRef< SCEVUse > Ops, SCEV::NoWrapFlags Flags)
static bool containsConstantInAddMulChain(const SCEV *StartExpr)
Determine if any of the operands in this SCEV are a constant or if any of the add or multiply express...
static const SCEV * getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, ScalarEvolution *SE, unsigned Depth)
static bool CollectAddOperandsWithScales(SmallDenseMap< SCEVUse, APInt, 16 > &M, SmallVectorImpl< SCEVUse > &NewOps, APInt &AccumulatedConstant, ArrayRef< SCEVUse > Ops, const APInt &Scale, ScalarEvolution &SE)
Process the given Ops list, which is a list of operands to be added under the given scale,...
static const SCEV * constantFoldAndGroupOps(ScalarEvolution &SE, LoopInfo &LI, DominatorTree &DT, SmallVectorImpl< SCEVUse > &Ops, FoldT Fold, IsIdentityT IsIdentity, IsAbsorberT IsAbsorber)
Performs a number of common optimizations on the passed Ops.
static cl::opt< unsigned > MaxPhiSCCAnalysisSize("scalar-evolution-max-scc-analysis-depth", cl::Hidden, cl::desc("Maximum amount of nodes to process while searching SCEVUnknown " "Phi strongly connected components"), cl::init(8))
static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
static void GroupByComplexity(SmallVectorImpl< SCEVUse > &Ops, LoopInfo *LI, DominatorTree &DT)
Given a list of SCEV objects, order them by their complexity, and group objects of the same complexit...
static bool collectDivisibilityInformation(ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS, DenseMap< const SCEV *, const SCEV * > &DivInfo, DenseMap< const SCEV *, APInt > &Multiples, ScalarEvolution &SE)
static cl::opt< unsigned > MaxSCEVOperationsImplicationDepth("scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, cl::desc("Maximum depth of recursive SCEV operations implication analysis"), cl::init(2))
static void PushDefUseChildren(Instruction *I, SmallVectorImpl< Instruction * > &Worklist, SmallPtrSetImpl< Instruction * > &Visited)
Push users of the given Instruction onto the given Worklist.
static std::optional< APInt > SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, const ConstantRange &Range, ScalarEvolution &SE)
Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n iterations.
static cl::opt< bool > UseContextForNoWrapFlagInference("scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden, cl::desc("Infer nuw/nsw flags using context where suitable"), cl::init(true))
static cl::opt< bool > EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden, cl::desc("Handle <= and >= in finite loops"), cl::init(true))
static bool getOperandsForSelectLikePHI(DominatorTree &DT, PHINode *PN, Value *&Cond, Value *&LHS, Value *&RHS)
static std::optional< std::tuple< APInt, APInt, APInt, APInt, unsigned > > GetQuadraticEquation(const SCEVAddRecExpr *AddRec)
For a given quadratic addrec, generate coefficients of the corresponding quadratic equation,...
static bool isKnownPredicateExtendIdiom(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
static std::optional< BinaryOp > MatchBinaryOp(Value *V, const DataLayout &DL, AssumptionCache &AC, const DominatorTree &DT, const Instruction *CxtI)
Try to map V into a BinaryOp, and return std::nullopt on failure.
static std::optional< APInt > SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE)
Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n iterations.
static std::optional< APInt > TruncIfPossible(std::optional< APInt > X, unsigned BitWidth)
Helper function to truncate an optional APInt to a given BitWidth.
static cl::opt< unsigned > MaxSCEVCompareDepth("scalar-evolution-max-scev-compare-depth", cl::Hidden, cl::desc("Maximum depth of recursive SCEV complexity comparisons"), cl::init(32))
static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, const SCEVConstant *ConstantTerm, const SCEVAddExpr *WholeAddExpr)
static cl::opt< unsigned > MaxConstantEvolvingDepth("scalar-evolution-max-constant-evolving-depth", cl::Hidden, cl::desc("Maximum depth of recursive constant evolving"), cl::init(32))
static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS)
static std::optional< ConstantRange > GetRangeFromMetadata(Value *V)
Helper method to assign a range to V from metadata present in the IR.
static cl::opt< unsigned > HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, cl::desc("Size of the expression which is considered huge"), cl::init(4096))
static Type * isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, bool &Signed, ScalarEvolution &SE)
Helper function to createAddRecFromPHIWithCasts.
static Constant * EvaluateExpression(Value *V, const Loop *L, DenseMap< Instruction *, Constant * > &Vals, const DataLayout &DL, const TargetLibraryInfo *TLI)
EvaluateExpression - Given an expression that passes the getConstantEvolvingPHI predicate,...
static const SCEV * getPreviousSCEVDivisibleByDivisor(const SCEV *Expr, const APInt &DivisorVal, ScalarEvolution &SE)
static const SCEV * MatchNotExpr(const SCEV *Expr)
If Expr computes ~A, return A else return nullptr.
static std::pair< ConstantRange, bool > getRangeForAffineARHelper(APInt Step, const ConstantRange &StartRange, const APInt &MaxBECount, bool Signed)
static cl::opt< unsigned > MaxValueCompareDepth("scalar-evolution-max-value-compare-depth", cl::Hidden, cl::desc("Maximum depth of recursive value complexity comparisons"), cl::init(2))
static const SCEV * applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr, APInt Divisor, ScalarEvolution &SE)
static cl::opt< bool, true > VerifySCEVOpt("verify-scev", cl::Hidden, cl::location(VerifySCEV), cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"))
static const SCEV * getSignedOverflowLimitForStep(const SCEV *Step, ICmpInst::Predicate *Pred, ScalarEvolution *SE)
static cl::opt< unsigned > MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, cl::desc("Maximum depth of recursive arithmetics"), cl::init(32))
static bool HasSameValue(const SCEV *A, const SCEV *B)
SCEV structural equivalence is usually sufficient for testing whether two expressions are equal,...
static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow)
Compute the result of "n choose k", the binomial coefficient.
static std::optional< int > CompareSCEVComplexity(const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, DominatorTree &DT, unsigned Depth=0)
static bool canConstantEvolve(Instruction *I, const Loop *L)
Determine whether this instruction can constant evolve within this loop assuming its operands can all...
static PHINode * getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, DenseMap< Instruction *, PHINode * > &PHIMap, unsigned Depth)
getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by recursing through each instructi...
static bool scevUnconditionallyPropagatesPoisonFromOperands(SCEVTypes Kind)
static cl::opt< bool > VerifySCEVStrict("verify-scev-strict", cl::Hidden, cl::desc("Enable stricter verification with -verify-scev is passed"))
static Constant * getOtherIncomingValue(PHINode *PN, BasicBlock *BB)
static cl::opt< bool > UseExpensiveRangeSharpening("scalar-evolution-use-expensive-range-sharpening", cl::Hidden, cl::init(false), cl::desc("Use more powerful methods of sharpening expression ranges. May " "be costly in terms of compile time"))
static const SCEV * getUnsignedOverflowLimitForStep(const SCEV *Step, ICmpInst::Predicate *Pred, ScalarEvolution *SE)
static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Is LHS Pred RHS true on the virtue of LHS or RHS being a Min or Max expression?
static bool BrPHIToSelect(DominatorTree &DT, CondBrInst *BI, PHINode *Merge, Value *&C, Value *&LHS, Value *&RHS)
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
static bool InBlock(const Value *V, const BasicBlock *BB)
Provides some synthesis utilities to produce sequences of values.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
static std::optional< bool > isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS, const Value *ARHS, const Value *BLHS, const Value *BRHS)
Return true if "icmp Pred BLHS BRHS" is true whenever "icmp PredALHS ARHS" is true.
Virtual Register Rewriter
Value * RHS
Value * LHS
BinaryOperator * Mul
static const uint32_t IV[8]
Definition blake3_impl.h:83
SCEVCastSinkingRewriter(ScalarEvolution &SE, Type *TargetTy, ConversionFn CreatePtrCast)
static const SCEV * rewrite(const SCEV *Scev, ScalarEvolution &SE, Type *TargetTy, ConversionFn CreatePtrCast)
const SCEV * visitUnknown(const SCEVUnknown *Expr)
const SCEV * visitMulExpr(const SCEVMulExpr *Expr)
const SCEV * visitAddExpr(const SCEVAddExpr *Expr)
const SCEV * visit(const SCEV *S)
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2006
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1055
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:424
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1565
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1537
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:968
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:207
APInt abs() const
Get the absolute value.
Definition APInt.h:1820
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1210
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:372
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1191
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:381
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition APInt.h:467
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1692
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1513
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1120
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:210
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:217
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:330
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1175
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1970
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:220
bool isNonPositive() const
Determine if this APInt Value is non-positive (<= 0).
Definition APInt.h:362
unsigned countTrailingZeros() const
Definition APInt.h:1672
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:357
unsigned logBase2() const
Definition APInt.h:1786
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:476
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:834
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1300
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1159
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1028
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:880
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:441
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:307
bool isSignBitSet() const
Determine if sign bit of this APInt is set.
Definition APInt.h:342
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1139
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:201
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition APInt.h:433
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1246
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:240
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1230
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
AnalysisUsage & addRequiredTransitive()
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
MutableArrayRef< WeakVH > assumptions()
Access the list of assumption handles currently tracked for this function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:461
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction & front() const
Definition BasicBlock.h:484
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI unsigned getNoWrapKind() const
Returns one of OBO::NoSignedWrap or OBO::NoUnsignedWrap.
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
This class represents a function call, abstracting a target machine's calling convention.
virtual void deleted()
Callback for Value destruction.
void setValPtr(Value *P)
bool isFalseWhenEqual() const
This is just a convenience.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
bool isSigned() const
Definition InstrTypes.h:993
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
bool isUnsigned() const
Definition InstrTypes.h:999
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Definition InstrTypes.h:989
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
LLVM_ABI CmpInst::Predicate getPreferredSignedPredicate() const
Attempts to return a signed CmpInst::Predicate from the CmpPredicate.
CmpInst::Predicate dropSameSign() const
Drops samesign information.
Conditional Branch instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static LLVM_ABI Constant * getNot(Constant *C)
static Constant * getPtrAdd(Constant *Ptr, Constant *Offset, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReduced=nullptr)
Create a getelementptr i8, ptr, offset constant expression.
Definition Constants.h:1497
static LLVM_ABI Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getPtrToAddr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
This class represents a range of values.
LLVM_ABI ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
LLVM_ABI ConstantRange zextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
LLVM_ABI bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const
Set up Pred and RHS such that ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.
const APInt & getLower() const
Return the lower value for this range.
LLVM_ABI ConstantRange urem(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned remainder operation of...
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI ConstantRange zeroExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
LLVM_ABI bool isSignWrappedSet() const
Return true if this set wraps around the signed domain.
LLVM_ABI APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
LLVM_ABI bool isWrappedSet() const
Return true if this set wraps around the unsigned domain.
LLVM_ABI void print(raw_ostream &OS) const
Print out the bounds to a stream.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
LLVM_ABI ConstantRange signExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
const APInt & getUpper() const
Return the upper value for this range.
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static LLVM_ABI ConstantRange makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp, const ConstantRange &Other, unsigned NoWrapKind)
Produce the largest range containing all X such that "X BinOp Y" is guaranteed not to wrap (overflow)...
LLVM_ABI unsigned getMinSignedBits() const
Compute the maximal number of bits needed to represent every value in this signed range.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
LLVM_ABI ConstantRange sextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
static LLVM_ABI ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp, const APInt &Other, unsigned NoWrapKind)
Produce the range that contains X if and only if "X BinOp Other" does not wrap.
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
LLVM_ABI IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space.
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
LLVM_ABI IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:791
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:250
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:299
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition DenseMap.h:133
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive,...
Definition DenseMap.h:236
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:219
iterator end()
Definition DenseMap.h:141
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:214
void swap(DerivedT &RHS)
Definition DenseMap.h:437
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
Analysis pass which computes a DominatorTree.
Definition Dominators.h:270
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:306
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:151
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This class describes a reference to an interned FoldingSetNodeID, which can be a useful to store node...
Definition FoldingSet.h:171
This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:208
FunctionPass(char &pid)
Definition Pass.h:316
Represents flags for the getelementptr instruction/expression.
bool hasNoUnsignedSignedWrap() const
bool hasNoUnsignedWrap() const
static GEPNoWrapFlags none()
static LLVM_ABI Type * getTypeAtIndex(Type *Ty, Value *Idx)
Return the type of the element at the given index of an indexable type.
Module * getParent()
Get the module that this global value is contained inside of...
static bool isPrivateLinkage(LinkageTypes Linkage)
static bool isInternalLinkage(LinkageTypes Linkage)
This instruction compares its operands according to the predicate given to the constructor.
CmpPredicate getCmpPredicate() const
static bool isGE(Predicate P)
Return true if the predicate is SGE or UGE.
CmpPredicate getSwappedCmpPredicate() const
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
static bool isLT(Predicate P)
Return true if the predicate is SLT or ULT.
CmpPredicate getInverseCmpPredicate() const
Predicate getNonStrictCmpPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
static bool isGT(Predicate P)
Return true if the predicate is SGT or UGT.
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
static CmpPredicate getInverseCmpPredicate(CmpPredicate Pred)
bool isEquality() const
Return true if this predicate is either EQ or NE.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
static bool isLE(Predicate P)
Return true if the predicate is SLE or ULE.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI bool isIdenticalToWhenDefined(const Instruction *I, bool IntersectAttrs=false) const LLVM_READONLY
This is like isIdenticalTo, except that it ignores the SubclassOptionalData flags,...
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:348
A helper class to return the specified delimiter string after the first invocation of operator String...
An instruction for reading from memory.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:587
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getHeader() const
unsigned getLoopDepth() const
Return the nesting level of this loop.
BlockT * getLoopPredecessor() const
If the given loop's header has exactly one unique predecessor outside the loop, return it.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
unsigned getLoopDepth(const BlockT *BB) const
Return the loop nesting level of the specified block.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:612
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:67
Metadata node.
Definition Metadata.h:1069
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition Operator.h:113
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition Operator.h:107
iterator_range< const_block_iterator > blocks() const
op_range incoming_values()
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
PointerIntPair - This class implements a pair of a pointer and small integer.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
LLVM_ABI void addPredicate(const SCEVPredicate &Pred)
Adds a new predicate.
LLVM_ABI const SCEVPredicate & getPredicate() const
LLVM_ABI const SCEV * getPredicatedSCEV(const SCEV *Expr)
Returns the rewritten SCEV for Expr in the context of the current SCEV predicate.
LLVM_ABI bool areAddRecsEqualWithPreds(const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2, ArrayRef< const SCEVPredicate * > ExtraPreds={}) const
Check if AR1 and AR2 are equal, while taking into account Equal predicates in Preds and ExtraPreds.
LLVM_ABI bool hasNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags)
Returns true if we've statically proved that V doesn't wrap.
LLVM_ABI const SCEVAddRecExpr * getAsAddRec(Value *V, SmallVectorImpl< const SCEVPredicate * > *WrapPredsAdded=nullptr)
Attempts to produce an AddRecExpr for V by adding additional SCEV predicates.
LLVM_ABI void print(raw_ostream &OS, unsigned Depth) const
Print the SCEV mappings done by the Predicated Scalar Evolution.
LLVM_ABI PredicatedScalarEvolution(ScalarEvolution &SE, Loop &L)
LLVM_ABI unsigned getSmallConstantMaxTripCount()
Returns the upper bound of the loop trip count as a normal unsigned value, or 0 if the trip count is ...
LLVM_ABI void addPredicates(ArrayRef< const SCEVPredicate * > Preds)
Adds all predicates in Preds.
LLVM_ABI const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSymbolicMaxBackedgeTakenCount()
Get the (predicated) symbolic max backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
constexpr bool isValid() const
Definition Register.h:112
This node represents an addition of some number of SCEVs.
This node represents a polynomial recurrence on the trip count of the specified loop.
LLVM_ABI const SCEV * evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const
Return the value of this chain of recurrences at the specified iteration number.
void setNoWrapFlags(NoWrapFlags Flags)
Set flags for a recurrence without clearing any previously set flags.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
bool isQuadratic() const
Return true if this represents an expression A + B*x + C*x^2 where A, B and C are loop invariant valu...
LLVM_ABI const SCEV * getNumIterationsInRange(const ConstantRange &Range, ScalarEvolution &SE) const
Return the number of iterations of this loop that produce values in the specified constant range.
LLVM_ABI const SCEVAddRecExpr * getPostIncExpr(ScalarEvolution &SE) const
Return an expression representing the value of this expression one iteration of the loop ahead.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This is the base class for unary cast operator classes.
LLVM_ABI SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, SCEVUse op, Type *ty)
void setNoWrapFlags(NoWrapFlags Flags)
Set flags for a non-recurrence without clearing previously set flags.
This class represents an assumption that the expression LHS Pred RHS evaluates to true,...
SCEVComparePredicate(const FoldingSetNodeIDRef ID, const ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
bool isAlwaysTrue() const override
Returns true if the predicate is always true.
void print(raw_ostream &OS, unsigned Depth=0) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Implementation of the SCEVPredicate interface.
This class represents a constant integer value.
ConstantInt * getValue() const
const APInt & getAPInt() const
This is the base class for unary integral cast operator classes.
LLVM_ABI SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, SCEVUse op, Type *ty)
This node is the base class min/max selections.
static enum SCEVTypes negate(enum SCEVTypes T)
This node represents multiplication of some number of SCEVs.
This node is a base class providing common functionality for n'ary operators.
ArrayRef< SCEVUse > operands() const
NoWrapFlags getNoWrapFlags(NoWrapFlags Mask=NoWrapMask) const
SCEVUse getOperand(unsigned i) const
This class represents an assumption made using SCEV expressions which can be checked at run-time.
SCEVPredicate(const SCEVPredicate &)=default
virtual bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const =0
Returns true if this predicate implies N.
SCEVPredicateKind Kind
This class represents a cast from a pointer to a pointer-sized integer value, without capturing the p...
This class represents a cast from a pointer to a pointer-sized integer value.
This visitor recursively visits a SCEV expression and re-writes it.
const SCEV * visitSignExtendExpr(const SCEVSignExtendExpr *Expr)
const SCEV * visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr)
const SCEV * visitSMinExpr(const SCEVSMinExpr *Expr)
const SCEV * visitUMinExpr(const SCEVUMinExpr *Expr)
This class represents a signed minimum selection.
This node is the base class for sequential/in-order min/max selections.
static SCEVTypes getEquivalentNonSequentialSCEVType(SCEVTypes Ty)
This class represents a sign extension of a small integer value to a larger integer value.
Visit all nodes in the expression tree using worklist traversal.
This class represents a truncation of an integer value to a smaller integer value.
This class represents a binary unsigned division operation.
This class represents an unsigned minimum selection.
This class represents a composition of other SCEV predicates, and is the class that most clients will...
void print(raw_ostream &OS, unsigned Depth) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Returns true if this predicate implies N.
SCEVUnionPredicate(ArrayRef< const SCEVPredicate * > Preds, ScalarEvolution &SE)
Union predicates don't get cached so create a dummy set ID for it.
bool isAlwaysTrue() const override
Implementation of the SCEVPredicate interface.
SCEVUnionPredicate getUnionWith(const SCEVPredicate *N, ScalarEvolution &SE) const
Returns a new SCEVUnionPredicate that is the union of this predicate and the given predicate N.
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
This class represents the value of vscale, as used when defining the length of a scalable vector or r...
This class represents an assumption made on an AddRec expression.
IncrementWrapFlags
Similar to SCEV::NoWrapFlags, but with slightly different semantics for FlagNUSW.
SCEVWrapPredicate(const FoldingSetNodeIDRef ID, const SCEVAddRecExpr *AR, IncrementWrapFlags Flags)
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Returns true if this predicate implies N.
static SCEVWrapPredicate::IncrementWrapFlags setFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OnFlags)
void print(raw_ostream &OS, unsigned Depth=0) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool isAlwaysTrue() const override
Returns true if the predicate is always true.
const SCEVAddRecExpr * getExpr() const
Implementation of the SCEVPredicate interface.
static SCEVWrapPredicate::IncrementWrapFlags clearFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OffFlags)
Convenient IncrementWrapFlags manipulation methods.
static SCEVWrapPredicate::IncrementWrapFlags getImpliedFlags(const SCEVAddRecExpr *AR, ScalarEvolution &SE)
Returns the set of SCEVWrapPredicate no wrap flags implied by a SCEVAddRecExpr.
IncrementWrapFlags getFlags() const
Returns the set assumed no overflow flags.
This class represents a zero extension of a small integer value to a larger integer value.
This class represents an analyzed expression in the program.
unsigned short getExpressionSize() const
SCEVNoWrapFlags NoWrapFlags
LLVM_ABI bool isOne() const
Return true if the expression is a constant one.
static constexpr auto FlagNUW
LLVM_ABI void computeAndSetCanonical(ScalarEvolution &SE)
Compute and set the canonical SCEV, by constructing a SCEV with the same operands,...
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
const SCEV * CanonicalSCEV
Pointer to the canonical version of the SCEV, i.e.
static constexpr auto FlagAnyWrap
LLVM_ABI void dump() const
This method is used for debugging.
LLVM_ABI bool isAllOnesValue() const
Return true if the expression is a constant all-ones value.
LLVM_ABI bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
static constexpr auto FlagNSW
LLVM_ABI ArrayRef< SCEVUse > operands() const
Return operands of this SCEV expression.
LLVM_ABI void print(raw_ostream &OS) const
Print out the internal representation of this scalar to the specified stream.
SCEV(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, unsigned short ExpressionSize)
SCEVTypes getSCEVType() const
static constexpr auto FlagNW
LLVM_ABI Type * getType() const
Return the LLVM type of this SCEV expression.
Analysis pass that exposes the ScalarEvolution for a function.
LLVM_ABI ScalarEvolution run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void print(raw_ostream &OS, const Module *=nullptr) const override
print - Print out the internal state of the pass.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
static LLVM_ABI LoopGuards collect(const Loop *L, ScalarEvolution &SE)
Collect rewrite map for loop guards for loop L, together with flags indicating if NUW and NSW can be ...
LLVM_ABI const SCEV * rewrite(const SCEV *Expr) const
Try to apply the collected loop guards to Expr.
The main scalar evolution driver.
LLVM_ABI const SCEV * getUDivExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
const SCEV * getConstantMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
static bool hasFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags TestFlags)
const DataLayout & getDataLayout() const
Return the DataLayout associated with the module this SCEV instance is operating on.
LLVM_ABI bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
LLVM_ABI bool isKnownOnEveryIteration(CmpPredicate Pred, const SCEVAddRecExpr *LHS, const SCEV *RHS)
Test if the condition described by Pred, LHS, RHS is known to be true on every iteration of the loop ...
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantExitCondDuringFirstIterationsImpl(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI, const SCEV *MaxIter)
LLVM_ABI const SCEV * getUDivCeilSCEV(const SCEV *N, const SCEV *D)
Compute ceil(N / D).
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantExitCondDuringFirstIterations(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI, const SCEV *MaxIter)
If the result of the predicate LHS Pred RHS is loop invariant with respect to L at given Context duri...
LLVM_ABI Type * getWiderType(Type *Ty1, Type *Ty2) const
LLVM_ABI const SCEV * getAbsExpr(const SCEV *Op, bool IsNSW)
LLVM_ABI bool isKnownNonPositive(const SCEV *S)
Test if the given expression is known to be non-positive.
LLVM_ABI bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
LLVM_ABI const SCEV * getPredicatedConstantMaxBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getConstantMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
LLVM_ABI const SCEV * removePointerBase(const SCEV *S)
Compute an expression equivalent to S - getPointerBase(S).
LLVM_ABI bool isLoopEntryGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the loop is protected by a conditional between LHS and RHS.
LLVM_ABI bool isKnownNonZero(const SCEV *S)
Test if the given expression is known to be non-zero.
LLVM_ABI const SCEV * getURemExpr(SCEVUse LHS, SCEVUse RHS)
Represents an unsigned remainder expression based on unsigned division.
LLVM_ABI const SCEV * getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LLVM_ABI const SCEV * getSMinExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI void setNoWrapFlags(SCEVAddRecExpr *AddRec, SCEV::NoWrapFlags Flags)
Update no-wrap flags of an AddRec.
LLVM_ABI const SCEV * getUMaxFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS)
Promote the operands to the wider of the types using zero-extension, and then perform a umax operatio...
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
LLVM_ABI bool willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI=nullptr)
Is operation BinOp between LHS and RHS provably does not have a signed/unsigned overflow (Signed)?
LLVM_ABI ExitLimit computeExitLimitFromCond(const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit, bool AllowPredicates=false)
Compute the number of times the backedge of the specified loop will execute if its exit condition wer...
LLVM_ABI const SCEV * getZeroExtendExprImpl(const SCEV *Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getMinMaxExpr(SCEVTypes Kind, SmallVectorImpl< SCEVUse > &Operands)
LLVM_ABI const SCEVPredicate * getEqualPredicate(const SCEV *LHS, const SCEV *RHS)
LLVM_ABI unsigned getSmallConstantTripMultiple(const Loop *L, const SCEV *ExitCount)
Returns the largest constant divisor of the trip count as a normal unsigned value,...
LLVM_ABI uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getPredicatedBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getBackedgeTakenCount, except it will add a set of SCEV predicates to Predicates that are ...
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
ConstantRange getSignedRange(const SCEV *S)
Determine the signed range for a particular SCEV.
LLVM_ABI const SCEV * getAddRecExpr(SCEVUse Start, SCEVUse Step, const Loop *L, SCEV::NoWrapFlags Flags)
Get an add recurrence expression for the specified loop.
LLVM_ABI const SCEV * getNoopOrSignExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
static LLVM_ABI bool isGuaranteedNotToBePoison(const SCEV *Op)
Returns true if Op is guaranteed to not be poison.
bool loopHasNoAbnormalExits(const Loop *L)
Return true if the loop has no abnormal exits.
LLVM_ABI const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
LLVM_ABI ScalarEvolution(Function &F, TargetLibraryInfo &TLI, AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI)
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI const SCEV * getTruncateOrNoop(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI const SCEV * getLosslessPtrToIntExpr(const SCEV *Op)
LLVM_ABI const SCEV * getCastExpr(SCEVTypes Kind, const SCEV *Op, Type *Ty)
LLVM_ABI const SCEV * getSequentialMinMaxExpr(SCEVTypes Kind, SmallVectorImpl< SCEVUse > &Operands)
LLVM_ABI std::optional< bool > evaluatePredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Check whether the condition described by Pred, LHS, and RHS is true or false in the given Context.
LLVM_ABI unsigned getSmallConstantMaxTripCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Returns the upper bound of the loop trip count as a normal unsigned value.
LLVM_ABI const SCEV * getPtrToIntExpr(const SCEV *Op, Type *Ty)
LLVM_ABI bool isBackedgeTakenCountMaxOrZero(const Loop *L)
Return true if the backedge taken count is either the value returned by getConstantMaxBackedgeTakenCo...
LLVM_ABI void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI bool isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
LLVM_ABI bool SimplifyICmpOperands(CmpPredicate &Pred, SCEVUse &LHS, SCEVUse &RHS, unsigned Depth=0)
Simplify LHS and RHS in a comparison with predicate Pred.
APInt getUnsignedRangeMin(const SCEV *S)
Determine the min of the unsigned range for a particular SCEV.
LLVM_ABI const SCEV * getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo)
Return an expression for offsetof on the given field with type IntTy.
LLVM_ABI LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L)
Return the "disposition" of the given SCEV with respect to the given loop.
LLVM_ABI bool containsAddRecurrence(const SCEV *S)
Return true if the SCEV is a scAddRecExpr or it contains scAddRecExpr.
LLVM_ABI const SCEV * getSignExtendExprImpl(const SCEV *Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool hasOperand(const SCEV *S, const SCEV *Op) const
Test whether the given SCEV has Op as a direct or indirect operand.
LLVM_ABI const SCEV * getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI Type * getEffectiveSCEVType(Type *Ty) const
Return a type with the same bitwidth as the given type and which represents how SCEV will treat the g...
LLVM_ABI const SCEVPredicate * getComparePredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
LLVM_ABI bool haveSameSign(const SCEV *S1, const SCEV *S2)
Return true if we know that S1 and S2 must have the same sign.
LLVM_ABI const SCEV * getNotSCEV(const SCEV *V)
Return the SCEV object corresponding to ~V.
LLVM_ABI const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
LLVM_ABI bool instructionCouldExistWithOperands(const SCEV *A, const SCEV *B)
Return true if there exists a point in the program at which both A and B could be operands to the sam...
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
LLVM_ABI void print(raw_ostream &OS) const
LLVM_ABI const SCEV * getPredicatedExitCount(const Loop *L, const BasicBlock *ExitingBlock, SmallVectorImpl< const SCEVPredicate * > *Predicates, ExitCountKind Kind=Exact)
Same as above except this uses the predicated backedge taken info and may require predicates.
static SCEV::NoWrapFlags clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags)
LLVM_ABI void forgetTopmostLoop(const Loop *L)
LLVM_ABI void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
APInt getSignedRangeMin(const SCEV *S)
Determine the min of the signed range for a particular SCEV.
LLVM_ABI bool isLoopUniform(const SCEV *S, const Loop *L)
Returns true if the given SCEV is loop-uniform with respect to the specified loop L.
LLVM_ABI const SCEV * getNoopOrAnyExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
LLVM_ABI const SCEV * getTruncateExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getUMaxExpr(SCEVUse LHS, SCEVUse RHS)
static SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags Mask)
Convenient NoWrapFlags manipulation.
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantPredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI=nullptr)
If the result of the predicate LHS Pred RHS is loop invariant with respect to L, return a LoopInvaria...
LLVM_ABI const SCEV * getStoreSizeOfExpr(Type *IntTy, Type *StoreTy)
Return an expression for the store size of StoreTy that is type IntTy.
LLVM_ABI const SCEVPredicate * getWrapPredicate(const SCEVAddRecExpr *AR, SCEVWrapPredicate::IncrementWrapFlags AddedFlags)
LLVM_ABI bool isLoopBackedgeGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether the backedge of the loop is protected by a conditional between LHS and RHS.
LLVM_ABI APInt getNonZeroConstantMultiple(const SCEV *S)
const SCEV * getMinusOne(Type *Ty)
Return a SCEV for the constant -1 of a specific type.
static SCEV::NoWrapFlags setFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OnFlags)
LLVM_ABI bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count.
LLVM_ABI BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB)
Return the "disposition" of the given SCEV with respect to the given block.
LLVM_ABI const SCEV * getNoopOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
LLVM_ABI const SCEV * getUMinFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS, bool Sequential=false)
Promote the operands to the wider of the types using zero-extension, and then perform a umin operatio...
LLVM_ABI bool loopIsFiniteByAssumption(const Loop *L)
Return true if this loop is finite by assumption.
LLVM_ABI const SCEV * getExistingSCEV(Value *V)
Return an existing SCEV for V if there is one, otherwise return nullptr.
LLVM_ABI APInt getConstantMultiple(const SCEV *S, const Instruction *CtxI=nullptr)
Returns the max constant multiple of S.
LoopDisposition
An enum describing the relationship between a SCEV and a loop.
@ LoopComputable
The SCEV varies predictably with the loop.
@ LoopVariant
The SCEV is loop-variant (unknown).
@ LoopInvariant
The SCEV is loop-invariant.
@ LoopUniform
The SCEV is loop-uniform.
LLVM_ABI bool isKnownMultipleOf(const SCEV *S, uint64_t M, SmallVectorImpl< const SCEVPredicate * > &Assumptions)
Check that S is a multiple of M.
LLVM_ABI const SCEV * getAnyExtendExpr(const SCEV *Op, Type *Ty)
getAnyExtendExpr - Return a SCEV for the given operand extended with unspecified bits out to the give...
LLVM_ABI bool isKnownToBeAPowerOfTwo(const SCEV *S, bool OrZero=false, bool OrNegative=false)
Test if the given expression is known to be a power of 2.
LLVM_ABI std::optional< SCEV::NoWrapFlags > getStrengthenedNoWrapFlagsFromBinOp(const OverflowingBinaryOperator *OBO)
Parse NSW/NUW flags from add/sub/mul IR binary operation Op into SCEV no-wrap flags,...
LLVM_ABI void forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V)
Forget LCSSA phi node V of loop L to which a new predecessor was added, such that it may no longer be...
LLVM_ABI bool containsUndefs(const SCEV *S) const
Return true if the SCEV expression contains an undef value.
LLVM_ABI std::optional< MonotonicPredicateType > getMonotonicPredicateType(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred)
If, for all loop invariant X, the predicate "LHS `Pred` X" is monotonically increasing or decreasing,...
LLVM_ABI const SCEV * getCouldNotCompute()
LLVM_ABI const SCEV * getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
LLVM_ABI bool isAvailableAtLoopEntry(const SCEV *S, const Loop *L)
Determine if the SCEV can be evaluated at loop's entry.
LLVM_ABI uint32_t getMinTrailingZeros(const SCEV *S, const Instruction *CtxI=nullptr)
Determine the minimum number of zero bits that S is guaranteed to end in (at every loop iteration).
BlockDisposition
An enum describing the relationship between a SCEV and a basic block.
@ DominatesBlock
The SCEV dominates the block.
@ ProperlyDominatesBlock
The SCEV properly dominates the block.
@ DoesNotDominateBlock
The SCEV does not dominate the block.
LLVM_ABI const SCEV * getExitCount(const Loop *L, const BasicBlock *ExitingBlock, ExitCountKind Kind=Exact)
Return the number of times the backedge executes before the given exit would be taken; if not exactly...
LLVM_ABI const SCEV * getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
LLVM_ABI void getPoisonGeneratingValues(SmallPtrSetImpl< const Value * > &Result, const SCEV *S)
Return the set of Values that, if poison, will definitively result in S being poison as well.
LLVM_ABI void forgetLoopDispositions()
Called when the client has changed the disposition of values in this loop.
LLVM_ABI const SCEV * getVScale(Type *Ty)
LLVM_ABI unsigned getSmallConstantTripCount(const Loop *L)
Returns the exact trip count of the loop if we can compute it, and the result is a small constant.
LLVM_ABI bool hasComputableLoopEvolution(const SCEV *S, const Loop *L)
Return true if the given SCEV changes value in a known way in the specified loop.
LLVM_ABI const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
LLVM_ABI void forgetAllLoops()
LLVM_ABI bool dominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV dominate the specified basic block.
APInt getUnsignedRangeMax(const SCEV *S)
Determine the max of the unsigned range for a particular SCEV.
LLVM_ABI const SCEV * getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
ExitCountKind
The terms "backedge taken count" and "exit count" are used interchangeably to refer to the number of ...
@ SymbolicMaximum
An expression which provides an upper bound on the exact trip count.
@ ConstantMaximum
A constant which provides an upper bound on the exact trip count.
@ Exact
An expression exactly describing the number of times the backedge has executed when a loop is exited.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
LLVM_ABI const SCEV * getPtrToAddrExpr(const SCEV *Op)
LLVM_ABI const SCEVAddRecExpr * convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Preds)
Tries to convert the S expression to an AddRec expression, adding additional predicates to Preds as r...
LLVM_ABI const SCEV * getSMaxExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI const SCEV * getElementSize(Instruction *Inst)
Return the size of an element read or written by Inst.
LLVM_ABI const SCEV * getSizeOfExpr(Type *IntTy, TypeSize Size)
Return an expression for a TypeSize.
LLVM_ABI std::optional< bool > evaluatePredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Check whether the condition described by Pred, LHS, and RHS is true or false.
LLVM_ABI const SCEV * getUnknown(Value *V)
LLVM_ABI std::optional< std::pair< const SCEV *, SmallVector< const SCEVPredicate *, 3 > > > createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI)
Checks if SymbolicPHI can be rewritten as an AddRecExpr under some Predicates.
LLVM_ABI const SCEV * getTruncateOrZeroExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool isKnownViaInduction(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
We'd like to check the predicate on every iteration of the most dominated loop between loops used in ...
LLVM_ABI std::optional< APInt > computeConstantDifference(const SCEV *LHS, const SCEV *RHS)
Compute LHS - RHS and returns the result as an APInt if it is a constant, and std::nullopt if it isn'...
LLVM_ABI bool properlyDominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV properly dominate the specified basic block.
LLVM_ABI const SCEV * getUDivExactExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
LLVM_ABI const SCEV * rewriteUsingPredicate(const SCEV *S, const Loop *L, const SCEVPredicate &A)
Re-writes the SCEV according to the Predicates in A.
LLVM_ABI std::pair< const SCEV *, const SCEV * > SplitIntoInitAndPostInc(const Loop *L, const SCEV *S)
Splits SCEV expression S into two SCEVs.
LLVM_ABI bool canReuseInstruction(const SCEV *S, Instruction *I, SmallVectorImpl< Instruction * > &DropPoisonGeneratingInsts)
Check whether it is poison-safe to represent the expression S using the instruction I.
LLVM_ABI bool isKnownPredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * getPredicatedSymbolicMaxBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getSymbolicMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
LLVM_ABI const SCEV * getGEPExpr(GEPOperator *GEP, ArrayRef< SCEVUse > IndexExprs)
Returns an expression for a GEP.
LLVM_ABI const SCEV * getUMinExpr(SCEVUse LHS, SCEVUse RHS, bool Sequential=false)
LLVM_ABI void registerUser(const SCEV *User, ArrayRef< const SCEV * > Ops)
Notify this ScalarEvolution that User directly uses SCEVs in Ops.
LLVM_ABI bool isBasicBlockEntryGuardedByCond(const BasicBlock *BB, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the basic block is protected by a conditional between LHS and RHS.
LLVM_ABI const SCEV * getTruncateOrSignExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool containsErasedValue(const SCEV *S) const
Return true if the SCEV expression contains a Value that has been optimised out and is now a nullptr.
const SCEV * getSymbolicMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEV that is greater than or equal to (i.e.
APInt getSignedRangeMax(const SCEV *S)
Determine the max of the signed range for a particular SCEV.
LLVM_ABI void verify() const
LLVMContext & getContext() const
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:293
size_type size() const
Definition SmallPtrSet.h:99
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:743
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
TypeSize getSizeInBits() const
Definition DataLayout.h:754
Class to represent struct types.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:306
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:270
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:313
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
Use & Op()
Definition User.h:171
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition Value.h:543
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition APInt.h:2279
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition APInt.h:2284
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition APInt.h:2289
LLVM_ABI std::optional< APInt > SolveQuadraticEquationWrap(APInt A, APInt B, APInt C, unsigned RangeWidth)
Let q(n) = An^2 + Bn + C, and BW = bit width of the value range (e.g.
Definition APInt.cpp:2847
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2294
LLVM_ABI APInt GreatestCommonDivisor(APInt A, APInt B)
Compute GCD of two unsigned APInt values.
Definition APInt.cpp:830
constexpr bool any(E Val)
@ Entry
Definition COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
int getMinValue(MCInstrInfo const &MCII, MCInst const &MCI)
Return the minimum value of an extendable operand.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
bind_cst_ty m_scev_APInt(const APInt *&C)
Match an SCEV constant and bind it to an APInt.
cst_pred_ty< is_all_ones > m_scev_AllOnes()
Match an integer with all bits set.
SCEVUnaryExpr_match< SCEVZeroExtendExpr, Op0_t > m_scev_ZExt(const Op0_t &Op0)
is_undef_or_poison m_scev_UndefOrPoison()
Match an SCEVUnknown wrapping undef or poison.
cst_pred_ty< is_one > m_scev_One()
Match an integer 1.
specificloop_ty m_SpecificLoop(const Loop *L)
SCEVUnaryExpr_match< SCEVSignExtendExpr, Op0_t > m_scev_SExt(const Op0_t &Op0)
match_bind< const SCEVMulExpr > m_scev_Mul(const SCEVMulExpr *&V)
cst_pred_ty< is_zero > m_scev_Zero()
Match an integer 0.
SCEVUnaryExpr_match< SCEVTruncateExpr, Op0_t > m_scev_Trunc(const Op0_t &Op0)
bool match(const SCEV *S, const Pattern &P)
SCEVBinaryExpr_match< SCEVUDivExpr, Op0_t, Op1_t > m_scev_UDiv(const Op0_t &Op0, const Op1_t &Op1)
specificscev_ty m_scev_Specific(const SCEV *S)
Match if we have a specific specified SCEV.
SCEVAffineAddRec_match< Op0_t, Op1_t, match_isa< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
match_bind< const SCEVUnknown > m_SCEVUnknown(const SCEVUnknown *&V)
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t, SCEV::FlagNUW, true > m_scev_c_NUWMul(const Op0_t &Op0, const Op1_t &Op1)
match_bind< const SCEVAddExpr > m_scev_Add(const SCEVAddExpr *&V)
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t, SCEV::FlagAnyWrap, true > m_scev_c_Mul(const Op0_t &Op0, const Op1_t &Op1)
SCEVBinaryExpr_match< SCEVSMaxExpr, Op0_t, Op1_t > m_scev_SMax(const Op0_t &Op0, const Op1_t &Op1)
SCEVURem_match< Op0_t, Op1_t > m_scev_URem(Op0_t LHS, Op1_t RHS, ScalarEvolution &SE)
Match the mathematical pattern A - (A / B) * B, where A and B can be arbitrary expressions.
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
Definition CoroShape.h:31
constexpr double e
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:392
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
void visitAll(const SCEV *Root, SV &Visitor)
Use SCEVTraversal to visit all nodes in the given expression tree.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
@ Offset
Definition DWP.cpp:578
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt gcd(const DynamicAPInt &A, const DynamicAPInt &B)
void stable_sort(R &&Range)
Definition STLExtras.h:2116
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
SaveAndRestore(T &) -> SaveAndRestore< T >
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
LLVM_ABI bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
LLVM_ABI bool mustTriggerUB(const Instruction *I, const SmallPtrSetImpl< const Value * > &KnownPoison)
Return true if the given instruction must trigger undefined behavior when I is executed with any oper...
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
@ Known
Known to have no common set bits.
@ Dead
Unused definition.
LLVM_ABI bool canConstantFoldCallTo(const CallBase *Call, const Function *F)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function.
InterleavedRange< Range > interleaved(const Range &R, StringRef Separator=", ", StringRef Prefix="", StringRef Suffix="")
Output range R as a sequence of interleaved elements.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
auto successors(const MachineBasicBlock *BB)
scope_exit(Callable) -> scope_exit< Callable >
@ BinaryOp
One of the operands is a binary op.
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
constexpr from_range_t from_range
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
bool set_is_subset(const S1Ty &S1, const S2Ty &S2)
set_is_subset(A, B) - Return true iff A in B
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:243
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Instruction *I=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
void * PointerTy
LLVM_ABI bool VerifySCEV
auto uninitialized_copy(R &&Src, IterTy Dst)
Definition STLExtras.h:2111
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, const DominatorTree &DT)
Returns true if the arithmetic part of the WO 's result is used only along the paths control dependen...
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:94
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2200
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
iterator_range< pointee_iterator< WrappedIteratorT > > make_pointee_range(RangeT &&Range)
Definition iterator.h:341
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
LLVM_ABI bool isMustProgress(const Loop *L)
Return true if this loop can be assumed to make progress.
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
LLVM_ABI bool isFinite(const Loop *L)
Return true if this loop can be assumed to run for a finite number of iterations.
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
unsigned short computeExpressionSize(ArrayRef< SCEVUse > Args)
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:374
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:394
LLVM_ABI bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ Mul
Product of integers.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ Add
Sum of integers.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2012
IntPtrTy
Definition InstrProf.h:82
DWARFExpression::Operation Op
auto max_element(R &&Range)
Provide wrappers to std::max_element which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2088
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2019
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:248
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
iterator_range< df_iterator< T > > depth_first(const T &G)
auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:305
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
SCEVUseT< const SCEV * > SCEVUse
bool SCEVExprContains(const SCEV *Root, PredTy Pred)
Return true if any node in Root satisfies the predicate Pred.
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
#define NC
Definition regutils.h:42
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
An object of this class is returned by queries that could not be answered.
static LLVM_ABI bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
This class defines a simple visitor class that may be used for various SCEV analysis purposes.
A utility class that uses RAII to save and restore the value of a variable.
Information about the number of loop iterations for which a loop exit's branch condition evaluates to...
LLVM_ABI ExitLimit(const SCEV *E)
Construct either an exact exit limit from a constant, or an unknown one from a SCEVCouldNotCompute.
SmallVector< const SCEVPredicate *, 4 > Predicates
A vector of predicate guards for this ExitLimit.