LLVM 18.0.0git
ScalarEvolution.cpp
Go to the documentation of this file.
1//===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the implementation of the scalar evolution analysis
10// engine, which is used primarily to analyze expressions involving induction
11// variables in loops.
12//
13// There are several aspects to this library. First is the representation of
14// scalar expressions, which are represented as subclasses of the SCEV class.
15// These classes are used to represent certain types of subexpressions that we
16// can handle. We only create one SCEV of a particular shape, so
17// pointer-comparisons for equality are legal.
18//
19// One important aspect of the SCEV objects is that they are never cyclic, even
20// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
21// the PHI node is one of the idioms that we can represent (e.g., a polynomial
22// recurrence) then we represent it directly as a recurrence node, otherwise we
23// represent it as a SCEVUnknown node.
24//
25// In addition to being able to represent expressions of various types, we also
26// have folders that are used to build the *canonical* representation for a
27// particular expression. These folders are capable of using a variety of
28// rewrite rules to simplify the expressions.
29//
30// Once the folders are defined, we can implement the more interesting
31// higher-level code, such as the code that recognizes PHI nodes of various
32// types, computes the execution count of a loop, etc.
33//
34// TODO: We should use these routines and value representations to implement
35// dependence analysis!
36//
37//===----------------------------------------------------------------------===//
38//
39// There are several good references for the techniques used in this analysis.
40//
41// Chains of recurrences -- a method to expedite the evaluation
42// of closed-form functions
43// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
44//
45// On computational properties of chains of recurrences
46// Eugene V. Zima
47//
48// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
49// Robert A. van Engelen
50//
51// Efficient Symbolic Analysis for Optimizing Compilers
52// Robert A. van Engelen
53//
54// Using the chains of recurrences algebra for data dependence testing and
55// induction variable substitution
56// MS Thesis, Johnie Birch
57//
58//===----------------------------------------------------------------------===//
59
61#include "llvm/ADT/APInt.h"
62#include "llvm/ADT/ArrayRef.h"
63#include "llvm/ADT/DenseMap.h"
66#include "llvm/ADT/FoldingSet.h"
67#include "llvm/ADT/STLExtras.h"
68#include "llvm/ADT/ScopeExit.h"
69#include "llvm/ADT/Sequence.h"
71#include "llvm/ADT/SmallSet.h"
73#include "llvm/ADT/Statistic.h"
75#include "llvm/ADT/StringRef.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"
90#include "llvm/IR/Constants.h"
91#include "llvm/IR/DataLayout.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"
98#include "llvm/IR/InstrTypes.h"
99#include "llvm/IR/Instruction.h"
100#include "llvm/IR/Instructions.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"
112#include "llvm/Pass.h"
113#include "llvm/Support/Casting.h"
116#include "llvm/Support/Debug.h"
121#include <algorithm>
122#include <cassert>
123#include <climits>
124#include <cstdint>
125#include <cstdlib>
126#include <map>
127#include <memory>
128#include <numeric>
129#include <optional>
130#include <tuple>
131#include <utility>
132#include <vector>
133
134using namespace llvm;
135using namespace PatternMatch;
136
137#define DEBUG_TYPE "scalar-evolution"
138
139STATISTIC(NumExitCountsComputed,
140 "Number of loop exits with predictable exit counts");
141STATISTIC(NumExitCountsNotComputed,
142 "Number of loop exits without predictable exit counts");
143STATISTIC(NumBruteForceTripCountsComputed,
144 "Number of loops with trip counts computed by force");
145
146#ifdef EXPENSIVE_CHECKS
147bool llvm::VerifySCEV = true;
148#else
149bool llvm::VerifySCEV = false;
150#endif
151
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));
158
160 "verify-scev", cl::Hidden, cl::location(VerifySCEV),
161 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
163 "verify-scev-strict", cl::Hidden,
164 cl::desc("Enable stricter verification with -verify-scev is passed"));
165
167 "scev-verify-ir", cl::Hidden,
168 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
169 cl::init(false));
170
172 "scev-mulops-inline-threshold", cl::Hidden,
173 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
174 cl::init(32));
175
177 "scev-addops-inline-threshold", cl::Hidden,
178 cl::desc("Threshold for inlining addition operands into a SCEV"),
179 cl::init(500));
180
182 "scalar-evolution-max-scev-compare-depth", cl::Hidden,
183 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
184 cl::init(32));
185
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));
190
192 "scalar-evolution-max-value-compare-depth", cl::Hidden,
193 cl::desc("Maximum depth of recursive value complexity comparisons"),
194 cl::init(2));
195
197 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
198 cl::desc("Maximum depth of recursive arithmetics"),
199 cl::init(32));
200
202 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
203 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
204
206 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
207 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
208 cl::init(8));
209
211 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
212 cl::desc("Max coefficients in AddRec during evolving"),
213 cl::init(8));
214
216 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
217 cl::desc("Size of the expression which is considered huge"),
218 cl::init(4096));
219
221 "scev-range-iter-threshold", cl::Hidden,
222 cl::desc("Threshold for switching to iteratively computing SCEV ranges"),
223 cl::init(32));
224
225static cl::opt<bool>
226ClassifyExpressions("scalar-evolution-classify-expressions",
227 cl::Hidden, cl::init(true),
228 cl::desc("When printing analysis, include information on every instruction"));
229
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"));
235
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));
241
242static cl::opt<bool>
243 EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
244 cl::desc("Handle <= and >= in finite loops"),
245 cl::init(true));
246
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));
251
252//===----------------------------------------------------------------------===//
253// SCEV class definitions
254//===----------------------------------------------------------------------===//
255
256//===----------------------------------------------------------------------===//
257// Implementation of the SCEV class.
258//
259
260#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
262 print(dbgs());
263 dbgs() << '\n';
264}
265#endif
266
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;
281 }
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;
288 }
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;
295 }
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;
302 }
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() &&
315 OS << "nw><";
316 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
317 OS << ">";
318 return;
319 }
320 case scAddExpr:
321 case scMulExpr:
322 case scUMaxExpr:
323 case scSMaxExpr:
324 case scUMinExpr:
325 case scSMinExpr:
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;
341 OpStr = " umin_seq ";
342 break;
343 default:
344 llvm_unreachable("There are no other nary expression types.");
345 }
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;
362 }
363 return;
364 }
365 case scUDivExpr: {
366 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
367 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
368 return;
369 }
370 case scUnknown:
371 cast<SCEVUnknown>(this)->getValue()->printAsOperand(OS, false);
372 return;
374 OS << "***COULDNOTCOMPUTE***";
375 return;
376 }
377 llvm_unreachable("Unknown SCEV kind!");
378}
379
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();
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();
409 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
410 }
411 llvm_unreachable("Unknown SCEV kind!");
412}
413
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:
433 return cast<SCEVNAryExpr>(this)->operands();
434 case scUDivExpr:
435 return cast<SCEVUDivExpr>(this)->operands();
437 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
438 }
439 llvm_unreachable("Unknown SCEV kind!");
440}
441
442bool SCEV::isZero() const {
443 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
444 return SC->getValue()->isZero();
445 return false;
446}
447
448bool SCEV::isOne() const {
449 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
450 return SC->getValue()->isOne();
451 return false;
452}
453
455 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
456 return SC->getValue()->isMinusOne();
457 return false;
458}
459
461 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
462 if (!Mul) return false;
463
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;
467
468 // Return true if the value is negative, this matches things like (-42 * V).
469 return SC->getAPInt().isNegative();
470}
471
474
476 return S->getSCEVType() == scCouldNotCompute;
477}
478
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;
488}
489
492}
493
494const SCEV *
496 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
497 return getConstant(ConstantInt::get(ITy, V, isSigned));
498}
499
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;
510}
511
513 const SCEV *op, Type *ty)
514 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {}
515
516SCEVPtrToIntExpr::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!");
521}
522
524 SCEVTypes SCEVTy, const SCEV *op,
525 Type *ty)
526 : SCEVCastExpr(ID, SCEVTy, op, ty) {}
527
528SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op,
529 Type *ty)
531 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
532 "Cannot truncate non-integer value!");
533}
534
535SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
536 const SCEV *op, Type *ty)
538 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
539 "Cannot zero extend non-integer value!");
540}
541
542SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
543 const SCEV *op, Type *ty)
545 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
546 "Cannot sign extend non-integer value!");
547}
548
549void SCEVUnknown::deleted() {
550 // Clear this SCEVUnknown from various maps.
551 SE->forgetMemoizedResults(this);
552
553 // Remove this SCEVUnknown from the uniquing map.
554 SE->UniqueSCEVs.RemoveNode(this);
555
556 // Release the value.
557 setValPtr(nullptr);
558}
559
560void SCEVUnknown::allUsesReplacedWith(Value *New) {
561 // Clear this SCEVUnknown from various maps.
562 SE->forgetMemoizedResults(this);
563
564 // Remove this SCEVUnknown from the uniquing map.
565 SE->UniqueSCEVs.RemoveNode(this);
566
567 // Replace the value pointer in case someone is still using this SCEVUnknown.
568 setValPtr(New);
569}
570
571//===----------------------------------------------------------------------===//
572// SCEV Utilities
573//===----------------------------------------------------------------------===//
574
575/// Compare the two values \p LV and \p RV in terms of their "complexity" where
576/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
577/// operands in SCEV expressions. \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:
580///
581/// %a = f(%x, %y)
582/// %b = f(%a, %a)
583/// %c = f(%b, %b)
584///
585/// %d = f(%x, %y)
586/// %e = f(%d, %d)
587/// %f = f(%e, %e)
588///
589/// CompareValueComplexity(%f, %c)
590///
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.
593static int
595 const LoopInfo *const LI, Value *LV, Value *RV,
596 unsigned Depth) {
597 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
598 return 0;
599
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;
606
607 // Compare getValueID values.
608 unsigned LID = LV->getValueID(), RID = RV->getValueID();
609 if (LID != RID)
610 return (int)LID - (int)RID;
611
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;
617 }
618
619 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
620 const auto *RGV = cast<GlobalValue>(RV);
621
622 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
623 auto LT = GV->getLinkage();
624 return !(GlobalValue::isPrivateLinkage(LT) ||
626 };
627
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());
632 }
633
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);
638
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;
647 }
648
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;
654
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;
661 }
662 }
663
664 EqCacheValue.unionSets(LV, RV);
665 return 0;
666}
667
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.
673static std::optional<int>
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;
681
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;
686
687 if (EqCacheSCEV.isEquivalent(LHS, RHS))
688 return 0;
689
691 return std::nullopt;
692
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);
700
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;
706 }
707
708 case scConstant: {
709 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
710 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
711
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;
719 }
720
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();
725 }
726
727 case scAddRecExpr: {
728 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
729 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
730
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;
743 }
744
745 [[fallthrough]];
746 }
747
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:
760 ArrayRef<const SCEV *> LOps = LHS->operands();
761 ArrayRef<const SCEV *> ROps = RHS->operands();
762
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;
767
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;
773 }
774 EqCacheSCEV.unionSets(LHS, RHS);
775 return 0;
776 }
777
779 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
780 }
781 llvm_unreachable("Unknown SCEV kind!");
782}
783
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.
788///
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.
794 LoopInfo *LI, DominatorTree &DT) {
795 if (Ops.size() < 2) return; // Noop
796
799
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;
805 };
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;
813 }
814
815 // Do the rough sort by complexity.
816 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
817 return IsLessComplex(LHS, RHS);
818 });
819
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();
827
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!
836 }
837 }
838 }
839}
840
841/// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
842/// least HugeExprThreshold nodes).
844 return any_of(Ops, [](const SCEV *S) {
846 });
847}
848
849//===----------------------------------------------------------------------===//
850// Simple SCEV method implementations
851//===----------------------------------------------------------------------===//
852
853/// Compute BC(It, K). The result has width W. Assume, K > 0.
854static 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);
860
861 // We are using the following formula for BC(It, K):
862 //
863 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
864 //
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.
869 //
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:
874 //
875 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
876 //
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.
883 //
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.
890 //
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.
895 //
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.
903 //
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.)
909
910 // Protection from insane SCEVs; this bound is conservative,
911 // but it probably doesn't matter.
912 if (K > 1000)
913 return SE.getCouldNotCompute();
914
915 unsigned W = SE.getTypeSizeInBits(ResultTy);
916
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;
929 }
930
931 // We need at least W + T bits for the multiplication step
932 unsigned CalculationBits = W + T;
933
934 // Calculate 2^T, at width T+W.
935 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
936
937 // Calculate the multiplicative inverse of K! / 2^T;
938 // this multiplication factor will perform the exact division by
939 // K! / 2^T.
941 APInt MultiplyFactor = OddFactorial.zext(W+1);
942 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
943 MultiplyFactor = MultiplyFactor.trunc(W);
944
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));
953 }
954
955 // Divide by 2^T
956 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
957
958 // Truncate the result, and divide by K! / 2^T.
959
960 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
961 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
962}
963
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:
968///
969/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
970///
971/// where BC(It, k) stands for binomial coefficient.
973 ScalarEvolution &SE) const {
974 return evaluateAtIteration(operands(), It, SE);
975}
976
977const SCEV *
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;
989
990 Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff));
991 }
992 return Result;
993}
994
995//===----------------------------------------------------------------------===//
996// SCEV Expression folder implementations
997//===----------------------------------------------------------------------===//
998
1000 unsigned Depth) {
1001 assert(Depth <= 1 &&
1002 "getLosslessPtrToIntExpr() should self-recurse at most once.");
1003
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;
1008
1009 // What would be an ID for such a SCEV cast expression?
1011 ID.AddInteger(scPtrToInt);
1012 ID.AddPointer(Op);
1013
1014 void *IP = nullptr;
1015
1016 // Is there already an expression for such a cast?
1017 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1018 return S;
1019
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();
1024
1025 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1026
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.
1032 getDataLayout().getTypeSizeInBits(IntPtrTy))
1033 return getCouldNotCompute();
1034
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);
1043
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;
1052 }
1053
1054 assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for "
1055 "non-SCEVUnknown's.");
1056
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.
1062
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> {
1070
1071 public:
1072 SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1073
1074 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1075 SCEVPtrToIntSinkingRewriter Rewriter(SE);
1076 return Rewriter.visit(Scev);
1077 }
1078
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);
1086 }
1087
1088 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1090 bool Changed = false;
1091 for (const auto *Op : Expr->operands()) {
1092 Operands.push_back(visit(Op));
1093 Changed |= Op != Operands.back();
1094 }
1095 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1096 }
1097
1098 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1100 bool Changed = false;
1101 for (const auto *Op : Expr->operands()) {
1102 Operands.push_back(visit(Op));
1103 Changed |= Op != Operands.back();
1104 }
1105 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1106 }
1107
1108 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1109 assert(Expr->getType()->isPointerTy() &&
1110 "Should only reach pointer-typed SCEVUnknown's.");
1111 return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1);
1112 }
1113 };
1114
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;
1121}
1122
1124 assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1125
1126 const SCEV *IntOp = getLosslessPtrToIntExpr(Op);
1127 if (isa<SCEVCouldNotCompute>(IntOp))
1128 return IntOp;
1129
1130 return getTruncateOrZeroExtend(IntOp, Ty);
1131}
1132
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);
1141
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;
1148
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)));
1153
1154 // trunc(trunc(x)) --> trunc(x)
1155 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1156 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1157
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);
1161
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);
1165
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;
1172 }
1173
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);
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);
1189 }
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.");
1196 }
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;
1202 }
1203
1204 // If the input value is a chrec scev, truncate the chrec's operands.
1205 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1207 for (const SCEV *Op : AddRec->operands())
1208 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1209 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1210 }
1211
1212 // Return zero if truncating to known zeros.
1213 uint32_t MinTrailingZeros = getMinTrailingZeros(Op);
1214 if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1215 return getZero(Ty);
1216
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;
1225}
1226
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.
1230static 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;
1237 SE->getSignedRangeMax(Step));
1238 }
1239 if (SE->isKnownNegative(Step)) {
1240 *Pred = ICmpInst::ICMP_SGT;
1242 SE->getSignedRangeMin(Step));
1243 }
1244 return nullptr;
1245}
1246
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.
1251 ICmpInst::Predicate *Pred,
1252 ScalarEvolution *SE) {
1253 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1254 *Pred = ICmpInst::ICMP_ULT;
1255
1257 SE->getUnsignedRangeMax(Step));
1258}
1259
1260namespace {
1261
1262struct ExtendOpTraitsBase {
1263 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1264 unsigned);
1265};
1266
1267// Used to make code generic over signed and unsigned overflow.
1268template <typename ExtendOp> struct ExtendOpTraits {
1269 // Members present:
1270 //
1271 // static const SCEV::NoWrapFlags WrapType;
1272 //
1273 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1274 //
1275 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1276 // ICmpInst::Predicate *Pred,
1277 // ScalarEvolution *SE);
1278};
1279
1280template <>
1281struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1282 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1283
1284 static const GetExtendExprTy GetExtendExpr;
1285
1286 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1287 ICmpInst::Predicate *Pred,
1288 ScalarEvolution *SE) {
1289 return getSignedOverflowLimitForStep(Step, Pred, SE);
1290 }
1291};
1292
1293const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1295
1296template <>
1297struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1298 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1299
1300 static const GetExtendExprTy GetExtendExpr;
1301
1302 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1303 ICmpInst::Predicate *Pred,
1304 ScalarEvolution *SE) {
1305 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1306 }
1307};
1308
1309const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1311
1312} // end anonymous namespace
1313
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)"
1321template <typename ExtendOpTy>
1322static 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;
1326
1327 const Loop *L = AR->getLoop();
1328 const SCEV *Start = AR->getStart();
1329 const SCEV *Step = AR->getStepRecurrence(*SE);
1330
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;
1335
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.
1340 for (const SCEV *Op : SA->operands())
1341 if (Op != Step)
1342 DiffOps.push_back(Op);
1343
1344 if (DiffOps.size() == SA->getNumOperands())
1345 return nullptr;
1346
1347 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1348 // `Step`:
1349
1350 // 1. NSW/NUW flags on the step increment.
1351 auto PreStartFlags =
1353 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1354 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1355 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1356
1357 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1358 // "S+X does not sign/unsign-overflow".
1359 //
1360
1361 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1362 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1363 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1364 return PreStart;
1365
1366 // 2. Direct overflow check on the step operation's expression.
1367 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1368 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1369 const SCEV *OperandExtendedStart =
1370 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1371 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1372 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1373 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1374 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1375 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1376 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1377 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1378 }
1379 return PreStart;
1380 }
1381
1382 // 3. Loop precondition.
1384 const SCEV *OverflowLimit =
1385 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1386
1387 if (OverflowLimit &&
1388 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1389 return PreStart;
1390
1391 return nullptr;
1392}
1393
1394// Get the normalized zero or sign extended expression for this AddRec's Start.
1395template <typename ExtendOpTy>
1396static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1397 ScalarEvolution *SE,
1398 unsigned Depth) {
1399 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1400
1401 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1402 if (!PreStart)
1403 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1404
1405 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1406 Depth),
1407 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1408}
1409
1410// Try to prove away overflow by looking at "nearby" add recurrences. A
1411// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1412// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1413//
1414// Formally:
1415//
1416// {S,+,X} == {S-T,+,X} + T
1417// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1418//
1419// If ({S-T,+,X} + T) does not overflow ... (1)
1420//
1421// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1422//
1423// If {S-T,+,X} does not overflow ... (2)
1424//
1425// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1426// == {Ext(S-T)+Ext(T),+,Ext(X)}
1427//
1428// If (S-T)+T does not overflow ... (3)
1429//
1430// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1431// == {Ext(S),+,Ext(X)} == LHS
1432//
1433// Thus, if (1), (2) and (3) are true for some T, then
1434// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1435//
1436// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1437// does not overflow" restricted to the 0th iteration. Therefore we only need
1438// to check for (1) and (2).
1439//
1440// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1441// is `Delta` (defined below).
1442template <typename ExtendOpTy>
1443bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1444 const SCEV *Step,
1445 const Loop *L) {
1446 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1447
1448 // We restrict `Start` to a constant to prevent SCEV from spending too much
1449 // time here. It is correct (but more expensive) to continue with a
1450 // non-constant `Start` and do a general SCEV subtraction to compute
1451 // `PreStart` below.
1452 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1453 if (!StartC)
1454 return false;
1455
1456 APInt StartAI = StartC->getAPInt();
1457
1458 for (unsigned Delta : {-2, -1, 1, 2}) {
1459 const SCEV *PreStart = getConstant(StartAI - Delta);
1460
1462 ID.AddInteger(scAddRecExpr);
1463 ID.AddPointer(PreStart);
1464 ID.AddPointer(Step);
1465 ID.AddPointer(L);
1466 void *IP = nullptr;
1467 const auto *PreAR =
1468 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1469
1470 // Give up if we don't already have the add recurrence we need because
1471 // actually constructing an add recurrence is relatively expensive.
1472 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1473 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1475 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1476 DeltaS, &Pred, this);
1477 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1478 return true;
1479 }
1480 }
1481
1482 return false;
1483}
1484
1485// Finds an integer D for an expression (C + x + y + ...) such that the top
1486// level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1487// unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1488// maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1489// the (C + x + y + ...) expression is \p WholeAddExpr.
1491 const SCEVConstant *ConstantTerm,
1492 const SCEVAddExpr *WholeAddExpr) {
1493 const APInt &C = ConstantTerm->getAPInt();
1494 const unsigned BitWidth = C.getBitWidth();
1495 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1496 uint32_t TZ = BitWidth;
1497 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1498 TZ = std::min(TZ, SE.getMinTrailingZeros(WholeAddExpr->getOperand(I)));
1499 if (TZ) {
1500 // Set D to be as many least significant bits of C as possible while still
1501 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1502 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1503 }
1504 return APInt(BitWidth, 0);
1505}
1506
1507// Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1508// level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1509// number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1510// ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1512 const APInt &ConstantStart,
1513 const SCEV *Step) {
1514 const unsigned BitWidth = ConstantStart.getBitWidth();
1515 const uint32_t TZ = SE.getMinTrailingZeros(Step);
1516 if (TZ)
1517 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1518 : ConstantStart;
1519 return APInt(BitWidth, 0);
1520}
1521
1523 const ScalarEvolution::FoldID &ID, const SCEV *S,
1526 &FoldCacheUser) {
1527 auto I = FoldCache.insert({ID, S});
1528 if (!I.second) {
1529 // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1530 // entry.
1531 auto &UserIDs = FoldCacheUser[I.first->second];
1532 assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
1533 for (unsigned I = 0; I != UserIDs.size(); ++I)
1534 if (UserIDs[I] == ID) {
1535 std::swap(UserIDs[I], UserIDs.back());
1536 break;
1537 }
1538 UserIDs.pop_back();
1539 I.first->second = S;
1540 }
1541 auto R = FoldCacheUser.insert({S, {}});
1542 R.first->second.push_back(ID);
1543}
1544
1545const SCEV *
1547 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1548 "This is not an extending conversion!");
1549 assert(isSCEVable(Ty) &&
1550 "This is not a conversion to a SCEVable type!");
1551 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1552 Ty = getEffectiveSCEVType(Ty);
1553
1554 FoldID ID(scZeroExtend, Op, Ty);
1555 auto Iter = FoldCache.find(ID);
1556 if (Iter != FoldCache.end())
1557 return Iter->second;
1558
1559 const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1560 if (!isa<SCEVZeroExtendExpr>(S))
1561 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1562 return S;
1563}
1564
1566 unsigned Depth) {
1567 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1568 "This is not an extending conversion!");
1569 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1570 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1571
1572 // Fold if the operand is constant.
1573 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1574 return getConstant(
1575 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1576
1577 // zext(zext(x)) --> zext(x)
1578 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1579 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1580
1581 // Before doing any expensive analysis, check to see if we've already
1582 // computed a SCEV for this Op and Ty.
1584 ID.AddInteger(scZeroExtend);
1585 ID.AddPointer(Op);
1586 ID.AddPointer(Ty);
1587 void *IP = nullptr;
1588 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1589 if (Depth > MaxCastDepth) {
1590 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1591 Op, Ty);
1592 UniqueSCEVs.InsertNode(S, IP);
1593 registerUser(S, Op);
1594 return S;
1595 }
1596
1597 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1598 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1599 // It's possible the bits taken off by the truncate were all zero bits. If
1600 // so, we should be able to simplify this further.
1601 const SCEV *X = ST->getOperand();
1603 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1604 unsigned NewBits = getTypeSizeInBits(Ty);
1605 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1606 CR.zextOrTrunc(NewBits)))
1607 return getTruncateOrZeroExtend(X, Ty, Depth);
1608 }
1609
1610 // If the input value is a chrec scev, and we can prove that the value
1611 // did not overflow the old, smaller, value, we can zero extend all of the
1612 // operands (often constants). This allows analysis of something like
1613 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1614 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1615 if (AR->isAffine()) {
1616 const SCEV *Start = AR->getStart();
1617 const SCEV *Step = AR->getStepRecurrence(*this);
1618 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1619 const Loop *L = AR->getLoop();
1620
1621 // If we have special knowledge that this addrec won't overflow,
1622 // we don't need to do any further analysis.
1623 if (AR->hasNoUnsignedWrap()) {
1624 Start =
1625 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1626 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1627 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1628 }
1629
1630 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1631 // Note that this serves two purposes: It filters out loops that are
1632 // simply not analyzable, and it covers the case where this code is
1633 // being called from within backedge-taken count analysis, such that
1634 // attempting to ask for the backedge-taken count would likely result
1635 // in infinite recursion. In the later case, the analysis code will
1636 // cope with a conservative value, and it will take care to purge
1637 // that value once it has finished.
1638 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1639 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1640 // Manually compute the final value for AR, checking for overflow.
1641
1642 // Check whether the backedge-taken count can be losslessly casted to
1643 // the addrec's type. The count is always unsigned.
1644 const SCEV *CastedMaxBECount =
1645 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1646 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1647 CastedMaxBECount, MaxBECount->getType(), Depth);
1648 if (MaxBECount == RecastedMaxBECount) {
1649 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1650 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1651 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1653 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1655 Depth + 1),
1656 WideTy, Depth + 1);
1657 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1658 const SCEV *WideMaxBECount =
1659 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1660 const SCEV *OperandExtendedAdd =
1661 getAddExpr(WideStart,
1662 getMulExpr(WideMaxBECount,
1663 getZeroExtendExpr(Step, WideTy, Depth + 1),
1666 if (ZAdd == OperandExtendedAdd) {
1667 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1668 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1669 // Return the expression with the addrec on the outside.
1670 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1671 Depth + 1);
1672 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1673 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1674 }
1675 // Similar to above, only this time treat the step value as signed.
1676 // This covers loops that count down.
1677 OperandExtendedAdd =
1678 getAddExpr(WideStart,
1679 getMulExpr(WideMaxBECount,
1680 getSignExtendExpr(Step, WideTy, Depth + 1),
1683 if (ZAdd == OperandExtendedAdd) {
1684 // Cache knowledge of AR NW, which is propagated to this AddRec.
1685 // Negative step causes unsigned wrap, but it still can't self-wrap.
1686 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1687 // Return the expression with the addrec on the outside.
1688 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1689 Depth + 1);
1690 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1691 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1692 }
1693 }
1694 }
1695
1696 // Normally, in the cases we can prove no-overflow via a
1697 // backedge guarding condition, we can also compute a backedge
1698 // taken count for the loop. The exceptions are assumptions and
1699 // guards present in the loop -- SCEV is not great at exploiting
1700 // these to compute max backedge taken counts, but can still use
1701 // these to prove lack of overflow. Use this fact to avoid
1702 // doing extra work that may not pay off.
1703 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1704 !AC.assumptions().empty()) {
1705
1706 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1707 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1708 if (AR->hasNoUnsignedWrap()) {
1709 // Same as nuw case above - duplicated here to avoid a compile time
1710 // issue. It's not clear that the order of checks does matter, but
1711 // it's one of two issue possible causes for a change which was
1712 // reverted. Be conservative for the moment.
1713 Start =
1714 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1715 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1716 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1717 }
1718
1719 // For a negative step, we can extend the operands iff doing so only
1720 // traverses values in the range zext([0,UINT_MAX]).
1721 if (isKnownNegative(Step)) {
1723 getSignedRangeMin(Step));
1726 // Cache knowledge of AR NW, which is propagated to this
1727 // AddRec. Negative step causes unsigned wrap, but it
1728 // still can't self-wrap.
1729 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1730 // Return the expression with the addrec on the outside.
1731 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1732 Depth + 1);
1733 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1734 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1735 }
1736 }
1737 }
1738
1739 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1740 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1741 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1742 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1743 const APInt &C = SC->getAPInt();
1744 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1745 if (D != 0) {
1746 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1747 const SCEV *SResidual =
1748 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1749 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1750 return getAddExpr(SZExtD, SZExtR,
1752 Depth + 1);
1753 }
1754 }
1755
1756 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1757 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1758 Start =
1759 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1760 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1761 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1762 }
1763 }
1764
1765 // zext(A % B) --> zext(A) % zext(B)
1766 {
1767 const SCEV *LHS;
1768 const SCEV *RHS;
1769 if (matchURem(Op, LHS, RHS))
1770 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1771 getZeroExtendExpr(RHS, Ty, Depth + 1));
1772 }
1773
1774 // zext(A / B) --> zext(A) / zext(B).
1775 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1776 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1777 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1778
1779 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1780 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1781 if (SA->hasNoUnsignedWrap()) {
1782 // If the addition does not unsign overflow then we can, by definition,
1783 // commute the zero extension with the addition operation.
1785 for (const auto *Op : SA->operands())
1786 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1787 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1788 }
1789
1790 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1791 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1792 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1793 //
1794 // Often address arithmetics contain expressions like
1795 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1796 // This transformation is useful while proving that such expressions are
1797 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1798 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1799 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1800 if (D != 0) {
1801 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1802 const SCEV *SResidual =
1804 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1805 return getAddExpr(SZExtD, SZExtR,
1807 Depth + 1);
1808 }
1809 }
1810 }
1811
1812 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1813 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1814 if (SM->hasNoUnsignedWrap()) {
1815 // If the multiply does not unsign overflow then we can, by definition,
1816 // commute the zero extension with the multiply operation.
1818 for (const auto *Op : SM->operands())
1819 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1820 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1821 }
1822
1823 // zext(2^K * (trunc X to iN)) to iM ->
1824 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1825 //
1826 // Proof:
1827 //
1828 // zext(2^K * (trunc X to iN)) to iM
1829 // = zext((trunc X to iN) << K) to iM
1830 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1831 // (because shl removes the top K bits)
1832 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1833 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1834 //
1835 if (SM->getNumOperands() == 2)
1836 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1837 if (MulLHS->getAPInt().isPowerOf2())
1838 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1839 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1840 MulLHS->getAPInt().logBase2();
1841 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1842 return getMulExpr(
1843 getZeroExtendExpr(MulLHS, Ty),
1845 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1846 SCEV::FlagNUW, Depth + 1);
1847 }
1848 }
1849
1850 // zext(umin(x, y)) -> umin(zext(x), zext(y))
1851 // zext(umax(x, y)) -> umax(zext(x), zext(y))
1852 if (isa<SCEVUMinExpr>(Op) || isa<SCEVUMaxExpr>(Op)) {
1853 auto *MinMax = cast<SCEVMinMaxExpr>(Op);
1855 for (auto *Operand : MinMax->operands())
1856 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1857 if (isa<SCEVUMinExpr>(MinMax))
1858 return getUMinExpr(Operands);
1859 return getUMaxExpr(Operands);
1860 }
1861
1862 // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
1863 if (auto *MinMax = dyn_cast<SCEVSequentialMinMaxExpr>(Op)) {
1864 assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!");
1866 for (auto *Operand : MinMax->operands())
1867 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1868 return getUMinExpr(Operands, /*Sequential*/ true);
1869 }
1870
1871 // The cast wasn't folded; create an explicit cast node.
1872 // Recompute the insert position, as it may have been invalidated.
1873 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1874 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1875 Op, Ty);
1876 UniqueSCEVs.InsertNode(S, IP);
1877 registerUser(S, Op);
1878 return S;
1879}
1880
1881const SCEV *
1883 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1884 "This is not an extending conversion!");
1885 assert(isSCEVable(Ty) &&
1886 "This is not a conversion to a SCEVable type!");
1887 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1888 Ty = getEffectiveSCEVType(Ty);
1889
1890 FoldID ID(scSignExtend, Op, Ty);
1891 auto Iter = FoldCache.find(ID);
1892 if (Iter != FoldCache.end())
1893 return Iter->second;
1894
1895 const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
1896 if (!isa<SCEVSignExtendExpr>(S))
1897 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1898 return S;
1899}
1900
1902 unsigned Depth) {
1903 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1904 "This is not an extending conversion!");
1905 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1906 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1907 Ty = getEffectiveSCEVType(Ty);
1908
1909 // Fold if the operand is constant.
1910 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1911 return getConstant(
1912 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1913
1914 // sext(sext(x)) --> sext(x)
1915 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1916 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1917
1918 // sext(zext(x)) --> zext(x)
1919 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1920 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1921
1922 // Before doing any expensive analysis, check to see if we've already
1923 // computed a SCEV for this Op and Ty.
1925 ID.AddInteger(scSignExtend);
1926 ID.AddPointer(Op);
1927 ID.AddPointer(Ty);
1928 void *IP = nullptr;
1929 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1930 // Limit recursion depth.
1931 if (Depth > MaxCastDepth) {
1932 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1933 Op, Ty);
1934 UniqueSCEVs.InsertNode(S, IP);
1935 registerUser(S, Op);
1936 return S;
1937 }
1938
1939 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1940 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1941 // It's possible the bits taken off by the truncate were all sign bits. If
1942 // so, we should be able to simplify this further.
1943 const SCEV *X = ST->getOperand();
1945 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1946 unsigned NewBits = getTypeSizeInBits(Ty);
1947 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1948 CR.sextOrTrunc(NewBits)))
1949 return getTruncateOrSignExtend(X, Ty, Depth);
1950 }
1951
1952 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1953 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1954 if (SA->hasNoSignedWrap()) {
1955 // If the addition does not sign overflow then we can, by definition,
1956 // commute the sign extension with the addition operation.
1958 for (const auto *Op : SA->operands())
1959 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1960 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1961 }
1962
1963 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1964 // if D + (C - D + x + y + ...) could be proven to not signed wrap
1965 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1966 //
1967 // For instance, this will bring two seemingly different expressions:
1968 // 1 + sext(5 + 20 * %x + 24 * %y) and
1969 // sext(6 + 20 * %x + 24 * %y)
1970 // to the same form:
1971 // 2 + sext(4 + 20 * %x + 24 * %y)
1972 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1973 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1974 if (D != 0) {
1975 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1976 const SCEV *SResidual =
1978 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1979 return getAddExpr(SSExtD, SSExtR,
1981 Depth + 1);
1982 }
1983 }
1984 }
1985 // If the input value is a chrec scev, and we can prove that the value
1986 // did not overflow the old, smaller, value, we can sign extend all of the
1987 // operands (often constants). This allows analysis of something like
1988 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1989 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1990 if (AR->isAffine()) {
1991 const SCEV *Start = AR->getStart();
1992 const SCEV *Step = AR->getStepRecurrence(*this);
1993 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1994 const Loop *L = AR->getLoop();
1995
1996 // If we have special knowledge that this addrec won't overflow,
1997 // we don't need to do any further analysis.
1998 if (AR->hasNoSignedWrap()) {
1999 Start =
2000 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2001 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2002 return getAddRecExpr(Start, Step, L, SCEV::FlagNSW);
2003 }
2004
2005 // Check whether the backedge-taken count is SCEVCouldNotCompute.
2006 // Note that this serves two purposes: It filters out loops that are
2007 // simply not analyzable, and it covers the case where this code is
2008 // being called from within backedge-taken count analysis, such that
2009 // attempting to ask for the backedge-taken count would likely result
2010 // in infinite recursion. In the later case, the analysis code will
2011 // cope with a conservative value, and it will take care to purge
2012 // that value once it has finished.
2013 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2014 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2015 // Manually compute the final value for AR, checking for
2016 // overflow.
2017
2018 // Check whether the backedge-taken count can be losslessly casted to
2019 // the addrec's type. The count is always unsigned.
2020 const SCEV *CastedMaxBECount =
2021 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2022 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2023 CastedMaxBECount, MaxBECount->getType(), Depth);
2024 if (MaxBECount == RecastedMaxBECount) {
2025 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2026 // Check whether Start+Step*MaxBECount has no signed overflow.
2027 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2029 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2031 Depth + 1),
2032 WideTy, Depth + 1);
2033 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2034 const SCEV *WideMaxBECount =
2035 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2036 const SCEV *OperandExtendedAdd =
2037 getAddExpr(WideStart,
2038 getMulExpr(WideMaxBECount,
2039 getSignExtendExpr(Step, WideTy, Depth + 1),
2042 if (SAdd == OperandExtendedAdd) {
2043 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2044 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2045 // Return the expression with the addrec on the outside.
2046 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2047 Depth + 1);
2048 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2049 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2050 }
2051 // Similar to above, only this time treat the step value as unsigned.
2052 // This covers loops that count up with an unsigned step.
2053 OperandExtendedAdd =
2054 getAddExpr(WideStart,
2055 getMulExpr(WideMaxBECount,
2056 getZeroExtendExpr(Step, WideTy, Depth + 1),
2059 if (SAdd == OperandExtendedAdd) {
2060 // If AR wraps around then
2061 //
2062 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2063 // => SAdd != OperandExtendedAdd
2064 //
2065 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2066 // (SAdd == OperandExtendedAdd => AR is NW)
2067
2068 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2069
2070 // Return the expression with the addrec on the outside.
2071 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2072 Depth + 1);
2073 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
2074 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2075 }
2076 }
2077 }
2078
2079 auto NewFlags = proveNoSignedWrapViaInduction(AR);
2080 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2081 if (AR->hasNoSignedWrap()) {
2082 // Same as nsw case above - duplicated here to avoid a compile time
2083 // issue. It's not clear that the order of checks does matter, but
2084 // it's one of two issue possible causes for a change which was
2085 // reverted. Be conservative for the moment.
2086 Start =
2087 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2088 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2089 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2090 }
2091
2092 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2093 // if D + (C - D + Step * n) could be proven to not signed wrap
2094 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2095 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2096 const APInt &C = SC->getAPInt();
2097 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2098 if (D != 0) {
2099 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2100 const SCEV *SResidual =
2101 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2102 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2103 return getAddExpr(SSExtD, SSExtR,
2105 Depth + 1);
2106 }
2107 }
2108
2109 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2110 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2111 Start =
2112 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2113 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2114 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2115 }
2116 }
2117
2118 // If the input value is provably positive and we could not simplify
2119 // away the sext build a zext instead.
2121 return getZeroExtendExpr(Op, Ty, Depth + 1);
2122
2123 // sext(smin(x, y)) -> smin(sext(x), sext(y))
2124 // sext(smax(x, y)) -> smax(sext(x), sext(y))
2125 if (isa<SCEVSMinExpr>(Op) || isa<SCEVSMaxExpr>(Op)) {
2126 auto *MinMax = cast<SCEVMinMaxExpr>(Op);
2128 for (auto *Operand : MinMax->operands())
2129 Operands.push_back(getSignExtendExpr(Operand, Ty));
2130 if (isa<SCEVSMinExpr>(MinMax))
2131 return getSMinExpr(Operands);
2132 return getSMaxExpr(Operands);
2133 }
2134
2135 // The cast wasn't folded; create an explicit cast node.
2136 // Recompute the insert position, as it may have been invalidated.
2137 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2138 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2139 Op, Ty);
2140 UniqueSCEVs.InsertNode(S, IP);
2141 registerUser(S, { Op });
2142 return S;
2143}
2144
2146 Type *Ty) {
2147 switch (Kind) {
2148 case scTruncate:
2149 return getTruncateExpr(Op, Ty);
2150 case scZeroExtend:
2151 return getZeroExtendExpr(Op, Ty);
2152 case scSignExtend:
2153 return getSignExtendExpr(Op, Ty);
2154 case scPtrToInt:
2155 return getPtrToIntExpr(Op, Ty);
2156 default:
2157 llvm_unreachable("Not a SCEV cast expression!");
2158 }
2159}
2160
2161/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2162/// unspecified bits out to the given type.
2164 Type *Ty) {
2165 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2166 "This is not an extending conversion!");
2167 assert(isSCEVable(Ty) &&
2168 "This is not a conversion to a SCEVable type!");
2169 Ty = getEffectiveSCEVType(Ty);
2170
2171 // Sign-extend negative constants.
2172 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2173 if (SC->getAPInt().isNegative())
2174 return getSignExtendExpr(Op, Ty);
2175
2176 // Peel off a truncate cast.
2177 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2178 const SCEV *NewOp = T->getOperand();
2179 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2180 return getAnyExtendExpr(NewOp, Ty);
2181 return getTruncateOrNoop(NewOp, Ty);
2182 }
2183
2184 // Next try a zext cast. If the cast is folded, use it.
2185 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2186 if (!isa<SCEVZeroExtendExpr>(ZExt))
2187 return ZExt;
2188
2189 // Next try a sext cast. If the cast is folded, use it.
2190 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2191 if (!isa<SCEVSignExtendExpr>(SExt))
2192 return SExt;
2193
2194 // Force the cast to be folded into the operands of an addrec.
2195 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2197 for (const SCEV *Op : AR->operands())
2198 Ops.push_back(getAnyExtendExpr(Op, Ty));
2199 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2200 }
2201
2202 // If the expression is obviously signed, use the sext cast value.
2203 if (isa<SCEVSMaxExpr>(Op))
2204 return SExt;
2205
2206 // Absent any other information, use the zext cast value.
2207 return ZExt;
2208}
2209
2210/// Process the given Ops list, which is a list of operands to be added under
2211/// the given scale, update the given map. This is a helper function for
2212/// getAddRecExpr. As an example of what it does, given a sequence of operands
2213/// that would form an add expression like this:
2214///
2215/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2216///
2217/// where A and B are constants, update the map with these values:
2218///
2219/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2220///
2221/// and add 13 + A*B*29 to AccumulatedConstant.
2222/// This will allow getAddRecExpr to produce this:
2223///
2224/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2225///
2226/// This form often exposes folding opportunities that are hidden in
2227/// the original operand list.
2228///
2229/// Return true iff it appears that any interesting folding opportunities
2230/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2231/// the common case where no interesting opportunities are present, and
2232/// is also used as a check to avoid infinite recursion.
2233static bool
2236 APInt &AccumulatedConstant,
2237 ArrayRef<const SCEV *> Ops, const APInt &Scale,
2238 ScalarEvolution &SE) {
2239 bool Interesting = false;
2240
2241 // Iterate over the add operands. They are sorted, with constants first.
2242 unsigned i = 0;
2243 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2244 ++i;
2245 // Pull a buried constant out to the outside.
2246 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2247 Interesting = true;
2248 AccumulatedConstant += Scale * C->getAPInt();
2249 }
2250
2251 // Next comes everything else. We're especially interested in multiplies
2252 // here, but they're in the middle, so just visit the rest with one loop.
2253 for (; i != Ops.size(); ++i) {
2254 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2255 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2256 APInt NewScale =
2257 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2258 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2259 // A multiplication of a constant with another add; recurse.
2260 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2261 Interesting |=
2262 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2263 Add->operands(), NewScale, SE);
2264 } else {
2265 // A multiplication of a constant with some other value. Update
2266 // the map.
2267 SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands()));
2268 const SCEV *Key = SE.getMulExpr(MulOps);
2269 auto Pair = M.insert({Key, NewScale});
2270 if (Pair.second) {
2271 NewOps.push_back(Pair.first->first);
2272 } else {
2273 Pair.first->second += NewScale;
2274 // The map already had an entry for this value, which may indicate
2275 // a folding opportunity.
2276 Interesting = true;
2277 }
2278 }
2279 } else {
2280 // An ordinary operand. Update the map.
2281 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2282 M.insert({Ops[i], Scale});
2283 if (Pair.second) {
2284 NewOps.push_back(Pair.first->first);
2285 } else {
2286 Pair.first->second += Scale;
2287 // The map already had an entry for this value, which may indicate
2288 // a folding opportunity.
2289 Interesting = true;
2290 }
2291 }
2292 }
2293
2294 return Interesting;
2295}
2296
2298 const SCEV *LHS, const SCEV *RHS,
2299 const Instruction *CtxI) {
2300 const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *,
2301 SCEV::NoWrapFlags, unsigned);
2302 switch (BinOp) {
2303 default:
2304 llvm_unreachable("Unsupported binary op");
2305 case Instruction::Add:
2307 break;
2308 case Instruction::Sub:
2310 break;
2311 case Instruction::Mul:
2313 break;
2314 }
2315
2316 const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
2319
2320 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2321 auto *NarrowTy = cast<IntegerType>(LHS->getType());
2322 auto *WideTy =
2323 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2324
2325 const SCEV *A = (this->*Extension)(
2326 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2327 const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2328 const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2329 const SCEV *B = (this->*Operation)(LHSB, RHSB, SCEV::FlagAnyWrap, 0);
2330 if (A == B)
2331 return true;
2332 // Can we use context to prove the fact we need?
2333 if (!CtxI)
2334 return false;
2335 // TODO: Support mul.
2336 if (BinOp == Instruction::Mul)
2337 return false;
2338 auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2339 // TODO: Lift this limitation.
2340 if (!RHSC)
2341 return false;
2342 APInt C = RHSC->getAPInt();
2343 unsigned NumBits = C.getBitWidth();
2344 bool IsSub = (BinOp == Instruction::Sub);
2345 bool IsNegativeConst = (Signed && C.isNegative());
2346 // Compute the direction and magnitude by which we need to check overflow.
2347 bool OverflowDown = IsSub ^ IsNegativeConst;
2348 APInt Magnitude = C;
2349 if (IsNegativeConst) {
2350 if (C == APInt::getSignedMinValue(NumBits))
2351 // TODO: SINT_MIN on inversion gives the same negative value, we don't
2352 // want to deal with that.
2353 return false;
2354 Magnitude = -C;
2355 }
2356
2358 if (OverflowDown) {
2359 // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2360 APInt Min = Signed ? APInt::getSignedMinValue(NumBits)
2361 : APInt::getMinValue(NumBits);
2362 APInt Limit = Min + Magnitude;
2363 return isKnownPredicateAt(Pred, getConstant(Limit), LHS, CtxI);
2364 } else {
2365 // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2366 APInt Max = Signed ? APInt::getSignedMaxValue(NumBits)
2367 : APInt::getMaxValue(NumBits);
2368 APInt Limit = Max - Magnitude;
2369 return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2370 }
2371}
2372
2373std::optional<SCEV::NoWrapFlags>
2375 const OverflowingBinaryOperator *OBO) {
2376 // It cannot be done any better.
2377 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2378 return std::nullopt;
2379
2381
2382 if (OBO->hasNoUnsignedWrap())
2384 if (OBO->hasNoSignedWrap())
2386
2387 bool Deduced = false;
2388
2389 if (OBO->getOpcode() != Instruction::Add &&
2390 OBO->getOpcode() != Instruction::Sub &&
2391 OBO->getOpcode() != Instruction::Mul)
2392 return std::nullopt;
2393
2394 const SCEV *LHS = getSCEV(OBO->getOperand(0));
2395 const SCEV *RHS = getSCEV(OBO->getOperand(1));
2396
2397 const Instruction *CtxI =
2398 UseContextForNoWrapFlagInference ? dyn_cast<Instruction>(OBO) : nullptr;
2399 if (!OBO->hasNoUnsignedWrap() &&
2401 /* Signed */ false, LHS, RHS, CtxI)) {
2403 Deduced = true;
2404 }
2405
2406 if (!OBO->hasNoSignedWrap() &&
2408 /* Signed */ true, LHS, RHS, CtxI)) {
2410 Deduced = true;
2411 }
2412
2413 if (Deduced)
2414 return Flags;
2415 return std::nullopt;
2416}
2417
2418// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2419// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2420// can't-overflow flags for the operation if possible.
2421static SCEV::NoWrapFlags
2423 const ArrayRef<const SCEV *> Ops,
2424 SCEV::NoWrapFlags Flags) {
2425 using namespace std::placeholders;
2426
2427 using OBO = OverflowingBinaryOperator;
2428
2429 bool CanAnalyze =
2431 (void)CanAnalyze;
2432 assert(CanAnalyze && "don't call from other places!");
2433
2434 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2435 SCEV::NoWrapFlags SignOrUnsignWrap =
2436 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2437
2438 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2439 auto IsKnownNonNegative = [&](const SCEV *S) {
2440 return SE->isKnownNonNegative(S);
2441 };
2442
2443 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2444 Flags =
2445 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2446
2447 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2448
2449 if (SignOrUnsignWrap != SignOrUnsignMask &&
2450 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2451 isa<SCEVConstant>(Ops[0])) {
2452
2453 auto Opcode = [&] {
2454 switch (Type) {
2455 case scAddExpr:
2456 return Instruction::Add;
2457 case scMulExpr:
2458 return Instruction::Mul;
2459 default:
2460 llvm_unreachable("Unexpected SCEV op.");
2461 }
2462 }();
2463
2464 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2465
2466 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2467 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2469 Opcode, C, OBO::NoSignedWrap);
2470 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2472 }
2473
2474 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2475 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2477 Opcode, C, OBO::NoUnsignedWrap);
2478 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2480 }
2481 }
2482
2483 // <0,+,nonnegative><nw> is also nuw
2484 // TODO: Add corresponding nsw case
2486 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2487 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2489
2490 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2492 Ops.size() == 2) {
2493 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2494 if (UDiv->getOperand(1) == Ops[1])
2496 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2497 if (UDiv->getOperand(1) == Ops[0])
2499 }
2500
2501 return Flags;
2502}
2503
2505 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2506}
2507
2508/// Get a canonical add expression, or something simpler if possible.
2510 SCEV::NoWrapFlags OrigFlags,
2511 unsigned Depth) {
2512 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2513 "only nuw or nsw allowed");
2514 assert(!Ops.empty() && "Cannot get empty add!");
2515 if (Ops.size() == 1) return Ops[0];
2516#ifndef NDEBUG
2517 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2518 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2519 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2520 "SCEVAddExpr operand types don't match!");
2521 unsigned NumPtrs = count_if(
2522 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2523 assert(NumPtrs <= 1 && "add has at most one pointer operand");
2524#endif
2525
2526 // Sort by complexity, this groups all similar expression types together.
2527 GroupByComplexity(Ops, &LI, DT);
2528
2529 // If there are any constants, fold them together.
2530 unsigned Idx = 0;
2531 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2532 ++Idx;
2533 assert(Idx < Ops.size());
2534 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2535 // We found two constants, fold them together!
2536 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2537 if (Ops.size() == 2) return Ops[0];
2538 Ops.erase(Ops.begin()+1); // Erase the folded element
2539 LHSC = cast<SCEVConstant>(Ops[0]);
2540 }
2541
2542 // If we are left with a constant zero being added, strip it off.
2543 if (LHSC->getValue()->isZero()) {
2544 Ops.erase(Ops.begin());
2545 --Idx;
2546 }
2547
2548 if (Ops.size() == 1) return Ops[0];
2549 }
2550
2551 // Delay expensive flag strengthening until necessary.
2552 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2553 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2554 };
2555
2556 // Limit recursion calls depth.
2558 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2559
2560 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2561 // Don't strengthen flags if we have no new information.
2562 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2563 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2564 Add->setNoWrapFlags(ComputeFlags(Ops));
2565 return S;
2566 }
2567
2568 // Okay, check to see if the same value occurs in the operand list more than
2569 // once. If so, merge them together into an multiply expression. Since we
2570 // sorted the list, these values are required to be adjacent.
2571 Type *Ty = Ops[0]->getType();
2572 bool FoundMatch = false;
2573 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2574 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2575 // Scan ahead to count how many equal operands there are.
2576 unsigned Count = 2;
2577 while (i+Count != e && Ops[i+Count] == Ops[i])
2578 ++Count;
2579 // Merge the values into a multiply.
2580 const SCEV *Scale = getConstant(Ty, Count);
2581 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2582 if (Ops.size() == Count)
2583 return Mul;
2584 Ops[i] = Mul;
2585 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2586 --i; e -= Count - 1;
2587 FoundMatch = true;
2588 }
2589 if (FoundMatch)
2590 return getAddExpr(Ops, OrigFlags, Depth + 1);
2591
2592 // Check for truncates. If all the operands are truncated from the same
2593 // type, see if factoring out the truncate would permit the result to be
2594 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2595 // if the contents of the resulting outer trunc fold to something simple.
2596 auto FindTruncSrcType = [&]() -> Type * {
2597 // We're ultimately looking to fold an addrec of truncs and muls of only
2598 // constants and truncs, so if we find any other types of SCEV
2599 // as operands of the addrec then we bail and return nullptr here.
2600 // Otherwise, we return the type of the operand of a trunc that we find.
2601 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2602 return T->getOperand()->getType();
2603 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2604 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2605 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2606 return T->getOperand()->getType();
2607 }
2608 return nullptr;
2609 };
2610 if (auto *SrcType = FindTruncSrcType()) {
2612 bool Ok = true;
2613 // Check all the operands to see if they can be represented in the
2614 // source type of the truncate.
2615 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2616 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2617 if (T->getOperand()->getType() != SrcType) {
2618 Ok = false;
2619 break;
2620 }
2621 LargeOps.push_back(T->getOperand());
2622 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2623 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2624 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2625 SmallVector<const SCEV *, 8> LargeMulOps;
2626 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2627 if (const SCEVTruncateExpr *T =
2628 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2629 if (T->getOperand()->getType() != SrcType) {
2630 Ok = false;
2631 break;
2632 }
2633 LargeMulOps.push_back(T->getOperand());
2634 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2635 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2636 } else {
2637 Ok = false;
2638 break;
2639 }
2640 }
2641 if (Ok)
2642 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2643 } else {
2644 Ok = false;
2645 break;
2646 }
2647 }
2648 if (Ok) {
2649 // Evaluate the expression in the larger type.
2650 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2651 // If it folds to something simple, use it. Otherwise, don't.
2652 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2653 return getTruncateExpr(Fold, Ty);
2654 }
2655 }
2656
2657 if (Ops.size() == 2) {
2658 // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2659 // C2 can be folded in a way that allows retaining wrapping flags of (X +
2660 // C1).
2661 const SCEV *A = Ops[0];
2662 const SCEV *B = Ops[1];
2663 auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2664 auto *C = dyn_cast<SCEVConstant>(A);
2665 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2666 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2667 auto C2 = C->getAPInt();
2668 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2669
2670 APInt ConstAdd = C1 + C2;
2671 auto AddFlags = AddExpr->getNoWrapFlags();
2672 // Adding a smaller constant is NUW if the original AddExpr was NUW.
2674 ConstAdd.ule(C1)) {
2675 PreservedFlags =
2677 }
2678
2679 // Adding a constant with the same sign and small magnitude is NSW, if the
2680 // original AddExpr was NSW.
2682 C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2683 ConstAdd.abs().ule(C1.abs())) {
2684 PreservedFlags =
2686 }
2687
2688 if (PreservedFlags != SCEV::FlagAnyWrap) {
2689 SmallVector<const SCEV *, 4> NewOps(AddExpr->operands());
2690 NewOps[0] = getConstant(ConstAdd);
2691 return getAddExpr(NewOps, PreservedFlags);
2692 }
2693 }
2694 }
2695
2696 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2697 if (Ops.size() == 2) {
2698 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[0]);
2699 if (Mul && Mul->getNumOperands() == 2 &&
2700 Mul->getOperand(0)->isAllOnesValue()) {
2701 const SCEV *X;
2702 const SCEV *Y;
2703 if (matchURem(Mul->getOperand(1), X, Y) && X == Ops[1]) {
2704 return getMulExpr(Y, getUDivExpr(X, Y));
2705 }
2706 }
2707 }
2708
2709 // Skip past any other cast SCEVs.
2710 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2711 ++Idx;
2712
2713 // If there are add operands they would be next.
2714 if (Idx < Ops.size()) {
2715 bool DeletedAdd = false;
2716 // If the original flags and all inlined SCEVAddExprs are NUW, use the
2717 // common NUW flag for expression after inlining. Other flags cannot be
2718 // preserved, because they may depend on the original order of operations.
2719 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2720 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2721 if (Ops.size() > AddOpsInlineThreshold ||
2722 Add->getNumOperands() > AddOpsInlineThreshold)
2723 break;
2724 // If we have an add, expand the add operands onto the end of the operands
2725 // list.
2726 Ops.erase(Ops.begin()+Idx);
2727 append_range(Ops, Add->operands());
2728 DeletedAdd = true;
2729 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2730 }
2731
2732 // If we deleted at least one add, we added operands to the end of the list,
2733 // and they are not necessarily sorted. Recurse to resort and resimplify
2734 // any operands we just acquired.
2735 if (DeletedAdd)
2736 return getAddExpr(Ops, CommonFlags, Depth + 1);
2737 }
2738
2739 // Skip over the add expression until we get to a multiply.
2740 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2741 ++Idx;
2742
2743 // Check to see if there are any folding opportunities present with
2744 // operands multiplied by constant values.
2745 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2749 APInt AccumulatedConstant(BitWidth, 0);
2750 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2751 Ops, APInt(BitWidth, 1), *this)) {
2752 struct APIntCompare {
2753 bool operator()(const APInt &LHS, const APInt &RHS) const {
2754 return LHS.ult(RHS);
2755 }
2756 };
2757
2758 // Some interesting folding opportunity is present, so its worthwhile to
2759 // re-generate the operands list. Group the operands by constant scale,
2760 // to avoid multiplying by the same constant scale multiple times.
2761 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2762 for (const SCEV *NewOp : NewOps)
2763 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2764 // Re-generate the operands list.
2765 Ops.clear();
2766 if (AccumulatedConstant != 0)
2767 Ops.push_back(getConstant(AccumulatedConstant));
2768 for (auto &MulOp : MulOpLists) {
2769 if (MulOp.first == 1) {
2770 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2771 } else if (MulOp.first != 0) {
2773 getConstant(MulOp.first),
2774 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2775 SCEV::FlagAnyWrap, Depth + 1));
2776 }
2777 }
2778 if (Ops.empty())
2779 return getZero(Ty);
2780 if (Ops.size() == 1)
2781 return Ops[0];
2782 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2783 }
2784 }
2785
2786 // If we are adding something to a multiply expression, make sure the
2787 // something is not already an operand of the multiply. If so, merge it into
2788 // the multiply.
2789 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2790 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2791 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2792 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2793 if (isa<SCEVConstant>(MulOpSCEV))
2794 continue;
2795 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2796 if (MulOpSCEV == Ops[AddOp]) {
2797 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2798 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2799 if (Mul->getNumOperands() != 2) {
2800 // If the multiply has more than two operands, we must get the
2801 // Y*Z term.
2803 Mul->operands().take_front(MulOp));
2804 append_range(MulOps, Mul->operands().drop_front(MulOp + 1));
2805 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2806 }
2807 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2808 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2809 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2811 if (Ops.size() == 2) return OuterMul;
2812 if (AddOp < Idx) {
2813 Ops.erase(Ops.begin()+AddOp);
2814 Ops.erase(Ops.begin()+Idx-1);
2815 } else {
2816 Ops.erase(Ops.begin()+Idx);
2817 Ops.erase(Ops.begin()+AddOp-1);
2818 }
2819 Ops.push_back(OuterMul);
2820 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2821 }
2822
2823 // Check this multiply against other multiplies being added together.
2824 for (unsigned OtherMulIdx = Idx+1;
2825 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2826 ++OtherMulIdx) {
2827 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2828 // If MulOp occurs in OtherMul, we can fold the two multiplies
2829 // together.
2830 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2831 OMulOp != e; ++OMulOp)
2832 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2833 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2834 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2835 if (Mul->getNumOperands() != 2) {
2837 Mul->operands().take_front(MulOp));
2838 append_range(MulOps, Mul->operands().drop_front(MulOp+1));
2839 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2840 }
2841 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2842 if (OtherMul->getNumOperands() != 2) {
2844 OtherMul->operands().take_front(OMulOp));
2845 append_range(MulOps, OtherMul->operands().drop_front(OMulOp+1));
2846 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2847 }
2848 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2849 const SCEV *InnerMulSum =
2850 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2851 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2853 if (Ops.size() == 2) return OuterMul;
2854 Ops.erase(Ops.begin()+Idx);
2855 Ops.erase(Ops.begin()+OtherMulIdx-1);
2856 Ops.push_back(OuterMul);
2857 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2858 }
2859 }
2860 }
2861 }
2862
2863 // If there are any add recurrences in the operands list, see if any other
2864 // added values are loop invariant. If so, we can fold them into the
2865 // recurrence.
2866 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2867 ++Idx;
2868
2869 // Scan over all recurrences, trying to fold loop invariants into them.
2870 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2871 // Scan all of the other operands to this add and add them to the vector if
2872 // they are loop invariant w.r.t. the recurrence.
2874 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2875 const Loop *AddRecLoop = AddRec->getLoop();
2876 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2877 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2878 LIOps.push_back(Ops[i]);
2879 Ops.erase(Ops.begin()+i);
2880 --i; --e;
2881 }
2882
2883 // If we found some loop invariants, fold them into the recurrence.
2884 if (!LIOps.empty()) {
2885 // Compute nowrap flags for the addition of the loop-invariant ops and
2886 // the addrec. Temporarily push it as an operand for that purpose. These
2887 // flags are valid in the scope of the addrec only.
2888 LIOps.push_back(AddRec);
2889 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2890 LIOps.pop_back();
2891
2892 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2893 LIOps.push_back(AddRec->getStart());
2894
2895 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2896
2897 // It is not in general safe to propagate flags valid on an add within
2898 // the addrec scope to one outside it. We must prove that the inner
2899 // scope is guaranteed to execute if the outer one does to be able to
2900 // safely propagate. We know the program is undefined if poison is
2901 // produced on the inner scoped addrec. We also know that *for this use*
2902 // the outer scoped add can't overflow (because of the flags we just
2903 // computed for the inner scoped add) without the program being undefined.
2904 // Proving that entry to the outer scope neccesitates entry to the inner
2905 // scope, thus proves the program undefined if the flags would be violated
2906 // in the outer scope.
2907 SCEV::NoWrapFlags AddFlags = Flags;
2908 if (AddFlags != SCEV::FlagAnyWrap) {
2909 auto *DefI = getDefiningScopeBound(LIOps);
2910 auto *ReachI = &*AddRecLoop->getHeader()->begin();
2911 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2912 AddFlags = SCEV::FlagAnyWrap;
2913 }
2914 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2915
2916 // Build the new addrec. Propagate the NUW and NSW flags if both the
2917 // outer add and the inner addrec are guaranteed to have no overflow.
2918 // Always propagate NW.
2919 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2920 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2921
2922 // If all of the other operands were loop invariant, we are done.
2923 if (Ops.size() == 1) return NewRec;
2924
2925 // Otherwise, add the folded AddRec by the non-invariant parts.
2926 for (unsigned i = 0;; ++i)
2927 if (Ops[i] == AddRec) {
2928 Ops[i] = NewRec;
2929 break;
2930 }
2931 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2932 }
2933
2934 // Okay, if there weren't any loop invariants to be folded, check to see if
2935 // there are multiple AddRec's with the same loop induction variable being
2936 // added together. If so, we can fold them.
2937 for (unsigned OtherIdx = Idx+1;
2938 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2939 ++OtherIdx) {
2940 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2941 // so that the 1st found AddRecExpr is dominated by all others.
2942 assert(DT.dominates(
2943 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2944 AddRec->getLoop()->getHeader()) &&
2945 "AddRecExprs are not sorted in reverse dominance order?");
2946 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2947 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2948 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2949 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2950 ++OtherIdx) {
2951 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2952 if (OtherAddRec->getLoop() == AddRecLoop) {
2953 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2954 i != e; ++i) {
2955 if (i >= AddRecOps.size()) {
2956 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
2957 break;
2958 }
2960 AddRecOps[i], OtherAddRec->getOperand(i)};
2961 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2962 }
2963 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2964 }
2965 }
2966 // Step size has changed, so we cannot guarantee no self-wraparound.
2967 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2968 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2969 }
2970 }
2971
2972 // Otherwise couldn't fold anything into this recurrence. Move onto the
2973 // next one.
2974 }
2975
2976 // Okay, it looks like we really DO need an add expr. Check to see if we
2977 // already have one, otherwise create a new one.
2978 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2979}
2980
2981const SCEV *
2982ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2983 SCEV::NoWrapFlags Flags) {
2985 ID.AddInteger(scAddExpr);
2986 for (const SCEV *Op : Ops)
2987 ID.AddPointer(Op);
2988 void *IP = nullptr;
2989 SCEVAddExpr *S =
2990 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2991 if (!S) {
2992 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2993 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2994 S = new (SCEVAllocator)
2995 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2996 UniqueSCEVs.InsertNode(S, IP);
2997 registerUser(S, Ops);
2998 }
2999 S->setNoWrapFlags(Flags);
3000 return S;
3001}
3002
3003const SCEV *
3004ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
3005 const Loop *L, SCEV::NoWrapFlags Flags) {
3007 ID.AddInteger(scAddRecExpr);
3008 for (const SCEV *Op : Ops)
3009 ID.AddPointer(Op);
3010 ID.AddPointer(L);
3011 void *IP = nullptr;
3012 SCEVAddRecExpr *S =
3013 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3014 if (!S) {
3015 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3016 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3017 S = new (SCEVAllocator)
3018 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
3019 UniqueSCEVs.InsertNode(S, IP);
3020 LoopUsers[L].push_back(S);
3021 registerUser(S, Ops);
3022 }
3023 setNoWrapFlags(S, Flags);
3024 return S;
3025}
3026
3027const SCEV *
3028ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
3029 SCEV::NoWrapFlags Flags) {
3031 ID.AddInteger(scMulExpr);
3032 for (const SCEV *Op : Ops)
3033 ID.AddPointer(Op);
3034 void *IP = nullptr;
3035 SCEVMulExpr *S =
3036 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3037 if (!S) {
3038 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3039 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3040 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
3041 O, Ops.size());
3042 UniqueSCEVs.InsertNode(S, IP);
3043 registerUser(S, Ops);
3044 }
3045 S->setNoWrapFlags(Flags);
3046 return S;
3047}
3048
3049static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
3050 uint64_t k = i*j;
3051 if (j > 1 && k / j != i) Overflow = true;
3052 return k;
3053}
3054
3055/// Compute the result of "n choose k", the binomial coefficient. If an
3056/// intermediate computation overflows, Overflow will be set and the return will
3057/// be garbage. Overflow is not cleared on absence of overflow.
3058static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3059 // We use the multiplicative formula:
3060 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3061 // At each iteration, we take the n-th term of the numeral and divide by the
3062 // (k-n)th term of the denominator. This division will always produce an
3063 // integral result, and helps reduce the chance of overflow in the
3064 // intermediate computations. However, we can still overflow even when the
3065 // final result would fit.
3066
3067 if (n == 0 || n == k) return 1;
3068 if (k > n) return 0;
3069
3070 if (k > n/2)
3071 k = n-k;
3072
3073 uint64_t r = 1;
3074 for (uint64_t i = 1; i <= k; ++i) {
3075 r = umul_ov(r, n-(i-1), Overflow);
3076 r /= i;
3077 }
3078 return r;
3079}
3080
3081/// Determine if any of the operands in this SCEV are a constant or if
3082/// any of the add or multiply expressions in this SCEV contain a constant.
3083static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3084 struct FindConstantInAddMulChain {
3085 bool FoundConstant = false;
3086
3087 bool follow(const SCEV *S) {
3088 FoundConstant |= isa<SCEVConstant>(S);
3089 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3090 }
3091
3092 bool isDone() const {
3093 return FoundConstant;
3094 }
3095 };
3096
3097 FindConstantInAddMulChain F;
3099 ST.visitAll(StartExpr);
3100 return F.FoundConstant;
3101}
3102
3103/// Get a canonical multiply expression, or something simpler if possible.
3105 SCEV::NoWrapFlags OrigFlags,
3106 unsigned Depth) {
3107 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3108 "only nuw or nsw allowed");
3109 assert(!Ops.empty() && "Cannot get empty mul!");
3110 if (Ops.size() == 1) return Ops[0];
3111#ifndef NDEBUG
3112 Type *ETy = Ops[0]->getType();
3113 assert(!ETy->isPointerTy());
3114 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3115 assert(Ops[i]->getType() == ETy &&
3116 "SCEVMulExpr operand types don't match!");
3117#endif
3118
3119 // Sort by complexity, this groups all similar expression types together.
3120 GroupByComplexity(Ops, &LI, DT);
3121
3122 // If there are any constants, fold them together.
3123 unsigned Idx = 0;
3124 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3125 ++Idx;
3126 assert(Idx < Ops.size());
3127 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3128 // We found two constants, fold them together!
3129 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
3130 if (Ops.size() == 2) return Ops[0];
3131 Ops.erase(Ops.begin()+1); // Erase the folded element
3132 LHSC = cast<SCEVConstant>(Ops[0]);
3133 }
3134
3135 // If we have a multiply of zero, it will always be zero.
3136 if (LHSC->getValue()->isZero())
3137 return LHSC;
3138
3139 // If we are left with a constant one being multiplied, strip it off.
3140 if (LHSC->getValue()->isOne()) {
3141 Ops.erase(Ops.begin());
3142 --Idx;
3143 }
3144
3145 if (Ops.size() == 1)
3146 return Ops[0];
3147 }
3148
3149 // Delay expensive flag strengthening until necessary.
3150 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
3151 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3152 };
3153
3154 // Limit recursion calls depth.
3156 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3157
3158 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3159 // Don't strengthen flags if we have no new information.
3160 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3161 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3162 Mul->setNoWrapFlags(ComputeFlags(Ops));
3163 return S;
3164 }
3165
3166 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3167 if (Ops.size() == 2) {
3168 // C1*(C2+V) -> C1*C2 + C1*V
3169 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
3170 // If any of Add's ops are Adds or Muls with a constant, apply this
3171 // transformation as well.
3172 //
3173 // TODO: There are some cases where this transformation is not
3174 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
3175 // this transformation should be narrowed down.
3176 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) {
3177 const SCEV *LHS = getMulExpr(LHSC, Add->getOperand(0),
3179 const SCEV *RHS = getMulExpr(LHSC, Add->getOperand(1),
3181 return getAddExpr(LHS, RHS, SCEV::FlagAnyWrap, Depth + 1);
3182 }
3183
3184 if (Ops[0]->isAllOnesValue()) {
3185 // If we have a mul by -1 of an add, try distributing the -1 among the
3186 // add operands.
3187 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3189 bool AnyFolded = false;
3190 for (const SCEV *AddOp : Add->operands()) {
3191 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
3192 Depth + 1);
3193 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3194 NewOps.push_back(Mul);
3195 }
3196 if (AnyFolded)
3197 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3198 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3199 // Negation preserves a recurrence's no self-wrap property.
3201 for (const SCEV *AddRecOp : AddRec->operands())
3202 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
3203 Depth + 1));
3204 // Let M be the minimum representable signed value. AddRec with nsw
3205 // multiplied by -1 can have signed overflow if and only if it takes a
3206 // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3207 // maximum signed value. In all other cases signed overflow is
3208 // impossible.
3209 auto FlagsMask = SCEV::FlagNW;
3210 if (hasFlags(AddRec->getNoWrapFlags(), SCEV::FlagNSW)) {
3211 auto MinInt =
3212 APInt::getSignedMinValue(getTypeSizeInBits(AddRec->getType()));
3213 if (getSignedRangeMin(AddRec) != MinInt)
3214 FlagsMask = setFlags(FlagsMask, SCEV::FlagNSW);
3215 }
3216 return getAddRecExpr(Operands, AddRec->getLoop(),
3217 AddRec->getNoWrapFlags(FlagsMask));
3218 }
3219 }
3220 }
3221 }
3222
3223 // Skip over the add expression until we get to a multiply.
3224 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3225 ++Idx;
3226
3227 // If there are mul operands inline them all into this expression.
3228 if (Idx < Ops.size()) {
3229 bool DeletedMul = false;
3230 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3231 if (Ops.size() > MulOpsInlineThreshold)
3232 break;
3233 // If we have an mul, expand the mul operands onto the end of the
3234 // operands list.
3235 Ops.erase(Ops.begin()+Idx);
3236 append_range(Ops, Mul->operands());
3237 DeletedMul = true;
3238 }
3239
3240 // If we deleted at least one mul, we added operands to the end of the
3241 // list, and they are not necessarily sorted. Recurse to resort and
3242 // resimplify any operands we just acquired.
3243 if (DeletedMul)
3244 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3245 }
3246
3247 // If there are any add recurrences in the operands list, see if any other
3248 // added values are loop invariant. If so, we can fold them into the
3249 // recurrence.
3250 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3251 ++Idx;
3252
3253 // Scan over all recurrences, trying to fold loop invariants into them.
3254 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3255 // Scan all of the other operands to this mul and add them to the vector
3256 // if they are loop invariant w.r.t. the recurrence.
3258 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3259 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3260 if (isAvailableAtLoopEntry(Ops[i], AddRec->getLoop())) {
3261 LIOps.push_back(Ops[i]);
3262 Ops.erase(Ops.begin()+i);
3263 --i; --e;
3264 }
3265
3266 // If we found some loop invariants, fold them into the recurrence.
3267 if (!LIOps.empty()) {
3268 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3270 NewOps.reserve(AddRec->getNumOperands());
3271 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3272
3273 // If both the mul and addrec are nuw, we can preserve nuw.
3274 // If both the mul and addrec are nsw, we can only preserve nsw if either
3275 // a) they are also nuw, or
3276 // b) all multiplications of addrec operands with scale are nsw.
3277 SCEV::NoWrapFlags Flags =
3278 AddRec->getNoWrapFlags(ComputeFlags({Scale, AddRec}));
3279
3280 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3281 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3282 SCEV::FlagAnyWrap, Depth + 1));
3283
3284 if (hasFlags(Flags, SCEV::FlagNSW) && !hasFlags(Flags, SCEV::FlagNUW)) {
3286 Instruction::Mul, getSignedRange(Scale),
3288 if (!NSWRegion.contains(getSignedRange(AddRec->getOperand(i))))
3289 Flags = clearFlags(Flags, SCEV::FlagNSW);
3290 }
3291 }
3292
3293 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(), Flags);
3294
3295 // If all of the other operands were loop invariant, we are done.
3296 if (Ops.size() == 1) return NewRec;
3297
3298 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3299 for (unsigned i = 0;; ++i)
3300 if (Ops[i] == AddRec) {
3301 Ops[i] = NewRec;
3302 break;
3303 }
3304 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3305 }
3306
3307 // Okay, if there weren't any loop invariants to be folded, check to see
3308 // if there are multiple AddRec's with the same loop induction variable
3309 // being multiplied together. If so, we can fold them.
3310
3311 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3312 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3313 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3314 // ]]],+,...up to x=2n}.
3315 // Note that the arguments to choose() are always integers with values
3316 // known at compile time, never SCEV objects.
3317 //
3318 // The implementation avoids pointless extra computations when the two
3319 // addrec's are of different length (mathematically, it's equivalent to
3320 // an infinite stream of zeros on the right).
3321 bool OpsModified = false;
3322 for (unsigned OtherIdx = Idx+1;
3323 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3324 ++OtherIdx) {
3325 const SCEVAddRecExpr *OtherAddRec =
3326 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3327 if (!OtherAddRec || OtherAddRec->getLoop() != AddRec->getLoop())
3328 continue;
3329
3330 // Limit max number of arguments to avoid creation of unreasonably big
3331 // SCEVAddRecs with very complex operands.
3332 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3333 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3334 continue;
3335
3336 bool Overflow = false;
3337 Type *Ty = AddRec->getType();
3338 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3340 for (int x = 0, xe = AddRec->getNumOperands() +
3341 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3342 SmallVector <const SCEV *, 7> SumOps;
3343 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3344 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3345 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3346 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3347 z < ze && !Overflow; ++z) {
3348 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3349 uint64_t Coeff;
3350 if (LargerThan64Bits)
3351 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3352 else
3353 Coeff = Coeff1*Coeff2;
3354 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3355 const SCEV *Term1 = AddRec->getOperand(y-z);
3356 const SCEV *Term2 = OtherAddRec->getOperand(z);
3357 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3358 SCEV::FlagAnyWrap, Depth + 1));
3359 }
3360 }
3361 if (SumOps.empty())
3362 SumOps.push_back(getZero(Ty));
3363 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3364 }
3365 if (!Overflow) {
3366 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
3368 if (Ops.size() == 2) return NewAddRec;
3369 Ops[Idx] = NewAddRec;
3370 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3371 OpsModified = true;
3372 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3373 if (!AddRec)
3374 break;
3375 }
3376 }
3377 if (OpsModified)
3378 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3379
3380 // Otherwise couldn't fold anything into this recurrence. Move onto the
3381 // next one.
3382 }
3383
3384 // Okay, it looks like we really DO need an mul expr. Check to see if we
3385 // already have one, otherwise create a new one.
3386 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3387}
3388
3389/// Represents an unsigned remainder expression based on unsigned division.
3391 const SCEV *RHS) {
3394 "SCEVURemExpr operand types don't match!");
3395
3396 // Short-circuit easy cases
3397 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3398 // If constant is one, the result is trivial
3399 if (RHSC->getValue()->isOne())
3400 return getZero(LHS->getType()); // X urem 1 --> 0
3401
3402 // If constant is a power of two, fold into a zext(trunc(LHS)).
3403 if (RHSC->getAPInt().isPowerOf2()) {
3404 Type *FullTy = LHS->getType();
3405 Type *TruncTy =
3406 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3407 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3408 }
3409 }
3410
3411 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3412 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3413 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3414 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3415}
3416
3417/// Get a canonical unsigned division expression, or something simpler if
3418/// possible.
3420 const SCEV *RHS) {
3421 assert(!LHS->getType()->isPointerTy() &&
3422 "SCEVUDivExpr operand can't be pointer!");
3423 assert(LHS->getType() == RHS->getType() &&
3424 "SCEVUDivExpr operand types don't match!");
3425
3427 ID.AddInteger(scUDivExpr);
3428 ID.AddPointer(LHS);
3429 ID.AddPointer(RHS);
3430 void *IP = nullptr;
3431 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3432 return S;
3433
3434 // 0 udiv Y == 0
3435 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3436 if (LHSC->getValue()->isZero())
3437 return LHS;
3438
3439 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3440 if (RHSC->getValue()->isOne())
3441 return LHS; // X udiv 1 --> x
3442 // If the denominator is zero, the result of the udiv is undefined. Don't
3443 // try to analyze it, because the resolution chosen here may differ from
3444 // the resolution chosen in other parts of the compiler.
3445 if (!RHSC->getValue()->isZero()) {
3446 // Determine if the division can be folded into the operands of
3447 // its operands.
3448 // TODO: Generalize this to non-constants by using known-bits information.
3449 Type *Ty = LHS->getType();
3450 unsigned LZ = RHSC->getAPInt().countl_zero();
3451 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3452 // For non-power-of-two values, effectively round the value up to the
3453 // nearest power of two.
3454 if (!RHSC->getAPInt().isPowerOf2())
3455 ++MaxShiftAmt;
3456 IntegerType *ExtTy =
3457 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3458 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3459 if (const SCEVConstant *Step =
3460 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3461 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3462 const APInt &StepInt = Step->getAPInt();
3463 const APInt &DivInt = RHSC->getAPInt();
3464 if (!StepInt.urem(DivInt) &&
3465 getZeroExtendExpr(AR, ExtTy) ==
3466 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3467 getZeroExtendExpr(Step, ExtTy),
3468 AR->getLoop(), SCEV::FlagAnyWrap)) {
3470 for (const SCEV *Op : AR->operands())
3471 Operands.push_back(getUDivExpr(Op, RHS));
3472 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3473 }
3474 /// Get a canonical UDivExpr for a recurrence.
3475 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3476 // We can currently only fold X%N if X is constant.
3477 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3478 if (StartC && !DivInt.urem(StepInt) &&
3479 getZeroExtendExpr(AR, ExtTy) ==
3480 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3481 getZeroExtendExpr(Step, ExtTy),
3482 AR->getLoop(), SCEV::FlagAnyWrap)) {
3483 const APInt &StartInt = StartC->getAPInt();
3484 const APInt &StartRem = StartInt.urem(StepInt);
3485 if (StartRem != 0) {
3486 const SCEV *NewLHS =
3487 getAddRecExpr(getConstant(StartInt - StartRem), Step,
3488 AR->getLoop(), SCEV::FlagNW);
3489 if (LHS != NewLHS) {
3490 LHS = NewLHS;
3491
3492 // Reset the ID to include the new LHS, and check if it is
3493 // already cached.
3494 ID.clear();
3495 ID.AddInteger(scUDivExpr);
3496 ID.AddPointer(LHS);
3497 ID.AddPointer(RHS);
3498 IP = nullptr;
3499 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3500 return S;
3501 }
3502 }
3503 }
3504 }
3505 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3506 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3508 for (const SCEV *Op : M->operands())
3509 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3510 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3511 // Find an operand that's safely divisible.
3512 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3513 const SCEV *Op = M->getOperand(i);
3514 const SCEV *Div = getUDivExpr(Op, RHSC);
3515 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3516 Operands = SmallVector<const SCEV *, 4>(M->operands());
3517 Operands[i] = Div;
3518 return getMulExpr(Operands);
3519 }
3520 }
3521 }
3522
3523 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3524 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3525 if (auto *DivisorConstant =
3526 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3527 bool Overflow = false;
3528 APInt NewRHS =
3529 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3530 if (Overflow) {
3531 return getConstant(RHSC->getType(), 0, false);
3532 }
3533 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3534 }
3535 }
3536
3537 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3538 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3540 for (const SCEV *Op : A->operands())
3541 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3542 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3543 Operands.clear();
3544 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3545 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3546 if (isa<SCEVUDivExpr>(Op) ||
3547 getMulExpr(Op, RHS) != A->getOperand(i))
3548 break;
3549 Operands.push_back(Op);
3550 }
3551 if (Operands.size() == A->getNumOperands())
3552 return getAddExpr(Operands);
3553 }
3554 }
3555
3556 // Fold if both operands are constant.
3557 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3558 return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3559 }
3560 }
3561
3562 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3563 // changes). Make sure we get a new one.
3564 IP = nullptr;
3565 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3566 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3567 LHS, RHS);
3568 UniqueSCEVs.InsertNode(S, IP);
3569 registerUser(S, {LHS, RHS});
3570 return S;
3571}
3572
3573APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3574 APInt A = C1->getAPInt().abs();
3575 APInt B = C2->getAPInt().abs();
3576 uint32_t ABW = A.getBitWidth();
3577 uint32_t BBW = B.getBitWidth();
3578
3579 if (ABW > BBW)
3580 B = B.zext(ABW);
3581 else if (ABW < BBW)
3582 A = A.zext(BBW);
3583
3584 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3585}
3586
3587/// Get a canonical unsigned division expression, or something simpler if
3588/// possible. There is no representation for an exact udiv in SCEV IR, but we
3589/// can attempt to remove factors from the LHS and RHS. We can't do this when
3590/// it's not exact because the udiv may be clearing bits.
3592 const SCEV *RHS) {
3593 // TODO: we could try to find factors in all sorts of things, but for now we
3594 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3595 // end of this file for inspiration.
3596
3597 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3598 if (!Mul || !Mul->hasNoUnsignedWrap())
3599 return getUDivExpr(LHS, RHS);
3600
3601 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3602 // If the mulexpr multiplies by a constant, then that constant must be the
3603 // first element of the mulexpr.
3604 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3605 if (LHSCst == RHSCst) {
3607 return getMulExpr(Operands);
3608 }
3609
3610 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3611 // that there's a factor provided by one of the other terms. We need to
3612 // check.
3613 APInt Factor = gcd(LHSCst, RHSCst);
3614 if (!Factor.isIntN(1)) {
3615 LHSCst =
3616 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3617 RHSCst =
3618 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3620 Operands.push_back(LHSCst);
3621 append_range(Operands, Mul->operands().drop_front());
3623 RHS = RHSCst;
3624 Mul = dyn_cast<SCEVMulExpr>(LHS);
3625 if (!Mul)
3626 return getUDivExactExpr(LHS, RHS);
3627 }
3628 }
3629 }
3630
3631 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3632 if (Mul->getOperand(i) == RHS) {
3634 append_range(Operands, Mul->operands().take_front(i));
3635 append_range(Operands, Mul->operands().drop_front(i + 1));
3636 return getMulExpr(Operands);
3637 }
3638 }
3639
3640 return getUDivExpr(LHS, RHS);
3641}
3642
3643/// Get an add recurrence expression for the specified loop. Simplify the
3644/// expression as much as possible.
3645const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3646 const Loop *L,
3647 SCEV::NoWrapFlags Flags) {
3649 Operands.push_back(Start);
3650 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3651 if (StepChrec->getLoop() == L) {
3652 append_range(Operands, StepChrec->operands());
3653 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3654 }
3655
3656 Operands.push_back(Step);
3657 return getAddRecExpr(Operands, L, Flags);
3658}
3659
3660/// Get an add recurrence expression for the specified loop. Simplify the
3661/// expression as much as possible.
3662const SCEV *
3664 const Loop *L, SCEV::NoWrapFlags Flags) {
3665 if (Operands.size() == 1) return Operands[0];
3666#ifndef NDEBUG
3668 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
3670 "SCEVAddRecExpr operand types don't match!");
3671 assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer");
3672 }
3673 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3675 "SCEVAddRecExpr operand is not loop-invariant!");
3676#endif
3677
3678 if (Operands.back()->isZero()) {
3679 Operands.pop_back();
3680 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3681 }
3682
3683 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3684 // use that information to infer NUW and NSW flags. However, computing a
3685 // BE count requires calling getAddRecExpr, so we may not yet have a
3686 // meaningful BE count at this point (and if we don't, we'd be stuck
3687 // with a SCEVCouldNotCompute as the cached BE count).
3688
3689 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3690
3691 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3692 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3693 const Loop *NestedLoop = NestedAR->getLoop();
3694 if (L->contains(NestedLoop)
3695 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3696 : (!NestedLoop->contains(L) &&
3697 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3698 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands());
3699 Operands[0] = NestedAR->getStart();
3700 // AddRecs require their operands be loop-invariant with respect to their
3701 // loops. Don't perform this transformation if it would break this
3702 // requirement.
3703 bool AllInvariant = all_of(
3704 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3705
3706 if (AllInvariant) {
3707 // Create a recurrence for the outer loop with the same step size.
3708 //
3709 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3710 // inner recurrence has the same property.
3711 SCEV::NoWrapFlags OuterFlags =
3712 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3713
3714 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3715 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3716 return isLoopInvariant(Op, NestedLoop);
3717 });
3718
3719 if (AllInvariant) {
3720 // Ok, both add recurrences are valid after the transformation.
3721 //
3722 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3723 // the outer recurrence has the same property.
3724 SCEV::NoWrapFlags InnerFlags =
3725 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3726 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3727 }
3728 }
3729 // Reset Operands to its original state.
3730 Operands[0] = NestedAR;
3731 }
3732 }
3733
3734 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3735 // already have one, otherwise create a new one.
3736 return getOrCreateAddRecExpr(Operands, L, Flags);
3737}
3738
3739const SCEV *
3741 const SmallVectorImpl<const SCEV *> &IndexExprs) {
3742 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3743 // getSCEV(Base)->getType() has the same address space as Base->getType()
3744 // because SCEV::getType() preserves the address space.
3745 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3746 const bool AssumeInBoundsFlags = [&]() {
3747 if (!GEP->isInBounds())
3748 return false;
3749
3750 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3751 // but to do that, we have to ensure that said flag is valid in the entire
3752 // defined scope of the SCEV.
3753 auto *GEPI = dyn_cast<Instruction>(GEP);
3754 // TODO: non-instructions have global scope. We might be able to prove
3755 // some global scope cases
3756 return GEPI && isSCEVExprNeverPoison(GEPI);
3757 }();
3758
3759 SCEV::NoWrapFlags OffsetWrap =
3760 AssumeInBoundsFlags ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3761
3762 Type *CurTy = GEP->getType();
3763 bool FirstIter = true;
3765 for (const SCEV *IndexExpr : IndexExprs) {
3766 // Compute the (potentially symbolic) offset in bytes for this index.
3767 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3768 // For a struct, add the member offset.
3769 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3770 unsigned FieldNo = Index->getZExtValue();
3771 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3772 Offsets.push_back(FieldOffset);
3773
3774 // Update CurTy to the type of the field at Index.
3775 CurTy = STy->getTypeAtIndex(Index);
3776 } else {
3777 // Update CurTy to its element type.
3778 if (FirstIter) {
3779 assert(isa<PointerType>(CurTy) &&
3780 "The first index of a GEP indexes a pointer");
3781 CurTy = GEP->getSourceElementType();
3782 FirstIter = false;
3783 } else {
3785 }
3786 // For an array, add the element offset, explicitly scaled.
3787 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3788 // Getelementptr indices are signed.
3789 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3790
3791 // Multiply the index by the element size to compute the element offset.
3792 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3793 Offsets.push_back(LocalOffset);
3794 }
3795 }
3796
3797 // Handle degenerate case of GEP without offsets.
3798 if (Offsets.empty())
3799 return BaseExpr;
3800
3801 // Add the offsets together, assuming nsw if inbounds.
3802 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3803 // Add the base address and the offset. We cannot use the nsw flag, as the
3804 // base address is unsigned. However, if we know that the offset is
3805 // non-negative, we can use nuw.
3806 SCEV::NoWrapFlags BaseWrap = AssumeInBoundsFlags && isKnownNonNegative(Offset)
3808 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3809 assert(BaseExpr->getType() == GEPExpr->getType() &&
3810 "GEP should not change type mid-flight.");
3811 return GEPExpr;
3812}
3813
3814SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3817 ID.AddInteger(SCEVType);
3818 for (const SCEV *Op : Ops)
3819 ID.AddPointer(Op);
3820 void *IP = nullptr;
3821 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3822}
3823
3824const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3826 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3827}
3828
3831 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3832 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3833 if (Ops.size() == 1) return Ops[0];
3834#ifndef NDEBUG
3835 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3836 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3837 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3838 "Operand types don't match!");
3839 assert(Ops[0]->getType()->isPointerTy() ==
3840 Ops[i]->getType()->isPointerTy() &&
3841 "min/max should be consistently pointerish");
3842 }
3843#endif
3844
3845 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3846 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3847
3848 // Sort by complexity, this groups all similar expression types together.
3849 GroupByComplexity(Ops, &LI, DT);
3850
3851 // Check if we have created the same expression before.
3852 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3853 return S;
3854 }
3855
3856 // If there are any constants, fold them together.
3857 unsigned Idx = 0;
3858 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3859 ++Idx;
3860 assert(Idx < Ops.size());
3861 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3862 switch (Kind) {
3863 case scSMaxExpr:
3864 return APIntOps::smax(LHS, RHS);
3865 case scSMinExpr:
3866 return APIntOps::smin(LHS, RHS);
3867 case scUMaxExpr:
3868 return APIntOps::umax(LHS, RHS);
3869 case scUMinExpr:
3870 return APIntOps::umin(LHS, RHS);
3871 default:
3872 llvm_unreachable("Unknown SCEV min/max opcode");
3873 }
3874 };
3875
3876 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3877 // We found two constants, fold them together!
3879 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3880 Ops[0] = getConstant(Fold);
3881 Ops.erase(Ops.begin()+1); // Erase the folded element
3882 if (Ops.size() == 1) return Ops[0];
3883 LHSC = cast<SCEVConstant>(Ops[0]);
3884 }
3885
3886 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3887 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3888
3889 if (IsMax ? IsMinV : IsMaxV) {
3890 // If we are left with a constant minimum(/maximum)-int, strip it off.
3891 Ops.erase(Ops.begin());
3892 --Idx;
3893 } else if (IsMax ? IsMaxV : IsMinV) {
3894 // If we have a max(/min) with a constant maximum(/minimum)-int,
3895 // it will always be the extremum.
3896 return LHSC;
3897 }
3898
3899 if (Ops.size() == 1) return Ops[0];
3900 }
3901
3902 // Find the first operation of the same kind
3903 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3904 ++Idx;
3905
3906 // Check to see if one of the operands is of the same kind. If so, expand its
3907 // operands onto our operand list, and recurse to simplify.
3908 if (Idx < Ops.size()) {
3909 bool DeletedAny = false;
3910 while (Ops[Idx]->getSCEVType() == Kind) {
3911 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3912 Ops.erase(Ops.begin()+Idx);
3913 append_range(Ops, SMME->operands());
3914 DeletedAny = true;
3915 }
3916
3917 if (DeletedAny)
3918 return getMinMaxExpr(Kind, Ops);
3919 }
3920
3921 // Okay, check to see if the same value occurs in the operand list twice. If
3922 // so, delete one. Since we sorted the list, these values are required to
3923 // be adjacent.
3928 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3929 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3930 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3931 if (Ops[i] == Ops[i + 1] ||
3932 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3933 // X op Y op Y --> X op Y
3934 // X op Y --> X, if we know X, Y are ordered appropriately
3935 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3936 --i;
3937 --e;
3938 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3939 Ops[i + 1])) {
3940 // X op Y --> Y, if we know X, Y are ordered appropriately
3941 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3942 --i;
3943 --e;
3944 }
3945 }
3946
3947 if (Ops.size() == 1) return Ops[0];
3948
3949 assert(!Ops.empty() && "Reduced smax down to nothing!");
3950
3951 // Okay, it looks like we really DO need an expr. Check to see if we
3952 // already have one, otherwise create a new one.
3954 ID.AddInteger(Kind);
3955 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3956 ID.AddPointer(Ops[i]);
3957 void *IP = nullptr;
3958 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3959 if (ExistingSCEV)
3960 return ExistingSCEV;
3961 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3962 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3963 SCEV *S = new (SCEVAllocator)
3964 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3965
3966 UniqueSCEVs.InsertNode(S, IP);
3967 registerUser(S, Ops);
3968 return S;
3969}
3970
3971namespace {
3972
3973class SCEVSequentialMinMaxDeduplicatingVisitor final
3974 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
3975 std::optional<const SCEV *>> {
3976 using RetVal = std::optional<const SCEV *>;
3978
3979 ScalarEvolution &SE;
3980 const SCEVTypes RootKind; // Must be a sequential min/max expression.
3981 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
3983
3984 bool canRecurseInto(SCEVTypes Kind) const {
3985 // We can only recurse into the SCEV expression of the same effective type
3986 // as the type of our root SCEV expression.
3987 return RootKind == Kind || NonSequentialRootKind == Kind;
3988 };
3989
3990 RetVal visitAnyMinMaxExpr(const SCEV *S) {
3991 assert((isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) &&
3992 "Only for min/max expressions.");
3993 SCEVTypes Kind = S->getSCEVType();
3994
3995 if (!canRecurseInto(Kind))
3996 return S;
3997
3998 auto *NAry = cast<SCEVNAryExpr>(S);
4000 bool Changed = visit(Kind, NAry->operands(), NewOps);
4001
4002 if (!Changed)
4003 return S;
4004 if (NewOps.empty())
4005 return std::nullopt;
4006
4007 return isa<SCEVSequentialMinMaxExpr>(S)
4008 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
4009 : SE.getMinMaxExpr(Kind, NewOps);
4010 }
4011
4012 RetVal visit(const SCEV *S) {
4013 // Has the whole operand been seen already?
4014 if (!SeenOps.insert(S).second)
4015 return std::nullopt;
4016 return Base::visit(S);
4017 }
4018
4019public:
4020 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
4021 SCEVTypes RootKind)
4022 : SE(SE), RootKind(RootKind),
4023 NonSequentialRootKind(
4024 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4025 RootKind)) {}
4026
4027 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<const SCEV *> OrigOps,
4029 bool Changed = false;
4031 Ops.reserve(OrigOps.size());
4032
4033 for (const SCEV *Op : OrigOps) {
4034 RetVal NewOp = visit(Op);
4035 if (NewOp != Op)
4036 Changed = true;
4037 if (NewOp)
4038 Ops.emplace_back(*NewOp);
4039 }
4040
4041 if (Changed)
4042 NewOps = std::move(Ops);
4043 return Changed;
4044 }
4045
4046 RetVal visitConstant(const SCEVConstant *Constant) { return Constant; }
4047
4048 RetVal visitVScale(const SCEVVScale *VScale) { return VScale; }
4049
4050 RetVal visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) { return Expr; }
4051
4052 RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
4053
4054 RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; }
4055
4056 RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; }
4057
4058 RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; }
4059
4060 RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; }
4061
4062 RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
4063
4064 RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
4065
4066 RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) {
4067 return visitAnyMinMaxExpr(Expr);
4068 }
4069
4070 RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) {
4071 return visitAnyMinMaxExpr(Expr);
4072 }
4073
4074 RetVal visitSMinExpr(const SCEVSMinExpr *Expr) {
4075 return visitAnyMinMaxExpr(Expr);
4076 }
4077
4078 RetVal visitUMinExpr(const SCEVUMinExpr *Expr) {
4079 return visitAnyMinMaxExpr(Expr);
4080 }
4081
4082 RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
4083 return visitAnyMinMaxExpr(Expr);
4084 }
4085
4086 RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; }
4087
4088 RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; }
4089};
4090
4091} // namespace
4092
4094 switch (Kind) {
4095 case scConstant:
4096 case scVScale:
4097 case scTruncate:
4098 case scZeroExtend:
4099 case scSignExtend:
4100 case scPtrToInt:
4101 case scAddExpr:
4102 case scMulExpr:
4103 case scUDivExpr:
4104 case scAddRecExpr:
4105 case scUMaxExpr:
4106 case scSMaxExpr:
4107 case scUMinExpr:
4108 case scSMinExpr:
4109 case scUnknown:
4110 // If any operand is poison, the whole expression is poison.
4111 return true;
4113 // FIXME: if the *first* operand is poison, the whole expression is poison.
4114 return false; // Pessimistically, say that it does not propagate poison.
4115 case scCouldNotCompute:
4116 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4117 }
4118 llvm_unreachable("Unknown SCEV kind!");
4119}
4120
4121namespace {
4122// The only way poison may be introduced in a SCEV expression is from a
4123// poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4124// not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not*
4125// introduce poison -- they encode guaranteed, non-speculated knowledge.
4126//
4127// Additionally, all SCEV nodes propagate poison from inputs to outputs,
4128// with the notable exception of umin_seq, where only poison from the first
4129// operand is (unconditionally) propagated.
4130struct SCEVPoisonCollector {
4131 bool LookThroughMaybePoisonBlocking;
4133 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4134 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4135
4136 bool follow(const SCEV *S) {
4137 if (!LookThroughMaybePoisonBlocking &&
4139 return false;
4140
4141 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4142 if (!isGuaranteedNotToBePoison(SU->getValue()))
4143 MaybePoison.insert(SU);
4144 }
4145 return true;
4146 }
4147 bool isDone() const { return false; }
4148};
4149} // namespace
4150
4151/// Return true if V is poison given that AssumedPoison is already poison.
4152static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4153 // First collect all SCEVs that might result in AssumedPoison to be poison.
4154 // We need to look through potentially poison-blocking operations here,
4155 // because we want to find all SCEVs that *might* result in poison, not only
4156 // those that are *required* to.
4157 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4158 visitAll(AssumedPoison, PC1);
4159
4160 // AssumedPoison is never poison. As the assumption is false, the implication
4161 // is true. Don't bother walking the other SCEV in this case.
4162 if (PC1.MaybePoison.empty())
4163 return true;
4164
4165 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4166 // as well. We cannot look through potentially poison-blocking operations
4167 // here, as their arguments only *may* make the result poison.
4168 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4169 visitAll(S, PC2);
4170
4171 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4172 // it will also make S poison by being part of PC2.MaybePoison.
4173 return all_of(PC1.MaybePoison, [&](const SCEVUnknown *S) {
4174 return PC2.MaybePoison.contains(S);
4175 });
4176}
4177
4179 SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4180 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4181 visitAll(S, PC);
4182 for (const SCEVUnknown *SU : PC.MaybePoison)
4183 Result.insert(SU->getValue());
4184}
4185
4186const SCEV *
4189 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4190 "Not a SCEVSequentialMinMaxExpr!");
4191 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4192 if (Ops.size() == 1)
4193 return Ops[0];
4194#ifndef NDEBUG
4195 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4196 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4197 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4198 "Operand types don't match!");
4199 assert(Ops[0]->getType()->isPointerTy() ==
4200 Ops[i]->getType()->isPointerTy() &&
4201 "min/max should be consistently pointerish");
4202 }
4203#endif
4204
4205 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4206 // so we can *NOT* do any kind of sorting of the expressions!
4207
4208 // Check if we have created the same expression before.
4209 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4210 return S;
4211
4212 // FIXME: there are *some* simplifications that we can do here.
4213
4214 // Keep only the first instance of an operand.
4215 {
4216 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4217 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4218 if (Changed)
4219 return getSequentialMinMaxExpr(Kind, Ops);
4220 }
4221
4222 // Check to see if one of the operands is of the same kind. If so, expand its
4223 // operands onto our operand list, and recurse to simplify.
4224 {
4225 unsigned Idx = 0;
4226 bool DeletedAny = false;
4227 while (Idx < Ops.size()) {
4228 if (Ops[Idx]->getSCEVType() != Kind) {
4229 ++Idx;
4230 continue;
4231 }
4232 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4233 Ops.erase(Ops.begin() + Idx);
4234 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4235 SMME->operands().end());
4236 DeletedAny = true;
4237 }
4238
4239 if (DeletedAny)
4240 return getSequentialMinMaxExpr(Kind, Ops);
4241 }
4242
4243 const SCEV *SaturationPoint;
4245 switch (Kind) {
4247 SaturationPoint = getZero(Ops[0]->getType());
4248 Pred = ICmpInst::ICMP_ULE;
4249 break;
4250 default:
4251 llvm_unreachable("Not a sequential min/max type.");
4252 }
4253
4254 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4255 // We can replace %x umin_seq %y with %x umin %y if either:
4256 // * %y being poison implies %x is also poison.
4257 // * %x cannot be the saturating value (e.g. zero for umin).
4258 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4259 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4260 SaturationPoint)) {
4261 SmallVector<const SCEV *> SeqOps = {Ops[i - 1], Ops[i]};
4262 Ops[i - 1] = getMinMaxExpr(
4264 SeqOps);
4265 Ops.erase(Ops.begin() + i);
4266 return getSequentialMinMaxExpr(Kind, Ops);
4267 }
4268 // Fold %x umin_seq %y to %x if %x ule %y.
4269 // TODO: We might be able to prove the predicate for a later operand.
4270 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4271 Ops.erase(Ops.begin() + i);
4272 return getSequentialMinMaxExpr(Kind, Ops);
4273 }
4274 }
4275
4276 // Okay, it looks like we really DO need an expr. Check to see if we
4277 // already have one, otherwise create a new one.
4279 ID.AddInteger(Kind);
4280 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
4281 ID.AddPointer(Ops[i]);
4282 void *IP = nullptr;
4283 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4284 if (ExistingSCEV)
4285 return ExistingSCEV;
4286
4287 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
4288 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
4289 SCEV *S = new (SCEVAllocator)
4290 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4291
4292 UniqueSCEVs.InsertNode(S, IP);
4293 registerUser(S, Ops);
4294 return S;
4295}
4296
4297const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4299 return getSMaxExpr(Ops);
4300}
4301
4303 return getMinMaxExpr(scSMaxExpr, Ops);
4304}
4305
4306const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4308 return getUMaxExpr(Ops);
4309}
4310
4312 return getMinMaxExpr(scUMaxExpr, Ops);
4313}
4314
4316 const SCEV *RHS) {
4318 return getSMinExpr(Ops);
4319}
4320
4322 return getMinMaxExpr(scSMinExpr, Ops);
4323}
4324
4325const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, const SCEV *RHS,
4326 bool Sequential) {
4328 return getUMinExpr(Ops, Sequential);
4329}
4330
4332 bool Sequential) {
4333 return Sequential ? getSequentialMinMaxExpr(scSequentialUMinExpr, Ops)
4334 : getMinMaxExpr(scUMinExpr, Ops);
4335}
4336
4337const SCEV *
4339 const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4340 if (Size.isScalable())
4341 Res = getMulExpr(Res, getVScale(IntTy));
4342 return Res;
4343}
4344
4346 return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4347}
4348
4350 return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4351}
4352
4354 StructType *STy,
4355 unsigned FieldNo) {
4356 // We can bypass creating a target-independent constant expression and then
4357 // folding it back into a ConstantInt. This is just a compile-time
4358 // optimization.
4359 const StructLayout *SL = getDataLayout().getStructLayout(STy);
4360 assert(!SL->getSizeInBits().isScalable() &&
4361 "Cannot get offset for structure containing scalable vector types");
4362 return getConstant(IntTy, SL->getElementOffset(FieldNo));
4363}
4364
4366 // Don't attempt to do anything other than create a SCEVUnknown object
4367 // here. createSCEV only calls getUnknown after checking for all other
4368 // interesting possibilities, and any other code that calls getUnknown
4369 // is doing so in order to hide a value from SCEV canonicalization.
4370
4372 ID.AddInteger(scUnknown);
4373 ID.AddPointer(V);
4374 void *IP = nullptr;
4375 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
4376 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4377 "Stale SCEVUnknown in uniquing map!");
4378 return S;
4379 }
4380 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4381 FirstUnknown);
4382 FirstUnknown = cast<SCEVUnknown>(S);
4383 UniqueSCEVs.InsertNode(S, IP);
4384 return S;
4385}
4386
4387//===----------------------------------------------------------------------===//
4388// Basic SCEV Analysis and PHI Idiom Recognition Code
4389//
4390
4391/// Test if values of the given type are analyzable within the SCEV
4392/// framework. This primarily includes integer types, and it can optionally
4393/// include pointer types if the ScalarEvolution class has access to
4394/// target-specific information.
4396 // Integers and pointers are always SCEVable.
4397 return Ty->isIntOrPtrTy();
4398}
4399
4400/// Return the size in bits of the specified type, for which isSCEVable must
4401/// return true.
4403 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4404 if (Ty->isPointerTy())
4406 return getDataLayout().getTypeSizeInBits(Ty);
4407}
4408
4409/// Return a type with the same bitwidth as the given type and which represents
4410/// how SCEV will treat the given type, for which isSCEVable must return
4411/// true. For pointer types, this is the pointer index sized integer type.
4413 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4414
4415 if (Ty->isIntegerTy())
4416 return Ty;
4417
4418 // The only other support type is pointer.
4419 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4420 return getDataLayout().getIndexType(Ty);
4421}
4422
4424 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4425}
4426
4428 const SCEV *B) {
4429 /// For a valid use point to exist, the defining scope of one operand
4430 /// must dominate the other.
4431 bool PreciseA, PreciseB;
4432 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4433 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4434 if (!PreciseA || !PreciseB)
4435 // Can't tell.
4436 return false;
4437 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4438 DT.dominates(ScopeB, ScopeA);
4439}
4440
4442 return CouldNotCompute.get();
4443}
4444
4445bool ScalarEvolution::checkValidity(const SCEV *S) const {
4446 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4447 auto *SU = dyn_cast<SCEVUnknown>(S);
4448 return SU && SU->getValue() == nullptr;
4449 });
4450
4451 return !ContainsNulls;
4452}
4453
4455 HasRecMapType::iterator I = HasRecMap.find(S);
4456 if (I != HasRecMap.end())
4457 return I->second;
4458
4459 bool FoundAddRec =
4460 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4461 HasRecMap.insert({S, FoundAddRec});
4462 return FoundAddRec;
4463}
4464
4465/// Return the ValueOffsetPair set for \p S. \p S can be represented
4466/// by the value and offset from any ValueOffsetPair in the set.
4467ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4468 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4469 if (SI == ExprValueMap.end())
4470 return std::nullopt;
4471 return SI->second.getArrayRef();
4472}
4473
4474/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4475/// cannot be used separately. eraseValueFromMap should be used to remove
4476/// V from ValueExprMap and ExprValueMap at the same time.
4477void ScalarEvolution::eraseValueFromMap(Value *V) {
4478 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4479 if (I != ValueExprMap.end()) {
4480 auto EVIt = ExprValueMap.find(I->second);
4481 bool Removed = EVIt->second.remove(V);
4482 (void) Removed;
4483 assert(Removed && "Value not in ExprValueMap?");
4484 ValueExprMap.erase(I);
4485 }
4486}
4487
4488void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4489 // A recursive query may have already computed the SCEV. It should be
4490 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4491 // inferred nowrap flags.
4492 auto It = ValueExprMap.find_as(V);
4493 if (It == ValueExprMap.end()) {
4494 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4495 ExprValueMap[S].insert(V);
4496 }
4497}
4498
4499/// Determine whether this instruction is either not SCEVable or will always
4500/// produce a SCEVUnknown. We do not have to walk past such instructions when
4501/// invalidating.
4502static bool isAlwaysUnknown(const Instruction *I) {
4503 switch (I->getOpcode()) {
4504 case Instruction::Load:
4505 return true;
4506 default:
4507 return false;
4508 }
4509