Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / llvm / lib / Analysis / ScalarEvolution.cpp
blobde24aa986688a1e1578556c1dc33b1d5f5b72968
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.
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.
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.
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.
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.
34 // TODO: We should use these routines and value representations to implement
35 // dependence analysis!
37 //===----------------------------------------------------------------------===//
39 // There are several good references for the techniques used in this analysis.
41 // Chains of recurrences -- a method to expedite the evaluation
42 // of closed-form functions
43 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45 // On computational properties of chains of recurrences
46 // Eugene V. Zima
48 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization
49 // Robert A. van Engelen
51 // Efficient Symbolic Analysis for Optimizing Compilers
52 // Robert A. van Engelen
54 // Using the chains of recurrences algebra for data dependence testing and
55 // induction variable substitution
56 // MS Thesis, Johnie Birch
58 //===----------------------------------------------------------------------===//
60 #include "llvm/Analysis/ScalarEvolution.h"
61 #include "llvm/ADT/APInt.h"
62 #include "llvm/ADT/ArrayRef.h"
63 #include "llvm/ADT/DenseMap.h"
64 #include "llvm/ADT/DepthFirstIterator.h"
65 #include "llvm/ADT/EquivalenceClasses.h"
66 #include "llvm/ADT/FoldingSet.h"
67 #include "llvm/ADT/STLExtras.h"
68 #include "llvm/ADT/ScopeExit.h"
69 #include "llvm/ADT/Sequence.h"
70 #include "llvm/ADT/SmallPtrSet.h"
71 #include "llvm/ADT/SmallSet.h"
72 #include "llvm/ADT/SmallVector.h"
73 #include "llvm/ADT/Statistic.h"
74 #include "llvm/ADT/StringExtras.h"
75 #include "llvm/ADT/StringRef.h"
76 #include "llvm/Analysis/AssumptionCache.h"
77 #include "llvm/Analysis/ConstantFolding.h"
78 #include "llvm/Analysis/InstructionSimplify.h"
79 #include "llvm/Analysis/LoopInfo.h"
80 #include "llvm/Analysis/MemoryBuiltins.h"
81 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
82 #include "llvm/Analysis/TargetLibraryInfo.h"
83 #include "llvm/Analysis/ValueTracking.h"
84 #include "llvm/Config/llvm-config.h"
85 #include "llvm/IR/Argument.h"
86 #include "llvm/IR/BasicBlock.h"
87 #include "llvm/IR/CFG.h"
88 #include "llvm/IR/Constant.h"
89 #include "llvm/IR/ConstantRange.h"
90 #include "llvm/IR/Constants.h"
91 #include "llvm/IR/DataLayout.h"
92 #include "llvm/IR/DerivedTypes.h"
93 #include "llvm/IR/Dominators.h"
94 #include "llvm/IR/Function.h"
95 #include "llvm/IR/GlobalAlias.h"
96 #include "llvm/IR/GlobalValue.h"
97 #include "llvm/IR/InstIterator.h"
98 #include "llvm/IR/InstrTypes.h"
99 #include "llvm/IR/Instruction.h"
100 #include "llvm/IR/Instructions.h"
101 #include "llvm/IR/IntrinsicInst.h"
102 #include "llvm/IR/Intrinsics.h"
103 #include "llvm/IR/LLVMContext.h"
104 #include "llvm/IR/Operator.h"
105 #include "llvm/IR/PatternMatch.h"
106 #include "llvm/IR/Type.h"
107 #include "llvm/IR/Use.h"
108 #include "llvm/IR/User.h"
109 #include "llvm/IR/Value.h"
110 #include "llvm/IR/Verifier.h"
111 #include "llvm/InitializePasses.h"
112 #include "llvm/Pass.h"
113 #include "llvm/Support/Casting.h"
114 #include "llvm/Support/CommandLine.h"
115 #include "llvm/Support/Compiler.h"
116 #include "llvm/Support/Debug.h"
117 #include "llvm/Support/ErrorHandling.h"
118 #include "llvm/Support/KnownBits.h"
119 #include "llvm/Support/SaveAndRestore.h"
120 #include "llvm/Support/raw_ostream.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>
134 using namespace llvm;
135 using namespace PatternMatch;
137 #define DEBUG_TYPE "scalar-evolution"
139 STATISTIC(NumExitCountsComputed,
140 "Number of loop exits with predictable exit counts");
141 STATISTIC(NumExitCountsNotComputed,
142 "Number of loop exits without predictable exit counts");
143 STATISTIC(NumBruteForceTripCountsComputed,
144 "Number of loops with trip counts computed by force");
146 #ifdef EXPENSIVE_CHECKS
147 bool llvm::VerifySCEV = true;
148 #else
149 bool llvm::VerifySCEV = false;
150 #endif
152 static cl::opt<unsigned>
153 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
154 cl::desc("Maximum number of iterations SCEV will "
155 "symbolically execute a constant "
156 "derived loop"),
157 cl::init(100));
159 static cl::opt<bool, true> VerifySCEVOpt(
160 "verify-scev", cl::Hidden, cl::location(VerifySCEV),
161 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
162 static cl::opt<bool> VerifySCEVStrict(
163 "verify-scev-strict", cl::Hidden,
164 cl::desc("Enable stricter verification with -verify-scev is passed"));
166 static cl::opt<bool> VerifyIR(
167 "scev-verify-ir", cl::Hidden,
168 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
169 cl::init(false));
171 static cl::opt<unsigned> MulOpsInlineThreshold(
172 "scev-mulops-inline-threshold", cl::Hidden,
173 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
174 cl::init(32));
176 static cl::opt<unsigned> AddOpsInlineThreshold(
177 "scev-addops-inline-threshold", cl::Hidden,
178 cl::desc("Threshold for inlining addition operands into a SCEV"),
179 cl::init(500));
181 static cl::opt<unsigned> MaxSCEVCompareDepth(
182 "scalar-evolution-max-scev-compare-depth", cl::Hidden,
183 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
184 cl::init(32));
186 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
187 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
188 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
189 cl::init(2));
191 static cl::opt<unsigned> MaxValueCompareDepth(
192 "scalar-evolution-max-value-compare-depth", cl::Hidden,
193 cl::desc("Maximum depth of recursive value complexity comparisons"),
194 cl::init(2));
196 static cl::opt<unsigned>
197 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
198 cl::desc("Maximum depth of recursive arithmetics"),
199 cl::init(32));
201 static cl::opt<unsigned> MaxConstantEvolvingDepth(
202 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
203 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
205 static cl::opt<unsigned>
206 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
207 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
208 cl::init(8));
210 static cl::opt<unsigned>
211 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
212 cl::desc("Max coefficients in AddRec during evolving"),
213 cl::init(8));
215 static cl::opt<unsigned>
216 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
217 cl::desc("Size of the expression which is considered huge"),
218 cl::init(4096));
220 static cl::opt<unsigned> RangeIterThreshold(
221 "scev-range-iter-threshold", cl::Hidden,
222 cl::desc("Threshold for switching to iteratively computing SCEV ranges"),
223 cl::init(32));
225 static cl::opt<bool>
226 ClassifyExpressions("scalar-evolution-classify-expressions",
227 cl::Hidden, cl::init(true),
228 cl::desc("When printing analysis, include information on every instruction"));
230 static cl::opt<bool> UseExpensiveRangeSharpening(
231 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
232 cl::init(false),
233 cl::desc("Use more powerful methods of sharpening expression ranges. May "
234 "be costly in terms of compile time"));
236 static cl::opt<unsigned> MaxPhiSCCAnalysisSize(
237 "scalar-evolution-max-scc-analysis-depth", cl::Hidden,
238 cl::desc("Maximum amount of nodes to process while searching SCEVUnknown "
239 "Phi strongly connected components"),
240 cl::init(8));
242 static cl::opt<bool>
243 EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
244 cl::desc("Handle <= and >= in finite loops"),
245 cl::init(true));
247 static cl::opt<bool> UseContextForNoWrapFlagInference(
248 "scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden,
249 cl::desc("Infer nuw/nsw flags using context where suitable"),
250 cl::init(true));
252 //===----------------------------------------------------------------------===//
253 // SCEV class definitions
254 //===----------------------------------------------------------------------===//
256 //===----------------------------------------------------------------------===//
257 // Implementation of the SCEV class.
260 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
261 LLVM_DUMP_METHOD void SCEV::dump() const {
262 print(dbgs());
263 dbgs() << '\n';
265 #endif
267 void SCEV::print(raw_ostream &OS) const {
268 switch (getSCEVType()) {
269 case scConstant:
270 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
271 return;
272 case scVScale:
273 OS << "vscale";
274 return;
275 case scPtrToInt: {
276 const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this);
277 const SCEV *Op = PtrToInt->getOperand();
278 OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to "
279 << *PtrToInt->getType() << ")";
280 return;
282 case scTruncate: {
283 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
284 const SCEV *Op = Trunc->getOperand();
285 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
286 << *Trunc->getType() << ")";
287 return;
289 case scZeroExtend: {
290 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
291 const SCEV *Op = ZExt->getOperand();
292 OS << "(zext " << *Op->getType() << " " << *Op << " to "
293 << *ZExt->getType() << ")";
294 return;
296 case scSignExtend: {
297 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
298 const SCEV *Op = SExt->getOperand();
299 OS << "(sext " << *Op->getType() << " " << *Op << " to "
300 << *SExt->getType() << ")";
301 return;
303 case scAddRecExpr: {
304 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
305 OS << "{" << *AR->getOperand(0);
306 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
307 OS << ",+," << *AR->getOperand(i);
308 OS << "}<";
309 if (AR->hasNoUnsignedWrap())
310 OS << "nuw><";
311 if (AR->hasNoSignedWrap())
312 OS << "nsw><";
313 if (AR->hasNoSelfWrap() &&
314 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
315 OS << "nw><";
316 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
317 OS << ">";
318 return;
320 case scAddExpr:
321 case scMulExpr:
322 case scUMaxExpr:
323 case scSMaxExpr:
324 case scUMinExpr:
325 case scSMinExpr:
326 case scSequentialUMinExpr: {
327 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
328 const char *OpStr = nullptr;
329 switch (NAry->getSCEVType()) {
330 case scAddExpr: OpStr = " + "; break;
331 case scMulExpr: OpStr = " * "; break;
332 case scUMaxExpr: OpStr = " umax "; break;
333 case scSMaxExpr: OpStr = " smax "; break;
334 case scUMinExpr:
335 OpStr = " umin ";
336 break;
337 case scSMinExpr:
338 OpStr = " smin ";
339 break;
340 case scSequentialUMinExpr:
341 OpStr = " umin_seq ";
342 break;
343 default:
344 llvm_unreachable("There are no other nary expression types.");
346 OS << "(";
347 ListSeparator LS(OpStr);
348 for (const SCEV *Op : NAry->operands())
349 OS << LS << *Op;
350 OS << ")";
351 switch (NAry->getSCEVType()) {
352 case scAddExpr:
353 case scMulExpr:
354 if (NAry->hasNoUnsignedWrap())
355 OS << "<nuw>";
356 if (NAry->hasNoSignedWrap())
357 OS << "<nsw>";
358 break;
359 default:
360 // Nothing to print for other nary expressions.
361 break;
363 return;
365 case scUDivExpr: {
366 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
367 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
368 return;
370 case scUnknown:
371 cast<SCEVUnknown>(this)->getValue()->printAsOperand(OS, false);
372 return;
373 case scCouldNotCompute:
374 OS << "***COULDNOTCOMPUTE***";
375 return;
377 llvm_unreachable("Unknown SCEV kind!");
380 Type *SCEV::getType() const {
381 switch (getSCEVType()) {
382 case scConstant:
383 return cast<SCEVConstant>(this)->getType();
384 case scVScale:
385 return cast<SCEVVScale>(this)->getType();
386 case scPtrToInt:
387 case scTruncate:
388 case scZeroExtend:
389 case scSignExtend:
390 return cast<SCEVCastExpr>(this)->getType();
391 case scAddRecExpr:
392 return cast<SCEVAddRecExpr>(this)->getType();
393 case scMulExpr:
394 return cast<SCEVMulExpr>(this)->getType();
395 case scUMaxExpr:
396 case scSMaxExpr:
397 case scUMinExpr:
398 case scSMinExpr:
399 return cast<SCEVMinMaxExpr>(this)->getType();
400 case scSequentialUMinExpr:
401 return cast<SCEVSequentialMinMaxExpr>(this)->getType();
402 case scAddExpr:
403 return cast<SCEVAddExpr>(this)->getType();
404 case scUDivExpr:
405 return cast<SCEVUDivExpr>(this)->getType();
406 case scUnknown:
407 return cast<SCEVUnknown>(this)->getType();
408 case scCouldNotCompute:
409 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
411 llvm_unreachable("Unknown SCEV kind!");
414 ArrayRef<const SCEV *> SCEV::operands() const {
415 switch (getSCEVType()) {
416 case scConstant:
417 case scVScale:
418 case scUnknown:
419 return {};
420 case scPtrToInt:
421 case scTruncate:
422 case scZeroExtend:
423 case scSignExtend:
424 return cast<SCEVCastExpr>(this)->operands();
425 case scAddRecExpr:
426 case scAddExpr:
427 case scMulExpr:
428 case scUMaxExpr:
429 case scSMaxExpr:
430 case scUMinExpr:
431 case scSMinExpr:
432 case scSequentialUMinExpr:
433 return cast<SCEVNAryExpr>(this)->operands();
434 case scUDivExpr:
435 return cast<SCEVUDivExpr>(this)->operands();
436 case scCouldNotCompute:
437 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
439 llvm_unreachable("Unknown SCEV kind!");
442 bool SCEV::isZero() const {
443 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
444 return SC->getValue()->isZero();
445 return false;
448 bool SCEV::isOne() const {
449 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
450 return SC->getValue()->isOne();
451 return false;
454 bool SCEV::isAllOnesValue() const {
455 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
456 return SC->getValue()->isMinusOne();
457 return false;
460 bool SCEV::isNonConstantNegative() const {
461 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
462 if (!Mul) return false;
464 // If there is a constant factor, it will be first.
465 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
466 if (!SC) return false;
468 // Return true if the value is negative, this matches things like (-42 * V).
469 return SC->getAPInt().isNegative();
472 SCEVCouldNotCompute::SCEVCouldNotCompute() :
473 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
475 bool SCEVCouldNotCompute::classof(const SCEV *S) {
476 return S->getSCEVType() == scCouldNotCompute;
479 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
480 FoldingSetNodeID ID;
481 ID.AddInteger(scConstant);
482 ID.AddPointer(V);
483 void *IP = nullptr;
484 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
485 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
486 UniqueSCEVs.InsertNode(S, IP);
487 return S;
490 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
491 return getConstant(ConstantInt::get(getContext(), Val));
494 const SCEV *
495 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
496 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
497 return getConstant(ConstantInt::get(ITy, V, isSigned));
500 const SCEV *ScalarEvolution::getVScale(Type *Ty) {
501 FoldingSetNodeID ID;
502 ID.AddInteger(scVScale);
503 ID.AddPointer(Ty);
504 void *IP = nullptr;
505 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
506 return S;
507 SCEV *S = new (SCEVAllocator) SCEVVScale(ID.Intern(SCEVAllocator), Ty);
508 UniqueSCEVs.InsertNode(S, IP);
509 return S;
512 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
513 const SCEV *op, Type *ty)
514 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {}
516 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op,
517 Type *ITy)
518 : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
519 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
520 "Must be a non-bit-width-changing pointer-to-integer cast!");
523 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,
524 SCEVTypes SCEVTy, const SCEV *op,
525 Type *ty)
526 : SCEVCastExpr(ID, SCEVTy, op, ty) {}
528 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op,
529 Type *ty)
530 : SCEVIntegralCastExpr(ID, scTruncate, op, ty) {
531 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
532 "Cannot truncate non-integer value!");
535 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
536 const SCEV *op, Type *ty)
537 : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) {
538 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
539 "Cannot zero extend non-integer value!");
542 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
543 const SCEV *op, Type *ty)
544 : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) {
545 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
546 "Cannot sign extend non-integer value!");
549 void SCEVUnknown::deleted() {
550 // Clear this SCEVUnknown from various maps.
551 SE->forgetMemoizedResults(this);
553 // Remove this SCEVUnknown from the uniquing map.
554 SE->UniqueSCEVs.RemoveNode(this);
556 // Release the value.
557 setValPtr(nullptr);
560 void SCEVUnknown::allUsesReplacedWith(Value *New) {
561 // Clear this SCEVUnknown from various maps.
562 SE->forgetMemoizedResults(this);
564 // Remove this SCEVUnknown from the uniquing map.
565 SE->UniqueSCEVs.RemoveNode(this);
567 // Replace the value pointer in case someone is still using this SCEVUnknown.
568 setValPtr(New);
571 //===----------------------------------------------------------------------===//
572 // SCEV Utilities
573 //===----------------------------------------------------------------------===//
575 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
576 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
577 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that
578 /// have been previously deemed to be "equally complex" by this routine. It is
579 /// intended to avoid exponential time complexity in cases like:
581 /// %a = f(%x, %y)
582 /// %b = f(%a, %a)
583 /// %c = f(%b, %b)
585 /// %d = f(%x, %y)
586 /// %e = f(%d, %d)
587 /// %f = f(%e, %e)
589 /// CompareValueComplexity(%f, %c)
591 /// Since we do not continue running this routine on expression trees once we
592 /// have seen unequal values, there is no need to track them in the cache.
593 static int
594 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
595 const LoopInfo *const LI, Value *LV, Value *RV,
596 unsigned Depth) {
597 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
598 return 0;
600 // Order pointer values after integer values. This helps SCEVExpander form
601 // GEPs.
602 bool LIsPointer = LV->getType()->isPointerTy(),
603 RIsPointer = RV->getType()->isPointerTy();
604 if (LIsPointer != RIsPointer)
605 return (int)LIsPointer - (int)RIsPointer;
607 // Compare getValueID values.
608 unsigned LID = LV->getValueID(), RID = RV->getValueID();
609 if (LID != RID)
610 return (int)LID - (int)RID;
612 // Sort arguments by their position.
613 if (const auto *LA = dyn_cast<Argument>(LV)) {
614 const auto *RA = cast<Argument>(RV);
615 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
616 return (int)LArgNo - (int)RArgNo;
619 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
620 const auto *RGV = cast<GlobalValue>(RV);
622 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
623 auto LT = GV->getLinkage();
624 return !(GlobalValue::isPrivateLinkage(LT) ||
625 GlobalValue::isInternalLinkage(LT));
628 // Use the names to distinguish the two values, but only if the
629 // names are semantically important.
630 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
631 return LGV->getName().compare(RGV->getName());
634 // For instructions, compare their loop depth, and their operand count. This
635 // is pretty loose.
636 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
637 const auto *RInst = cast<Instruction>(RV);
639 // Compare loop depths.
640 const BasicBlock *LParent = LInst->getParent(),
641 *RParent = RInst->getParent();
642 if (LParent != RParent) {
643 unsigned LDepth = LI->getLoopDepth(LParent),
644 RDepth = LI->getLoopDepth(RParent);
645 if (LDepth != RDepth)
646 return (int)LDepth - (int)RDepth;
649 // Compare the number of operands.
650 unsigned LNumOps = LInst->getNumOperands(),
651 RNumOps = RInst->getNumOperands();
652 if (LNumOps != RNumOps)
653 return (int)LNumOps - (int)RNumOps;
655 for (unsigned Idx : seq(LNumOps)) {
656 int Result =
657 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
658 RInst->getOperand(Idx), Depth + 1);
659 if (Result != 0)
660 return Result;
664 EqCacheValue.unionSets(LV, RV);
665 return 0;
668 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
669 // than RHS, respectively. A three-way result allows recursive comparisons to be
670 // more efficient.
671 // If the max analysis depth was reached, return std::nullopt, assuming we do
672 // not know if they are equivalent for sure.
673 static std::optional<int>
674 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV,
675 EquivalenceClasses<const Value *> &EqCacheValue,
676 const LoopInfo *const LI, const SCEV *LHS,
677 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
678 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
679 if (LHS == RHS)
680 return 0;
682 // Primarily, sort the SCEVs by their getSCEVType().
683 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
684 if (LType != RType)
685 return (int)LType - (int)RType;
687 if (EqCacheSCEV.isEquivalent(LHS, RHS))
688 return 0;
690 if (Depth > MaxSCEVCompareDepth)
691 return std::nullopt;
693 // Aside from the getSCEVType() ordering, the particular ordering
694 // isn't very important except that it's beneficial to be consistent,
695 // so that (a + b) and (b + a) don't end up as different expressions.
696 switch (LType) {
697 case scUnknown: {
698 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
699 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
701 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
702 RU->getValue(), Depth + 1);
703 if (X == 0)
704 EqCacheSCEV.unionSets(LHS, RHS);
705 return X;
708 case scConstant: {
709 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
710 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
712 // Compare constant values.
713 const APInt &LA = LC->getAPInt();
714 const APInt &RA = RC->getAPInt();
715 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
716 if (LBitWidth != RBitWidth)
717 return (int)LBitWidth - (int)RBitWidth;
718 return LA.ult(RA) ? -1 : 1;
721 case scVScale: {
722 const auto *LTy = cast<IntegerType>(cast<SCEVVScale>(LHS)->getType());
723 const auto *RTy = cast<IntegerType>(cast<SCEVVScale>(RHS)->getType());
724 return LTy->getBitWidth() - RTy->getBitWidth();
727 case scAddRecExpr: {
728 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
729 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
731 // There is always a dominance between two recs that are used by one SCEV,
732 // so we can safely sort recs by loop header dominance. We require such
733 // order in getAddExpr.
734 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
735 if (LLoop != RLoop) {
736 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
737 assert(LHead != RHead && "Two loops share the same header?");
738 if (DT.dominates(LHead, RHead))
739 return 1;
740 assert(DT.dominates(RHead, LHead) &&
741 "No dominance between recurrences used by one SCEV?");
742 return -1;
745 [[fallthrough]];
748 case scTruncate:
749 case scZeroExtend:
750 case scSignExtend:
751 case scPtrToInt:
752 case scAddExpr:
753 case scMulExpr:
754 case scUDivExpr:
755 case scSMaxExpr:
756 case scUMaxExpr:
757 case scSMinExpr:
758 case scUMinExpr:
759 case scSequentialUMinExpr: {
760 ArrayRef<const SCEV *> LOps = LHS->operands();
761 ArrayRef<const SCEV *> ROps = RHS->operands();
763 // Lexicographically compare n-ary-like expressions.
764 unsigned LNumOps = LOps.size(), RNumOps = ROps.size();
765 if (LNumOps != RNumOps)
766 return (int)LNumOps - (int)RNumOps;
768 for (unsigned i = 0; i != LNumOps; ++i) {
769 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LOps[i],
770 ROps[i], DT, Depth + 1);
771 if (X != 0)
772 return X;
774 EqCacheSCEV.unionSets(LHS, RHS);
775 return 0;
778 case scCouldNotCompute:
779 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
781 llvm_unreachable("Unknown SCEV kind!");
784 /// Given a list of SCEV objects, order them by their complexity, and group
785 /// objects of the same complexity together by value. When this routine is
786 /// finished, we know that any duplicates in the vector are consecutive and that
787 /// complexity is monotonically increasing.
789 /// Note that we go take special precautions to ensure that we get deterministic
790 /// results from this routine. In other words, we don't want the results of
791 /// this to depend on where the addresses of various SCEV objects happened to
792 /// land in memory.
793 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
794 LoopInfo *LI, DominatorTree &DT) {
795 if (Ops.size() < 2) return; // Noop
797 EquivalenceClasses<const SCEV *> EqCacheSCEV;
798 EquivalenceClasses<const Value *> EqCacheValue;
800 // Whether LHS has provably less complexity than RHS.
801 auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) {
802 auto Complexity =
803 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT);
804 return Complexity && *Complexity < 0;
806 if (Ops.size() == 2) {
807 // This is the common case, which also happens to be trivially simple.
808 // Special case it.
809 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
810 if (IsLessComplex(RHS, LHS))
811 std::swap(LHS, RHS);
812 return;
815 // Do the rough sort by complexity.
816 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
817 return IsLessComplex(LHS, RHS);
820 // Now that we are sorted by complexity, group elements of the same
821 // complexity. Note that this is, at worst, N^2, but the vector is likely to
822 // be extremely short in practice. Note that we take this approach because we
823 // do not want to depend on the addresses of the objects we are grouping.
824 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
825 const SCEV *S = Ops[i];
826 unsigned Complexity = S->getSCEVType();
828 // If there are any objects of the same complexity and same value as this
829 // one, group them.
830 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
831 if (Ops[j] == S) { // Found a duplicate.
832 // Move it to immediately after i'th element.
833 std::swap(Ops[i+1], Ops[j]);
834 ++i; // no need to rescan it.
835 if (i == e-2) return; // Done!
841 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
842 /// least HugeExprThreshold nodes).
843 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
844 return any_of(Ops, [](const SCEV *S) {
845 return S->getExpressionSize() >= HugeExprThreshold;
849 //===----------------------------------------------------------------------===//
850 // Simple SCEV method implementations
851 //===----------------------------------------------------------------------===//
853 /// Compute BC(It, K). The result has width W. Assume, K > 0.
854 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
855 ScalarEvolution &SE,
856 Type *ResultTy) {
857 // Handle the simplest case efficiently.
858 if (K == 1)
859 return SE.getTruncateOrZeroExtend(It, ResultTy);
861 // We are using the following formula for BC(It, K):
863 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
865 // Suppose, W is the bitwidth of the return value. We must be prepared for
866 // overflow. Hence, we must assure that the result of our computation is
867 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
868 // safe in modular arithmetic.
870 // However, this code doesn't use exactly that formula; the formula it uses
871 // is something like the following, where T is the number of factors of 2 in
872 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
873 // exponentiation:
875 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
877 // This formula is trivially equivalent to the previous formula. However,
878 // this formula can be implemented much more efficiently. The trick is that
879 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
880 // arithmetic. To do exact division in modular arithmetic, all we have
881 // to do is multiply by the inverse. Therefore, this step can be done at
882 // width W.
884 // The next issue is how to safely do the division by 2^T. The way this
885 // is done is by doing the multiplication step at a width of at least W + T
886 // bits. This way, the bottom W+T bits of the product are accurate. Then,
887 // when we perform the division by 2^T (which is equivalent to a right shift
888 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
889 // truncated out after the division by 2^T.
891 // In comparison to just directly using the first formula, this technique
892 // is much more efficient; using the first formula requires W * K bits,
893 // but this formula less than W + K bits. Also, the first formula requires
894 // a division step, whereas this formula only requires multiplies and shifts.
896 // It doesn't matter whether the subtraction step is done in the calculation
897 // width or the input iteration count's width; if the subtraction overflows,
898 // the result must be zero anyway. We prefer here to do it in the width of
899 // the induction variable because it helps a lot for certain cases; CodeGen
900 // isn't smart enough to ignore the overflow, which leads to much less
901 // efficient code if the width of the subtraction is wider than the native
902 // register width.
904 // (It's possible to not widen at all by pulling out factors of 2 before
905 // the multiplication; for example, K=2 can be calculated as
906 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
907 // extra arithmetic, so it's not an obvious win, and it gets
908 // much more complicated for K > 3.)
910 // Protection from insane SCEVs; this bound is conservative,
911 // but it probably doesn't matter.
912 if (K > 1000)
913 return SE.getCouldNotCompute();
915 unsigned W = SE.getTypeSizeInBits(ResultTy);
917 // Calculate K! / 2^T and T; we divide out the factors of two before
918 // multiplying for calculating K! / 2^T to avoid overflow.
919 // Other overflow doesn't matter because we only care about the bottom
920 // W bits of the result.
921 APInt OddFactorial(W, 1);
922 unsigned T = 1;
923 for (unsigned i = 3; i <= K; ++i) {
924 APInt Mult(W, i);
925 unsigned TwoFactors = Mult.countr_zero();
926 T += TwoFactors;
927 Mult.lshrInPlace(TwoFactors);
928 OddFactorial *= Mult;
931 // We need at least W + T bits for the multiplication step
932 unsigned CalculationBits = W + T;
934 // Calculate 2^T, at width T+W.
935 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
937 // Calculate the multiplicative inverse of K! / 2^T;
938 // this multiplication factor will perform the exact division by
939 // K! / 2^T.
940 APInt Mod = APInt::getSignedMinValue(W+1);
941 APInt MultiplyFactor = OddFactorial.zext(W+1);
942 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
943 MultiplyFactor = MultiplyFactor.trunc(W);
945 // Calculate the product, at width T+W
946 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
947 CalculationBits);
948 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
949 for (unsigned i = 1; i != K; ++i) {
950 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
951 Dividend = SE.getMulExpr(Dividend,
952 SE.getTruncateOrZeroExtend(S, CalculationTy));
955 // Divide by 2^T
956 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
958 // Truncate the result, and divide by K! / 2^T.
960 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
961 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
964 /// Return the value of this chain of recurrences at the specified iteration
965 /// number. We can evaluate this recurrence by multiplying each element in the
966 /// chain by the binomial coefficient corresponding to it. In other words, we
967 /// can evaluate {A,+,B,+,C,+,D} as:
969 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
971 /// where BC(It, k) stands for binomial coefficient.
972 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
973 ScalarEvolution &SE) const {
974 return evaluateAtIteration(operands(), It, SE);
977 const SCEV *
978 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands,
979 const SCEV *It, ScalarEvolution &SE) {
980 assert(Operands.size() > 0);
981 const SCEV *Result = Operands[0];
982 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
983 // The computation is correct in the face of overflow provided that the
984 // multiplication is performed _after_ the evaluation of the binomial
985 // coefficient.
986 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
987 if (isa<SCEVCouldNotCompute>(Coeff))
988 return Coeff;
990 Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff));
992 return Result;
995 //===----------------------------------------------------------------------===//
996 // SCEV Expression folder implementations
997 //===----------------------------------------------------------------------===//
999 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op,
1000 unsigned Depth) {
1001 assert(Depth <= 1 &&
1002 "getLosslessPtrToIntExpr() should self-recurse at most once.");
1004 // We could be called with an integer-typed operands during SCEV rewrites.
1005 // Since the operand is an integer already, just perform zext/trunc/self cast.
1006 if (!Op->getType()->isPointerTy())
1007 return Op;
1009 // What would be an ID for such a SCEV cast expression?
1010 FoldingSetNodeID ID;
1011 ID.AddInteger(scPtrToInt);
1012 ID.AddPointer(Op);
1014 void *IP = nullptr;
1016 // Is there already an expression for such a cast?
1017 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1018 return S;
1020 // It isn't legal for optimizations to construct new ptrtoint expressions
1021 // for non-integral pointers.
1022 if (getDataLayout().isNonIntegralPointerType(Op->getType()))
1023 return getCouldNotCompute();
1025 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1027 // We can only trivially model ptrtoint if SCEV's effective (integer) type
1028 // is sufficiently wide to represent all possible pointer values.
1029 // We could theoretically teach SCEV to truncate wider pointers, but
1030 // that isn't implemented for now.
1031 if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) !=
1032 getDataLayout().getTypeSizeInBits(IntPtrTy))
1033 return getCouldNotCompute();
1035 // If not, is this expression something we can't reduce any further?
1036 if (auto *U = dyn_cast<SCEVUnknown>(Op)) {
1037 // Perform some basic constant folding. If the operand of the ptr2int cast
1038 // is a null pointer, don't create a ptr2int SCEV expression (that will be
1039 // left as-is), but produce a zero constant.
1040 // NOTE: We could handle a more general case, but lack motivational cases.
1041 if (isa<ConstantPointerNull>(U->getValue()))
1042 return getZero(IntPtrTy);
1044 // Create an explicit cast node.
1045 // We can reuse the existing insert position since if we get here,
1046 // we won't have made any changes which would invalidate it.
1047 SCEV *S = new (SCEVAllocator)
1048 SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1049 UniqueSCEVs.InsertNode(S, IP);
1050 registerUser(S, Op);
1051 return S;
1054 assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for "
1055 "non-SCEVUnknown's.");
1057 // Otherwise, we've got some expression that is more complex than just a
1058 // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1059 // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1060 // only, and the expressions must otherwise be integer-typed.
1061 // So sink the cast down to the SCEVUnknown's.
1063 /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1064 /// which computes a pointer-typed value, and rewrites the whole expression
1065 /// tree so that *all* the computations are done on integers, and the only
1066 /// pointer-typed operands in the expression are SCEVUnknown.
1067 class SCEVPtrToIntSinkingRewriter
1068 : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1069 using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>;
1071 public:
1072 SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1074 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1075 SCEVPtrToIntSinkingRewriter Rewriter(SE);
1076 return Rewriter.visit(Scev);
1079 const SCEV *visit(const SCEV *S) {
1080 Type *STy = S->getType();
1081 // If the expression is not pointer-typed, just keep it as-is.
1082 if (!STy->isPointerTy())
1083 return S;
1084 // Else, recursively sink the cast down into it.
1085 return Base::visit(S);
1088 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1089 SmallVector<const SCEV *, 2> Operands;
1090 bool Changed = false;
1091 for (const auto *Op : Expr->operands()) {
1092 Operands.push_back(visit(Op));
1093 Changed |= Op != Operands.back();
1095 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1098 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1099 SmallVector<const SCEV *, 2> Operands;
1100 bool Changed = false;
1101 for (const auto *Op : Expr->operands()) {
1102 Operands.push_back(visit(Op));
1103 Changed |= Op != Operands.back();
1105 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1108 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1109 assert(Expr->getType()->isPointerTy() &&
1110 "Should only reach pointer-typed SCEVUnknown's.");
1111 return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1);
1115 // And actually perform the cast sinking.
1116 const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1117 assert(IntOp->getType()->isIntegerTy() &&
1118 "We must have succeeded in sinking the cast, "
1119 "and ending up with an integer-typed expression!");
1120 return IntOp;
1123 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) {
1124 assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1126 const SCEV *IntOp = getLosslessPtrToIntExpr(Op);
1127 if (isa<SCEVCouldNotCompute>(IntOp))
1128 return IntOp;
1130 return getTruncateOrZeroExtend(IntOp, Ty);
1133 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1134 unsigned Depth) {
1135 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1136 "This is not a truncating conversion!");
1137 assert(isSCEVable(Ty) &&
1138 "This is not a conversion to a SCEVable type!");
1139 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1140 Ty = getEffectiveSCEVType(Ty);
1142 FoldingSetNodeID ID;
1143 ID.AddInteger(scTruncate);
1144 ID.AddPointer(Op);
1145 ID.AddPointer(Ty);
1146 void *IP = nullptr;
1147 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1149 // Fold if the operand is constant.
1150 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1151 return getConstant(
1152 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1154 // trunc(trunc(x)) --> trunc(x)
1155 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1156 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1158 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1159 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1160 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1162 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1163 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1164 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1166 if (Depth > MaxCastDepth) {
1167 SCEV *S =
1168 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1169 UniqueSCEVs.InsertNode(S, IP);
1170 registerUser(S, Op);
1171 return S;
1174 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1175 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1176 // if after transforming we have at most one truncate, not counting truncates
1177 // that replace other casts.
1178 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1179 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1180 SmallVector<const SCEV *, 4> Operands;
1181 unsigned numTruncs = 0;
1182 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1183 ++i) {
1184 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1185 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1186 isa<SCEVTruncateExpr>(S))
1187 numTruncs++;
1188 Operands.push_back(S);
1190 if (numTruncs < 2) {
1191 if (isa<SCEVAddExpr>(Op))
1192 return getAddExpr(Operands);
1193 if (isa<SCEVMulExpr>(Op))
1194 return getMulExpr(Operands);
1195 llvm_unreachable("Unexpected SCEV type for Op.");
1197 // Although we checked in the beginning that ID is not in the cache, it is
1198 // possible that during recursion and different modification ID was inserted
1199 // into the cache. So if we find it, just return it.
1200 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1201 return S;
1204 // If the input value is a chrec scev, truncate the chrec's operands.
1205 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1206 SmallVector<const SCEV *, 4> Operands;
1207 for (const SCEV *Op : AddRec->operands())
1208 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1209 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1212 // Return zero if truncating to known zeros.
1213 uint32_t MinTrailingZeros = getMinTrailingZeros(Op);
1214 if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1215 return getZero(Ty);
1217 // The cast wasn't folded; create an explicit cast node. We can reuse
1218 // the existing insert position since if we get here, we won't have
1219 // made any changes which would invalidate it.
1220 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1221 Op, Ty);
1222 UniqueSCEVs.InsertNode(S, IP);
1223 registerUser(S, Op);
1224 return S;
1227 // Get the limit of a recurrence such that incrementing by Step cannot cause
1228 // signed overflow as long as the value of the recurrence within the
1229 // loop does not exceed this limit before incrementing.
1230 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1231 ICmpInst::Predicate *Pred,
1232 ScalarEvolution *SE) {
1233 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1234 if (SE->isKnownPositive(Step)) {
1235 *Pred = ICmpInst::ICMP_SLT;
1236 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1237 SE->getSignedRangeMax(Step));
1239 if (SE->isKnownNegative(Step)) {
1240 *Pred = ICmpInst::ICMP_SGT;
1241 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1242 SE->getSignedRangeMin(Step));
1244 return nullptr;
1247 // Get the limit of a recurrence such that incrementing by Step cannot cause
1248 // unsigned overflow as long as the value of the recurrence within the loop does
1249 // not exceed this limit before incrementing.
1250 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1251 ICmpInst::Predicate *Pred,
1252 ScalarEvolution *SE) {
1253 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1254 *Pred = ICmpInst::ICMP_ULT;
1256 return SE->getConstant(APInt::getMinValue(BitWidth) -
1257 SE->getUnsignedRangeMax(Step));
1260 namespace {
1262 struct ExtendOpTraitsBase {
1263 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1264 unsigned);
1267 // Used to make code generic over signed and unsigned overflow.
1268 template <typename ExtendOp> struct ExtendOpTraits {
1269 // Members present:
1271 // static const SCEV::NoWrapFlags WrapType;
1273 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1275 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1276 // ICmpInst::Predicate *Pred,
1277 // ScalarEvolution *SE);
1280 template <>
1281 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1282 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1284 static const GetExtendExprTy GetExtendExpr;
1286 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1287 ICmpInst::Predicate *Pred,
1288 ScalarEvolution *SE) {
1289 return getSignedOverflowLimitForStep(Step, Pred, SE);
1293 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1294 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1296 template <>
1297 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1298 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1300 static const GetExtendExprTy GetExtendExpr;
1302 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1303 ICmpInst::Predicate *Pred,
1304 ScalarEvolution *SE) {
1305 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1309 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1310 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1312 } // end anonymous namespace
1314 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1315 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1316 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1317 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1318 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1319 // expression "Step + sext/zext(PreIncAR)" is congruent with
1320 // "sext/zext(PostIncAR)"
1321 template <typename ExtendOpTy>
1322 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1323 ScalarEvolution *SE, unsigned Depth) {
1324 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1325 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1327 const Loop *L = AR->getLoop();
1328 const SCEV *Start = AR->getStart();
1329 const SCEV *Step = AR->getStepRecurrence(*SE);
1331 // Check for a simple looking step prior to loop entry.
1332 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1333 if (!SA)
1334 return nullptr;
1336 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1337 // subtraction is expensive. For this purpose, perform a quick and dirty
1338 // difference, by checking for Step in the operand list. Note, that
1339 // SA might have repeated ops, like %a + %a + ..., so only remove one.
1340 SmallVector<const SCEV *, 4> DiffOps(SA->operands());
1341 for (auto It = DiffOps.begin(); It != DiffOps.end(); ++It)
1342 if (*It == Step) {
1343 DiffOps.erase(It);
1344 break;
1347 if (DiffOps.size() == SA->getNumOperands())
1348 return nullptr;
1350 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1351 // `Step`:
1353 // 1. NSW/NUW flags on the step increment.
1354 auto PreStartFlags =
1355 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1356 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1357 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1358 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1360 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1361 // "S+X does not sign/unsign-overflow".
1364 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1365 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1366 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1367 return PreStart;
1369 // 2. Direct overflow check on the step operation's expression.
1370 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1371 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1372 const SCEV *OperandExtendedStart =
1373 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1374 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1375 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1376 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1377 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1378 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1379 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1380 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1382 return PreStart;
1385 // 3. Loop precondition.
1386 ICmpInst::Predicate Pred;
1387 const SCEV *OverflowLimit =
1388 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1390 if (OverflowLimit &&
1391 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1392 return PreStart;
1394 return nullptr;
1397 // Get the normalized zero or sign extended expression for this AddRec's Start.
1398 template <typename ExtendOpTy>
1399 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1400 ScalarEvolution *SE,
1401 unsigned Depth) {
1402 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1404 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1405 if (!PreStart)
1406 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1408 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1409 Depth),
1410 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1413 // Try to prove away overflow by looking at "nearby" add recurrences. A
1414 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1415 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1417 // Formally:
1419 // {S,+,X} == {S-T,+,X} + T
1420 // => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1422 // If ({S-T,+,X} + T) does not overflow ... (1)
1424 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1426 // If {S-T,+,X} does not overflow ... (2)
1428 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1429 // == {Ext(S-T)+Ext(T),+,Ext(X)}
1431 // If (S-T)+T does not overflow ... (3)
1433 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1434 // == {Ext(S),+,Ext(X)} == LHS
1436 // Thus, if (1), (2) and (3) are true for some T, then
1437 // Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1439 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1440 // does not overflow" restricted to the 0th iteration. Therefore we only need
1441 // to check for (1) and (2).
1443 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1444 // is `Delta` (defined below).
1445 template <typename ExtendOpTy>
1446 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1447 const SCEV *Step,
1448 const Loop *L) {
1449 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1451 // We restrict `Start` to a constant to prevent SCEV from spending too much
1452 // time here. It is correct (but more expensive) to continue with a
1453 // non-constant `Start` and do a general SCEV subtraction to compute
1454 // `PreStart` below.
1455 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1456 if (!StartC)
1457 return false;
1459 APInt StartAI = StartC->getAPInt();
1461 for (unsigned Delta : {-2, -1, 1, 2}) {
1462 const SCEV *PreStart = getConstant(StartAI - Delta);
1464 FoldingSetNodeID ID;
1465 ID.AddInteger(scAddRecExpr);
1466 ID.AddPointer(PreStart);
1467 ID.AddPointer(Step);
1468 ID.AddPointer(L);
1469 void *IP = nullptr;
1470 const auto *PreAR =
1471 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1473 // Give up if we don't already have the add recurrence we need because
1474 // actually constructing an add recurrence is relatively expensive.
1475 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1476 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1477 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1478 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1479 DeltaS, &Pred, this);
1480 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1481 return true;
1485 return false;
1488 // Finds an integer D for an expression (C + x + y + ...) such that the top
1489 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1490 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1491 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1492 // the (C + x + y + ...) expression is \p WholeAddExpr.
1493 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1494 const SCEVConstant *ConstantTerm,
1495 const SCEVAddExpr *WholeAddExpr) {
1496 const APInt &C = ConstantTerm->getAPInt();
1497 const unsigned BitWidth = C.getBitWidth();
1498 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1499 uint32_t TZ = BitWidth;
1500 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1501 TZ = std::min(TZ, SE.getMinTrailingZeros(WholeAddExpr->getOperand(I)));
1502 if (TZ) {
1503 // Set D to be as many least significant bits of C as possible while still
1504 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1505 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1507 return APInt(BitWidth, 0);
1510 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1511 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1512 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1513 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1514 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1515 const APInt &ConstantStart,
1516 const SCEV *Step) {
1517 const unsigned BitWidth = ConstantStart.getBitWidth();
1518 const uint32_t TZ = SE.getMinTrailingZeros(Step);
1519 if (TZ)
1520 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1521 : ConstantStart;
1522 return APInt(BitWidth, 0);
1525 static void insertFoldCacheEntry(
1526 const ScalarEvolution::FoldID &ID, const SCEV *S,
1527 DenseMap<ScalarEvolution::FoldID, const SCEV *> &FoldCache,
1528 DenseMap<const SCEV *, SmallVector<ScalarEvolution::FoldID, 2>>
1529 &FoldCacheUser) {
1530 auto I = FoldCache.insert({ID, S});
1531 if (!I.second) {
1532 // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1533 // entry.
1534 auto &UserIDs = FoldCacheUser[I.first->second];
1535 assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
1536 for (unsigned I = 0; I != UserIDs.size(); ++I)
1537 if (UserIDs[I] == ID) {
1538 std::swap(UserIDs[I], UserIDs.back());
1539 break;
1541 UserIDs.pop_back();
1542 I.first->second = S;
1544 auto R = FoldCacheUser.insert({S, {}});
1545 R.first->second.push_back(ID);
1548 const SCEV *
1549 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1550 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1551 "This is not an extending conversion!");
1552 assert(isSCEVable(Ty) &&
1553 "This is not a conversion to a SCEVable type!");
1554 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1555 Ty = getEffectiveSCEVType(Ty);
1557 FoldID ID(scZeroExtend, Op, Ty);
1558 auto Iter = FoldCache.find(ID);
1559 if (Iter != FoldCache.end())
1560 return Iter->second;
1562 const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1563 if (!isa<SCEVZeroExtendExpr>(S))
1564 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1565 return S;
1568 const SCEV *ScalarEvolution::getZeroExtendExprImpl(const SCEV *Op, Type *Ty,
1569 unsigned Depth) {
1570 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1571 "This is not an extending conversion!");
1572 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1573 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1575 // Fold if the operand is constant.
1576 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1577 return getConstant(SC->getAPInt().zext(getTypeSizeInBits(Ty)));
1579 // zext(zext(x)) --> zext(x)
1580 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1581 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1583 // Before doing any expensive analysis, check to see if we've already
1584 // computed a SCEV for this Op and Ty.
1585 FoldingSetNodeID ID;
1586 ID.AddInteger(scZeroExtend);
1587 ID.AddPointer(Op);
1588 ID.AddPointer(Ty);
1589 void *IP = nullptr;
1590 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1591 if (Depth > MaxCastDepth) {
1592 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1593 Op, Ty);
1594 UniqueSCEVs.InsertNode(S, IP);
1595 registerUser(S, Op);
1596 return S;
1599 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1600 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1601 // It's possible the bits taken off by the truncate were all zero bits. If
1602 // so, we should be able to simplify this further.
1603 const SCEV *X = ST->getOperand();
1604 ConstantRange CR = getUnsignedRange(X);
1605 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1606 unsigned NewBits = getTypeSizeInBits(Ty);
1607 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1608 CR.zextOrTrunc(NewBits)))
1609 return getTruncateOrZeroExtend(X, Ty, Depth);
1612 // If the input value is a chrec scev, and we can prove that the value
1613 // did not overflow the old, smaller, value, we can zero extend all of the
1614 // operands (often constants). This allows analysis of something like
1615 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1616 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1617 if (AR->isAffine()) {
1618 const SCEV *Start = AR->getStart();
1619 const SCEV *Step = AR->getStepRecurrence(*this);
1620 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1621 const Loop *L = AR->getLoop();
1623 // If we have special knowledge that this addrec won't overflow,
1624 // we don't need to do any further analysis.
1625 if (AR->hasNoUnsignedWrap()) {
1626 Start =
1627 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1628 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1629 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1632 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1633 // Note that this serves two purposes: It filters out loops that are
1634 // simply not analyzable, and it covers the case where this code is
1635 // being called from within backedge-taken count analysis, such that
1636 // attempting to ask for the backedge-taken count would likely result
1637 // in infinite recursion. In the later case, the analysis code will
1638 // cope with a conservative value, and it will take care to purge
1639 // that value once it has finished.
1640 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1641 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1642 // Manually compute the final value for AR, checking for overflow.
1644 // Check whether the backedge-taken count can be losslessly casted to
1645 // the addrec's type. The count is always unsigned.
1646 const SCEV *CastedMaxBECount =
1647 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1648 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1649 CastedMaxBECount, MaxBECount->getType(), Depth);
1650 if (MaxBECount == RecastedMaxBECount) {
1651 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1652 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1653 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1654 SCEV::FlagAnyWrap, Depth + 1);
1655 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1656 SCEV::FlagAnyWrap,
1657 Depth + 1),
1658 WideTy, Depth + 1);
1659 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1660 const SCEV *WideMaxBECount =
1661 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1662 const SCEV *OperandExtendedAdd =
1663 getAddExpr(WideStart,
1664 getMulExpr(WideMaxBECount,
1665 getZeroExtendExpr(Step, WideTy, Depth + 1),
1666 SCEV::FlagAnyWrap, Depth + 1),
1667 SCEV::FlagAnyWrap, Depth + 1);
1668 if (ZAdd == OperandExtendedAdd) {
1669 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1670 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1671 // Return the expression with the addrec on the outside.
1672 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1673 Depth + 1);
1674 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1675 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1677 // Similar to above, only this time treat the step value as signed.
1678 // This covers loops that count down.
1679 OperandExtendedAdd =
1680 getAddExpr(WideStart,
1681 getMulExpr(WideMaxBECount,
1682 getSignExtendExpr(Step, WideTy, Depth + 1),
1683 SCEV::FlagAnyWrap, Depth + 1),
1684 SCEV::FlagAnyWrap, Depth + 1);
1685 if (ZAdd == OperandExtendedAdd) {
1686 // Cache knowledge of AR NW, which is propagated to this AddRec.
1687 // Negative step causes unsigned wrap, but it still can't self-wrap.
1688 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1689 // Return the expression with the addrec on the outside.
1690 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1691 Depth + 1);
1692 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1693 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1698 // Normally, in the cases we can prove no-overflow via a
1699 // backedge guarding condition, we can also compute a backedge
1700 // taken count for the loop. The exceptions are assumptions and
1701 // guards present in the loop -- SCEV is not great at exploiting
1702 // these to compute max backedge taken counts, but can still use
1703 // these to prove lack of overflow. Use this fact to avoid
1704 // doing extra work that may not pay off.
1705 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1706 !AC.assumptions().empty()) {
1708 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1709 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1710 if (AR->hasNoUnsignedWrap()) {
1711 // Same as nuw case above - duplicated here to avoid a compile time
1712 // issue. It's not clear that the order of checks does matter, but
1713 // it's one of two issue possible causes for a change which was
1714 // reverted. Be conservative for the moment.
1715 Start =
1716 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1717 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1718 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1721 // For a negative step, we can extend the operands iff doing so only
1722 // traverses values in the range zext([0,UINT_MAX]).
1723 if (isKnownNegative(Step)) {
1724 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1725 getSignedRangeMin(Step));
1726 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1727 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1728 // Cache knowledge of AR NW, which is propagated to this
1729 // AddRec. Negative step causes unsigned wrap, but it
1730 // still can't self-wrap.
1731 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1732 // Return the expression with the addrec on the outside.
1733 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1734 Depth + 1);
1735 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1736 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1741 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1742 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1743 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1744 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1745 const APInt &C = SC->getAPInt();
1746 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1747 if (D != 0) {
1748 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1749 const SCEV *SResidual =
1750 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1751 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1752 return getAddExpr(SZExtD, SZExtR,
1753 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1754 Depth + 1);
1758 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1759 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1760 Start =
1761 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1762 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1763 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1767 // zext(A % B) --> zext(A) % zext(B)
1769 const SCEV *LHS;
1770 const SCEV *RHS;
1771 if (matchURem(Op, LHS, RHS))
1772 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1773 getZeroExtendExpr(RHS, Ty, Depth + 1));
1776 // zext(A / B) --> zext(A) / zext(B).
1777 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1778 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1779 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1781 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1782 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1783 if (SA->hasNoUnsignedWrap()) {
1784 // If the addition does not unsign overflow then we can, by definition,
1785 // commute the zero extension with the addition operation.
1786 SmallVector<const SCEV *, 4> Ops;
1787 for (const auto *Op : SA->operands())
1788 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1789 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1792 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1793 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1794 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1796 // Often address arithmetics contain expressions like
1797 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1798 // This transformation is useful while proving that such expressions are
1799 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1800 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1801 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1802 if (D != 0) {
1803 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1804 const SCEV *SResidual =
1805 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1806 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1807 return getAddExpr(SZExtD, SZExtR,
1808 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1809 Depth + 1);
1814 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1815 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1816 if (SM->hasNoUnsignedWrap()) {
1817 // If the multiply does not unsign overflow then we can, by definition,
1818 // commute the zero extension with the multiply operation.
1819 SmallVector<const SCEV *, 4> Ops;
1820 for (const auto *Op : SM->operands())
1821 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1822 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1825 // zext(2^K * (trunc X to iN)) to iM ->
1826 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1828 // Proof:
1830 // zext(2^K * (trunc X to iN)) to iM
1831 // = zext((trunc X to iN) << K) to iM
1832 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1833 // (because shl removes the top K bits)
1834 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1835 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1837 if (SM->getNumOperands() == 2)
1838 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1839 if (MulLHS->getAPInt().isPowerOf2())
1840 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1841 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1842 MulLHS->getAPInt().logBase2();
1843 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1844 return getMulExpr(
1845 getZeroExtendExpr(MulLHS, Ty),
1846 getZeroExtendExpr(
1847 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1848 SCEV::FlagNUW, Depth + 1);
1852 // zext(umin(x, y)) -> umin(zext(x), zext(y))
1853 // zext(umax(x, y)) -> umax(zext(x), zext(y))
1854 if (isa<SCEVUMinExpr>(Op) || isa<SCEVUMaxExpr>(Op)) {
1855 auto *MinMax = cast<SCEVMinMaxExpr>(Op);
1856 SmallVector<const SCEV *, 4> Operands;
1857 for (auto *Operand : MinMax->operands())
1858 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1859 if (isa<SCEVUMinExpr>(MinMax))
1860 return getUMinExpr(Operands);
1861 return getUMaxExpr(Operands);
1864 // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
1865 if (auto *MinMax = dyn_cast<SCEVSequentialMinMaxExpr>(Op)) {
1866 assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!");
1867 SmallVector<const SCEV *, 4> Operands;
1868 for (auto *Operand : MinMax->operands())
1869 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1870 return getUMinExpr(Operands, /*Sequential*/ true);
1873 // The cast wasn't folded; create an explicit cast node.
1874 // Recompute the insert position, as it may have been invalidated.
1875 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1876 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1877 Op, Ty);
1878 UniqueSCEVs.InsertNode(S, IP);
1879 registerUser(S, Op);
1880 return S;
1883 const SCEV *
1884 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1885 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1886 "This is not an extending conversion!");
1887 assert(isSCEVable(Ty) &&
1888 "This is not a conversion to a SCEVable type!");
1889 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1890 Ty = getEffectiveSCEVType(Ty);
1892 FoldID ID(scSignExtend, Op, Ty);
1893 auto Iter = FoldCache.find(ID);
1894 if (Iter != FoldCache.end())
1895 return Iter->second;
1897 const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
1898 if (!isa<SCEVSignExtendExpr>(S))
1899 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1900 return S;
1903 const SCEV *ScalarEvolution::getSignExtendExprImpl(const SCEV *Op, Type *Ty,
1904 unsigned Depth) {
1905 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1906 "This is not an extending conversion!");
1907 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1908 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1909 Ty = getEffectiveSCEVType(Ty);
1911 // Fold if the operand is constant.
1912 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1913 return getConstant(SC->getAPInt().sext(getTypeSizeInBits(Ty)));
1915 // sext(sext(x)) --> sext(x)
1916 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1917 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1919 // sext(zext(x)) --> zext(x)
1920 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1921 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1923 // Before doing any expensive analysis, check to see if we've already
1924 // computed a SCEV for this Op and Ty.
1925 FoldingSetNodeID ID;
1926 ID.AddInteger(scSignExtend);
1927 ID.AddPointer(Op);
1928 ID.AddPointer(Ty);
1929 void *IP = nullptr;
1930 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1931 // Limit recursion depth.
1932 if (Depth > MaxCastDepth) {
1933 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1934 Op, Ty);
1935 UniqueSCEVs.InsertNode(S, IP);
1936 registerUser(S, Op);
1937 return S;
1940 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1941 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1942 // It's possible the bits taken off by the truncate were all sign bits. If
1943 // so, we should be able to simplify this further.
1944 const SCEV *X = ST->getOperand();
1945 ConstantRange CR = getSignedRange(X);
1946 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1947 unsigned NewBits = getTypeSizeInBits(Ty);
1948 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1949 CR.sextOrTrunc(NewBits)))
1950 return getTruncateOrSignExtend(X, Ty, Depth);
1953 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1954 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1955 if (SA->hasNoSignedWrap()) {
1956 // If the addition does not sign overflow then we can, by definition,
1957 // commute the sign extension with the addition operation.
1958 SmallVector<const SCEV *, 4> Ops;
1959 for (const auto *Op : SA->operands())
1960 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1961 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1964 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1965 // if D + (C - D + x + y + ...) could be proven to not signed wrap
1966 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1968 // For instance, this will bring two seemingly different expressions:
1969 // 1 + sext(5 + 20 * %x + 24 * %y) and
1970 // sext(6 + 20 * %x + 24 * %y)
1971 // to the same form:
1972 // 2 + sext(4 + 20 * %x + 24 * %y)
1973 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1974 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1975 if (D != 0) {
1976 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1977 const SCEV *SResidual =
1978 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1979 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1980 return getAddExpr(SSExtD, SSExtR,
1981 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1982 Depth + 1);
1986 // If the input value is a chrec scev, and we can prove that the value
1987 // did not overflow the old, smaller, value, we can sign extend all of the
1988 // operands (often constants). This allows analysis of something like
1989 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1990 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1991 if (AR->isAffine()) {
1992 const SCEV *Start = AR->getStart();
1993 const SCEV *Step = AR->getStepRecurrence(*this);
1994 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1995 const Loop *L = AR->getLoop();
1997 // If we have special knowledge that this addrec won't overflow,
1998 // we don't need to do any further analysis.
1999 if (AR->hasNoSignedWrap()) {
2000 Start =
2001 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2002 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2003 return getAddRecExpr(Start, Step, L, SCEV::FlagNSW);
2006 // Check whether the backedge-taken count is SCEVCouldNotCompute.
2007 // Note that this serves two purposes: It filters out loops that are
2008 // simply not analyzable, and it covers the case where this code is
2009 // being called from within backedge-taken count analysis, such that
2010 // attempting to ask for the backedge-taken count would likely result
2011 // in infinite recursion. In the later case, the analysis code will
2012 // cope with a conservative value, and it will take care to purge
2013 // that value once it has finished.
2014 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2015 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2016 // Manually compute the final value for AR, checking for
2017 // overflow.
2019 // Check whether the backedge-taken count can be losslessly casted to
2020 // the addrec's type. The count is always unsigned.
2021 const SCEV *CastedMaxBECount =
2022 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2023 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2024 CastedMaxBECount, MaxBECount->getType(), Depth);
2025 if (MaxBECount == RecastedMaxBECount) {
2026 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2027 // Check whether Start+Step*MaxBECount has no signed overflow.
2028 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2029 SCEV::FlagAnyWrap, Depth + 1);
2030 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2031 SCEV::FlagAnyWrap,
2032 Depth + 1),
2033 WideTy, Depth + 1);
2034 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2035 const SCEV *WideMaxBECount =
2036 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2037 const SCEV *OperandExtendedAdd =
2038 getAddExpr(WideStart,
2039 getMulExpr(WideMaxBECount,
2040 getSignExtendExpr(Step, WideTy, Depth + 1),
2041 SCEV::FlagAnyWrap, Depth + 1),
2042 SCEV::FlagAnyWrap, Depth + 1);
2043 if (SAdd == OperandExtendedAdd) {
2044 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2045 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2046 // Return the expression with the addrec on the outside.
2047 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2048 Depth + 1);
2049 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2050 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2052 // Similar to above, only this time treat the step value as unsigned.
2053 // This covers loops that count up with an unsigned step.
2054 OperandExtendedAdd =
2055 getAddExpr(WideStart,
2056 getMulExpr(WideMaxBECount,
2057 getZeroExtendExpr(Step, WideTy, Depth + 1),
2058 SCEV::FlagAnyWrap, Depth + 1),
2059 SCEV::FlagAnyWrap, Depth + 1);
2060 if (SAdd == OperandExtendedAdd) {
2061 // If AR wraps around then
2063 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2064 // => SAdd != OperandExtendedAdd
2066 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2067 // (SAdd == OperandExtendedAdd => AR is NW)
2069 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2071 // Return the expression with the addrec on the outside.
2072 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2073 Depth + 1);
2074 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
2075 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2080 auto NewFlags = proveNoSignedWrapViaInduction(AR);
2081 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2082 if (AR->hasNoSignedWrap()) {
2083 // Same as nsw case above - duplicated here to avoid a compile time
2084 // issue. It's not clear that the order of checks does matter, but
2085 // it's one of two issue possible causes for a change which was
2086 // reverted. Be conservative for the moment.
2087 Start =
2088 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2089 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2090 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2093 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2094 // if D + (C - D + Step * n) could be proven to not signed wrap
2095 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2096 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2097 const APInt &C = SC->getAPInt();
2098 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2099 if (D != 0) {
2100 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2101 const SCEV *SResidual =
2102 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2103 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2104 return getAddExpr(SSExtD, SSExtR,
2105 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2106 Depth + 1);
2110 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2111 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2112 Start =
2113 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2114 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2115 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2119 // If the input value is provably positive and we could not simplify
2120 // away the sext build a zext instead.
2121 if (isKnownNonNegative(Op))
2122 return getZeroExtendExpr(Op, Ty, Depth + 1);
2124 // sext(smin(x, y)) -> smin(sext(x), sext(y))
2125 // sext(smax(x, y)) -> smax(sext(x), sext(y))
2126 if (isa<SCEVSMinExpr>(Op) || isa<SCEVSMaxExpr>(Op)) {
2127 auto *MinMax = cast<SCEVMinMaxExpr>(Op);
2128 SmallVector<const SCEV *, 4> Operands;
2129 for (auto *Operand : MinMax->operands())
2130 Operands.push_back(getSignExtendExpr(Operand, Ty));
2131 if (isa<SCEVSMinExpr>(MinMax))
2132 return getSMinExpr(Operands);
2133 return getSMaxExpr(Operands);
2136 // The cast wasn't folded; create an explicit cast node.
2137 // Recompute the insert position, as it may have been invalidated.
2138 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2139 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2140 Op, Ty);
2141 UniqueSCEVs.InsertNode(S, IP);
2142 registerUser(S, { Op });
2143 return S;
2146 const SCEV *ScalarEvolution::getCastExpr(SCEVTypes Kind, const SCEV *Op,
2147 Type *Ty) {
2148 switch (Kind) {
2149 case scTruncate:
2150 return getTruncateExpr(Op, Ty);
2151 case scZeroExtend:
2152 return getZeroExtendExpr(Op, Ty);
2153 case scSignExtend:
2154 return getSignExtendExpr(Op, Ty);
2155 case scPtrToInt:
2156 return getPtrToIntExpr(Op, Ty);
2157 default:
2158 llvm_unreachable("Not a SCEV cast expression!");
2162 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2163 /// unspecified bits out to the given type.
2164 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2165 Type *Ty) {
2166 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2167 "This is not an extending conversion!");
2168 assert(isSCEVable(Ty) &&
2169 "This is not a conversion to a SCEVable type!");
2170 Ty = getEffectiveSCEVType(Ty);
2172 // Sign-extend negative constants.
2173 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2174 if (SC->getAPInt().isNegative())
2175 return getSignExtendExpr(Op, Ty);
2177 // Peel off a truncate cast.
2178 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2179 const SCEV *NewOp = T->getOperand();
2180 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2181 return getAnyExtendExpr(NewOp, Ty);
2182 return getTruncateOrNoop(NewOp, Ty);
2185 // Next try a zext cast. If the cast is folded, use it.
2186 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2187 if (!isa<SCEVZeroExtendExpr>(ZExt))
2188 return ZExt;
2190 // Next try a sext cast. If the cast is folded, use it.
2191 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2192 if (!isa<SCEVSignExtendExpr>(SExt))
2193 return SExt;
2195 // Force the cast to be folded into the operands of an addrec.
2196 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2197 SmallVector<const SCEV *, 4> Ops;
2198 for (const SCEV *Op : AR->operands())
2199 Ops.push_back(getAnyExtendExpr(Op, Ty));
2200 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2203 // If the expression is obviously signed, use the sext cast value.
2204 if (isa<SCEVSMaxExpr>(Op))
2205 return SExt;
2207 // Absent any other information, use the zext cast value.
2208 return ZExt;
2211 /// Process the given Ops list, which is a list of operands to be added under
2212 /// the given scale, update the given map. This is a helper function for
2213 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2214 /// that would form an add expression like this:
2216 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2218 /// where A and B are constants, update the map with these values:
2220 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2222 /// and add 13 + A*B*29 to AccumulatedConstant.
2223 /// This will allow getAddRecExpr to produce this:
2225 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2227 /// This form often exposes folding opportunities that are hidden in
2228 /// the original operand list.
2230 /// Return true iff it appears that any interesting folding opportunities
2231 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2232 /// the common case where no interesting opportunities are present, and
2233 /// is also used as a check to avoid infinite recursion.
2234 static bool
2235 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2236 SmallVectorImpl<const SCEV *> &NewOps,
2237 APInt &AccumulatedConstant,
2238 ArrayRef<const SCEV *> Ops, const APInt &Scale,
2239 ScalarEvolution &SE) {
2240 bool Interesting = false;
2242 // Iterate over the add operands. They are sorted, with constants first.
2243 unsigned i = 0;
2244 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2245 ++i;
2246 // Pull a buried constant out to the outside.
2247 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2248 Interesting = true;
2249 AccumulatedConstant += Scale * C->getAPInt();
2252 // Next comes everything else. We're especially interested in multiplies
2253 // here, but they're in the middle, so just visit the rest with one loop.
2254 for (; i != Ops.size(); ++i) {
2255 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2256 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2257 APInt NewScale =
2258 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2259 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2260 // A multiplication of a constant with another add; recurse.
2261 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2262 Interesting |=
2263 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2264 Add->operands(), NewScale, SE);
2265 } else {
2266 // A multiplication of a constant with some other value. Update
2267 // the map.
2268 SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands()));
2269 const SCEV *Key = SE.getMulExpr(MulOps);
2270 auto Pair = M.insert({Key, NewScale});
2271 if (Pair.second) {
2272 NewOps.push_back(Pair.first->first);
2273 } else {
2274 Pair.first->second += NewScale;
2275 // The map already had an entry for this value, which may indicate
2276 // a folding opportunity.
2277 Interesting = true;
2280 } else {
2281 // An ordinary operand. Update the map.
2282 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2283 M.insert({Ops[i], Scale});
2284 if (Pair.second) {
2285 NewOps.push_back(Pair.first->first);
2286 } else {
2287 Pair.first->second += Scale;
2288 // The map already had an entry for this value, which may indicate
2289 // a folding opportunity.
2290 Interesting = true;
2295 return Interesting;
2298 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed,
2299 const SCEV *LHS, const SCEV *RHS,
2300 const Instruction *CtxI) {
2301 const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *,
2302 SCEV::NoWrapFlags, unsigned);
2303 switch (BinOp) {
2304 default:
2305 llvm_unreachable("Unsupported binary op");
2306 case Instruction::Add:
2307 Operation = &ScalarEvolution::getAddExpr;
2308 break;
2309 case Instruction::Sub:
2310 Operation = &ScalarEvolution::getMinusSCEV;
2311 break;
2312 case Instruction::Mul:
2313 Operation = &ScalarEvolution::getMulExpr;
2314 break;
2317 const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
2318 Signed ? &ScalarEvolution::getSignExtendExpr
2319 : &ScalarEvolution::getZeroExtendExpr;
2321 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2322 auto *NarrowTy = cast<IntegerType>(LHS->getType());
2323 auto *WideTy =
2324 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2326 const SCEV *A = (this->*Extension)(
2327 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2328 const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2329 const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2330 const SCEV *B = (this->*Operation)(LHSB, RHSB, SCEV::FlagAnyWrap, 0);
2331 if (A == B)
2332 return true;
2333 // Can we use context to prove the fact we need?
2334 if (!CtxI)
2335 return false;
2336 // TODO: Support mul.
2337 if (BinOp == Instruction::Mul)
2338 return false;
2339 auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2340 // TODO: Lift this limitation.
2341 if (!RHSC)
2342 return false;
2343 APInt C = RHSC->getAPInt();
2344 unsigned NumBits = C.getBitWidth();
2345 bool IsSub = (BinOp == Instruction::Sub);
2346 bool IsNegativeConst = (Signed && C.isNegative());
2347 // Compute the direction and magnitude by which we need to check overflow.
2348 bool OverflowDown = IsSub ^ IsNegativeConst;
2349 APInt Magnitude = C;
2350 if (IsNegativeConst) {
2351 if (C == APInt::getSignedMinValue(NumBits))
2352 // TODO: SINT_MIN on inversion gives the same negative value, we don't
2353 // want to deal with that.
2354 return false;
2355 Magnitude = -C;
2358 ICmpInst::Predicate Pred = Signed ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
2359 if (OverflowDown) {
2360 // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2361 APInt Min = Signed ? APInt::getSignedMinValue(NumBits)
2362 : APInt::getMinValue(NumBits);
2363 APInt Limit = Min + Magnitude;
2364 return isKnownPredicateAt(Pred, getConstant(Limit), LHS, CtxI);
2365 } else {
2366 // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2367 APInt Max = Signed ? APInt::getSignedMaxValue(NumBits)
2368 : APInt::getMaxValue(NumBits);
2369 APInt Limit = Max - Magnitude;
2370 return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2374 std::optional<SCEV::NoWrapFlags>
2375 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp(
2376 const OverflowingBinaryOperator *OBO) {
2377 // It cannot be done any better.
2378 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2379 return std::nullopt;
2381 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2383 if (OBO->hasNoUnsignedWrap())
2384 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2385 if (OBO->hasNoSignedWrap())
2386 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2388 bool Deduced = false;
2390 if (OBO->getOpcode() != Instruction::Add &&
2391 OBO->getOpcode() != Instruction::Sub &&
2392 OBO->getOpcode() != Instruction::Mul)
2393 return std::nullopt;
2395 const SCEV *LHS = getSCEV(OBO->getOperand(0));
2396 const SCEV *RHS = getSCEV(OBO->getOperand(1));
2398 const Instruction *CtxI =
2399 UseContextForNoWrapFlagInference ? dyn_cast<Instruction>(OBO) : nullptr;
2400 if (!OBO->hasNoUnsignedWrap() &&
2401 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2402 /* Signed */ false, LHS, RHS, CtxI)) {
2403 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2404 Deduced = true;
2407 if (!OBO->hasNoSignedWrap() &&
2408 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2409 /* Signed */ true, LHS, RHS, CtxI)) {
2410 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2411 Deduced = true;
2414 if (Deduced)
2415 return Flags;
2416 return std::nullopt;
2419 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2420 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2421 // can't-overflow flags for the operation if possible.
2422 static SCEV::NoWrapFlags
2423 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2424 const ArrayRef<const SCEV *> Ops,
2425 SCEV::NoWrapFlags Flags) {
2426 using namespace std::placeholders;
2428 using OBO = OverflowingBinaryOperator;
2430 bool CanAnalyze =
2431 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2432 (void)CanAnalyze;
2433 assert(CanAnalyze && "don't call from other places!");
2435 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2436 SCEV::NoWrapFlags SignOrUnsignWrap =
2437 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2439 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2440 auto IsKnownNonNegative = [&](const SCEV *S) {
2441 return SE->isKnownNonNegative(S);
2444 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2445 Flags =
2446 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2448 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2450 if (SignOrUnsignWrap != SignOrUnsignMask &&
2451 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2452 isa<SCEVConstant>(Ops[0])) {
2454 auto Opcode = [&] {
2455 switch (Type) {
2456 case scAddExpr:
2457 return Instruction::Add;
2458 case scMulExpr:
2459 return Instruction::Mul;
2460 default:
2461 llvm_unreachable("Unexpected SCEV op.");
2463 }();
2465 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2467 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2468 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2469 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2470 Opcode, C, OBO::NoSignedWrap);
2471 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2472 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2475 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2476 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2477 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2478 Opcode, C, OBO::NoUnsignedWrap);
2479 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2480 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2484 // <0,+,nonnegative><nw> is also nuw
2485 // TODO: Add corresponding nsw case
2486 if (Type == scAddRecExpr && ScalarEvolution::hasFlags(Flags, SCEV::FlagNW) &&
2487 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2488 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2489 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2491 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2492 if (Type == scMulExpr && !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) &&
2493 Ops.size() == 2) {
2494 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2495 if (UDiv->getOperand(1) == Ops[1])
2496 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2497 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2498 if (UDiv->getOperand(1) == Ops[0])
2499 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2502 return Flags;
2505 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2506 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2509 /// Get a canonical add expression, or something simpler if possible.
2510 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2511 SCEV::NoWrapFlags OrigFlags,
2512 unsigned Depth) {
2513 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2514 "only nuw or nsw allowed");
2515 assert(!Ops.empty() && "Cannot get empty add!");
2516 if (Ops.size() == 1) return Ops[0];
2517 #ifndef NDEBUG
2518 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2519 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2520 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2521 "SCEVAddExpr operand types don't match!");
2522 unsigned NumPtrs = count_if(
2523 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2524 assert(NumPtrs <= 1 && "add has at most one pointer operand");
2525 #endif
2527 // Sort by complexity, this groups all similar expression types together.
2528 GroupByComplexity(Ops, &LI, DT);
2530 // If there are any constants, fold them together.
2531 unsigned Idx = 0;
2532 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2533 ++Idx;
2534 assert(Idx < Ops.size());
2535 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2536 // We found two constants, fold them together!
2537 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2538 if (Ops.size() == 2) return Ops[0];
2539 Ops.erase(Ops.begin()+1); // Erase the folded element
2540 LHSC = cast<SCEVConstant>(Ops[0]);
2543 // If we are left with a constant zero being added, strip it off.
2544 if (LHSC->getValue()->isZero()) {
2545 Ops.erase(Ops.begin());
2546 --Idx;
2549 if (Ops.size() == 1) return Ops[0];
2552 // Delay expensive flag strengthening until necessary.
2553 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2554 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2557 // Limit recursion calls depth.
2558 if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2559 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2561 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2562 // Don't strengthen flags if we have no new information.
2563 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2564 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2565 Add->setNoWrapFlags(ComputeFlags(Ops));
2566 return S;
2569 // Okay, check to see if the same value occurs in the operand list more than
2570 // once. If so, merge them together into an multiply expression. Since we
2571 // sorted the list, these values are required to be adjacent.
2572 Type *Ty = Ops[0]->getType();
2573 bool FoundMatch = false;
2574 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2575 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2576 // Scan ahead to count how many equal operands there are.
2577 unsigned Count = 2;
2578 while (i+Count != e && Ops[i+Count] == Ops[i])
2579 ++Count;
2580 // Merge the values into a multiply.
2581 const SCEV *Scale = getConstant(Ty, Count);
2582 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2583 if (Ops.size() == Count)
2584 return Mul;
2585 Ops[i] = Mul;
2586 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2587 --i; e -= Count - 1;
2588 FoundMatch = true;
2590 if (FoundMatch)
2591 return getAddExpr(Ops, OrigFlags, Depth + 1);
2593 // Check for truncates. If all the operands are truncated from the same
2594 // type, see if factoring out the truncate would permit the result to be
2595 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2596 // if the contents of the resulting outer trunc fold to something simple.
2597 auto FindTruncSrcType = [&]() -> Type * {
2598 // We're ultimately looking to fold an addrec of truncs and muls of only
2599 // constants and truncs, so if we find any other types of SCEV
2600 // as operands of the addrec then we bail and return nullptr here.
2601 // Otherwise, we return the type of the operand of a trunc that we find.
2602 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2603 return T->getOperand()->getType();
2604 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2605 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2606 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2607 return T->getOperand()->getType();
2609 return nullptr;
2611 if (auto *SrcType = FindTruncSrcType()) {
2612 SmallVector<const SCEV *, 8> LargeOps;
2613 bool Ok = true;
2614 // Check all the operands to see if they can be represented in the
2615 // source type of the truncate.
2616 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2617 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2618 if (T->getOperand()->getType() != SrcType) {
2619 Ok = false;
2620 break;
2622 LargeOps.push_back(T->getOperand());
2623 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2624 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2625 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2626 SmallVector<const SCEV *, 8> LargeMulOps;
2627 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2628 if (const SCEVTruncateExpr *T =
2629 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2630 if (T->getOperand()->getType() != SrcType) {
2631 Ok = false;
2632 break;
2634 LargeMulOps.push_back(T->getOperand());
2635 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2636 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2637 } else {
2638 Ok = false;
2639 break;
2642 if (Ok)
2643 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2644 } else {
2645 Ok = false;
2646 break;
2649 if (Ok) {
2650 // Evaluate the expression in the larger type.
2651 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2652 // If it folds to something simple, use it. Otherwise, don't.
2653 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2654 return getTruncateExpr(Fold, Ty);
2658 if (Ops.size() == 2) {
2659 // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2660 // C2 can be folded in a way that allows retaining wrapping flags of (X +
2661 // C1).
2662 const SCEV *A = Ops[0];
2663 const SCEV *B = Ops[1];
2664 auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2665 auto *C = dyn_cast<SCEVConstant>(A);
2666 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2667 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2668 auto C2 = C->getAPInt();
2669 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2671 APInt ConstAdd = C1 + C2;
2672 auto AddFlags = AddExpr->getNoWrapFlags();
2673 // Adding a smaller constant is NUW if the original AddExpr was NUW.
2674 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNUW) &&
2675 ConstAdd.ule(C1)) {
2676 PreservedFlags =
2677 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW);
2680 // Adding a constant with the same sign and small magnitude is NSW, if the
2681 // original AddExpr was NSW.
2682 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNSW) &&
2683 C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2684 ConstAdd.abs().ule(C1.abs())) {
2685 PreservedFlags =
2686 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW);
2689 if (PreservedFlags != SCEV::FlagAnyWrap) {
2690 SmallVector<const SCEV *, 4> NewOps(AddExpr->operands());
2691 NewOps[0] = getConstant(ConstAdd);
2692 return getAddExpr(NewOps, PreservedFlags);
2697 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2698 if (Ops.size() == 2) {
2699 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[0]);
2700 if (Mul && Mul->getNumOperands() == 2 &&
2701 Mul->getOperand(0)->isAllOnesValue()) {
2702 const SCEV *X;
2703 const SCEV *Y;
2704 if (matchURem(Mul->getOperand(1), X, Y) && X == Ops[1]) {
2705 return getMulExpr(Y, getUDivExpr(X, Y));
2710 // Skip past any other cast SCEVs.
2711 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2712 ++Idx;
2714 // If there are add operands they would be next.
2715 if (Idx < Ops.size()) {
2716 bool DeletedAdd = false;
2717 // If the original flags and all inlined SCEVAddExprs are NUW, use the
2718 // common NUW flag for expression after inlining. Other flags cannot be
2719 // preserved, because they may depend on the original order of operations.
2720 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2721 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2722 if (Ops.size() > AddOpsInlineThreshold ||
2723 Add->getNumOperands() > AddOpsInlineThreshold)
2724 break;
2725 // If we have an add, expand the add operands onto the end of the operands
2726 // list.
2727 Ops.erase(Ops.begin()+Idx);
2728 append_range(Ops, Add->operands());
2729 DeletedAdd = true;
2730 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2733 // If we deleted at least one add, we added operands to the end of the list,
2734 // and they are not necessarily sorted. Recurse to resort and resimplify
2735 // any operands we just acquired.
2736 if (DeletedAdd)
2737 return getAddExpr(Ops, CommonFlags, Depth + 1);
2740 // Skip over the add expression until we get to a multiply.
2741 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2742 ++Idx;
2744 // Check to see if there are any folding opportunities present with
2745 // operands multiplied by constant values.
2746 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2747 uint64_t BitWidth = getTypeSizeInBits(Ty);
2748 DenseMap<const SCEV *, APInt> M;
2749 SmallVector<const SCEV *, 8> NewOps;
2750 APInt AccumulatedConstant(BitWidth, 0);
2751 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2752 Ops, APInt(BitWidth, 1), *this)) {
2753 struct APIntCompare {
2754 bool operator()(const APInt &LHS, const APInt &RHS) const {
2755 return LHS.ult(RHS);
2759 // Some interesting folding opportunity is present, so its worthwhile to
2760 // re-generate the operands list. Group the operands by constant scale,
2761 // to avoid multiplying by the same constant scale multiple times.
2762 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2763 for (const SCEV *NewOp : NewOps)
2764 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2765 // Re-generate the operands list.
2766 Ops.clear();
2767 if (AccumulatedConstant != 0)
2768 Ops.push_back(getConstant(AccumulatedConstant));
2769 for (auto &MulOp : MulOpLists) {
2770 if (MulOp.first == 1) {
2771 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2772 } else if (MulOp.first != 0) {
2773 Ops.push_back(getMulExpr(
2774 getConstant(MulOp.first),
2775 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2776 SCEV::FlagAnyWrap, Depth + 1));
2779 if (Ops.empty())
2780 return getZero(Ty);
2781 if (Ops.size() == 1)
2782 return Ops[0];
2783 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2787 // If we are adding something to a multiply expression, make sure the
2788 // something is not already an operand of the multiply. If so, merge it into
2789 // the multiply.
2790 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2791 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2792 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2793 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2794 if (isa<SCEVConstant>(MulOpSCEV))
2795 continue;
2796 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2797 if (MulOpSCEV == Ops[AddOp]) {
2798 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2799 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2800 if (Mul->getNumOperands() != 2) {
2801 // If the multiply has more than two operands, we must get the
2802 // Y*Z term.
2803 SmallVector<const SCEV *, 4> MulOps(
2804 Mul->operands().take_front(MulOp));
2805 append_range(MulOps, Mul->operands().drop_front(MulOp + 1));
2806 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2808 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2809 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2810 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2811 SCEV::FlagAnyWrap, Depth + 1);
2812 if (Ops.size() == 2) return OuterMul;
2813 if (AddOp < Idx) {
2814 Ops.erase(Ops.begin()+AddOp);
2815 Ops.erase(Ops.begin()+Idx-1);
2816 } else {
2817 Ops.erase(Ops.begin()+Idx);
2818 Ops.erase(Ops.begin()+AddOp-1);
2820 Ops.push_back(OuterMul);
2821 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2824 // Check this multiply against other multiplies being added together.
2825 for (unsigned OtherMulIdx = Idx+1;
2826 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2827 ++OtherMulIdx) {
2828 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2829 // If MulOp occurs in OtherMul, we can fold the two multiplies
2830 // together.
2831 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2832 OMulOp != e; ++OMulOp)
2833 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2834 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2835 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2836 if (Mul->getNumOperands() != 2) {
2837 SmallVector<const SCEV *, 4> MulOps(
2838 Mul->operands().take_front(MulOp));
2839 append_range(MulOps, Mul->operands().drop_front(MulOp+1));
2840 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2842 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2843 if (OtherMul->getNumOperands() != 2) {
2844 SmallVector<const SCEV *, 4> MulOps(
2845 OtherMul->operands().take_front(OMulOp));
2846 append_range(MulOps, OtherMul->operands().drop_front(OMulOp+1));
2847 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2849 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2850 const SCEV *InnerMulSum =
2851 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2852 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2853 SCEV::FlagAnyWrap, Depth + 1);
2854 if (Ops.size() == 2) return OuterMul;
2855 Ops.erase(Ops.begin()+Idx);
2856 Ops.erase(Ops.begin()+OtherMulIdx-1);
2857 Ops.push_back(OuterMul);
2858 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2864 // If there are any add recurrences in the operands list, see if any other
2865 // added values are loop invariant. If so, we can fold them into the
2866 // recurrence.
2867 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2868 ++Idx;
2870 // Scan over all recurrences, trying to fold loop invariants into them.
2871 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2872 // Scan all of the other operands to this add and add them to the vector if
2873 // they are loop invariant w.r.t. the recurrence.
2874 SmallVector<const SCEV *, 8> LIOps;
2875 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2876 const Loop *AddRecLoop = AddRec->getLoop();
2877 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2878 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2879 LIOps.push_back(Ops[i]);
2880 Ops.erase(Ops.begin()+i);
2881 --i; --e;
2884 // If we found some loop invariants, fold them into the recurrence.
2885 if (!LIOps.empty()) {
2886 // Compute nowrap flags for the addition of the loop-invariant ops and
2887 // the addrec. Temporarily push it as an operand for that purpose. These
2888 // flags are valid in the scope of the addrec only.
2889 LIOps.push_back(AddRec);
2890 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2891 LIOps.pop_back();
2893 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2894 LIOps.push_back(AddRec->getStart());
2896 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2898 // It is not in general safe to propagate flags valid on an add within
2899 // the addrec scope to one outside it. We must prove that the inner
2900 // scope is guaranteed to execute if the outer one does to be able to
2901 // safely propagate. We know the program is undefined if poison is
2902 // produced on the inner scoped addrec. We also know that *for this use*
2903 // the outer scoped add can't overflow (because of the flags we just
2904 // computed for the inner scoped add) without the program being undefined.
2905 // Proving that entry to the outer scope neccesitates entry to the inner
2906 // scope, thus proves the program undefined if the flags would be violated
2907 // in the outer scope.
2908 SCEV::NoWrapFlags AddFlags = Flags;
2909 if (AddFlags != SCEV::FlagAnyWrap) {
2910 auto *DefI = getDefiningScopeBound(LIOps);
2911 auto *ReachI = &*AddRecLoop->getHeader()->begin();
2912 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2913 AddFlags = SCEV::FlagAnyWrap;
2915 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2917 // Build the new addrec. Propagate the NUW and NSW flags if both the
2918 // outer add and the inner addrec are guaranteed to have no overflow.
2919 // Always propagate NW.
2920 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2921 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2923 // If all of the other operands were loop invariant, we are done.
2924 if (Ops.size() == 1) return NewRec;
2926 // Otherwise, add the folded AddRec by the non-invariant parts.
2927 for (unsigned i = 0;; ++i)
2928 if (Ops[i] == AddRec) {
2929 Ops[i] = NewRec;
2930 break;
2932 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2935 // Okay, if there weren't any loop invariants to be folded, check to see if
2936 // there are multiple AddRec's with the same loop induction variable being
2937 // added together. If so, we can fold them.
2938 for (unsigned OtherIdx = Idx+1;
2939 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2940 ++OtherIdx) {
2941 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2942 // so that the 1st found AddRecExpr is dominated by all others.
2943 assert(DT.dominates(
2944 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2945 AddRec->getLoop()->getHeader()) &&
2946 "AddRecExprs are not sorted in reverse dominance order?");
2947 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2948 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2949 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2950 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2951 ++OtherIdx) {
2952 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2953 if (OtherAddRec->getLoop() == AddRecLoop) {
2954 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2955 i != e; ++i) {
2956 if (i >= AddRecOps.size()) {
2957 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
2958 break;
2960 SmallVector<const SCEV *, 2> TwoOps = {
2961 AddRecOps[i], OtherAddRec->getOperand(i)};
2962 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2964 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2967 // Step size has changed, so we cannot guarantee no self-wraparound.
2968 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2969 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2973 // Otherwise couldn't fold anything into this recurrence. Move onto the
2974 // next one.
2977 // Okay, it looks like we really DO need an add expr. Check to see if we
2978 // already have one, otherwise create a new one.
2979 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2982 const SCEV *
2983 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2984 SCEV::NoWrapFlags Flags) {
2985 FoldingSetNodeID ID;
2986 ID.AddInteger(scAddExpr);
2987 for (const SCEV *Op : Ops)
2988 ID.AddPointer(Op);
2989 void *IP = nullptr;
2990 SCEVAddExpr *S =
2991 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2992 if (!S) {
2993 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2994 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2995 S = new (SCEVAllocator)
2996 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2997 UniqueSCEVs.InsertNode(S, IP);
2998 registerUser(S, Ops);
3000 S->setNoWrapFlags(Flags);
3001 return S;
3004 const SCEV *
3005 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
3006 const Loop *L, SCEV::NoWrapFlags Flags) {
3007 FoldingSetNodeID ID;
3008 ID.AddInteger(scAddRecExpr);
3009 for (const SCEV *Op : Ops)
3010 ID.AddPointer(Op);
3011 ID.AddPointer(L);
3012 void *IP = nullptr;
3013 SCEVAddRecExpr *S =
3014 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3015 if (!S) {
3016 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3017 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3018 S = new (SCEVAllocator)
3019 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
3020 UniqueSCEVs.InsertNode(S, IP);
3021 LoopUsers[L].push_back(S);
3022 registerUser(S, Ops);
3024 setNoWrapFlags(S, Flags);
3025 return S;
3028 const SCEV *
3029 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
3030 SCEV::NoWrapFlags Flags) {
3031 FoldingSetNodeID ID;
3032 ID.AddInteger(scMulExpr);
3033 for (const SCEV *Op : Ops)
3034 ID.AddPointer(Op);
3035 void *IP = nullptr;
3036 SCEVMulExpr *S =
3037 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3038 if (!S) {
3039 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3040 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3041 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
3042 O, Ops.size());
3043 UniqueSCEVs.InsertNode(S, IP);
3044 registerUser(S, Ops);
3046 S->setNoWrapFlags(Flags);
3047 return S;
3050 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
3051 uint64_t k = i*j;
3052 if (j > 1 && k / j != i) Overflow = true;
3053 return k;
3056 /// Compute the result of "n choose k", the binomial coefficient. If an
3057 /// intermediate computation overflows, Overflow will be set and the return will
3058 /// be garbage. Overflow is not cleared on absence of overflow.
3059 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3060 // We use the multiplicative formula:
3061 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3062 // At each iteration, we take the n-th term of the numeral and divide by the
3063 // (k-n)th term of the denominator. This division will always produce an
3064 // integral result, and helps reduce the chance of overflow in the
3065 // intermediate computations. However, we can still overflow even when the
3066 // final result would fit.
3068 if (n == 0 || n == k) return 1;
3069 if (k > n) return 0;
3071 if (k > n/2)
3072 k = n-k;
3074 uint64_t r = 1;
3075 for (uint64_t i = 1; i <= k; ++i) {
3076 r = umul_ov(r, n-(i-1), Overflow);
3077 r /= i;
3079 return r;
3082 /// Determine if any of the operands in this SCEV are a constant or if
3083 /// any of the add or multiply expressions in this SCEV contain a constant.
3084 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3085 struct FindConstantInAddMulChain {
3086 bool FoundConstant = false;
3088 bool follow(const SCEV *S) {
3089 FoundConstant |= isa<SCEVConstant>(S);
3090 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3093 bool isDone() const {
3094 return FoundConstant;
3098 FindConstantInAddMulChain F;
3099 SCEVTraversal<FindConstantInAddMulChain> ST(F);
3100 ST.visitAll(StartExpr);
3101 return F.FoundConstant;
3104 /// Get a canonical multiply expression, or something simpler if possible.
3105 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
3106 SCEV::NoWrapFlags OrigFlags,
3107 unsigned Depth) {
3108 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3109 "only nuw or nsw allowed");
3110 assert(!Ops.empty() && "Cannot get empty mul!");
3111 if (Ops.size() == 1) return Ops[0];
3112 #ifndef NDEBUG
3113 Type *ETy = Ops[0]->getType();
3114 assert(!ETy->isPointerTy());
3115 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3116 assert(Ops[i]->getType() == ETy &&
3117 "SCEVMulExpr operand types don't match!");
3118 #endif
3120 // Sort by complexity, this groups all similar expression types together.
3121 GroupByComplexity(Ops, &LI, DT);
3123 // If there are any constants, fold them together.
3124 unsigned Idx = 0;
3125 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3126 ++Idx;
3127 assert(Idx < Ops.size());
3128 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3129 // We found two constants, fold them together!
3130 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
3131 if (Ops.size() == 2) return Ops[0];
3132 Ops.erase(Ops.begin()+1); // Erase the folded element
3133 LHSC = cast<SCEVConstant>(Ops[0]);
3136 // If we have a multiply of zero, it will always be zero.
3137 if (LHSC->getValue()->isZero())
3138 return LHSC;
3140 // If we are left with a constant one being multiplied, strip it off.
3141 if (LHSC->getValue()->isOne()) {
3142 Ops.erase(Ops.begin());
3143 --Idx;
3146 if (Ops.size() == 1)
3147 return Ops[0];
3150 // Delay expensive flag strengthening until necessary.
3151 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
3152 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3155 // Limit recursion calls depth.
3156 if (Depth > MaxArithDepth || hasHugeExpression(Ops))
3157 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3159 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3160 // Don't strengthen flags if we have no new information.
3161 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3162 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3163 Mul->setNoWrapFlags(ComputeFlags(Ops));
3164 return S;
3167 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3168 if (Ops.size() == 2) {
3169 // C1*(C2+V) -> C1*C2 + C1*V
3170 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
3171 // If any of Add's ops are Adds or Muls with a constant, apply this
3172 // transformation as well.
3174 // TODO: There are some cases where this transformation is not
3175 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
3176 // this transformation should be narrowed down.
3177 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) {
3178 const SCEV *LHS = getMulExpr(LHSC, Add->getOperand(0),
3179 SCEV::FlagAnyWrap, Depth + 1);
3180 const SCEV *RHS = getMulExpr(LHSC, Add->getOperand(1),
3181 SCEV::FlagAnyWrap, Depth + 1);
3182 return getAddExpr(LHS, RHS, SCEV::FlagAnyWrap, Depth + 1);
3185 if (Ops[0]->isAllOnesValue()) {
3186 // If we have a mul by -1 of an add, try distributing the -1 among the
3187 // add operands.
3188 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3189 SmallVector<const SCEV *, 4> NewOps;
3190 bool AnyFolded = false;
3191 for (const SCEV *AddOp : Add->operands()) {
3192 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
3193 Depth + 1);
3194 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3195 NewOps.push_back(Mul);
3197 if (AnyFolded)
3198 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3199 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3200 // Negation preserves a recurrence's no self-wrap property.
3201 SmallVector<const SCEV *, 4> Operands;
3202 for (const SCEV *AddRecOp : AddRec->operands())
3203 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
3204 Depth + 1));
3205 // Let M be the minimum representable signed value. AddRec with nsw
3206 // multiplied by -1 can have signed overflow if and only if it takes a
3207 // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3208 // maximum signed value. In all other cases signed overflow is
3209 // impossible.
3210 auto FlagsMask = SCEV::FlagNW;
3211 if (hasFlags(AddRec->getNoWrapFlags(), SCEV::FlagNSW)) {
3212 auto MinInt =
3213 APInt::getSignedMinValue(getTypeSizeInBits(AddRec->getType()));
3214 if (getSignedRangeMin(AddRec) != MinInt)
3215 FlagsMask = setFlags(FlagsMask, SCEV::FlagNSW);
3217 return getAddRecExpr(Operands, AddRec->getLoop(),
3218 AddRec->getNoWrapFlags(FlagsMask));
3224 // Skip over the add expression until we get to a multiply.
3225 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3226 ++Idx;
3228 // If there are mul operands inline them all into this expression.
3229 if (Idx < Ops.size()) {
3230 bool DeletedMul = false;
3231 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3232 if (Ops.size() > MulOpsInlineThreshold)
3233 break;
3234 // If we have an mul, expand the mul operands onto the end of the
3235 // operands list.
3236 Ops.erase(Ops.begin()+Idx);
3237 append_range(Ops, Mul->operands());
3238 DeletedMul = true;
3241 // If we deleted at least one mul, we added operands to the end of the
3242 // list, and they are not necessarily sorted. Recurse to resort and
3243 // resimplify any operands we just acquired.
3244 if (DeletedMul)
3245 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3248 // If there are any add recurrences in the operands list, see if any other
3249 // added values are loop invariant. If so, we can fold them into the
3250 // recurrence.
3251 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3252 ++Idx;
3254 // Scan over all recurrences, trying to fold loop invariants into them.
3255 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3256 // Scan all of the other operands to this mul and add them to the vector
3257 // if they are loop invariant w.r.t. the recurrence.
3258 SmallVector<const SCEV *, 8> LIOps;
3259 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3260 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3261 if (isAvailableAtLoopEntry(Ops[i], AddRec->getLoop())) {
3262 LIOps.push_back(Ops[i]);
3263 Ops.erase(Ops.begin()+i);
3264 --i; --e;
3267 // If we found some loop invariants, fold them into the recurrence.
3268 if (!LIOps.empty()) {
3269 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3270 SmallVector<const SCEV *, 4> NewOps;
3271 NewOps.reserve(AddRec->getNumOperands());
3272 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3274 // If both the mul and addrec are nuw, we can preserve nuw.
3275 // If both the mul and addrec are nsw, we can only preserve nsw if either
3276 // a) they are also nuw, or
3277 // b) all multiplications of addrec operands with scale are nsw.
3278 SCEV::NoWrapFlags Flags =
3279 AddRec->getNoWrapFlags(ComputeFlags({Scale, AddRec}));
3281 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3282 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3283 SCEV::FlagAnyWrap, Depth + 1));
3285 if (hasFlags(Flags, SCEV::FlagNSW) && !hasFlags(Flags, SCEV::FlagNUW)) {
3286 ConstantRange NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3287 Instruction::Mul, getSignedRange(Scale),
3288 OverflowingBinaryOperator::NoSignedWrap);
3289 if (!NSWRegion.contains(getSignedRange(AddRec->getOperand(i))))
3290 Flags = clearFlags(Flags, SCEV::FlagNSW);
3294 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(), Flags);
3296 // If all of the other operands were loop invariant, we are done.
3297 if (Ops.size() == 1) return NewRec;
3299 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3300 for (unsigned i = 0;; ++i)
3301 if (Ops[i] == AddRec) {
3302 Ops[i] = NewRec;
3303 break;
3305 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3308 // Okay, if there weren't any loop invariants to be folded, check to see
3309 // if there are multiple AddRec's with the same loop induction variable
3310 // being multiplied together. If so, we can fold them.
3312 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3313 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3314 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3315 // ]]],+,...up to x=2n}.
3316 // Note that the arguments to choose() are always integers with values
3317 // known at compile time, never SCEV objects.
3319 // The implementation avoids pointless extra computations when the two
3320 // addrec's are of different length (mathematically, it's equivalent to
3321 // an infinite stream of zeros on the right).
3322 bool OpsModified = false;
3323 for (unsigned OtherIdx = Idx+1;
3324 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3325 ++OtherIdx) {
3326 const SCEVAddRecExpr *OtherAddRec =
3327 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3328 if (!OtherAddRec || OtherAddRec->getLoop() != AddRec->getLoop())
3329 continue;
3331 // Limit max number of arguments to avoid creation of unreasonably big
3332 // SCEVAddRecs with very complex operands.
3333 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3334 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3335 continue;
3337 bool Overflow = false;
3338 Type *Ty = AddRec->getType();
3339 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3340 SmallVector<const SCEV*, 7> AddRecOps;
3341 for (int x = 0, xe = AddRec->getNumOperands() +
3342 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3343 SmallVector <const SCEV *, 7> SumOps;
3344 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3345 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3346 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3347 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3348 z < ze && !Overflow; ++z) {
3349 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3350 uint64_t Coeff;
3351 if (LargerThan64Bits)
3352 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3353 else
3354 Coeff = Coeff1*Coeff2;
3355 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3356 const SCEV *Term1 = AddRec->getOperand(y-z);
3357 const SCEV *Term2 = OtherAddRec->getOperand(z);
3358 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3359 SCEV::FlagAnyWrap, Depth + 1));
3362 if (SumOps.empty())
3363 SumOps.push_back(getZero(Ty));
3364 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3366 if (!Overflow) {
3367 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
3368 SCEV::FlagAnyWrap);
3369 if (Ops.size() == 2) return NewAddRec;
3370 Ops[Idx] = NewAddRec;
3371 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3372 OpsModified = true;
3373 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3374 if (!AddRec)
3375 break;
3378 if (OpsModified)
3379 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3381 // Otherwise couldn't fold anything into this recurrence. Move onto the
3382 // next one.
3385 // Okay, it looks like we really DO need an mul expr. Check to see if we
3386 // already have one, otherwise create a new one.
3387 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3390 /// Represents an unsigned remainder expression based on unsigned division.
3391 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3392 const SCEV *RHS) {
3393 assert(getEffectiveSCEVType(LHS->getType()) ==
3394 getEffectiveSCEVType(RHS->getType()) &&
3395 "SCEVURemExpr operand types don't match!");
3397 // Short-circuit easy cases
3398 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3399 // If constant is one, the result is trivial
3400 if (RHSC->getValue()->isOne())
3401 return getZero(LHS->getType()); // X urem 1 --> 0
3403 // If constant is a power of two, fold into a zext(trunc(LHS)).
3404 if (RHSC->getAPInt().isPowerOf2()) {
3405 Type *FullTy = LHS->getType();
3406 Type *TruncTy =
3407 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3408 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3412 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3413 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3414 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3415 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3418 /// Get a canonical unsigned division expression, or something simpler if
3419 /// possible.
3420 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3421 const SCEV *RHS) {
3422 assert(!LHS->getType()->isPointerTy() &&
3423 "SCEVUDivExpr operand can't be pointer!");
3424 assert(LHS->getType() == RHS->getType() &&
3425 "SCEVUDivExpr operand types don't match!");
3427 FoldingSetNodeID ID;
3428 ID.AddInteger(scUDivExpr);
3429 ID.AddPointer(LHS);
3430 ID.AddPointer(RHS);
3431 void *IP = nullptr;
3432 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3433 return S;
3435 // 0 udiv Y == 0
3436 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3437 if (LHSC->getValue()->isZero())
3438 return LHS;
3440 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3441 if (RHSC->getValue()->isOne())
3442 return LHS; // X udiv 1 --> x
3443 // If the denominator is zero, the result of the udiv is undefined. Don't
3444 // try to analyze it, because the resolution chosen here may differ from
3445 // the resolution chosen in other parts of the compiler.
3446 if (!RHSC->getValue()->isZero()) {
3447 // Determine if the division can be folded into the operands of
3448 // its operands.
3449 // TODO: Generalize this to non-constants by using known-bits information.
3450 Type *Ty = LHS->getType();
3451 unsigned LZ = RHSC->getAPInt().countl_zero();
3452 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3453 // For non-power-of-two values, effectively round the value up to the
3454 // nearest power of two.
3455 if (!RHSC->getAPInt().isPowerOf2())
3456 ++MaxShiftAmt;
3457 IntegerType *ExtTy =
3458 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3459 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3460 if (const SCEVConstant *Step =
3461 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3462 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3463 const APInt &StepInt = Step->getAPInt();
3464 const APInt &DivInt = RHSC->getAPInt();
3465 if (!StepInt.urem(DivInt) &&
3466 getZeroExtendExpr(AR, ExtTy) ==
3467 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3468 getZeroExtendExpr(Step, ExtTy),
3469 AR->getLoop(), SCEV::FlagAnyWrap)) {
3470 SmallVector<const SCEV *, 4> Operands;
3471 for (const SCEV *Op : AR->operands())
3472 Operands.push_back(getUDivExpr(Op, RHS));
3473 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3475 /// Get a canonical UDivExpr for a recurrence.
3476 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3477 // We can currently only fold X%N if X is constant.
3478 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3479 if (StartC && !DivInt.urem(StepInt) &&
3480 getZeroExtendExpr(AR, ExtTy) ==
3481 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3482 getZeroExtendExpr(Step, ExtTy),
3483 AR->getLoop(), SCEV::FlagAnyWrap)) {
3484 const APInt &StartInt = StartC->getAPInt();
3485 const APInt &StartRem = StartInt.urem(StepInt);
3486 if (StartRem != 0) {
3487 const SCEV *NewLHS =
3488 getAddRecExpr(getConstant(StartInt - StartRem), Step,
3489 AR->getLoop(), SCEV::FlagNW);
3490 if (LHS != NewLHS) {
3491 LHS = NewLHS;
3493 // Reset the ID to include the new LHS, and check if it is
3494 // already cached.
3495 ID.clear();
3496 ID.AddInteger(scUDivExpr);
3497 ID.AddPointer(LHS);
3498 ID.AddPointer(RHS);
3499 IP = nullptr;
3500 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3501 return S;
3506 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3507 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3508 SmallVector<const SCEV *, 4> Operands;
3509 for (const SCEV *Op : M->operands())
3510 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3511 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3512 // Find an operand that's safely divisible.
3513 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3514 const SCEV *Op = M->getOperand(i);
3515 const SCEV *Div = getUDivExpr(Op, RHSC);
3516 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3517 Operands = SmallVector<const SCEV *, 4>(M->operands());
3518 Operands[i] = Div;
3519 return getMulExpr(Operands);
3524 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3525 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3526 if (auto *DivisorConstant =
3527 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3528 bool Overflow = false;
3529 APInt NewRHS =
3530 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3531 if (Overflow) {
3532 return getConstant(RHSC->getType(), 0, false);
3534 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3538 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3539 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3540 SmallVector<const SCEV *, 4> Operands;
3541 for (const SCEV *Op : A->operands())
3542 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3543 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3544 Operands.clear();
3545 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3546 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3547 if (isa<SCEVUDivExpr>(Op) ||
3548 getMulExpr(Op, RHS) != A->getOperand(i))
3549 break;
3550 Operands.push_back(Op);
3552 if (Operands.size() == A->getNumOperands())
3553 return getAddExpr(Operands);
3557 // Fold if both operands are constant.
3558 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3559 return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3563 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3564 // changes). Make sure we get a new one.
3565 IP = nullptr;
3566 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3567 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3568 LHS, RHS);
3569 UniqueSCEVs.InsertNode(S, IP);
3570 registerUser(S, {LHS, RHS});
3571 return S;
3574 APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3575 APInt A = C1->getAPInt().abs();
3576 APInt B = C2->getAPInt().abs();
3577 uint32_t ABW = A.getBitWidth();
3578 uint32_t BBW = B.getBitWidth();
3580 if (ABW > BBW)
3581 B = B.zext(ABW);
3582 else if (ABW < BBW)
3583 A = A.zext(BBW);
3585 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3588 /// Get a canonical unsigned division expression, or something simpler if
3589 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3590 /// can attempt to remove factors from the LHS and RHS. We can't do this when
3591 /// it's not exact because the udiv may be clearing bits.
3592 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3593 const SCEV *RHS) {
3594 // TODO: we could try to find factors in all sorts of things, but for now we
3595 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3596 // end of this file for inspiration.
3598 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3599 if (!Mul || !Mul->hasNoUnsignedWrap())
3600 return getUDivExpr(LHS, RHS);
3602 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3603 // If the mulexpr multiplies by a constant, then that constant must be the
3604 // first element of the mulexpr.
3605 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3606 if (LHSCst == RHSCst) {
3607 SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands()));
3608 return getMulExpr(Operands);
3611 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3612 // that there's a factor provided by one of the other terms. We need to
3613 // check.
3614 APInt Factor = gcd(LHSCst, RHSCst);
3615 if (!Factor.isIntN(1)) {
3616 LHSCst =
3617 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3618 RHSCst =
3619 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3620 SmallVector<const SCEV *, 2> Operands;
3621 Operands.push_back(LHSCst);
3622 append_range(Operands, Mul->operands().drop_front());
3623 LHS = getMulExpr(Operands);
3624 RHS = RHSCst;
3625 Mul = dyn_cast<SCEVMulExpr>(LHS);
3626 if (!Mul)
3627 return getUDivExactExpr(LHS, RHS);
3632 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3633 if (Mul->getOperand(i) == RHS) {
3634 SmallVector<const SCEV *, 2> Operands;
3635 append_range(Operands, Mul->operands().take_front(i));
3636 append_range(Operands, Mul->operands().drop_front(i + 1));
3637 return getMulExpr(Operands);
3641 return getUDivExpr(LHS, RHS);
3644 /// Get an add recurrence expression for the specified loop. Simplify the
3645 /// expression as much as possible.
3646 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3647 const Loop *L,
3648 SCEV::NoWrapFlags Flags) {
3649 SmallVector<const SCEV *, 4> Operands;
3650 Operands.push_back(Start);
3651 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3652 if (StepChrec->getLoop() == L) {
3653 append_range(Operands, StepChrec->operands());
3654 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3657 Operands.push_back(Step);
3658 return getAddRecExpr(Operands, L, Flags);
3661 /// Get an add recurrence expression for the specified loop. Simplify the
3662 /// expression as much as possible.
3663 const SCEV *
3664 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3665 const Loop *L, SCEV::NoWrapFlags Flags) {
3666 if (Operands.size() == 1) return Operands[0];
3667 #ifndef NDEBUG
3668 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3669 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
3670 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3671 "SCEVAddRecExpr operand types don't match!");
3672 assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer");
3674 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3675 assert(isAvailableAtLoopEntry(Operands[i], L) &&
3676 "SCEVAddRecExpr operand is not available at loop entry!");
3677 #endif
3679 if (Operands.back()->isZero()) {
3680 Operands.pop_back();
3681 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3684 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3685 // use that information to infer NUW and NSW flags. However, computing a
3686 // BE count requires calling getAddRecExpr, so we may not yet have a
3687 // meaningful BE count at this point (and if we don't, we'd be stuck
3688 // with a SCEVCouldNotCompute as the cached BE count).
3690 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3692 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3693 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3694 const Loop *NestedLoop = NestedAR->getLoop();
3695 if (L->contains(NestedLoop)
3696 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3697 : (!NestedLoop->contains(L) &&
3698 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3699 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands());
3700 Operands[0] = NestedAR->getStart();
3701 // AddRecs require their operands be loop-invariant with respect to their
3702 // loops. Don't perform this transformation if it would break this
3703 // requirement.
3704 bool AllInvariant = all_of(
3705 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3707 if (AllInvariant) {
3708 // Create a recurrence for the outer loop with the same step size.
3710 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3711 // inner recurrence has the same property.
3712 SCEV::NoWrapFlags OuterFlags =
3713 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3715 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3716 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3717 return isLoopInvariant(Op, NestedLoop);
3720 if (AllInvariant) {
3721 // Ok, both add recurrences are valid after the transformation.
3723 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3724 // the outer recurrence has the same property.
3725 SCEV::NoWrapFlags InnerFlags =
3726 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3727 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3730 // Reset Operands to its original state.
3731 Operands[0] = NestedAR;
3735 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3736 // already have one, otherwise create a new one.
3737 return getOrCreateAddRecExpr(Operands, L, Flags);
3740 const SCEV *
3741 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3742 const SmallVectorImpl<const SCEV *> &IndexExprs) {
3743 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3744 // getSCEV(Base)->getType() has the same address space as Base->getType()
3745 // because SCEV::getType() preserves the address space.
3746 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3747 const bool AssumeInBoundsFlags = [&]() {
3748 if (!GEP->isInBounds())
3749 return false;
3751 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3752 // but to do that, we have to ensure that said flag is valid in the entire
3753 // defined scope of the SCEV.
3754 auto *GEPI = dyn_cast<Instruction>(GEP);
3755 // TODO: non-instructions have global scope. We might be able to prove
3756 // some global scope cases
3757 return GEPI && isSCEVExprNeverPoison(GEPI);
3758 }();
3760 SCEV::NoWrapFlags OffsetWrap =
3761 AssumeInBoundsFlags ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3763 Type *CurTy = GEP->getType();
3764 bool FirstIter = true;
3765 SmallVector<const SCEV *, 4> Offsets;
3766 for (const SCEV *IndexExpr : IndexExprs) {
3767 // Compute the (potentially symbolic) offset in bytes for this index.
3768 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3769 // For a struct, add the member offset.
3770 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3771 unsigned FieldNo = Index->getZExtValue();
3772 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3773 Offsets.push_back(FieldOffset);
3775 // Update CurTy to the type of the field at Index.
3776 CurTy = STy->getTypeAtIndex(Index);
3777 } else {
3778 // Update CurTy to its element type.
3779 if (FirstIter) {
3780 assert(isa<PointerType>(CurTy) &&
3781 "The first index of a GEP indexes a pointer");
3782 CurTy = GEP->getSourceElementType();
3783 FirstIter = false;
3784 } else {
3785 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3787 // For an array, add the element offset, explicitly scaled.
3788 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3789 // Getelementptr indices are signed.
3790 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3792 // Multiply the index by the element size to compute the element offset.
3793 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3794 Offsets.push_back(LocalOffset);
3798 // Handle degenerate case of GEP without offsets.
3799 if (Offsets.empty())
3800 return BaseExpr;
3802 // Add the offsets together, assuming nsw if inbounds.
3803 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3804 // Add the base address and the offset. We cannot use the nsw flag, as the
3805 // base address is unsigned. However, if we know that the offset is
3806 // non-negative, we can use nuw.
3807 SCEV::NoWrapFlags BaseWrap = AssumeInBoundsFlags && isKnownNonNegative(Offset)
3808 ? SCEV::FlagNUW : SCEV::FlagAnyWrap;
3809 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3810 assert(BaseExpr->getType() == GEPExpr->getType() &&
3811 "GEP should not change type mid-flight.");
3812 return GEPExpr;
3815 SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3816 ArrayRef<const SCEV *> Ops) {
3817 FoldingSetNodeID ID;
3818 ID.AddInteger(SCEVType);
3819 for (const SCEV *Op : Ops)
3820 ID.AddPointer(Op);
3821 void *IP = nullptr;
3822 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3825 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3826 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3827 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3830 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
3831 SmallVectorImpl<const SCEV *> &Ops) {
3832 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3833 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3834 if (Ops.size() == 1) return Ops[0];
3835 #ifndef NDEBUG
3836 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3837 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3838 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3839 "Operand types don't match!");
3840 assert(Ops[0]->getType()->isPointerTy() ==
3841 Ops[i]->getType()->isPointerTy() &&
3842 "min/max should be consistently pointerish");
3844 #endif
3846 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3847 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3849 // Sort by complexity, this groups all similar expression types together.
3850 GroupByComplexity(Ops, &LI, DT);
3852 // Check if we have created the same expression before.
3853 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3854 return S;
3857 // If there are any constants, fold them together.
3858 unsigned Idx = 0;
3859 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3860 ++Idx;
3861 assert(Idx < Ops.size());
3862 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3863 switch (Kind) {
3864 case scSMaxExpr:
3865 return APIntOps::smax(LHS, RHS);
3866 case scSMinExpr:
3867 return APIntOps::smin(LHS, RHS);
3868 case scUMaxExpr:
3869 return APIntOps::umax(LHS, RHS);
3870 case scUMinExpr:
3871 return APIntOps::umin(LHS, RHS);
3872 default:
3873 llvm_unreachable("Unknown SCEV min/max opcode");
3877 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3878 // We found two constants, fold them together!
3879 ConstantInt *Fold = ConstantInt::get(
3880 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3881 Ops[0] = getConstant(Fold);
3882 Ops.erase(Ops.begin()+1); // Erase the folded element
3883 if (Ops.size() == 1) return Ops[0];
3884 LHSC = cast<SCEVConstant>(Ops[0]);
3887 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3888 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3890 if (IsMax ? IsMinV : IsMaxV) {
3891 // If we are left with a constant minimum(/maximum)-int, strip it off.
3892 Ops.erase(Ops.begin());
3893 --Idx;
3894 } else if (IsMax ? IsMaxV : IsMinV) {
3895 // If we have a max(/min) with a constant maximum(/minimum)-int,
3896 // it will always be the extremum.
3897 return LHSC;
3900 if (Ops.size() == 1) return Ops[0];
3903 // Find the first operation of the same kind
3904 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3905 ++Idx;
3907 // Check to see if one of the operands is of the same kind. If so, expand its
3908 // operands onto our operand list, and recurse to simplify.
3909 if (Idx < Ops.size()) {
3910 bool DeletedAny = false;
3911 while (Ops[Idx]->getSCEVType() == Kind) {
3912 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3913 Ops.erase(Ops.begin()+Idx);
3914 append_range(Ops, SMME->operands());
3915 DeletedAny = true;
3918 if (DeletedAny)
3919 return getMinMaxExpr(Kind, Ops);
3922 // Okay, check to see if the same value occurs in the operand list twice. If
3923 // so, delete one. Since we sorted the list, these values are required to
3924 // be adjacent.
3925 llvm::CmpInst::Predicate GEPred =
3926 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3927 llvm::CmpInst::Predicate LEPred =
3928 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3929 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3930 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3931 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3932 if (Ops[i] == Ops[i + 1] ||
3933 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3934 // X op Y op Y --> X op Y
3935 // X op Y --> X, if we know X, Y are ordered appropriately
3936 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3937 --i;
3938 --e;
3939 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3940 Ops[i + 1])) {
3941 // X op Y --> Y, if we know X, Y are ordered appropriately
3942 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3943 --i;
3944 --e;
3948 if (Ops.size() == 1) return Ops[0];
3950 assert(!Ops.empty() && "Reduced smax down to nothing!");
3952 // Okay, it looks like we really DO need an expr. Check to see if we
3953 // already have one, otherwise create a new one.
3954 FoldingSetNodeID ID;
3955 ID.AddInteger(Kind);
3956 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3957 ID.AddPointer(Ops[i]);
3958 void *IP = nullptr;
3959 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3960 if (ExistingSCEV)
3961 return ExistingSCEV;
3962 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3963 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3964 SCEV *S = new (SCEVAllocator)
3965 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3967 UniqueSCEVs.InsertNode(S, IP);
3968 registerUser(S, Ops);
3969 return S;
3972 namespace {
3974 class SCEVSequentialMinMaxDeduplicatingVisitor final
3975 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
3976 std::optional<const SCEV *>> {
3977 using RetVal = std::optional<const SCEV *>;
3978 using Base = SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor, RetVal>;
3980 ScalarEvolution &SE;
3981 const SCEVTypes RootKind; // Must be a sequential min/max expression.
3982 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
3983 SmallPtrSet<const SCEV *, 16> SeenOps;
3985 bool canRecurseInto(SCEVTypes Kind) const {
3986 // We can only recurse into the SCEV expression of the same effective type
3987 // as the type of our root SCEV expression.
3988 return RootKind == Kind || NonSequentialRootKind == Kind;
3991 RetVal visitAnyMinMaxExpr(const SCEV *S) {
3992 assert((isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) &&
3993 "Only for min/max expressions.");
3994 SCEVTypes Kind = S->getSCEVType();
3996 if (!canRecurseInto(Kind))
3997 return S;
3999 auto *NAry = cast<SCEVNAryExpr>(S);
4000 SmallVector<const SCEV *> NewOps;
4001 bool Changed = visit(Kind, NAry->operands(), NewOps);
4003 if (!Changed)
4004 return S;
4005 if (NewOps.empty())
4006 return std::nullopt;
4008 return isa<SCEVSequentialMinMaxExpr>(S)
4009 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
4010 : SE.getMinMaxExpr(Kind, NewOps);
4013 RetVal visit(const SCEV *S) {
4014 // Has the whole operand been seen already?
4015 if (!SeenOps.insert(S).second)
4016 return std::nullopt;
4017 return Base::visit(S);
4020 public:
4021 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
4022 SCEVTypes RootKind)
4023 : SE(SE), RootKind(RootKind),
4024 NonSequentialRootKind(
4025 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4026 RootKind)) {}
4028 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<const SCEV *> OrigOps,
4029 SmallVectorImpl<const SCEV *> &NewOps) {
4030 bool Changed = false;
4031 SmallVector<const SCEV *> Ops;
4032 Ops.reserve(OrigOps.size());
4034 for (const SCEV *Op : OrigOps) {
4035 RetVal NewOp = visit(Op);
4036 if (NewOp != Op)
4037 Changed = true;
4038 if (NewOp)
4039 Ops.emplace_back(*NewOp);
4042 if (Changed)
4043 NewOps = std::move(Ops);
4044 return Changed;
4047 RetVal visitConstant(const SCEVConstant *Constant) { return Constant; }
4049 RetVal visitVScale(const SCEVVScale *VScale) { return VScale; }
4051 RetVal visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) { return Expr; }
4053 RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
4055 RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; }
4057 RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; }
4059 RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; }
4061 RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; }
4063 RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
4065 RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
4067 RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) {
4068 return visitAnyMinMaxExpr(Expr);
4071 RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) {
4072 return visitAnyMinMaxExpr(Expr);
4075 RetVal visitSMinExpr(const SCEVSMinExpr *Expr) {
4076 return visitAnyMinMaxExpr(Expr);
4079 RetVal visitUMinExpr(const SCEVUMinExpr *Expr) {
4080 return visitAnyMinMaxExpr(Expr);
4083 RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
4084 return visitAnyMinMaxExpr(Expr);
4087 RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; }
4089 RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; }
4092 } // namespace
4094 static bool scevUnconditionallyPropagatesPoisonFromOperands(SCEVTypes Kind) {
4095 switch (Kind) {
4096 case scConstant:
4097 case scVScale:
4098 case scTruncate:
4099 case scZeroExtend:
4100 case scSignExtend:
4101 case scPtrToInt:
4102 case scAddExpr:
4103 case scMulExpr:
4104 case scUDivExpr:
4105 case scAddRecExpr:
4106 case scUMaxExpr:
4107 case scSMaxExpr:
4108 case scUMinExpr:
4109 case scSMinExpr:
4110 case scUnknown:
4111 // If any operand is poison, the whole expression is poison.
4112 return true;
4113 case scSequentialUMinExpr:
4114 // FIXME: if the *first* operand is poison, the whole expression is poison.
4115 return false; // Pessimistically, say that it does not propagate poison.
4116 case scCouldNotCompute:
4117 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4119 llvm_unreachable("Unknown SCEV kind!");
4122 namespace {
4123 // The only way poison may be introduced in a SCEV expression is from a
4124 // poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4125 // not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not*
4126 // introduce poison -- they encode guaranteed, non-speculated knowledge.
4128 // Additionally, all SCEV nodes propagate poison from inputs to outputs,
4129 // with the notable exception of umin_seq, where only poison from the first
4130 // operand is (unconditionally) propagated.
4131 struct SCEVPoisonCollector {
4132 bool LookThroughMaybePoisonBlocking;
4133 SmallPtrSet<const SCEVUnknown *, 4> MaybePoison;
4134 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4135 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4137 bool follow(const SCEV *S) {
4138 if (!LookThroughMaybePoisonBlocking &&
4139 !scevUnconditionallyPropagatesPoisonFromOperands(S->getSCEVType()))
4140 return false;
4142 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4143 if (!isGuaranteedNotToBePoison(SU->getValue()))
4144 MaybePoison.insert(SU);
4146 return true;
4148 bool isDone() const { return false; }
4150 } // namespace
4152 /// Return true if V is poison given that AssumedPoison is already poison.
4153 static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4154 // First collect all SCEVs that might result in AssumedPoison to be poison.
4155 // We need to look through potentially poison-blocking operations here,
4156 // because we want to find all SCEVs that *might* result in poison, not only
4157 // those that are *required* to.
4158 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4159 visitAll(AssumedPoison, PC1);
4161 // AssumedPoison is never poison. As the assumption is false, the implication
4162 // is true. Don't bother walking the other SCEV in this case.
4163 if (PC1.MaybePoison.empty())
4164 return true;
4166 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4167 // as well. We cannot look through potentially poison-blocking operations
4168 // here, as their arguments only *may* make the result poison.
4169 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4170 visitAll(S, PC2);
4172 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4173 // it will also make S poison by being part of PC2.MaybePoison.
4174 return all_of(PC1.MaybePoison, [&](const SCEVUnknown *S) {
4175 return PC2.MaybePoison.contains(S);
4179 void ScalarEvolution::getPoisonGeneratingValues(
4180 SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4181 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4182 visitAll(S, PC);
4183 for (const SCEVUnknown *SU : PC.MaybePoison)
4184 Result.insert(SU->getValue());
4187 const SCEV *
4188 ScalarEvolution::getSequentialMinMaxExpr(SCEVTypes Kind,
4189 SmallVectorImpl<const SCEV *> &Ops) {
4190 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4191 "Not a SCEVSequentialMinMaxExpr!");
4192 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4193 if (Ops.size() == 1)
4194 return Ops[0];
4195 #ifndef NDEBUG
4196 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4197 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4198 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4199 "Operand types don't match!");
4200 assert(Ops[0]->getType()->isPointerTy() ==
4201 Ops[i]->getType()->isPointerTy() &&
4202 "min/max should be consistently pointerish");
4204 #endif
4206 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4207 // so we can *NOT* do any kind of sorting of the expressions!
4209 // Check if we have created the same expression before.
4210 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4211 return S;
4213 // FIXME: there are *some* simplifications that we can do here.
4215 // Keep only the first instance of an operand.
4217 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4218 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4219 if (Changed)
4220 return getSequentialMinMaxExpr(Kind, Ops);
4223 // Check to see if one of the operands is of the same kind. If so, expand its
4224 // operands onto our operand list, and recurse to simplify.
4226 unsigned Idx = 0;
4227 bool DeletedAny = false;
4228 while (Idx < Ops.size()) {
4229 if (Ops[Idx]->getSCEVType() != Kind) {
4230 ++Idx;
4231 continue;
4233 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4234 Ops.erase(Ops.begin() + Idx);
4235 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4236 SMME->operands().end());
4237 DeletedAny = true;
4240 if (DeletedAny)
4241 return getSequentialMinMaxExpr(Kind, Ops);
4244 const SCEV *SaturationPoint;
4245 ICmpInst::Predicate Pred;
4246 switch (Kind) {
4247 case scSequentialUMinExpr:
4248 SaturationPoint = getZero(Ops[0]->getType());
4249 Pred = ICmpInst::ICMP_ULE;
4250 break;
4251 default:
4252 llvm_unreachable("Not a sequential min/max type.");
4255 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4256 // We can replace %x umin_seq %y with %x umin %y if either:
4257 // * %y being poison implies %x is also poison.
4258 // * %x cannot be the saturating value (e.g. zero for umin).
4259 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4260 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4261 SaturationPoint)) {
4262 SmallVector<const SCEV *> SeqOps = {Ops[i - 1], Ops[i]};
4263 Ops[i - 1] = getMinMaxExpr(
4264 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(Kind),
4265 SeqOps);
4266 Ops.erase(Ops.begin() + i);
4267 return getSequentialMinMaxExpr(Kind, Ops);
4269 // Fold %x umin_seq %y to %x if %x ule %y.
4270 // TODO: We might be able to prove the predicate for a later operand.
4271 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4272 Ops.erase(Ops.begin() + i);
4273 return getSequentialMinMaxExpr(Kind, Ops);
4277 // Okay, it looks like we really DO need an expr. Check to see if we
4278 // already have one, otherwise create a new one.
4279 FoldingSetNodeID ID;
4280 ID.AddInteger(Kind);
4281 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
4282 ID.AddPointer(Ops[i]);
4283 void *IP = nullptr;
4284 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4285 if (ExistingSCEV)
4286 return ExistingSCEV;
4288 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
4289 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
4290 SCEV *S = new (SCEVAllocator)
4291 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4293 UniqueSCEVs.InsertNode(S, IP);
4294 registerUser(S, Ops);
4295 return S;
4298 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4299 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
4300 return getSMaxExpr(Ops);
4303 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
4304 return getMinMaxExpr(scSMaxExpr, Ops);
4307 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4308 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
4309 return getUMaxExpr(Ops);
4312 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
4313 return getMinMaxExpr(scUMaxExpr, Ops);
4316 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
4317 const SCEV *RHS) {
4318 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4319 return getSMinExpr(Ops);
4322 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
4323 return getMinMaxExpr(scSMinExpr, Ops);
4326 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, const SCEV *RHS,
4327 bool Sequential) {
4328 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4329 return getUMinExpr(Ops, Sequential);
4332 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops,
4333 bool Sequential) {
4334 return Sequential ? getSequentialMinMaxExpr(scSequentialUMinExpr, Ops)
4335 : getMinMaxExpr(scUMinExpr, Ops);
4338 const SCEV *
4339 ScalarEvolution::getSizeOfExpr(Type *IntTy, TypeSize Size) {
4340 const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4341 if (Size.isScalable())
4342 Res = getMulExpr(Res, getVScale(IntTy));
4343 return Res;
4346 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
4347 return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4350 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) {
4351 return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4354 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
4355 StructType *STy,
4356 unsigned FieldNo) {
4357 // We can bypass creating a target-independent constant expression and then
4358 // folding it back into a ConstantInt. This is just a compile-time
4359 // optimization.
4360 const StructLayout *SL = getDataLayout().getStructLayout(STy);
4361 assert(!SL->getSizeInBits().isScalable() &&
4362 "Cannot get offset for structure containing scalable vector types");
4363 return getConstant(IntTy, SL->getElementOffset(FieldNo));
4366 const SCEV *ScalarEvolution::getUnknown(Value *V) {
4367 // Don't attempt to do anything other than create a SCEVUnknown object
4368 // here. createSCEV only calls getUnknown after checking for all other
4369 // interesting possibilities, and any other code that calls getUnknown
4370 // is doing so in order to hide a value from SCEV canonicalization.
4372 FoldingSetNodeID ID;
4373 ID.AddInteger(scUnknown);
4374 ID.AddPointer(V);
4375 void *IP = nullptr;
4376 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
4377 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4378 "Stale SCEVUnknown in uniquing map!");
4379 return S;
4381 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4382 FirstUnknown);
4383 FirstUnknown = cast<SCEVUnknown>(S);
4384 UniqueSCEVs.InsertNode(S, IP);
4385 return S;
4388 //===----------------------------------------------------------------------===//
4389 // Basic SCEV Analysis and PHI Idiom Recognition Code
4392 /// Test if values of the given type are analyzable within the SCEV
4393 /// framework. This primarily includes integer types, and it can optionally
4394 /// include pointer types if the ScalarEvolution class has access to
4395 /// target-specific information.
4396 bool ScalarEvolution::isSCEVable(Type *Ty) const {
4397 // Integers and pointers are always SCEVable.
4398 return Ty->isIntOrPtrTy();
4401 /// Return the size in bits of the specified type, for which isSCEVable must
4402 /// return true.
4403 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
4404 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4405 if (Ty->isPointerTy())
4406 return getDataLayout().getIndexTypeSizeInBits(Ty);
4407 return getDataLayout().getTypeSizeInBits(Ty);
4410 /// Return a type with the same bitwidth as the given type and which represents
4411 /// how SCEV will treat the given type, for which isSCEVable must return
4412 /// true. For pointer types, this is the pointer index sized integer type.
4413 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
4414 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4416 if (Ty->isIntegerTy())
4417 return Ty;
4419 // The only other support type is pointer.
4420 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4421 return getDataLayout().getIndexType(Ty);
4424 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
4425 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4428 bool ScalarEvolution::instructionCouldExistWithOperands(const SCEV *A,
4429 const SCEV *B) {
4430 /// For a valid use point to exist, the defining scope of one operand
4431 /// must dominate the other.
4432 bool PreciseA, PreciseB;
4433 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4434 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4435 if (!PreciseA || !PreciseB)
4436 // Can't tell.
4437 return false;
4438 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4439 DT.dominates(ScopeB, ScopeA);
4442 const SCEV *ScalarEvolution::getCouldNotCompute() {
4443 return CouldNotCompute.get();
4446 bool ScalarEvolution::checkValidity(const SCEV *S) const {
4447 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4448 auto *SU = dyn_cast<SCEVUnknown>(S);
4449 return SU && SU->getValue() == nullptr;
4452 return !ContainsNulls;
4455 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
4456 HasRecMapType::iterator I = HasRecMap.find(S);
4457 if (I != HasRecMap.end())
4458 return I->second;
4460 bool FoundAddRec =
4461 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4462 HasRecMap.insert({S, FoundAddRec});
4463 return FoundAddRec;
4466 /// Return the ValueOffsetPair set for \p S. \p S can be represented
4467 /// by the value and offset from any ValueOffsetPair in the set.
4468 ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4469 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4470 if (SI == ExprValueMap.end())
4471 return std::nullopt;
4472 return SI->second.getArrayRef();
4475 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4476 /// cannot be used separately. eraseValueFromMap should be used to remove
4477 /// V from ValueExprMap and ExprValueMap at the same time.
4478 void ScalarEvolution::eraseValueFromMap(Value *V) {
4479 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4480 if (I != ValueExprMap.end()) {
4481 auto EVIt = ExprValueMap.find(I->second);
4482 bool Removed = EVIt->second.remove(V);
4483 (void) Removed;
4484 assert(Removed && "Value not in ExprValueMap?");
4485 ValueExprMap.erase(I);
4489 void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4490 // A recursive query may have already computed the SCEV. It should be
4491 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4492 // inferred nowrap flags.
4493 auto It = ValueExprMap.find_as(V);
4494 if (It == ValueExprMap.end()) {
4495 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4496 ExprValueMap[S].insert(V);
4500 /// Return an existing SCEV if it exists, otherwise analyze the expression and
4501 /// create a new one.
4502 const SCEV *ScalarEvolution::getSCEV(Value *V) {
4503 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4505 if (const SCEV *S = getExistingSCEV(V))
4506 return S;
4507 return createSCEVIter(V);
4510 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
4511 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4513 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4514 if (I != ValueExprMap.end()) {
4515 const SCEV *S = I->second;
4516 assert(checkValidity(S) &&
4517 "existing SCEV has not been properly invalidated");
4518 return S;
4520 return nullptr;
4523 /// Return a SCEV corresponding to -V = -1*V
4524 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
4525 SCEV::NoWrapFlags Flags) {
4526 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4527 return getConstant(
4528 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4530 Type *Ty = V->getType();
4531 Ty = getEffectiveSCEVType(Ty);
4532 return getMulExpr(V, getMinusOne(Ty), Flags);
4535 /// If Expr computes ~A, return A else return nullptr
4536 static const SCEV *MatchNotExpr(const SCEV *Expr) {
4537 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
4538 if (!Add || Add->getNumOperands() != 2 ||
4539 !Add->getOperand(0)->isAllOnesValue())
4540 return nullptr;
4542 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
4543 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
4544 !AddRHS->getOperand(0)->isAllOnesValue())
4545 return nullptr;
4547 return AddRHS->getOperand(1);
4550 /// Return a SCEV corresponding to ~V = -1-V
4551 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
4552 assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4554 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4555 return getConstant(
4556 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4558 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4559 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4560 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4561 SmallVector<const SCEV *, 2> MatchedOperands;
4562 for (const SCEV *Operand : MME->operands()) {
4563 const SCEV *Matched = MatchNotExpr(Operand);
4564 if (!Matched)
4565 return (const SCEV *)nullptr;
4566 MatchedOperands.push_back(Matched);
4568 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4569 MatchedOperands);
4571 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4572 return Replaced;
4575 Type *Ty = V->getType();
4576 Ty = getEffectiveSCEVType(Ty);
4577 return getMinusSCEV(getMinusOne(Ty), V);
4580 const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) {
4581 assert(P->getType()->isPointerTy());
4583 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4584 // The base of an AddRec is the first operand.
4585 SmallVector<const SCEV *> Ops{AddRec->operands()};
4586 Ops[0] = removePointerBase(Ops[0]);
4587 // Don't try to transfer nowrap flags for now. We could in some cases
4588 // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4589 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
4591 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4592 // The base of an Add is the pointer operand.
4593 SmallVector<const SCEV *> Ops{Add->operands()};
4594 const SCEV **PtrOp = nullptr;
4595 for (const SCEV *&AddOp : Ops) {
4596 if (AddOp->getType()->isPointerTy()) {
4597 assert(!PtrOp && "Cannot have multiple pointer ops");
4598 PtrOp = &AddOp;
4601 *PtrOp = removePointerBase(*PtrOp);
4602 // Don't try to transfer nowrap flags for now. We could in some cases
4603 // (for example, if the pointer operand of the Add is a SCEVUnknown).
4604 return getAddExpr(Ops);
4606 // Any other expression must be a pointer base.
4607 return getZero(P->getType());
4610 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
4611 SCEV::NoWrapFlags Flags,
4612 unsigned Depth) {
4613 // Fast path: X - X --> 0.
4614 if (LHS == RHS)
4615 return getZero(LHS->getType());
4617 // If we subtract two pointers with different pointer bases, bail.
4618 // Eventually, we're going to add an assertion to getMulExpr that we
4619 // can't multiply by a pointer.
4620 if (RHS->getType()->isPointerTy()) {
4621 if (!LHS->getType()->isPointerTy() ||
4622 getPointerBase(LHS) != getPointerBase(RHS))
4623 return getCouldNotCompute();
4624 LHS = removePointerBase(LHS);
4625 RHS = removePointerBase(RHS);
4628 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4629 // makes it so that we cannot make much use of NUW.
4630 auto AddFlags = SCEV::FlagAnyWrap;
4631 const bool RHSIsNotMinSigned =
4632 !getSignedRangeMin(RHS).isMinSignedValue();
4633 if (hasFlags(Flags, SCEV::FlagNSW)) {
4634 // Let M be the minimum representable signed value. Then (-1)*RHS
4635 // signed-wraps if and only if RHS is M. That can happen even for
4636 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4637 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4638 // (-1)*RHS, we need to prove that RHS != M.
4640 // If LHS is non-negative and we know that LHS - RHS does not
4641 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4642 // either by proving that RHS > M or that LHS >= 0.
4643 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4644 AddFlags = SCEV::FlagNSW;
4648 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4649 // RHS is NSW and LHS >= 0.
4651 // The difficulty here is that the NSW flag may have been proven
4652 // relative to a loop that is to be found in a recurrence in LHS and
4653 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4654 // larger scope than intended.
4655 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4657 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4660 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4661 unsigned Depth) {
4662 Type *SrcTy = V->getType();
4663 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4664 "Cannot truncate or zero extend with non-integer arguments!");
4665 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4666 return V; // No conversion
4667 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4668 return getTruncateExpr(V, Ty, Depth);
4669 return getZeroExtendExpr(V, Ty, Depth);
4672 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4673 unsigned Depth) {
4674 Type *SrcTy = V->getType();
4675 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4676 "Cannot truncate or zero extend with non-integer arguments!");
4677 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4678 return V; // No conversion
4679 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4680 return getTruncateExpr(V, Ty, Depth);
4681 return getSignExtendExpr(V, Ty, Depth);
4684 const SCEV *
4685 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4686 Type *SrcTy = V->getType();
4687 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4688 "Cannot noop or zero extend with non-integer arguments!");
4689 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4690 "getNoopOrZeroExtend cannot truncate!");
4691 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4692 return V; // No conversion
4693 return getZeroExtendExpr(V, Ty);
4696 const SCEV *
4697 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4698 Type *SrcTy = V->getType();
4699 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4700 "Cannot noop or sign extend with non-integer arguments!");
4701 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4702 "getNoopOrSignExtend cannot truncate!");
4703 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4704 return V; // No conversion
4705 return getSignExtendExpr(V, Ty);
4708 const SCEV *
4709 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4710 Type *SrcTy = V->getType();
4711 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4712 "Cannot noop or any extend with non-integer arguments!");
4713 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4714 "getNoopOrAnyExtend cannot truncate!");
4715 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4716 return V; // No conversion
4717 return getAnyExtendExpr(V, Ty);
4720 const SCEV *
4721 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4722 Type *SrcTy = V->getType();
4723 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4724 "Cannot truncate or noop with non-integer arguments!");
4725 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4726 "getTruncateOrNoop cannot extend!");
4727 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4728 return V; // No conversion
4729 return getTruncateExpr(V, Ty);
4732 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4733 const SCEV *RHS) {
4734 const SCEV *PromotedLHS = LHS;
4735 const SCEV *PromotedRHS = RHS;
4737 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4738 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4739 else
4740 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4742 return getUMaxExpr(PromotedLHS, PromotedRHS);
4745 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4746 const SCEV *RHS,
4747 bool Sequential) {
4748 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4749 return getUMinFromMismatchedTypes(Ops, Sequential);
4752 const SCEV *
4753 ScalarEvolution::getUMinFromMismatchedTypes(SmallVectorImpl<const SCEV *> &Ops,
4754 bool Sequential) {
4755 assert(!Ops.empty() && "At least one operand must be!");
4756 // Trivial case.
4757 if (Ops.size() == 1)
4758 return Ops[0];
4760 // Find the max type first.
4761 Type *MaxType = nullptr;
4762 for (const auto *S : Ops)
4763 if (MaxType)
4764 MaxType = getWiderType(MaxType, S->getType());
4765 else
4766 MaxType = S->getType();
4767 assert(MaxType && "Failed to find maximum type!");
4769 // Extend all ops to max type.
4770 SmallVector<const SCEV *, 2> PromotedOps;
4771 for (const auto *S : Ops)
4772 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4774 // Generate umin.
4775 return getUMinExpr(PromotedOps, Sequential);
4778 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4779 // A pointer operand may evaluate to a nonpointer expression, such as null.
4780 if (!V->getType()->isPointerTy())
4781 return V;
4783 while (true) {
4784 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4785 V = AddRec->getStart();
4786 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4787 const SCEV *PtrOp = nullptr;
4788 for (const SCEV *AddOp : Add->operands()) {
4789 if (AddOp->getType()->isPointerTy()) {
4790 assert(!PtrOp && "Cannot have multiple pointer ops");
4791 PtrOp = AddOp;
4794 assert(PtrOp && "Must have pointer op");
4795 V = PtrOp;
4796 } else // Not something we can look further into.
4797 return V;
4801 /// Push users of the given Instruction onto the given Worklist.
4802 static void PushDefUseChildren(Instruction *I,
4803 SmallVectorImpl<Instruction *> &Worklist,
4804 SmallPtrSetImpl<Instruction *> &Visited) {
4805 // Push the def-use children onto the Worklist stack.
4806 for (User *U : I->users()) {
4807 auto *UserInsn = cast<Instruction>(U);
4808 if (Visited.insert(UserInsn).second)
4809 Worklist.push_back(UserInsn);
4813 namespace {
4815 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4816 /// expression in case its Loop is L. If it is not L then
4817 /// if IgnoreOtherLoops is true then use AddRec itself
4818 /// otherwise rewrite cannot be done.
4819 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4820 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4821 public:
4822 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4823 bool IgnoreOtherLoops = true) {
4824 SCEVInitRewriter Rewriter(L, SE);
4825 const SCEV *Result = Rewriter.visit(S);
4826 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4827 return SE.getCouldNotCompute();
4828 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4829 ? SE.getCouldNotCompute()
4830 : Result;
4833 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4834 if (!SE.isLoopInvariant(Expr, L))
4835 SeenLoopVariantSCEVUnknown = true;
4836 return Expr;
4839 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4840 // Only re-write AddRecExprs for this loop.
4841 if (Expr->getLoop() == L)
4842 return Expr->getStart();
4843 SeenOtherLoops = true;
4844 return Expr;
4847 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4849 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4851 private:
4852 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4853 : SCEVRewriteVisitor(SE), L(L) {}
4855 const Loop *L;
4856 bool SeenLoopVariantSCEVUnknown = false;
4857 bool SeenOtherLoops = false;
4860 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4861 /// increment expression in case its Loop is L. If it is not L then
4862 /// use AddRec itself.
4863 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4864 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4865 public:
4866 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4867 SCEVPostIncRewriter Rewriter(L, SE);
4868 const SCEV *Result = Rewriter.visit(S);
4869 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4870 ? SE.getCouldNotCompute()
4871 : Result;
4874 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4875 if (!SE.isLoopInvariant(Expr, L))
4876 SeenLoopVariantSCEVUnknown = true;
4877 return Expr;
4880 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4881 // Only re-write AddRecExprs for this loop.
4882 if (Expr->getLoop() == L)
4883 return Expr->getPostIncExpr(SE);
4884 SeenOtherLoops = true;
4885 return Expr;
4888 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4890 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4892 private:
4893 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4894 : SCEVRewriteVisitor(SE), L(L) {}
4896 const Loop *L;
4897 bool SeenLoopVariantSCEVUnknown = false;
4898 bool SeenOtherLoops = false;
4901 /// This class evaluates the compare condition by matching it against the
4902 /// condition of loop latch. If there is a match we assume a true value
4903 /// for the condition while building SCEV nodes.
4904 class SCEVBackedgeConditionFolder
4905 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4906 public:
4907 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4908 ScalarEvolution &SE) {
4909 bool IsPosBECond = false;
4910 Value *BECond = nullptr;
4911 if (BasicBlock *Latch = L->getLoopLatch()) {
4912 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4913 if (BI && BI->isConditional()) {
4914 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4915 "Both outgoing branches should not target same header!");
4916 BECond = BI->getCondition();
4917 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4918 } else {
4919 return S;
4922 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4923 return Rewriter.visit(S);
4926 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4927 const SCEV *Result = Expr;
4928 bool InvariantF = SE.isLoopInvariant(Expr, L);
4930 if (!InvariantF) {
4931 Instruction *I = cast<Instruction>(Expr->getValue());
4932 switch (I->getOpcode()) {
4933 case Instruction::Select: {
4934 SelectInst *SI = cast<SelectInst>(I);
4935 std::optional<const SCEV *> Res =
4936 compareWithBackedgeCondition(SI->getCondition());
4937 if (Res) {
4938 bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
4939 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4941 break;
4943 default: {
4944 std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4945 if (Res)
4946 Result = *Res;
4947 break;
4951 return Result;
4954 private:
4955 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4956 bool IsPosBECond, ScalarEvolution &SE)
4957 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4958 IsPositiveBECond(IsPosBECond) {}
4960 std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4962 const Loop *L;
4963 /// Loop back condition.
4964 Value *BackedgeCond = nullptr;
4965 /// Set to true if loop back is on positive branch condition.
4966 bool IsPositiveBECond;
4969 std::optional<const SCEV *>
4970 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4972 // If value matches the backedge condition for loop latch,
4973 // then return a constant evolution node based on loopback
4974 // branch taken.
4975 if (BackedgeCond == IC)
4976 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4977 : SE.getZero(Type::getInt1Ty(SE.getContext()));
4978 return std::nullopt;
4981 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4982 public:
4983 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4984 ScalarEvolution &SE) {
4985 SCEVShiftRewriter Rewriter(L, SE);
4986 const SCEV *Result = Rewriter.visit(S);
4987 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4990 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4991 // Only allow AddRecExprs for this loop.
4992 if (!SE.isLoopInvariant(Expr, L))
4993 Valid = false;
4994 return Expr;
4997 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4998 if (Expr->getLoop() == L && Expr->isAffine())
4999 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
5000 Valid = false;
5001 return Expr;
5004 bool isValid() { return Valid; }
5006 private:
5007 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
5008 : SCEVRewriteVisitor(SE), L(L) {}
5010 const Loop *L;
5011 bool Valid = true;
5014 } // end anonymous namespace
5016 SCEV::NoWrapFlags
5017 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
5018 if (!AR->isAffine())
5019 return SCEV::FlagAnyWrap;
5021 using OBO = OverflowingBinaryOperator;
5023 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
5025 if (!AR->hasNoSelfWrap()) {
5026 const SCEV *BECount = getConstantMaxBackedgeTakenCount(AR->getLoop());
5027 if (const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(BECount)) {
5028 ConstantRange StepCR = getSignedRange(AR->getStepRecurrence(*this));
5029 const APInt &BECountAP = BECountMax->getAPInt();
5030 unsigned NoOverflowBitWidth =
5031 BECountAP.getActiveBits() + StepCR.getMinSignedBits();
5032 if (NoOverflowBitWidth <= getTypeSizeInBits(AR->getType()))
5033 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNW);
5037 if (!AR->hasNoSignedWrap()) {
5038 ConstantRange AddRecRange = getSignedRange(AR);
5039 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
5041 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
5042 Instruction::Add, IncRange, OBO::NoSignedWrap);
5043 if (NSWRegion.contains(AddRecRange))
5044 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
5047 if (!AR->hasNoUnsignedWrap()) {
5048 ConstantRange AddRecRange = getUnsignedRange(AR);
5049 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
5051 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
5052 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
5053 if (NUWRegion.contains(AddRecRange))
5054 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
5057 return Result;
5060 SCEV::NoWrapFlags
5061 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5062 SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
5064 if (AR->hasNoSignedWrap())
5065 return Result;
5067 if (!AR->isAffine())
5068 return Result;
5070 // This function can be expensive, only try to prove NSW once per AddRec.
5071 if (!SignedWrapViaInductionTried.insert(AR).second)
5072 return Result;
5074 const SCEV *Step = AR->getStepRecurrence(*this);
5075 const Loop *L = AR->getLoop();
5077 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5078 // Note that this serves two purposes: It filters out loops that are
5079 // simply not analyzable, and it covers the case where this code is
5080 // being called from within backedge-taken count analysis, such that
5081 // attempting to ask for the backedge-taken count would likely result
5082 // in infinite recursion. In the later case, the analysis code will
5083 // cope with a conservative value, and it will take care to purge
5084 // that value once it has finished.
5085 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5087 // Normally, in the cases we can prove no-overflow via a
5088 // backedge guarding condition, we can also compute a backedge
5089 // taken count for the loop. The exceptions are assumptions and
5090 // guards present in the loop -- SCEV is not great at exploiting
5091 // these to compute max backedge taken counts, but can still use
5092 // these to prove lack of overflow. Use this fact to avoid
5093 // doing extra work that may not pay off.
5095 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5096 AC.assumptions().empty())
5097 return Result;
5099 // If the backedge is guarded by a comparison with the pre-inc value the
5100 // addrec is safe. Also, if the entry is guarded by a comparison with the
5101 // start value and the backedge is guarded by a comparison with the post-inc
5102 // value, the addrec is safe.
5103 ICmpInst::Predicate Pred;
5104 const SCEV *OverflowLimit =
5105 getSignedOverflowLimitForStep(Step, &Pred, this);
5106 if (OverflowLimit &&
5107 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5108 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
5109 Result = setFlags(Result, SCEV::FlagNSW);
5111 return Result;
5113 SCEV::NoWrapFlags
5114 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5115 SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
5117 if (AR->hasNoUnsignedWrap())
5118 return Result;
5120 if (!AR->isAffine())
5121 return Result;
5123 // This function can be expensive, only try to prove NUW once per AddRec.
5124 if (!UnsignedWrapViaInductionTried.insert(AR).second)
5125 return Result;
5127 const SCEV *Step = AR->getStepRecurrence(*this);
5128 unsigned BitWidth = getTypeSizeInBits(AR->getType());
5129 const Loop *L = AR->getLoop();
5131 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5132 // Note that this serves two purposes: It filters out loops that are
5133 // simply not analyzable, and it covers the case where this code is
5134 // being called from within backedge-taken count analysis, such that
5135 // attempting to ask for the backedge-taken count would likely result
5136 // in infinite recursion. In the later case, the analysis code will
5137 // cope with a conservative value, and it will take care to purge
5138 // that value once it has finished.
5139 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5141 // Normally, in the cases we can prove no-overflow via a
5142 // backedge guarding condition, we can also compute a backedge
5143 // taken count for the loop. The exceptions are assumptions and
5144 // guards present in the loop -- SCEV is not great at exploiting
5145 // these to compute max backedge taken counts, but can still use
5146 // these to prove lack of overflow. Use this fact to avoid
5147 // doing extra work that may not pay off.
5149 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5150 AC.assumptions().empty())
5151 return Result;
5153 // If the backedge is guarded by a comparison with the pre-inc value the
5154 // addrec is safe. Also, if the entry is guarded by a comparison with the
5155 // start value and the backedge is guarded by a comparison with the post-inc
5156 // value, the addrec is safe.
5157 if (isKnownPositive(Step)) {
5158 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
5159 getUnsignedRangeMax(Step));
5160 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
5161 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
5162 Result = setFlags(Result, SCEV::FlagNUW);
5166 return Result;
5169 namespace {
5171 /// Represents an abstract binary operation. This may exist as a
5172 /// normal instruction or constant expression, or may have been
5173 /// derived from an expression tree.
5174 struct BinaryOp {
5175 unsigned Opcode;
5176 Value *LHS;
5177 Value *RHS;
5178 bool IsNSW = false;
5179 bool IsNUW = false;
5181 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5182 /// constant expression.
5183 Operator *Op = nullptr;
5185 explicit BinaryOp(Operator *Op)
5186 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5187 Op(Op) {
5188 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5189 IsNSW = OBO->hasNoSignedWrap();
5190 IsNUW = OBO->hasNoUnsignedWrap();
5194 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5195 bool IsNUW = false)
5196 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5199 } // end anonymous namespace
5201 /// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
5202 static std::optional<BinaryOp> MatchBinaryOp(Value *V, const DataLayout &DL,
5203 AssumptionCache &AC,
5204 const DominatorTree &DT,
5205 const Instruction *CxtI) {
5206 auto *Op = dyn_cast<Operator>(V);
5207 if (!Op)
5208 return std::nullopt;
5210 // Implementation detail: all the cleverness here should happen without
5211 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5212 // SCEV expressions when possible, and we should not break that.
5214 switch (Op->getOpcode()) {
5215 case Instruction::Add:
5216 case Instruction::Sub:
5217 case Instruction::Mul:
5218 case Instruction::UDiv:
5219 case Instruction::URem:
5220 case Instruction::And:
5221 case Instruction::AShr:
5222 case Instruction::Shl:
5223 return BinaryOp(Op);
5225 case Instruction::Or: {
5226 // LLVM loves to convert `add` of operands with no common bits
5227 // into an `or`. But SCEV really doesn't deal with `or` that well,
5228 // so try extra hard to recognize this `or` as an `add`.
5229 if (haveNoCommonBitsSet(Op->getOperand(0), Op->getOperand(1),
5230 SimplifyQuery(DL, &DT, &AC, CxtI)))
5231 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
5232 /*IsNSW=*/true, /*IsNUW=*/true);
5233 return BinaryOp(Op);
5236 case Instruction::Xor:
5237 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5238 // If the RHS of the xor is a signmask, then this is just an add.
5239 // Instcombine turns add of signmask into xor as a strength reduction step.
5240 if (RHSC->getValue().isSignMask())
5241 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5242 // Binary `xor` is a bit-wise `add`.
5243 if (V->getType()->isIntegerTy(1))
5244 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5245 return BinaryOp(Op);
5247 case Instruction::LShr:
5248 // Turn logical shift right of a constant into a unsigned divide.
5249 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5250 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5252 // If the shift count is not less than the bitwidth, the result of
5253 // the shift is undefined. Don't try to analyze it, because the
5254 // resolution chosen here may differ from the resolution chosen in
5255 // other parts of the compiler.
5256 if (SA->getValue().ult(BitWidth)) {
5257 Constant *X =
5258 ConstantInt::get(SA->getContext(),
5259 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5260 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5263 return BinaryOp(Op);
5265 case Instruction::ExtractValue: {
5266 auto *EVI = cast<ExtractValueInst>(Op);
5267 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5268 break;
5270 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5271 if (!WO)
5272 break;
5274 Instruction::BinaryOps BinOp = WO->getBinaryOp();
5275 bool Signed = WO->isSigned();
5276 // TODO: Should add nuw/nsw flags for mul as well.
5277 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5278 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5280 // Now that we know that all uses of the arithmetic-result component of
5281 // CI are guarded by the overflow check, we can go ahead and pretend
5282 // that the arithmetic is non-overflowing.
5283 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5284 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5287 default:
5288 break;
5291 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5292 // semantics as a Sub, return a binary sub expression.
5293 if (auto *II = dyn_cast<IntrinsicInst>(V))
5294 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5295 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5297 return std::nullopt;
5300 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
5301 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5302 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5303 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5304 /// follows one of the following patterns:
5305 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5306 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5307 /// If the SCEV expression of \p Op conforms with one of the expected patterns
5308 /// we return the type of the truncation operation, and indicate whether the
5309 /// truncated type should be treated as signed/unsigned by setting
5310 /// \p Signed to true/false, respectively.
5311 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5312 bool &Signed, ScalarEvolution &SE) {
5313 // The case where Op == SymbolicPHI (that is, with no type conversions on
5314 // the way) is handled by the regular add recurrence creating logic and
5315 // would have already been triggered in createAddRecForPHI. Reaching it here
5316 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5317 // because one of the other operands of the SCEVAddExpr updating this PHI is
5318 // not invariant).
5320 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5321 // this case predicates that allow us to prove that Op == SymbolicPHI will
5322 // be added.
5323 if (Op == SymbolicPHI)
5324 return nullptr;
5326 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5327 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5328 if (SourceBits != NewBits)
5329 return nullptr;
5331 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
5332 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
5333 if (!SExt && !ZExt)
5334 return nullptr;
5335 const SCEVTruncateExpr *Trunc =
5336 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
5337 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
5338 if (!Trunc)
5339 return nullptr;
5340 const SCEV *X = Trunc->getOperand();
5341 if (X != SymbolicPHI)
5342 return nullptr;
5343 Signed = SExt != nullptr;
5344 return Trunc->getType();
5347 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5348 if (!PN->getType()->isIntegerTy())
5349 return nullptr;
5350 const Loop *L = LI.getLoopFor(PN->getParent());
5351 if (!L || L->getHeader() != PN->getParent())
5352 return nullptr;
5353 return L;
5356 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5357 // computation that updates the phi follows the following pattern:
5358 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5359 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
5360 // If so, try to see if it can be rewritten as an AddRecExpr under some
5361 // Predicates. If successful, return them as a pair. Also cache the results
5362 // of the analysis.
5364 // Example usage scenario:
5365 // Say the Rewriter is called for the following SCEV:
5366 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5367 // where:
5368 // %X = phi i64 (%Start, %BEValue)
5369 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5370 // and call this function with %SymbolicPHI = %X.
5372 // The analysis will find that the value coming around the backedge has
5373 // the following SCEV:
5374 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5375 // Upon concluding that this matches the desired pattern, the function
5376 // will return the pair {NewAddRec, SmallPredsVec} where:
5377 // NewAddRec = {%Start,+,%Step}
5378 // SmallPredsVec = {P1, P2, P3} as follows:
5379 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5380 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5381 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5382 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5383 // under the predicates {P1,P2,P3}.
5384 // This predicated rewrite will be cached in PredicatedSCEVRewrites:
5385 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5387 // TODO's:
5389 // 1) Extend the Induction descriptor to also support inductions that involve
5390 // casts: When needed (namely, when we are called in the context of the
5391 // vectorizer induction analysis), a Set of cast instructions will be
5392 // populated by this method, and provided back to isInductionPHI. This is
5393 // needed to allow the vectorizer to properly record them to be ignored by
5394 // the cost model and to avoid vectorizing them (otherwise these casts,
5395 // which are redundant under the runtime overflow checks, will be
5396 // vectorized, which can be costly).
5398 // 2) Support additional induction/PHISCEV patterns: We also want to support
5399 // inductions where the sext-trunc / zext-trunc operations (partly) occur
5400 // after the induction update operation (the induction increment):
5402 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5403 // which correspond to a phi->add->trunc->sext/zext->phi update chain.
5405 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5406 // which correspond to a phi->trunc->add->sext/zext->phi update chain.
5408 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
5409 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5410 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5411 SmallVector<const SCEVPredicate *, 3> Predicates;
5413 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5414 // return an AddRec expression under some predicate.
5416 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5417 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5418 assert(L && "Expecting an integer loop header phi");
5420 // The loop may have multiple entrances or multiple exits; we can analyze
5421 // this phi as an addrec if it has a unique entry value and a unique
5422 // backedge value.
5423 Value *BEValueV = nullptr, *StartValueV = nullptr;
5424 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5425 Value *V = PN->getIncomingValue(i);
5426 if (L->contains(PN->getIncomingBlock(i))) {
5427 if (!BEValueV) {
5428 BEValueV = V;
5429 } else if (BEValueV != V) {
5430 BEValueV = nullptr;
5431 break;
5433 } else if (!StartValueV) {
5434 StartValueV = V;
5435 } else if (StartValueV != V) {
5436 StartValueV = nullptr;
5437 break;
5440 if (!BEValueV || !StartValueV)
5441 return std::nullopt;
5443 const SCEV *BEValue = getSCEV(BEValueV);
5445 // If the value coming around the backedge is an add with the symbolic
5446 // value we just inserted, possibly with casts that we can ignore under
5447 // an appropriate runtime guard, then we found a simple induction variable!
5448 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5449 if (!Add)
5450 return std::nullopt;
5452 // If there is a single occurrence of the symbolic value, possibly
5453 // casted, replace it with a recurrence.
5454 unsigned FoundIndex = Add->getNumOperands();
5455 Type *TruncTy = nullptr;
5456 bool Signed;
5457 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5458 if ((TruncTy =
5459 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5460 if (FoundIndex == e) {
5461 FoundIndex = i;
5462 break;
5465 if (FoundIndex == Add->getNumOperands())
5466 return std::nullopt;
5468 // Create an add with everything but the specified operand.
5469 SmallVector<const SCEV *, 8> Ops;
5470 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5471 if (i != FoundIndex)
5472 Ops.push_back(Add->getOperand(i));
5473 const SCEV *Accum = getAddExpr(Ops);
5475 // The runtime checks will not be valid if the step amount is
5476 // varying inside the loop.
5477 if (!isLoopInvariant(Accum, L))
5478 return std::nullopt;
5480 // *** Part2: Create the predicates
5482 // Analysis was successful: we have a phi-with-cast pattern for which we
5483 // can return an AddRec expression under the following predicates:
5485 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5486 // fits within the truncated type (does not overflow) for i = 0 to n-1.
5487 // P2: An Equal predicate that guarantees that
5488 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5489 // P3: An Equal predicate that guarantees that
5490 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5492 // As we next prove, the above predicates guarantee that:
5493 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5496 // More formally, we want to prove that:
5497 // Expr(i+1) = Start + (i+1) * Accum
5498 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5500 // Given that:
5501 // 1) Expr(0) = Start
5502 // 2) Expr(1) = Start + Accum
5503 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5504 // 3) Induction hypothesis (step i):
5505 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5507 // Proof:
5508 // Expr(i+1) =
5509 // = Start + (i+1)*Accum
5510 // = (Start + i*Accum) + Accum
5511 // = Expr(i) + Accum
5512 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5513 // :: from step i
5515 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5517 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5518 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
5519 // + Accum :: from P3
5521 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5522 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5524 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5525 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5527 // By induction, the same applies to all iterations 1<=i<n:
5530 // Create a truncated addrec for which we will add a no overflow check (P1).
5531 const SCEV *StartVal = getSCEV(StartValueV);
5532 const SCEV *PHISCEV =
5533 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5534 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5536 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5537 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5538 // will be constant.
5540 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5541 // add P1.
5542 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5543 SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
5544 Signed ? SCEVWrapPredicate::IncrementNSSW
5545 : SCEVWrapPredicate::IncrementNUSW;
5546 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5547 Predicates.push_back(AddRecPred);
5550 // Create the Equal Predicates P2,P3:
5552 // It is possible that the predicates P2 and/or P3 are computable at
5553 // compile time due to StartVal and/or Accum being constants.
5554 // If either one is, then we can check that now and escape if either P2
5555 // or P3 is false.
5557 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5558 // for each of StartVal and Accum
5559 auto getExtendedExpr = [&](const SCEV *Expr,
5560 bool CreateSignExtend) -> const SCEV * {
5561 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5562 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5563 const SCEV *ExtendedExpr =
5564 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5565 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5566 return ExtendedExpr;
5569 // Given:
5570 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5571 // = getExtendedExpr(Expr)
5572 // Determine whether the predicate P: Expr == ExtendedExpr
5573 // is known to be false at compile time
5574 auto PredIsKnownFalse = [&](const SCEV *Expr,
5575 const SCEV *ExtendedExpr) -> bool {
5576 return Expr != ExtendedExpr &&
5577 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5580 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5581 if (PredIsKnownFalse(StartVal, StartExtended)) {
5582 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5583 return std::nullopt;
5586 // The Step is always Signed (because the overflow checks are either
5587 // NSSW or NUSW)
5588 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5589 if (PredIsKnownFalse(Accum, AccumExtended)) {
5590 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5591 return std::nullopt;
5594 auto AppendPredicate = [&](const SCEV *Expr,
5595 const SCEV *ExtendedExpr) -> void {
5596 if (Expr != ExtendedExpr &&
5597 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5598 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5599 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5600 Predicates.push_back(Pred);
5604 AppendPredicate(StartVal, StartExtended);
5605 AppendPredicate(Accum, AccumExtended);
5607 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5608 // which the casts had been folded away. The caller can rewrite SymbolicPHI
5609 // into NewAR if it will also add the runtime overflow checks specified in
5610 // Predicates.
5611 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5613 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5614 std::make_pair(NewAR, Predicates);
5615 // Remember the result of the analysis for this SCEV at this locayyytion.
5616 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5617 return PredRewrite;
5620 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5621 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
5622 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5623 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5624 if (!L)
5625 return std::nullopt;
5627 // Check to see if we already analyzed this PHI.
5628 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5629 if (I != PredicatedSCEVRewrites.end()) {
5630 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5631 I->second;
5632 // Analysis was done before and failed to create an AddRec:
5633 if (Rewrite.first == SymbolicPHI)
5634 return std::nullopt;
5635 // Analysis was done before and succeeded to create an AddRec under
5636 // a predicate:
5637 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5638 assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5639 return Rewrite;
5642 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5643 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5645 // Record in the cache that the analysis failed
5646 if (!Rewrite) {
5647 SmallVector<const SCEVPredicate *, 3> Predicates;
5648 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5649 return std::nullopt;
5652 return Rewrite;
5655 // FIXME: This utility is currently required because the Rewriter currently
5656 // does not rewrite this expression:
5657 // {0, +, (sext ix (trunc iy to ix) to iy)}
5658 // into {0, +, %step},
5659 // even when the following Equal predicate exists:
5660 // "%step == (sext ix (trunc iy to ix) to iy)".
5661 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5662 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
5663 if (AR1 == AR2)
5664 return true;
5666 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5667 if (Expr1 != Expr2 && !Preds->implies(SE.getEqualPredicate(Expr1, Expr2)) &&
5668 !Preds->implies(SE.getEqualPredicate(Expr2, Expr1)))
5669 return false;
5670 return true;
5673 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5674 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5675 return false;
5676 return true;
5679 /// A helper function for createAddRecFromPHI to handle simple cases.
5681 /// This function tries to find an AddRec expression for the simplest (yet most
5682 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5683 /// If it fails, createAddRecFromPHI will use a more general, but slow,
5684 /// technique for finding the AddRec expression.
5685 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5686 Value *BEValueV,
5687 Value *StartValueV) {
5688 const Loop *L = LI.getLoopFor(PN->getParent());
5689 assert(L && L->getHeader() == PN->getParent());
5690 assert(BEValueV && StartValueV);
5692 auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN);
5693 if (!BO)
5694 return nullptr;
5696 if (BO->Opcode != Instruction::Add)
5697 return nullptr;
5699 const SCEV *Accum = nullptr;
5700 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5701 Accum = getSCEV(BO->RHS);
5702 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5703 Accum = getSCEV(BO->LHS);
5705 if (!Accum)
5706 return nullptr;
5708 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5709 if (BO->IsNUW)
5710 Flags = setFlags(Flags, SCEV::FlagNUW);
5711 if (BO->IsNSW)
5712 Flags = setFlags(Flags, SCEV::FlagNSW);
5714 const SCEV *StartVal = getSCEV(StartValueV);
5715 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5716 insertValueToMap(PN, PHISCEV);
5718 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5719 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR),
5720 (SCEV::NoWrapFlags)(AR->getNoWrapFlags() |
5721 proveNoWrapViaConstantRanges(AR)));
5724 // We can add Flags to the post-inc expression only if we
5725 // know that it is *undefined behavior* for BEValueV to
5726 // overflow.
5727 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5728 assert(isLoopInvariant(Accum, L) &&
5729 "Accum is defined outside L, but is not invariant?");
5730 if (isAddRecNeverPoison(BEInst, L))
5731 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5734 return PHISCEV;
5737 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5738 const Loop *L = LI.getLoopFor(PN->getParent());
5739 if (!L || L->getHeader() != PN->getParent())
5740 return nullptr;
5742 // The loop may have multiple entrances or multiple exits; we can analyze
5743 // this phi as an addrec if it has a unique entry value and a unique
5744 // backedge value.
5745 Value *BEValueV = nullptr, *StartValueV = nullptr;
5746 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5747 Value *V = PN->getIncomingValue(i);
5748 if (L->contains(PN->getIncomingBlock(i))) {
5749 if (!BEValueV) {
5750 BEValueV = V;
5751 } else if (BEValueV != V) {
5752 BEValueV = nullptr;
5753 break;
5755 } else if (!StartValueV) {
5756 StartValueV = V;
5757 } else if (StartValueV != V) {
5758 StartValueV = nullptr;
5759 break;
5762 if (!BEValueV || !StartValueV)
5763 return nullptr;
5765 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5766 "PHI node already processed?");
5768 // First, try to find AddRec expression without creating a fictituos symbolic
5769 // value for PN.
5770 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5771 return S;
5773 // Handle PHI node value symbolically.
5774 const SCEV *SymbolicName = getUnknown(PN);
5775 insertValueToMap(PN, SymbolicName);
5777 // Using this symbolic name for the PHI, analyze the value coming around
5778 // the back-edge.
5779 const SCEV *BEValue = getSCEV(BEValueV);
5781 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5782 // has a special value for the first iteration of the loop.
5784 // If the value coming around the backedge is an add with the symbolic
5785 // value we just inserted, then we found a simple induction variable!
5786 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5787 // If there is a single occurrence of the symbolic value, replace it
5788 // with a recurrence.
5789 unsigned FoundIndex = Add->getNumOperands();
5790 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5791 if (Add->getOperand(i) == SymbolicName)
5792 if (FoundIndex == e) {
5793 FoundIndex = i;
5794 break;
5797 if (FoundIndex != Add->getNumOperands()) {
5798 // Create an add with everything but the specified operand.
5799 SmallVector<const SCEV *, 8> Ops;
5800 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5801 if (i != FoundIndex)
5802 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5803 L, *this));
5804 const SCEV *Accum = getAddExpr(Ops);
5806 // This is not a valid addrec if the step amount is varying each
5807 // loop iteration, but is not itself an addrec in this loop.
5808 if (isLoopInvariant(Accum, L) ||
5809 (isa<SCEVAddRecExpr>(Accum) &&
5810 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5811 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5813 if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
5814 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5815 if (BO->IsNUW)
5816 Flags = setFlags(Flags, SCEV::FlagNUW);
5817 if (BO->IsNSW)
5818 Flags = setFlags(Flags, SCEV::FlagNSW);
5820 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5821 // If the increment is an inbounds GEP, then we know the address
5822 // space cannot be wrapped around. We cannot make any guarantee
5823 // about signed or unsigned overflow because pointers are
5824 // unsigned but we may have a negative index from the base
5825 // pointer. We can guarantee that no unsigned wrap occurs if the
5826 // indices form a positive value.
5827 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5828 Flags = setFlags(Flags, SCEV::FlagNW);
5829 if (isKnownPositive(Accum))
5830 Flags = setFlags(Flags, SCEV::FlagNUW);
5833 // We cannot transfer nuw and nsw flags from subtraction
5834 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5835 // for instance.
5838 const SCEV *StartVal = getSCEV(StartValueV);
5839 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5841 // Okay, for the entire analysis of this edge we assumed the PHI
5842 // to be symbolic. We now need to go back and purge all of the
5843 // entries for the scalars that use the symbolic expression.
5844 forgetMemoizedResults(SymbolicName);
5845 insertValueToMap(PN, PHISCEV);
5847 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5848 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR),
5849 (SCEV::NoWrapFlags)(AR->getNoWrapFlags() |
5850 proveNoWrapViaConstantRanges(AR)));
5853 // We can add Flags to the post-inc expression only if we
5854 // know that it is *undefined behavior* for BEValueV to
5855 // overflow.
5856 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5857 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5858 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5860 return PHISCEV;
5863 } else {
5864 // Otherwise, this could be a loop like this:
5865 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5866 // In this case, j = {1,+,1} and BEValue is j.
5867 // Because the other in-value of i (0) fits the evolution of BEValue
5868 // i really is an addrec evolution.
5870 // We can generalize this saying that i is the shifted value of BEValue
5871 // by one iteration:
5872 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5873 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5874 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5875 if (Shifted != getCouldNotCompute() &&
5876 Start != getCouldNotCompute()) {
5877 const SCEV *StartVal = getSCEV(StartValueV);
5878 if (Start == StartVal) {
5879 // Okay, for the entire analysis of this edge we assumed the PHI
5880 // to be symbolic. We now need to go back and purge all of the
5881 // entries for the scalars that use the symbolic expression.
5882 forgetMemoizedResults(SymbolicName);
5883 insertValueToMap(PN, Shifted);
5884 return Shifted;
5889 // Remove the temporary PHI node SCEV that has been inserted while intending
5890 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5891 // as it will prevent later (possibly simpler) SCEV expressions to be added
5892 // to the ValueExprMap.
5893 eraseValueFromMap(PN);
5895 return nullptr;
5898 // Try to match a control flow sequence that branches out at BI and merges back
5899 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5900 // match.
5901 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5902 Value *&C, Value *&LHS, Value *&RHS) {
5903 C = BI->getCondition();
5905 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5906 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5908 if (!LeftEdge.isSingleEdge())
5909 return false;
5911 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5913 Use &LeftUse = Merge->getOperandUse(0);
5914 Use &RightUse = Merge->getOperandUse(1);
5916 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5917 LHS = LeftUse;
5918 RHS = RightUse;
5919 return true;
5922 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5923 LHS = RightUse;
5924 RHS = LeftUse;
5925 return true;
5928 return false;
5931 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5932 auto IsReachable =
5933 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5934 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5935 // Try to match
5937 // br %cond, label %left, label %right
5938 // left:
5939 // br label %merge
5940 // right:
5941 // br label %merge
5942 // merge:
5943 // V = phi [ %x, %left ], [ %y, %right ]
5945 // as "select %cond, %x, %y"
5947 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5948 assert(IDom && "At least the entry block should dominate PN");
5950 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5951 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5953 if (BI && BI->isConditional() &&
5954 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5955 properlyDominates(getSCEV(LHS), PN->getParent()) &&
5956 properlyDominates(getSCEV(RHS), PN->getParent()))
5957 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5960 return nullptr;
5963 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5964 if (const SCEV *S = createAddRecFromPHI(PN))
5965 return S;
5967 if (Value *V = simplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5968 return getSCEV(V);
5970 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5971 return S;
5973 // If it's not a loop phi, we can't handle it yet.
5974 return getUnknown(PN);
5977 bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
5978 SCEVTypes RootKind) {
5979 struct FindClosure {
5980 const SCEV *OperandToFind;
5981 const SCEVTypes RootKind; // Must be a sequential min/max expression.
5982 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
5984 bool Found = false;
5986 bool canRecurseInto(SCEVTypes Kind) const {
5987 // We can only recurse into the SCEV expression of the same effective type
5988 // as the type of our root SCEV expression, and into zero-extensions.
5989 return RootKind == Kind || NonSequentialRootKind == Kind ||
5990 scZeroExtend == Kind;
5993 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
5994 : OperandToFind(OperandToFind), RootKind(RootKind),
5995 NonSequentialRootKind(
5996 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
5997 RootKind)) {}
5999 bool follow(const SCEV *S) {
6000 Found = S == OperandToFind;
6002 return !isDone() && canRecurseInto(S->getSCEVType());
6005 bool isDone() const { return Found; }
6008 FindClosure FC(OperandToFind, RootKind);
6009 visitAll(Root, FC);
6010 return FC.Found;
6013 std::optional<const SCEV *>
6014 ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
6015 ICmpInst *Cond,
6016 Value *TrueVal,
6017 Value *FalseVal) {
6018 // Try to match some simple smax or umax patterns.
6019 auto *ICI = Cond;
6021 Value *LHS = ICI->getOperand(0);
6022 Value *RHS = ICI->getOperand(1);
6024 switch (ICI->getPredicate()) {
6025 case ICmpInst::ICMP_SLT:
6026 case ICmpInst::ICMP_SLE:
6027 case ICmpInst::ICMP_ULT:
6028 case ICmpInst::ICMP_ULE:
6029 std::swap(LHS, RHS);
6030 [[fallthrough]];
6031 case ICmpInst::ICMP_SGT:
6032 case ICmpInst::ICMP_SGE:
6033 case ICmpInst::ICMP_UGT:
6034 case ICmpInst::ICMP_UGE:
6035 // a > b ? a+x : b+x -> max(a, b)+x
6036 // a > b ? b+x : a+x -> min(a, b)+x
6037 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(Ty)) {
6038 bool Signed = ICI->isSigned();
6039 const SCEV *LA = getSCEV(TrueVal);
6040 const SCEV *RA = getSCEV(FalseVal);
6041 const SCEV *LS = getSCEV(LHS);
6042 const SCEV *RS = getSCEV(RHS);
6043 if (LA->getType()->isPointerTy()) {
6044 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6045 // Need to make sure we can't produce weird expressions involving
6046 // negated pointers.
6047 if (LA == LS && RA == RS)
6048 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6049 if (LA == RS && RA == LS)
6050 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6052 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6053 if (Op->getType()->isPointerTy()) {
6054 Op = getLosslessPtrToIntExpr(Op);
6055 if (isa<SCEVCouldNotCompute>(Op))
6056 return Op;
6058 if (Signed)
6059 Op = getNoopOrSignExtend(Op, Ty);
6060 else
6061 Op = getNoopOrZeroExtend(Op, Ty);
6062 return Op;
6064 LS = CoerceOperand(LS);
6065 RS = CoerceOperand(RS);
6066 if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS))
6067 break;
6068 const SCEV *LDiff = getMinusSCEV(LA, LS);
6069 const SCEV *RDiff = getMinusSCEV(RA, RS);
6070 if (LDiff == RDiff)
6071 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6072 LDiff);
6073 LDiff = getMinusSCEV(LA, RS);
6074 RDiff = getMinusSCEV(RA, LS);
6075 if (LDiff == RDiff)
6076 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6077 LDiff);
6079 break;
6080 case ICmpInst::ICMP_NE:
6081 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
6082 std::swap(TrueVal, FalseVal);
6083 [[fallthrough]];
6084 case ICmpInst::ICMP_EQ:
6085 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
6086 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(Ty) &&
6087 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
6088 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6089 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y
6090 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y
6091 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6092 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y
6093 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6094 return getAddExpr(getUMaxExpr(X, C), Y);
6096 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
6097 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
6098 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
6099 // -> umin_seq(x, umin (..., umin_seq(...), ...))
6100 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero() &&
6101 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6102 const SCEV *X = getSCEV(LHS);
6103 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6104 X = ZExt->getOperand();
6105 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6106 const SCEV *FalseValExpr = getSCEV(FalseVal);
6107 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6108 return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6109 /*Sequential=*/true);
6112 break;
6113 default:
6114 break;
6117 return std::nullopt;
6120 static std::optional<const SCEV *>
6121 createNodeForSelectViaUMinSeq(ScalarEvolution *SE, const SCEV *CondExpr,
6122 const SCEV *TrueExpr, const SCEV *FalseExpr) {
6123 assert(CondExpr->getType()->isIntegerTy(1) &&
6124 TrueExpr->getType() == FalseExpr->getType() &&
6125 TrueExpr->getType()->isIntegerTy(1) &&
6126 "Unexpected operands of a select.");
6128 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
6129 // --> C + (umin_seq cond, x - C)
6131 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
6132 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6133 // --> C + (umin_seq ~cond, x - C)
6135 // FIXME: while we can't legally model the case where both of the hands
6136 // are fully variable, we only require that the *difference* is constant.
6137 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6138 return std::nullopt;
6140 const SCEV *X, *C;
6141 if (isa<SCEVConstant>(TrueExpr)) {
6142 CondExpr = SE->getNotSCEV(CondExpr);
6143 X = FalseExpr;
6144 C = TrueExpr;
6145 } else {
6146 X = TrueExpr;
6147 C = FalseExpr;
6149 return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6150 /*Sequential=*/true));
6153 static std::optional<const SCEV *>
6154 createNodeForSelectViaUMinSeq(ScalarEvolution *SE, Value *Cond, Value *TrueVal,
6155 Value *FalseVal) {
6156 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6157 return std::nullopt;
6159 const auto *SECond = SE->getSCEV(Cond);
6160 const auto *SETrue = SE->getSCEV(TrueVal);
6161 const auto *SEFalse = SE->getSCEV(FalseVal);
6162 return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6165 const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6166 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6167 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6168 assert(TrueVal->getType() == FalseVal->getType() &&
6169 V->getType() == TrueVal->getType() &&
6170 "Types of select hands and of the result must match.");
6172 // For now, only deal with i1-typed `select`s.
6173 if (!V->getType()->isIntegerTy(1))
6174 return getUnknown(V);
6176 if (std::optional<const SCEV *> S =
6177 createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6178 return *S;
6180 return getUnknown(V);
6183 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6184 Value *TrueVal,
6185 Value *FalseVal) {
6186 // Handle "constant" branch or select. This can occur for instance when a
6187 // loop pass transforms an inner loop and moves on to process the outer loop.
6188 if (auto *CI = dyn_cast<ConstantInt>(Cond))
6189 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6191 if (auto *I = dyn_cast<Instruction>(V)) {
6192 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6193 if (std::optional<const SCEV *> S =
6194 createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6195 TrueVal, FalseVal))
6196 return *S;
6200 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6203 /// Expand GEP instructions into add and multiply operations. This allows them
6204 /// to be analyzed by regular SCEV code.
6205 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6206 assert(GEP->getSourceElementType()->isSized() &&
6207 "GEP source element type must be sized");
6209 SmallVector<const SCEV *, 4> IndexExprs;
6210 for (Value *Index : GEP->indices())
6211 IndexExprs.push_back(getSCEV(Index));
6212 return getGEPExpr(GEP, IndexExprs);
6215 APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S) {
6216 uint64_t BitWidth = getTypeSizeInBits(S->getType());
6217 auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6218 return TrailingZeros >= BitWidth
6219 ? APInt::getZero(BitWidth)
6220 : APInt::getOneBitSet(BitWidth, TrailingZeros);
6222 auto GetGCDMultiple = [this](const SCEVNAryExpr *N) {
6223 // The result is GCD of all operands results.
6224 APInt Res = getConstantMultiple(N->getOperand(0));
6225 for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6226 Res = APIntOps::GreatestCommonDivisor(
6227 Res, getConstantMultiple(N->getOperand(I)));
6228 return Res;
6231 switch (S->getSCEVType()) {
6232 case scConstant:
6233 return cast<SCEVConstant>(S)->getAPInt();
6234 case scPtrToInt:
6235 return getConstantMultiple(cast<SCEVPtrToIntExpr>(S)->getOperand());
6236 case scUDivExpr:
6237 case scVScale:
6238 return APInt(BitWidth, 1);
6239 case scTruncate: {
6240 // Only multiples that are a power of 2 will hold after truncation.
6241 const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6242 uint32_t TZ = getMinTrailingZeros(T->getOperand());
6243 return GetShiftedByZeros(TZ);
6245 case scZeroExtend: {
6246 const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(S);
6247 return getConstantMultiple(Z->getOperand()).zext(BitWidth);
6249 case scSignExtend: {
6250 const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6251 return getConstantMultiple(E->getOperand()).sext(BitWidth);
6253 case scMulExpr: {
6254 const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6255 if (M->hasNoUnsignedWrap()) {
6256 // The result is the product of all operand results.
6257 APInt Res = getConstantMultiple(M->getOperand(0));
6258 for (const SCEV *Operand : M->operands().drop_front())
6259 Res = Res * getConstantMultiple(Operand);
6260 return Res;
6263 // If there are no wrap guarentees, find the trailing zeros, which is the
6264 // sum of trailing zeros for all its operands.
6265 uint32_t TZ = 0;
6266 for (const SCEV *Operand : M->operands())
6267 TZ += getMinTrailingZeros(Operand);
6268 return GetShiftedByZeros(TZ);
6270 case scAddExpr:
6271 case scAddRecExpr: {
6272 const SCEVNAryExpr *N = cast<SCEVNAryExpr>(S);
6273 if (N->hasNoUnsignedWrap())
6274 return GetGCDMultiple(N);
6275 // Find the trailing bits, which is the minimum of its operands.
6276 uint32_t TZ = getMinTrailingZeros(N->getOperand(0));
6277 for (const SCEV *Operand : N->operands().drop_front())
6278 TZ = std::min(TZ, getMinTrailingZeros(Operand));
6279 return GetShiftedByZeros(TZ);
6281 case scUMaxExpr:
6282 case scSMaxExpr:
6283 case scUMinExpr:
6284 case scSMinExpr:
6285 case scSequentialUMinExpr:
6286 return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6287 case scUnknown: {
6288 // ask ValueTracking for known bits
6289 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6290 unsigned Known =
6291 computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT)
6292 .countMinTrailingZeros();
6293 return GetShiftedByZeros(Known);
6295 case scCouldNotCompute:
6296 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6298 llvm_unreachable("Unknown SCEV kind!");
6301 APInt ScalarEvolution::getConstantMultiple(const SCEV *S) {
6302 auto I = ConstantMultipleCache.find(S);
6303 if (I != ConstantMultipleCache.end())
6304 return I->second;
6306 APInt Result = getConstantMultipleImpl(S);
6307 auto InsertPair = ConstantMultipleCache.insert({S, Result});
6308 assert(InsertPair.second && "Should insert a new key");
6309 return InsertPair.first->second;
6312 APInt ScalarEvolution::getNonZeroConstantMultiple(const SCEV *S) {
6313 APInt Multiple = getConstantMultiple(S);
6314 return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6317 uint32_t ScalarEvolution::getMinTrailingZeros(const SCEV *S) {
6318 return std::min(getConstantMultiple(S).countTrailingZeros(),
6319 (unsigned)getTypeSizeInBits(S->getType()));
6322 /// Helper method to assign a range to V from metadata present in the IR.
6323 static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6324 if (Instruction *I = dyn_cast<Instruction>(V))
6325 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6326 return getConstantRangeFromMetadata(*MD);
6328 return std::nullopt;
6331 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
6332 SCEV::NoWrapFlags Flags) {
6333 if (AddRec->getNoWrapFlags(Flags) != Flags) {
6334 AddRec->setNoWrapFlags(Flags);
6335 UnsignedRanges.erase(AddRec);
6336 SignedRanges.erase(AddRec);
6337 ConstantMultipleCache.erase(AddRec);
6341 ConstantRange ScalarEvolution::
6342 getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6343 const DataLayout &DL = getDataLayout();
6345 unsigned BitWidth = getTypeSizeInBits(U->getType());
6346 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6348 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6349 // use information about the trip count to improve our available range. Note
6350 // that the trip count independent cases are already handled by known bits.
6351 // WARNING: The definition of recurrence used here is subtly different than
6352 // the one used by AddRec (and thus most of this file). Step is allowed to
6353 // be arbitrarily loop varying here, where AddRec allows only loop invariant
6354 // and other addrecs in the same loop (for non-affine addrecs). The code
6355 // below intentionally handles the case where step is not loop invariant.
6356 auto *P = dyn_cast<PHINode>(U->getValue());
6357 if (!P)
6358 return FullSet;
6360 // Make sure that no Phi input comes from an unreachable block. Otherwise,
6361 // even the values that are not available in these blocks may come from them,
6362 // and this leads to false-positive recurrence test.
6363 for (auto *Pred : predecessors(P->getParent()))
6364 if (!DT.isReachableFromEntry(Pred))
6365 return FullSet;
6367 BinaryOperator *BO;
6368 Value *Start, *Step;
6369 if (!matchSimpleRecurrence(P, BO, Start, Step))
6370 return FullSet;
6372 // If we found a recurrence in reachable code, we must be in a loop. Note
6373 // that BO might be in some subloop of L, and that's completely okay.
6374 auto *L = LI.getLoopFor(P->getParent());
6375 assert(L && L->getHeader() == P->getParent());
6376 if (!L->contains(BO->getParent()))
6377 // NOTE: This bailout should be an assert instead. However, asserting
6378 // the condition here exposes a case where LoopFusion is querying SCEV
6379 // with malformed loop information during the midst of the transform.
6380 // There doesn't appear to be an obvious fix, so for the moment bailout
6381 // until the caller issue can be fixed. PR49566 tracks the bug.
6382 return FullSet;
6384 // TODO: Extend to other opcodes such as mul, and div
6385 switch (BO->getOpcode()) {
6386 default:
6387 return FullSet;
6388 case Instruction::AShr:
6389 case Instruction::LShr:
6390 case Instruction::Shl:
6391 break;
6394 if (BO->getOperand(0) != P)
6395 // TODO: Handle the power function forms some day.
6396 return FullSet;
6398 unsigned TC = getSmallConstantMaxTripCount(L);
6399 if (!TC || TC >= BitWidth)
6400 return FullSet;
6402 auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT);
6403 auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT);
6404 assert(KnownStart.getBitWidth() == BitWidth &&
6405 KnownStep.getBitWidth() == BitWidth);
6407 // Compute total shift amount, being careful of overflow and bitwidths.
6408 auto MaxShiftAmt = KnownStep.getMaxValue();
6409 APInt TCAP(BitWidth, TC-1);
6410 bool Overflow = false;
6411 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6412 if (Overflow)
6413 return FullSet;
6415 switch (BO->getOpcode()) {
6416 default:
6417 llvm_unreachable("filtered out above");
6418 case Instruction::AShr: {
6419 // For each ashr, three cases:
6420 // shift = 0 => unchanged value
6421 // saturation => 0 or -1
6422 // other => a value closer to zero (of the same sign)
6423 // Thus, the end value is closer to zero than the start.
6424 auto KnownEnd = KnownBits::ashr(KnownStart,
6425 KnownBits::makeConstant(TotalShift));
6426 if (KnownStart.isNonNegative())
6427 // Analogous to lshr (simply not yet canonicalized)
6428 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6429 KnownStart.getMaxValue() + 1);
6430 if (KnownStart.isNegative())
6431 // End >=u Start && End <=s Start
6432 return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6433 KnownEnd.getMaxValue() + 1);
6434 break;
6436 case Instruction::LShr: {
6437 // For each lshr, three cases:
6438 // shift = 0 => unchanged value
6439 // saturation => 0
6440 // other => a smaller positive number
6441 // Thus, the low end of the unsigned range is the last value produced.
6442 auto KnownEnd = KnownBits::lshr(KnownStart,
6443 KnownBits::makeConstant(TotalShift));
6444 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6445 KnownStart.getMaxValue() + 1);
6447 case Instruction::Shl: {
6448 // Iff no bits are shifted out, value increases on every shift.
6449 auto KnownEnd = KnownBits::shl(KnownStart,
6450 KnownBits::makeConstant(TotalShift));
6451 if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6452 return ConstantRange(KnownStart.getMinValue(),
6453 KnownEnd.getMaxValue() + 1);
6454 break;
6457 return FullSet;
6460 const ConstantRange &
6461 ScalarEvolution::getRangeRefIter(const SCEV *S,
6462 ScalarEvolution::RangeSignHint SignHint) {
6463 DenseMap<const SCEV *, ConstantRange> &Cache =
6464 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6465 : SignedRanges;
6466 SmallVector<const SCEV *> WorkList;
6467 SmallPtrSet<const SCEV *, 8> Seen;
6469 // Add Expr to the worklist, if Expr is either an N-ary expression or a
6470 // SCEVUnknown PHI node.
6471 auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6472 if (!Seen.insert(Expr).second)
6473 return;
6474 if (Cache.contains(Expr))
6475 return;
6476 switch (Expr->getSCEVType()) {
6477 case scUnknown:
6478 if (!isa<PHINode>(cast<SCEVUnknown>(Expr)->getValue()))
6479 break;
6480 [[fallthrough]];
6481 case scConstant:
6482 case scVScale:
6483 case scTruncate:
6484 case scZeroExtend:
6485 case scSignExtend:
6486 case scPtrToInt:
6487 case scAddExpr:
6488 case scMulExpr:
6489 case scUDivExpr:
6490 case scAddRecExpr:
6491 case scUMaxExpr:
6492 case scSMaxExpr:
6493 case scUMinExpr:
6494 case scSMinExpr:
6495 case scSequentialUMinExpr:
6496 WorkList.push_back(Expr);
6497 break;
6498 case scCouldNotCompute:
6499 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6502 AddToWorklist(S);
6504 // Build worklist by queuing operands of N-ary expressions and phi nodes.
6505 for (unsigned I = 0; I != WorkList.size(); ++I) {
6506 const SCEV *P = WorkList[I];
6507 auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6508 // If it is not a `SCEVUnknown`, just recurse into operands.
6509 if (!UnknownS) {
6510 for (const SCEV *Op : P->operands())
6511 AddToWorklist(Op);
6512 continue;
6514 // `SCEVUnknown`'s require special treatment.
6515 if (const PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6516 if (!PendingPhiRangesIter.insert(P).second)
6517 continue;
6518 for (auto &Op : reverse(P->operands()))
6519 AddToWorklist(getSCEV(Op));
6523 if (!WorkList.empty()) {
6524 // Use getRangeRef to compute ranges for items in the worklist in reverse
6525 // order. This will force ranges for earlier operands to be computed before
6526 // their users in most cases.
6527 for (const SCEV *P : reverse(drop_begin(WorkList))) {
6528 getRangeRef(P, SignHint);
6530 if (auto *UnknownS = dyn_cast<SCEVUnknown>(P))
6531 if (const PHINode *P = dyn_cast<PHINode>(UnknownS->getValue()))
6532 PendingPhiRangesIter.erase(P);
6536 return getRangeRef(S, SignHint, 0);
6539 /// Determine the range for a particular SCEV. If SignHint is
6540 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6541 /// with a "cleaner" unsigned (resp. signed) representation.
6542 const ConstantRange &ScalarEvolution::getRangeRef(
6543 const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6544 DenseMap<const SCEV *, ConstantRange> &Cache =
6545 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6546 : SignedRanges;
6547 ConstantRange::PreferredRangeType RangeType =
6548 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6549 : ConstantRange::Signed;
6551 // See if we've computed this range already.
6552 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
6553 if (I != Cache.end())
6554 return I->second;
6556 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6557 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6559 // Switch to iteratively computing the range for S, if it is part of a deeply
6560 // nested expression.
6561 if (Depth > RangeIterThreshold)
6562 return getRangeRefIter(S, SignHint);
6564 unsigned BitWidth = getTypeSizeInBits(S->getType());
6565 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6566 using OBO = OverflowingBinaryOperator;
6568 // If the value has known zeros, the maximum value will have those known zeros
6569 // as well.
6570 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6571 APInt Multiple = getNonZeroConstantMultiple(S);
6572 APInt Remainder = APInt::getMaxValue(BitWidth).urem(Multiple);
6573 if (!Remainder.isZero())
6574 ConservativeResult =
6575 ConstantRange(APInt::getMinValue(BitWidth),
6576 APInt::getMaxValue(BitWidth) - Remainder + 1);
6578 else {
6579 uint32_t TZ = getMinTrailingZeros(S);
6580 if (TZ != 0) {
6581 ConservativeResult = ConstantRange(
6582 APInt::getSignedMinValue(BitWidth),
6583 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6587 switch (S->getSCEVType()) {
6588 case scConstant:
6589 llvm_unreachable("Already handled above.");
6590 case scVScale:
6591 return setRange(S, SignHint, getVScaleRange(&F, BitWidth));
6592 case scTruncate: {
6593 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6594 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6595 return setRange(
6596 Trunc, SignHint,
6597 ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6599 case scZeroExtend: {
6600 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6601 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6602 return setRange(
6603 ZExt, SignHint,
6604 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6606 case scSignExtend: {
6607 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6608 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6609 return setRange(
6610 SExt, SignHint,
6611 ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6613 case scPtrToInt: {
6614 const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(S);
6615 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint, Depth + 1);
6616 return setRange(PtrToInt, SignHint, X);
6618 case scAddExpr: {
6619 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6620 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6621 unsigned WrapType = OBO::AnyWrap;
6622 if (Add->hasNoSignedWrap())
6623 WrapType |= OBO::NoSignedWrap;
6624 if (Add->hasNoUnsignedWrap())
6625 WrapType |= OBO::NoUnsignedWrap;
6626 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
6627 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint, Depth + 1),
6628 WrapType, RangeType);
6629 return setRange(Add, SignHint,
6630 ConservativeResult.intersectWith(X, RangeType));
6632 case scMulExpr: {
6633 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6634 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6635 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
6636 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint, Depth + 1));
6637 return setRange(Mul, SignHint,
6638 ConservativeResult.intersectWith(X, RangeType));
6640 case scUDivExpr: {
6641 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6642 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6643 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6644 return setRange(UDiv, SignHint,
6645 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6647 case scAddRecExpr: {
6648 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6649 // If there's no unsigned wrap, the value will never be less than its
6650 // initial value.
6651 if (AddRec->hasNoUnsignedWrap()) {
6652 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6653 if (!UnsignedMinValue.isZero())
6654 ConservativeResult = ConservativeResult.intersectWith(
6655 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6658 // If there's no signed wrap, and all the operands except initial value have
6659 // the same sign or zero, the value won't ever be:
6660 // 1: smaller than initial value if operands are non negative,
6661 // 2: bigger than initial value if operands are non positive.
6662 // For both cases, value can not cross signed min/max boundary.
6663 if (AddRec->hasNoSignedWrap()) {
6664 bool AllNonNeg = true;
6665 bool AllNonPos = true;
6666 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6667 if (!isKnownNonNegative(AddRec->getOperand(i)))
6668 AllNonNeg = false;
6669 if (!isKnownNonPositive(AddRec->getOperand(i)))
6670 AllNonPos = false;
6672 if (AllNonNeg)
6673 ConservativeResult = ConservativeResult.intersectWith(
6674 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
6675 APInt::getSignedMinValue(BitWidth)),
6676 RangeType);
6677 else if (AllNonPos)
6678 ConservativeResult = ConservativeResult.intersectWith(
6679 ConstantRange::getNonEmpty(APInt::getSignedMinValue(BitWidth),
6680 getSignedRangeMax(AddRec->getStart()) +
6682 RangeType);
6685 // TODO: non-affine addrec
6686 if (AddRec->isAffine()) {
6687 const SCEV *MaxBEScev =
6688 getConstantMaxBackedgeTakenCount(AddRec->getLoop());
6689 if (!isa<SCEVCouldNotCompute>(MaxBEScev)) {
6690 APInt MaxBECount = cast<SCEVConstant>(MaxBEScev)->getAPInt();
6692 // Adjust MaxBECount to the same bitwidth as AddRec. We can truncate if
6693 // MaxBECount's active bits are all <= AddRec's bit width.
6694 if (MaxBECount.getBitWidth() > BitWidth &&
6695 MaxBECount.getActiveBits() <= BitWidth)
6696 MaxBECount = MaxBECount.trunc(BitWidth);
6697 else if (MaxBECount.getBitWidth() < BitWidth)
6698 MaxBECount = MaxBECount.zext(BitWidth);
6700 if (MaxBECount.getBitWidth() == BitWidth) {
6701 auto RangeFromAffine = getRangeForAffineAR(
6702 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6703 ConservativeResult =
6704 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6706 auto RangeFromFactoring = getRangeViaFactoring(
6707 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6708 ConservativeResult =
6709 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6713 // Now try symbolic BE count and more powerful methods.
6714 if (UseExpensiveRangeSharpening) {
6715 const SCEV *SymbolicMaxBECount =
6716 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
6717 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6718 getTypeSizeInBits(MaxBEScev->getType()) <= BitWidth &&
6719 AddRec->hasNoSelfWrap()) {
6720 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6721 AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6722 ConservativeResult =
6723 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6728 return setRange(AddRec, SignHint, std::move(ConservativeResult));
6730 case scUMaxExpr:
6731 case scSMaxExpr:
6732 case scUMinExpr:
6733 case scSMinExpr:
6734 case scSequentialUMinExpr: {
6735 Intrinsic::ID ID;
6736 switch (S->getSCEVType()) {
6737 case scUMaxExpr:
6738 ID = Intrinsic::umax;
6739 break;
6740 case scSMaxExpr:
6741 ID = Intrinsic::smax;
6742 break;
6743 case scUMinExpr:
6744 case scSequentialUMinExpr:
6745 ID = Intrinsic::umin;
6746 break;
6747 case scSMinExpr:
6748 ID = Intrinsic::smin;
6749 break;
6750 default:
6751 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6754 const auto *NAry = cast<SCEVNAryExpr>(S);
6755 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
6756 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6757 X = X.intrinsic(
6758 ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
6759 return setRange(S, SignHint,
6760 ConservativeResult.intersectWith(X, RangeType));
6762 case scUnknown: {
6763 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6764 Value *V = U->getValue();
6766 // Check if the IR explicitly contains !range metadata.
6767 std::optional<ConstantRange> MDRange = GetRangeFromMetadata(V);
6768 if (MDRange)
6769 ConservativeResult =
6770 ConservativeResult.intersectWith(*MDRange, RangeType);
6772 // Use facts about recurrences in the underlying IR. Note that add
6773 // recurrences are AddRecExprs and thus don't hit this path. This
6774 // primarily handles shift recurrences.
6775 auto CR = getRangeForUnknownRecurrence(U);
6776 ConservativeResult = ConservativeResult.intersectWith(CR);
6778 // See if ValueTracking can give us a useful range.
6779 const DataLayout &DL = getDataLayout();
6780 KnownBits Known = computeKnownBits(V, DL, 0, &AC, nullptr, &DT);
6781 if (Known.getBitWidth() != BitWidth)
6782 Known = Known.zextOrTrunc(BitWidth);
6784 // ValueTracking may be able to compute a tighter result for the number of
6785 // sign bits than for the value of those sign bits.
6786 unsigned NS = ComputeNumSignBits(V, DL, 0, &AC, nullptr, &DT);
6787 if (U->getType()->isPointerTy()) {
6788 // If the pointer size is larger than the index size type, this can cause
6789 // NS to be larger than BitWidth. So compensate for this.
6790 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
6791 int ptrIdxDiff = ptrSize - BitWidth;
6792 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
6793 NS -= ptrIdxDiff;
6796 if (NS > 1) {
6797 // If we know any of the sign bits, we know all of the sign bits.
6798 if (!Known.Zero.getHiBits(NS).isZero())
6799 Known.Zero.setHighBits(NS);
6800 if (!Known.One.getHiBits(NS).isZero())
6801 Known.One.setHighBits(NS);
6804 if (Known.getMinValue() != Known.getMaxValue() + 1)
6805 ConservativeResult = ConservativeResult.intersectWith(
6806 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6807 RangeType);
6808 if (NS > 1)
6809 ConservativeResult = ConservativeResult.intersectWith(
6810 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6811 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6812 RangeType);
6814 if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
6815 // Strengthen the range if the underlying IR value is a
6816 // global/alloca/heap allocation using the size of the object.
6817 ObjectSizeOpts Opts;
6818 Opts.RoundToAlign = false;
6819 Opts.NullIsUnknownSize = true;
6820 uint64_t ObjSize;
6821 if ((isa<GlobalVariable>(V) || isa<AllocaInst>(V) ||
6822 isAllocationFn(V, &TLI)) &&
6823 getObjectSize(V, ObjSize, DL, &TLI, Opts) && ObjSize > 1) {
6824 // The highest address the object can start is ObjSize bytes before the
6825 // end (unsigned max value). If this value is not a multiple of the
6826 // alignment, the last possible start value is the next lowest multiple
6827 // of the alignment. Note: The computations below cannot overflow,
6828 // because if they would there's no possible start address for the
6829 // object.
6830 APInt MaxVal = APInt::getMaxValue(BitWidth) - APInt(BitWidth, ObjSize);
6831 uint64_t Align = U->getValue()->getPointerAlignment(DL).value();
6832 uint64_t Rem = MaxVal.urem(Align);
6833 MaxVal -= APInt(BitWidth, Rem);
6834 APInt MinVal = APInt::getZero(BitWidth);
6835 if (llvm::isKnownNonZero(V, DL))
6836 MinVal = Align;
6837 ConservativeResult = ConservativeResult.intersectWith(
6838 ConstantRange::getNonEmpty(MinVal, MaxVal + 1), RangeType);
6842 // A range of Phi is a subset of union of all ranges of its input.
6843 if (PHINode *Phi = dyn_cast<PHINode>(V)) {
6844 // Make sure that we do not run over cycled Phis.
6845 if (PendingPhiRanges.insert(Phi).second) {
6846 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6848 for (const auto &Op : Phi->operands()) {
6849 auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
6850 RangeFromOps = RangeFromOps.unionWith(OpRange);
6851 // No point to continue if we already have a full set.
6852 if (RangeFromOps.isFullSet())
6853 break;
6855 ConservativeResult =
6856 ConservativeResult.intersectWith(RangeFromOps, RangeType);
6857 bool Erased = PendingPhiRanges.erase(Phi);
6858 assert(Erased && "Failed to erase Phi properly?");
6859 (void)Erased;
6863 // vscale can't be equal to zero
6864 if (const auto *II = dyn_cast<IntrinsicInst>(V))
6865 if (II->getIntrinsicID() == Intrinsic::vscale) {
6866 ConstantRange Disallowed = APInt::getZero(BitWidth);
6867 ConservativeResult = ConservativeResult.difference(Disallowed);
6870 return setRange(U, SignHint, std::move(ConservativeResult));
6872 case scCouldNotCompute:
6873 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6876 return setRange(S, SignHint, std::move(ConservativeResult));
6879 // Given a StartRange, Step and MaxBECount for an expression compute a range of
6880 // values that the expression can take. Initially, the expression has a value
6881 // from StartRange and then is changed by Step up to MaxBECount times. Signed
6882 // argument defines if we treat Step as signed or unsigned.
6883 static ConstantRange getRangeForAffineARHelper(APInt Step,
6884 const ConstantRange &StartRange,
6885 const APInt &MaxBECount,
6886 bool Signed) {
6887 unsigned BitWidth = Step.getBitWidth();
6888 assert(BitWidth == StartRange.getBitWidth() &&
6889 BitWidth == MaxBECount.getBitWidth() && "mismatched bit widths");
6890 // If either Step or MaxBECount is 0, then the expression won't change, and we
6891 // just need to return the initial range.
6892 if (Step == 0 || MaxBECount == 0)
6893 return StartRange;
6895 // If we don't know anything about the initial value (i.e. StartRange is
6896 // FullRange), then we don't know anything about the final range either.
6897 // Return FullRange.
6898 if (StartRange.isFullSet())
6899 return ConstantRange::getFull(BitWidth);
6901 // If Step is signed and negative, then we use its absolute value, but we also
6902 // note that we're moving in the opposite direction.
6903 bool Descending = Signed && Step.isNegative();
6905 if (Signed)
6906 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
6907 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
6908 // This equations hold true due to the well-defined wrap-around behavior of
6909 // APInt.
6910 Step = Step.abs();
6912 // Check if Offset is more than full span of BitWidth. If it is, the
6913 // expression is guaranteed to overflow.
6914 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
6915 return ConstantRange::getFull(BitWidth);
6917 // Offset is by how much the expression can change. Checks above guarantee no
6918 // overflow here.
6919 APInt Offset = Step * MaxBECount;
6921 // Minimum value of the final range will match the minimal value of StartRange
6922 // if the expression is increasing and will be decreased by Offset otherwise.
6923 // Maximum value of the final range will match the maximal value of StartRange
6924 // if the expression is decreasing and will be increased by Offset otherwise.
6925 APInt StartLower = StartRange.getLower();
6926 APInt StartUpper = StartRange.getUpper() - 1;
6927 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
6928 : (StartUpper + std::move(Offset));
6930 // It's possible that the new minimum/maximum value will fall into the initial
6931 // range (due to wrap around). This means that the expression can take any
6932 // value in this bitwidth, and we have to return full range.
6933 if (StartRange.contains(MovedBoundary))
6934 return ConstantRange::getFull(BitWidth);
6936 APInt NewLower =
6937 Descending ? std::move(MovedBoundary) : std::move(StartLower);
6938 APInt NewUpper =
6939 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
6940 NewUpper += 1;
6942 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
6943 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
6946 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
6947 const SCEV *Step,
6948 const APInt &MaxBECount) {
6949 assert(getTypeSizeInBits(Start->getType()) ==
6950 getTypeSizeInBits(Step->getType()) &&
6951 getTypeSizeInBits(Start->getType()) == MaxBECount.getBitWidth() &&
6952 "mismatched bit widths");
6954 // First, consider step signed.
6955 ConstantRange StartSRange = getSignedRange(Start);
6956 ConstantRange StepSRange = getSignedRange(Step);
6958 // If Step can be both positive and negative, we need to find ranges for the
6959 // maximum absolute step values in both directions and union them.
6960 ConstantRange SR = getRangeForAffineARHelper(
6961 StepSRange.getSignedMin(), StartSRange, MaxBECount, /* Signed = */ true);
6962 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
6963 StartSRange, MaxBECount,
6964 /* Signed = */ true));
6966 // Next, consider step unsigned.
6967 ConstantRange UR = getRangeForAffineARHelper(
6968 getUnsignedRangeMax(Step), getUnsignedRange(Start), MaxBECount,
6969 /* Signed = */ false);
6971 // Finally, intersect signed and unsigned ranges.
6972 return SR.intersectWith(UR, ConstantRange::Smallest);
6975 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
6976 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
6977 ScalarEvolution::RangeSignHint SignHint) {
6978 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
6979 assert(AddRec->hasNoSelfWrap() &&
6980 "This only works for non-self-wrapping AddRecs!");
6981 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
6982 const SCEV *Step = AddRec->getStepRecurrence(*this);
6983 // Only deal with constant step to save compile time.
6984 if (!isa<SCEVConstant>(Step))
6985 return ConstantRange::getFull(BitWidth);
6986 // Let's make sure that we can prove that we do not self-wrap during
6987 // MaxBECount iterations. We need this because MaxBECount is a maximum
6988 // iteration count estimate, and we might infer nw from some exit for which we
6989 // do not know max exit count (or any other side reasoning).
6990 // TODO: Turn into assert at some point.
6991 if (getTypeSizeInBits(MaxBECount->getType()) >
6992 getTypeSizeInBits(AddRec->getType()))
6993 return ConstantRange::getFull(BitWidth);
6994 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
6995 const SCEV *RangeWidth = getMinusOne(AddRec->getType());
6996 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
6997 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
6998 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
6999 MaxItersWithoutWrap))
7000 return ConstantRange::getFull(BitWidth);
7002 ICmpInst::Predicate LEPred =
7003 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
7004 ICmpInst::Predicate GEPred =
7005 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
7006 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7008 // We know that there is no self-wrap. Let's take Start and End values and
7009 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7010 // the iteration. They either lie inside the range [Min(Start, End),
7011 // Max(Start, End)] or outside it:
7013 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
7014 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
7016 // No self wrap flag guarantees that the intermediate values cannot be BOTH
7017 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7018 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7019 // Start <= End and step is positive, or Start >= End and step is negative.
7020 const SCEV *Start = applyLoopGuards(AddRec->getStart(), AddRec->getLoop());
7021 ConstantRange StartRange = getRangeRef(Start, SignHint);
7022 ConstantRange EndRange = getRangeRef(End, SignHint);
7023 ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7024 // If they already cover full iteration space, we will know nothing useful
7025 // even if we prove what we want to prove.
7026 if (RangeBetween.isFullSet())
7027 return RangeBetween;
7028 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7029 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7030 : RangeBetween.isWrappedSet();
7031 if (IsWrappedSet)
7032 return ConstantRange::getFull(BitWidth);
7034 if (isKnownPositive(Step) &&
7035 isKnownPredicateViaConstantRanges(LEPred, Start, End))
7036 return RangeBetween;
7037 if (isKnownNegative(Step) &&
7038 isKnownPredicateViaConstantRanges(GEPred, Start, End))
7039 return RangeBetween;
7040 return ConstantRange::getFull(BitWidth);
7043 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7044 const SCEV *Step,
7045 const APInt &MaxBECount) {
7046 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7047 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7049 unsigned BitWidth = MaxBECount.getBitWidth();
7050 assert(getTypeSizeInBits(Start->getType()) == BitWidth &&
7051 getTypeSizeInBits(Step->getType()) == BitWidth &&
7052 "mismatched bit widths");
7054 struct SelectPattern {
7055 Value *Condition = nullptr;
7056 APInt TrueValue;
7057 APInt FalseValue;
7059 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7060 const SCEV *S) {
7061 std::optional<unsigned> CastOp;
7062 APInt Offset(BitWidth, 0);
7064 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
7065 "Should be!");
7067 // Peel off a constant offset:
7068 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
7069 // In the future we could consider being smarter here and handle
7070 // {Start+Step,+,Step} too.
7071 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
7072 return;
7074 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
7075 S = SA->getOperand(1);
7078 // Peel off a cast operation
7079 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7080 CastOp = SCast->getSCEVType();
7081 S = SCast->getOperand();
7084 using namespace llvm::PatternMatch;
7086 auto *SU = dyn_cast<SCEVUnknown>(S);
7087 const APInt *TrueVal, *FalseVal;
7088 if (!SU ||
7089 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7090 m_APInt(FalseVal)))) {
7091 Condition = nullptr;
7092 return;
7095 TrueValue = *TrueVal;
7096 FalseValue = *FalseVal;
7098 // Re-apply the cast we peeled off earlier
7099 if (CastOp)
7100 switch (*CastOp) {
7101 default:
7102 llvm_unreachable("Unknown SCEV cast type!");
7104 case scTruncate:
7105 TrueValue = TrueValue.trunc(BitWidth);
7106 FalseValue = FalseValue.trunc(BitWidth);
7107 break;
7108 case scZeroExtend:
7109 TrueValue = TrueValue.zext(BitWidth);
7110 FalseValue = FalseValue.zext(BitWidth);
7111 break;
7112 case scSignExtend:
7113 TrueValue = TrueValue.sext(BitWidth);
7114 FalseValue = FalseValue.sext(BitWidth);
7115 break;
7118 // Re-apply the constant offset we peeled off earlier
7119 TrueValue += Offset;
7120 FalseValue += Offset;
7123 bool isRecognized() { return Condition != nullptr; }
7126 SelectPattern StartPattern(*this, BitWidth, Start);
7127 if (!StartPattern.isRecognized())
7128 return ConstantRange::getFull(BitWidth);
7130 SelectPattern StepPattern(*this, BitWidth, Step);
7131 if (!StepPattern.isRecognized())
7132 return ConstantRange::getFull(BitWidth);
7134 if (StartPattern.Condition != StepPattern.Condition) {
7135 // We don't handle this case today; but we could, by considering four
7136 // possibilities below instead of two. I'm not sure if there are cases where
7137 // that will help over what getRange already does, though.
7138 return ConstantRange::getFull(BitWidth);
7141 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7142 // construct arbitrary general SCEV expressions here. This function is called
7143 // from deep in the call stack, and calling getSCEV (on a sext instruction,
7144 // say) can end up caching a suboptimal value.
7146 // FIXME: without the explicit `this` receiver below, MSVC errors out with
7147 // C2352 and C2512 (otherwise it isn't needed).
7149 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7150 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7151 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7152 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7154 ConstantRange TrueRange =
7155 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount);
7156 ConstantRange FalseRange =
7157 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount);
7159 return TrueRange.unionWith(FalseRange);
7162 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7163 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
7164 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7166 // Return early if there are no flags to propagate to the SCEV.
7167 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
7168 if (BinOp->hasNoUnsignedWrap())
7169 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
7170 if (BinOp->hasNoSignedWrap())
7171 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
7172 if (Flags == SCEV::FlagAnyWrap)
7173 return SCEV::FlagAnyWrap;
7175 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
7178 const Instruction *
7179 ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7180 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7181 return &*AddRec->getLoop()->getHeader()->begin();
7182 if (auto *U = dyn_cast<SCEVUnknown>(S))
7183 if (auto *I = dyn_cast<Instruction>(U->getValue()))
7184 return I;
7185 return nullptr;
7188 const Instruction *
7189 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops,
7190 bool &Precise) {
7191 Precise = true;
7192 // Do a bounded search of the def relation of the requested SCEVs.
7193 SmallSet<const SCEV *, 16> Visited;
7194 SmallVector<const SCEV *> Worklist;
7195 auto pushOp = [&](const SCEV *S) {
7196 if (!Visited.insert(S).second)
7197 return;
7198 // Threshold of 30 here is arbitrary.
7199 if (Visited.size() > 30) {
7200 Precise = false;
7201 return;
7203 Worklist.push_back(S);
7206 for (const auto *S : Ops)
7207 pushOp(S);
7209 const Instruction *Bound = nullptr;
7210 while (!Worklist.empty()) {
7211 auto *S = Worklist.pop_back_val();
7212 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7213 if (!Bound || DT.dominates(Bound, DefI))
7214 Bound = DefI;
7215 } else {
7216 for (const auto *Op : S->operands())
7217 pushOp(Op);
7220 return Bound ? Bound : &*F.getEntryBlock().begin();
7223 const Instruction *
7224 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops) {
7225 bool Discard;
7226 return getDefiningScopeBound(Ops, Discard);
7229 bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7230 const Instruction *B) {
7231 if (A->getParent() == B->getParent() &&
7232 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
7233 B->getIterator()))
7234 return true;
7236 auto *BLoop = LI.getLoopFor(B->getParent());
7237 if (BLoop && BLoop->getHeader() == B->getParent() &&
7238 BLoop->getLoopPreheader() == A->getParent() &&
7239 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
7240 A->getParent()->end()) &&
7241 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7242 B->getIterator()))
7243 return true;
7244 return false;
7248 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7249 // Only proceed if we can prove that I does not yield poison.
7250 if (!programUndefinedIfPoison(I))
7251 return false;
7253 // At this point we know that if I is executed, then it does not wrap
7254 // according to at least one of NSW or NUW. If I is not executed, then we do
7255 // not know if the calculation that I represents would wrap. Multiple
7256 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7257 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7258 // derived from other instructions that map to the same SCEV. We cannot make
7259 // that guarantee for cases where I is not executed. So we need to find a
7260 // upper bound on the defining scope for the SCEV, and prove that I is
7261 // executed every time we enter that scope. When the bounding scope is a
7262 // loop (the common case), this is equivalent to proving I executes on every
7263 // iteration of that loop.
7264 SmallVector<const SCEV *> SCEVOps;
7265 for (const Use &Op : I->operands()) {
7266 // I could be an extractvalue from a call to an overflow intrinsic.
7267 // TODO: We can do better here in some cases.
7268 if (isSCEVable(Op->getType()))
7269 SCEVOps.push_back(getSCEV(Op));
7271 auto *DefI = getDefiningScopeBound(SCEVOps);
7272 return isGuaranteedToTransferExecutionTo(DefI, I);
7275 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7276 // If we know that \c I can never be poison period, then that's enough.
7277 if (isSCEVExprNeverPoison(I))
7278 return true;
7280 // If the loop only has one exit, then we know that, if the loop is entered,
7281 // any instruction dominating that exit will be executed. If any such
7282 // instruction would result in UB, the addrec cannot be poison.
7284 // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7285 // also handles uses outside the loop header (they just need to dominate the
7286 // single exit).
7288 auto *ExitingBB = L->getExitingBlock();
7289 if (!ExitingBB || !loopHasNoAbnormalExits(L))
7290 return false;
7292 SmallPtrSet<const Value *, 16> KnownPoison;
7293 SmallVector<const Instruction *, 8> Worklist;
7295 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
7296 // things that are known to be poison under that assumption go on the
7297 // Worklist.
7298 KnownPoison.insert(I);
7299 Worklist.push_back(I);
7301 while (!Worklist.empty()) {
7302 const Instruction *Poison = Worklist.pop_back_val();
7304 for (const Use &U : Poison->uses()) {
7305 const Instruction *PoisonUser = cast<Instruction>(U.getUser());
7306 if (mustTriggerUB(PoisonUser, KnownPoison) &&
7307 DT.dominates(PoisonUser->getParent(), ExitingBB))
7308 return true;
7310 if (propagatesPoison(U) && L->contains(PoisonUser))
7311 if (KnownPoison.insert(PoisonUser).second)
7312 Worklist.push_back(PoisonUser);
7316 return false;
7319 ScalarEvolution::LoopProperties
7320 ScalarEvolution::getLoopProperties(const Loop *L) {
7321 using LoopProperties = ScalarEvolution::LoopProperties;
7323 auto Itr = LoopPropertiesCache.find(L);
7324 if (Itr == LoopPropertiesCache.end()) {
7325 auto HasSideEffects = [](Instruction *I) {
7326 if (auto *SI = dyn_cast<StoreInst>(I))
7327 return !SI->isSimple();
7329 return I->mayThrow() || I->mayWriteToMemory();
7332 LoopProperties LP = {/* HasNoAbnormalExits */ true,
7333 /*HasNoSideEffects*/ true};
7335 for (auto *BB : L->getBlocks())
7336 for (auto &I : *BB) {
7337 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
7338 LP.HasNoAbnormalExits = false;
7339 if (HasSideEffects(&I))
7340 LP.HasNoSideEffects = false;
7341 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7342 break; // We're already as pessimistic as we can get.
7345 auto InsertPair = LoopPropertiesCache.insert({L, LP});
7346 assert(InsertPair.second && "We just checked!");
7347 Itr = InsertPair.first;
7350 return Itr->second;
7353 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) {
7354 // A mustprogress loop without side effects must be finite.
7355 // TODO: The check used here is very conservative. It's only *specific*
7356 // side effects which are well defined in infinite loops.
7357 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7360 const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7361 // Worklist item with a Value and a bool indicating whether all operands have
7362 // been visited already.
7363 using PointerTy = PointerIntPair<Value *, 1, bool>;
7364 SmallVector<PointerTy> Stack;
7366 Stack.emplace_back(V, true);
7367 Stack.emplace_back(V, false);
7368 while (!Stack.empty()) {
7369 auto E = Stack.pop_back_val();
7370 Value *CurV = E.getPointer();
7372 if (getExistingSCEV(CurV))
7373 continue;
7375 SmallVector<Value *> Ops;
7376 const SCEV *CreatedSCEV = nullptr;
7377 // If all operands have been visited already, create the SCEV.
7378 if (E.getInt()) {
7379 CreatedSCEV = createSCEV(CurV);
7380 } else {
7381 // Otherwise get the operands we need to create SCEV's for before creating
7382 // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7383 // just use it.
7384 CreatedSCEV = getOperandsToCreate(CurV, Ops);
7387 if (CreatedSCEV) {
7388 insertValueToMap(CurV, CreatedSCEV);
7389 } else {
7390 // Queue CurV for SCEV creation, followed by its's operands which need to
7391 // be constructed first.
7392 Stack.emplace_back(CurV, true);
7393 for (Value *Op : Ops)
7394 Stack.emplace_back(Op, false);
7398 return getExistingSCEV(V);
7401 const SCEV *
7402 ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7403 if (!isSCEVable(V->getType()))
7404 return getUnknown(V);
7406 if (Instruction *I = dyn_cast<Instruction>(V)) {
7407 // Don't attempt to analyze instructions in blocks that aren't
7408 // reachable. Such instructions don't matter, and they aren't required
7409 // to obey basic rules for definitions dominating uses which this
7410 // analysis depends on.
7411 if (!DT.isReachableFromEntry(I->getParent()))
7412 return getUnknown(PoisonValue::get(V->getType()));
7413 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7414 return getConstant(CI);
7415 else if (isa<GlobalAlias>(V))
7416 return getUnknown(V);
7417 else if (!isa<ConstantExpr>(V))
7418 return getUnknown(V);
7420 Operator *U = cast<Operator>(V);
7421 if (auto BO =
7422 MatchBinaryOp(U, getDataLayout(), AC, DT, dyn_cast<Instruction>(V))) {
7423 bool IsConstArg = isa<ConstantInt>(BO->RHS);
7424 switch (BO->Opcode) {
7425 case Instruction::Add:
7426 case Instruction::Mul: {
7427 // For additions and multiplications, traverse add/mul chains for which we
7428 // can potentially create a single SCEV, to reduce the number of
7429 // get{Add,Mul}Expr calls.
7430 do {
7431 if (BO->Op) {
7432 if (BO->Op != V && getExistingSCEV(BO->Op)) {
7433 Ops.push_back(BO->Op);
7434 break;
7437 Ops.push_back(BO->RHS);
7438 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7439 dyn_cast<Instruction>(V));
7440 if (!NewBO ||
7441 (BO->Opcode == Instruction::Add &&
7442 (NewBO->Opcode != Instruction::Add &&
7443 NewBO->Opcode != Instruction::Sub)) ||
7444 (BO->Opcode == Instruction::Mul &&
7445 NewBO->Opcode != Instruction::Mul)) {
7446 Ops.push_back(BO->LHS);
7447 break;
7449 // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7450 // requires a SCEV for the LHS.
7451 if (BO->Op && (BO->IsNSW || BO->IsNUW)) {
7452 auto *I = dyn_cast<Instruction>(BO->Op);
7453 if (I && programUndefinedIfPoison(I)) {
7454 Ops.push_back(BO->LHS);
7455 break;
7458 BO = NewBO;
7459 } while (true);
7460 return nullptr;
7462 case Instruction::Sub:
7463 case Instruction::UDiv:
7464 case Instruction::URem:
7465 break;
7466 case Instruction::AShr:
7467 case Instruction::Shl:
7468 case Instruction::Xor:
7469 if (!IsConstArg)
7470 return nullptr;
7471 break;
7472 case Instruction::And:
7473 case Instruction::Or:
7474 if (!IsConstArg && !BO->LHS->getType()->isIntegerTy(1))
7475 return nullptr;
7476 break;
7477 case Instruction::LShr:
7478 return getUnknown(V);
7479 default:
7480 llvm_unreachable("Unhandled binop");
7481 break;
7484 Ops.push_back(BO->LHS);
7485 Ops.push_back(BO->RHS);
7486 return nullptr;
7489 switch (U->getOpcode()) {
7490 case Instruction::Trunc:
7491 case Instruction::ZExt:
7492 case Instruction::SExt:
7493 case Instruction::PtrToInt:
7494 Ops.push_back(U->getOperand(0));
7495 return nullptr;
7497 case Instruction::BitCast:
7498 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
7499 Ops.push_back(U->getOperand(0));
7500 return nullptr;
7502 return getUnknown(V);
7504 case Instruction::SDiv:
7505 case Instruction::SRem:
7506 Ops.push_back(U->getOperand(0));
7507 Ops.push_back(U->getOperand(1));
7508 return nullptr;
7510 case Instruction::GetElementPtr:
7511 assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7512 "GEP source element type must be sized");
7513 for (Value *Index : U->operands())
7514 Ops.push_back(Index);
7515 return nullptr;
7517 case Instruction::IntToPtr:
7518 return getUnknown(V);
7520 case Instruction::PHI:
7521 // Keep constructing SCEVs' for phis recursively for now.
7522 return nullptr;
7524 case Instruction::Select: {
7525 // Check if U is a select that can be simplified to a SCEVUnknown.
7526 auto CanSimplifyToUnknown = [this, U]() {
7527 if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
7528 return false;
7530 auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
7531 if (!ICI)
7532 return false;
7533 Value *LHS = ICI->getOperand(0);
7534 Value *RHS = ICI->getOperand(1);
7535 if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7536 ICI->getPredicate() == CmpInst::ICMP_NE) {
7537 if (!(isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()))
7538 return true;
7539 } else if (getTypeSizeInBits(LHS->getType()) >
7540 getTypeSizeInBits(U->getType()))
7541 return true;
7542 return false;
7544 if (CanSimplifyToUnknown())
7545 return getUnknown(U);
7547 for (Value *Inc : U->operands())
7548 Ops.push_back(Inc);
7549 return nullptr;
7550 break;
7552 case Instruction::Call:
7553 case Instruction::Invoke:
7554 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7555 Ops.push_back(RV);
7556 return nullptr;
7559 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7560 switch (II->getIntrinsicID()) {
7561 case Intrinsic::abs:
7562 Ops.push_back(II->getArgOperand(0));
7563 return nullptr;
7564 case Intrinsic::umax:
7565 case Intrinsic::umin:
7566 case Intrinsic::smax:
7567 case Intrinsic::smin:
7568 case Intrinsic::usub_sat:
7569 case Intrinsic::uadd_sat:
7570 Ops.push_back(II->getArgOperand(0));
7571 Ops.push_back(II->getArgOperand(1));
7572 return nullptr;
7573 case Intrinsic::start_loop_iterations:
7574 case Intrinsic::annotation:
7575 case Intrinsic::ptr_annotation:
7576 Ops.push_back(II->getArgOperand(0));
7577 return nullptr;
7578 default:
7579 break;
7582 break;
7585 return nullptr;
7588 const SCEV *ScalarEvolution::createSCEV(Value *V) {
7589 if (!isSCEVable(V->getType()))
7590 return getUnknown(V);
7592 if (Instruction *I = dyn_cast<Instruction>(V)) {
7593 // Don't attempt to analyze instructions in blocks that aren't
7594 // reachable. Such instructions don't matter, and they aren't required
7595 // to obey basic rules for definitions dominating uses which this
7596 // analysis depends on.
7597 if (!DT.isReachableFromEntry(I->getParent()))
7598 return getUnknown(PoisonValue::get(V->getType()));
7599 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7600 return getConstant(CI);
7601 else if (isa<GlobalAlias>(V))
7602 return getUnknown(V);
7603 else if (!isa<ConstantExpr>(V))
7604 return getUnknown(V);
7606 const SCEV *LHS;
7607 const SCEV *RHS;
7609 Operator *U = cast<Operator>(V);
7610 if (auto BO =
7611 MatchBinaryOp(U, getDataLayout(), AC, DT, dyn_cast<Instruction>(V))) {
7612 switch (BO->Opcode) {
7613 case Instruction::Add: {
7614 // The simple thing to do would be to just call getSCEV on both operands
7615 // and call getAddExpr with the result. However if we're looking at a
7616 // bunch of things all added together, this can be quite inefficient,
7617 // because it leads to N-1 getAddExpr calls for N ultimate operands.
7618 // Instead, gather up all the operands and make a single getAddExpr call.
7619 // LLVM IR canonical form means we need only traverse the left operands.
7620 SmallVector<const SCEV *, 4> AddOps;
7621 do {
7622 if (BO->Op) {
7623 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7624 AddOps.push_back(OpSCEV);
7625 break;
7628 // If a NUW or NSW flag can be applied to the SCEV for this
7629 // addition, then compute the SCEV for this addition by itself
7630 // with a separate call to getAddExpr. We need to do that
7631 // instead of pushing the operands of the addition onto AddOps,
7632 // since the flags are only known to apply to this particular
7633 // addition - they may not apply to other additions that can be
7634 // formed with operands from AddOps.
7635 const SCEV *RHS = getSCEV(BO->RHS);
7636 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7637 if (Flags != SCEV::FlagAnyWrap) {
7638 const SCEV *LHS = getSCEV(BO->LHS);
7639 if (BO->Opcode == Instruction::Sub)
7640 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7641 else
7642 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7643 break;
7647 if (BO->Opcode == Instruction::Sub)
7648 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7649 else
7650 AddOps.push_back(getSCEV(BO->RHS));
7652 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7653 dyn_cast<Instruction>(V));
7654 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7655 NewBO->Opcode != Instruction::Sub)) {
7656 AddOps.push_back(getSCEV(BO->LHS));
7657 break;
7659 BO = NewBO;
7660 } while (true);
7662 return getAddExpr(AddOps);
7665 case Instruction::Mul: {
7666 SmallVector<const SCEV *, 4> MulOps;
7667 do {
7668 if (BO->Op) {
7669 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7670 MulOps.push_back(OpSCEV);
7671 break;
7674 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7675 if (Flags != SCEV::FlagAnyWrap) {
7676 LHS = getSCEV(BO->LHS);
7677 RHS = getSCEV(BO->RHS);
7678 MulOps.push_back(getMulExpr(LHS, RHS, Flags));
7679 break;
7683 MulOps.push_back(getSCEV(BO->RHS));
7684 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7685 dyn_cast<Instruction>(V));
7686 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7687 MulOps.push_back(getSCEV(BO->LHS));
7688 break;
7690 BO = NewBO;
7691 } while (true);
7693 return getMulExpr(MulOps);
7695 case Instruction::UDiv:
7696 LHS = getSCEV(BO->LHS);
7697 RHS = getSCEV(BO->RHS);
7698 return getUDivExpr(LHS, RHS);
7699 case Instruction::URem:
7700 LHS = getSCEV(BO->LHS);
7701 RHS = getSCEV(BO->RHS);
7702 return getURemExpr(LHS, RHS);
7703 case Instruction::Sub: {
7704 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
7705 if (BO->Op)
7706 Flags = getNoWrapFlagsFromUB(BO->Op);
7707 LHS = getSCEV(BO->LHS);
7708 RHS = getSCEV(BO->RHS);
7709 return getMinusSCEV(LHS, RHS, Flags);
7711 case Instruction::And:
7712 // For an expression like x&255 that merely masks off the high bits,
7713 // use zext(trunc(x)) as the SCEV expression.
7714 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7715 if (CI->isZero())
7716 return getSCEV(BO->RHS);
7717 if (CI->isMinusOne())
7718 return getSCEV(BO->LHS);
7719 const APInt &A = CI->getValue();
7721 // Instcombine's ShrinkDemandedConstant may strip bits out of
7722 // constants, obscuring what would otherwise be a low-bits mask.
7723 // Use computeKnownBits to compute what ShrinkDemandedConstant
7724 // knew about to reconstruct a low-bits mask value.
7725 unsigned LZ = A.countl_zero();
7726 unsigned TZ = A.countr_zero();
7727 unsigned BitWidth = A.getBitWidth();
7728 KnownBits Known(BitWidth);
7729 computeKnownBits(BO->LHS, Known, getDataLayout(),
7730 0, &AC, nullptr, &DT);
7732 APInt EffectiveMask =
7733 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
7734 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
7735 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
7736 const SCEV *LHS = getSCEV(BO->LHS);
7737 const SCEV *ShiftedLHS = nullptr;
7738 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
7739 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
7740 // For an expression like (x * 8) & 8, simplify the multiply.
7741 unsigned MulZeros = OpC->getAPInt().countr_zero();
7742 unsigned GCD = std::min(MulZeros, TZ);
7743 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
7744 SmallVector<const SCEV*, 4> MulOps;
7745 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
7746 append_range(MulOps, LHSMul->operands().drop_front());
7747 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
7748 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
7751 if (!ShiftedLHS)
7752 ShiftedLHS = getUDivExpr(LHS, MulCount);
7753 return getMulExpr(
7754 getZeroExtendExpr(
7755 getTruncateExpr(ShiftedLHS,
7756 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
7757 BO->LHS->getType()),
7758 MulCount);
7761 // Binary `and` is a bit-wise `umin`.
7762 if (BO->LHS->getType()->isIntegerTy(1)) {
7763 LHS = getSCEV(BO->LHS);
7764 RHS = getSCEV(BO->RHS);
7765 return getUMinExpr(LHS, RHS);
7767 break;
7769 case Instruction::Or:
7770 // Binary `or` is a bit-wise `umax`.
7771 if (BO->LHS->getType()->isIntegerTy(1)) {
7772 LHS = getSCEV(BO->LHS);
7773 RHS = getSCEV(BO->RHS);
7774 return getUMaxExpr(LHS, RHS);
7776 break;
7778 case Instruction::Xor:
7779 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7780 // If the RHS of xor is -1, then this is a not operation.
7781 if (CI->isMinusOne())
7782 return getNotSCEV(getSCEV(BO->LHS));
7784 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
7785 // This is a variant of the check for xor with -1, and it handles
7786 // the case where instcombine has trimmed non-demanded bits out
7787 // of an xor with -1.
7788 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
7789 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
7790 if (LBO->getOpcode() == Instruction::And &&
7791 LCI->getValue() == CI->getValue())
7792 if (const SCEVZeroExtendExpr *Z =
7793 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
7794 Type *UTy = BO->LHS->getType();
7795 const SCEV *Z0 = Z->getOperand();
7796 Type *Z0Ty = Z0->getType();
7797 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
7799 // If C is a low-bits mask, the zero extend is serving to
7800 // mask off the high bits. Complement the operand and
7801 // re-apply the zext.
7802 if (CI->getValue().isMask(Z0TySize))
7803 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
7805 // If C is a single bit, it may be in the sign-bit position
7806 // before the zero-extend. In this case, represent the xor
7807 // using an add, which is equivalent, and re-apply the zext.
7808 APInt Trunc = CI->getValue().trunc(Z0TySize);
7809 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
7810 Trunc.isSignMask())
7811 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
7812 UTy);
7815 break;
7817 case Instruction::Shl:
7818 // Turn shift left of a constant amount into a multiply.
7819 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
7820 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
7822 // If the shift count is not less than the bitwidth, the result of
7823 // the shift is undefined. Don't try to analyze it, because the
7824 // resolution chosen here may differ from the resolution chosen in
7825 // other parts of the compiler.
7826 if (SA->getValue().uge(BitWidth))
7827 break;
7829 // We can safely preserve the nuw flag in all cases. It's also safe to
7830 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
7831 // requires special handling. It can be preserved as long as we're not
7832 // left shifting by bitwidth - 1.
7833 auto Flags = SCEV::FlagAnyWrap;
7834 if (BO->Op) {
7835 auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
7836 if ((MulFlags & SCEV::FlagNSW) &&
7837 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
7838 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
7839 if (MulFlags & SCEV::FlagNUW)
7840 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
7843 ConstantInt *X = ConstantInt::get(
7844 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
7845 return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
7847 break;
7849 case Instruction::AShr:
7850 // AShr X, C, where C is a constant.
7851 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
7852 if (!CI)
7853 break;
7855 Type *OuterTy = BO->LHS->getType();
7856 uint64_t BitWidth = getTypeSizeInBits(OuterTy);
7857 // If the shift count is not less than the bitwidth, the result of
7858 // the shift is undefined. Don't try to analyze it, because the
7859 // resolution chosen here may differ from the resolution chosen in
7860 // other parts of the compiler.
7861 if (CI->getValue().uge(BitWidth))
7862 break;
7864 if (CI->isZero())
7865 return getSCEV(BO->LHS); // shift by zero --> noop
7867 uint64_t AShrAmt = CI->getZExtValue();
7868 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
7870 Operator *L = dyn_cast<Operator>(BO->LHS);
7871 const SCEV *AddTruncateExpr = nullptr;
7872 ConstantInt *ShlAmtCI = nullptr;
7873 const SCEV *AddConstant = nullptr;
7875 if (L && L->getOpcode() == Instruction::Add) {
7876 // X = Shl A, n
7877 // Y = Add X, c
7878 // Z = AShr Y, m
7879 // n, c and m are constants.
7881 Operator *LShift = dyn_cast<Operator>(L->getOperand(0));
7882 ConstantInt *AddOperandCI = dyn_cast<ConstantInt>(L->getOperand(1));
7883 if (LShift && LShift->getOpcode() == Instruction::Shl) {
7884 if (AddOperandCI) {
7885 const SCEV *ShlOp0SCEV = getSCEV(LShift->getOperand(0));
7886 ShlAmtCI = dyn_cast<ConstantInt>(LShift->getOperand(1));
7887 // since we truncate to TruncTy, the AddConstant should be of the
7888 // same type, so create a new Constant with type same as TruncTy.
7889 // Also, the Add constant should be shifted right by AShr amount.
7890 APInt AddOperand = AddOperandCI->getValue().ashr(AShrAmt);
7891 AddConstant = getConstant(TruncTy, AddOperand.getZExtValue(),
7892 AddOperand.isSignBitSet());
7893 // we model the expression as sext(add(trunc(A), c << n)), since the
7894 // sext(trunc) part is already handled below, we create a
7895 // AddExpr(TruncExp) which will be used later.
7896 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
7899 } else if (L && L->getOpcode() == Instruction::Shl) {
7900 // X = Shl A, n
7901 // Y = AShr X, m
7902 // Both n and m are constant.
7904 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
7905 ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
7906 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
7909 if (AddTruncateExpr && ShlAmtCI) {
7910 // We can merge the two given cases into a single SCEV statement,
7911 // incase n = m, the mul expression will be 2^0, so it gets resolved to
7912 // a simpler case. The following code handles the two cases:
7914 // 1) For a two-shift sext-inreg, i.e. n = m,
7915 // use sext(trunc(x)) as the SCEV expression.
7917 // 2) When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
7918 // expression. We already checked that ShlAmt < BitWidth, so
7919 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
7920 // ShlAmt - AShrAmt < Amt.
7921 uint64_t ShlAmt = ShlAmtCI->getZExtValue();
7922 if (ShlAmtCI->getValue().ult(BitWidth) && ShlAmt >= AShrAmt) {
7923 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, ShlAmt - AShrAmt);
7924 const SCEV *CompositeExpr =
7925 getMulExpr(AddTruncateExpr, getConstant(Mul));
7926 if (L->getOpcode() != Instruction::Shl)
7927 CompositeExpr = getAddExpr(CompositeExpr, AddConstant);
7929 return getSignExtendExpr(CompositeExpr, OuterTy);
7932 break;
7936 switch (U->getOpcode()) {
7937 case Instruction::Trunc:
7938 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
7940 case Instruction::ZExt:
7941 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7943 case Instruction::SExt:
7944 if (auto BO = MatchBinaryOp(U->getOperand(0), getDataLayout(), AC, DT,
7945 dyn_cast<Instruction>(V))) {
7946 // The NSW flag of a subtract does not always survive the conversion to
7947 // A + (-1)*B. By pushing sign extension onto its operands we are much
7948 // more likely to preserve NSW and allow later AddRec optimisations.
7950 // NOTE: This is effectively duplicating this logic from getSignExtend:
7951 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
7952 // but by that point the NSW information has potentially been lost.
7953 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
7954 Type *Ty = U->getType();
7955 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
7956 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
7957 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
7960 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7962 case Instruction::BitCast:
7963 // BitCasts are no-op casts so we just eliminate the cast.
7964 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
7965 return getSCEV(U->getOperand(0));
7966 break;
7968 case Instruction::PtrToInt: {
7969 // Pointer to integer cast is straight-forward, so do model it.
7970 const SCEV *Op = getSCEV(U->getOperand(0));
7971 Type *DstIntTy = U->getType();
7972 // But only if effective SCEV (integer) type is wide enough to represent
7973 // all possible pointer values.
7974 const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy);
7975 if (isa<SCEVCouldNotCompute>(IntOp))
7976 return getUnknown(V);
7977 return IntOp;
7979 case Instruction::IntToPtr:
7980 // Just don't deal with inttoptr casts.
7981 return getUnknown(V);
7983 case Instruction::SDiv:
7984 // If both operands are non-negative, this is just an udiv.
7985 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7986 isKnownNonNegative(getSCEV(U->getOperand(1))))
7987 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7988 break;
7990 case Instruction::SRem:
7991 // If both operands are non-negative, this is just an urem.
7992 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7993 isKnownNonNegative(getSCEV(U->getOperand(1))))
7994 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7995 break;
7997 case Instruction::GetElementPtr:
7998 return createNodeForGEP(cast<GEPOperator>(U));
8000 case Instruction::PHI:
8001 return createNodeForPHI(cast<PHINode>(U));
8003 case Instruction::Select:
8004 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
8005 U->getOperand(2));
8007 case Instruction::Call:
8008 case Instruction::Invoke:
8009 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
8010 return getSCEV(RV);
8012 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
8013 switch (II->getIntrinsicID()) {
8014 case Intrinsic::abs:
8015 return getAbsExpr(
8016 getSCEV(II->getArgOperand(0)),
8017 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
8018 case Intrinsic::umax:
8019 LHS = getSCEV(II->getArgOperand(0));
8020 RHS = getSCEV(II->getArgOperand(1));
8021 return getUMaxExpr(LHS, RHS);
8022 case Intrinsic::umin:
8023 LHS = getSCEV(II->getArgOperand(0));
8024 RHS = getSCEV(II->getArgOperand(1));
8025 return getUMinExpr(LHS, RHS);
8026 case Intrinsic::smax:
8027 LHS = getSCEV(II->getArgOperand(0));
8028 RHS = getSCEV(II->getArgOperand(1));
8029 return getSMaxExpr(LHS, RHS);
8030 case Intrinsic::smin:
8031 LHS = getSCEV(II->getArgOperand(0));
8032 RHS = getSCEV(II->getArgOperand(1));
8033 return getSMinExpr(LHS, RHS);
8034 case Intrinsic::usub_sat: {
8035 const SCEV *X = getSCEV(II->getArgOperand(0));
8036 const SCEV *Y = getSCEV(II->getArgOperand(1));
8037 const SCEV *ClampedY = getUMinExpr(X, Y);
8038 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
8040 case Intrinsic::uadd_sat: {
8041 const SCEV *X = getSCEV(II->getArgOperand(0));
8042 const SCEV *Y = getSCEV(II->getArgOperand(1));
8043 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
8044 return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
8046 case Intrinsic::start_loop_iterations:
8047 case Intrinsic::annotation:
8048 case Intrinsic::ptr_annotation:
8049 // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8050 // just eqivalent to the first operand for SCEV purposes.
8051 return getSCEV(II->getArgOperand(0));
8052 case Intrinsic::vscale:
8053 return getVScale(II->getType());
8054 default:
8055 break;
8058 break;
8061 return getUnknown(V);
8064 //===----------------------------------------------------------------------===//
8065 // Iteration Count Computation Code
8068 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount) {
8069 if (isa<SCEVCouldNotCompute>(ExitCount))
8070 return getCouldNotCompute();
8072 auto *ExitCountType = ExitCount->getType();
8073 assert(ExitCountType->isIntegerTy());
8074 auto *EvalTy = Type::getIntNTy(ExitCountType->getContext(),
8075 1 + ExitCountType->getScalarSizeInBits());
8076 return getTripCountFromExitCount(ExitCount, EvalTy, nullptr);
8079 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount,
8080 Type *EvalTy,
8081 const Loop *L) {
8082 if (isa<SCEVCouldNotCompute>(ExitCount))
8083 return getCouldNotCompute();
8085 unsigned ExitCountSize = getTypeSizeInBits(ExitCount->getType());
8086 unsigned EvalSize = EvalTy->getPrimitiveSizeInBits();
8088 auto CanAddOneWithoutOverflow = [&]() {
8089 ConstantRange ExitCountRange =
8090 getRangeRef(ExitCount, RangeSignHint::HINT_RANGE_UNSIGNED);
8091 if (!ExitCountRange.contains(APInt::getMaxValue(ExitCountSize)))
8092 return true;
8094 return L && isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
8095 getMinusOne(ExitCount->getType()));
8098 // If we need to zero extend the backedge count, check if we can add one to
8099 // it prior to zero extending without overflow. Provided this is safe, it
8100 // allows better simplification of the +1.
8101 if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8102 return getZeroExtendExpr(
8103 getAddExpr(ExitCount, getOne(ExitCount->getType())), EvalTy);
8105 // Get the total trip count from the count by adding 1. This may wrap.
8106 return getAddExpr(getTruncateOrZeroExtend(ExitCount, EvalTy), getOne(EvalTy));
8109 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8110 if (!ExitCount)
8111 return 0;
8113 ConstantInt *ExitConst = ExitCount->getValue();
8115 // Guard against huge trip counts.
8116 if (ExitConst->getValue().getActiveBits() > 32)
8117 return 0;
8119 // In case of integer overflow, this returns 0, which is correct.
8120 return ((unsigned)ExitConst->getZExtValue()) + 1;
8123 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
8124 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
8125 return getConstantTripCount(ExitCount);
8128 unsigned
8129 ScalarEvolution::getSmallConstantTripCount(const Loop *L,
8130 const BasicBlock *ExitingBlock) {
8131 assert(ExitingBlock && "Must pass a non-null exiting block!");
8132 assert(L->isLoopExiting(ExitingBlock) &&
8133 "Exiting block must actually branch out of the loop!");
8134 const SCEVConstant *ExitCount =
8135 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
8136 return getConstantTripCount(ExitCount);
8139 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
8140 const auto *MaxExitCount =
8141 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
8142 return getConstantTripCount(MaxExitCount);
8145 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
8146 SmallVector<BasicBlock *, 8> ExitingBlocks;
8147 L->getExitingBlocks(ExitingBlocks);
8149 std::optional<unsigned> Res;
8150 for (auto *ExitingBB : ExitingBlocks) {
8151 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
8152 if (!Res)
8153 Res = Multiple;
8154 Res = (unsigned)std::gcd(*Res, Multiple);
8156 return Res.value_or(1);
8159 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
8160 const SCEV *ExitCount) {
8161 if (ExitCount == getCouldNotCompute())
8162 return 1;
8164 // Get the trip count
8165 const SCEV *TCExpr = getTripCountFromExitCount(applyLoopGuards(ExitCount, L));
8167 APInt Multiple = getNonZeroConstantMultiple(TCExpr);
8168 // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8169 // the greatest power of 2 divisor less than 2^32.
8170 return Multiple.getActiveBits() > 32
8171 ? 1U << std::min((unsigned)31, Multiple.countTrailingZeros())
8172 : (unsigned)Multiple.zextOrTrunc(32).getZExtValue();
8175 /// Returns the largest constant divisor of the trip count of this loop as a
8176 /// normal unsigned value, if possible. This means that the actual trip count is
8177 /// always a multiple of the returned value (don't forget the trip count could
8178 /// very well be zero as well!).
8180 /// Returns 1 if the trip count is unknown or not guaranteed to be the
8181 /// multiple of a constant (which is also the case if the trip count is simply
8182 /// constant, use getSmallConstantTripCount for that case), Will also return 1
8183 /// if the trip count is very large (>= 2^32).
8185 /// As explained in the comments for getSmallConstantTripCount, this assumes
8186 /// that control exits the loop via ExitingBlock.
8187 unsigned
8188 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
8189 const BasicBlock *ExitingBlock) {
8190 assert(ExitingBlock && "Must pass a non-null exiting block!");
8191 assert(L->isLoopExiting(ExitingBlock) &&
8192 "Exiting block must actually branch out of the loop!");
8193 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8194 return getSmallConstantTripMultiple(L, ExitCount);
8197 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
8198 const BasicBlock *ExitingBlock,
8199 ExitCountKind Kind) {
8200 switch (Kind) {
8201 case Exact:
8202 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8203 case SymbolicMaximum:
8204 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8205 case ConstantMaximum:
8206 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8208 llvm_unreachable("Invalid ExitCountKind!");
8211 const SCEV *
8212 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
8213 SmallVector<const SCEVPredicate *, 4> &Preds) {
8214 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8217 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
8218 ExitCountKind Kind) {
8219 switch (Kind) {
8220 case Exact:
8221 return getBackedgeTakenInfo(L).getExact(L, this);
8222 case ConstantMaximum:
8223 return getBackedgeTakenInfo(L).getConstantMax(this);
8224 case SymbolicMaximum:
8225 return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8227 llvm_unreachable("Invalid ExitCountKind!");
8230 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
8231 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8234 /// Push PHI nodes in the header of the given loop onto the given Worklist.
8235 static void PushLoopPHIs(const Loop *L,
8236 SmallVectorImpl<Instruction *> &Worklist,
8237 SmallPtrSetImpl<Instruction *> &Visited) {
8238 BasicBlock *Header = L->getHeader();
8240 // Push all Loop-header PHIs onto the Worklist stack.
8241 for (PHINode &PN : Header->phis())
8242 if (Visited.insert(&PN).second)
8243 Worklist.push_back(&PN);
8246 const ScalarEvolution::BackedgeTakenInfo &
8247 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8248 auto &BTI = getBackedgeTakenInfo(L);
8249 if (BTI.hasFullInfo())
8250 return BTI;
8252 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
8254 if (!Pair.second)
8255 return Pair.first->second;
8257 BackedgeTakenInfo Result =
8258 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8260 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8263 ScalarEvolution::BackedgeTakenInfo &
8264 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8265 // Initially insert an invalid entry for this loop. If the insertion
8266 // succeeds, proceed to actually compute a backedge-taken count and
8267 // update the value. The temporary CouldNotCompute value tells SCEV
8268 // code elsewhere that it shouldn't attempt to request a new
8269 // backedge-taken count, which could result in infinite recursion.
8270 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8271 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
8272 if (!Pair.second)
8273 return Pair.first->second;
8275 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8276 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8277 // must be cleared in this scope.
8278 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8280 // Now that we know more about the trip count for this loop, forget any
8281 // existing SCEV values for PHI nodes in this loop since they are only
8282 // conservative estimates made without the benefit of trip count
8283 // information. This invalidation is not necessary for correctness, and is
8284 // only done to produce more precise results.
8285 if (Result.hasAnyInfo()) {
8286 // Invalidate any expression using an addrec in this loop.
8287 SmallVector<const SCEV *, 8> ToForget;
8288 auto LoopUsersIt = LoopUsers.find(L);
8289 if (LoopUsersIt != LoopUsers.end())
8290 append_range(ToForget, LoopUsersIt->second);
8291 forgetMemoizedResults(ToForget);
8293 // Invalidate constant-evolved loop header phis.
8294 for (PHINode &PN : L->getHeader()->phis())
8295 ConstantEvolutionLoopExitValue.erase(&PN);
8298 // Re-lookup the insert position, since the call to
8299 // computeBackedgeTakenCount above could result in a
8300 // recusive call to getBackedgeTakenInfo (on a different
8301 // loop), which would invalidate the iterator computed
8302 // earlier.
8303 return BackedgeTakenCounts.find(L)->second = std::move(Result);
8306 void ScalarEvolution::forgetAllLoops() {
8307 // This method is intended to forget all info about loops. It should
8308 // invalidate caches as if the following happened:
8309 // - The trip counts of all loops have changed arbitrarily
8310 // - Every llvm::Value has been updated in place to produce a different
8311 // result.
8312 BackedgeTakenCounts.clear();
8313 PredicatedBackedgeTakenCounts.clear();
8314 BECountUsers.clear();
8315 LoopPropertiesCache.clear();
8316 ConstantEvolutionLoopExitValue.clear();
8317 ValueExprMap.clear();
8318 ValuesAtScopes.clear();
8319 ValuesAtScopesUsers.clear();
8320 LoopDispositions.clear();
8321 BlockDispositions.clear();
8322 UnsignedRanges.clear();
8323 SignedRanges.clear();
8324 ExprValueMap.clear();
8325 HasRecMap.clear();
8326 ConstantMultipleCache.clear();
8327 PredicatedSCEVRewrites.clear();
8328 FoldCache.clear();
8329 FoldCacheUser.clear();
8331 void ScalarEvolution::visitAndClearUsers(
8332 SmallVectorImpl<Instruction *> &Worklist,
8333 SmallPtrSetImpl<Instruction *> &Visited,
8334 SmallVectorImpl<const SCEV *> &ToForget) {
8335 while (!Worklist.empty()) {
8336 Instruction *I = Worklist.pop_back_val();
8337 if (!isSCEVable(I->getType()))
8338 continue;
8340 ValueExprMapType::iterator It =
8341 ValueExprMap.find_as(static_cast<Value *>(I));
8342 if (It != ValueExprMap.end()) {
8343 eraseValueFromMap(It->first);
8344 ToForget.push_back(It->second);
8345 if (PHINode *PN = dyn_cast<PHINode>(I))
8346 ConstantEvolutionLoopExitValue.erase(PN);
8349 PushDefUseChildren(I, Worklist, Visited);
8353 void ScalarEvolution::forgetLoop(const Loop *L) {
8354 SmallVector<const Loop *, 16> LoopWorklist(1, L);
8355 SmallVector<Instruction *, 32> Worklist;
8356 SmallPtrSet<Instruction *, 16> Visited;
8357 SmallVector<const SCEV *, 16> ToForget;
8359 // Iterate over all the loops and sub-loops to drop SCEV information.
8360 while (!LoopWorklist.empty()) {
8361 auto *CurrL = LoopWorklist.pop_back_val();
8363 // Drop any stored trip count value.
8364 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8365 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8367 // Drop information about predicated SCEV rewrites for this loop.
8368 for (auto I = PredicatedSCEVRewrites.begin();
8369 I != PredicatedSCEVRewrites.end();) {
8370 std::pair<const SCEV *, const Loop *> Entry = I->first;
8371 if (Entry.second == CurrL)
8372 PredicatedSCEVRewrites.erase(I++);
8373 else
8374 ++I;
8377 auto LoopUsersItr = LoopUsers.find(CurrL);
8378 if (LoopUsersItr != LoopUsers.end()) {
8379 ToForget.insert(ToForget.end(), LoopUsersItr->second.begin(),
8380 LoopUsersItr->second.end());
8383 // Drop information about expressions based on loop-header PHIs.
8384 PushLoopPHIs(CurrL, Worklist, Visited);
8385 visitAndClearUsers(Worklist, Visited, ToForget);
8387 LoopPropertiesCache.erase(CurrL);
8388 // Forget all contained loops too, to avoid dangling entries in the
8389 // ValuesAtScopes map.
8390 LoopWorklist.append(CurrL->begin(), CurrL->end());
8392 forgetMemoizedResults(ToForget);
8395 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
8396 forgetLoop(L->getOutermostLoop());
8399 void ScalarEvolution::forgetValue(Value *V) {
8400 Instruction *I = dyn_cast<Instruction>(V);
8401 if (!I) return;
8403 // Drop information about expressions based on loop-header PHIs.
8404 SmallVector<Instruction *, 16> Worklist;
8405 SmallPtrSet<Instruction *, 8> Visited;
8406 SmallVector<const SCEV *, 8> ToForget;
8407 Worklist.push_back(I);
8408 Visited.insert(I);
8409 visitAndClearUsers(Worklist, Visited, ToForget);
8411 forgetMemoizedResults(ToForget);
8414 void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8416 void ScalarEvolution::forgetBlockAndLoopDispositions(Value *V) {
8417 // Unless a specific value is passed to invalidation, completely clear both
8418 // caches.
8419 if (!V) {
8420 BlockDispositions.clear();
8421 LoopDispositions.clear();
8422 return;
8425 if (!isSCEVable(V->getType()))
8426 return;
8428 const SCEV *S = getExistingSCEV(V);
8429 if (!S)
8430 return;
8432 // Invalidate the block and loop dispositions cached for S. Dispositions of
8433 // S's users may change if S's disposition changes (i.e. a user may change to
8434 // loop-invariant, if S changes to loop invariant), so also invalidate
8435 // dispositions of S's users recursively.
8436 SmallVector<const SCEV *, 8> Worklist = {S};
8437 SmallPtrSet<const SCEV *, 8> Seen = {S};
8438 while (!Worklist.empty()) {
8439 const SCEV *Curr = Worklist.pop_back_val();
8440 bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8441 bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8442 if (!LoopDispoRemoved && !BlockDispoRemoved)
8443 continue;
8444 auto Users = SCEVUsers.find(Curr);
8445 if (Users != SCEVUsers.end())
8446 for (const auto *User : Users->second)
8447 if (Seen.insert(User).second)
8448 Worklist.push_back(User);
8452 /// Get the exact loop backedge taken count considering all loop exits. A
8453 /// computable result can only be returned for loops with all exiting blocks
8454 /// dominating the latch. howFarToZero assumes that the limit of each loop test
8455 /// is never skipped. This is a valid assumption as long as the loop exits via
8456 /// that test. For precise results, it is the caller's responsibility to specify
8457 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
8458 const SCEV *
8459 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
8460 SmallVector<const SCEVPredicate *, 4> *Preds) const {
8461 // If any exits were not computable, the loop is not computable.
8462 if (!isComplete() || ExitNotTaken.empty())
8463 return SE->getCouldNotCompute();
8465 const BasicBlock *Latch = L->getLoopLatch();
8466 // All exiting blocks we have collected must dominate the only backedge.
8467 if (!Latch)
8468 return SE->getCouldNotCompute();
8470 // All exiting blocks we have gathered dominate loop's latch, so exact trip
8471 // count is simply a minimum out of all these calculated exit counts.
8472 SmallVector<const SCEV *, 2> Ops;
8473 for (const auto &ENT : ExitNotTaken) {
8474 const SCEV *BECount = ENT.ExactNotTaken;
8475 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8476 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8477 "We should only have known counts for exiting blocks that dominate "
8478 "latch!");
8480 Ops.push_back(BECount);
8482 if (Preds)
8483 for (const auto *P : ENT.Predicates)
8484 Preds->push_back(P);
8486 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8487 "Predicate should be always true!");
8490 // If an earlier exit exits on the first iteration (exit count zero), then
8491 // a later poison exit count should not propagate into the result. This are
8492 // exactly the semantics provided by umin_seq.
8493 return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8496 /// Get the exact not taken count for this loop exit.
8497 const SCEV *
8498 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
8499 ScalarEvolution *SE) const {
8500 for (const auto &ENT : ExitNotTaken)
8501 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8502 return ENT.ExactNotTaken;
8504 return SE->getCouldNotCompute();
8507 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8508 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
8509 for (const auto &ENT : ExitNotTaken)
8510 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8511 return ENT.ConstantMaxNotTaken;
8513 return SE->getCouldNotCompute();
8516 const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8517 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
8518 for (const auto &ENT : ExitNotTaken)
8519 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8520 return ENT.SymbolicMaxNotTaken;
8522 return SE->getCouldNotCompute();
8525 /// getConstantMax - Get the constant max backedge taken count for the loop.
8526 const SCEV *
8527 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
8528 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8529 return !ENT.hasAlwaysTruePredicate();
8532 if (!getConstantMax() || any_of(ExitNotTaken, PredicateNotAlwaysTrue))
8533 return SE->getCouldNotCompute();
8535 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8536 isa<SCEVConstant>(getConstantMax())) &&
8537 "No point in having a non-constant max backedge taken count!");
8538 return getConstantMax();
8541 const SCEV *
8542 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
8543 ScalarEvolution *SE) {
8544 if (!SymbolicMax)
8545 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
8546 return SymbolicMax;
8549 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8550 ScalarEvolution *SE) const {
8551 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8552 return !ENT.hasAlwaysTruePredicate();
8554 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8557 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
8558 : ExitLimit(E, E, E, false, std::nullopt) {}
8560 ScalarEvolution::ExitLimit::ExitLimit(
8561 const SCEV *E, const SCEV *ConstantMaxNotTaken,
8562 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8563 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
8564 : ExactNotTaken(E), ConstantMaxNotTaken(ConstantMaxNotTaken),
8565 SymbolicMaxNotTaken(SymbolicMaxNotTaken), MaxOrZero(MaxOrZero) {
8566 // If we prove the max count is zero, so is the symbolic bound. This happens
8567 // in practice due to differences in a) how context sensitive we've chosen
8568 // to be and b) how we reason about bounds implied by UB.
8569 if (ConstantMaxNotTaken->isZero()) {
8570 this->ExactNotTaken = E = ConstantMaxNotTaken;
8571 this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
8574 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
8575 !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) &&
8576 "Exact is not allowed to be less precise than Constant Max");
8577 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
8578 !isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken)) &&
8579 "Exact is not allowed to be less precise than Symbolic Max");
8580 assert((isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken) ||
8581 !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) &&
8582 "Symbolic Max is not allowed to be less precise than Constant Max");
8583 assert((isa<SCEVCouldNotCompute>(ConstantMaxNotTaken) ||
8584 isa<SCEVConstant>(ConstantMaxNotTaken)) &&
8585 "No point in having a non-constant max backedge taken count!");
8586 for (const auto *PredSet : PredSetList)
8587 for (const auto *P : *PredSet)
8588 addPredicate(P);
8589 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8590 "Backedge count should be int");
8591 assert((isa<SCEVCouldNotCompute>(ConstantMaxNotTaken) ||
8592 !ConstantMaxNotTaken->getType()->isPointerTy()) &&
8593 "Max backedge count should be int");
8596 ScalarEvolution::ExitLimit::ExitLimit(
8597 const SCEV *E, const SCEV *ConstantMaxNotTaken,
8598 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8599 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
8600 : ExitLimit(E, ConstantMaxNotTaken, SymbolicMaxNotTaken, MaxOrZero,
8601 { &PredSet }) {}
8603 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8604 /// computable exit into a persistent ExitNotTakenInfo array.
8605 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8606 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
8607 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
8608 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8609 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8611 ExitNotTaken.reserve(ExitCounts.size());
8612 std::transform(ExitCounts.begin(), ExitCounts.end(),
8613 std::back_inserter(ExitNotTaken),
8614 [&](const EdgeExitInfo &EEI) {
8615 BasicBlock *ExitBB = EEI.first;
8616 const ExitLimit &EL = EEI.second;
8617 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
8618 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
8619 EL.Predicates);
8621 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
8622 isa<SCEVConstant>(ConstantMax)) &&
8623 "No point in having a non-constant max backedge taken count!");
8626 /// Compute the number of times the backedge of the specified loop will execute.
8627 ScalarEvolution::BackedgeTakenInfo
8628 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
8629 bool AllowPredicates) {
8630 SmallVector<BasicBlock *, 8> ExitingBlocks;
8631 L->getExitingBlocks(ExitingBlocks);
8633 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8635 SmallVector<EdgeExitInfo, 4> ExitCounts;
8636 bool CouldComputeBECount = true;
8637 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
8638 const SCEV *MustExitMaxBECount = nullptr;
8639 const SCEV *MayExitMaxBECount = nullptr;
8640 bool MustExitMaxOrZero = false;
8642 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
8643 // and compute maxBECount.
8644 // Do a union of all the predicates here.
8645 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
8646 BasicBlock *ExitBB = ExitingBlocks[i];
8648 // We canonicalize untaken exits to br (constant), ignore them so that
8649 // proving an exit untaken doesn't negatively impact our ability to reason
8650 // about the loop as whole.
8651 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
8652 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
8653 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8654 if (ExitIfTrue == CI->isZero())
8655 continue;
8658 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
8660 assert((AllowPredicates || EL.Predicates.empty()) &&
8661 "Predicated exit limit when predicates are not allowed!");
8663 // 1. For each exit that can be computed, add an entry to ExitCounts.
8664 // CouldComputeBECount is true only if all exits can be computed.
8665 if (EL.ExactNotTaken != getCouldNotCompute())
8666 ++NumExitCountsComputed;
8667 else
8668 // We couldn't compute an exact value for this exit, so
8669 // we won't be able to compute an exact value for the loop.
8670 CouldComputeBECount = false;
8671 // Remember exit count if either exact or symbolic is known. Because
8672 // Exact always implies symbolic, only check symbolic.
8673 if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
8674 ExitCounts.emplace_back(ExitBB, EL);
8675 else {
8676 assert(EL.ExactNotTaken == getCouldNotCompute() &&
8677 "Exact is known but symbolic isn't?");
8678 ++NumExitCountsNotComputed;
8681 // 2. Derive the loop's MaxBECount from each exit's max number of
8682 // non-exiting iterations. Partition the loop exits into two kinds:
8683 // LoopMustExits and LoopMayExits.
8685 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
8686 // is a LoopMayExit. If any computable LoopMustExit is found, then
8687 // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
8688 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
8689 // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
8690 // any
8691 // computable EL.ConstantMaxNotTaken.
8692 if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
8693 DT.dominates(ExitBB, Latch)) {
8694 if (!MustExitMaxBECount) {
8695 MustExitMaxBECount = EL.ConstantMaxNotTaken;
8696 MustExitMaxOrZero = EL.MaxOrZero;
8697 } else {
8698 MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
8699 EL.ConstantMaxNotTaken);
8701 } else if (MayExitMaxBECount != getCouldNotCompute()) {
8702 if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
8703 MayExitMaxBECount = EL.ConstantMaxNotTaken;
8704 else {
8705 MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
8706 EL.ConstantMaxNotTaken);
8710 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
8711 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
8712 // The loop backedge will be taken the maximum or zero times if there's
8713 // a single exit that must be taken the maximum or zero times.
8714 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
8716 // Remember which SCEVs are used in exit limits for invalidation purposes.
8717 // We only care about non-constant SCEVs here, so we can ignore
8718 // EL.ConstantMaxNotTaken
8719 // and MaxBECount, which must be SCEVConstant.
8720 for (const auto &Pair : ExitCounts) {
8721 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
8722 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
8723 if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
8724 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
8725 {L, AllowPredicates});
8727 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
8728 MaxBECount, MaxOrZero);
8731 ScalarEvolution::ExitLimit
8732 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
8733 bool AllowPredicates) {
8734 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
8735 // If our exiting block does not dominate the latch, then its connection with
8736 // loop's exit limit may be far from trivial.
8737 const BasicBlock *Latch = L->getLoopLatch();
8738 if (!Latch || !DT.dominates(ExitingBlock, Latch))
8739 return getCouldNotCompute();
8741 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
8742 Instruction *Term = ExitingBlock->getTerminator();
8743 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
8744 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
8745 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8746 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
8747 "It should have one successor in loop and one exit block!");
8748 // Proceed to the next level to examine the exit condition expression.
8749 return computeExitLimitFromCond(L, BI->getCondition(), ExitIfTrue,
8750 /*ControlsOnlyExit=*/IsOnlyExit,
8751 AllowPredicates);
8754 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
8755 // For switch, make sure that there is a single exit from the loop.
8756 BasicBlock *Exit = nullptr;
8757 for (auto *SBB : successors(ExitingBlock))
8758 if (!L->contains(SBB)) {
8759 if (Exit) // Multiple exit successors.
8760 return getCouldNotCompute();
8761 Exit = SBB;
8763 assert(Exit && "Exiting block must have at least one exit");
8764 return computeExitLimitFromSingleExitSwitch(
8765 L, SI, Exit,
8766 /*ControlsOnlyExit=*/IsOnlyExit);
8769 return getCouldNotCompute();
8772 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
8773 const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
8774 bool AllowPredicates) {
8775 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
8776 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
8777 ControlsOnlyExit, AllowPredicates);
8780 std::optional<ScalarEvolution::ExitLimit>
8781 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
8782 bool ExitIfTrue, bool ControlsOnlyExit,
8783 bool AllowPredicates) {
8784 (void)this->L;
8785 (void)this->ExitIfTrue;
8786 (void)this->AllowPredicates;
8788 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8789 this->AllowPredicates == AllowPredicates &&
8790 "Variance in assumed invariant key components!");
8791 auto Itr = TripCountMap.find({ExitCond, ControlsOnlyExit});
8792 if (Itr == TripCountMap.end())
8793 return std::nullopt;
8794 return Itr->second;
8797 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
8798 bool ExitIfTrue,
8799 bool ControlsOnlyExit,
8800 bool AllowPredicates,
8801 const ExitLimit &EL) {
8802 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8803 this->AllowPredicates == AllowPredicates &&
8804 "Variance in assumed invariant key components!");
8806 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsOnlyExit}, EL});
8807 assert(InsertResult.second && "Expected successful insertion!");
8808 (void)InsertResult;
8809 (void)ExitIfTrue;
8812 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
8813 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8814 bool ControlsOnlyExit, bool AllowPredicates) {
8816 if (auto MaybeEL = Cache.find(L, ExitCond, ExitIfTrue, ControlsOnlyExit,
8817 AllowPredicates))
8818 return *MaybeEL;
8820 ExitLimit EL = computeExitLimitFromCondImpl(
8821 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates);
8822 Cache.insert(L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates, EL);
8823 return EL;
8826 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
8827 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8828 bool ControlsOnlyExit, bool AllowPredicates) {
8829 // Handle BinOp conditions (And, Or).
8830 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
8831 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates))
8832 return *LimitFromBinOp;
8834 // With an icmp, it may be feasible to compute an exact backedge-taken count.
8835 // Proceed to the next level to examine the icmp.
8836 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
8837 ExitLimit EL =
8838 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsOnlyExit);
8839 if (EL.hasFullInfo() || !AllowPredicates)
8840 return EL;
8842 // Try again, but use SCEV predicates this time.
8843 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue,
8844 ControlsOnlyExit,
8845 /*AllowPredicates=*/true);
8848 // Check for a constant condition. These are normally stripped out by
8849 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
8850 // preserve the CFG and is temporarily leaving constant conditions
8851 // in place.
8852 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
8853 if (ExitIfTrue == !CI->getZExtValue())
8854 // The backedge is always taken.
8855 return getCouldNotCompute();
8856 // The backedge is never taken.
8857 return getZero(CI->getType());
8860 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
8861 // with a constant step, we can form an equivalent icmp predicate and figure
8862 // out how many iterations will be taken before we exit.
8863 const WithOverflowInst *WO;
8864 const APInt *C;
8865 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
8866 match(WO->getRHS(), m_APInt(C))) {
8867 ConstantRange NWR =
8868 ConstantRange::makeExactNoWrapRegion(WO->getBinaryOp(), *C,
8869 WO->getNoWrapKind());
8870 CmpInst::Predicate Pred;
8871 APInt NewRHSC, Offset;
8872 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
8873 if (!ExitIfTrue)
8874 Pred = ICmpInst::getInversePredicate(Pred);
8875 auto *LHS = getSCEV(WO->getLHS());
8876 if (Offset != 0)
8877 LHS = getAddExpr(LHS, getConstant(Offset));
8878 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
8879 ControlsOnlyExit, AllowPredicates);
8880 if (EL.hasAnyInfo())
8881 return EL;
8884 // If it's not an integer or pointer comparison then compute it the hard way.
8885 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
8888 std::optional<ScalarEvolution::ExitLimit>
8889 ScalarEvolution::computeExitLimitFromCondFromBinOp(
8890 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8891 bool ControlsOnlyExit, bool AllowPredicates) {
8892 // Check if the controlling expression for this loop is an And or Or.
8893 Value *Op0, *Op1;
8894 bool IsAnd = false;
8895 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
8896 IsAnd = true;
8897 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
8898 IsAnd = false;
8899 else
8900 return std::nullopt;
8902 // EitherMayExit is true in these two cases:
8903 // br (and Op0 Op1), loop, exit
8904 // br (or Op0 Op1), exit, loop
8905 bool EitherMayExit = IsAnd ^ ExitIfTrue;
8906 ExitLimit EL0 = computeExitLimitFromCondCached(
8907 Cache, L, Op0, ExitIfTrue, ControlsOnlyExit && !EitherMayExit,
8908 AllowPredicates);
8909 ExitLimit EL1 = computeExitLimitFromCondCached(
8910 Cache, L, Op1, ExitIfTrue, ControlsOnlyExit && !EitherMayExit,
8911 AllowPredicates);
8913 // Be robust against unsimplified IR for the form "op i1 X, NeutralElement"
8914 const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd);
8915 if (isa<ConstantInt>(Op1))
8916 return Op1 == NeutralElement ? EL0 : EL1;
8917 if (isa<ConstantInt>(Op0))
8918 return Op0 == NeutralElement ? EL1 : EL0;
8920 const SCEV *BECount = getCouldNotCompute();
8921 const SCEV *ConstantMaxBECount = getCouldNotCompute();
8922 const SCEV *SymbolicMaxBECount = getCouldNotCompute();
8923 if (EitherMayExit) {
8924 bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
8925 // Both conditions must be same for the loop to continue executing.
8926 // Choose the less conservative count.
8927 if (EL0.ExactNotTaken != getCouldNotCompute() &&
8928 EL1.ExactNotTaken != getCouldNotCompute()) {
8929 BECount = getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken,
8930 UseSequentialUMin);
8932 if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
8933 ConstantMaxBECount = EL1.ConstantMaxNotTaken;
8934 else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
8935 ConstantMaxBECount = EL0.ConstantMaxNotTaken;
8936 else
8937 ConstantMaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
8938 EL1.ConstantMaxNotTaken);
8939 if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
8940 SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
8941 else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
8942 SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
8943 else
8944 SymbolicMaxBECount = getUMinFromMismatchedTypes(
8945 EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
8946 } else {
8947 // Both conditions must be same at the same time for the loop to exit.
8948 // For now, be conservative.
8949 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
8950 BECount = EL0.ExactNotTaken;
8953 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
8954 // to be more aggressive when computing BECount than when computing
8955 // ConstantMaxBECount. In these cases it is possible for EL0.ExactNotTaken
8956 // and
8957 // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
8958 // EL1.ConstantMaxNotTaken to not.
8959 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
8960 !isa<SCEVCouldNotCompute>(BECount))
8961 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
8962 if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
8963 SymbolicMaxBECount =
8964 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
8965 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
8966 { &EL0.Predicates, &EL1.Predicates });
8969 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
8970 const Loop *L, ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
8971 bool AllowPredicates) {
8972 // If the condition was exit on true, convert the condition to exit on false
8973 ICmpInst::Predicate Pred;
8974 if (!ExitIfTrue)
8975 Pred = ExitCond->getPredicate();
8976 else
8977 Pred = ExitCond->getInversePredicate();
8978 const ICmpInst::Predicate OriginalPred = Pred;
8980 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
8981 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
8983 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsOnlyExit,
8984 AllowPredicates);
8985 if (EL.hasAnyInfo())
8986 return EL;
8988 auto *ExhaustiveCount =
8989 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
8991 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
8992 return ExhaustiveCount;
8994 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
8995 ExitCond->getOperand(1), L, OriginalPred);
8997 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
8998 const Loop *L, ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8999 bool ControlsOnlyExit, bool AllowPredicates) {
9001 // Try to evaluate any dependencies out of the loop.
9002 LHS = getSCEVAtScope(LHS, L);
9003 RHS = getSCEVAtScope(RHS, L);
9005 // At this point, we would like to compute how many iterations of the
9006 // loop the predicate will return true for these inputs.
9007 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
9008 // If there is a loop-invariant, force it into the RHS.
9009 std::swap(LHS, RHS);
9010 Pred = ICmpInst::getSwappedPredicate(Pred);
9013 bool ControllingFiniteLoop = ControlsOnlyExit && loopHasNoAbnormalExits(L) &&
9014 loopIsFiniteByAssumption(L);
9015 // Simplify the operands before analyzing them.
9016 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0);
9018 // If we have a comparison of a chrec against a constant, try to use value
9019 // ranges to answer this query.
9020 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
9021 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
9022 if (AddRec->getLoop() == L) {
9023 // Form the constant range.
9024 ConstantRange CompRange =
9025 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
9027 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
9028 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
9031 // If this loop must exit based on this condition (or execute undefined
9032 // behaviour), and we can prove the test sequence produced must repeat
9033 // the same values on self-wrap of the IV, then we can infer that IV
9034 // doesn't self wrap because if it did, we'd have an infinite (undefined)
9035 // loop.
9036 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
9037 // TODO: We can peel off any functions which are invertible *in L*. Loop
9038 // invariant terms are effectively constants for our purposes here.
9039 auto *InnerLHS = LHS;
9040 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
9041 InnerLHS = ZExt->getOperand();
9042 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS)) {
9043 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
9044 if (!AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
9045 StrideC && StrideC->getAPInt().isPowerOf2()) {
9046 auto Flags = AR->getNoWrapFlags();
9047 Flags = setFlags(Flags, SCEV::FlagNW);
9048 SmallVector<const SCEV*> Operands{AR->operands()};
9049 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
9050 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9055 switch (Pred) {
9056 case ICmpInst::ICMP_NE: { // while (X != Y)
9057 // Convert to: while (X-Y != 0)
9058 if (LHS->getType()->isPointerTy()) {
9059 LHS = getLosslessPtrToIntExpr(LHS);
9060 if (isa<SCEVCouldNotCompute>(LHS))
9061 return LHS;
9063 if (RHS->getType()->isPointerTy()) {
9064 RHS = getLosslessPtrToIntExpr(RHS);
9065 if (isa<SCEVCouldNotCompute>(RHS))
9066 return RHS;
9068 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit,
9069 AllowPredicates);
9070 if (EL.hasAnyInfo())
9071 return EL;
9072 break;
9074 case ICmpInst::ICMP_EQ: { // while (X == Y)
9075 // Convert to: while (X-Y == 0)
9076 if (LHS->getType()->isPointerTy()) {
9077 LHS = getLosslessPtrToIntExpr(LHS);
9078 if (isa<SCEVCouldNotCompute>(LHS))
9079 return LHS;
9081 if (RHS->getType()->isPointerTy()) {
9082 RHS = getLosslessPtrToIntExpr(RHS);
9083 if (isa<SCEVCouldNotCompute>(RHS))
9084 return RHS;
9086 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
9087 if (EL.hasAnyInfo()) return EL;
9088 break;
9090 case ICmpInst::ICMP_SLE:
9091 case ICmpInst::ICMP_ULE:
9092 // Since the loop is finite, an invariant RHS cannot include the boundary
9093 // value, otherwise it would loop forever.
9094 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9095 !isLoopInvariant(RHS, L))
9096 break;
9097 RHS = getAddExpr(getOne(RHS->getType()), RHS);
9098 [[fallthrough]];
9099 case ICmpInst::ICMP_SLT:
9100 case ICmpInst::ICMP_ULT: { // while (X < Y)
9101 bool IsSigned = ICmpInst::isSigned(Pred);
9102 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9103 AllowPredicates);
9104 if (EL.hasAnyInfo())
9105 return EL;
9106 break;
9108 case ICmpInst::ICMP_SGE:
9109 case ICmpInst::ICMP_UGE:
9110 // Since the loop is finite, an invariant RHS cannot include the boundary
9111 // value, otherwise it would loop forever.
9112 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9113 !isLoopInvariant(RHS, L))
9114 break;
9115 RHS = getAddExpr(getMinusOne(RHS->getType()), RHS);
9116 [[fallthrough]];
9117 case ICmpInst::ICMP_SGT:
9118 case ICmpInst::ICMP_UGT: { // while (X > Y)
9119 bool IsSigned = ICmpInst::isSigned(Pred);
9120 ExitLimit EL = howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9121 AllowPredicates);
9122 if (EL.hasAnyInfo())
9123 return EL;
9124 break;
9126 default:
9127 break;
9130 return getCouldNotCompute();
9133 ScalarEvolution::ExitLimit
9134 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
9135 SwitchInst *Switch,
9136 BasicBlock *ExitingBlock,
9137 bool ControlsOnlyExit) {
9138 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
9140 // Give up if the exit is the default dest of a switch.
9141 if (Switch->getDefaultDest() == ExitingBlock)
9142 return getCouldNotCompute();
9144 assert(L->contains(Switch->getDefaultDest()) &&
9145 "Default case must not exit the loop!");
9146 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
9147 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
9149 // while (X != Y) --> while (X-Y != 0)
9150 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit);
9151 if (EL.hasAnyInfo())
9152 return EL;
9154 return getCouldNotCompute();
9157 static ConstantInt *
9158 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
9159 ScalarEvolution &SE) {
9160 const SCEV *InVal = SE.getConstant(C);
9161 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
9162 assert(isa<SCEVConstant>(Val) &&
9163 "Evaluation of SCEV at constant didn't fold correctly?");
9164 return cast<SCEVConstant>(Val)->getValue();
9167 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
9168 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
9169 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
9170 if (!RHS)
9171 return getCouldNotCompute();
9173 const BasicBlock *Latch = L->getLoopLatch();
9174 if (!Latch)
9175 return getCouldNotCompute();
9177 const BasicBlock *Predecessor = L->getLoopPredecessor();
9178 if (!Predecessor)
9179 return getCouldNotCompute();
9181 // Return true if V is of the form "LHS `shift_op` <positive constant>".
9182 // Return LHS in OutLHS and shift_opt in OutOpCode.
9183 auto MatchPositiveShift =
9184 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
9186 using namespace PatternMatch;
9188 ConstantInt *ShiftAmt;
9189 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9190 OutOpCode = Instruction::LShr;
9191 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9192 OutOpCode = Instruction::AShr;
9193 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9194 OutOpCode = Instruction::Shl;
9195 else
9196 return false;
9198 return ShiftAmt->getValue().isStrictlyPositive();
9201 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
9203 // loop:
9204 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
9205 // %iv.shifted = lshr i32 %iv, <positive constant>
9207 // Return true on a successful match. Return the corresponding PHI node (%iv
9208 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
9209 auto MatchShiftRecurrence =
9210 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
9211 std::optional<Instruction::BinaryOps> PostShiftOpCode;
9214 Instruction::BinaryOps OpC;
9215 Value *V;
9217 // If we encounter a shift instruction, "peel off" the shift operation,
9218 // and remember that we did so. Later when we inspect %iv's backedge
9219 // value, we will make sure that the backedge value uses the same
9220 // operation.
9222 // Note: the peeled shift operation does not have to be the same
9223 // instruction as the one feeding into the PHI's backedge value. We only
9224 // really care about it being the same *kind* of shift instruction --
9225 // that's all that is required for our later inferences to hold.
9226 if (MatchPositiveShift(LHS, V, OpC)) {
9227 PostShiftOpCode = OpC;
9228 LHS = V;
9232 PNOut = dyn_cast<PHINode>(LHS);
9233 if (!PNOut || PNOut->getParent() != L->getHeader())
9234 return false;
9236 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
9237 Value *OpLHS;
9239 return
9240 // The backedge value for the PHI node must be a shift by a positive
9241 // amount
9242 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
9244 // of the PHI node itself
9245 OpLHS == PNOut &&
9247 // and the kind of shift should be match the kind of shift we peeled
9248 // off, if any.
9249 (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9252 PHINode *PN;
9253 Instruction::BinaryOps OpCode;
9254 if (!MatchShiftRecurrence(LHS, PN, OpCode))
9255 return getCouldNotCompute();
9257 const DataLayout &DL = getDataLayout();
9259 // The key rationale for this optimization is that for some kinds of shift
9260 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
9261 // within a finite number of iterations. If the condition guarding the
9262 // backedge (in the sense that the backedge is taken if the condition is true)
9263 // is false for the value the shift recurrence stabilizes to, then we know
9264 // that the backedge is taken only a finite number of times.
9266 ConstantInt *StableValue = nullptr;
9267 switch (OpCode) {
9268 default:
9269 llvm_unreachable("Impossible case!");
9271 case Instruction::AShr: {
9272 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
9273 // bitwidth(K) iterations.
9274 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
9275 KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC,
9276 Predecessor->getTerminator(), &DT);
9277 auto *Ty = cast<IntegerType>(RHS->getType());
9278 if (Known.isNonNegative())
9279 StableValue = ConstantInt::get(Ty, 0);
9280 else if (Known.isNegative())
9281 StableValue = ConstantInt::get(Ty, -1, true);
9282 else
9283 return getCouldNotCompute();
9285 break;
9287 case Instruction::LShr:
9288 case Instruction::Shl:
9289 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
9290 // stabilize to 0 in at most bitwidth(K) iterations.
9291 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
9292 break;
9295 auto *Result =
9296 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
9297 assert(Result->getType()->isIntegerTy(1) &&
9298 "Otherwise cannot be an operand to a branch instruction");
9300 if (Result->isZeroValue()) {
9301 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9302 const SCEV *UpperBound =
9303 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
9304 return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
9307 return getCouldNotCompute();
9310 /// Return true if we can constant fold an instruction of the specified type,
9311 /// assuming that all operands were constants.
9312 static bool CanConstantFold(const Instruction *I) {
9313 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
9314 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
9315 isa<LoadInst>(I) || isa<ExtractValueInst>(I))
9316 return true;
9318 if (const CallInst *CI = dyn_cast<CallInst>(I))
9319 if (const Function *F = CI->getCalledFunction())
9320 return canConstantFoldCallTo(CI, F);
9321 return false;
9324 /// Determine whether this instruction can constant evolve within this loop
9325 /// assuming its operands can all constant evolve.
9326 static bool canConstantEvolve(Instruction *I, const Loop *L) {
9327 // An instruction outside of the loop can't be derived from a loop PHI.
9328 if (!L->contains(I)) return false;
9330 if (isa<PHINode>(I)) {
9331 // We don't currently keep track of the control flow needed to evaluate
9332 // PHIs, so we cannot handle PHIs inside of loops.
9333 return L->getHeader() == I->getParent();
9336 // If we won't be able to constant fold this expression even if the operands
9337 // are constants, bail early.
9338 return CanConstantFold(I);
9341 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
9342 /// recursing through each instruction operand until reaching a loop header phi.
9343 static PHINode *
9344 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
9345 DenseMap<Instruction *, PHINode *> &PHIMap,
9346 unsigned Depth) {
9347 if (Depth > MaxConstantEvolvingDepth)
9348 return nullptr;
9350 // Otherwise, we can evaluate this instruction if all of its operands are
9351 // constant or derived from a PHI node themselves.
9352 PHINode *PHI = nullptr;
9353 for (Value *Op : UseInst->operands()) {
9354 if (isa<Constant>(Op)) continue;
9356 Instruction *OpInst = dyn_cast<Instruction>(Op);
9357 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
9359 PHINode *P = dyn_cast<PHINode>(OpInst);
9360 if (!P)
9361 // If this operand is already visited, reuse the prior result.
9362 // We may have P != PHI if this is the deepest point at which the
9363 // inconsistent paths meet.
9364 P = PHIMap.lookup(OpInst);
9365 if (!P) {
9366 // Recurse and memoize the results, whether a phi is found or not.
9367 // This recursive call invalidates pointers into PHIMap.
9368 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
9369 PHIMap[OpInst] = P;
9371 if (!P)
9372 return nullptr; // Not evolving from PHI
9373 if (PHI && PHI != P)
9374 return nullptr; // Evolving from multiple different PHIs.
9375 PHI = P;
9377 // This is a expression evolving from a constant PHI!
9378 return PHI;
9381 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9382 /// in the loop that V is derived from. We allow arbitrary operations along the
9383 /// way, but the operands of an operation must either be constants or a value
9384 /// derived from a constant PHI. If this expression does not fit with these
9385 /// constraints, return null.
9386 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
9387 Instruction *I = dyn_cast<Instruction>(V);
9388 if (!I || !canConstantEvolve(I, L)) return nullptr;
9390 if (PHINode *PN = dyn_cast<PHINode>(I))
9391 return PN;
9393 // Record non-constant instructions contained by the loop.
9394 DenseMap<Instruction *, PHINode *> PHIMap;
9395 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
9398 /// EvaluateExpression - Given an expression that passes the
9399 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9400 /// in the loop has the value PHIVal. If we can't fold this expression for some
9401 /// reason, return null.
9402 static Constant *EvaluateExpression(Value *V, const Loop *L,
9403 DenseMap<Instruction *, Constant *> &Vals,
9404 const DataLayout &DL,
9405 const TargetLibraryInfo *TLI) {
9406 // Convenient constant check, but redundant for recursive calls.
9407 if (Constant *C = dyn_cast<Constant>(V)) return C;
9408 Instruction *I = dyn_cast<Instruction>(V);
9409 if (!I) return nullptr;
9411 if (Constant *C = Vals.lookup(I)) return C;
9413 // An instruction inside the loop depends on a value outside the loop that we
9414 // weren't given a mapping for, or a value such as a call inside the loop.
9415 if (!canConstantEvolve(I, L)) return nullptr;
9417 // An unmapped PHI can be due to a branch or another loop inside this loop,
9418 // or due to this not being the initial iteration through a loop where we
9419 // couldn't compute the evolution of this particular PHI last time.
9420 if (isa<PHINode>(I)) return nullptr;
9422 std::vector<Constant*> Operands(I->getNumOperands());
9424 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9425 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9426 if (!Operand) {
9427 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9428 if (!Operands[i]) return nullptr;
9429 continue;
9431 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9432 Vals[Operand] = C;
9433 if (!C) return nullptr;
9434 Operands[i] = C;
9437 return ConstantFoldInstOperands(I, Operands, DL, TLI);
9441 // If every incoming value to PN except the one for BB is a specific Constant,
9442 // return that, else return nullptr.
9443 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
9444 Constant *IncomingVal = nullptr;
9446 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9447 if (PN->getIncomingBlock(i) == BB)
9448 continue;
9450 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
9451 if (!CurrentVal)
9452 return nullptr;
9454 if (IncomingVal != CurrentVal) {
9455 if (IncomingVal)
9456 return nullptr;
9457 IncomingVal = CurrentVal;
9461 return IncomingVal;
9464 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9465 /// in the header of its containing loop, we know the loop executes a
9466 /// constant number of times, and the PHI node is just a recurrence
9467 /// involving constants, fold it.
9468 Constant *
9469 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9470 const APInt &BEs,
9471 const Loop *L) {
9472 auto I = ConstantEvolutionLoopExitValue.find(PN);
9473 if (I != ConstantEvolutionLoopExitValue.end())
9474 return I->second;
9476 if (BEs.ugt(MaxBruteForceIterations))
9477 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
9479 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
9481 DenseMap<Instruction *, Constant *> CurrentIterVals;
9482 BasicBlock *Header = L->getHeader();
9483 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9485 BasicBlock *Latch = L->getLoopLatch();
9486 if (!Latch)
9487 return nullptr;
9489 for (PHINode &PHI : Header->phis()) {
9490 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9491 CurrentIterVals[&PHI] = StartCST;
9493 if (!CurrentIterVals.count(PN))
9494 return RetVal = nullptr;
9496 Value *BEValue = PN->getIncomingValueForBlock(Latch);
9498 // Execute the loop symbolically to determine the exit value.
9499 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
9500 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
9502 unsigned NumIterations = BEs.getZExtValue(); // must be in range
9503 unsigned IterationNum = 0;
9504 const DataLayout &DL = getDataLayout();
9505 for (; ; ++IterationNum) {
9506 if (IterationNum == NumIterations)
9507 return RetVal = CurrentIterVals[PN]; // Got exit value!
9509 // Compute the value of the PHIs for the next iteration.
9510 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9511 DenseMap<Instruction *, Constant *> NextIterVals;
9512 Constant *NextPHI =
9513 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9514 if (!NextPHI)
9515 return nullptr; // Couldn't evaluate!
9516 NextIterVals[PN] = NextPHI;
9518 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9520 // Also evaluate the other PHI nodes. However, we don't get to stop if we
9521 // cease to be able to evaluate one of them or if they stop evolving,
9522 // because that doesn't necessarily prevent us from computing PN.
9523 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
9524 for (const auto &I : CurrentIterVals) {
9525 PHINode *PHI = dyn_cast<PHINode>(I.first);
9526 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
9527 PHIsToCompute.emplace_back(PHI, I.second);
9529 // We use two distinct loops because EvaluateExpression may invalidate any
9530 // iterators into CurrentIterVals.
9531 for (const auto &I : PHIsToCompute) {
9532 PHINode *PHI = I.first;
9533 Constant *&NextPHI = NextIterVals[PHI];
9534 if (!NextPHI) { // Not already computed.
9535 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9536 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9538 if (NextPHI != I.second)
9539 StoppedEvolving = false;
9542 // If all entries in CurrentIterVals == NextIterVals then we can stop
9543 // iterating, the loop can't continue to change.
9544 if (StoppedEvolving)
9545 return RetVal = CurrentIterVals[PN];
9547 CurrentIterVals.swap(NextIterVals);
9551 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
9552 Value *Cond,
9553 bool ExitWhen) {
9554 PHINode *PN = getConstantEvolvingPHI(Cond, L);
9555 if (!PN) return getCouldNotCompute();
9557 // If the loop is canonicalized, the PHI will have exactly two entries.
9558 // That's the only form we support here.
9559 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
9561 DenseMap<Instruction *, Constant *> CurrentIterVals;
9562 BasicBlock *Header = L->getHeader();
9563 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9565 BasicBlock *Latch = L->getLoopLatch();
9566 assert(Latch && "Should follow from NumIncomingValues == 2!");
9568 for (PHINode &PHI : Header->phis()) {
9569 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9570 CurrentIterVals[&PHI] = StartCST;
9572 if (!CurrentIterVals.count(PN))
9573 return getCouldNotCompute();
9575 // Okay, we find a PHI node that defines the trip count of this loop. Execute
9576 // the loop symbolically to determine when the condition gets a value of
9577 // "ExitWhen".
9578 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
9579 const DataLayout &DL = getDataLayout();
9580 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
9581 auto *CondVal = dyn_cast_or_null<ConstantInt>(
9582 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
9584 // Couldn't symbolically evaluate.
9585 if (!CondVal) return getCouldNotCompute();
9587 if (CondVal->getValue() == uint64_t(ExitWhen)) {
9588 ++NumBruteForceTripCountsComputed;
9589 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
9592 // Update all the PHI nodes for the next iteration.
9593 DenseMap<Instruction *, Constant *> NextIterVals;
9595 // Create a list of which PHIs we need to compute. We want to do this before
9596 // calling EvaluateExpression on them because that may invalidate iterators
9597 // into CurrentIterVals.
9598 SmallVector<PHINode *, 8> PHIsToCompute;
9599 for (const auto &I : CurrentIterVals) {
9600 PHINode *PHI = dyn_cast<PHINode>(I.first);
9601 if (!PHI || PHI->getParent() != Header) continue;
9602 PHIsToCompute.push_back(PHI);
9604 for (PHINode *PHI : PHIsToCompute) {
9605 Constant *&NextPHI = NextIterVals[PHI];
9606 if (NextPHI) continue; // Already computed!
9608 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9609 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9611 CurrentIterVals.swap(NextIterVals);
9614 // Too many iterations were needed to evaluate.
9615 return getCouldNotCompute();
9618 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
9619 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
9620 ValuesAtScopes[V];
9621 // Check to see if we've folded this expression at this loop before.
9622 for (auto &LS : Values)
9623 if (LS.first == L)
9624 return LS.second ? LS.second : V;
9626 Values.emplace_back(L, nullptr);
9628 // Otherwise compute it.
9629 const SCEV *C = computeSCEVAtScope(V, L);
9630 for (auto &LS : reverse(ValuesAtScopes[V]))
9631 if (LS.first == L) {
9632 LS.second = C;
9633 if (!isa<SCEVConstant>(C))
9634 ValuesAtScopesUsers[C].push_back({L, V});
9635 break;
9637 return C;
9640 /// This builds up a Constant using the ConstantExpr interface. That way, we
9641 /// will return Constants for objects which aren't represented by a
9642 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
9643 /// Returns NULL if the SCEV isn't representable as a Constant.
9644 static Constant *BuildConstantFromSCEV(const SCEV *V) {
9645 switch (V->getSCEVType()) {
9646 case scCouldNotCompute:
9647 case scAddRecExpr:
9648 case scVScale:
9649 return nullptr;
9650 case scConstant:
9651 return cast<SCEVConstant>(V)->getValue();
9652 case scUnknown:
9653 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
9654 case scPtrToInt: {
9655 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
9656 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
9657 return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
9659 return nullptr;
9661 case scTruncate: {
9662 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
9663 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
9664 return ConstantExpr::getTrunc(CastOp, ST->getType());
9665 return nullptr;
9667 case scAddExpr: {
9668 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
9669 Constant *C = nullptr;
9670 for (const SCEV *Op : SA->operands()) {
9671 Constant *OpC = BuildConstantFromSCEV(Op);
9672 if (!OpC)
9673 return nullptr;
9674 if (!C) {
9675 C = OpC;
9676 continue;
9678 assert(!C->getType()->isPointerTy() &&
9679 "Can only have one pointer, and it must be last");
9680 if (OpC->getType()->isPointerTy()) {
9681 // The offsets have been converted to bytes. We can add bytes using
9682 // an i8 GEP.
9683 C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()),
9684 OpC, C);
9685 } else {
9686 C = ConstantExpr::getAdd(C, OpC);
9689 return C;
9691 case scMulExpr: {
9692 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
9693 Constant *C = nullptr;
9694 for (const SCEV *Op : SM->operands()) {
9695 assert(!Op->getType()->isPointerTy() && "Can't multiply pointers");
9696 Constant *OpC = BuildConstantFromSCEV(Op);
9697 if (!OpC)
9698 return nullptr;
9699 C = C ? ConstantExpr::getMul(C, OpC) : OpC;
9701 return C;
9703 case scSignExtend:
9704 case scZeroExtend:
9705 case scUDivExpr:
9706 case scSMaxExpr:
9707 case scUMaxExpr:
9708 case scSMinExpr:
9709 case scUMinExpr:
9710 case scSequentialUMinExpr:
9711 return nullptr;
9713 llvm_unreachable("Unknown SCEV kind!");
9716 const SCEV *
9717 ScalarEvolution::getWithOperands(const SCEV *S,
9718 SmallVectorImpl<const SCEV *> &NewOps) {
9719 switch (S->getSCEVType()) {
9720 case scTruncate:
9721 case scZeroExtend:
9722 case scSignExtend:
9723 case scPtrToInt:
9724 return getCastExpr(S->getSCEVType(), NewOps[0], S->getType());
9725 case scAddRecExpr: {
9726 auto *AddRec = cast<SCEVAddRecExpr>(S);
9727 return getAddRecExpr(NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags());
9729 case scAddExpr:
9730 return getAddExpr(NewOps, cast<SCEVAddExpr>(S)->getNoWrapFlags());
9731 case scMulExpr:
9732 return getMulExpr(NewOps, cast<SCEVMulExpr>(S)->getNoWrapFlags());
9733 case scUDivExpr:
9734 return getUDivExpr(NewOps[0], NewOps[1]);
9735 case scUMaxExpr:
9736 case scSMaxExpr:
9737 case scUMinExpr:
9738 case scSMinExpr:
9739 return getMinMaxExpr(S->getSCEVType(), NewOps);
9740 case scSequentialUMinExpr:
9741 return getSequentialMinMaxExpr(S->getSCEVType(), NewOps);
9742 case scConstant:
9743 case scVScale:
9744 case scUnknown:
9745 return S;
9746 case scCouldNotCompute:
9747 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
9749 llvm_unreachable("Unknown SCEV kind!");
9752 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
9753 switch (V->getSCEVType()) {
9754 case scConstant:
9755 case scVScale:
9756 return V;
9757 case scAddRecExpr: {
9758 // If this is a loop recurrence for a loop that does not contain L, then we
9759 // are dealing with the final value computed by the loop.
9760 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(V);
9761 // First, attempt to evaluate each operand.
9762 // Avoid performing the look-up in the common case where the specified
9763 // expression has no loop-variant portions.
9764 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
9765 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
9766 if (OpAtScope == AddRec->getOperand(i))
9767 continue;
9769 // Okay, at least one of these operands is loop variant but might be
9770 // foldable. Build a new instance of the folded commutative expression.
9771 SmallVector<const SCEV *, 8> NewOps;
9772 NewOps.reserve(AddRec->getNumOperands());
9773 append_range(NewOps, AddRec->operands().take_front(i));
9774 NewOps.push_back(OpAtScope);
9775 for (++i; i != e; ++i)
9776 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
9778 const SCEV *FoldedRec = getAddRecExpr(
9779 NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags(SCEV::FlagNW));
9780 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
9781 // The addrec may be folded to a nonrecurrence, for example, if the
9782 // induction variable is multiplied by zero after constant folding. Go
9783 // ahead and return the folded value.
9784 if (!AddRec)
9785 return FoldedRec;
9786 break;
9789 // If the scope is outside the addrec's loop, evaluate it by using the
9790 // loop exit value of the addrec.
9791 if (!AddRec->getLoop()->contains(L)) {
9792 // To evaluate this recurrence, we need to know how many times the AddRec
9793 // loop iterates. Compute this now.
9794 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
9795 if (BackedgeTakenCount == getCouldNotCompute())
9796 return AddRec;
9798 // Then, evaluate the AddRec.
9799 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
9802 return AddRec;
9804 case scTruncate:
9805 case scZeroExtend:
9806 case scSignExtend:
9807 case scPtrToInt:
9808 case scAddExpr:
9809 case scMulExpr:
9810 case scUDivExpr:
9811 case scUMaxExpr:
9812 case scSMaxExpr:
9813 case scUMinExpr:
9814 case scSMinExpr:
9815 case scSequentialUMinExpr: {
9816 ArrayRef<const SCEV *> Ops = V->operands();
9817 // Avoid performing the look-up in the common case where the specified
9818 // expression has no loop-variant portions.
9819 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
9820 const SCEV *OpAtScope = getSCEVAtScope(Ops[i], L);
9821 if (OpAtScope != Ops[i]) {
9822 // Okay, at least one of these operands is loop variant but might be
9823 // foldable. Build a new instance of the folded commutative expression.
9824 SmallVector<const SCEV *, 8> NewOps;
9825 NewOps.reserve(Ops.size());
9826 append_range(NewOps, Ops.take_front(i));
9827 NewOps.push_back(OpAtScope);
9829 for (++i; i != e; ++i) {
9830 OpAtScope = getSCEVAtScope(Ops[i], L);
9831 NewOps.push_back(OpAtScope);
9834 return getWithOperands(V, NewOps);
9837 // If we got here, all operands are loop invariant.
9838 return V;
9840 case scUnknown: {
9841 // If this instruction is evolved from a constant-evolving PHI, compute the
9842 // exit value from the loop without using SCEVs.
9843 const SCEVUnknown *SU = cast<SCEVUnknown>(V);
9844 Instruction *I = dyn_cast<Instruction>(SU->getValue());
9845 if (!I)
9846 return V; // This is some other type of SCEVUnknown, just return it.
9848 if (PHINode *PN = dyn_cast<PHINode>(I)) {
9849 const Loop *CurrLoop = this->LI[I->getParent()];
9850 // Looking for loop exit value.
9851 if (CurrLoop && CurrLoop->getParentLoop() == L &&
9852 PN->getParent() == CurrLoop->getHeader()) {
9853 // Okay, there is no closed form solution for the PHI node. Check
9854 // to see if the loop that contains it has a known backedge-taken
9855 // count. If so, we may be able to force computation of the exit
9856 // value.
9857 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
9858 // This trivial case can show up in some degenerate cases where
9859 // the incoming IR has not yet been fully simplified.
9860 if (BackedgeTakenCount->isZero()) {
9861 Value *InitValue = nullptr;
9862 bool MultipleInitValues = false;
9863 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
9864 if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
9865 if (!InitValue)
9866 InitValue = PN->getIncomingValue(i);
9867 else if (InitValue != PN->getIncomingValue(i)) {
9868 MultipleInitValues = true;
9869 break;
9873 if (!MultipleInitValues && InitValue)
9874 return getSCEV(InitValue);
9876 // Do we have a loop invariant value flowing around the backedge
9877 // for a loop which must execute the backedge?
9878 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
9879 isKnownNonZero(BackedgeTakenCount) &&
9880 PN->getNumIncomingValues() == 2) {
9882 unsigned InLoopPred =
9883 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
9884 Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
9885 if (CurrLoop->isLoopInvariant(BackedgeVal))
9886 return getSCEV(BackedgeVal);
9888 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
9889 // Okay, we know how many times the containing loop executes. If
9890 // this is a constant evolving PHI node, get the final value at
9891 // the specified iteration number.
9892 Constant *RV =
9893 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
9894 if (RV)
9895 return getSCEV(RV);
9900 // Okay, this is an expression that we cannot symbolically evaluate
9901 // into a SCEV. Check to see if it's possible to symbolically evaluate
9902 // the arguments into constants, and if so, try to constant propagate the
9903 // result. This is particularly useful for computing loop exit values.
9904 if (!CanConstantFold(I))
9905 return V; // This is some other type of SCEVUnknown, just return it.
9907 SmallVector<Constant *, 4> Operands;
9908 Operands.reserve(I->getNumOperands());
9909 bool MadeImprovement = false;
9910 for (Value *Op : I->operands()) {
9911 if (Constant *C = dyn_cast<Constant>(Op)) {
9912 Operands.push_back(C);
9913 continue;
9916 // If any of the operands is non-constant and if they are
9917 // non-integer and non-pointer, don't even try to analyze them
9918 // with scev techniques.
9919 if (!isSCEVable(Op->getType()))
9920 return V;
9922 const SCEV *OrigV = getSCEV(Op);
9923 const SCEV *OpV = getSCEVAtScope(OrigV, L);
9924 MadeImprovement |= OrigV != OpV;
9926 Constant *C = BuildConstantFromSCEV(OpV);
9927 if (!C)
9928 return V;
9929 assert(C->getType() == Op->getType() && "Type mismatch");
9930 Operands.push_back(C);
9933 // Check to see if getSCEVAtScope actually made an improvement.
9934 if (!MadeImprovement)
9935 return V; // This is some other type of SCEVUnknown, just return it.
9937 Constant *C = nullptr;
9938 const DataLayout &DL = getDataLayout();
9939 C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
9940 if (!C)
9941 return V;
9942 return getSCEV(C);
9944 case scCouldNotCompute:
9945 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
9947 llvm_unreachable("Unknown SCEV type!");
9950 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
9951 return getSCEVAtScope(getSCEV(V), L);
9954 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
9955 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
9956 return stripInjectiveFunctions(ZExt->getOperand());
9957 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
9958 return stripInjectiveFunctions(SExt->getOperand());
9959 return S;
9962 /// Finds the minimum unsigned root of the following equation:
9964 /// A * X = B (mod N)
9966 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
9967 /// A and B isn't important.
9969 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
9970 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
9971 ScalarEvolution &SE) {
9972 uint32_t BW = A.getBitWidth();
9973 assert(BW == SE.getTypeSizeInBits(B->getType()));
9974 assert(A != 0 && "A must be non-zero.");
9976 // 1. D = gcd(A, N)
9978 // The gcd of A and N may have only one prime factor: 2. The number of
9979 // trailing zeros in A is its multiplicity
9980 uint32_t Mult2 = A.countr_zero();
9981 // D = 2^Mult2
9983 // 2. Check if B is divisible by D.
9985 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
9986 // is not less than multiplicity of this prime factor for D.
9987 if (SE.getMinTrailingZeros(B) < Mult2)
9988 return SE.getCouldNotCompute();
9990 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
9991 // modulo (N / D).
9993 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
9994 // (N / D) in general. The inverse itself always fits into BW bits, though,
9995 // so we immediately truncate it.
9996 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
9997 APInt Mod(BW + 1, 0);
9998 Mod.setBit(BW - Mult2); // Mod = N / D
9999 APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
10001 // 4. Compute the minimum unsigned root of the equation:
10002 // I * (B / D) mod (N / D)
10003 // To simplify the computation, we factor out the divide by D:
10004 // (I * B mod N) / D
10005 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
10006 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
10009 /// For a given quadratic addrec, generate coefficients of the corresponding
10010 /// quadratic equation, multiplied by a common value to ensure that they are
10011 /// integers.
10012 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
10013 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
10014 /// were multiplied by, and BitWidth is the bit width of the original addrec
10015 /// coefficients.
10016 /// This function returns std::nullopt if the addrec coefficients are not
10017 /// compile- time constants.
10018 static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
10019 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
10020 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
10021 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
10022 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
10023 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
10024 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
10025 << *AddRec << '\n');
10027 // We currently can only solve this if the coefficients are constants.
10028 if (!LC || !MC || !NC) {
10029 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
10030 return std::nullopt;
10033 APInt L = LC->getAPInt();
10034 APInt M = MC->getAPInt();
10035 APInt N = NC->getAPInt();
10036 assert(!N.isZero() && "This is not a quadratic addrec");
10038 unsigned BitWidth = LC->getAPInt().getBitWidth();
10039 unsigned NewWidth = BitWidth + 1;
10040 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
10041 << BitWidth << '\n');
10042 // The sign-extension (as opposed to a zero-extension) here matches the
10043 // extension used in SolveQuadraticEquationWrap (with the same motivation).
10044 N = N.sext(NewWidth);
10045 M = M.sext(NewWidth);
10046 L = L.sext(NewWidth);
10048 // The increments are M, M+N, M+2N, ..., so the accumulated values are
10049 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
10050 // L+M, L+2M+N, L+3M+3N, ...
10051 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
10053 // The equation Acc = 0 is then
10054 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
10055 // In a quadratic form it becomes:
10056 // N n^2 + (2M-N) n + 2L = 0.
10058 APInt A = N;
10059 APInt B = 2 * M - A;
10060 APInt C = 2 * L;
10061 APInt T = APInt(NewWidth, 2);
10062 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
10063 << "x + " << C << ", coeff bw: " << NewWidth
10064 << ", multiplied by " << T << '\n');
10065 return std::make_tuple(A, B, C, T, BitWidth);
10068 /// Helper function to compare optional APInts:
10069 /// (a) if X and Y both exist, return min(X, Y),
10070 /// (b) if neither X nor Y exist, return std::nullopt,
10071 /// (c) if exactly one of X and Y exists, return that value.
10072 static std::optional<APInt> MinOptional(std::optional<APInt> X,
10073 std::optional<APInt> Y) {
10074 if (X && Y) {
10075 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
10076 APInt XW = X->sext(W);
10077 APInt YW = Y->sext(W);
10078 return XW.slt(YW) ? *X : *Y;
10080 if (!X && !Y)
10081 return std::nullopt;
10082 return X ? *X : *Y;
10085 /// Helper function to truncate an optional APInt to a given BitWidth.
10086 /// When solving addrec-related equations, it is preferable to return a value
10087 /// that has the same bit width as the original addrec's coefficients. If the
10088 /// solution fits in the original bit width, truncate it (except for i1).
10089 /// Returning a value of a different bit width may inhibit some optimizations.
10091 /// In general, a solution to a quadratic equation generated from an addrec
10092 /// may require BW+1 bits, where BW is the bit width of the addrec's
10093 /// coefficients. The reason is that the coefficients of the quadratic
10094 /// equation are BW+1 bits wide (to avoid truncation when converting from
10095 /// the addrec to the equation).
10096 static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
10097 unsigned BitWidth) {
10098 if (!X)
10099 return std::nullopt;
10100 unsigned W = X->getBitWidth();
10101 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
10102 return X->trunc(BitWidth);
10103 return X;
10106 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
10107 /// iterations. The values L, M, N are assumed to be signed, and they
10108 /// should all have the same bit widths.
10109 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
10110 /// where BW is the bit width of the addrec's coefficients.
10111 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
10112 /// returned as such, otherwise the bit width of the returned value may
10113 /// be greater than BW.
10115 /// This function returns std::nullopt if
10116 /// (a) the addrec coefficients are not constant, or
10117 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
10118 /// like x^2 = 5, no integer solutions exist, in other cases an integer
10119 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
10120 static std::optional<APInt>
10121 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
10122 APInt A, B, C, M;
10123 unsigned BitWidth;
10124 auto T = GetQuadraticEquation(AddRec);
10125 if (!T)
10126 return std::nullopt;
10128 std::tie(A, B, C, M, BitWidth) = *T;
10129 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
10130 std::optional<APInt> X =
10131 APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth + 1);
10132 if (!X)
10133 return std::nullopt;
10135 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
10136 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
10137 if (!V->isZero())
10138 return std::nullopt;
10140 return TruncIfPossible(X, BitWidth);
10143 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
10144 /// iterations. The values M, N are assumed to be signed, and they
10145 /// should all have the same bit widths.
10146 /// Find the least n such that c(n) does not belong to the given range,
10147 /// while c(n-1) does.
10149 /// This function returns std::nullopt if
10150 /// (a) the addrec coefficients are not constant, or
10151 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
10152 /// bounds of the range.
10153 static std::optional<APInt>
10154 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
10155 const ConstantRange &Range, ScalarEvolution &SE) {
10156 assert(AddRec->getOperand(0)->isZero() &&
10157 "Starting value of addrec should be 0");
10158 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
10159 << Range << ", addrec " << *AddRec << '\n');
10160 // This case is handled in getNumIterationsInRange. Here we can assume that
10161 // we start in the range.
10162 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
10163 "Addrec's initial value should be in range");
10165 APInt A, B, C, M;
10166 unsigned BitWidth;
10167 auto T = GetQuadraticEquation(AddRec);
10168 if (!T)
10169 return std::nullopt;
10171 // Be careful about the return value: there can be two reasons for not
10172 // returning an actual number. First, if no solutions to the equations
10173 // were found, and second, if the solutions don't leave the given range.
10174 // The first case means that the actual solution is "unknown", the second
10175 // means that it's known, but not valid. If the solution is unknown, we
10176 // cannot make any conclusions.
10177 // Return a pair: the optional solution and a flag indicating if the
10178 // solution was found.
10179 auto SolveForBoundary =
10180 [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
10181 // Solve for signed overflow and unsigned overflow, pick the lower
10182 // solution.
10183 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
10184 << Bound << " (before multiplying by " << M << ")\n");
10185 Bound *= M; // The quadratic equation multiplier.
10187 std::optional<APInt> SO;
10188 if (BitWidth > 1) {
10189 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10190 "signed overflow\n");
10191 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
10193 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10194 "unsigned overflow\n");
10195 std::optional<APInt> UO =
10196 APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth + 1);
10198 auto LeavesRange = [&] (const APInt &X) {
10199 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
10200 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
10201 if (Range.contains(V0->getValue()))
10202 return false;
10203 // X should be at least 1, so X-1 is non-negative.
10204 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
10205 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
10206 if (Range.contains(V1->getValue()))
10207 return true;
10208 return false;
10211 // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
10212 // can be a solution, but the function failed to find it. We cannot treat it
10213 // as "no solution".
10214 if (!SO || !UO)
10215 return {std::nullopt, false};
10217 // Check the smaller value first to see if it leaves the range.
10218 // At this point, both SO and UO must have values.
10219 std::optional<APInt> Min = MinOptional(SO, UO);
10220 if (LeavesRange(*Min))
10221 return { Min, true };
10222 std::optional<APInt> Max = Min == SO ? UO : SO;
10223 if (LeavesRange(*Max))
10224 return { Max, true };
10226 // Solutions were found, but were eliminated, hence the "true".
10227 return {std::nullopt, true};
10230 std::tie(A, B, C, M, BitWidth) = *T;
10231 // Lower bound is inclusive, subtract 1 to represent the exiting value.
10232 APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
10233 APInt Upper = Range.getUpper().sext(A.getBitWidth());
10234 auto SL = SolveForBoundary(Lower);
10235 auto SU = SolveForBoundary(Upper);
10236 // If any of the solutions was unknown, no meaninigful conclusions can
10237 // be made.
10238 if (!SL.second || !SU.second)
10239 return std::nullopt;
10241 // Claim: The correct solution is not some value between Min and Max.
10243 // Justification: Assuming that Min and Max are different values, one of
10244 // them is when the first signed overflow happens, the other is when the
10245 // first unsigned overflow happens. Crossing the range boundary is only
10246 // possible via an overflow (treating 0 as a special case of it, modeling
10247 // an overflow as crossing k*2^W for some k).
10249 // The interesting case here is when Min was eliminated as an invalid
10250 // solution, but Max was not. The argument is that if there was another
10251 // overflow between Min and Max, it would also have been eliminated if
10252 // it was considered.
10254 // For a given boundary, it is possible to have two overflows of the same
10255 // type (signed/unsigned) without having the other type in between: this
10256 // can happen when the vertex of the parabola is between the iterations
10257 // corresponding to the overflows. This is only possible when the two
10258 // overflows cross k*2^W for the same k. In such case, if the second one
10259 // left the range (and was the first one to do so), the first overflow
10260 // would have to enter the range, which would mean that either we had left
10261 // the range before or that we started outside of it. Both of these cases
10262 // are contradictions.
10264 // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
10265 // solution is not some value between the Max for this boundary and the
10266 // Min of the other boundary.
10268 // Justification: Assume that we had such Max_A and Min_B corresponding
10269 // to range boundaries A and B and such that Max_A < Min_B. If there was
10270 // a solution between Max_A and Min_B, it would have to be caused by an
10271 // overflow corresponding to either A or B. It cannot correspond to B,
10272 // since Min_B is the first occurrence of such an overflow. If it
10273 // corresponded to A, it would have to be either a signed or an unsigned
10274 // overflow that is larger than both eliminated overflows for A. But
10275 // between the eliminated overflows and this overflow, the values would
10276 // cover the entire value space, thus crossing the other boundary, which
10277 // is a contradiction.
10279 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
10282 ScalarEvolution::ExitLimit ScalarEvolution::howFarToZero(const SCEV *V,
10283 const Loop *L,
10284 bool ControlsOnlyExit,
10285 bool AllowPredicates) {
10287 // This is only used for loops with a "x != y" exit test. The exit condition
10288 // is now expressed as a single expression, V = x-y. So the exit test is
10289 // effectively V != 0. We know and take advantage of the fact that this
10290 // expression only being used in a comparison by zero context.
10292 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10293 // If the value is a constant
10294 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10295 // If the value is already zero, the branch will execute zero times.
10296 if (C->getValue()->isZero()) return C;
10297 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10300 const SCEVAddRecExpr *AddRec =
10301 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
10303 if (!AddRec && AllowPredicates)
10304 // Try to make this an AddRec using runtime tests, in the first X
10305 // iterations of this loop, where X is the SCEV expression found by the
10306 // algorithm below.
10307 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
10309 if (!AddRec || AddRec->getLoop() != L)
10310 return getCouldNotCompute();
10312 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
10313 // the quadratic equation to solve it.
10314 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
10315 // We can only use this value if the chrec ends up with an exact zero
10316 // value at this index. When solving for "X*X != 5", for example, we
10317 // should not accept a root of 2.
10318 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
10319 const auto *R = cast<SCEVConstant>(getConstant(*S));
10320 return ExitLimit(R, R, R, false, Predicates);
10322 return getCouldNotCompute();
10325 // Otherwise we can only handle this if it is affine.
10326 if (!AddRec->isAffine())
10327 return getCouldNotCompute();
10329 // If this is an affine expression, the execution count of this branch is
10330 // the minimum unsigned root of the following equation:
10332 // Start + Step*N = 0 (mod 2^BW)
10334 // equivalent to:
10336 // Step*N = -Start (mod 2^BW)
10338 // where BW is the common bit width of Start and Step.
10340 // Get the initial value for the loop.
10341 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
10342 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
10344 // For now we handle only constant steps.
10346 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
10347 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
10348 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
10349 // We have not yet seen any such cases.
10350 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
10351 if (!StepC || StepC->getValue()->isZero())
10352 return getCouldNotCompute();
10354 // For positive steps (counting up until unsigned overflow):
10355 // N = -Start/Step (as unsigned)
10356 // For negative steps (counting down to zero):
10357 // N = Start/-Step
10358 // First compute the unsigned distance from zero in the direction of Step.
10359 bool CountDown = StepC->getAPInt().isNegative();
10360 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
10362 // Handle unitary steps, which cannot wraparound.
10363 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10364 // N = Distance (as unsigned)
10365 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
10366 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
10367 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
10369 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10370 // we end up with a loop whose backedge-taken count is n - 1. Detect this
10371 // case, and see if we can improve the bound.
10373 // Explicitly handling this here is necessary because getUnsignedRange
10374 // isn't context-sensitive; it doesn't know that we only care about the
10375 // range inside the loop.
10376 const SCEV *Zero = getZero(Distance->getType());
10377 const SCEV *One = getOne(Distance->getType());
10378 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
10379 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
10380 // If Distance + 1 doesn't overflow, we can compute the maximum distance
10381 // as "unsigned_max(Distance + 1) - 1".
10382 ConstantRange CR = getUnsignedRange(DistancePlusOne);
10383 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
10385 return ExitLimit(Distance, getConstant(MaxBECount), Distance, false,
10386 Predicates);
10389 // If the condition controls loop exit (the loop exits only if the expression
10390 // is true) and the addition is no-wrap we can use unsigned divide to
10391 // compute the backedge count. In this case, the step may not divide the
10392 // distance, but we don't care because if the condition is "missed" the loop
10393 // will have undefined behavior due to wrapping.
10394 if (ControlsOnlyExit && AddRec->hasNoSelfWrap() &&
10395 loopHasNoAbnormalExits(AddRec->getLoop())) {
10396 const SCEV *Exact =
10397 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10398 const SCEV *ConstantMax = getCouldNotCompute();
10399 if (Exact != getCouldNotCompute()) {
10400 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L));
10401 ConstantMax =
10402 getConstant(APIntOps::umin(MaxInt, getUnsignedRangeMax(Exact)));
10404 const SCEV *SymbolicMax =
10405 isa<SCEVCouldNotCompute>(Exact) ? ConstantMax : Exact;
10406 return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
10409 // Solve the general equation.
10410 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
10411 getNegativeSCEV(Start), *this);
10413 const SCEV *M = E;
10414 if (E != getCouldNotCompute()) {
10415 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, L));
10416 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
10418 auto *S = isa<SCEVCouldNotCompute>(E) ? M : E;
10419 return ExitLimit(E, M, S, false, Predicates);
10422 ScalarEvolution::ExitLimit
10423 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10424 // Loops that look like: while (X == 0) are very strange indeed. We don't
10425 // handle them yet except for the trivial case. This could be expanded in the
10426 // future as needed.
10428 // If the value is a constant, check to see if it is known to be non-zero
10429 // already. If so, the backedge will execute zero times.
10430 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10431 if (!C->getValue()->isZero())
10432 return getZero(C->getType());
10433 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10436 // We could implement others, but I really doubt anyone writes loops like
10437 // this, and if they did, they would already be constant folded.
10438 return getCouldNotCompute();
10441 std::pair<const BasicBlock *, const BasicBlock *>
10442 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10443 const {
10444 // If the block has a unique predecessor, then there is no path from the
10445 // predecessor to the block that does not go through the direct edge
10446 // from the predecessor to the block.
10447 if (const BasicBlock *Pred = BB->getSinglePredecessor())
10448 return {Pred, BB};
10450 // A loop's header is defined to be a block that dominates the loop.
10451 // If the header has a unique predecessor outside the loop, it must be
10452 // a block that has exactly one successor that can reach the loop.
10453 if (const Loop *L = LI.getLoopFor(BB))
10454 return {L->getLoopPredecessor(), L->getHeader()};
10456 return {nullptr, nullptr};
10459 /// SCEV structural equivalence is usually sufficient for testing whether two
10460 /// expressions are equal, however for the purposes of looking for a condition
10461 /// guarding a loop, it can be useful to be a little more general, since a
10462 /// front-end may have replicated the controlling expression.
10463 static bool HasSameValue(const SCEV *A, const SCEV *B) {
10464 // Quick check to see if they are the same SCEV.
10465 if (A == B) return true;
10467 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10468 // Not all instructions that are "identical" compute the same value. For
10469 // instance, two distinct alloca instructions allocating the same type are
10470 // identical and do not read memory; but compute distinct values.
10471 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
10474 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10475 // two different instructions with the same value. Check for this case.
10476 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
10477 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
10478 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
10479 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
10480 if (ComputesEqualValues(AI, BI))
10481 return true;
10483 // Otherwise assume they may have a different value.
10484 return false;
10487 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
10488 const SCEV *&LHS, const SCEV *&RHS,
10489 unsigned Depth) {
10490 bool Changed = false;
10491 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
10492 // '0 != 0'.
10493 auto TrivialCase = [&](bool TriviallyTrue) {
10494 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
10495 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
10496 return true;
10498 // If we hit the max recursion limit bail out.
10499 if (Depth >= 3)
10500 return false;
10502 // Canonicalize a constant to the right side.
10503 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
10504 // Check for both operands constant.
10505 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
10506 if (ConstantExpr::getICmp(Pred,
10507 LHSC->getValue(),
10508 RHSC->getValue())->isNullValue())
10509 return TrivialCase(false);
10510 return TrivialCase(true);
10512 // Otherwise swap the operands to put the constant on the right.
10513 std::swap(LHS, RHS);
10514 Pred = ICmpInst::getSwappedPredicate(Pred);
10515 Changed = true;
10518 // If we're comparing an addrec with a value which is loop-invariant in the
10519 // addrec's loop, put the addrec on the left. Also make a dominance check,
10520 // as both operands could be addrecs loop-invariant in each other's loop.
10521 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
10522 const Loop *L = AR->getLoop();
10523 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
10524 std::swap(LHS, RHS);
10525 Pred = ICmpInst::getSwappedPredicate(Pred);
10526 Changed = true;
10530 // If there's a constant operand, canonicalize comparisons with boundary
10531 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
10532 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
10533 const APInt &RA = RC->getAPInt();
10535 bool SimplifiedByConstantRange = false;
10537 if (!ICmpInst::isEquality(Pred)) {
10538 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
10539 if (ExactCR.isFullSet())
10540 return TrivialCase(true);
10541 if (ExactCR.isEmptySet())
10542 return TrivialCase(false);
10544 APInt NewRHS;
10545 CmpInst::Predicate NewPred;
10546 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
10547 ICmpInst::isEquality(NewPred)) {
10548 // We were able to convert an inequality to an equality.
10549 Pred = NewPred;
10550 RHS = getConstant(NewRHS);
10551 Changed = SimplifiedByConstantRange = true;
10555 if (!SimplifiedByConstantRange) {
10556 switch (Pred) {
10557 default:
10558 break;
10559 case ICmpInst::ICMP_EQ:
10560 case ICmpInst::ICMP_NE:
10561 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
10562 if (!RA)
10563 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
10564 if (const SCEVMulExpr *ME =
10565 dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
10566 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
10567 ME->getOperand(0)->isAllOnesValue()) {
10568 RHS = AE->getOperand(1);
10569 LHS = ME->getOperand(1);
10570 Changed = true;
10572 break;
10575 // The "Should have been caught earlier!" messages refer to the fact
10576 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
10577 // should have fired on the corresponding cases, and canonicalized the
10578 // check to trivial case.
10580 case ICmpInst::ICMP_UGE:
10581 assert(!RA.isMinValue() && "Should have been caught earlier!");
10582 Pred = ICmpInst::ICMP_UGT;
10583 RHS = getConstant(RA - 1);
10584 Changed = true;
10585 break;
10586 case ICmpInst::ICMP_ULE:
10587 assert(!RA.isMaxValue() && "Should have been caught earlier!");
10588 Pred = ICmpInst::ICMP_ULT;
10589 RHS = getConstant(RA + 1);
10590 Changed = true;
10591 break;
10592 case ICmpInst::ICMP_SGE:
10593 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
10594 Pred = ICmpInst::ICMP_SGT;
10595 RHS = getConstant(RA - 1);
10596 Changed = true;
10597 break;
10598 case ICmpInst::ICMP_SLE:
10599 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
10600 Pred = ICmpInst::ICMP_SLT;
10601 RHS = getConstant(RA + 1);
10602 Changed = true;
10603 break;
10608 // Check for obvious equality.
10609 if (HasSameValue(LHS, RHS)) {
10610 if (ICmpInst::isTrueWhenEqual(Pred))
10611 return TrivialCase(true);
10612 if (ICmpInst::isFalseWhenEqual(Pred))
10613 return TrivialCase(false);
10616 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
10617 // adding or subtracting 1 from one of the operands.
10618 switch (Pred) {
10619 case ICmpInst::ICMP_SLE:
10620 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
10621 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
10622 SCEV::FlagNSW);
10623 Pred = ICmpInst::ICMP_SLT;
10624 Changed = true;
10625 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
10626 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
10627 SCEV::FlagNSW);
10628 Pred = ICmpInst::ICMP_SLT;
10629 Changed = true;
10631 break;
10632 case ICmpInst::ICMP_SGE:
10633 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
10634 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
10635 SCEV::FlagNSW);
10636 Pred = ICmpInst::ICMP_SGT;
10637 Changed = true;
10638 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
10639 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
10640 SCEV::FlagNSW);
10641 Pred = ICmpInst::ICMP_SGT;
10642 Changed = true;
10644 break;
10645 case ICmpInst::ICMP_ULE:
10646 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
10647 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
10648 SCEV::FlagNUW);
10649 Pred = ICmpInst::ICMP_ULT;
10650 Changed = true;
10651 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
10652 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
10653 Pred = ICmpInst::ICMP_ULT;
10654 Changed = true;
10656 break;
10657 case ICmpInst::ICMP_UGE:
10658 if (!getUnsignedRangeMin(RHS).isMinValue()) {
10659 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
10660 Pred = ICmpInst::ICMP_UGT;
10661 Changed = true;
10662 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
10663 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
10664 SCEV::FlagNUW);
10665 Pred = ICmpInst::ICMP_UGT;
10666 Changed = true;
10668 break;
10669 default:
10670 break;
10673 // TODO: More simplifications are possible here.
10675 // Recursively simplify until we either hit a recursion limit or nothing
10676 // changes.
10677 if (Changed)
10678 return SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1);
10680 return Changed;
10683 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
10684 return getSignedRangeMax(S).isNegative();
10687 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
10688 return getSignedRangeMin(S).isStrictlyPositive();
10691 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
10692 return !getSignedRangeMin(S).isNegative();
10695 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
10696 return !getSignedRangeMax(S).isStrictlyPositive();
10699 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
10700 return getUnsignedRangeMin(S) != 0;
10703 std::pair<const SCEV *, const SCEV *>
10704 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
10705 // Compute SCEV on entry of loop L.
10706 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
10707 if (Start == getCouldNotCompute())
10708 return { Start, Start };
10709 // Compute post increment SCEV for loop L.
10710 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
10711 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
10712 return { Start, PostInc };
10715 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
10716 const SCEV *LHS, const SCEV *RHS) {
10717 // First collect all loops.
10718 SmallPtrSet<const Loop *, 8> LoopsUsed;
10719 getUsedLoops(LHS, LoopsUsed);
10720 getUsedLoops(RHS, LoopsUsed);
10722 if (LoopsUsed.empty())
10723 return false;
10725 // Domination relationship must be a linear order on collected loops.
10726 #ifndef NDEBUG
10727 for (const auto *L1 : LoopsUsed)
10728 for (const auto *L2 : LoopsUsed)
10729 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
10730 DT.dominates(L2->getHeader(), L1->getHeader())) &&
10731 "Domination relationship is not a linear order");
10732 #endif
10734 const Loop *MDL =
10735 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
10736 [&](const Loop *L1, const Loop *L2) {
10737 return DT.properlyDominates(L1->getHeader(), L2->getHeader());
10740 // Get init and post increment value for LHS.
10741 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
10742 // if LHS contains unknown non-invariant SCEV then bail out.
10743 if (SplitLHS.first == getCouldNotCompute())
10744 return false;
10745 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
10746 // Get init and post increment value for RHS.
10747 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
10748 // if RHS contains unknown non-invariant SCEV then bail out.
10749 if (SplitRHS.first == getCouldNotCompute())
10750 return false;
10751 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
10752 // It is possible that init SCEV contains an invariant load but it does
10753 // not dominate MDL and is not available at MDL loop entry, so we should
10754 // check it here.
10755 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
10756 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
10757 return false;
10759 // It seems backedge guard check is faster than entry one so in some cases
10760 // it can speed up whole estimation by short circuit
10761 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
10762 SplitRHS.second) &&
10763 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
10766 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
10767 const SCEV *LHS, const SCEV *RHS) {
10768 // Canonicalize the inputs first.
10769 (void)SimplifyICmpOperands(Pred, LHS, RHS);
10771 if (isKnownViaInduction(Pred, LHS, RHS))
10772 return true;
10774 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
10775 return true;
10777 // Otherwise see what can be done with some simple reasoning.
10778 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
10781 std::optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred,
10782 const SCEV *LHS,
10783 const SCEV *RHS) {
10784 if (isKnownPredicate(Pred, LHS, RHS))
10785 return true;
10786 if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS))
10787 return false;
10788 return std::nullopt;
10791 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
10792 const SCEV *LHS, const SCEV *RHS,
10793 const Instruction *CtxI) {
10794 // TODO: Analyze guards and assumes from Context's block.
10795 return isKnownPredicate(Pred, LHS, RHS) ||
10796 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
10799 std::optional<bool>
10800 ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, const SCEV *LHS,
10801 const SCEV *RHS, const Instruction *CtxI) {
10802 std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
10803 if (KnownWithoutContext)
10804 return KnownWithoutContext;
10806 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
10807 return true;
10808 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(),
10809 ICmpInst::getInversePredicate(Pred),
10810 LHS, RHS))
10811 return false;
10812 return std::nullopt;
10815 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
10816 const SCEVAddRecExpr *LHS,
10817 const SCEV *RHS) {
10818 const Loop *L = LHS->getLoop();
10819 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
10820 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
10823 std::optional<ScalarEvolution::MonotonicPredicateType>
10824 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
10825 ICmpInst::Predicate Pred) {
10826 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
10828 #ifndef NDEBUG
10829 // Verify an invariant: inverting the predicate should turn a monotonically
10830 // increasing change to a monotonically decreasing one, and vice versa.
10831 if (Result) {
10832 auto ResultSwapped =
10833 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
10835 assert(*ResultSwapped != *Result &&
10836 "monotonicity should flip as we flip the predicate");
10838 #endif
10840 return Result;
10843 std::optional<ScalarEvolution::MonotonicPredicateType>
10844 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
10845 ICmpInst::Predicate Pred) {
10846 // A zero step value for LHS means the induction variable is essentially a
10847 // loop invariant value. We don't really depend on the predicate actually
10848 // flipping from false to true (for increasing predicates, and the other way
10849 // around for decreasing predicates), all we care about is that *if* the
10850 // predicate changes then it only changes from false to true.
10852 // A zero step value in itself is not very useful, but there may be places
10853 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
10854 // as general as possible.
10856 // Only handle LE/LT/GE/GT predicates.
10857 if (!ICmpInst::isRelational(Pred))
10858 return std::nullopt;
10860 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
10861 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
10862 "Should be greater or less!");
10864 // Check that AR does not wrap.
10865 if (ICmpInst::isUnsigned(Pred)) {
10866 if (!LHS->hasNoUnsignedWrap())
10867 return std::nullopt;
10868 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10870 assert(ICmpInst::isSigned(Pred) &&
10871 "Relational predicate is either signed or unsigned!");
10872 if (!LHS->hasNoSignedWrap())
10873 return std::nullopt;
10875 const SCEV *Step = LHS->getStepRecurrence(*this);
10877 if (isKnownNonNegative(Step))
10878 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10880 if (isKnownNonPositive(Step))
10881 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
10883 return std::nullopt;
10886 std::optional<ScalarEvolution::LoopInvariantPredicate>
10887 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
10888 const SCEV *LHS, const SCEV *RHS,
10889 const Loop *L,
10890 const Instruction *CtxI) {
10891 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
10892 if (!isLoopInvariant(RHS, L)) {
10893 if (!isLoopInvariant(LHS, L))
10894 return std::nullopt;
10896 std::swap(LHS, RHS);
10897 Pred = ICmpInst::getSwappedPredicate(Pred);
10900 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
10901 if (!ArLHS || ArLHS->getLoop() != L)
10902 return std::nullopt;
10904 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
10905 if (!MonotonicType)
10906 return std::nullopt;
10907 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
10908 // true as the loop iterates, and the backedge is control dependent on
10909 // "ArLHS `Pred` RHS" == true then we can reason as follows:
10911 // * if the predicate was false in the first iteration then the predicate
10912 // is never evaluated again, since the loop exits without taking the
10913 // backedge.
10914 // * if the predicate was true in the first iteration then it will
10915 // continue to be true for all future iterations since it is
10916 // monotonically increasing.
10918 // For both the above possibilities, we can replace the loop varying
10919 // predicate with its value on the first iteration of the loop (which is
10920 // loop invariant).
10922 // A similar reasoning applies for a monotonically decreasing predicate, by
10923 // replacing true with false and false with true in the above two bullets.
10924 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
10925 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
10927 if (isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
10928 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(),
10929 RHS);
10931 if (!CtxI)
10932 return std::nullopt;
10933 // Try to prove via context.
10934 // TODO: Support other cases.
10935 switch (Pred) {
10936 default:
10937 break;
10938 case ICmpInst::ICMP_ULE:
10939 case ICmpInst::ICMP_ULT: {
10940 assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!");
10941 // Given preconditions
10942 // (1) ArLHS does not cross the border of positive and negative parts of
10943 // range because of:
10944 // - Positive step; (TODO: lift this limitation)
10945 // - nuw - does not cross zero boundary;
10946 // - nsw - does not cross SINT_MAX boundary;
10947 // (2) ArLHS <s RHS
10948 // (3) RHS >=s 0
10949 // we can replace the loop variant ArLHS <u RHS condition with loop
10950 // invariant Start(ArLHS) <u RHS.
10952 // Because of (1) there are two options:
10953 // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
10954 // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
10955 // It means that ArLHS <s RHS <=> ArLHS <u RHS.
10956 // Because of (2) ArLHS <u RHS is trivially true.
10957 // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
10958 // We can strengthen this to Start(ArLHS) <u RHS.
10959 auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
10960 if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
10961 isKnownPositive(ArLHS->getStepRecurrence(*this)) &&
10962 isKnownNonNegative(RHS) &&
10963 isKnownPredicateAt(SignFlippedPred, ArLHS, RHS, CtxI))
10964 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(),
10965 RHS);
10969 return std::nullopt;
10972 std::optional<ScalarEvolution::LoopInvariantPredicate>
10973 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
10974 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
10975 const Instruction *CtxI, const SCEV *MaxIter) {
10976 if (auto LIP = getLoopInvariantExitCondDuringFirstIterationsImpl(
10977 Pred, LHS, RHS, L, CtxI, MaxIter))
10978 return LIP;
10979 if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
10980 // Number of iterations expressed as UMIN isn't always great for expressing
10981 // the value on the last iteration. If the straightforward approach didn't
10982 // work, try the following trick: if the a predicate is invariant for X, it
10983 // is also invariant for umin(X, ...). So try to find something that works
10984 // among subexpressions of MaxIter expressed as umin.
10985 for (auto *Op : UMin->operands())
10986 if (auto LIP = getLoopInvariantExitCondDuringFirstIterationsImpl(
10987 Pred, LHS, RHS, L, CtxI, Op))
10988 return LIP;
10989 return std::nullopt;
10992 std::optional<ScalarEvolution::LoopInvariantPredicate>
10993 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterationsImpl(
10994 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
10995 const Instruction *CtxI, const SCEV *MaxIter) {
10996 // Try to prove the following set of facts:
10997 // - The predicate is monotonic in the iteration space.
10998 // - If the check does not fail on the 1st iteration:
10999 // - No overflow will happen during first MaxIter iterations;
11000 // - It will not fail on the MaxIter'th iteration.
11001 // If the check does fail on the 1st iteration, we leave the loop and no
11002 // other checks matter.
11004 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11005 if (!isLoopInvariant(RHS, L)) {
11006 if (!isLoopInvariant(LHS, L))
11007 return std::nullopt;
11009 std::swap(LHS, RHS);
11010 Pred = ICmpInst::getSwappedPredicate(Pred);
11013 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
11014 if (!AR || AR->getLoop() != L)
11015 return std::nullopt;
11017 // The predicate must be relational (i.e. <, <=, >=, >).
11018 if (!ICmpInst::isRelational(Pred))
11019 return std::nullopt;
11021 // TODO: Support steps other than +/- 1.
11022 const SCEV *Step = AR->getStepRecurrence(*this);
11023 auto *One = getOne(Step->getType());
11024 auto *MinusOne = getNegativeSCEV(One);
11025 if (Step != One && Step != MinusOne)
11026 return std::nullopt;
11028 // Type mismatch here means that MaxIter is potentially larger than max
11029 // unsigned value in start type, which mean we cannot prove no wrap for the
11030 // indvar.
11031 if (AR->getType() != MaxIter->getType())
11032 return std::nullopt;
11034 // Value of IV on suggested last iteration.
11035 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
11036 // Does it still meet the requirement?
11037 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
11038 return std::nullopt;
11039 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
11040 // not exceed max unsigned value of this type), this effectively proves
11041 // that there is no wrap during the iteration. To prove that there is no
11042 // signed/unsigned wrap, we need to check that
11043 // Start <= Last for step = 1 or Start >= Last for step = -1.
11044 ICmpInst::Predicate NoOverflowPred =
11045 CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
11046 if (Step == MinusOne)
11047 NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
11048 const SCEV *Start = AR->getStart();
11049 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
11050 return std::nullopt;
11052 // Everything is fine.
11053 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
11056 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
11057 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
11058 if (HasSameValue(LHS, RHS))
11059 return ICmpInst::isTrueWhenEqual(Pred);
11061 // This code is split out from isKnownPredicate because it is called from
11062 // within isLoopEntryGuardedByCond.
11064 auto CheckRanges = [&](const ConstantRange &RangeLHS,
11065 const ConstantRange &RangeRHS) {
11066 return RangeLHS.icmp(Pred, RangeRHS);
11069 // The check at the top of the function catches the case where the values are
11070 // known to be equal.
11071 if (Pred == CmpInst::ICMP_EQ)
11072 return false;
11074 if (Pred == CmpInst::ICMP_NE) {
11075 auto SL = getSignedRange(LHS);
11076 auto SR = getSignedRange(RHS);
11077 if (CheckRanges(SL, SR))
11078 return true;
11079 auto UL = getUnsignedRange(LHS);
11080 auto UR = getUnsignedRange(RHS);
11081 if (CheckRanges(UL, UR))
11082 return true;
11083 auto *Diff = getMinusSCEV(LHS, RHS);
11084 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
11087 if (CmpInst::isSigned(Pred)) {
11088 auto SL = getSignedRange(LHS);
11089 auto SR = getSignedRange(RHS);
11090 return CheckRanges(SL, SR);
11093 auto UL = getUnsignedRange(LHS);
11094 auto UR = getUnsignedRange(RHS);
11095 return CheckRanges(UL, UR);
11098 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
11099 const SCEV *LHS,
11100 const SCEV *RHS) {
11101 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
11102 // C1 and C2 are constant integers. If either X or Y are not add expressions,
11103 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
11104 // OutC1 and OutC2.
11105 auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y,
11106 APInt &OutC1, APInt &OutC2,
11107 SCEV::NoWrapFlags ExpectedFlags) {
11108 const SCEV *XNonConstOp, *XConstOp;
11109 const SCEV *YNonConstOp, *YConstOp;
11110 SCEV::NoWrapFlags XFlagsPresent;
11111 SCEV::NoWrapFlags YFlagsPresent;
11113 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
11114 XConstOp = getZero(X->getType());
11115 XNonConstOp = X;
11116 XFlagsPresent = ExpectedFlags;
11118 if (!isa<SCEVConstant>(XConstOp) ||
11119 (XFlagsPresent & ExpectedFlags) != ExpectedFlags)
11120 return false;
11122 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
11123 YConstOp = getZero(Y->getType());
11124 YNonConstOp = Y;
11125 YFlagsPresent = ExpectedFlags;
11128 if (!isa<SCEVConstant>(YConstOp) ||
11129 (YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11130 return false;
11132 if (YNonConstOp != XNonConstOp)
11133 return false;
11135 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
11136 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
11138 return true;
11141 APInt C1;
11142 APInt C2;
11144 switch (Pred) {
11145 default:
11146 break;
11148 case ICmpInst::ICMP_SGE:
11149 std::swap(LHS, RHS);
11150 [[fallthrough]];
11151 case ICmpInst::ICMP_SLE:
11152 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
11153 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
11154 return true;
11156 break;
11158 case ICmpInst::ICMP_SGT:
11159 std::swap(LHS, RHS);
11160 [[fallthrough]];
11161 case ICmpInst::ICMP_SLT:
11162 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
11163 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
11164 return true;
11166 break;
11168 case ICmpInst::ICMP_UGE:
11169 std::swap(LHS, RHS);
11170 [[fallthrough]];
11171 case ICmpInst::ICMP_ULE:
11172 // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2.
11173 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2))
11174 return true;
11176 break;
11178 case ICmpInst::ICMP_UGT:
11179 std::swap(LHS, RHS);
11180 [[fallthrough]];
11181 case ICmpInst::ICMP_ULT:
11182 // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2.
11183 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2))
11184 return true;
11185 break;
11188 return false;
11191 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
11192 const SCEV *LHS,
11193 const SCEV *RHS) {
11194 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
11195 return false;
11197 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
11198 // the stack can result in exponential time complexity.
11199 SaveAndRestore Restore(ProvingSplitPredicate, true);
11201 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
11203 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
11204 // isKnownPredicate. isKnownPredicate is more powerful, but also more
11205 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
11206 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
11207 // use isKnownPredicate later if needed.
11208 return isKnownNonNegative(RHS) &&
11209 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
11210 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
11213 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
11214 ICmpInst::Predicate Pred,
11215 const SCEV *LHS, const SCEV *RHS) {
11216 // No need to even try if we know the module has no guards.
11217 if (!HasGuards)
11218 return false;
11220 return any_of(*BB, [&](const Instruction &I) {
11221 using namespace llvm::PatternMatch;
11223 Value *Condition;
11224 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
11225 m_Value(Condition))) &&
11226 isImpliedCond(Pred, LHS, RHS, Condition, false);
11230 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
11231 /// protected by a conditional between LHS and RHS. This is used to
11232 /// to eliminate casts.
11233 bool
11234 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
11235 ICmpInst::Predicate Pred,
11236 const SCEV *LHS, const SCEV *RHS) {
11237 // Interpret a null as meaning no loop, where there is obviously no guard
11238 // (interprocedural conditions notwithstanding). Do not bother about
11239 // unreachable loops.
11240 if (!L || !DT.isReachableFromEntry(L->getHeader()))
11241 return true;
11243 if (VerifyIR)
11244 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
11245 "This cannot be done on broken IR!");
11248 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11249 return true;
11251 BasicBlock *Latch = L->getLoopLatch();
11252 if (!Latch)
11253 return false;
11255 BranchInst *LoopContinuePredicate =
11256 dyn_cast<BranchInst>(Latch->getTerminator());
11257 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
11258 isImpliedCond(Pred, LHS, RHS,
11259 LoopContinuePredicate->getCondition(),
11260 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
11261 return true;
11263 // We don't want more than one activation of the following loops on the stack
11264 // -- that can lead to O(n!) time complexity.
11265 if (WalkingBEDominatingConds)
11266 return false;
11268 SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
11270 // See if we can exploit a trip count to prove the predicate.
11271 const auto &BETakenInfo = getBackedgeTakenInfo(L);
11272 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
11273 if (LatchBECount != getCouldNotCompute()) {
11274 // We know that Latch branches back to the loop header exactly
11275 // LatchBECount times. This means the backdege condition at Latch is
11276 // equivalent to "{0,+,1} u< LatchBECount".
11277 Type *Ty = LatchBECount->getType();
11278 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
11279 const SCEV *LoopCounter =
11280 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
11281 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
11282 LatchBECount))
11283 return true;
11286 // Check conditions due to any @llvm.assume intrinsics.
11287 for (auto &AssumeVH : AC.assumptions()) {
11288 if (!AssumeVH)
11289 continue;
11290 auto *CI = cast<CallInst>(AssumeVH);
11291 if (!DT.dominates(CI, Latch->getTerminator()))
11292 continue;
11294 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
11295 return true;
11298 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
11299 return true;
11301 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
11302 DTN != HeaderDTN; DTN = DTN->getIDom()) {
11303 assert(DTN && "should reach the loop header before reaching the root!");
11305 BasicBlock *BB = DTN->getBlock();
11306 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
11307 return true;
11309 BasicBlock *PBB = BB->getSinglePredecessor();
11310 if (!PBB)
11311 continue;
11313 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
11314 if (!ContinuePredicate || !ContinuePredicate->isConditional())
11315 continue;
11317 Value *Condition = ContinuePredicate->getCondition();
11319 // If we have an edge `E` within the loop body that dominates the only
11320 // latch, the condition guarding `E` also guards the backedge. This
11321 // reasoning works only for loops with a single latch.
11323 BasicBlockEdge DominatingEdge(PBB, BB);
11324 if (DominatingEdge.isSingleEdge()) {
11325 // We're constructively (and conservatively) enumerating edges within the
11326 // loop body that dominate the latch. The dominator tree better agree
11327 // with us on this:
11328 assert(DT.dominates(DominatingEdge, Latch) && "should be!");
11330 if (isImpliedCond(Pred, LHS, RHS, Condition,
11331 BB != ContinuePredicate->getSuccessor(0)))
11332 return true;
11336 return false;
11339 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
11340 ICmpInst::Predicate Pred,
11341 const SCEV *LHS,
11342 const SCEV *RHS) {
11343 // Do not bother proving facts for unreachable code.
11344 if (!DT.isReachableFromEntry(BB))
11345 return true;
11346 if (VerifyIR)
11347 assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
11348 "This cannot be done on broken IR!");
11350 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
11351 // the facts (a >= b && a != b) separately. A typical situation is when the
11352 // non-strict comparison is known from ranges and non-equality is known from
11353 // dominating predicates. If we are proving strict comparison, we always try
11354 // to prove non-equality and non-strict comparison separately.
11355 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
11356 const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
11357 bool ProvedNonStrictComparison = false;
11358 bool ProvedNonEquality = false;
11360 auto SplitAndProve =
11361 [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool {
11362 if (!ProvedNonStrictComparison)
11363 ProvedNonStrictComparison = Fn(NonStrictPredicate);
11364 if (!ProvedNonEquality)
11365 ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
11366 if (ProvedNonStrictComparison && ProvedNonEquality)
11367 return true;
11368 return false;
11371 if (ProvingStrictComparison) {
11372 auto ProofFn = [&](ICmpInst::Predicate P) {
11373 return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
11375 if (SplitAndProve(ProofFn))
11376 return true;
11379 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
11380 auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
11381 const Instruction *CtxI = &BB->front();
11382 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
11383 return true;
11384 if (ProvingStrictComparison) {
11385 auto ProofFn = [&](ICmpInst::Predicate P) {
11386 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
11388 if (SplitAndProve(ProofFn))
11389 return true;
11391 return false;
11394 // Starting at the block's predecessor, climb up the predecessor chain, as long
11395 // as there are predecessors that can be found that have unique successors
11396 // leading to the original block.
11397 const Loop *ContainingLoop = LI.getLoopFor(BB);
11398 const BasicBlock *PredBB;
11399 if (ContainingLoop && ContainingLoop->getHeader() == BB)
11400 PredBB = ContainingLoop->getLoopPredecessor();
11401 else
11402 PredBB = BB->getSinglePredecessor();
11403 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
11404 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
11405 const BranchInst *BlockEntryPredicate =
11406 dyn_cast<BranchInst>(Pair.first->getTerminator());
11407 if (!BlockEntryPredicate || BlockEntryPredicate->isUnconditional())
11408 continue;
11410 if (ProveViaCond(BlockEntryPredicate->getCondition(),
11411 BlockEntryPredicate->getSuccessor(0) != Pair.second))
11412 return true;
11415 // Check conditions due to any @llvm.assume intrinsics.
11416 for (auto &AssumeVH : AC.assumptions()) {
11417 if (!AssumeVH)
11418 continue;
11419 auto *CI = cast<CallInst>(AssumeVH);
11420 if (!DT.dominates(CI, BB))
11421 continue;
11423 if (ProveViaCond(CI->getArgOperand(0), false))
11424 return true;
11427 // Check conditions due to any @llvm.experimental.guard intrinsics.
11428 auto *GuardDecl = F.getParent()->getFunction(
11429 Intrinsic::getName(Intrinsic::experimental_guard));
11430 if (GuardDecl)
11431 for (const auto *GU : GuardDecl->users())
11432 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
11433 if (Guard->getFunction() == BB->getParent() && DT.dominates(Guard, BB))
11434 if (ProveViaCond(Guard->getArgOperand(0), false))
11435 return true;
11436 return false;
11439 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
11440 ICmpInst::Predicate Pred,
11441 const SCEV *LHS,
11442 const SCEV *RHS) {
11443 // Interpret a null as meaning no loop, where there is obviously no guard
11444 // (interprocedural conditions notwithstanding).
11445 if (!L)
11446 return false;
11448 // Both LHS and RHS must be available at loop entry.
11449 assert(isAvailableAtLoopEntry(LHS, L) &&
11450 "LHS is not available at Loop Entry");
11451 assert(isAvailableAtLoopEntry(RHS, L) &&
11452 "RHS is not available at Loop Entry");
11454 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11455 return true;
11457 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
11460 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
11461 const SCEV *RHS,
11462 const Value *FoundCondValue, bool Inverse,
11463 const Instruction *CtxI) {
11464 // False conditions implies anything. Do not bother analyzing it further.
11465 if (FoundCondValue ==
11466 ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
11467 return true;
11469 if (!PendingLoopPredicates.insert(FoundCondValue).second)
11470 return false;
11472 auto ClearOnExit =
11473 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
11475 // Recursively handle And and Or conditions.
11476 const Value *Op0, *Op1;
11477 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
11478 if (!Inverse)
11479 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
11480 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
11481 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
11482 if (Inverse)
11483 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
11484 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
11487 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
11488 if (!ICI) return false;
11490 // Now that we found a conditional branch that dominates the loop or controls
11491 // the loop latch. Check to see if it is the comparison we are looking for.
11492 ICmpInst::Predicate FoundPred;
11493 if (Inverse)
11494 FoundPred = ICI->getInversePredicate();
11495 else
11496 FoundPred = ICI->getPredicate();
11498 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
11499 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
11501 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
11504 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
11505 const SCEV *RHS,
11506 ICmpInst::Predicate FoundPred,
11507 const SCEV *FoundLHS, const SCEV *FoundRHS,
11508 const Instruction *CtxI) {
11509 // Balance the types.
11510 if (getTypeSizeInBits(LHS->getType()) <
11511 getTypeSizeInBits(FoundLHS->getType())) {
11512 // For unsigned and equality predicates, try to prove that both found
11513 // operands fit into narrow unsigned range. If so, try to prove facts in
11514 // narrow types.
11515 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
11516 !FoundRHS->getType()->isPointerTy()) {
11517 auto *NarrowType = LHS->getType();
11518 auto *WideType = FoundLHS->getType();
11519 auto BitWidth = getTypeSizeInBits(NarrowType);
11520 const SCEV *MaxValue = getZeroExtendExpr(
11521 getConstant(APInt::getMaxValue(BitWidth)), WideType);
11522 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
11523 MaxValue) &&
11524 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
11525 MaxValue)) {
11526 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
11527 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
11528 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
11529 TruncFoundRHS, CtxI))
11530 return true;
11534 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
11535 return false;
11536 if (CmpInst::isSigned(Pred)) {
11537 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
11538 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
11539 } else {
11540 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
11541 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
11543 } else if (getTypeSizeInBits(LHS->getType()) >
11544 getTypeSizeInBits(FoundLHS->getType())) {
11545 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
11546 return false;
11547 if (CmpInst::isSigned(FoundPred)) {
11548 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
11549 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
11550 } else {
11551 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
11552 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
11555 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
11556 FoundRHS, CtxI);
11559 bool ScalarEvolution::isImpliedCondBalancedTypes(
11560 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11561 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
11562 const Instruction *CtxI) {
11563 assert(getTypeSizeInBits(LHS->getType()) ==
11564 getTypeSizeInBits(FoundLHS->getType()) &&
11565 "Types should be balanced!");
11566 // Canonicalize the query to match the way instcombine will have
11567 // canonicalized the comparison.
11568 if (SimplifyICmpOperands(Pred, LHS, RHS))
11569 if (LHS == RHS)
11570 return CmpInst::isTrueWhenEqual(Pred);
11571 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
11572 if (FoundLHS == FoundRHS)
11573 return CmpInst::isFalseWhenEqual(FoundPred);
11575 // Check to see if we can make the LHS or RHS match.
11576 if (LHS == FoundRHS || RHS == FoundLHS) {
11577 if (isa<SCEVConstant>(RHS)) {
11578 std::swap(FoundLHS, FoundRHS);
11579 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
11580 } else {
11581 std::swap(LHS, RHS);
11582 Pred = ICmpInst::getSwappedPredicate(Pred);
11586 // Check whether the found predicate is the same as the desired predicate.
11587 if (FoundPred == Pred)
11588 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
11590 // Check whether swapping the found predicate makes it the same as the
11591 // desired predicate.
11592 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
11593 // We can write the implication
11594 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS
11595 // using one of the following ways:
11596 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS
11597 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS
11598 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS
11599 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS
11600 // Forms 1. and 2. require swapping the operands of one condition. Don't
11601 // do this if it would break canonical constant/addrec ordering.
11602 if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS))
11603 return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS,
11604 CtxI);
11605 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
11606 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI);
11608 // There's no clear preference between forms 3. and 4., try both. Avoid
11609 // forming getNotSCEV of pointer values as the resulting subtract is
11610 // not legal.
11611 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() &&
11612 isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS),
11613 FoundLHS, FoundRHS, CtxI))
11614 return true;
11616 if (!FoundLHS->getType()->isPointerTy() &&
11617 !FoundRHS->getType()->isPointerTy() &&
11618 isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS),
11619 getNotSCEV(FoundRHS), CtxI))
11620 return true;
11622 return false;
11625 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
11626 CmpInst::Predicate P2) {
11627 assert(P1 != P2 && "Handled earlier!");
11628 return CmpInst::isRelational(P2) &&
11629 P1 == CmpInst::getFlippedSignednessPredicate(P2);
11631 if (IsSignFlippedPredicate(Pred, FoundPred)) {
11632 // Unsigned comparison is the same as signed comparison when both the
11633 // operands are non-negative or negative.
11634 if ((isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) ||
11635 (isKnownNegative(FoundLHS) && isKnownNegative(FoundRHS)))
11636 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
11637 // Create local copies that we can freely swap and canonicalize our
11638 // conditions to "le/lt".
11639 ICmpInst::Predicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
11640 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
11641 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
11642 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
11643 CanonicalPred = ICmpInst::getSwappedPredicate(CanonicalPred);
11644 CanonicalFoundPred = ICmpInst::getSwappedPredicate(CanonicalFoundPred);
11645 std::swap(CanonicalLHS, CanonicalRHS);
11646 std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
11648 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
11649 "Must be!");
11650 assert((ICmpInst::isLT(CanonicalFoundPred) ||
11651 ICmpInst::isLE(CanonicalFoundPred)) &&
11652 "Must be!");
11653 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
11654 // Use implication:
11655 // x <u y && y >=s 0 --> x <s y.
11656 // If we can prove the left part, the right part is also proven.
11657 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
11658 CanonicalRHS, CanonicalFoundLHS,
11659 CanonicalFoundRHS);
11660 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
11661 // Use implication:
11662 // x <s y && y <s 0 --> x <u y.
11663 // If we can prove the left part, the right part is also proven.
11664 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
11665 CanonicalRHS, CanonicalFoundLHS,
11666 CanonicalFoundRHS);
11669 // Check if we can make progress by sharpening ranges.
11670 if (FoundPred == ICmpInst::ICMP_NE &&
11671 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
11673 const SCEVConstant *C = nullptr;
11674 const SCEV *V = nullptr;
11676 if (isa<SCEVConstant>(FoundLHS)) {
11677 C = cast<SCEVConstant>(FoundLHS);
11678 V = FoundRHS;
11679 } else {
11680 C = cast<SCEVConstant>(FoundRHS);
11681 V = FoundLHS;
11684 // The guarding predicate tells us that C != V. If the known range
11685 // of V is [C, t), we can sharpen the range to [C + 1, t). The
11686 // range we consider has to correspond to same signedness as the
11687 // predicate we're interested in folding.
11689 APInt Min = ICmpInst::isSigned(Pred) ?
11690 getSignedRangeMin(V) : getUnsignedRangeMin(V);
11692 if (Min == C->getAPInt()) {
11693 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
11694 // This is true even if (Min + 1) wraps around -- in case of
11695 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
11697 APInt SharperMin = Min + 1;
11699 switch (Pred) {
11700 case ICmpInst::ICMP_SGE:
11701 case ICmpInst::ICMP_UGE:
11702 // We know V `Pred` SharperMin. If this implies LHS `Pred`
11703 // RHS, we're done.
11704 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
11705 CtxI))
11706 return true;
11707 [[fallthrough]];
11709 case ICmpInst::ICMP_SGT:
11710 case ICmpInst::ICMP_UGT:
11711 // We know from the range information that (V `Pred` Min ||
11712 // V == Min). We know from the guarding condition that !(V
11713 // == Min). This gives us
11715 // V `Pred` Min || V == Min && !(V == Min)
11716 // => V `Pred` Min
11718 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
11720 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
11721 return true;
11722 break;
11724 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
11725 case ICmpInst::ICMP_SLE:
11726 case ICmpInst::ICMP_ULE:
11727 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
11728 LHS, V, getConstant(SharperMin), CtxI))
11729 return true;
11730 [[fallthrough]];
11732 case ICmpInst::ICMP_SLT:
11733 case ICmpInst::ICMP_ULT:
11734 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
11735 LHS, V, getConstant(Min), CtxI))
11736 return true;
11737 break;
11739 default:
11740 // No change
11741 break;
11746 // Check whether the actual condition is beyond sufficient.
11747 if (FoundPred == ICmpInst::ICMP_EQ)
11748 if (ICmpInst::isTrueWhenEqual(Pred))
11749 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
11750 return true;
11751 if (Pred == ICmpInst::ICMP_NE)
11752 if (!ICmpInst::isTrueWhenEqual(FoundPred))
11753 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
11754 return true;
11756 // Otherwise assume the worst.
11757 return false;
11760 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
11761 const SCEV *&L, const SCEV *&R,
11762 SCEV::NoWrapFlags &Flags) {
11763 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
11764 if (!AE || AE->getNumOperands() != 2)
11765 return false;
11767 L = AE->getOperand(0);
11768 R = AE->getOperand(1);
11769 Flags = AE->getNoWrapFlags();
11770 return true;
11773 std::optional<APInt>
11774 ScalarEvolution::computeConstantDifference(const SCEV *More, const SCEV *Less) {
11775 // We avoid subtracting expressions here because this function is usually
11776 // fairly deep in the call stack (i.e. is called many times).
11778 // X - X = 0.
11779 if (More == Less)
11780 return APInt(getTypeSizeInBits(More->getType()), 0);
11782 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
11783 const auto *LAR = cast<SCEVAddRecExpr>(Less);
11784 const auto *MAR = cast<SCEVAddRecExpr>(More);
11786 if (LAR->getLoop() != MAR->getLoop())
11787 return std::nullopt;
11789 // We look at affine expressions only; not for correctness but to keep
11790 // getStepRecurrence cheap.
11791 if (!LAR->isAffine() || !MAR->isAffine())
11792 return std::nullopt;
11794 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
11795 return std::nullopt;
11797 Less = LAR->getStart();
11798 More = MAR->getStart();
11800 // fall through
11803 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
11804 const auto &M = cast<SCEVConstant>(More)->getAPInt();
11805 const auto &L = cast<SCEVConstant>(Less)->getAPInt();
11806 return M - L;
11809 SCEV::NoWrapFlags Flags;
11810 const SCEV *LLess = nullptr, *RLess = nullptr;
11811 const SCEV *LMore = nullptr, *RMore = nullptr;
11812 const SCEVConstant *C1 = nullptr, *C2 = nullptr;
11813 // Compare (X + C1) vs X.
11814 if (splitBinaryAdd(Less, LLess, RLess, Flags))
11815 if ((C1 = dyn_cast<SCEVConstant>(LLess)))
11816 if (RLess == More)
11817 return -(C1->getAPInt());
11819 // Compare X vs (X + C2).
11820 if (splitBinaryAdd(More, LMore, RMore, Flags))
11821 if ((C2 = dyn_cast<SCEVConstant>(LMore)))
11822 if (RMore == Less)
11823 return C2->getAPInt();
11825 // Compare (X + C1) vs (X + C2).
11826 if (C1 && C2 && RLess == RMore)
11827 return C2->getAPInt() - C1->getAPInt();
11829 return std::nullopt;
11832 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
11833 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11834 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *CtxI) {
11835 // Try to recognize the following pattern:
11837 // FoundRHS = ...
11838 // ...
11839 // loop:
11840 // FoundLHS = {Start,+,W}
11841 // context_bb: // Basic block from the same loop
11842 // known(Pred, FoundLHS, FoundRHS)
11844 // If some predicate is known in the context of a loop, it is also known on
11845 // each iteration of this loop, including the first iteration. Therefore, in
11846 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
11847 // prove the original pred using this fact.
11848 if (!CtxI)
11849 return false;
11850 const BasicBlock *ContextBB = CtxI->getParent();
11851 // Make sure AR varies in the context block.
11852 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
11853 const Loop *L = AR->getLoop();
11854 // Make sure that context belongs to the loop and executes on 1st iteration
11855 // (if it ever executes at all).
11856 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
11857 return false;
11858 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
11859 return false;
11860 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
11863 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
11864 const Loop *L = AR->getLoop();
11865 // Make sure that context belongs to the loop and executes on 1st iteration
11866 // (if it ever executes at all).
11867 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
11868 return false;
11869 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
11870 return false;
11871 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
11874 return false;
11877 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
11878 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11879 const SCEV *FoundLHS, const SCEV *FoundRHS) {
11880 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
11881 return false;
11883 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11884 if (!AddRecLHS)
11885 return false;
11887 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
11888 if (!AddRecFoundLHS)
11889 return false;
11891 // We'd like to let SCEV reason about control dependencies, so we constrain
11892 // both the inequalities to be about add recurrences on the same loop. This
11893 // way we can use isLoopEntryGuardedByCond later.
11895 const Loop *L = AddRecFoundLHS->getLoop();
11896 if (L != AddRecLHS->getLoop())
11897 return false;
11899 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
11901 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
11902 // ... (2)
11904 // Informal proof for (2), assuming (1) [*]:
11906 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
11908 // Then
11910 // FoundLHS s< FoundRHS s< INT_MIN - C
11911 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
11912 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
11913 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
11914 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
11915 // <=> FoundLHS + C s< FoundRHS + C
11917 // [*]: (1) can be proved by ruling out overflow.
11919 // [**]: This can be proved by analyzing all the four possibilities:
11920 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
11921 // (A s>= 0, B s>= 0).
11923 // Note:
11924 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
11925 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
11926 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
11927 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
11928 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
11929 // C)".
11931 std::optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
11932 std::optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
11933 if (!LDiff || !RDiff || *LDiff != *RDiff)
11934 return false;
11936 if (LDiff->isMinValue())
11937 return true;
11939 APInt FoundRHSLimit;
11941 if (Pred == CmpInst::ICMP_ULT) {
11942 FoundRHSLimit = -(*RDiff);
11943 } else {
11944 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
11945 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
11948 // Try to prove (1) or (2), as needed.
11949 return isAvailableAtLoopEntry(FoundRHS, L) &&
11950 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
11951 getConstant(FoundRHSLimit));
11954 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
11955 const SCEV *LHS, const SCEV *RHS,
11956 const SCEV *FoundLHS,
11957 const SCEV *FoundRHS, unsigned Depth) {
11958 const PHINode *LPhi = nullptr, *RPhi = nullptr;
11960 auto ClearOnExit = make_scope_exit([&]() {
11961 if (LPhi) {
11962 bool Erased = PendingMerges.erase(LPhi);
11963 assert(Erased && "Failed to erase LPhi!");
11964 (void)Erased;
11966 if (RPhi) {
11967 bool Erased = PendingMerges.erase(RPhi);
11968 assert(Erased && "Failed to erase RPhi!");
11969 (void)Erased;
11973 // Find respective Phis and check that they are not being pending.
11974 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
11975 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
11976 if (!PendingMerges.insert(Phi).second)
11977 return false;
11978 LPhi = Phi;
11980 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
11981 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
11982 // If we detect a loop of Phi nodes being processed by this method, for
11983 // example:
11985 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
11986 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
11988 // we don't want to deal with a case that complex, so return conservative
11989 // answer false.
11990 if (!PendingMerges.insert(Phi).second)
11991 return false;
11992 RPhi = Phi;
11995 // If none of LHS, RHS is a Phi, nothing to do here.
11996 if (!LPhi && !RPhi)
11997 return false;
11999 // If there is a SCEVUnknown Phi we are interested in, make it left.
12000 if (!LPhi) {
12001 std::swap(LHS, RHS);
12002 std::swap(FoundLHS, FoundRHS);
12003 std::swap(LPhi, RPhi);
12004 Pred = ICmpInst::getSwappedPredicate(Pred);
12007 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
12008 const BasicBlock *LBB = LPhi->getParent();
12009 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12011 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
12012 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
12013 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
12014 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
12017 if (RPhi && RPhi->getParent() == LBB) {
12018 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
12019 // If we compare two Phis from the same block, and for each entry block
12020 // the predicate is true for incoming values from this block, then the
12021 // predicate is also true for the Phis.
12022 for (const BasicBlock *IncBB : predecessors(LBB)) {
12023 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12024 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
12025 if (!ProvedEasily(L, R))
12026 return false;
12028 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
12029 // Case two: RHS is also a Phi from the same basic block, and it is an
12030 // AddRec. It means that there is a loop which has both AddRec and Unknown
12031 // PHIs, for it we can compare incoming values of AddRec from above the loop
12032 // and latch with their respective incoming values of LPhi.
12033 // TODO: Generalize to handle loops with many inputs in a header.
12034 if (LPhi->getNumIncomingValues() != 2) return false;
12036 auto *RLoop = RAR->getLoop();
12037 auto *Predecessor = RLoop->getLoopPredecessor();
12038 assert(Predecessor && "Loop with AddRec with no predecessor?");
12039 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
12040 if (!ProvedEasily(L1, RAR->getStart()))
12041 return false;
12042 auto *Latch = RLoop->getLoopLatch();
12043 assert(Latch && "Loop with AddRec with no latch?");
12044 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
12045 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
12046 return false;
12047 } else {
12048 // In all other cases go over inputs of LHS and compare each of them to RHS,
12049 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
12050 // At this point RHS is either a non-Phi, or it is a Phi from some block
12051 // different from LBB.
12052 for (const BasicBlock *IncBB : predecessors(LBB)) {
12053 // Check that RHS is available in this block.
12054 if (!dominates(RHS, IncBB))
12055 return false;
12056 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12057 // Make sure L does not refer to a value from a potentially previous
12058 // iteration of a loop.
12059 if (!properlyDominates(L, LBB))
12060 return false;
12061 if (!ProvedEasily(L, RHS))
12062 return false;
12065 return true;
12068 bool ScalarEvolution::isImpliedCondOperandsViaShift(ICmpInst::Predicate Pred,
12069 const SCEV *LHS,
12070 const SCEV *RHS,
12071 const SCEV *FoundLHS,
12072 const SCEV *FoundRHS) {
12073 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make
12074 // sure that we are dealing with same LHS.
12075 if (RHS == FoundRHS) {
12076 std::swap(LHS, RHS);
12077 std::swap(FoundLHS, FoundRHS);
12078 Pred = ICmpInst::getSwappedPredicate(Pred);
12080 if (LHS != FoundLHS)
12081 return false;
12083 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
12084 if (!SUFoundRHS)
12085 return false;
12087 Value *Shiftee, *ShiftValue;
12089 using namespace PatternMatch;
12090 if (match(SUFoundRHS->getValue(),
12091 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
12092 auto *ShifteeS = getSCEV(Shiftee);
12093 // Prove one of the following:
12094 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
12095 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
12096 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12097 // ---> LHS <s RHS
12098 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12099 // ---> LHS <=s RHS
12100 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
12101 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
12102 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
12103 if (isKnownNonNegative(ShifteeS))
12104 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
12107 return false;
12110 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
12111 const SCEV *LHS, const SCEV *RHS,
12112 const SCEV *FoundLHS,
12113 const SCEV *FoundRHS,
12114 const Instruction *CtxI) {
12115 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
12116 return true;
12118 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
12119 return true;
12121 if (isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS))
12122 return true;
12124 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12125 CtxI))
12126 return true;
12128 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
12129 FoundLHS, FoundRHS);
12132 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
12133 template <typename MinMaxExprType>
12134 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
12135 const SCEV *Candidate) {
12136 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12137 if (!MinMaxExpr)
12138 return false;
12140 return is_contained(MinMaxExpr->operands(), Candidate);
12143 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
12144 ICmpInst::Predicate Pred,
12145 const SCEV *LHS, const SCEV *RHS) {
12146 // If both sides are affine addrecs for the same loop, with equal
12147 // steps, and we know the recurrences don't wrap, then we only
12148 // need to check the predicate on the starting values.
12150 if (!ICmpInst::isRelational(Pred))
12151 return false;
12153 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
12154 if (!LAR)
12155 return false;
12156 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12157 if (!RAR)
12158 return false;
12159 if (LAR->getLoop() != RAR->getLoop())
12160 return false;
12161 if (!LAR->isAffine() || !RAR->isAffine())
12162 return false;
12164 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
12165 return false;
12167 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
12168 SCEV::FlagNSW : SCEV::FlagNUW;
12169 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
12170 return false;
12172 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
12175 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
12176 /// expression?
12177 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
12178 ICmpInst::Predicate Pred,
12179 const SCEV *LHS, const SCEV *RHS) {
12180 switch (Pred) {
12181 default:
12182 return false;
12184 case ICmpInst::ICMP_SGE:
12185 std::swap(LHS, RHS);
12186 [[fallthrough]];
12187 case ICmpInst::ICMP_SLE:
12188 return
12189 // min(A, ...) <= A
12190 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
12191 // A <= max(A, ...)
12192 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
12194 case ICmpInst::ICMP_UGE:
12195 std::swap(LHS, RHS);
12196 [[fallthrough]];
12197 case ICmpInst::ICMP_ULE:
12198 return
12199 // min(A, ...) <= A
12200 // FIXME: what about umin_seq?
12201 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
12202 // A <= max(A, ...)
12203 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
12206 llvm_unreachable("covered switch fell through?!");
12209 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
12210 const SCEV *LHS, const SCEV *RHS,
12211 const SCEV *FoundLHS,
12212 const SCEV *FoundRHS,
12213 unsigned Depth) {
12214 assert(getTypeSizeInBits(LHS->getType()) ==
12215 getTypeSizeInBits(RHS->getType()) &&
12216 "LHS and RHS have different sizes?");
12217 assert(getTypeSizeInBits(FoundLHS->getType()) ==
12218 getTypeSizeInBits(FoundRHS->getType()) &&
12219 "FoundLHS and FoundRHS have different sizes?");
12220 // We want to avoid hurting the compile time with analysis of too big trees.
12221 if (Depth > MaxSCEVOperationsImplicationDepth)
12222 return false;
12224 // We only want to work with GT comparison so far.
12225 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
12226 Pred = CmpInst::getSwappedPredicate(Pred);
12227 std::swap(LHS, RHS);
12228 std::swap(FoundLHS, FoundRHS);
12231 // For unsigned, try to reduce it to corresponding signed comparison.
12232 if (Pred == ICmpInst::ICMP_UGT)
12233 // We can replace unsigned predicate with its signed counterpart if all
12234 // involved values are non-negative.
12235 // TODO: We could have better support for unsigned.
12236 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
12237 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
12238 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
12239 // use this fact to prove that LHS and RHS are non-negative.
12240 const SCEV *MinusOne = getMinusOne(LHS->getType());
12241 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
12242 FoundRHS) &&
12243 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
12244 FoundRHS))
12245 Pred = ICmpInst::ICMP_SGT;
12248 if (Pred != ICmpInst::ICMP_SGT)
12249 return false;
12251 auto GetOpFromSExt = [&](const SCEV *S) {
12252 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
12253 return Ext->getOperand();
12254 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
12255 // the constant in some cases.
12256 return S;
12259 // Acquire values from extensions.
12260 auto *OrigLHS = LHS;
12261 auto *OrigFoundLHS = FoundLHS;
12262 LHS = GetOpFromSExt(LHS);
12263 FoundLHS = GetOpFromSExt(FoundLHS);
12265 // Is the SGT predicate can be proved trivially or using the found context.
12266 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
12267 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
12268 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
12269 FoundRHS, Depth + 1);
12272 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
12273 // We want to avoid creation of any new non-constant SCEV. Since we are
12274 // going to compare the operands to RHS, we should be certain that we don't
12275 // need any size extensions for this. So let's decline all cases when the
12276 // sizes of types of LHS and RHS do not match.
12277 // TODO: Maybe try to get RHS from sext to catch more cases?
12278 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
12279 return false;
12281 // Should not overflow.
12282 if (!LHSAddExpr->hasNoSignedWrap())
12283 return false;
12285 auto *LL = LHSAddExpr->getOperand(0);
12286 auto *LR = LHSAddExpr->getOperand(1);
12287 auto *MinusOne = getMinusOne(RHS->getType());
12289 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
12290 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
12291 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
12293 // Try to prove the following rule:
12294 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
12295 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
12296 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
12297 return true;
12298 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
12299 Value *LL, *LR;
12300 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
12302 using namespace llvm::PatternMatch;
12304 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
12305 // Rules for division.
12306 // We are going to perform some comparisons with Denominator and its
12307 // derivative expressions. In general case, creating a SCEV for it may
12308 // lead to a complex analysis of the entire graph, and in particular it
12309 // can request trip count recalculation for the same loop. This would
12310 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
12311 // this, we only want to create SCEVs that are constants in this section.
12312 // So we bail if Denominator is not a constant.
12313 if (!isa<ConstantInt>(LR))
12314 return false;
12316 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
12318 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
12319 // then a SCEV for the numerator already exists and matches with FoundLHS.
12320 auto *Numerator = getExistingSCEV(LL);
12321 if (!Numerator || Numerator->getType() != FoundLHS->getType())
12322 return false;
12324 // Make sure that the numerator matches with FoundLHS and the denominator
12325 // is positive.
12326 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
12327 return false;
12329 auto *DTy = Denominator->getType();
12330 auto *FRHSTy = FoundRHS->getType();
12331 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
12332 // One of types is a pointer and another one is not. We cannot extend
12333 // them properly to a wider type, so let us just reject this case.
12334 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
12335 // to avoid this check.
12336 return false;
12338 // Given that:
12339 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
12340 auto *WTy = getWiderType(DTy, FRHSTy);
12341 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
12342 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
12344 // Try to prove the following rule:
12345 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
12346 // For example, given that FoundLHS > 2. It means that FoundLHS is at
12347 // least 3. If we divide it by Denominator < 4, we will have at least 1.
12348 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
12349 if (isKnownNonPositive(RHS) &&
12350 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
12351 return true;
12353 // Try to prove the following rule:
12354 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
12355 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
12356 // If we divide it by Denominator > 2, then:
12357 // 1. If FoundLHS is negative, then the result is 0.
12358 // 2. If FoundLHS is non-negative, then the result is non-negative.
12359 // Anyways, the result is non-negative.
12360 auto *MinusOne = getMinusOne(WTy);
12361 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
12362 if (isKnownNegative(RHS) &&
12363 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
12364 return true;
12368 // If our expression contained SCEVUnknown Phis, and we split it down and now
12369 // need to prove something for them, try to prove the predicate for every
12370 // possible incoming values of those Phis.
12371 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
12372 return true;
12374 return false;
12377 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
12378 const SCEV *LHS, const SCEV *RHS) {
12379 // zext x u<= sext x, sext x s<= zext x
12380 switch (Pred) {
12381 case ICmpInst::ICMP_SGE:
12382 std::swap(LHS, RHS);
12383 [[fallthrough]];
12384 case ICmpInst::ICMP_SLE: {
12385 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt.
12386 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
12387 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
12388 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
12389 return true;
12390 break;
12392 case ICmpInst::ICMP_UGE:
12393 std::swap(LHS, RHS);
12394 [[fallthrough]];
12395 case ICmpInst::ICMP_ULE: {
12396 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt.
12397 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
12398 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
12399 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
12400 return true;
12401 break;
12403 default:
12404 break;
12406 return false;
12409 bool
12410 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
12411 const SCEV *LHS, const SCEV *RHS) {
12412 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
12413 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
12414 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
12415 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
12416 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
12419 bool
12420 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
12421 const SCEV *LHS, const SCEV *RHS,
12422 const SCEV *FoundLHS,
12423 const SCEV *FoundRHS) {
12424 switch (Pred) {
12425 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
12426 case ICmpInst::ICMP_EQ:
12427 case ICmpInst::ICMP_NE:
12428 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
12429 return true;
12430 break;
12431 case ICmpInst::ICMP_SLT:
12432 case ICmpInst::ICMP_SLE:
12433 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
12434 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
12435 return true;
12436 break;
12437 case ICmpInst::ICMP_SGT:
12438 case ICmpInst::ICMP_SGE:
12439 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
12440 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
12441 return true;
12442 break;
12443 case ICmpInst::ICMP_ULT:
12444 case ICmpInst::ICMP_ULE:
12445 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
12446 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
12447 return true;
12448 break;
12449 case ICmpInst::ICMP_UGT:
12450 case ICmpInst::ICMP_UGE:
12451 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
12452 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
12453 return true;
12454 break;
12457 // Maybe it can be proved via operations?
12458 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
12459 return true;
12461 return false;
12464 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
12465 const SCEV *LHS,
12466 const SCEV *RHS,
12467 const SCEV *FoundLHS,
12468 const SCEV *FoundRHS) {
12469 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
12470 // The restriction on `FoundRHS` be lifted easily -- it exists only to
12471 // reduce the compile time impact of this optimization.
12472 return false;
12474 std::optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
12475 if (!Addend)
12476 return false;
12478 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
12480 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
12481 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
12482 ConstantRange FoundLHSRange =
12483 ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS);
12485 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
12486 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
12488 // We can also compute the range of values for `LHS` that satisfy the
12489 // consequent, "`LHS` `Pred` `RHS`":
12490 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
12491 // The antecedent implies the consequent if every value of `LHS` that
12492 // satisfies the antecedent also satisfies the consequent.
12493 return LHSRange.icmp(Pred, ConstRHS);
12496 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
12497 bool IsSigned) {
12498 assert(isKnownPositive(Stride) && "Positive stride expected!");
12500 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
12501 const SCEV *One = getOne(Stride->getType());
12503 if (IsSigned) {
12504 APInt MaxRHS = getSignedRangeMax(RHS);
12505 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
12506 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
12508 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
12509 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
12512 APInt MaxRHS = getUnsignedRangeMax(RHS);
12513 APInt MaxValue = APInt::getMaxValue(BitWidth);
12514 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
12516 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
12517 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
12520 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
12521 bool IsSigned) {
12523 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
12524 const SCEV *One = getOne(Stride->getType());
12526 if (IsSigned) {
12527 APInt MinRHS = getSignedRangeMin(RHS);
12528 APInt MinValue = APInt::getSignedMinValue(BitWidth);
12529 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
12531 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
12532 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
12535 APInt MinRHS = getUnsignedRangeMin(RHS);
12536 APInt MinValue = APInt::getMinValue(BitWidth);
12537 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
12539 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
12540 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
12543 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) {
12544 // umin(N, 1) + floor((N - umin(N, 1)) / D)
12545 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
12546 // expression fixes the case of N=0.
12547 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
12548 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
12549 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
12552 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
12553 const SCEV *Stride,
12554 const SCEV *End,
12555 unsigned BitWidth,
12556 bool IsSigned) {
12557 // The logic in this function assumes we can represent a positive stride.
12558 // If we can't, the backedge-taken count must be zero.
12559 if (IsSigned && BitWidth == 1)
12560 return getZero(Stride->getType());
12562 // This code below only been closely audited for negative strides in the
12563 // unsigned comparison case, it may be correct for signed comparison, but
12564 // that needs to be established.
12565 if (IsSigned && isKnownNegative(Stride))
12566 return getCouldNotCompute();
12568 // Calculate the maximum backedge count based on the range of values
12569 // permitted by Start, End, and Stride.
12570 APInt MinStart =
12571 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
12573 APInt MinStride =
12574 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
12576 // We assume either the stride is positive, or the backedge-taken count
12577 // is zero. So force StrideForMaxBECount to be at least one.
12578 APInt One(BitWidth, 1);
12579 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
12580 : APIntOps::umax(One, MinStride);
12582 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
12583 : APInt::getMaxValue(BitWidth);
12584 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
12586 // Although End can be a MAX expression we estimate MaxEnd considering only
12587 // the case End = RHS of the loop termination condition. This is safe because
12588 // in the other case (End - Start) is zero, leading to a zero maximum backedge
12589 // taken count.
12590 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
12591 : APIntOps::umin(getUnsignedRangeMax(End), Limit);
12593 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
12594 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
12595 : APIntOps::umax(MaxEnd, MinStart);
12597 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */,
12598 getConstant(StrideForMaxBECount) /* Step */);
12601 ScalarEvolution::ExitLimit
12602 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
12603 const Loop *L, bool IsSigned,
12604 bool ControlsOnlyExit, bool AllowPredicates) {
12605 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
12607 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
12608 bool PredicatedIV = false;
12610 auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) {
12611 // Can we prove this loop *must* be UB if overflow of IV occurs?
12612 // Reasoning goes as follows:
12613 // * Suppose the IV did self wrap.
12614 // * If Stride evenly divides the iteration space, then once wrap
12615 // occurs, the loop must revisit the same values.
12616 // * We know that RHS is invariant, and that none of those values
12617 // caused this exit to be taken previously. Thus, this exit is
12618 // dynamically dead.
12619 // * If this is the sole exit, then a dead exit implies the loop
12620 // must be infinite if there are no abnormal exits.
12621 // * If the loop were infinite, then it must either not be mustprogress
12622 // or have side effects. Otherwise, it must be UB.
12623 // * It can't (by assumption), be UB so we have contradicted our
12624 // premise and can conclude the IV did not in fact self-wrap.
12625 if (!isLoopInvariant(RHS, L))
12626 return false;
12628 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
12629 if (!StrideC || !StrideC->getAPInt().isPowerOf2())
12630 return false;
12632 if (!ControlsOnlyExit || !loopHasNoAbnormalExits(L))
12633 return false;
12635 return loopIsFiniteByAssumption(L);
12638 if (!IV) {
12639 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
12640 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
12641 if (AR && AR->getLoop() == L && AR->isAffine()) {
12642 auto canProveNUW = [&]() {
12643 // We can use the comparison to infer no-wrap flags only if it fully
12644 // controls the loop exit.
12645 if (!ControlsOnlyExit)
12646 return false;
12648 if (!isLoopInvariant(RHS, L))
12649 return false;
12651 if (!isKnownNonZero(AR->getStepRecurrence(*this)))
12652 // We need the sequence defined by AR to strictly increase in the
12653 // unsigned integer domain for the logic below to hold.
12654 return false;
12656 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
12657 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
12658 // If RHS <=u Limit, then there must exist a value V in the sequence
12659 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
12660 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned
12661 // overflow occurs. This limit also implies that a signed comparison
12662 // (in the wide bitwidth) is equivalent to an unsigned comparison as
12663 // the high bits on both sides must be zero.
12664 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
12665 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
12666 Limit = Limit.zext(OuterBitWidth);
12667 return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit);
12669 auto Flags = AR->getNoWrapFlags();
12670 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
12671 Flags = setFlags(Flags, SCEV::FlagNUW);
12673 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
12674 if (AR->hasNoUnsignedWrap()) {
12675 // Emulate what getZeroExtendExpr would have done during construction
12676 // if we'd been able to infer the fact just above at that time.
12677 const SCEV *Step = AR->getStepRecurrence(*this);
12678 Type *Ty = ZExt->getType();
12679 auto *S = getAddRecExpr(
12680 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0),
12681 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
12682 IV = dyn_cast<SCEVAddRecExpr>(S);
12689 if (!IV && AllowPredicates) {
12690 // Try to make this an AddRec using runtime tests, in the first X
12691 // iterations of this loop, where X is the SCEV expression found by the
12692 // algorithm below.
12693 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
12694 PredicatedIV = true;
12697 // Avoid weird loops
12698 if (!IV || IV->getLoop() != L || !IV->isAffine())
12699 return getCouldNotCompute();
12701 // A precondition of this method is that the condition being analyzed
12702 // reaches an exiting branch which dominates the latch. Given that, we can
12703 // assume that an increment which violates the nowrap specification and
12704 // produces poison must cause undefined behavior when the resulting poison
12705 // value is branched upon and thus we can conclude that the backedge is
12706 // taken no more often than would be required to produce that poison value.
12707 // Note that a well defined loop can exit on the iteration which violates
12708 // the nowrap specification if there is another exit (either explicit or
12709 // implicit/exceptional) which causes the loop to execute before the
12710 // exiting instruction we're analyzing would trigger UB.
12711 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
12712 bool NoWrap = ControlsOnlyExit && IV->getNoWrapFlags(WrapType);
12713 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
12715 const SCEV *Stride = IV->getStepRecurrence(*this);
12717 bool PositiveStride = isKnownPositive(Stride);
12719 // Avoid negative or zero stride values.
12720 if (!PositiveStride) {
12721 // We can compute the correct backedge taken count for loops with unknown
12722 // strides if we can prove that the loop is not an infinite loop with side
12723 // effects. Here's the loop structure we are trying to handle -
12725 // i = start
12726 // do {
12727 // A[i] = i;
12728 // i += s;
12729 // } while (i < end);
12731 // The backedge taken count for such loops is evaluated as -
12732 // (max(end, start + stride) - start - 1) /u stride
12734 // The additional preconditions that we need to check to prove correctness
12735 // of the above formula is as follows -
12737 // a) IV is either nuw or nsw depending upon signedness (indicated by the
12738 // NoWrap flag).
12739 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
12740 // no side effects within the loop)
12741 // c) loop has a single static exit (with no abnormal exits)
12743 // Precondition a) implies that if the stride is negative, this is a single
12744 // trip loop. The backedge taken count formula reduces to zero in this case.
12746 // Precondition b) and c) combine to imply that if rhs is invariant in L,
12747 // then a zero stride means the backedge can't be taken without executing
12748 // undefined behavior.
12750 // The positive stride case is the same as isKnownPositive(Stride) returning
12751 // true (original behavior of the function).
12753 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
12754 !loopHasNoAbnormalExits(L))
12755 return getCouldNotCompute();
12757 if (!isKnownNonZero(Stride)) {
12758 // If we have a step of zero, and RHS isn't invariant in L, we don't know
12759 // if it might eventually be greater than start and if so, on which
12760 // iteration. We can't even produce a useful upper bound.
12761 if (!isLoopInvariant(RHS, L))
12762 return getCouldNotCompute();
12764 // We allow a potentially zero stride, but we need to divide by stride
12765 // below. Since the loop can't be infinite and this check must control
12766 // the sole exit, we can infer the exit must be taken on the first
12767 // iteration (e.g. backedge count = 0) if the stride is zero. Given that,
12768 // we know the numerator in the divides below must be zero, so we can
12769 // pick an arbitrary non-zero value for the denominator (e.g. stride)
12770 // and produce the right result.
12771 // FIXME: Handle the case where Stride is poison?
12772 auto wouldZeroStrideBeUB = [&]() {
12773 // Proof by contradiction. Suppose the stride were zero. If we can
12774 // prove that the backedge *is* taken on the first iteration, then since
12775 // we know this condition controls the sole exit, we must have an
12776 // infinite loop. We can't have a (well defined) infinite loop per
12777 // check just above.
12778 // Note: The (Start - Stride) term is used to get the start' term from
12779 // (start' + stride,+,stride). Remember that we only care about the
12780 // result of this expression when stride == 0 at runtime.
12781 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
12782 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
12784 if (!wouldZeroStrideBeUB()) {
12785 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
12788 } else if (!Stride->isOne() && !NoWrap) {
12789 auto isUBOnWrap = [&]() {
12790 // From no-self-wrap, we need to then prove no-(un)signed-wrap. This
12791 // follows trivially from the fact that every (un)signed-wrapped, but
12792 // not self-wrapped value must be LT than the last value before
12793 // (un)signed wrap. Since we know that last value didn't exit, nor
12794 // will any smaller one.
12795 return canAssumeNoSelfWrap(IV);
12798 // Avoid proven overflow cases: this will ensure that the backedge taken
12799 // count will not generate any unsigned overflow. Relaxed no-overflow
12800 // conditions exploit NoWrapFlags, allowing to optimize in presence of
12801 // undefined behaviors like the case of C language.
12802 if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap())
12803 return getCouldNotCompute();
12806 // On all paths just preceeding, we established the following invariant:
12807 // IV can be assumed not to overflow up to and including the exiting
12808 // iteration. We proved this in one of two ways:
12809 // 1) We can show overflow doesn't occur before the exiting iteration
12810 // 1a) canIVOverflowOnLT, and b) step of one
12811 // 2) We can show that if overflow occurs, the loop must execute UB
12812 // before any possible exit.
12813 // Note that we have not yet proved RHS invariant (in general).
12815 const SCEV *Start = IV->getStart();
12817 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
12818 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
12819 // Use integer-typed versions for actual computation; we can't subtract
12820 // pointers in general.
12821 const SCEV *OrigStart = Start;
12822 const SCEV *OrigRHS = RHS;
12823 if (Start->getType()->isPointerTy()) {
12824 Start = getLosslessPtrToIntExpr(Start);
12825 if (isa<SCEVCouldNotCompute>(Start))
12826 return Start;
12828 if (RHS->getType()->isPointerTy()) {
12829 RHS = getLosslessPtrToIntExpr(RHS);
12830 if (isa<SCEVCouldNotCompute>(RHS))
12831 return RHS;
12834 // When the RHS is not invariant, we do not know the end bound of the loop and
12835 // cannot calculate the ExactBECount needed by ExitLimit. However, we can
12836 // calculate the MaxBECount, given the start, stride and max value for the end
12837 // bound of the loop (RHS), and the fact that IV does not overflow (which is
12838 // checked above).
12839 if (!isLoopInvariant(RHS, L)) {
12840 const SCEV *MaxBECount = computeMaxBECountForLT(
12841 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
12842 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
12843 MaxBECount, false /*MaxOrZero*/, Predicates);
12846 // We use the expression (max(End,Start)-Start)/Stride to describe the
12847 // backedge count, as if the backedge is taken at least once max(End,Start)
12848 // is End and so the result is as above, and if not max(End,Start) is Start
12849 // so we get a backedge count of zero.
12850 const SCEV *BECount = nullptr;
12851 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
12852 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!");
12853 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
12854 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
12855 // Can we prove (max(RHS,Start) > Start - Stride?
12856 if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) &&
12857 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
12858 // In this case, we can use a refined formula for computing backedge taken
12859 // count. The general formula remains:
12860 // "End-Start /uceiling Stride" where "End = max(RHS,Start)"
12861 // We want to use the alternate formula:
12862 // "((End - 1) - (Start - Stride)) /u Stride"
12863 // Let's do a quick case analysis to show these are equivalent under
12864 // our precondition that max(RHS,Start) > Start - Stride.
12865 // * For RHS <= Start, the backedge-taken count must be zero.
12866 // "((End - 1) - (Start - Stride)) /u Stride" reduces to
12867 // "((Start - 1) - (Start - Stride)) /u Stride" which simplies to
12868 // "Stride - 1 /u Stride" which is indeed zero for all non-zero values
12869 // of Stride. For 0 stride, we've use umin(1,Stride) above, reducing
12870 // this to the stride of 1 case.
12871 // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride".
12872 // "((End - 1) - (Start - Stride)) /u Stride" reduces to
12873 // "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to
12874 // "((RHS - (Start - Stride) - 1) /u Stride".
12875 // Our preconditions trivially imply no overflow in that form.
12876 const SCEV *MinusOne = getMinusOne(Stride->getType());
12877 const SCEV *Numerator =
12878 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
12879 BECount = getUDivExpr(Numerator, Stride);
12882 const SCEV *BECountIfBackedgeTaken = nullptr;
12883 if (!BECount) {
12884 auto canProveRHSGreaterThanEqualStart = [&]() {
12885 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
12886 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart))
12887 return true;
12889 // (RHS > Start - 1) implies RHS >= Start.
12890 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
12891 // "Start - 1" doesn't overflow.
12892 // * For signed comparison, if Start - 1 does overflow, it's equal
12893 // to INT_MAX, and "RHS >s INT_MAX" is trivially false.
12894 // * For unsigned comparison, if Start - 1 does overflow, it's equal
12895 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
12897 // FIXME: Should isLoopEntryGuardedByCond do this for us?
12898 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
12899 auto *StartMinusOne = getAddExpr(OrigStart,
12900 getMinusOne(OrigStart->getType()));
12901 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
12904 // If we know that RHS >= Start in the context of loop, then we know that
12905 // max(RHS, Start) = RHS at this point.
12906 const SCEV *End;
12907 if (canProveRHSGreaterThanEqualStart()) {
12908 End = RHS;
12909 } else {
12910 // If RHS < Start, the backedge will be taken zero times. So in
12911 // general, we can write the backedge-taken count as:
12913 // RHS >= Start ? ceil(RHS - Start) / Stride : 0
12915 // We convert it to the following to make it more convenient for SCEV:
12917 // ceil(max(RHS, Start) - Start) / Stride
12918 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
12920 // See what would happen if we assume the backedge is taken. This is
12921 // used to compute MaxBECount.
12922 BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
12925 // At this point, we know:
12927 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
12928 // 2. The index variable doesn't overflow.
12930 // Therefore, we know N exists such that
12931 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
12932 // doesn't overflow.
12934 // Using this information, try to prove whether the addition in
12935 // "(Start - End) + (Stride - 1)" has unsigned overflow.
12936 const SCEV *One = getOne(Stride->getType());
12937 bool MayAddOverflow = [&] {
12938 if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) {
12939 if (StrideC->getAPInt().isPowerOf2()) {
12940 // Suppose Stride is a power of two, and Start/End are unsigned
12941 // integers. Let UMAX be the largest representable unsigned
12942 // integer.
12944 // By the preconditions of this function, we know
12945 // "(Start + Stride * N) >= End", and this doesn't overflow.
12946 // As a formula:
12948 // End <= (Start + Stride * N) <= UMAX
12950 // Subtracting Start from all the terms:
12952 // End - Start <= Stride * N <= UMAX - Start
12954 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore:
12956 // End - Start <= Stride * N <= UMAX
12958 // Stride * N is a multiple of Stride. Therefore,
12960 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
12962 // Since Stride is a power of two, UMAX + 1 is divisible by Stride.
12963 // Therefore, UMAX mod Stride == Stride - 1. So we can write:
12965 // End - Start <= Stride * N <= UMAX - Stride - 1
12967 // Dropping the middle term:
12969 // End - Start <= UMAX - Stride - 1
12971 // Adding Stride - 1 to both sides:
12973 // (End - Start) + (Stride - 1) <= UMAX
12975 // In other words, the addition doesn't have unsigned overflow.
12977 // A similar proof works if we treat Start/End as signed values.
12978 // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to
12979 // use signed max instead of unsigned max. Note that we're trying
12980 // to prove a lack of unsigned overflow in either case.
12981 return false;
12984 if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
12985 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1.
12986 // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End.
12987 // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End.
12989 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End.
12990 return false;
12992 return true;
12993 }();
12995 const SCEV *Delta = getMinusSCEV(End, Start);
12996 if (!MayAddOverflow) {
12997 // floor((D + (S - 1)) / S)
12998 // We prefer this formulation if it's legal because it's fewer operations.
12999 BECount =
13000 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13001 } else {
13002 BECount = getUDivCeilSCEV(Delta, Stride);
13006 const SCEV *ConstantMaxBECount;
13007 bool MaxOrZero = false;
13008 if (isa<SCEVConstant>(BECount)) {
13009 ConstantMaxBECount = BECount;
13010 } else if (BECountIfBackedgeTaken &&
13011 isa<SCEVConstant>(BECountIfBackedgeTaken)) {
13012 // If we know exactly how many times the backedge will be taken if it's
13013 // taken at least once, then the backedge count will either be that or
13014 // zero.
13015 ConstantMaxBECount = BECountIfBackedgeTaken;
13016 MaxOrZero = true;
13017 } else {
13018 ConstantMaxBECount = computeMaxBECountForLT(
13019 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
13022 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
13023 !isa<SCEVCouldNotCompute>(BECount))
13024 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
13026 const SCEV *SymbolicMaxBECount =
13027 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13028 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
13029 Predicates);
13032 ScalarEvolution::ExitLimit ScalarEvolution::howManyGreaterThans(
13033 const SCEV *LHS, const SCEV *RHS, const Loop *L, bool IsSigned,
13034 bool ControlsOnlyExit, bool AllowPredicates) {
13035 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
13036 // We handle only IV > Invariant
13037 if (!isLoopInvariant(RHS, L))
13038 return getCouldNotCompute();
13040 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
13041 if (!IV && AllowPredicates)
13042 // Try to make this an AddRec using runtime tests, in the first X
13043 // iterations of this loop, where X is the SCEV expression found by the
13044 // algorithm below.
13045 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13047 // Avoid weird loops
13048 if (!IV || IV->getLoop() != L || !IV->isAffine())
13049 return getCouldNotCompute();
13051 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13052 bool NoWrap = ControlsOnlyExit && IV->getNoWrapFlags(WrapType);
13053 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13055 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
13057 // Avoid negative or zero stride values
13058 if (!isKnownPositive(Stride))
13059 return getCouldNotCompute();
13061 // Avoid proven overflow cases: this will ensure that the backedge taken count
13062 // will not generate any unsigned overflow. Relaxed no-overflow conditions
13063 // exploit NoWrapFlags, allowing to optimize in presence of undefined
13064 // behaviors like the case of C language.
13065 if (!Stride->isOne() && !NoWrap)
13066 if (canIVOverflowOnGT(RHS, Stride, IsSigned))
13067 return getCouldNotCompute();
13069 const SCEV *Start = IV->getStart();
13070 const SCEV *End = RHS;
13071 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
13072 // If we know that Start >= RHS in the context of loop, then we know that
13073 // min(RHS, Start) = RHS at this point.
13074 if (isLoopEntryGuardedByCond(
13075 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
13076 End = RHS;
13077 else
13078 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
13081 if (Start->getType()->isPointerTy()) {
13082 Start = getLosslessPtrToIntExpr(Start);
13083 if (isa<SCEVCouldNotCompute>(Start))
13084 return Start;
13086 if (End->getType()->isPointerTy()) {
13087 End = getLosslessPtrToIntExpr(End);
13088 if (isa<SCEVCouldNotCompute>(End))
13089 return End;
13092 // Compute ((Start - End) + (Stride - 1)) / Stride.
13093 // FIXME: This can overflow. Holding off on fixing this for now;
13094 // howManyGreaterThans will hopefully be gone soon.
13095 const SCEV *One = getOne(Stride->getType());
13096 const SCEV *BECount = getUDivExpr(
13097 getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride);
13099 APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
13100 : getUnsignedRangeMax(Start);
13102 APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
13103 : getUnsignedRangeMin(Stride);
13105 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
13106 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
13107 : APInt::getMinValue(BitWidth) + (MinStride - 1);
13109 // Although End can be a MIN expression we estimate MinEnd considering only
13110 // the case End = RHS. This is safe because in the other case (Start - End)
13111 // is zero, leading to a zero maximum backedge taken count.
13112 APInt MinEnd =
13113 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
13114 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
13116 const SCEV *ConstantMaxBECount =
13117 isa<SCEVConstant>(BECount)
13118 ? BECount
13119 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd),
13120 getConstant(MinStride));
13122 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount))
13123 ConstantMaxBECount = BECount;
13124 const SCEV *SymbolicMaxBECount =
13125 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13127 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
13128 Predicates);
13131 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
13132 ScalarEvolution &SE) const {
13133 if (Range.isFullSet()) // Infinite loop.
13134 return SE.getCouldNotCompute();
13136 // If the start is a non-zero constant, shift the range to simplify things.
13137 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
13138 if (!SC->getValue()->isZero()) {
13139 SmallVector<const SCEV *, 4> Operands(operands());
13140 Operands[0] = SE.getZero(SC->getType());
13141 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
13142 getNoWrapFlags(FlagNW));
13143 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
13144 return ShiftedAddRec->getNumIterationsInRange(
13145 Range.subtract(SC->getAPInt()), SE);
13146 // This is strange and shouldn't happen.
13147 return SE.getCouldNotCompute();
13150 // The only time we can solve this is when we have all constant indices.
13151 // Otherwise, we cannot determine the overflow conditions.
13152 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
13153 return SE.getCouldNotCompute();
13155 // Okay at this point we know that all elements of the chrec are constants and
13156 // that the start element is zero.
13158 // First check to see if the range contains zero. If not, the first
13159 // iteration exits.
13160 unsigned BitWidth = SE.getTypeSizeInBits(getType());
13161 if (!Range.contains(APInt(BitWidth, 0)))
13162 return SE.getZero(getType());
13164 if (isAffine()) {
13165 // If this is an affine expression then we have this situation:
13166 // Solve {0,+,A} in Range === Ax in Range
13168 // We know that zero is in the range. If A is positive then we know that
13169 // the upper value of the range must be the first possible exit value.
13170 // If A is negative then the lower of the range is the last possible loop
13171 // value. Also note that we already checked for a full range.
13172 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
13173 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
13175 // The exit value should be (End+A)/A.
13176 APInt ExitVal = (End + A).udiv(A);
13177 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
13179 // Evaluate at the exit value. If we really did fall out of the valid
13180 // range, then we computed our trip count, otherwise wrap around or other
13181 // things must have happened.
13182 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
13183 if (Range.contains(Val->getValue()))
13184 return SE.getCouldNotCompute(); // Something strange happened
13186 // Ensure that the previous value is in the range.
13187 assert(Range.contains(
13188 EvaluateConstantChrecAtConstant(this,
13189 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
13190 "Linear scev computation is off in a bad way!");
13191 return SE.getConstant(ExitValue);
13194 if (isQuadratic()) {
13195 if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
13196 return SE.getConstant(*S);
13199 return SE.getCouldNotCompute();
13202 const SCEVAddRecExpr *
13203 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
13204 assert(getNumOperands() > 1 && "AddRec with zero step?");
13205 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
13206 // but in this case we cannot guarantee that the value returned will be an
13207 // AddRec because SCEV does not have a fixed point where it stops
13208 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
13209 // may happen if we reach arithmetic depth limit while simplifying. So we
13210 // construct the returned value explicitly.
13211 SmallVector<const SCEV *, 3> Ops;
13212 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
13213 // (this + Step) is {A+B,+,B+C,+...,+,N}.
13214 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
13215 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
13216 // We know that the last operand is not a constant zero (otherwise it would
13217 // have been popped out earlier). This guarantees us that if the result has
13218 // the same last operand, then it will also not be popped out, meaning that
13219 // the returned value will be an AddRec.
13220 const SCEV *Last = getOperand(getNumOperands() - 1);
13221 assert(!Last->isZero() && "Recurrency with zero step?");
13222 Ops.push_back(Last);
13223 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
13224 SCEV::FlagAnyWrap));
13227 // Return true when S contains at least an undef value.
13228 bool ScalarEvolution::containsUndefs(const SCEV *S) const {
13229 return SCEVExprContains(S, [](const SCEV *S) {
13230 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
13231 return isa<UndefValue>(SU->getValue());
13232 return false;
13236 // Return true when S contains a value that is a nullptr.
13237 bool ScalarEvolution::containsErasedValue(const SCEV *S) const {
13238 return SCEVExprContains(S, [](const SCEV *S) {
13239 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
13240 return SU->getValue() == nullptr;
13241 return false;
13245 /// Return the size of an element read or written by Inst.
13246 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
13247 Type *Ty;
13248 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
13249 Ty = Store->getValueOperand()->getType();
13250 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
13251 Ty = Load->getType();
13252 else
13253 return nullptr;
13255 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
13256 return getSizeOfExpr(ETy, Ty);
13259 //===----------------------------------------------------------------------===//
13260 // SCEVCallbackVH Class Implementation
13261 //===----------------------------------------------------------------------===//
13263 void ScalarEvolution::SCEVCallbackVH::deleted() {
13264 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
13265 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
13266 SE->ConstantEvolutionLoopExitValue.erase(PN);
13267 SE->eraseValueFromMap(getValPtr());
13268 // this now dangles!
13271 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
13272 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
13274 // Forget all the expressions associated with users of the old value,
13275 // so that future queries will recompute the expressions using the new
13276 // value.
13277 SE->forgetValue(getValPtr());
13278 // this now dangles!
13281 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
13282 : CallbackVH(V), SE(se) {}
13284 //===----------------------------------------------------------------------===//
13285 // ScalarEvolution Class Implementation
13286 //===----------------------------------------------------------------------===//
13288 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
13289 AssumptionCache &AC, DominatorTree &DT,
13290 LoopInfo &LI)
13291 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
13292 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
13293 LoopDispositions(64), BlockDispositions(64) {
13294 // To use guards for proving predicates, we need to scan every instruction in
13295 // relevant basic blocks, and not just terminators. Doing this is a waste of
13296 // time if the IR does not actually contain any calls to
13297 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
13299 // This pessimizes the case where a pass that preserves ScalarEvolution wants
13300 // to _add_ guards to the module when there weren't any before, and wants
13301 // ScalarEvolution to optimize based on those guards. For now we prefer to be
13302 // efficient in lieu of being smart in that rather obscure case.
13304 auto *GuardDecl = F.getParent()->getFunction(
13305 Intrinsic::getName(Intrinsic::experimental_guard));
13306 HasGuards = GuardDecl && !GuardDecl->use_empty();
13309 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
13310 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
13311 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
13312 ValueExprMap(std::move(Arg.ValueExprMap)),
13313 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
13314 PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
13315 PendingMerges(std::move(Arg.PendingMerges)),
13316 ConstantMultipleCache(std::move(Arg.ConstantMultipleCache)),
13317 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
13318 PredicatedBackedgeTakenCounts(
13319 std::move(Arg.PredicatedBackedgeTakenCounts)),
13320 BECountUsers(std::move(Arg.BECountUsers)),
13321 ConstantEvolutionLoopExitValue(
13322 std::move(Arg.ConstantEvolutionLoopExitValue)),
13323 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
13324 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
13325 LoopDispositions(std::move(Arg.LoopDispositions)),
13326 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
13327 BlockDispositions(std::move(Arg.BlockDispositions)),
13328 SCEVUsers(std::move(Arg.SCEVUsers)),
13329 UnsignedRanges(std::move(Arg.UnsignedRanges)),
13330 SignedRanges(std::move(Arg.SignedRanges)),
13331 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
13332 UniquePreds(std::move(Arg.UniquePreds)),
13333 SCEVAllocator(std::move(Arg.SCEVAllocator)),
13334 LoopUsers(std::move(Arg.LoopUsers)),
13335 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
13336 FirstUnknown(Arg.FirstUnknown) {
13337 Arg.FirstUnknown = nullptr;
13340 ScalarEvolution::~ScalarEvolution() {
13341 // Iterate through all the SCEVUnknown instances and call their
13342 // destructors, so that they release their references to their values.
13343 for (SCEVUnknown *U = FirstUnknown; U;) {
13344 SCEVUnknown *Tmp = U;
13345 U = U->Next;
13346 Tmp->~SCEVUnknown();
13348 FirstUnknown = nullptr;
13350 ExprValueMap.clear();
13351 ValueExprMap.clear();
13352 HasRecMap.clear();
13353 BackedgeTakenCounts.clear();
13354 PredicatedBackedgeTakenCounts.clear();
13356 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
13357 assert(PendingPhiRanges.empty() && "getRangeRef garbage");
13358 assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
13359 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
13360 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
13363 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
13364 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
13367 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
13368 const Loop *L) {
13369 // Print all inner loops first
13370 for (Loop *I : *L)
13371 PrintLoopInfo(OS, SE, I);
13373 OS << "Loop ";
13374 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13375 OS << ": ";
13377 SmallVector<BasicBlock *, 8> ExitingBlocks;
13378 L->getExitingBlocks(ExitingBlocks);
13379 if (ExitingBlocks.size() != 1)
13380 OS << "<multiple exits> ";
13382 if (SE->hasLoopInvariantBackedgeTakenCount(L))
13383 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
13384 else
13385 OS << "Unpredictable backedge-taken count.\n";
13387 if (ExitingBlocks.size() > 1)
13388 for (BasicBlock *ExitingBlock : ExitingBlocks) {
13389 OS << " exit count for " << ExitingBlock->getName() << ": "
13390 << *SE->getExitCount(L, ExitingBlock) << "\n";
13393 OS << "Loop ";
13394 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13395 OS << ": ";
13397 auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
13398 if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
13399 OS << "constant max backedge-taken count is " << *ConstantBTC;
13400 if (SE->isBackedgeTakenCountMaxOrZero(L))
13401 OS << ", actual taken count either this or zero.";
13402 } else {
13403 OS << "Unpredictable constant max backedge-taken count. ";
13406 OS << "\n"
13407 "Loop ";
13408 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13409 OS << ": ";
13411 auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
13412 if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
13413 OS << "symbolic max backedge-taken count is " << *SymbolicBTC;
13414 if (SE->isBackedgeTakenCountMaxOrZero(L))
13415 OS << ", actual taken count either this or zero.";
13416 } else {
13417 OS << "Unpredictable symbolic max backedge-taken count. ";
13420 OS << "\n";
13421 if (ExitingBlocks.size() > 1)
13422 for (BasicBlock *ExitingBlock : ExitingBlocks) {
13423 OS << " symbolic max exit count for " << ExitingBlock->getName() << ": "
13424 << *SE->getExitCount(L, ExitingBlock, ScalarEvolution::SymbolicMaximum)
13425 << "\n";
13428 OS << "Loop ";
13429 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13430 OS << ": ";
13432 SmallVector<const SCEVPredicate *, 4> Preds;
13433 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
13434 if (!isa<SCEVCouldNotCompute>(PBT)) {
13435 OS << "Predicated backedge-taken count is " << *PBT << "\n";
13436 OS << " Predicates:\n";
13437 for (const auto *P : Preds)
13438 P->print(OS, 4);
13439 } else {
13440 OS << "Unpredictable predicated backedge-taken count. ";
13442 OS << "\n";
13444 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
13445 OS << "Loop ";
13446 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13447 OS << ": ";
13448 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
13452 namespace llvm {
13453 raw_ostream &operator<<(raw_ostream &OS, ScalarEvolution::LoopDisposition LD) {
13454 switch (LD) {
13455 case ScalarEvolution::LoopVariant:
13456 OS << "Variant";
13457 break;
13458 case ScalarEvolution::LoopInvariant:
13459 OS << "Invariant";
13460 break;
13461 case ScalarEvolution::LoopComputable:
13462 OS << "Computable";
13463 break;
13465 return OS;
13468 raw_ostream &operator<<(raw_ostream &OS, ScalarEvolution::BlockDisposition BD) {
13469 switch (BD) {
13470 case ScalarEvolution::DoesNotDominateBlock:
13471 OS << "DoesNotDominate";
13472 break;
13473 case ScalarEvolution::DominatesBlock:
13474 OS << "Dominates";
13475 break;
13476 case ScalarEvolution::ProperlyDominatesBlock:
13477 OS << "ProperlyDominates";
13478 break;
13480 return OS;
13484 void ScalarEvolution::print(raw_ostream &OS) const {
13485 // ScalarEvolution's implementation of the print method is to print
13486 // out SCEV values of all instructions that are interesting. Doing
13487 // this potentially causes it to create new SCEV objects though,
13488 // which technically conflicts with the const qualifier. This isn't
13489 // observable from outside the class though, so casting away the
13490 // const isn't dangerous.
13491 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
13493 if (ClassifyExpressions) {
13494 OS << "Classifying expressions for: ";
13495 F.printAsOperand(OS, /*PrintType=*/false);
13496 OS << "\n";
13497 for (Instruction &I : instructions(F))
13498 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
13499 OS << I << '\n';
13500 OS << " --> ";
13501 const SCEV *SV = SE.getSCEV(&I);
13502 SV->print(OS);
13503 if (!isa<SCEVCouldNotCompute>(SV)) {
13504 OS << " U: ";
13505 SE.getUnsignedRange(SV).print(OS);
13506 OS << " S: ";
13507 SE.getSignedRange(SV).print(OS);
13510 const Loop *L = LI.getLoopFor(I.getParent());
13512 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
13513 if (AtUse != SV) {
13514 OS << " --> ";
13515 AtUse->print(OS);
13516 if (!isa<SCEVCouldNotCompute>(AtUse)) {
13517 OS << " U: ";
13518 SE.getUnsignedRange(AtUse).print(OS);
13519 OS << " S: ";
13520 SE.getSignedRange(AtUse).print(OS);
13524 if (L) {
13525 OS << "\t\t" "Exits: ";
13526 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
13527 if (!SE.isLoopInvariant(ExitValue, L)) {
13528 OS << "<<Unknown>>";
13529 } else {
13530 OS << *ExitValue;
13533 bool First = true;
13534 for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
13535 if (First) {
13536 OS << "\t\t" "LoopDispositions: { ";
13537 First = false;
13538 } else {
13539 OS << ", ";
13542 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13543 OS << ": " << SE.getLoopDisposition(SV, Iter);
13546 for (const auto *InnerL : depth_first(L)) {
13547 if (InnerL == L)
13548 continue;
13549 if (First) {
13550 OS << "\t\t" "LoopDispositions: { ";
13551 First = false;
13552 } else {
13553 OS << ", ";
13556 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13557 OS << ": " << SE.getLoopDisposition(SV, InnerL);
13560 OS << " }";
13563 OS << "\n";
13567 OS << "Determining loop execution counts for: ";
13568 F.printAsOperand(OS, /*PrintType=*/false);
13569 OS << "\n";
13570 for (Loop *I : LI)
13571 PrintLoopInfo(OS, &SE, I);
13574 ScalarEvolution::LoopDisposition
13575 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
13576 auto &Values = LoopDispositions[S];
13577 for (auto &V : Values) {
13578 if (V.getPointer() == L)
13579 return V.getInt();
13581 Values.emplace_back(L, LoopVariant);
13582 LoopDisposition D = computeLoopDisposition(S, L);
13583 auto &Values2 = LoopDispositions[S];
13584 for (auto &V : llvm::reverse(Values2)) {
13585 if (V.getPointer() == L) {
13586 V.setInt(D);
13587 break;
13590 return D;
13593 ScalarEvolution::LoopDisposition
13594 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
13595 switch (S->getSCEVType()) {
13596 case scConstant:
13597 case scVScale:
13598 return LoopInvariant;
13599 case scAddRecExpr: {
13600 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
13602 // If L is the addrec's loop, it's computable.
13603 if (AR->getLoop() == L)
13604 return LoopComputable;
13606 // Add recurrences are never invariant in the function-body (null loop).
13607 if (!L)
13608 return LoopVariant;
13610 // Everything that is not defined at loop entry is variant.
13611 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
13612 return LoopVariant;
13613 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
13614 " dominate the contained loop's header?");
13616 // This recurrence is invariant w.r.t. L if AR's loop contains L.
13617 if (AR->getLoop()->contains(L))
13618 return LoopInvariant;
13620 // This recurrence is variant w.r.t. L if any of its operands
13621 // are variant.
13622 for (const auto *Op : AR->operands())
13623 if (!isLoopInvariant(Op, L))
13624 return LoopVariant;
13626 // Otherwise it's loop-invariant.
13627 return LoopInvariant;
13629 case scTruncate:
13630 case scZeroExtend:
13631 case scSignExtend:
13632 case scPtrToInt:
13633 case scAddExpr:
13634 case scMulExpr:
13635 case scUDivExpr:
13636 case scUMaxExpr:
13637 case scSMaxExpr:
13638 case scUMinExpr:
13639 case scSMinExpr:
13640 case scSequentialUMinExpr: {
13641 bool HasVarying = false;
13642 for (const auto *Op : S->operands()) {
13643 LoopDisposition D = getLoopDisposition(Op, L);
13644 if (D == LoopVariant)
13645 return LoopVariant;
13646 if (D == LoopComputable)
13647 HasVarying = true;
13649 return HasVarying ? LoopComputable : LoopInvariant;
13651 case scUnknown:
13652 // All non-instruction values are loop invariant. All instructions are loop
13653 // invariant if they are not contained in the specified loop.
13654 // Instructions are never considered invariant in the function body
13655 // (null loop) because they are defined within the "loop".
13656 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
13657 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
13658 return LoopInvariant;
13659 case scCouldNotCompute:
13660 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
13662 llvm_unreachable("Unknown SCEV kind!");
13665 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
13666 return getLoopDisposition(S, L) == LoopInvariant;
13669 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
13670 return getLoopDisposition(S, L) == LoopComputable;
13673 ScalarEvolution::BlockDisposition
13674 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
13675 auto &Values = BlockDispositions[S];
13676 for (auto &V : Values) {
13677 if (V.getPointer() == BB)
13678 return V.getInt();
13680 Values.emplace_back(BB, DoesNotDominateBlock);
13681 BlockDisposition D = computeBlockDisposition(S, BB);
13682 auto &Values2 = BlockDispositions[S];
13683 for (auto &V : llvm::reverse(Values2)) {
13684 if (V.getPointer() == BB) {
13685 V.setInt(D);
13686 break;
13689 return D;
13692 ScalarEvolution::BlockDisposition
13693 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
13694 switch (S->getSCEVType()) {
13695 case scConstant:
13696 case scVScale:
13697 return ProperlyDominatesBlock;
13698 case scAddRecExpr: {
13699 // This uses a "dominates" query instead of "properly dominates" query
13700 // to test for proper dominance too, because the instruction which
13701 // produces the addrec's value is a PHI, and a PHI effectively properly
13702 // dominates its entire containing block.
13703 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
13704 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
13705 return DoesNotDominateBlock;
13707 // Fall through into SCEVNAryExpr handling.
13708 [[fallthrough]];
13710 case scTruncate:
13711 case scZeroExtend:
13712 case scSignExtend:
13713 case scPtrToInt:
13714 case scAddExpr:
13715 case scMulExpr:
13716 case scUDivExpr:
13717 case scUMaxExpr:
13718 case scSMaxExpr:
13719 case scUMinExpr:
13720 case scSMinExpr:
13721 case scSequentialUMinExpr: {
13722 bool Proper = true;
13723 for (const SCEV *NAryOp : S->operands()) {
13724 BlockDisposition D = getBlockDisposition(NAryOp, BB);
13725 if (D == DoesNotDominateBlock)
13726 return DoesNotDominateBlock;
13727 if (D == DominatesBlock)
13728 Proper = false;
13730 return Proper ? ProperlyDominatesBlock : DominatesBlock;
13732 case scUnknown:
13733 if (Instruction *I =
13734 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
13735 if (I->getParent() == BB)
13736 return DominatesBlock;
13737 if (DT.properlyDominates(I->getParent(), BB))
13738 return ProperlyDominatesBlock;
13739 return DoesNotDominateBlock;
13741 return ProperlyDominatesBlock;
13742 case scCouldNotCompute:
13743 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
13745 llvm_unreachable("Unknown SCEV kind!");
13748 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
13749 return getBlockDisposition(S, BB) >= DominatesBlock;
13752 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
13753 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
13756 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
13757 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
13760 void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
13761 bool Predicated) {
13762 auto &BECounts =
13763 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
13764 auto It = BECounts.find(L);
13765 if (It != BECounts.end()) {
13766 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
13767 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
13768 if (!isa<SCEVConstant>(S)) {
13769 auto UserIt = BECountUsers.find(S);
13770 assert(UserIt != BECountUsers.end());
13771 UserIt->second.erase({L, Predicated});
13775 BECounts.erase(It);
13779 void ScalarEvolution::forgetMemoizedResults(ArrayRef<const SCEV *> SCEVs) {
13780 SmallPtrSet<const SCEV *, 8> ToForget(SCEVs.begin(), SCEVs.end());
13781 SmallVector<const SCEV *, 8> Worklist(ToForget.begin(), ToForget.end());
13783 while (!Worklist.empty()) {
13784 const SCEV *Curr = Worklist.pop_back_val();
13785 auto Users = SCEVUsers.find(Curr);
13786 if (Users != SCEVUsers.end())
13787 for (const auto *User : Users->second)
13788 if (ToForget.insert(User).second)
13789 Worklist.push_back(User);
13792 for (const auto *S : ToForget)
13793 forgetMemoizedResultsImpl(S);
13795 for (auto I = PredicatedSCEVRewrites.begin();
13796 I != PredicatedSCEVRewrites.end();) {
13797 std::pair<const SCEV *, const Loop *> Entry = I->first;
13798 if (ToForget.count(Entry.first))
13799 PredicatedSCEVRewrites.erase(I++);
13800 else
13801 ++I;
13805 void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
13806 LoopDispositions.erase(S);
13807 BlockDispositions.erase(S);
13808 UnsignedRanges.erase(S);
13809 SignedRanges.erase(S);
13810 HasRecMap.erase(S);
13811 ConstantMultipleCache.erase(S);
13813 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
13814 UnsignedWrapViaInductionTried.erase(AR);
13815 SignedWrapViaInductionTried.erase(AR);
13818 auto ExprIt = ExprValueMap.find(S);
13819 if (ExprIt != ExprValueMap.end()) {
13820 for (Value *V : ExprIt->second) {
13821 auto ValueIt = ValueExprMap.find_as(V);
13822 if (ValueIt != ValueExprMap.end())
13823 ValueExprMap.erase(ValueIt);
13825 ExprValueMap.erase(ExprIt);
13828 auto ScopeIt = ValuesAtScopes.find(S);
13829 if (ScopeIt != ValuesAtScopes.end()) {
13830 for (const auto &Pair : ScopeIt->second)
13831 if (!isa_and_nonnull<SCEVConstant>(Pair.second))
13832 llvm::erase(ValuesAtScopesUsers[Pair.second],
13833 std::make_pair(Pair.first, S));
13834 ValuesAtScopes.erase(ScopeIt);
13837 auto ScopeUserIt = ValuesAtScopesUsers.find(S);
13838 if (ScopeUserIt != ValuesAtScopesUsers.end()) {
13839 for (const auto &Pair : ScopeUserIt->second)
13840 llvm::erase(ValuesAtScopes[Pair.second], std::make_pair(Pair.first, S));
13841 ValuesAtScopesUsers.erase(ScopeUserIt);
13844 auto BEUsersIt = BECountUsers.find(S);
13845 if (BEUsersIt != BECountUsers.end()) {
13846 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
13847 auto Copy = BEUsersIt->second;
13848 for (const auto &Pair : Copy)
13849 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
13850 BECountUsers.erase(BEUsersIt);
13853 auto FoldUser = FoldCacheUser.find(S);
13854 if (FoldUser != FoldCacheUser.end())
13855 for (auto &KV : FoldUser->second)
13856 FoldCache.erase(KV);
13857 FoldCacheUser.erase(S);
13860 void
13861 ScalarEvolution::getUsedLoops(const SCEV *S,
13862 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
13863 struct FindUsedLoops {
13864 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
13865 : LoopsUsed(LoopsUsed) {}
13866 SmallPtrSetImpl<const Loop *> &LoopsUsed;
13867 bool follow(const SCEV *S) {
13868 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
13869 LoopsUsed.insert(AR->getLoop());
13870 return true;
13873 bool isDone() const { return false; }
13876 FindUsedLoops F(LoopsUsed);
13877 SCEVTraversal<FindUsedLoops>(F).visitAll(S);
13880 void ScalarEvolution::getReachableBlocks(
13881 SmallPtrSetImpl<BasicBlock *> &Reachable, Function &F) {
13882 SmallVector<BasicBlock *> Worklist;
13883 Worklist.push_back(&F.getEntryBlock());
13884 while (!Worklist.empty()) {
13885 BasicBlock *BB = Worklist.pop_back_val();
13886 if (!Reachable.insert(BB).second)
13887 continue;
13889 Value *Cond;
13890 BasicBlock *TrueBB, *FalseBB;
13891 if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
13892 m_BasicBlock(FalseBB)))) {
13893 if (auto *C = dyn_cast<ConstantInt>(Cond)) {
13894 Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
13895 continue;
13898 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
13899 const SCEV *L = getSCEV(Cmp->getOperand(0));
13900 const SCEV *R = getSCEV(Cmp->getOperand(1));
13901 if (isKnownPredicateViaConstantRanges(Cmp->getPredicate(), L, R)) {
13902 Worklist.push_back(TrueBB);
13903 continue;
13905 if (isKnownPredicateViaConstantRanges(Cmp->getInversePredicate(), L,
13906 R)) {
13907 Worklist.push_back(FalseBB);
13908 continue;
13913 append_range(Worklist, successors(BB));
13917 void ScalarEvolution::verify() const {
13918 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
13919 ScalarEvolution SE2(F, TLI, AC, DT, LI);
13921 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
13923 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
13924 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
13925 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
13927 const SCEV *visitConstant(const SCEVConstant *Constant) {
13928 return SE.getConstant(Constant->getAPInt());
13931 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13932 return SE.getUnknown(Expr->getValue());
13935 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
13936 return SE.getCouldNotCompute();
13940 SCEVMapper SCM(SE2);
13941 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
13942 SE2.getReachableBlocks(ReachableBlocks, F);
13944 auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
13945 if (containsUndefs(Old) || containsUndefs(New)) {
13946 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
13947 // not propagate undef aggressively). This means we can (and do) fail
13948 // verification in cases where a transform makes a value go from "undef"
13949 // to "undef+1" (say). The transform is fine, since in both cases the
13950 // result is "undef", but SCEV thinks the value increased by 1.
13951 return nullptr;
13954 // Unless VerifySCEVStrict is set, we only compare constant deltas.
13955 const SCEV *Delta = SE2.getMinusSCEV(Old, New);
13956 if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
13957 return nullptr;
13959 return Delta;
13962 while (!LoopStack.empty()) {
13963 auto *L = LoopStack.pop_back_val();
13964 llvm::append_range(LoopStack, *L);
13966 // Only verify BECounts in reachable loops. For an unreachable loop,
13967 // any BECount is legal.
13968 if (!ReachableBlocks.contains(L->getHeader()))
13969 continue;
13971 // Only verify cached BECounts. Computing new BECounts may change the
13972 // results of subsequent SCEV uses.
13973 auto It = BackedgeTakenCounts.find(L);
13974 if (It == BackedgeTakenCounts.end())
13975 continue;
13977 auto *CurBECount =
13978 SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
13979 auto *NewBECount = SE2.getBackedgeTakenCount(L);
13981 if (CurBECount == SE2.getCouldNotCompute() ||
13982 NewBECount == SE2.getCouldNotCompute()) {
13983 // NB! This situation is legal, but is very suspicious -- whatever pass
13984 // change the loop to make a trip count go from could not compute to
13985 // computable or vice-versa *should have* invalidated SCEV. However, we
13986 // choose not to assert here (for now) since we don't want false
13987 // positives.
13988 continue;
13991 if (SE.getTypeSizeInBits(CurBECount->getType()) >
13992 SE.getTypeSizeInBits(NewBECount->getType()))
13993 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
13994 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
13995 SE.getTypeSizeInBits(NewBECount->getType()))
13996 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
13998 const SCEV *Delta = GetDelta(CurBECount, NewBECount);
13999 if (Delta && !Delta->isZero()) {
14000 dbgs() << "Trip Count for " << *L << " Changed!\n";
14001 dbgs() << "Old: " << *CurBECount << "\n";
14002 dbgs() << "New: " << *NewBECount << "\n";
14003 dbgs() << "Delta: " << *Delta << "\n";
14004 std::abort();
14008 // Collect all valid loops currently in LoopInfo.
14009 SmallPtrSet<Loop *, 32> ValidLoops;
14010 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
14011 while (!Worklist.empty()) {
14012 Loop *L = Worklist.pop_back_val();
14013 if (ValidLoops.insert(L).second)
14014 Worklist.append(L->begin(), L->end());
14016 for (const auto &KV : ValueExprMap) {
14017 #ifndef NDEBUG
14018 // Check for SCEV expressions referencing invalid/deleted loops.
14019 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14020 assert(ValidLoops.contains(AR->getLoop()) &&
14021 "AddRec references invalid loop");
14023 #endif
14025 // Check that the value is also part of the reverse map.
14026 auto It = ExprValueMap.find(KV.second);
14027 if (It == ExprValueMap.end() || !It->second.contains(KV.first)) {
14028 dbgs() << "Value " << *KV.first
14029 << " is in ValueExprMap but not in ExprValueMap\n";
14030 std::abort();
14033 if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
14034 if (!ReachableBlocks.contains(I->getParent()))
14035 continue;
14036 const SCEV *OldSCEV = SCM.visit(KV.second);
14037 const SCEV *NewSCEV = SE2.getSCEV(I);
14038 const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14039 if (Delta && !Delta->isZero()) {
14040 dbgs() << "SCEV for value " << *I << " changed!\n"
14041 << "Old: " << *OldSCEV << "\n"
14042 << "New: " << *NewSCEV << "\n"
14043 << "Delta: " << *Delta << "\n";
14044 std::abort();
14049 for (const auto &KV : ExprValueMap) {
14050 for (Value *V : KV.second) {
14051 auto It = ValueExprMap.find_as(V);
14052 if (It == ValueExprMap.end()) {
14053 dbgs() << "Value " << *V
14054 << " is in ExprValueMap but not in ValueExprMap\n";
14055 std::abort();
14057 if (It->second != KV.first) {
14058 dbgs() << "Value " << *V << " mapped to " << *It->second
14059 << " rather than " << *KV.first << "\n";
14060 std::abort();
14065 // Verify integrity of SCEV users.
14066 for (const auto &S : UniqueSCEVs) {
14067 for (const auto *Op : S.operands()) {
14068 // We do not store dependencies of constants.
14069 if (isa<SCEVConstant>(Op))
14070 continue;
14071 auto It = SCEVUsers.find(Op);
14072 if (It != SCEVUsers.end() && It->second.count(&S))
14073 continue;
14074 dbgs() << "Use of operand " << *Op << " by user " << S
14075 << " is not being tracked!\n";
14076 std::abort();
14080 // Verify integrity of ValuesAtScopes users.
14081 for (const auto &ValueAndVec : ValuesAtScopes) {
14082 const SCEV *Value = ValueAndVec.first;
14083 for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
14084 const Loop *L = LoopAndValueAtScope.first;
14085 const SCEV *ValueAtScope = LoopAndValueAtScope.second;
14086 if (!isa<SCEVConstant>(ValueAtScope)) {
14087 auto It = ValuesAtScopesUsers.find(ValueAtScope);
14088 if (It != ValuesAtScopesUsers.end() &&
14089 is_contained(It->second, std::make_pair(L, Value)))
14090 continue;
14091 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14092 << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
14093 std::abort();
14098 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
14099 const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
14100 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
14101 const Loop *L = LoopAndValue.first;
14102 const SCEV *Value = LoopAndValue.second;
14103 assert(!isa<SCEVConstant>(Value));
14104 auto It = ValuesAtScopes.find(Value);
14105 if (It != ValuesAtScopes.end() &&
14106 is_contained(It->second, std::make_pair(L, ValueAtScope)))
14107 continue;
14108 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14109 << *ValueAtScope << " missing in ValuesAtScopes\n";
14110 std::abort();
14114 // Verify integrity of BECountUsers.
14115 auto VerifyBECountUsers = [&](bool Predicated) {
14116 auto &BECounts =
14117 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14118 for (const auto &LoopAndBEInfo : BECounts) {
14119 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
14120 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14121 if (!isa<SCEVConstant>(S)) {
14122 auto UserIt = BECountUsers.find(S);
14123 if (UserIt != BECountUsers.end() &&
14124 UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
14125 continue;
14126 dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
14127 << " missing from BECountUsers\n";
14128 std::abort();
14134 VerifyBECountUsers(/* Predicated */ false);
14135 VerifyBECountUsers(/* Predicated */ true);
14137 // Verify intergity of loop disposition cache.
14138 for (auto &[S, Values] : LoopDispositions) {
14139 for (auto [Loop, CachedDisposition] : Values) {
14140 const auto RecomputedDisposition = SE2.getLoopDisposition(S, Loop);
14141 if (CachedDisposition != RecomputedDisposition) {
14142 dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
14143 << " is incorrect: cached " << CachedDisposition << ", actual "
14144 << RecomputedDisposition << "\n";
14145 std::abort();
14150 // Verify integrity of the block disposition cache.
14151 for (auto &[S, Values] : BlockDispositions) {
14152 for (auto [BB, CachedDisposition] : Values) {
14153 const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
14154 if (CachedDisposition != RecomputedDisposition) {
14155 dbgs() << "Cached disposition of " << *S << " for block %"
14156 << BB->getName() << " is incorrect: cached " << CachedDisposition
14157 << ", actual " << RecomputedDisposition << "\n";
14158 std::abort();
14163 // Verify FoldCache/FoldCacheUser caches.
14164 for (auto [FoldID, Expr] : FoldCache) {
14165 auto I = FoldCacheUser.find(Expr);
14166 if (I == FoldCacheUser.end()) {
14167 dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
14168 << "!\n";
14169 std::abort();
14171 if (!is_contained(I->second, FoldID)) {
14172 dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
14173 std::abort();
14176 for (auto [Expr, IDs] : FoldCacheUser) {
14177 for (auto &FoldID : IDs) {
14178 auto I = FoldCache.find(FoldID);
14179 if (I == FoldCache.end()) {
14180 dbgs() << "Missing entry in FoldCache for expression " << *Expr
14181 << "!\n";
14182 std::abort();
14184 if (I->second != Expr) {
14185 dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: "
14186 << *I->second << " != " << *Expr << "!\n";
14187 std::abort();
14192 // Verify that ConstantMultipleCache computations are correct. We check that
14193 // cached multiples and recomputed multiples are multiples of each other to
14194 // verify correctness. It is possible that a recomputed multiple is different
14195 // from the cached multiple due to strengthened no wrap flags or changes in
14196 // KnownBits computations.
14197 for (auto [S, Multiple] : ConstantMultipleCache) {
14198 APInt RecomputedMultiple = SE2.getConstantMultiple(S);
14199 if ((Multiple != 0 && RecomputedMultiple != 0 &&
14200 Multiple.urem(RecomputedMultiple) != 0 &&
14201 RecomputedMultiple.urem(Multiple) != 0)) {
14202 dbgs() << "Incorrect cached computation in ConstantMultipleCache for "
14203 << *S << " : Computed " << RecomputedMultiple
14204 << " but cache contains " << Multiple << "!\n";
14205 std::abort();
14210 bool ScalarEvolution::invalidate(
14211 Function &F, const PreservedAnalyses &PA,
14212 FunctionAnalysisManager::Invalidator &Inv) {
14213 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
14214 // of its dependencies is invalidated.
14215 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
14216 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
14217 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
14218 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
14219 Inv.invalidate<LoopAnalysis>(F, PA);
14222 AnalysisKey ScalarEvolutionAnalysis::Key;
14224 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
14225 FunctionAnalysisManager &AM) {
14226 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
14227 auto &AC = AM.getResult<AssumptionAnalysis>(F);
14228 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
14229 auto &LI = AM.getResult<LoopAnalysis>(F);
14230 return ScalarEvolution(F, TLI, AC, DT, LI);
14233 PreservedAnalyses
14234 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
14235 AM.getResult<ScalarEvolutionAnalysis>(F).verify();
14236 return PreservedAnalyses::all();
14239 PreservedAnalyses
14240 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
14241 // For compatibility with opt's -analyze feature under legacy pass manager
14242 // which was not ported to NPM. This keeps tests using
14243 // update_analyze_test_checks.py working.
14244 OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
14245 << F.getName() << "':\n";
14246 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
14247 return PreservedAnalyses::all();
14250 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
14251 "Scalar Evolution Analysis", false, true)
14252 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
14253 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
14254 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
14255 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
14256 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
14257 "Scalar Evolution Analysis", false, true)
14259 char ScalarEvolutionWrapperPass::ID = 0;
14261 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
14262 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
14265 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
14266 SE.reset(new ScalarEvolution(
14267 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
14268 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
14269 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
14270 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
14271 return false;
14274 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
14276 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
14277 SE->print(OS);
14280 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
14281 if (!VerifySCEV)
14282 return;
14284 SE->verify();
14287 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
14288 AU.setPreservesAll();
14289 AU.addRequiredTransitive<AssumptionCacheTracker>();
14290 AU.addRequiredTransitive<LoopInfoWrapperPass>();
14291 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
14292 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
14295 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
14296 const SCEV *RHS) {
14297 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
14300 const SCEVPredicate *
14301 ScalarEvolution::getComparePredicate(const ICmpInst::Predicate Pred,
14302 const SCEV *LHS, const SCEV *RHS) {
14303 FoldingSetNodeID ID;
14304 assert(LHS->getType() == RHS->getType() &&
14305 "Type mismatch between LHS and RHS");
14306 // Unique this node based on the arguments
14307 ID.AddInteger(SCEVPredicate::P_Compare);
14308 ID.AddInteger(Pred);
14309 ID.AddPointer(LHS);
14310 ID.AddPointer(RHS);
14311 void *IP = nullptr;
14312 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
14313 return S;
14314 SCEVComparePredicate *Eq = new (SCEVAllocator)
14315 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
14316 UniquePreds.InsertNode(Eq, IP);
14317 return Eq;
14320 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
14321 const SCEVAddRecExpr *AR,
14322 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
14323 FoldingSetNodeID ID;
14324 // Unique this node based on the arguments
14325 ID.AddInteger(SCEVPredicate::P_Wrap);
14326 ID.AddPointer(AR);
14327 ID.AddInteger(AddedFlags);
14328 void *IP = nullptr;
14329 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
14330 return S;
14331 auto *OF = new (SCEVAllocator)
14332 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
14333 UniquePreds.InsertNode(OF, IP);
14334 return OF;
14337 namespace {
14339 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
14340 public:
14342 /// Rewrites \p S in the context of a loop L and the SCEV predication
14343 /// infrastructure.
14345 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
14346 /// equivalences present in \p Pred.
14348 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
14349 /// \p NewPreds such that the result will be an AddRecExpr.
14350 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
14351 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
14352 const SCEVPredicate *Pred) {
14353 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
14354 return Rewriter.visit(S);
14357 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14358 if (Pred) {
14359 if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
14360 for (const auto *Pred : U->getPredicates())
14361 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
14362 if (IPred->getLHS() == Expr &&
14363 IPred->getPredicate() == ICmpInst::ICMP_EQ)
14364 return IPred->getRHS();
14365 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
14366 if (IPred->getLHS() == Expr &&
14367 IPred->getPredicate() == ICmpInst::ICMP_EQ)
14368 return IPred->getRHS();
14371 return convertToAddRecWithPreds(Expr);
14374 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
14375 const SCEV *Operand = visit(Expr->getOperand());
14376 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
14377 if (AR && AR->getLoop() == L && AR->isAffine()) {
14378 // This couldn't be folded because the operand didn't have the nuw
14379 // flag. Add the nusw flag as an assumption that we could make.
14380 const SCEV *Step = AR->getStepRecurrence(SE);
14381 Type *Ty = Expr->getType();
14382 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
14383 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
14384 SE.getSignExtendExpr(Step, Ty), L,
14385 AR->getNoWrapFlags());
14387 return SE.getZeroExtendExpr(Operand, Expr->getType());
14390 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
14391 const SCEV *Operand = visit(Expr->getOperand());
14392 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
14393 if (AR && AR->getLoop() == L && AR->isAffine()) {
14394 // This couldn't be folded because the operand didn't have the nsw
14395 // flag. Add the nssw flag as an assumption that we could make.
14396 const SCEV *Step = AR->getStepRecurrence(SE);
14397 Type *Ty = Expr->getType();
14398 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
14399 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
14400 SE.getSignExtendExpr(Step, Ty), L,
14401 AR->getNoWrapFlags());
14403 return SE.getSignExtendExpr(Operand, Expr->getType());
14406 private:
14407 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
14408 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
14409 const SCEVPredicate *Pred)
14410 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
14412 bool addOverflowAssumption(const SCEVPredicate *P) {
14413 if (!NewPreds) {
14414 // Check if we've already made this assumption.
14415 return Pred && Pred->implies(P);
14417 NewPreds->insert(P);
14418 return true;
14421 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
14422 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
14423 auto *A = SE.getWrapPredicate(AR, AddedFlags);
14424 return addOverflowAssumption(A);
14427 // If \p Expr represents a PHINode, we try to see if it can be represented
14428 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
14429 // to add this predicate as a runtime overflow check, we return the AddRec.
14430 // If \p Expr does not meet these conditions (is not a PHI node, or we
14431 // couldn't create an AddRec for it, or couldn't add the predicate), we just
14432 // return \p Expr.
14433 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
14434 if (!isa<PHINode>(Expr->getValue()))
14435 return Expr;
14436 std::optional<
14437 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
14438 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
14439 if (!PredicatedRewrite)
14440 return Expr;
14441 for (const auto *P : PredicatedRewrite->second){
14442 // Wrap predicates from outer loops are not supported.
14443 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
14444 if (L != WP->getExpr()->getLoop())
14445 return Expr;
14447 if (!addOverflowAssumption(P))
14448 return Expr;
14450 return PredicatedRewrite->first;
14453 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
14454 const SCEVPredicate *Pred;
14455 const Loop *L;
14458 } // end anonymous namespace
14460 const SCEV *
14461 ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
14462 const SCEVPredicate &Preds) {
14463 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
14466 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
14467 const SCEV *S, const Loop *L,
14468 SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
14469 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
14470 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
14471 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
14473 if (!AddRec)
14474 return nullptr;
14476 // Since the transformation was successful, we can now transfer the SCEV
14477 // predicates.
14478 for (const auto *P : TransformPreds)
14479 Preds.insert(P);
14481 return AddRec;
14484 /// SCEV predicates
14485 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
14486 SCEVPredicateKind Kind)
14487 : FastID(ID), Kind(Kind) {}
14489 SCEVComparePredicate::SCEVComparePredicate(const FoldingSetNodeIDRef ID,
14490 const ICmpInst::Predicate Pred,
14491 const SCEV *LHS, const SCEV *RHS)
14492 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
14493 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
14494 assert(LHS != RHS && "LHS and RHS are the same SCEV");
14497 bool SCEVComparePredicate::implies(const SCEVPredicate *N) const {
14498 const auto *Op = dyn_cast<SCEVComparePredicate>(N);
14500 if (!Op)
14501 return false;
14503 if (Pred != ICmpInst::ICMP_EQ)
14504 return false;
14506 return Op->LHS == LHS && Op->RHS == RHS;
14509 bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
14511 void SCEVComparePredicate::print(raw_ostream &OS, unsigned Depth) const {
14512 if (Pred == ICmpInst::ICMP_EQ)
14513 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
14514 else
14515 OS.indent(Depth) << "Compare predicate: " << *LHS << " " << Pred << ") "
14516 << *RHS << "\n";
14520 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
14521 const SCEVAddRecExpr *AR,
14522 IncrementWrapFlags Flags)
14523 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
14525 const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
14527 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
14528 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
14530 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
14533 bool SCEVWrapPredicate::isAlwaysTrue() const {
14534 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
14535 IncrementWrapFlags IFlags = Flags;
14537 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
14538 IFlags = clearFlags(IFlags, IncrementNSSW);
14540 return IFlags == IncrementAnyWrap;
14543 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
14544 OS.indent(Depth) << *getExpr() << " Added Flags: ";
14545 if (SCEVWrapPredicate::IncrementNUSW & getFlags())
14546 OS << "<nusw>";
14547 if (SCEVWrapPredicate::IncrementNSSW & getFlags())
14548 OS << "<nssw>";
14549 OS << "\n";
14552 SCEVWrapPredicate::IncrementWrapFlags
14553 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
14554 ScalarEvolution &SE) {
14555 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
14556 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
14558 // We can safely transfer the NSW flag as NSSW.
14559 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
14560 ImpliedFlags = IncrementNSSW;
14562 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
14563 // If the increment is positive, the SCEV NUW flag will also imply the
14564 // WrapPredicate NUSW flag.
14565 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
14566 if (Step->getValue()->getValue().isNonNegative())
14567 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
14570 return ImpliedFlags;
14573 /// Union predicates don't get cached so create a dummy set ID for it.
14574 SCEVUnionPredicate::SCEVUnionPredicate(ArrayRef<const SCEVPredicate *> Preds)
14575 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {
14576 for (const auto *P : Preds)
14577 add(P);
14580 bool SCEVUnionPredicate::isAlwaysTrue() const {
14581 return all_of(Preds,
14582 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
14585 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
14586 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
14587 return all_of(Set->Preds,
14588 [this](const SCEVPredicate *I) { return this->implies(I); });
14590 return any_of(Preds,
14591 [N](const SCEVPredicate *I) { return I->implies(N); });
14594 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
14595 for (const auto *Pred : Preds)
14596 Pred->print(OS, Depth);
14599 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
14600 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
14601 for (const auto *Pred : Set->Preds)
14602 add(Pred);
14603 return;
14606 Preds.push_back(N);
14609 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
14610 Loop &L)
14611 : SE(SE), L(L) {
14612 SmallVector<const SCEVPredicate*, 4> Empty;
14613 Preds = std::make_unique<SCEVUnionPredicate>(Empty);
14616 void ScalarEvolution::registerUser(const SCEV *User,
14617 ArrayRef<const SCEV *> Ops) {
14618 for (const auto *Op : Ops)
14619 // We do not expect that forgetting cached data for SCEVConstants will ever
14620 // open any prospects for sharpening or introduce any correctness issues,
14621 // so we don't bother storing their dependencies.
14622 if (!isa<SCEVConstant>(Op))
14623 SCEVUsers[Op].insert(User);
14626 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
14627 const SCEV *Expr = SE.getSCEV(V);
14628 RewriteEntry &Entry = RewriteMap[Expr];
14630 // If we already have an entry and the version matches, return it.
14631 if (Entry.second && Generation == Entry.first)
14632 return Entry.second;
14634 // We found an entry but it's stale. Rewrite the stale entry
14635 // according to the current predicate.
14636 if (Entry.second)
14637 Expr = Entry.second;
14639 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
14640 Entry = {Generation, NewSCEV};
14642 return NewSCEV;
14645 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
14646 if (!BackedgeCount) {
14647 SmallVector<const SCEVPredicate *, 4> Preds;
14648 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
14649 for (const auto *P : Preds)
14650 addPredicate(*P);
14652 return BackedgeCount;
14655 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
14656 if (Preds->implies(&Pred))
14657 return;
14659 auto &OldPreds = Preds->getPredicates();
14660 SmallVector<const SCEVPredicate*, 4> NewPreds(OldPreds.begin(), OldPreds.end());
14661 NewPreds.push_back(&Pred);
14662 Preds = std::make_unique<SCEVUnionPredicate>(NewPreds);
14663 updateGeneration();
14666 const SCEVPredicate &PredicatedScalarEvolution::getPredicate() const {
14667 return *Preds;
14670 void PredicatedScalarEvolution::updateGeneration() {
14671 // If the generation number wrapped recompute everything.
14672 if (++Generation == 0) {
14673 for (auto &II : RewriteMap) {
14674 const SCEV *Rewritten = II.second.second;
14675 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
14680 void PredicatedScalarEvolution::setNoOverflow(
14681 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
14682 const SCEV *Expr = getSCEV(V);
14683 const auto *AR = cast<SCEVAddRecExpr>(Expr);
14685 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
14687 // Clear the statically implied flags.
14688 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
14689 addPredicate(*SE.getWrapPredicate(AR, Flags));
14691 auto II = FlagsMap.insert({V, Flags});
14692 if (!II.second)
14693 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
14696 bool PredicatedScalarEvolution::hasNoOverflow(
14697 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
14698 const SCEV *Expr = getSCEV(V);
14699 const auto *AR = cast<SCEVAddRecExpr>(Expr);
14701 Flags = SCEVWrapPredicate::clearFlags(
14702 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
14704 auto II = FlagsMap.find(V);
14706 if (II != FlagsMap.end())
14707 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
14709 return Flags == SCEVWrapPredicate::IncrementAnyWrap;
14712 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
14713 const SCEV *Expr = this->getSCEV(V);
14714 SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
14715 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
14717 if (!New)
14718 return nullptr;
14720 for (const auto *P : NewPreds)
14721 addPredicate(*P);
14723 RewriteMap[SE.getSCEV(V)] = {Generation, New};
14724 return New;
14727 PredicatedScalarEvolution::PredicatedScalarEvolution(
14728 const PredicatedScalarEvolution &Init)
14729 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
14730 Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates())),
14731 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
14732 for (auto I : Init.FlagsMap)
14733 FlagsMap.insert(I);
14736 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
14737 // For each block.
14738 for (auto *BB : L.getBlocks())
14739 for (auto &I : *BB) {
14740 if (!SE.isSCEVable(I.getType()))
14741 continue;
14743 auto *Expr = SE.getSCEV(&I);
14744 auto II = RewriteMap.find(Expr);
14746 if (II == RewriteMap.end())
14747 continue;
14749 // Don't print things that are not interesting.
14750 if (II->second.second == Expr)
14751 continue;
14753 OS.indent(Depth) << "[PSE]" << I << ":\n";
14754 OS.indent(Depth + 2) << *Expr << "\n";
14755 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
14759 // Match the mathematical pattern A - (A / B) * B, where A and B can be
14760 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
14761 // for URem with constant power-of-2 second operands.
14762 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
14763 // 4, A / B becomes X / 8).
14764 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
14765 const SCEV *&RHS) {
14766 // Try to match 'zext (trunc A to iB) to iY', which is used
14767 // for URem with constant power-of-2 second operands. Make sure the size of
14768 // the operand A matches the size of the whole expressions.
14769 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
14770 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
14771 LHS = Trunc->getOperand();
14772 // Bail out if the type of the LHS is larger than the type of the
14773 // expression for now.
14774 if (getTypeSizeInBits(LHS->getType()) >
14775 getTypeSizeInBits(Expr->getType()))
14776 return false;
14777 if (LHS->getType() != Expr->getType())
14778 LHS = getZeroExtendExpr(LHS, Expr->getType());
14779 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
14780 << getTypeSizeInBits(Trunc->getType()));
14781 return true;
14783 const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
14784 if (Add == nullptr || Add->getNumOperands() != 2)
14785 return false;
14787 const SCEV *A = Add->getOperand(1);
14788 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
14790 if (Mul == nullptr)
14791 return false;
14793 const auto MatchURemWithDivisor = [&](const SCEV *B) {
14794 // (SomeExpr + (-(SomeExpr / B) * B)).
14795 if (Expr == getURemExpr(A, B)) {
14796 LHS = A;
14797 RHS = B;
14798 return true;
14800 return false;
14803 // (SomeExpr + (-1 * (SomeExpr / B) * B)).
14804 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
14805 return MatchURemWithDivisor(Mul->getOperand(1)) ||
14806 MatchURemWithDivisor(Mul->getOperand(2));
14808 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
14809 if (Mul->getNumOperands() == 2)
14810 return MatchURemWithDivisor(Mul->getOperand(1)) ||
14811 MatchURemWithDivisor(Mul->getOperand(0)) ||
14812 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
14813 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
14814 return false;
14817 const SCEV *
14818 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
14819 SmallVector<BasicBlock*, 16> ExitingBlocks;
14820 L->getExitingBlocks(ExitingBlocks);
14822 // Form an expression for the maximum exit count possible for this loop. We
14823 // merge the max and exact information to approximate a version of
14824 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
14825 SmallVector<const SCEV*, 4> ExitCounts;
14826 for (BasicBlock *ExitingBB : ExitingBlocks) {
14827 const SCEV *ExitCount =
14828 getExitCount(L, ExitingBB, ScalarEvolution::SymbolicMaximum);
14829 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
14830 assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
14831 "We should only have known counts for exiting blocks that "
14832 "dominate latch!");
14833 ExitCounts.push_back(ExitCount);
14836 if (ExitCounts.empty())
14837 return getCouldNotCompute();
14838 return getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
14841 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
14842 /// in the map. It skips AddRecExpr because we cannot guarantee that the
14843 /// replacement is loop invariant in the loop of the AddRec.
14844 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
14845 const DenseMap<const SCEV *, const SCEV *> &Map;
14847 public:
14848 SCEVLoopGuardRewriter(ScalarEvolution &SE,
14849 DenseMap<const SCEV *, const SCEV *> &M)
14850 : SCEVRewriteVisitor(SE), Map(M) {}
14852 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
14854 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14855 auto I = Map.find(Expr);
14856 if (I == Map.end())
14857 return Expr;
14858 return I->second;
14861 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
14862 auto I = Map.find(Expr);
14863 if (I == Map.end()) {
14864 // If we didn't find the extact ZExt expr in the map, check if there's an
14865 // entry for a smaller ZExt we can use instead.
14866 Type *Ty = Expr->getType();
14867 const SCEV *Op = Expr->getOperand(0);
14868 unsigned Bitwidth = Ty->getScalarSizeInBits() / 2;
14869 while (Bitwidth % 8 == 0 && Bitwidth >= 8 &&
14870 Bitwidth > Op->getType()->getScalarSizeInBits()) {
14871 Type *NarrowTy = IntegerType::get(SE.getContext(), Bitwidth);
14872 auto *NarrowExt = SE.getZeroExtendExpr(Op, NarrowTy);
14873 auto I = Map.find(NarrowExt);
14874 if (I != Map.end())
14875 return SE.getZeroExtendExpr(I->second, Ty);
14876 Bitwidth = Bitwidth / 2;
14879 return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitZeroExtendExpr(
14880 Expr);
14882 return I->second;
14885 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
14886 auto I = Map.find(Expr);
14887 if (I == Map.end())
14888 return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitSignExtendExpr(
14889 Expr);
14890 return I->second;
14893 const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
14894 auto I = Map.find(Expr);
14895 if (I == Map.end())
14896 return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitUMinExpr(Expr);
14897 return I->second;
14900 const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
14901 auto I = Map.find(Expr);
14902 if (I == Map.end())
14903 return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitSMinExpr(Expr);
14904 return I->second;
14908 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
14909 SmallVector<const SCEV *> ExprsToRewrite;
14910 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
14911 const SCEV *RHS,
14912 DenseMap<const SCEV *, const SCEV *>
14913 &RewriteMap) {
14914 // WARNING: It is generally unsound to apply any wrap flags to the proposed
14915 // replacement SCEV which isn't directly implied by the structure of that
14916 // SCEV. In particular, using contextual facts to imply flags is *NOT*
14917 // legal. See the scoping rules for flags in the header to understand why.
14919 // If LHS is a constant, apply information to the other expression.
14920 if (isa<SCEVConstant>(LHS)) {
14921 std::swap(LHS, RHS);
14922 Predicate = CmpInst::getSwappedPredicate(Predicate);
14925 // Check for a condition of the form (-C1 + X < C2). InstCombine will
14926 // create this form when combining two checks of the form (X u< C2 + C1) and
14927 // (X >=u C1).
14928 auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap,
14929 &ExprsToRewrite]() {
14930 auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS);
14931 if (!AddExpr || AddExpr->getNumOperands() != 2)
14932 return false;
14934 auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0));
14935 auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1));
14936 auto *C2 = dyn_cast<SCEVConstant>(RHS);
14937 if (!C1 || !C2 || !LHSUnknown)
14938 return false;
14940 auto ExactRegion =
14941 ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt())
14942 .sub(C1->getAPInt());
14944 // Bail out, unless we have a non-wrapping, monotonic range.
14945 if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet())
14946 return false;
14947 auto I = RewriteMap.find(LHSUnknown);
14948 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown;
14949 RewriteMap[LHSUnknown] = getUMaxExpr(
14950 getConstant(ExactRegion.getUnsignedMin()),
14951 getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax())));
14952 ExprsToRewrite.push_back(LHSUnknown);
14953 return true;
14955 if (MatchRangeCheckIdiom())
14956 return;
14958 // Return true if \p Expr is a MinMax SCEV expression with a non-negative
14959 // constant operand. If so, return in \p SCTy the SCEV type and in \p RHS
14960 // the non-constant operand and in \p LHS the constant operand.
14961 auto IsMinMaxSCEVWithNonNegativeConstant =
14962 [&](const SCEV *Expr, SCEVTypes &SCTy, const SCEV *&LHS,
14963 const SCEV *&RHS) {
14964 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr)) {
14965 if (MinMax->getNumOperands() != 2)
14966 return false;
14967 if (auto *C = dyn_cast<SCEVConstant>(MinMax->getOperand(0))) {
14968 if (C->getAPInt().isNegative())
14969 return false;
14970 SCTy = MinMax->getSCEVType();
14971 LHS = MinMax->getOperand(0);
14972 RHS = MinMax->getOperand(1);
14973 return true;
14976 return false;
14979 // Checks whether Expr is a non-negative constant, and Divisor is a positive
14980 // constant, and returns their APInt in ExprVal and in DivisorVal.
14981 auto GetNonNegExprAndPosDivisor = [&](const SCEV *Expr, const SCEV *Divisor,
14982 APInt &ExprVal, APInt &DivisorVal) {
14983 auto *ConstExpr = dyn_cast<SCEVConstant>(Expr);
14984 auto *ConstDivisor = dyn_cast<SCEVConstant>(Divisor);
14985 if (!ConstExpr || !ConstDivisor)
14986 return false;
14987 ExprVal = ConstExpr->getAPInt();
14988 DivisorVal = ConstDivisor->getAPInt();
14989 return ExprVal.isNonNegative() && !DivisorVal.isNonPositive();
14992 // Return a new SCEV that modifies \p Expr to the closest number divides by
14993 // \p Divisor and greater or equal than Expr.
14994 // For now, only handle constant Expr and Divisor.
14995 auto GetNextSCEVDividesByDivisor = [&](const SCEV *Expr,
14996 const SCEV *Divisor) {
14997 APInt ExprVal;
14998 APInt DivisorVal;
14999 if (!GetNonNegExprAndPosDivisor(Expr, Divisor, ExprVal, DivisorVal))
15000 return Expr;
15001 APInt Rem = ExprVal.urem(DivisorVal);
15002 if (!Rem.isZero())
15003 // return the SCEV: Expr + Divisor - Expr % Divisor
15004 return getConstant(ExprVal + DivisorVal - Rem);
15005 return Expr;
15008 // Return a new SCEV that modifies \p Expr to the closest number divides by
15009 // \p Divisor and less or equal than Expr.
15010 // For now, only handle constant Expr and Divisor.
15011 auto GetPreviousSCEVDividesByDivisor = [&](const SCEV *Expr,
15012 const SCEV *Divisor) {
15013 APInt ExprVal;
15014 APInt DivisorVal;
15015 if (!GetNonNegExprAndPosDivisor(Expr, Divisor, ExprVal, DivisorVal))
15016 return Expr;
15017 APInt Rem = ExprVal.urem(DivisorVal);
15018 // return the SCEV: Expr - Expr % Divisor
15019 return getConstant(ExprVal - Rem);
15022 // Apply divisibilty by \p Divisor on MinMaxExpr with constant values,
15023 // recursively. This is done by aligning up/down the constant value to the
15024 // Divisor.
15025 std::function<const SCEV *(const SCEV *, const SCEV *)>
15026 ApplyDivisibiltyOnMinMaxExpr = [&](const SCEV *MinMaxExpr,
15027 const SCEV *Divisor) {
15028 const SCEV *MinMaxLHS = nullptr, *MinMaxRHS = nullptr;
15029 SCEVTypes SCTy;
15030 if (!IsMinMaxSCEVWithNonNegativeConstant(MinMaxExpr, SCTy, MinMaxLHS,
15031 MinMaxRHS))
15032 return MinMaxExpr;
15033 auto IsMin =
15034 isa<SCEVSMinExpr>(MinMaxExpr) || isa<SCEVUMinExpr>(MinMaxExpr);
15035 assert(isKnownNonNegative(MinMaxLHS) &&
15036 "Expected non-negative operand!");
15037 auto *DivisibleExpr =
15038 IsMin ? GetPreviousSCEVDividesByDivisor(MinMaxLHS, Divisor)
15039 : GetNextSCEVDividesByDivisor(MinMaxLHS, Divisor);
15040 SmallVector<const SCEV *> Ops = {
15041 ApplyDivisibiltyOnMinMaxExpr(MinMaxRHS, Divisor), DivisibleExpr};
15042 return getMinMaxExpr(SCTy, Ops);
15045 // If we have LHS == 0, check if LHS is computing a property of some unknown
15046 // SCEV %v which we can rewrite %v to express explicitly.
15047 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
15048 if (Predicate == CmpInst::ICMP_EQ && RHSC &&
15049 RHSC->getValue()->isNullValue()) {
15050 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
15051 // explicitly express that.
15052 const SCEV *URemLHS = nullptr;
15053 const SCEV *URemRHS = nullptr;
15054 if (matchURem(LHS, URemLHS, URemRHS)) {
15055 if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) {
15056 auto I = RewriteMap.find(LHSUnknown);
15057 const SCEV *RewrittenLHS =
15058 I != RewriteMap.end() ? I->second : LHSUnknown;
15059 RewrittenLHS = ApplyDivisibiltyOnMinMaxExpr(RewrittenLHS, URemRHS);
15060 const auto *Multiple =
15061 getMulExpr(getUDivExpr(RewrittenLHS, URemRHS), URemRHS);
15062 RewriteMap[LHSUnknown] = Multiple;
15063 ExprsToRewrite.push_back(LHSUnknown);
15064 return;
15069 // Do not apply information for constants or if RHS contains an AddRec.
15070 if (isa<SCEVConstant>(LHS) || containsAddRecurrence(RHS))
15071 return;
15073 // If RHS is SCEVUnknown, make sure the information is applied to it.
15074 if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) {
15075 std::swap(LHS, RHS);
15076 Predicate = CmpInst::getSwappedPredicate(Predicate);
15079 // Puts rewrite rule \p From -> \p To into the rewrite map. Also if \p From
15080 // and \p FromRewritten are the same (i.e. there has been no rewrite
15081 // registered for \p From), then puts this value in the list of rewritten
15082 // expressions.
15083 auto AddRewrite = [&](const SCEV *From, const SCEV *FromRewritten,
15084 const SCEV *To) {
15085 if (From == FromRewritten)
15086 ExprsToRewrite.push_back(From);
15087 RewriteMap[From] = To;
15090 // Checks whether \p S has already been rewritten. In that case returns the
15091 // existing rewrite because we want to chain further rewrites onto the
15092 // already rewritten value. Otherwise returns \p S.
15093 auto GetMaybeRewritten = [&](const SCEV *S) {
15094 auto I = RewriteMap.find(S);
15095 return I != RewriteMap.end() ? I->second : S;
15098 // Check for the SCEV expression (A /u B) * B while B is a constant, inside
15099 // \p Expr. The check is done recuresively on \p Expr, which is assumed to
15100 // be a composition of Min/Max SCEVs. Return whether the SCEV expression (A
15101 // /u B) * B was found, and return the divisor B in \p DividesBy. For
15102 // example, if Expr = umin (umax ((A /u 8) * 8, 16), 64), return true since
15103 // (A /u 8) * 8 matched the pattern, and return the constant SCEV 8 in \p
15104 // DividesBy.
15105 std::function<bool(const SCEV *, const SCEV *&)> HasDivisibiltyInfo =
15106 [&](const SCEV *Expr, const SCEV *&DividesBy) {
15107 if (auto *Mul = dyn_cast<SCEVMulExpr>(Expr)) {
15108 if (Mul->getNumOperands() != 2)
15109 return false;
15110 auto *MulLHS = Mul->getOperand(0);
15111 auto *MulRHS = Mul->getOperand(1);
15112 if (isa<SCEVConstant>(MulLHS))
15113 std::swap(MulLHS, MulRHS);
15114 if (auto *Div = dyn_cast<SCEVUDivExpr>(MulLHS))
15115 if (Div->getOperand(1) == MulRHS) {
15116 DividesBy = MulRHS;
15117 return true;
15120 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr))
15121 return HasDivisibiltyInfo(MinMax->getOperand(0), DividesBy) ||
15122 HasDivisibiltyInfo(MinMax->getOperand(1), DividesBy);
15123 return false;
15126 // Return true if Expr known to divide by \p DividesBy.
15127 std::function<bool(const SCEV *, const SCEV *&)> IsKnownToDivideBy =
15128 [&](const SCEV *Expr, const SCEV *DividesBy) {
15129 if (getURemExpr(Expr, DividesBy)->isZero())
15130 return true;
15131 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr))
15132 return IsKnownToDivideBy(MinMax->getOperand(0), DividesBy) &&
15133 IsKnownToDivideBy(MinMax->getOperand(1), DividesBy);
15134 return false;
15137 const SCEV *RewrittenLHS = GetMaybeRewritten(LHS);
15138 const SCEV *DividesBy = nullptr;
15139 if (HasDivisibiltyInfo(RewrittenLHS, DividesBy))
15140 // Check that the whole expression is divided by DividesBy
15141 DividesBy =
15142 IsKnownToDivideBy(RewrittenLHS, DividesBy) ? DividesBy : nullptr;
15144 // Collect rewrites for LHS and its transitive operands based on the
15145 // condition.
15146 // For min/max expressions, also apply the guard to its operands:
15147 // 'min(a, b) >= c' -> '(a >= c) and (b >= c)',
15148 // 'min(a, b) > c' -> '(a > c) and (b > c)',
15149 // 'max(a, b) <= c' -> '(a <= c) and (b <= c)',
15150 // 'max(a, b) < c' -> '(a < c) and (b < c)'.
15152 // We cannot express strict predicates in SCEV, so instead we replace them
15153 // with non-strict ones against plus or minus one of RHS depending on the
15154 // predicate.
15155 const SCEV *One = getOne(RHS->getType());
15156 switch (Predicate) {
15157 case CmpInst::ICMP_ULT:
15158 if (RHS->getType()->isPointerTy())
15159 return;
15160 RHS = getUMaxExpr(RHS, One);
15161 [[fallthrough]];
15162 case CmpInst::ICMP_SLT: {
15163 RHS = getMinusSCEV(RHS, One);
15164 RHS = DividesBy ? GetPreviousSCEVDividesByDivisor(RHS, DividesBy) : RHS;
15165 break;
15167 case CmpInst::ICMP_UGT:
15168 case CmpInst::ICMP_SGT:
15169 RHS = getAddExpr(RHS, One);
15170 RHS = DividesBy ? GetNextSCEVDividesByDivisor(RHS, DividesBy) : RHS;
15171 break;
15172 case CmpInst::ICMP_ULE:
15173 case CmpInst::ICMP_SLE:
15174 RHS = DividesBy ? GetPreviousSCEVDividesByDivisor(RHS, DividesBy) : RHS;
15175 break;
15176 case CmpInst::ICMP_UGE:
15177 case CmpInst::ICMP_SGE:
15178 RHS = DividesBy ? GetNextSCEVDividesByDivisor(RHS, DividesBy) : RHS;
15179 break;
15180 default:
15181 break;
15184 SmallVector<const SCEV *, 16> Worklist(1, LHS);
15185 SmallPtrSet<const SCEV *, 16> Visited;
15187 auto EnqueueOperands = [&Worklist](const SCEVNAryExpr *S) {
15188 append_range(Worklist, S->operands());
15191 while (!Worklist.empty()) {
15192 const SCEV *From = Worklist.pop_back_val();
15193 if (isa<SCEVConstant>(From))
15194 continue;
15195 if (!Visited.insert(From).second)
15196 continue;
15197 const SCEV *FromRewritten = GetMaybeRewritten(From);
15198 const SCEV *To = nullptr;
15200 switch (Predicate) {
15201 case CmpInst::ICMP_ULT:
15202 case CmpInst::ICMP_ULE:
15203 To = getUMinExpr(FromRewritten, RHS);
15204 if (auto *UMax = dyn_cast<SCEVUMaxExpr>(FromRewritten))
15205 EnqueueOperands(UMax);
15206 break;
15207 case CmpInst::ICMP_SLT:
15208 case CmpInst::ICMP_SLE:
15209 To = getSMinExpr(FromRewritten, RHS);
15210 if (auto *SMax = dyn_cast<SCEVSMaxExpr>(FromRewritten))
15211 EnqueueOperands(SMax);
15212 break;
15213 case CmpInst::ICMP_UGT:
15214 case CmpInst::ICMP_UGE:
15215 To = getUMaxExpr(FromRewritten, RHS);
15216 if (auto *UMin = dyn_cast<SCEVUMinExpr>(FromRewritten))
15217 EnqueueOperands(UMin);
15218 break;
15219 case CmpInst::ICMP_SGT:
15220 case CmpInst::ICMP_SGE:
15221 To = getSMaxExpr(FromRewritten, RHS);
15222 if (auto *SMin = dyn_cast<SCEVSMinExpr>(FromRewritten))
15223 EnqueueOperands(SMin);
15224 break;
15225 case CmpInst::ICMP_EQ:
15226 if (isa<SCEVConstant>(RHS))
15227 To = RHS;
15228 break;
15229 case CmpInst::ICMP_NE:
15230 if (isa<SCEVConstant>(RHS) &&
15231 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) {
15232 const SCEV *OneAlignedUp =
15233 DividesBy ? GetNextSCEVDividesByDivisor(One, DividesBy) : One;
15234 To = getUMaxExpr(FromRewritten, OneAlignedUp);
15236 break;
15237 default:
15238 break;
15241 if (To)
15242 AddRewrite(From, FromRewritten, To);
15246 BasicBlock *Header = L->getHeader();
15247 SmallVector<PointerIntPair<Value *, 1, bool>> Terms;
15248 // First, collect information from assumptions dominating the loop.
15249 for (auto &AssumeVH : AC.assumptions()) {
15250 if (!AssumeVH)
15251 continue;
15252 auto *AssumeI = cast<CallInst>(AssumeVH);
15253 if (!DT.dominates(AssumeI, Header))
15254 continue;
15255 Terms.emplace_back(AssumeI->getOperand(0), true);
15258 // Second, collect information from llvm.experimental.guards dominating the loop.
15259 auto *GuardDecl = F.getParent()->getFunction(
15260 Intrinsic::getName(Intrinsic::experimental_guard));
15261 if (GuardDecl)
15262 for (const auto *GU : GuardDecl->users())
15263 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
15264 if (Guard->getFunction() == Header->getParent() && DT.dominates(Guard, Header))
15265 Terms.emplace_back(Guard->getArgOperand(0), true);
15267 // Third, collect conditions from dominating branches. Starting at the loop
15268 // predecessor, climb up the predecessor chain, as long as there are
15269 // predecessors that can be found that have unique successors leading to the
15270 // original header.
15271 // TODO: share this logic with isLoopEntryGuardedByCond.
15272 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
15273 L->getLoopPredecessor(), Header);
15274 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
15276 const BranchInst *LoopEntryPredicate =
15277 dyn_cast<BranchInst>(Pair.first->getTerminator());
15278 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
15279 continue;
15281 Terms.emplace_back(LoopEntryPredicate->getCondition(),
15282 LoopEntryPredicate->getSuccessor(0) == Pair.second);
15285 // Now apply the information from the collected conditions to RewriteMap.
15286 // Conditions are processed in reverse order, so the earliest conditions is
15287 // processed first. This ensures the SCEVs with the shortest dependency chains
15288 // are constructed first.
15289 DenseMap<const SCEV *, const SCEV *> RewriteMap;
15290 for (auto [Term, EnterIfTrue] : reverse(Terms)) {
15291 SmallVector<Value *, 8> Worklist;
15292 SmallPtrSet<Value *, 8> Visited;
15293 Worklist.push_back(Term);
15294 while (!Worklist.empty()) {
15295 Value *Cond = Worklist.pop_back_val();
15296 if (!Visited.insert(Cond).second)
15297 continue;
15299 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
15300 auto Predicate =
15301 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
15302 const auto *LHS = getSCEV(Cmp->getOperand(0));
15303 const auto *RHS = getSCEV(Cmp->getOperand(1));
15304 CollectCondition(Predicate, LHS, RHS, RewriteMap);
15305 continue;
15308 Value *L, *R;
15309 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
15310 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
15311 Worklist.push_back(L);
15312 Worklist.push_back(R);
15317 if (RewriteMap.empty())
15318 return Expr;
15320 // Now that all rewrite information is collect, rewrite the collected
15321 // expressions with the information in the map. This applies information to
15322 // sub-expressions.
15323 if (ExprsToRewrite.size() > 1) {
15324 for (const SCEV *Expr : ExprsToRewrite) {
15325 const SCEV *RewriteTo = RewriteMap[Expr];
15326 RewriteMap.erase(Expr);
15327 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
15328 RewriteMap.insert({Expr, Rewriter.visit(RewriteTo)});
15332 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
15333 return Rewriter.visit(Expr);