LLVM 20.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
491 return getConstant(ConstantInt::get(getContext(), Val));
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 *Res = getConstant(Ty, EC.getKnownMinValue());
514 if (EC.isScalable())
515 Res = getMulExpr(Res, getVScale(Ty));
516 return Res;
517}
518
520 const SCEV *op, Type *ty)
521 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {}
522
523SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op,
524 Type *ITy)
525 : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
527 "Must be a non-bit-width-changing pointer-to-integer cast!");
528}
529
531 SCEVTypes SCEVTy, const SCEV *op,
532 Type *ty)
533 : SCEVCastExpr(ID, SCEVTy, op, ty) {}
534
535SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op,
536 Type *ty)
538 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
539 "Cannot truncate non-integer value!");
540}
541
542SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
543 const SCEV *op, Type *ty)
545 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
546 "Cannot zero extend non-integer value!");
547}
548
549SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
550 const SCEV *op, Type *ty)
552 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
553 "Cannot sign extend non-integer value!");
554}
555
556void SCEVUnknown::deleted() {
557 // Clear this SCEVUnknown from various maps.
558 SE->forgetMemoizedResults(this);
559
560 // Remove this SCEVUnknown from the uniquing map.
561 SE->UniqueSCEVs.RemoveNode(this);
562
563 // Release the value.
564 setValPtr(nullptr);
565}
566
567void SCEVUnknown::allUsesReplacedWith(Value *New) {
568 // Clear this SCEVUnknown from various maps.
569 SE->forgetMemoizedResults(this);
570
571 // Remove this SCEVUnknown from the uniquing map.
572 SE->UniqueSCEVs.RemoveNode(this);
573
574 // Replace the value pointer in case someone is still using this SCEVUnknown.
575 setValPtr(New);
576}
577
578//===----------------------------------------------------------------------===//
579// SCEV Utilities
580//===----------------------------------------------------------------------===//
581
582/// Compare the two values \p LV and \p RV in terms of their "complexity" where
583/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
584/// operands in SCEV expressions.
585static int CompareValueComplexity(const LoopInfo *const LI, Value *LV,
586 Value *RV, unsigned Depth) {
588 return 0;
589
590 // Order pointer values after integer values. This helps SCEVExpander form
591 // GEPs.
592 bool LIsPointer = LV->getType()->isPointerTy(),
593 RIsPointer = RV->getType()->isPointerTy();
594 if (LIsPointer != RIsPointer)
595 return (int)LIsPointer - (int)RIsPointer;
596
597 // Compare getValueID values.
598 unsigned LID = LV->getValueID(), RID = RV->getValueID();
599 if (LID != RID)
600 return (int)LID - (int)RID;
601
602 // Sort arguments by their position.
603 if (const auto *LA = dyn_cast<Argument>(LV)) {
604 const auto *RA = cast<Argument>(RV);
605 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
606 return (int)LArgNo - (int)RArgNo;
607 }
608
609 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
610 const auto *RGV = cast<GlobalValue>(RV);
611
612 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
613 auto LT = GV->getLinkage();
614 return !(GlobalValue::isPrivateLinkage(LT) ||
616 };
617
618 // Use the names to distinguish the two values, but only if the
619 // names are semantically important.
620 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
621 return LGV->getName().compare(RGV->getName());
622 }
623
624 // For instructions, compare their loop depth, and their operand count. This
625 // is pretty loose.
626 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
627 const auto *RInst = cast<Instruction>(RV);
628
629 // Compare loop depths.
630 const BasicBlock *LParent = LInst->getParent(),
631 *RParent = RInst->getParent();
632 if (LParent != RParent) {
633 unsigned LDepth = LI->getLoopDepth(LParent),
634 RDepth = LI->getLoopDepth(RParent);
635 if (LDepth != RDepth)
636 return (int)LDepth - (int)RDepth;
637 }
638
639 // Compare the number of operands.
640 unsigned LNumOps = LInst->getNumOperands(),
641 RNumOps = RInst->getNumOperands();
642 if (LNumOps != RNumOps)
643 return (int)LNumOps - (int)RNumOps;
644
645 for (unsigned Idx : seq(LNumOps)) {
646 int Result = CompareValueComplexity(LI, LInst->getOperand(Idx),
647 RInst->getOperand(Idx), Depth + 1);
648 if (Result != 0)
649 return Result;
650 }
651 }
652
653 return 0;
654}
655
656// Return negative, zero, or positive, if LHS is less than, equal to, or greater
657// than RHS, respectively. A three-way result allows recursive comparisons to be
658// more efficient.
659// If the max analysis depth was reached, return std::nullopt, assuming we do
660// not know if they are equivalent for sure.
661static std::optional<int>
663 const LoopInfo *const LI, const SCEV *LHS,
664 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
665 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
666 if (LHS == RHS)
667 return 0;
668
669 // Primarily, sort the SCEVs by their getSCEVType().
670 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
671 if (LType != RType)
672 return (int)LType - (int)RType;
673
674 if (EqCacheSCEV.isEquivalent(LHS, RHS))
675 return 0;
676
678 return std::nullopt;
679
680 // Aside from the getSCEVType() ordering, the particular ordering
681 // isn't very important except that it's beneficial to be consistent,
682 // so that (a + b) and (b + a) don't end up as different expressions.
683 switch (LType) {
684 case scUnknown: {
685 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
686 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
687
688 int X =
689 CompareValueComplexity(LI, LU->getValue(), RU->getValue(), Depth + 1);
690 if (X == 0)
691 EqCacheSCEV.unionSets(LHS, RHS);
692 return X;
693 }
694
695 case scConstant: {
696 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
697 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
698
699 // Compare constant values.
700 const APInt &LA = LC->getAPInt();
701 const APInt &RA = RC->getAPInt();
702 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
703 if (LBitWidth != RBitWidth)
704 return (int)LBitWidth - (int)RBitWidth;
705 return LA.ult(RA) ? -1 : 1;
706 }
707
708 case scVScale: {
709 const auto *LTy = cast<IntegerType>(cast<SCEVVScale>(LHS)->getType());
710 const auto *RTy = cast<IntegerType>(cast<SCEVVScale>(RHS)->getType());
711 return LTy->getBitWidth() - RTy->getBitWidth();
712 }
713
714 case scAddRecExpr: {
715 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
716 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
717
718 // There is always a dominance between two recs that are used by one SCEV,
719 // so we can safely sort recs by loop header dominance. We require such
720 // order in getAddExpr.
721 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
722 if (LLoop != RLoop) {
723 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
724 assert(LHead != RHead && "Two loops share the same header?");
725 if (DT.dominates(LHead, RHead))
726 return 1;
727 assert(DT.dominates(RHead, LHead) &&
728 "No dominance between recurrences used by one SCEV?");
729 return -1;
730 }
731
732 [[fallthrough]];
733 }
734
735 case scTruncate:
736 case scZeroExtend:
737 case scSignExtend:
738 case scPtrToInt:
739 case scAddExpr:
740 case scMulExpr:
741 case scUDivExpr:
742 case scSMaxExpr:
743 case scUMaxExpr:
744 case scSMinExpr:
745 case scUMinExpr:
747 ArrayRef<const SCEV *> LOps = LHS->operands();
748 ArrayRef<const SCEV *> ROps = RHS->operands();
749
750 // Lexicographically compare n-ary-like expressions.
751 unsigned LNumOps = LOps.size(), RNumOps = ROps.size();
752 if (LNumOps != RNumOps)
753 return (int)LNumOps - (int)RNumOps;
754
755 for (unsigned i = 0; i != LNumOps; ++i) {
756 auto X = CompareSCEVComplexity(EqCacheSCEV, LI, LOps[i], ROps[i], DT,
757 Depth + 1);
758 if (X != 0)
759 return X;
760 }
761 EqCacheSCEV.unionSets(LHS, RHS);
762 return 0;
763 }
764
766 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
767 }
768 llvm_unreachable("Unknown SCEV kind!");
769}
770
771/// Given a list of SCEV objects, order them by their complexity, and group
772/// objects of the same complexity together by value. When this routine is
773/// finished, we know that any duplicates in the vector are consecutive and that
774/// complexity is monotonically increasing.
775///
776/// Note that we go take special precautions to ensure that we get deterministic
777/// results from this routine. In other words, we don't want the results of
778/// this to depend on where the addresses of various SCEV objects happened to
779/// land in memory.
781 LoopInfo *LI, DominatorTree &DT) {
782 if (Ops.size() < 2) return; // Noop
783
785
786 // Whether LHS has provably less complexity than RHS.
787 auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) {
788 auto Complexity = CompareSCEVComplexity(EqCacheSCEV, LI, LHS, RHS, DT);
789 return Complexity && *Complexity < 0;
790 };
791 if (Ops.size() == 2) {
792 // This is the common case, which also happens to be trivially simple.
793 // Special case it.
794 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
795 if (IsLessComplex(RHS, LHS))
796 std::swap(LHS, RHS);
797 return;
798 }
799
800 // Do the rough sort by complexity.
801 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
802 return IsLessComplex(LHS, RHS);
803 });
804
805 // Now that we are sorted by complexity, group elements of the same
806 // complexity. Note that this is, at worst, N^2, but the vector is likely to
807 // be extremely short in practice. Note that we take this approach because we
808 // do not want to depend on the addresses of the objects we are grouping.
809 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
810 const SCEV *S = Ops[i];
811 unsigned Complexity = S->getSCEVType();
812
813 // If there are any objects of the same complexity and same value as this
814 // one, group them.
815 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
816 if (Ops[j] == S) { // Found a duplicate.
817 // Move it to immediately after i'th element.
818 std::swap(Ops[i+1], Ops[j]);
819 ++i; // no need to rescan it.
820 if (i == e-2) return; // Done!
821 }
822 }
823 }
824}
825
826/// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
827/// least HugeExprThreshold nodes).
829 return any_of(Ops, [](const SCEV *S) {
831 });
832}
833
834/// Performs a number of common optimizations on the passed \p Ops. If the
835/// whole expression reduces down to a single operand, it will be returned.
836///
837/// The following optimizations are performed:
838/// * Fold constants using the \p Fold function.
839/// * Remove identity constants satisfying \p IsIdentity.
840/// * If a constant satisfies \p IsAbsorber, return it.
841/// * Sort operands by complexity.
842template <typename FoldT, typename IsIdentityT, typename IsAbsorberT>
843static const SCEV *
845 SmallVectorImpl<const SCEV *> &Ops, FoldT Fold,
846 IsIdentityT IsIdentity, IsAbsorberT IsAbsorber) {
847 const SCEVConstant *Folded = nullptr;
848 for (unsigned Idx = 0; Idx < Ops.size();) {
849 const SCEV *Op = Ops[Idx];
850 if (const auto *C = dyn_cast<SCEVConstant>(Op)) {
851 if (!Folded)
852 Folded = C;
853 else
854 Folded = cast<SCEVConstant>(
855 SE.getConstant(Fold(Folded->getAPInt(), C->getAPInt())));
856 Ops.erase(Ops.begin() + Idx);
857 continue;
858 }
859 ++Idx;
860 }
861
862 if (Ops.empty()) {
863 assert(Folded && "Must have folded value");
864 return Folded;
865 }
866
867 if (Folded && IsAbsorber(Folded->getAPInt()))
868 return Folded;
869
870 GroupByComplexity(Ops, &LI, DT);
871 if (Folded && !IsIdentity(Folded->getAPInt()))
872 Ops.insert(Ops.begin(), Folded);
873
874 return Ops.size() == 1 ? Ops[0] : nullptr;
875}
876
877//===----------------------------------------------------------------------===//
878// Simple SCEV method implementations
879//===----------------------------------------------------------------------===//
880
881/// Compute BC(It, K). The result has width W. Assume, K > 0.
882static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
883 ScalarEvolution &SE,
884 Type *ResultTy) {
885 // Handle the simplest case efficiently.
886 if (K == 1)
887 return SE.getTruncateOrZeroExtend(It, ResultTy);
888
889 // We are using the following formula for BC(It, K):
890 //
891 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
892 //
893 // Suppose, W is the bitwidth of the return value. We must be prepared for
894 // overflow. Hence, we must assure that the result of our computation is
895 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
896 // safe in modular arithmetic.
897 //
898 // However, this code doesn't use exactly that formula; the formula it uses
899 // is something like the following, where T is the number of factors of 2 in
900 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
901 // exponentiation:
902 //
903 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
904 //
905 // This formula is trivially equivalent to the previous formula. However,
906 // this formula can be implemented much more efficiently. The trick is that
907 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
908 // arithmetic. To do exact division in modular arithmetic, all we have
909 // to do is multiply by the inverse. Therefore, this step can be done at
910 // width W.
911 //
912 // The next issue is how to safely do the division by 2^T. The way this
913 // is done is by doing the multiplication step at a width of at least W + T
914 // bits. This way, the bottom W+T bits of the product are accurate. Then,
915 // when we perform the division by 2^T (which is equivalent to a right shift
916 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
917 // truncated out after the division by 2^T.
918 //
919 // In comparison to just directly using the first formula, this technique
920 // is much more efficient; using the first formula requires W * K bits,
921 // but this formula less than W + K bits. Also, the first formula requires
922 // a division step, whereas this formula only requires multiplies and shifts.
923 //
924 // It doesn't matter whether the subtraction step is done in the calculation
925 // width or the input iteration count's width; if the subtraction overflows,
926 // the result must be zero anyway. We prefer here to do it in the width of
927 // the induction variable because it helps a lot for certain cases; CodeGen
928 // isn't smart enough to ignore the overflow, which leads to much less
929 // efficient code if the width of the subtraction is wider than the native
930 // register width.
931 //
932 // (It's possible to not widen at all by pulling out factors of 2 before
933 // the multiplication; for example, K=2 can be calculated as
934 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
935 // extra arithmetic, so it's not an obvious win, and it gets
936 // much more complicated for K > 3.)
937
938 // Protection from insane SCEVs; this bound is conservative,
939 // but it probably doesn't matter.
940 if (K > 1000)
941 return SE.getCouldNotCompute();
942
943 unsigned W = SE.getTypeSizeInBits(ResultTy);
944
945 // Calculate K! / 2^T and T; we divide out the factors of two before
946 // multiplying for calculating K! / 2^T to avoid overflow.
947 // Other overflow doesn't matter because we only care about the bottom
948 // W bits of the result.
949 APInt OddFactorial(W, 1);
950 unsigned T = 1;
951 for (unsigned i = 3; i <= K; ++i) {
952 unsigned TwoFactors = countr_zero(i);
953 T += TwoFactors;
954 OddFactorial *= (i >> TwoFactors);
955 }
956
957 // We need at least W + T bits for the multiplication step
958 unsigned CalculationBits = W + T;
959
960 // Calculate 2^T, at width T+W.
961 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
962
963 // Calculate the multiplicative inverse of K! / 2^T;
964 // this multiplication factor will perform the exact division by
965 // K! / 2^T.
966 APInt MultiplyFactor = OddFactorial.multiplicativeInverse();
967
968 // Calculate the product, at width T+W
969 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
970 CalculationBits);
971 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
972 for (unsigned i = 1; i != K; ++i) {
973 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
974 Dividend = SE.getMulExpr(Dividend,
975 SE.getTruncateOrZeroExtend(S, CalculationTy));
976 }
977
978 // Divide by 2^T
979 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
980
981 // Truncate the result, and divide by K! / 2^T.
982
983 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
984 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
985}
986
987/// Return the value of this chain of recurrences at the specified iteration
988/// number. We can evaluate this recurrence by multiplying each element in the
989/// chain by the binomial coefficient corresponding to it. In other words, we
990/// can evaluate {A,+,B,+,C,+,D} as:
991///
992/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
993///
994/// where BC(It, k) stands for binomial coefficient.
996 ScalarEvolution &SE) const {
997 return evaluateAtIteration(operands(), It, SE);
998}
999
1000const SCEV *
1002 const SCEV *It, ScalarEvolution &SE) {
1003 assert(Operands.size() > 0);
1004 const SCEV *Result = Operands[0];
1005 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1006 // The computation is correct in the face of overflow provided that the
1007 // multiplication is performed _after_ the evaluation of the binomial
1008 // coefficient.
1009 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
1010 if (isa<SCEVCouldNotCompute>(Coeff))
1011 return Coeff;
1012
1013 Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff));
1014 }
1015 return Result;
1016}
1017
1018//===----------------------------------------------------------------------===//
1019// SCEV Expression folder implementations
1020//===----------------------------------------------------------------------===//
1021
1023 unsigned Depth) {
1024 assert(Depth <= 1 &&
1025 "getLosslessPtrToIntExpr() should self-recurse at most once.");
1026
1027 // We could be called with an integer-typed operands during SCEV rewrites.
1028 // Since the operand is an integer already, just perform zext/trunc/self cast.
1029 if (!Op->getType()->isPointerTy())
1030 return Op;
1031
1032 // What would be an ID for such a SCEV cast expression?
1034 ID.AddInteger(scPtrToInt);
1035 ID.AddPointer(Op);
1036
1037 void *IP = nullptr;
1038
1039 // Is there already an expression for such a cast?
1040 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1041 return S;
1042
1043 // It isn't legal for optimizations to construct new ptrtoint expressions
1044 // for non-integral pointers.
1045 if (getDataLayout().isNonIntegralPointerType(Op->getType()))
1046 return getCouldNotCompute();
1047
1048 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1049
1050 // We can only trivially model ptrtoint if SCEV's effective (integer) type
1051 // is sufficiently wide to represent all possible pointer values.
1052 // We could theoretically teach SCEV to truncate wider pointers, but
1053 // that isn't implemented for now.
1055 getDataLayout().getTypeSizeInBits(IntPtrTy))
1056 return getCouldNotCompute();
1057
1058 // If not, is this expression something we can't reduce any further?
1059 if (auto *U = dyn_cast<SCEVUnknown>(Op)) {
1060 // Perform some basic constant folding. If the operand of the ptr2int cast
1061 // is a null pointer, don't create a ptr2int SCEV expression (that will be
1062 // left as-is), but produce a zero constant.
1063 // NOTE: We could handle a more general case, but lack motivational cases.
1064 if (isa<ConstantPointerNull>(U->getValue()))
1065 return getZero(IntPtrTy);
1066
1067 // Create an explicit cast node.
1068 // We can reuse the existing insert position since if we get here,
1069 // we won't have made any changes which would invalidate it.
1070 SCEV *S = new (SCEVAllocator)
1071 SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1072 UniqueSCEVs.InsertNode(S, IP);
1073 registerUser(S, Op);
1074 return S;
1075 }
1076
1077 assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for "
1078 "non-SCEVUnknown's.");
1079
1080 // Otherwise, we've got some expression that is more complex than just a
1081 // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1082 // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1083 // only, and the expressions must otherwise be integer-typed.
1084 // So sink the cast down to the SCEVUnknown's.
1085
1086 /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1087 /// which computes a pointer-typed value, and rewrites the whole expression
1088 /// tree so that *all* the computations are done on integers, and the only
1089 /// pointer-typed operands in the expression are SCEVUnknown.
1090 class SCEVPtrToIntSinkingRewriter
1091 : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1093
1094 public:
1095 SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1096
1097 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1098 SCEVPtrToIntSinkingRewriter Rewriter(SE);
1099 return Rewriter.visit(Scev);
1100 }
1101
1102 const SCEV *visit(const SCEV *S) {
1103 Type *STy = S->getType();
1104 // If the expression is not pointer-typed, just keep it as-is.
1105 if (!STy->isPointerTy())
1106 return S;
1107 // Else, recursively sink the cast down into it.
1108 return Base::visit(S);
1109 }
1110
1111 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1113 bool Changed = false;
1114 for (const auto *Op : Expr->operands()) {
1115 Operands.push_back(visit(Op));
1116 Changed |= Op != Operands.back();
1117 }
1118 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1119 }
1120
1121 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1123 bool Changed = false;
1124 for (const auto *Op : Expr->operands()) {
1125 Operands.push_back(visit(Op));
1126 Changed |= Op != Operands.back();
1127 }
1128 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1129 }
1130
1131 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1132 assert(Expr->getType()->isPointerTy() &&
1133 "Should only reach pointer-typed SCEVUnknown's.");
1134 return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1);
1135 }
1136 };
1137
1138 // And actually perform the cast sinking.
1139 const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1140 assert(IntOp->getType()->isIntegerTy() &&
1141 "We must have succeeded in sinking the cast, "
1142 "and ending up with an integer-typed expression!");
1143 return IntOp;
1144}
1145
1147 assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1148
1149 const SCEV *IntOp = getLosslessPtrToIntExpr(Op);
1150 if (isa<SCEVCouldNotCompute>(IntOp))
1151 return IntOp;
1152
1153 return getTruncateOrZeroExtend(IntOp, Ty);
1154}
1155
1157 unsigned Depth) {
1158 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1159 "This is not a truncating conversion!");
1160 assert(isSCEVable(Ty) &&
1161 "This is not a conversion to a SCEVable type!");
1162 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1163 Ty = getEffectiveSCEVType(Ty);
1164
1166 ID.AddInteger(scTruncate);
1167 ID.AddPointer(Op);
1168 ID.AddPointer(Ty);
1169 void *IP = nullptr;
1170 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1171
1172 // Fold if the operand is constant.
1173 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1174 return getConstant(
1175 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1176
1177 // trunc(trunc(x)) --> trunc(x)
1178 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1179 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1180
1181 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1182 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1183 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1184
1185 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1186 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1187 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1188
1189 if (Depth > MaxCastDepth) {
1190 SCEV *S =
1191 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1192 UniqueSCEVs.InsertNode(S, IP);
1193 registerUser(S, Op);
1194 return S;
1195 }
1196
1197 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1198 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1199 // if after transforming we have at most one truncate, not counting truncates
1200 // that replace other casts.
1201 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1202 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1204 unsigned numTruncs = 0;
1205 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1206 ++i) {
1207 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1208 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1209 isa<SCEVTruncateExpr>(S))
1210 numTruncs++;
1211 Operands.push_back(S);
1212 }
1213 if (numTruncs < 2) {
1214 if (isa<SCEVAddExpr>(Op))
1215 return getAddExpr(Operands);
1216 if (isa<SCEVMulExpr>(Op))
1217 return getMulExpr(Operands);
1218 llvm_unreachable("Unexpected SCEV type for Op.");
1219 }
1220 // Although we checked in the beginning that ID is not in the cache, it is
1221 // possible that during recursion and different modification ID was inserted
1222 // into the cache. So if we find it, just return it.
1223 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1224 return S;
1225 }
1226
1227 // If the input value is a chrec scev, truncate the chrec's operands.
1228 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1230 for (const SCEV *Op : AddRec->operands())
1231 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1232 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1233 }
1234
1235 // Return zero if truncating to known zeros.
1236 uint32_t MinTrailingZeros = getMinTrailingZeros(Op);
1237 if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1238 return getZero(Ty);
1239
1240 // The cast wasn't folded; create an explicit cast node. We can reuse
1241 // the existing insert position since if we get here, we won't have
1242 // made any changes which would invalidate it.
1243 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1244 Op, Ty);
1245 UniqueSCEVs.InsertNode(S, IP);
1246 registerUser(S, Op);
1247 return S;
1248}
1249
1250// Get the limit of a recurrence such that incrementing by Step cannot cause
1251// signed overflow as long as the value of the recurrence within the
1252// loop does not exceed this limit before incrementing.
1253static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1254 ICmpInst::Predicate *Pred,
1255 ScalarEvolution *SE) {
1256 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1257 if (SE->isKnownPositive(Step)) {
1258 *Pred = ICmpInst::ICMP_SLT;
1260 SE->getSignedRangeMax(Step));
1261 }
1262 if (SE->isKnownNegative(Step)) {
1263 *Pred = ICmpInst::ICMP_SGT;
1265 SE->getSignedRangeMin(Step));
1266 }
1267 return nullptr;
1268}
1269
1270// Get the limit of a recurrence such that incrementing by Step cannot cause
1271// unsigned overflow as long as the value of the recurrence within the loop does
1272// not exceed this limit before incrementing.
1274 ICmpInst::Predicate *Pred,
1275 ScalarEvolution *SE) {
1276 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1277 *Pred = ICmpInst::ICMP_ULT;
1278
1280 SE->getUnsignedRangeMax(Step));
1281}
1282
1283namespace {
1284
1285struct ExtendOpTraitsBase {
1286 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1287 unsigned);
1288};
1289
1290// Used to make code generic over signed and unsigned overflow.
1291template <typename ExtendOp> struct ExtendOpTraits {
1292 // Members present:
1293 //
1294 // static const SCEV::NoWrapFlags WrapType;
1295 //
1296 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1297 //
1298 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1299 // ICmpInst::Predicate *Pred,
1300 // ScalarEvolution *SE);
1301};
1302
1303template <>
1304struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1305 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1306
1307 static const GetExtendExprTy GetExtendExpr;
1308
1309 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1310 ICmpInst::Predicate *Pred,
1311 ScalarEvolution *SE) {
1312 return getSignedOverflowLimitForStep(Step, Pred, SE);
1313 }
1314};
1315
1316const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1318
1319template <>
1320struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1321 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1322
1323 static const GetExtendExprTy GetExtendExpr;
1324
1325 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1326 ICmpInst::Predicate *Pred,
1327 ScalarEvolution *SE) {
1328 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1329 }
1330};
1331
1332const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1334
1335} // end anonymous namespace
1336
1337// The recurrence AR has been shown to have no signed/unsigned wrap or something
1338// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1339// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1340// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1341// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1342// expression "Step + sext/zext(PreIncAR)" is congruent with
1343// "sext/zext(PostIncAR)"
1344template <typename ExtendOpTy>
1345static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1346 ScalarEvolution *SE, unsigned Depth) {
1347 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1348 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1349
1350 const Loop *L = AR->getLoop();
1351 const SCEV *Start = AR->getStart();
1352 const SCEV *Step = AR->getStepRecurrence(*SE);
1353
1354 // Check for a simple looking step prior to loop entry.
1355 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1356 if (!SA)
1357 return nullptr;
1358
1359 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1360 // subtraction is expensive. For this purpose, perform a quick and dirty
1361 // difference, by checking for Step in the operand list. Note, that
1362 // SA might have repeated ops, like %a + %a + ..., so only remove one.
1364 for (auto It = DiffOps.begin(); It != DiffOps.end(); ++It)
1365 if (*It == Step) {
1366 DiffOps.erase(It);
1367 break;
1368 }
1369
1370 if (DiffOps.size() == SA->getNumOperands())
1371 return nullptr;
1372
1373 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1374 // `Step`:
1375
1376 // 1. NSW/NUW flags on the step increment.
1377 auto PreStartFlags =
1379 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1380 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1381 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1382
1383 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1384 // "S+X does not sign/unsign-overflow".
1385 //
1386
1387 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1388 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1389 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1390 return PreStart;
1391
1392 // 2. Direct overflow check on the step operation's expression.
1393 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1394 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1395 const SCEV *OperandExtendedStart =
1396 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1397 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1398 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1399 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1400 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1401 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1402 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1403 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1404 }
1405 return PreStart;
1406 }
1407
1408 // 3. Loop precondition.
1410 const SCEV *OverflowLimit =
1411 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1412
1413 if (OverflowLimit &&
1414 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1415 return PreStart;
1416
1417 return nullptr;
1418}
1419
1420// Get the normalized zero or sign extended expression for this AddRec's Start.
1421template <typename ExtendOpTy>
1422static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1423 ScalarEvolution *SE,
1424 unsigned Depth) {
1425 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1426
1427 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1428 if (!PreStart)
1429 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1430
1431 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1432 Depth),
1433 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1434}
1435
1436// Try to prove away overflow by looking at "nearby" add recurrences. A
1437// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1438// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1439//
1440// Formally:
1441//
1442// {S,+,X} == {S-T,+,X} + T
1443// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1444//
1445// If ({S-T,+,X} + T) does not overflow ... (1)
1446//
1447// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1448//
1449// If {S-T,+,X} does not overflow ... (2)
1450//
1451// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1452// == {Ext(S-T)+Ext(T),+,Ext(X)}
1453//
1454// If (S-T)+T does not overflow ... (3)
1455//
1456// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1457// == {Ext(S),+,Ext(X)} == LHS
1458//
1459// Thus, if (1), (2) and (3) are true for some T, then
1460// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1461//
1462// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1463// does not overflow" restricted to the 0th iteration. Therefore we only need
1464// to check for (1) and (2).
1465//
1466// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1467// is `Delta` (defined below).
1468template <typename ExtendOpTy>
1469bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1470 const SCEV *Step,
1471 const Loop *L) {
1472 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1473
1474 // We restrict `Start` to a constant to prevent SCEV from spending too much
1475 // time here. It is correct (but more expensive) to continue with a
1476 // non-constant `Start` and do a general SCEV subtraction to compute
1477 // `PreStart` below.
1478 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1479 if (!StartC)
1480 return false;
1481
1482 APInt StartAI = StartC->getAPInt();
1483
1484 for (unsigned Delta : {-2, -1, 1, 2}) {
1485 const SCEV *PreStart = getConstant(StartAI - Delta);
1486
1488 ID.AddInteger(scAddRecExpr);
1489 ID.AddPointer(PreStart);
1490 ID.AddPointer(Step);
1491 ID.AddPointer(L);
1492 void *IP = nullptr;
1493 const auto *PreAR =
1494 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1495
1496 // Give up if we don't already have the add recurrence we need because
1497 // actually constructing an add recurrence is relatively expensive.
1498 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1499 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1501 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1502 DeltaS, &Pred, this);
1503 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1504 return true;
1505 }
1506 }
1507
1508 return false;
1509}
1510
1511// Finds an integer D for an expression (C + x + y + ...) such that the top
1512// level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1513// unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1514// maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1515// the (C + x + y + ...) expression is \p WholeAddExpr.
1517 const SCEVConstant *ConstantTerm,
1518 const SCEVAddExpr *WholeAddExpr) {
1519 const APInt &C = ConstantTerm->getAPInt();
1520 const unsigned BitWidth = C.getBitWidth();
1521 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1522 uint32_t TZ = BitWidth;
1523 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1524 TZ = std::min(TZ, SE.getMinTrailingZeros(WholeAddExpr->getOperand(I)));
1525 if (TZ) {
1526 // Set D to be as many least significant bits of C as possible while still
1527 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1528 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1529 }
1530 return APInt(BitWidth, 0);
1531}
1532
1533// Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1534// level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1535// number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1536// ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1538 const APInt &ConstantStart,
1539 const SCEV *Step) {
1540 const unsigned BitWidth = ConstantStart.getBitWidth();
1541 const uint32_t TZ = SE.getMinTrailingZeros(Step);
1542 if (TZ)
1543 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1544 : ConstantStart;
1545 return APInt(BitWidth, 0);
1546}
1547
1549 const ScalarEvolution::FoldID &ID, const SCEV *S,
1552 &FoldCacheUser) {
1553 auto I = FoldCache.insert({ID, S});
1554 if (!I.second) {
1555 // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1556 // entry.
1557 auto &UserIDs = FoldCacheUser[I.first->second];
1558 assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
1559 for (unsigned I = 0; I != UserIDs.size(); ++I)
1560 if (UserIDs[I] == ID) {
1561 std::swap(UserIDs[I], UserIDs.back());
1562 break;
1563 }
1564 UserIDs.pop_back();
1565 I.first->second = S;
1566 }
1567 auto R = FoldCacheUser.insert({S, {}});
1568 R.first->second.push_back(ID);
1569}
1570
1571const SCEV *
1573 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1574 "This is not an extending conversion!");
1575 assert(isSCEVable(Ty) &&
1576 "This is not a conversion to a SCEVable type!");
1577 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1578 Ty = getEffectiveSCEVType(Ty);
1579
1580 FoldID ID(scZeroExtend, Op, Ty);
1581 auto Iter = FoldCache.find(ID);
1582 if (Iter != FoldCache.end())
1583 return Iter->second;
1584
1585 const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1586 if (!isa<SCEVZeroExtendExpr>(S))
1587 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1588 return S;
1589}
1590
1592 unsigned Depth) {
1593 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1594 "This is not an extending conversion!");
1595 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1596 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1597
1598 // Fold if the operand is constant.
1599 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1600 return getConstant(SC->getAPInt().zext(getTypeSizeInBits(Ty)));
1601
1602 // zext(zext(x)) --> zext(x)
1603 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1604 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1605
1606 // Before doing any expensive analysis, check to see if we've already
1607 // computed a SCEV for this Op and Ty.
1609 ID.AddInteger(scZeroExtend);
1610 ID.AddPointer(Op);
1611 ID.AddPointer(Ty);
1612 void *IP = nullptr;
1613 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1614 if (Depth > MaxCastDepth) {
1615 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1616 Op, Ty);
1617 UniqueSCEVs.InsertNode(S, IP);
1618 registerUser(S, Op);
1619 return S;
1620 }
1621
1622 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1623 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1624 // It's possible the bits taken off by the truncate were all zero bits. If
1625 // so, we should be able to simplify this further.
1626 const SCEV *X = ST->getOperand();
1628 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1629 unsigned NewBits = getTypeSizeInBits(Ty);
1630 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1631 CR.zextOrTrunc(NewBits)))
1632 return getTruncateOrZeroExtend(X, Ty, Depth);
1633 }
1634
1635 // If the input value is a chrec scev, and we can prove that the value
1636 // did not overflow the old, smaller, value, we can zero extend all of the
1637 // operands (often constants). This allows analysis of something like
1638 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1639 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1640 if (AR->isAffine()) {
1641 const SCEV *Start = AR->getStart();
1642 const SCEV *Step = AR->getStepRecurrence(*this);
1643 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1644 const Loop *L = AR->getLoop();
1645
1646 // If we have special knowledge that this addrec won't overflow,
1647 // we don't need to do any further analysis.
1648 if (AR->hasNoUnsignedWrap()) {
1649 Start =
1650 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1651 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1652 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1653 }
1654
1655 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1656 // Note that this serves two purposes: It filters out loops that are
1657 // simply not analyzable, and it covers the case where this code is
1658 // being called from within backedge-taken count analysis, such that
1659 // attempting to ask for the backedge-taken count would likely result
1660 // in infinite recursion. In the later case, the analysis code will
1661 // cope with a conservative value, and it will take care to purge
1662 // that value once it has finished.
1663 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1664 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1665 // Manually compute the final value for AR, checking for overflow.
1666
1667 // Check whether the backedge-taken count can be losslessly casted to
1668 // the addrec's type. The count is always unsigned.
1669 const SCEV *CastedMaxBECount =
1670 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1671 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1672 CastedMaxBECount, MaxBECount->getType(), Depth);
1673 if (MaxBECount == RecastedMaxBECount) {
1674 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1675 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1676 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1678 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1680 Depth + 1),
1681 WideTy, Depth + 1);
1682 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1683 const SCEV *WideMaxBECount =
1684 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1685 const SCEV *OperandExtendedAdd =
1686 getAddExpr(WideStart,
1687 getMulExpr(WideMaxBECount,
1688 getZeroExtendExpr(Step, WideTy, Depth + 1),
1691 if (ZAdd == OperandExtendedAdd) {
1692 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1693 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1694 // Return the expression with the addrec on the outside.
1695 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1696 Depth + 1);
1697 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1698 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1699 }
1700 // Similar to above, only this time treat the step value as signed.
1701 // This covers loops that count down.
1702 OperandExtendedAdd =
1703 getAddExpr(WideStart,
1704 getMulExpr(WideMaxBECount,
1705 getSignExtendExpr(Step, WideTy, Depth + 1),
1708 if (ZAdd == OperandExtendedAdd) {
1709 // Cache knowledge of AR NW, which is propagated to this AddRec.
1710 // Negative step causes unsigned wrap, but it still can't self-wrap.
1711 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1712 // Return the expression with the addrec on the outside.
1713 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1714 Depth + 1);
1715 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1716 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1717 }
1718 }
1719 }
1720
1721 // Normally, in the cases we can prove no-overflow via a
1722 // backedge guarding condition, we can also compute a backedge
1723 // taken count for the loop. The exceptions are assumptions and
1724 // guards present in the loop -- SCEV is not great at exploiting
1725 // these to compute max backedge taken counts, but can still use
1726 // these to prove lack of overflow. Use this fact to avoid
1727 // doing extra work that may not pay off.
1728 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1729 !AC.assumptions().empty()) {
1730
1731 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1732 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1733 if (AR->hasNoUnsignedWrap()) {
1734 // Same as nuw case above - duplicated here to avoid a compile time
1735 // issue. It's not clear that the order of checks does matter, but
1736 // it's one of two issue possible causes for a change which was
1737 // reverted. Be conservative for the moment.
1738 Start =
1739 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1740 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1741 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1742 }
1743
1744 // For a negative step, we can extend the operands iff doing so only
1745 // traverses values in the range zext([0,UINT_MAX]).
1746 if (isKnownNegative(Step)) {
1748 getSignedRangeMin(Step));
1751 // Cache knowledge of AR NW, which is propagated to this
1752 // AddRec. Negative step causes unsigned wrap, but it
1753 // still can't self-wrap.
1754 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1755 // Return the expression with the addrec on the outside.
1756 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1757 Depth + 1);
1758 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1759 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1760 }
1761 }
1762 }
1763
1764 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1765 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1766 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1767 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1768 const APInt &C = SC->getAPInt();
1769 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1770 if (D != 0) {
1771 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1772 const SCEV *SResidual =
1773 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1774 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1775 return getAddExpr(SZExtD, SZExtR,
1777 Depth + 1);
1778 }
1779 }
1780
1781 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1782 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1783 Start =
1784 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1785 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1786 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1787 }
1788 }
1789
1790 // zext(A % B) --> zext(A) % zext(B)
1791 {
1792 const SCEV *LHS;
1793 const SCEV *RHS;
1794 if (matchURem(Op, LHS, RHS))
1795 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1796 getZeroExtendExpr(RHS, Ty, Depth + 1));
1797 }
1798
1799 // zext(A / B) --> zext(A) / zext(B).
1800 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1801 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1802 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1803
1804 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1805 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1806 if (SA->hasNoUnsignedWrap()) {
1807 // If the addition does not unsign overflow then we can, by definition,
1808 // commute the zero extension with the addition operation.
1810 for (const auto *Op : SA->operands())
1811 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1812 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1813 }
1814
1815 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1816 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1817 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1818 //
1819 // Often address arithmetics contain expressions like
1820 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1821 // This transformation is useful while proving that such expressions are
1822 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1823 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1824 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1825 if (D != 0) {
1826 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1827 const SCEV *SResidual =
1829 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1830 return getAddExpr(SZExtD, SZExtR,
1832 Depth + 1);
1833 }
1834 }
1835 }
1836
1837 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1838 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1839 if (SM->hasNoUnsignedWrap()) {
1840 // If the multiply does not unsign overflow then we can, by definition,
1841 // commute the zero extension with the multiply operation.
1843 for (const auto *Op : SM->operands())
1844 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1845 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1846 }
1847
1848 // zext(2^K * (trunc X to iN)) to iM ->
1849 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1850 //
1851 // Proof:
1852 //
1853 // zext(2^K * (trunc X to iN)) to iM
1854 // = zext((trunc X to iN) << K) to iM
1855 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1856 // (because shl removes the top K bits)
1857 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1858 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1859 //
1860 if (SM->getNumOperands() == 2)
1861 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1862 if (MulLHS->getAPInt().isPowerOf2())
1863 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1864 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1865 MulLHS->getAPInt().logBase2();
1866 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1867 return getMulExpr(
1868 getZeroExtendExpr(MulLHS, Ty),
1870 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1871 SCEV::FlagNUW, Depth + 1);
1872 }
1873 }
1874
1875 // zext(umin(x, y)) -> umin(zext(x), zext(y))
1876 // zext(umax(x, y)) -> umax(zext(x), zext(y))
1877 if (isa<SCEVUMinExpr>(Op) || isa<SCEVUMaxExpr>(Op)) {
1878 auto *MinMax = cast<SCEVMinMaxExpr>(Op);
1880 for (auto *Operand : MinMax->operands())
1881 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1882 if (isa<SCEVUMinExpr>(MinMax))
1883 return getUMinExpr(Operands);
1884 return getUMaxExpr(Operands);
1885 }
1886
1887 // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
1888 if (auto *MinMax = dyn_cast<SCEVSequentialMinMaxExpr>(Op)) {
1889 assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!");
1891 for (auto *Operand : MinMax->operands())
1892 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1893 return getUMinExpr(Operands, /*Sequential*/ true);
1894 }
1895
1896 // The cast wasn't folded; create an explicit cast node.
1897 // Recompute the insert position, as it may have been invalidated.
1898 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1899 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1900 Op, Ty);
1901 UniqueSCEVs.InsertNode(S, IP);
1902 registerUser(S, Op);
1903 return S;
1904}
1905
1906const SCEV *
1908 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1909 "This is not an extending conversion!");
1910 assert(isSCEVable(Ty) &&
1911 "This is not a conversion to a SCEVable type!");
1912 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1913 Ty = getEffectiveSCEVType(Ty);
1914
1915 FoldID ID(scSignExtend, Op, Ty);
1916 auto Iter = FoldCache.find(ID);
1917 if (Iter != FoldCache.end())
1918 return Iter->second;
1919
1920 const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
1921 if (!isa<SCEVSignExtendExpr>(S))
1922 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1923 return S;
1924}
1925
1927 unsigned Depth) {
1928 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1929 "This is not an extending conversion!");
1930 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1931 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1932 Ty = getEffectiveSCEVType(Ty);
1933
1934 // Fold if the operand is constant.
1935 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1936 return getConstant(SC->getAPInt().sext(getTypeSizeInBits(Ty)));
1937
1938 // sext(sext(x)) --> sext(x)
1939 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1940 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1941
1942 // sext(zext(x)) --> zext(x)
1943 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1944 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1945
1946 // Before doing any expensive analysis, check to see if we've already
1947 // computed a SCEV for this Op and Ty.
1949 ID.AddInteger(scSignExtend);
1950 ID.AddPointer(Op);
1951 ID.AddPointer(Ty);
1952 void *IP = nullptr;
1953 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1954 // Limit recursion depth.
1955 if (Depth > MaxCastDepth) {
1956 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1957 Op, Ty);
1958 UniqueSCEVs.InsertNode(S, IP);
1959 registerUser(S, Op);
1960 return S;
1961 }
1962
1963 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1964 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1965 // It's possible the bits taken off by the truncate were all sign bits. If
1966 // so, we should be able to simplify this further.
1967 const SCEV *X = ST->getOperand();
1969 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1970 unsigned NewBits = getTypeSizeInBits(Ty);
1971 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1972 CR.sextOrTrunc(NewBits)))
1973 return getTruncateOrSignExtend(X, Ty, Depth);
1974 }
1975
1976 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1977 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1978 if (SA->hasNoSignedWrap()) {
1979 // If the addition does not sign overflow then we can, by definition,
1980 // commute the sign extension with the addition operation.
1982 for (const auto *Op : SA->operands())
1983 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1984 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1985 }
1986
1987 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1988 // if D + (C - D + x + y + ...) could be proven to not signed wrap
1989 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1990 //
1991 // For instance, this will bring two seemingly different expressions:
1992 // 1 + sext(5 + 20 * %x + 24 * %y) and
1993 // sext(6 + 20 * %x + 24 * %y)
1994 // to the same form:
1995 // 2 + sext(4 + 20 * %x + 24 * %y)
1996 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1997 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1998 if (D != 0) {
1999 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2000 const SCEV *SResidual =
2002 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2003 return getAddExpr(SSExtD, SSExtR,
2005 Depth + 1);
2006 }
2007 }
2008 }
2009 // If the input value is a chrec scev, and we can prove that the value
2010 // did not overflow the old, smaller, value, we can sign extend all of the
2011 // operands (often constants). This allows analysis of something like
2012 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
2013 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
2014 if (AR->isAffine()) {
2015 const SCEV *Start = AR->getStart();
2016 const SCEV *Step = AR->getStepRecurrence(*this);
2017 unsigned BitWidth = getTypeSizeInBits(AR->getType());
2018 const Loop *L = AR->getLoop();
2019
2020 // If we have special knowledge that this addrec won't overflow,
2021 // we don't need to do any further analysis.
2022 if (AR->hasNoSignedWrap()) {
2023 Start =
2024 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2025 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2026 return getAddRecExpr(Start, Step, L, SCEV::FlagNSW);
2027 }
2028
2029 // Check whether the backedge-taken count is SCEVCouldNotCompute.
2030 // Note that this serves two purposes: It filters out loops that are
2031 // simply not analyzable, and it covers the case where this code is
2032 // being called from within backedge-taken count analysis, such that
2033 // attempting to ask for the backedge-taken count would likely result
2034 // in infinite recursion. In the later case, the analysis code will
2035 // cope with a conservative value, and it will take care to purge
2036 // that value once it has finished.
2037 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2038 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2039 // Manually compute the final value for AR, checking for
2040 // overflow.
2041
2042 // Check whether the backedge-taken count can be losslessly casted to
2043 // the addrec's type. The count is always unsigned.
2044 const SCEV *CastedMaxBECount =
2045 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2046 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2047 CastedMaxBECount, MaxBECount->getType(), Depth);
2048 if (MaxBECount == RecastedMaxBECount) {
2049 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2050 // Check whether Start+Step*MaxBECount has no signed overflow.
2051 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2053 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2055 Depth + 1),
2056 WideTy, Depth + 1);
2057 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2058 const SCEV *WideMaxBECount =
2059 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2060 const SCEV *OperandExtendedAdd =
2061 getAddExpr(WideStart,
2062 getMulExpr(WideMaxBECount,
2063 getSignExtendExpr(Step, WideTy, Depth + 1),
2066 if (SAdd == OperandExtendedAdd) {
2067 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2068 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2069 // Return the expression with the addrec on the outside.
2070 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2071 Depth + 1);
2072 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2073 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2074 }
2075 // Similar to above, only this time treat the step value as unsigned.
2076 // This covers loops that count up with an unsigned step.
2077 OperandExtendedAdd =
2078 getAddExpr(WideStart,
2079 getMulExpr(WideMaxBECount,
2080 getZeroExtendExpr(Step, WideTy, Depth + 1),
2083 if (SAdd == OperandExtendedAdd) {
2084 // If AR wraps around then
2085 //
2086 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2087 // => SAdd != OperandExtendedAdd
2088 //
2089 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2090 // (SAdd == OperandExtendedAdd => AR is NW)
2091
2092 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2093
2094 // Return the expression with the addrec on the outside.
2095 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2096 Depth + 1);
2097 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
2098 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2099 }
2100 }
2101 }
2102
2103 auto NewFlags = proveNoSignedWrapViaInduction(AR);
2104 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2105 if (AR->hasNoSignedWrap()) {
2106 // Same as nsw case above - duplicated here to avoid a compile time
2107 // issue. It's not clear that the order of checks does matter, but
2108 // it's one of two issue possible causes for a change which was
2109 // reverted. Be conservative for the moment.
2110 Start =
2111 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2112 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2113 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2114 }
2115
2116 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2117 // if D + (C - D + Step * n) could be proven to not signed wrap
2118 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2119 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2120 const APInt &C = SC->getAPInt();
2121 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2122 if (D != 0) {
2123 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2124 const SCEV *SResidual =
2125 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2126 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2127 return getAddExpr(SSExtD, SSExtR,
2129 Depth + 1);
2130 }
2131 }
2132
2133 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2134 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2135 Start =
2136 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2137 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2138 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2139 }
2140 }
2141
2142 // If the input value is provably positive and we could not simplify
2143 // away the sext build a zext instead.
2145 return getZeroExtendExpr(Op, Ty, Depth + 1);
2146
2147 // sext(smin(x, y)) -> smin(sext(x), sext(y))
2148 // sext(smax(x, y)) -> smax(sext(x), sext(y))
2149 if (isa<SCEVSMinExpr>(Op) || isa<SCEVSMaxExpr>(Op)) {
2150 auto *MinMax = cast<SCEVMinMaxExpr>(Op);
2152 for (auto *Operand : MinMax->operands())
2153 Operands.push_back(getSignExtendExpr(Operand, Ty));
2154 if (isa<SCEVSMinExpr>(MinMax))
2155 return getSMinExpr(Operands);
2156 return getSMaxExpr(Operands);
2157 }
2158
2159 // The cast wasn't folded; create an explicit cast node.
2160 // Recompute the insert position, as it may have been invalidated.
2161 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2162 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2163 Op, Ty);
2164 UniqueSCEVs.InsertNode(S, IP);
2165 registerUser(S, { Op });
2166 return S;
2167}
2168
2170 Type *Ty) {
2171 switch (Kind) {
2172 case scTruncate:
2173 return getTruncateExpr(Op, Ty);
2174 case scZeroExtend:
2175 return getZeroExtendExpr(Op, Ty);
2176 case scSignExtend:
2177 return getSignExtendExpr(Op, Ty);
2178 case scPtrToInt:
2179 return getPtrToIntExpr(Op, Ty);
2180 default:
2181 llvm_unreachable("Not a SCEV cast expression!");
2182 }
2183}
2184
2185/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2186/// unspecified bits out to the given type.
2188 Type *Ty) {
2189 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2190 "This is not an extending conversion!");
2191 assert(isSCEVable(Ty) &&
2192 "This is not a conversion to a SCEVable type!");
2193 Ty = getEffectiveSCEVType(Ty);
2194
2195 // Sign-extend negative constants.
2196 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2197 if (SC->getAPInt().isNegative())
2198 return getSignExtendExpr(Op, Ty);
2199
2200 // Peel off a truncate cast.
2201 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2202 const SCEV *NewOp = T->getOperand();
2203 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2204 return getAnyExtendExpr(NewOp, Ty);
2205 return getTruncateOrNoop(NewOp, Ty);
2206 }
2207
2208 // Next try a zext cast. If the cast is folded, use it.
2209 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2210 if (!isa<SCEVZeroExtendExpr>(ZExt))
2211 return ZExt;
2212
2213 // Next try a sext cast. If the cast is folded, use it.
2214 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2215 if (!isa<SCEVSignExtendExpr>(SExt))
2216 return SExt;
2217
2218 // Force the cast to be folded into the operands of an addrec.
2219 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2221 for (const SCEV *Op : AR->operands())
2222 Ops.push_back(getAnyExtendExpr(Op, Ty));
2223 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2224 }
2225
2226 // If the expression is obviously signed, use the sext cast value.
2227 if (isa<SCEVSMaxExpr>(Op))
2228 return SExt;
2229
2230 // Absent any other information, use the zext cast value.
2231 return ZExt;
2232}
2233
2234/// Process the given Ops list, which is a list of operands to be added under
2235/// the given scale, update the given map. This is a helper function for
2236/// getAddRecExpr. As an example of what it does, given a sequence of operands
2237/// that would form an add expression like this:
2238///
2239/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2240///
2241/// where A and B are constants, update the map with these values:
2242///
2243/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2244///
2245/// and add 13 + A*B*29 to AccumulatedConstant.
2246/// This will allow getAddRecExpr to produce this:
2247///
2248/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2249///
2250/// This form often exposes folding opportunities that are hidden in
2251/// the original operand list.
2252///
2253/// Return true iff it appears that any interesting folding opportunities
2254/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2255/// the common case where no interesting opportunities are present, and
2256/// is also used as a check to avoid infinite recursion.
2257static bool
2260 APInt &AccumulatedConstant,
2261 ArrayRef<const SCEV *> Ops, const APInt &Scale,
2262 ScalarEvolution &SE) {
2263 bool Interesting = false;
2264
2265 // Iterate over the add operands. They are sorted, with constants first.
2266 unsigned i = 0;
2267 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2268 ++i;
2269 // Pull a buried constant out to the outside.
2270 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2271 Interesting = true;
2272 AccumulatedConstant += Scale * C->getAPInt();
2273 }
2274
2275 // Next comes everything else. We're especially interested in multiplies
2276 // here, but they're in the middle, so just visit the rest with one loop.
2277 for (; i != Ops.size(); ++i) {
2278 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2279 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2280 APInt NewScale =
2281 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2282 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2283 // A multiplication of a constant with another add; recurse.
2284 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2285 Interesting |=
2286 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2287 Add->operands(), NewScale, SE);
2288 } else {
2289 // A multiplication of a constant with some other value. Update
2290 // the map.
2291 SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands()));
2292 const SCEV *Key = SE.getMulExpr(MulOps);
2293 auto Pair = M.insert({Key, NewScale});
2294 if (Pair.second) {
2295 NewOps.push_back(Pair.first->first);
2296 } else {
2297 Pair.first->second += NewScale;
2298 // The map already had an entry for this value, which may indicate
2299 // a folding opportunity.
2300 Interesting = true;
2301 }
2302 }
2303 } else {
2304 // An ordinary operand. Update the map.
2305 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2306 M.insert({Ops[i], Scale});
2307 if (Pair.second) {
2308 NewOps.push_back(Pair.first->first);
2309 } else {
2310 Pair.first->second += Scale;
2311 // The map already had an entry for this value, which may indicate
2312 // a folding opportunity.
2313 Interesting = true;
2314 }
2315 }
2316 }
2317
2318 return Interesting;
2319}
2320
2322 const SCEV *LHS, const SCEV *RHS,
2323 const Instruction *CtxI) {
2324 const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *,
2325 SCEV::NoWrapFlags, unsigned);
2326 switch (BinOp) {
2327 default:
2328 llvm_unreachable("Unsupported binary op");
2329 case Instruction::Add:
2331 break;
2332 case Instruction::Sub:
2334 break;
2335 case Instruction::Mul:
2337 break;
2338 }
2339
2340 const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
2343
2344 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2345 auto *NarrowTy = cast<IntegerType>(LHS->getType());
2346 auto *WideTy =
2347 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2348
2349 const SCEV *A = (this->*Extension)(
2350 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2351 const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2352 const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2353 const SCEV *B = (this->*Operation)(LHSB, RHSB, SCEV::FlagAnyWrap, 0);
2354 if (A == B)
2355 return true;
2356 // Can we use context to prove the fact we need?
2357 if (!CtxI)
2358 return false;
2359 // TODO: Support mul.
2360 if (BinOp == Instruction::Mul)
2361 return false;
2362 auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2363 // TODO: Lift this limitation.
2364 if (!RHSC)
2365 return false;
2366 APInt C = RHSC->getAPInt();
2367 unsigned NumBits = C.getBitWidth();
2368 bool IsSub = (BinOp == Instruction::Sub);
2369 bool IsNegativeConst = (Signed && C.isNegative());
2370 // Compute the direction and magnitude by which we need to check overflow.
2371 bool OverflowDown = IsSub ^ IsNegativeConst;
2372 APInt Magnitude = C;
2373 if (IsNegativeConst) {
2374 if (C == APInt::getSignedMinValue(NumBits))
2375 // TODO: SINT_MIN on inversion gives the same negative value, we don't
2376 // want to deal with that.
2377 return false;
2378 Magnitude = -C;
2379 }
2380
2382 if (OverflowDown) {
2383 // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2384 APInt Min = Signed ? APInt::getSignedMinValue(NumBits)
2385 : APInt::getMinValue(NumBits);
2386 APInt Limit = Min + Magnitude;
2387 return isKnownPredicateAt(Pred, getConstant(Limit), LHS, CtxI);
2388 } else {
2389 // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2390 APInt Max = Signed ? APInt::getSignedMaxValue(NumBits)
2391 : APInt::getMaxValue(NumBits);
2392 APInt Limit = Max - Magnitude;
2393 return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2394 }
2395}
2396
2397std::optional<SCEV::NoWrapFlags>
2399 const OverflowingBinaryOperator *OBO) {
2400 // It cannot be done any better.
2401 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2402 return std::nullopt;
2403
2405
2406 if (OBO->hasNoUnsignedWrap())
2408 if (OBO->hasNoSignedWrap())
2410
2411 bool Deduced = false;
2412
2413 if (OBO->getOpcode() != Instruction::Add &&
2414 OBO->getOpcode() != Instruction::Sub &&
2415 OBO->getOpcode() != Instruction::Mul)
2416 return std::nullopt;
2417
2418 const SCEV *LHS = getSCEV(OBO->getOperand(0));
2419 const SCEV *RHS = getSCEV(OBO->getOperand(1));
2420
2421 const Instruction *CtxI =
2422 UseContextForNoWrapFlagInference ? dyn_cast<Instruction>(OBO) : nullptr;
2423 if (!OBO->hasNoUnsignedWrap() &&
2425 /* Signed */ false, LHS, RHS, CtxI)) {
2427 Deduced = true;
2428 }
2429
2430 if (!OBO->hasNoSignedWrap() &&
2432 /* Signed */ true, LHS, RHS, CtxI)) {
2434 Deduced = true;
2435 }
2436
2437 if (Deduced)
2438 return Flags;
2439 return std::nullopt;
2440}
2441
2442// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2443// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2444// can't-overflow flags for the operation if possible.
2445static SCEV::NoWrapFlags
2447 const ArrayRef<const SCEV *> Ops,
2448 SCEV::NoWrapFlags Flags) {
2449 using namespace std::placeholders;
2450
2451 using OBO = OverflowingBinaryOperator;
2452
2453 bool CanAnalyze =
2455 (void)CanAnalyze;
2456 assert(CanAnalyze && "don't call from other places!");
2457
2458 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2459 SCEV::NoWrapFlags SignOrUnsignWrap =
2460 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2461
2462 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2463 auto IsKnownNonNegative = [&](const SCEV *S) {
2464 return SE->isKnownNonNegative(S);
2465 };
2466
2467 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2468 Flags =
2469 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2470
2471 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2472
2473 if (SignOrUnsignWrap != SignOrUnsignMask &&
2474 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2475 isa<SCEVConstant>(Ops[0])) {
2476
2477 auto Opcode = [&] {
2478 switch (Type) {
2479 case scAddExpr:
2480 return Instruction::Add;
2481 case scMulExpr:
2482 return Instruction::Mul;
2483 default:
2484 llvm_unreachable("Unexpected SCEV op.");
2485 }
2486 }();
2487
2488 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2489
2490 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2491 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2493 Opcode, C, OBO::NoSignedWrap);
2494 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2496 }
2497
2498 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2499 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2501 Opcode, C, OBO::NoUnsignedWrap);
2502 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2504 }
2505 }
2506
2507 // <0,+,nonnegative><nw> is also nuw
2508 // TODO: Add corresponding nsw case
2510 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2511 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2513
2514 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2516 Ops.size() == 2) {
2517 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2518 if (UDiv->getOperand(1) == Ops[1])
2520 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2521 if (UDiv->getOperand(1) == Ops[0])
2523 }
2524
2525 return Flags;
2526}
2527
2529 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2530}
2531
2532/// Get a canonical add expression, or something simpler if possible.
2534 SCEV::NoWrapFlags OrigFlags,
2535 unsigned Depth) {
2536 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2537 "only nuw or nsw allowed");
2538 assert(!Ops.empty() && "Cannot get empty add!");
2539 if (Ops.size() == 1) return Ops[0];
2540#ifndef NDEBUG
2541 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2542 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2543 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2544 "SCEVAddExpr operand types don't match!");
2545 unsigned NumPtrs = count_if(
2546 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2547 assert(NumPtrs <= 1 && "add has at most one pointer operand");
2548#endif
2549
2550 const SCEV *Folded = constantFoldAndGroupOps(
2551 *this, LI, DT, Ops,
2552 [](const APInt &C1, const APInt &C2) { return C1 + C2; },
2553 [](const APInt &C) { return C.isZero(); }, // identity
2554 [](const APInt &C) { return false; }); // absorber
2555 if (Folded)
2556 return Folded;
2557
2558 unsigned Idx = isa<SCEVConstant>(Ops[0]) ? 1 : 0;
2559
2560 // Delay expensive flag strengthening until necessary.
2561 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2562 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2563 };
2564
2565 // Limit recursion calls depth.
2567 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2568
2569 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2570 // Don't strengthen flags if we have no new information.
2571 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2572 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2573 Add->setNoWrapFlags(ComputeFlags(Ops));
2574 return S;
2575 }
2576
2577 // Okay, check to see if the same value occurs in the operand list more than
2578 // once. If so, merge them together into an multiply expression. Since we
2579 // sorted the list, these values are required to be adjacent.
2580 Type *Ty = Ops[0]->getType();
2581 bool FoundMatch = false;
2582 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2583 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2584 // Scan ahead to count how many equal operands there are.
2585 unsigned Count = 2;
2586 while (i+Count != e && Ops[i+Count] == Ops[i])
2587 ++Count;
2588 // Merge the values into a multiply.
2589 const SCEV *Scale = getConstant(Ty, Count);
2590 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2591 if (Ops.size() == Count)
2592 return Mul;
2593 Ops[i] = Mul;
2594 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2595 --i; e -= Count - 1;
2596 FoundMatch = true;
2597 }
2598 if (FoundMatch)
2599 return getAddExpr(Ops, OrigFlags, Depth + 1);
2600
2601 // Check for truncates. If all the operands are truncated from the same
2602 // type, see if factoring out the truncate would permit the result to be
2603 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2604 // if the contents of the resulting outer trunc fold to something simple.
2605 auto FindTruncSrcType = [&]() -> Type * {
2606 // We're ultimately looking to fold an addrec of truncs and muls of only
2607 // constants and truncs, so if we find any other types of SCEV
2608 // as operands of the addrec then we bail and return nullptr here.
2609 // Otherwise, we return the type of the operand of a trunc that we find.
2610 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2611 return T->getOperand()->getType();
2612 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2613 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2614 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2615 return T->getOperand()->getType();
2616 }
2617 return nullptr;
2618 };
2619 if (auto *SrcType = FindTruncSrcType()) {
2621 bool Ok = true;
2622 // Check all the operands to see if they can be represented in the
2623 // source type of the truncate.
2624 for (const SCEV *Op : Ops) {
2625 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2626 if (T->getOperand()->getType() != SrcType) {
2627 Ok = false;
2628 break;
2629 }
2630 LargeOps.push_back(T->getOperand());
2631 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Op)) {
2632 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2633 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Op)) {
2634 SmallVector<const SCEV *, 8> LargeMulOps;
2635 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2636 if (const SCEVTruncateExpr *T =
2637 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2638 if (T->getOperand()->getType() != SrcType) {
2639 Ok = false;
2640 break;
2641 }
2642 LargeMulOps.push_back(T->getOperand());
2643 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2644 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2645 } else {
2646 Ok = false;
2647 break;
2648 }
2649 }
2650 if (Ok)
2651 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2652 } else {
2653 Ok = false;
2654 break;
2655 }
2656 }
2657 if (Ok) {
2658 // Evaluate the expression in the larger type.
2659 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2660 // If it folds to something simple, use it. Otherwise, don't.
2661 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2662 return getTruncateExpr(Fold, Ty);
2663 }
2664 }
2665
2666 if (Ops.size() == 2) {
2667 // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2668 // C2 can be folded in a way that allows retaining wrapping flags of (X +
2669 // C1).
2670 const SCEV *A = Ops[0];
2671 const SCEV *B = Ops[1];
2672 auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2673 auto *C = dyn_cast<SCEVConstant>(A);
2674 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2675 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2676 auto C2 = C->getAPInt();
2677 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2678
2679 APInt ConstAdd = C1 + C2;
2680 auto AddFlags = AddExpr->getNoWrapFlags();
2681 // Adding a smaller constant is NUW if the original AddExpr was NUW.
2683 ConstAdd.ule(C1)) {
2684 PreservedFlags =
2686 }
2687
2688 // Adding a constant with the same sign and small magnitude is NSW, if the
2689 // original AddExpr was NSW.
2691 C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2692 ConstAdd.abs().ule(C1.abs())) {
2693 PreservedFlags =
2695 }
2696
2697 if (PreservedFlags != SCEV::FlagAnyWrap) {
2698 SmallVector<const SCEV *, 4> NewOps(AddExpr->operands());
2699 NewOps[0] = getConstant(ConstAdd);
2700 return getAddExpr(NewOps, PreservedFlags);
2701 }
2702 }
2703 }
2704
2705 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2706 if (Ops.size() == 2) {
2707 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[0]);
2708 if (Mul && Mul->getNumOperands() == 2 &&
2709 Mul->getOperand(0)->isAllOnesValue()) {
2710 const SCEV *X;
2711 const SCEV *Y;
2712 if (matchURem(Mul->getOperand(1), X, Y) && X == Ops[1]) {
2713 return getMulExpr(Y, getUDivExpr(X, Y));
2714 }
2715 }
2716 }
2717
2718 // Skip past any other cast SCEVs.
2719 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2720 ++Idx;
2721
2722 // If there are add operands they would be next.
2723 if (Idx < Ops.size()) {
2724 bool DeletedAdd = false;
2725 // If the original flags and all inlined SCEVAddExprs are NUW, use the
2726 // common NUW flag for expression after inlining. Other flags cannot be
2727 // preserved, because they may depend on the original order of operations.
2728 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2729 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2730 if (Ops.size() > AddOpsInlineThreshold ||
2731 Add->getNumOperands() > AddOpsInlineThreshold)
2732 break;
2733 // If we have an add, expand the add operands onto the end of the operands
2734 // list.
2735 Ops.erase(Ops.begin()+Idx);
2736 append_range(Ops, Add->operands());
2737 DeletedAdd = true;
2738 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2739 }
2740
2741 // If we deleted at least one add, we added operands to the end of the list,
2742 // and they are not necessarily sorted. Recurse to resort and resimplify
2743 // any operands we just acquired.
2744 if (DeletedAdd)
2745 return getAddExpr(Ops, CommonFlags, Depth + 1);
2746 }
2747
2748 // Skip over the add expression until we get to a multiply.
2749 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2750 ++Idx;
2751
2752 // Check to see if there are any folding opportunities present with
2753 // operands multiplied by constant values.
2754 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2758 APInt AccumulatedConstant(BitWidth, 0);
2759 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2760 Ops, APInt(BitWidth, 1), *this)) {
2761 struct APIntCompare {
2762 bool operator()(const APInt &LHS, const APInt &RHS) const {
2763 return LHS.ult(RHS);
2764 }
2765 };
2766
2767 // Some interesting folding opportunity is present, so its worthwhile to
2768 // re-generate the operands list. Group the operands by constant scale,
2769 // to avoid multiplying by the same constant scale multiple times.
2770 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2771 for (const SCEV *NewOp : NewOps)
2772 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2773 // Re-generate the operands list.
2774 Ops.clear();
2775 if (AccumulatedConstant != 0)
2776 Ops.push_back(getConstant(AccumulatedConstant));
2777 for (auto &MulOp : MulOpLists) {
2778 if (MulOp.first == 1) {
2779 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2780 } else if (MulOp.first != 0) {
2782 getConstant(MulOp.first),
2783 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2784 SCEV::FlagAnyWrap, Depth + 1));
2785 }
2786 }
2787 if (Ops.empty())
2788 return getZero(Ty);
2789 if (Ops.size() == 1)
2790 return Ops[0];
2791 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2792 }
2793 }
2794
2795 // If we are adding something to a multiply expression, make sure the
2796 // something is not already an operand of the multiply. If so, merge it into
2797 // the multiply.
2798 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2799 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2800 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2801 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2802 if (isa<SCEVConstant>(MulOpSCEV))
2803 continue;
2804 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2805 if (MulOpSCEV == Ops[AddOp]) {
2806 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2807 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2808 if (Mul->getNumOperands() != 2) {
2809 // If the multiply has more than two operands, we must get the
2810 // Y*Z term.
2812 Mul->operands().take_front(MulOp));
2813 append_range(MulOps, Mul->operands().drop_front(MulOp + 1));
2814 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2815 }
2816 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2817 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2818 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2820 if (Ops.size() == 2) return OuterMul;
2821 if (AddOp < Idx) {
2822 Ops.erase(Ops.begin()+AddOp);
2823 Ops.erase(Ops.begin()+Idx-1);
2824 } else {
2825 Ops.erase(Ops.begin()+Idx);
2826 Ops.erase(Ops.begin()+AddOp-1);
2827 }
2828 Ops.push_back(OuterMul);
2829 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2830 }
2831
2832 // Check this multiply against other multiplies being added together.
2833 for (unsigned OtherMulIdx = Idx+1;
2834 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2835 ++OtherMulIdx) {
2836 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2837 // If MulOp occurs in OtherMul, we can fold the two multiplies
2838 // together.
2839 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2840 OMulOp != e; ++OMulOp)
2841 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2842 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2843 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2844 if (Mul->getNumOperands() != 2) {
2846 Mul->operands().take_front(MulOp));
2847 append_range(MulOps, Mul->operands().drop_front(MulOp+1));
2848 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2849 }
2850 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2851 if (OtherMul->getNumOperands() != 2) {
2853 OtherMul->operands().take_front(OMulOp));
2854 append_range(MulOps, OtherMul->operands().drop_front(OMulOp+1));
2855 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2856 }
2857 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2858 const SCEV *InnerMulSum =
2859 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2860 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2862 if (Ops.size() == 2) return OuterMul;
2863 Ops.erase(Ops.begin()+Idx);
2864 Ops.erase(Ops.begin()+OtherMulIdx-1);
2865 Ops.push_back(OuterMul);
2866 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2867 }
2868 }
2869 }
2870 }
2871
2872 // If there are any add recurrences in the operands list, see if any other
2873 // added values are loop invariant. If so, we can fold them into the
2874 // recurrence.
2875 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2876 ++Idx;
2877
2878 // Scan over all recurrences, trying to fold loop invariants into them.
2879 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2880 // Scan all of the other operands to this add and add them to the vector if
2881 // they are loop invariant w.r.t. the recurrence.
2883 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2884 const Loop *AddRecLoop = AddRec->getLoop();
2885 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2886 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2887 LIOps.push_back(Ops[i]);
2888 Ops.erase(Ops.begin()+i);
2889 --i; --e;
2890 }
2891
2892 // If we found some loop invariants, fold them into the recurrence.
2893 if (!LIOps.empty()) {
2894 // Compute nowrap flags for the addition of the loop-invariant ops and
2895 // the addrec. Temporarily push it as an operand for that purpose. These
2896 // flags are valid in the scope of the addrec only.
2897 LIOps.push_back(AddRec);
2898 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2899 LIOps.pop_back();
2900
2901 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2902 LIOps.push_back(AddRec->getStart());
2903
2904 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2905
2906 // It is not in general safe to propagate flags valid on an add within
2907 // the addrec scope to one outside it. We must prove that the inner
2908 // scope is guaranteed to execute if the outer one does to be able to
2909 // safely propagate. We know the program is undefined if poison is
2910 // produced on the inner scoped addrec. We also know that *for this use*
2911 // the outer scoped add can't overflow (because of the flags we just
2912 // computed for the inner scoped add) without the program being undefined.
2913 // Proving that entry to the outer scope neccesitates entry to the inner
2914 // scope, thus proves the program undefined if the flags would be violated
2915 // in the outer scope.
2916 SCEV::NoWrapFlags AddFlags = Flags;
2917 if (AddFlags != SCEV::FlagAnyWrap) {
2918 auto *DefI = getDefiningScopeBound(LIOps);
2919 auto *ReachI = &*AddRecLoop->getHeader()->begin();
2920 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2921 AddFlags = SCEV::FlagAnyWrap;
2922 }
2923 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2924
2925 // Build the new addrec. Propagate the NUW and NSW flags if both the
2926 // outer add and the inner addrec are guaranteed to have no overflow.
2927 // Always propagate NW.
2928 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2929 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2930
2931 // If all of the other operands were loop invariant, we are done.
2932 if (Ops.size() == 1) return NewRec;
2933
2934 // Otherwise, add the folded AddRec by the non-invariant parts.
2935 for (unsigned i = 0;; ++i)
2936 if (Ops[i] == AddRec) {
2937 Ops[i] = NewRec;
2938 break;
2939 }
2940 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2941 }
2942
2943 // Okay, if there weren't any loop invariants to be folded, check to see if
2944 // there are multiple AddRec's with the same loop induction variable being
2945 // added together. If so, we can fold them.
2946 for (unsigned OtherIdx = Idx+1;
2947 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2948 ++OtherIdx) {
2949 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2950 // so that the 1st found AddRecExpr is dominated by all others.
2951 assert(DT.dominates(
2952 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2953 AddRec->getLoop()->getHeader()) &&
2954 "AddRecExprs are not sorted in reverse dominance order?");
2955 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2956 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2957 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2958 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2959 ++OtherIdx) {
2960 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2961 if (OtherAddRec->getLoop() == AddRecLoop) {
2962 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2963 i != e; ++i) {
2964 if (i >= AddRecOps.size()) {
2965 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
2966 break;
2967 }
2969 AddRecOps[i], OtherAddRec->getOperand(i)};
2970 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2971 }
2972 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2973 }
2974 }
2975 // Step size has changed, so we cannot guarantee no self-wraparound.
2976 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2977 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2978 }
2979 }
2980
2981 // Otherwise couldn't fold anything into this recurrence. Move onto the
2982 // next one.
2983 }
2984
2985 // Okay, it looks like we really DO need an add expr. Check to see if we
2986 // already have one, otherwise create a new one.
2987 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2988}
2989
2990const SCEV *
2991ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2992 SCEV::NoWrapFlags Flags) {
2994 ID.AddInteger(scAddExpr);
2995 for (const SCEV *Op : Ops)
2996 ID.AddPointer(Op);
2997 void *IP = nullptr;
2998 SCEVAddExpr *S =
2999 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3000 if (!S) {
3001 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3002 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3003 S = new (SCEVAllocator)
3004 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
3005 UniqueSCEVs.InsertNode(S, IP);
3006 registerUser(S, Ops);
3007 }
3008 S->setNoWrapFlags(Flags);
3009 return S;
3010}
3011
3012const SCEV *
3013ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
3014 const Loop *L, SCEV::NoWrapFlags Flags) {
3016 ID.AddInteger(scAddRecExpr);
3017 for (const SCEV *Op : Ops)
3018 ID.AddPointer(Op);
3019 ID.AddPointer(L);
3020 void *IP = nullptr;
3021 SCEVAddRecExpr *S =
3022 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3023 if (!S) {
3024 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3025 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3026 S = new (SCEVAllocator)
3027 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
3028 UniqueSCEVs.InsertNode(S, IP);
3029 LoopUsers[L].push_back(S);
3030 registerUser(S, Ops);
3031 }
3032 setNoWrapFlags(S, Flags);
3033 return S;
3034}
3035
3036const SCEV *
3037ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
3038 SCEV::NoWrapFlags Flags) {
3040 ID.AddInteger(scMulExpr);
3041 for (const SCEV *Op : Ops)
3042 ID.AddPointer(Op);
3043 void *IP = nullptr;
3044 SCEVMulExpr *S =
3045 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3046 if (!S) {
3047 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3048 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3049 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
3050 O, Ops.size());
3051 UniqueSCEVs.InsertNode(S, IP);
3052 registerUser(S, Ops);
3053 }
3054 S->setNoWrapFlags(Flags);
3055 return S;
3056}
3057
3058static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
3059 uint64_t k = i*j;
3060 if (j > 1 && k / j != i) Overflow = true;
3061 return k;
3062}
3063
3064/// Compute the result of "n choose k", the binomial coefficient. If an
3065/// intermediate computation overflows, Overflow will be set and the return will
3066/// be garbage. Overflow is not cleared on absence of overflow.
3067static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3068 // We use the multiplicative formula:
3069 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3070 // At each iteration, we take the n-th term of the numeral and divide by the
3071 // (k-n)th term of the denominator. This division will always produce an
3072 // integral result, and helps reduce the chance of overflow in the
3073 // intermediate computations. However, we can still overflow even when the
3074 // final result would fit.
3075
3076 if (n == 0 || n == k) return 1;
3077 if (k > n) return 0;
3078
3079 if (k > n/2)
3080 k = n-k;
3081
3082 uint64_t r = 1;
3083 for (uint64_t i = 1; i <= k; ++i) {
3084 r = umul_ov(r, n-(i-1), Overflow);
3085 r /= i;
3086 }
3087 return r;
3088}
3089
3090/// Determine if any of the operands in this SCEV are a constant or if
3091/// any of the add or multiply expressions in this SCEV contain a constant.
3092static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3093 struct FindConstantInAddMulChain {
3094 bool FoundConstant = false;
3095
3096 bool follow(const SCEV *S) {
3097 FoundConstant |= isa<SCEVConstant>(S);
3098 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3099 }
3100
3101 bool isDone() const {
3102 return FoundConstant;
3103 }
3104 };
3105
3106 FindConstantInAddMulChain F;
3108 ST.visitAll(StartExpr);
3109 return F.FoundConstant;
3110}
3111
3112/// Get a canonical multiply expression, or something simpler if possible.
3114 SCEV::NoWrapFlags OrigFlags,
3115 unsigned Depth) {
3116 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3117 "only nuw or nsw allowed");
3118 assert(!Ops.empty() && "Cannot get empty mul!");
3119 if (Ops.size() == 1) return Ops[0];
3120#ifndef NDEBUG
3121 Type *ETy = Ops[0]->getType();
3122 assert(!ETy->isPointerTy());
3123 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3124 assert(Ops[i]->getType() == ETy &&
3125 "SCEVMulExpr operand types don't match!");
3126#endif
3127
3128 const SCEV *Folded = constantFoldAndGroupOps(
3129 *this, LI, DT, Ops,
3130 [](const APInt &C1, const APInt &C2) { return C1 * C2; },
3131 [](const APInt &C) { return C.isOne(); }, // identity
3132 [](const APInt &C) { return C.isZero(); }); // absorber
3133 if (Folded)
3134 return Folded;
3135
3136 // Delay expensive flag strengthening until necessary.
3137 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
3138 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3139 };
3140
3141 // Limit recursion calls depth.
3143 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3144
3145 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3146 // Don't strengthen flags if we have no new information.
3147 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3148 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3149 Mul->setNoWrapFlags(ComputeFlags(Ops));
3150 return S;
3151 }
3152
3153 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3154 if (Ops.size() == 2) {
3155 // C1*(C2+V) -> C1*C2 + C1*V
3156 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
3157 // If any of Add's ops are Adds or Muls with a constant, apply this
3158 // transformation as well.
3159 //
3160 // TODO: There are some cases where this transformation is not
3161 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
3162 // this transformation should be narrowed down.
3163 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) {
3164 const SCEV *LHS = getMulExpr(LHSC, Add->getOperand(0),
3166 const SCEV *RHS = getMulExpr(LHSC, Add->getOperand(1),
3168 return getAddExpr(LHS, RHS, SCEV::FlagAnyWrap, Depth + 1);
3169 }
3170
3171 if (Ops[0]->isAllOnesValue()) {
3172 // If we have a mul by -1 of an add, try distributing the -1 among the
3173 // add operands.
3174 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3176 bool AnyFolded = false;
3177 for (const SCEV *AddOp : Add->operands()) {
3178 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
3179 Depth + 1);
3180 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3181 NewOps.push_back(Mul);
3182 }
3183 if (AnyFolded)
3184 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3185 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3186 // Negation preserves a recurrence's no self-wrap property.
3188 for (const SCEV *AddRecOp : AddRec->operands())
3189 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
3190 Depth + 1));
3191 // Let M be the minimum representable signed value. AddRec with nsw
3192 // multiplied by -1 can have signed overflow if and only if it takes a
3193 // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3194 // maximum signed value. In all other cases signed overflow is
3195 // impossible.
3196 auto FlagsMask = SCEV::FlagNW;
3197 if (hasFlags(AddRec->getNoWrapFlags(), SCEV::FlagNSW)) {
3198 auto MinInt =
3199 APInt::getSignedMinValue(getTypeSizeInBits(AddRec->getType()));
3200 if (getSignedRangeMin(AddRec) != MinInt)
3201 FlagsMask = setFlags(FlagsMask, SCEV::FlagNSW);
3202 }
3203 return getAddRecExpr(Operands, AddRec->getLoop(),
3204 AddRec->getNoWrapFlags(FlagsMask));
3205 }
3206 }
3207 }
3208 }
3209
3210 // Skip over the add expression until we get to a multiply.
3211 unsigned Idx = 0;
3212 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3213 ++Idx;
3214
3215 // If there are mul operands inline them all into this expression.
3216 if (Idx < Ops.size()) {
3217 bool DeletedMul = false;
3218 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3219 if (Ops.size() > MulOpsInlineThreshold)
3220 break;
3221 // If we have an mul, expand the mul operands onto the end of the
3222 // operands list.
3223 Ops.erase(Ops.begin()+Idx);
3224 append_range(Ops, Mul->operands());
3225 DeletedMul = true;
3226 }
3227
3228 // If we deleted at least one mul, we added operands to the end of the
3229 // list, and they are not necessarily sorted. Recurse to resort and
3230 // resimplify any operands we just acquired.
3231 if (DeletedMul)
3232 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3233 }
3234
3235 // If there are any add recurrences in the operands list, see if any other
3236 // added values are loop invariant. If so, we can fold them into the
3237 // recurrence.
3238 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3239 ++Idx;
3240
3241 // Scan over all recurrences, trying to fold loop invariants into them.
3242 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3243 // Scan all of the other operands to this mul and add them to the vector
3244 // if they are loop invariant w.r.t. the recurrence.
3246 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3247 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3248 if (isAvailableAtLoopEntry(Ops[i], AddRec->getLoop())) {
3249 LIOps.push_back(Ops[i]);
3250 Ops.erase(Ops.begin()+i);
3251 --i; --e;
3252 }
3253
3254 // If we found some loop invariants, fold them into the recurrence.
3255 if (!LIOps.empty()) {
3256 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3258 NewOps.reserve(AddRec->getNumOperands());
3259 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3260
3261 // If both the mul and addrec are nuw, we can preserve nuw.
3262 // If both the mul and addrec are nsw, we can only preserve nsw if either
3263 // a) they are also nuw, or
3264 // b) all multiplications of addrec operands with scale are nsw.
3265 SCEV::NoWrapFlags Flags =
3266 AddRec->getNoWrapFlags(ComputeFlags({Scale, AddRec}));
3267
3268 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3269 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3270 SCEV::FlagAnyWrap, Depth + 1));
3271
3272 if (hasFlags(Flags, SCEV::FlagNSW) && !hasFlags(Flags, SCEV::FlagNUW)) {
3274 Instruction::Mul, getSignedRange(Scale),
3276 if (!NSWRegion.contains(getSignedRange(AddRec->getOperand(i))))
3277 Flags = clearFlags(Flags, SCEV::FlagNSW);
3278 }
3279 }
3280
3281 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(), Flags);
3282
3283 // If all of the other operands were loop invariant, we are done.
3284 if (Ops.size() == 1) return NewRec;
3285
3286 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3287 for (unsigned i = 0;; ++i)
3288 if (Ops[i] == AddRec) {
3289 Ops[i] = NewRec;
3290 break;
3291 }
3292 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3293 }
3294
3295 // Okay, if there weren't any loop invariants to be folded, check to see
3296 // if there are multiple AddRec's with the same loop induction variable
3297 // being multiplied together. If so, we can fold them.
3298
3299 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3300 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3301 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3302 // ]]],+,...up to x=2n}.
3303 // Note that the arguments to choose() are always integers with values
3304 // known at compile time, never SCEV objects.
3305 //
3306 // The implementation avoids pointless extra computations when the two
3307 // addrec's are of different length (mathematically, it's equivalent to
3308 // an infinite stream of zeros on the right).
3309 bool OpsModified = false;
3310 for (unsigned OtherIdx = Idx+1;
3311 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3312 ++OtherIdx) {
3313 const SCEVAddRecExpr *OtherAddRec =
3314 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3315 if (!OtherAddRec || OtherAddRec->getLoop() != AddRec->getLoop())
3316 continue;
3317
3318 // Limit max number of arguments to avoid creation of unreasonably big
3319 // SCEVAddRecs with very complex operands.
3320 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3321 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3322 continue;
3323
3324 bool Overflow = false;
3325 Type *Ty = AddRec->getType();
3326 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3328 for (int x = 0, xe = AddRec->getNumOperands() +
3329 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3330 SmallVector <const SCEV *, 7> SumOps;
3331 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3332 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3333 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3334 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3335 z < ze && !Overflow; ++z) {
3336 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3337 uint64_t Coeff;
3338 if (LargerThan64Bits)
3339 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3340 else
3341 Coeff = Coeff1*Coeff2;
3342 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3343 const SCEV *Term1 = AddRec->getOperand(y-z);
3344 const SCEV *Term2 = OtherAddRec->getOperand(z);
3345 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3346 SCEV::FlagAnyWrap, Depth + 1));
3347 }
3348 }
3349 if (SumOps.empty())
3350 SumOps.push_back(getZero(Ty));
3351 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3352 }
3353 if (!Overflow) {
3354 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
3356 if (Ops.size() == 2) return NewAddRec;
3357 Ops[Idx] = NewAddRec;
3358 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3359 OpsModified = true;
3360 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3361 if (!AddRec)
3362 break;
3363 }
3364 }
3365 if (OpsModified)
3366 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3367
3368 // Otherwise couldn't fold anything into this recurrence. Move onto the
3369 // next one.
3370 }
3371
3372 // Okay, it looks like we really DO need an mul expr. Check to see if we
3373 // already have one, otherwise create a new one.
3374 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3375}
3376
3377/// Represents an unsigned remainder expression based on unsigned division.
3379 const SCEV *RHS) {
3382 "SCEVURemExpr operand types don't match!");
3383
3384 // Short-circuit easy cases
3385 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3386 // If constant is one, the result is trivial
3387 if (RHSC->getValue()->isOne())
3388 return getZero(LHS->getType()); // X urem 1 --> 0
3389
3390 // If constant is a power of two, fold into a zext(trunc(LHS)).
3391 if (RHSC->getAPInt().isPowerOf2()) {
3392 Type *FullTy = LHS->getType();
3393 Type *TruncTy =
3394 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3395 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3396 }
3397 }
3398
3399 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3400 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3401 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3402 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3403}
3404
3405/// Get a canonical unsigned division expression, or something simpler if
3406/// possible.
3408 const SCEV *RHS) {
3409 assert(!LHS->getType()->isPointerTy() &&
3410 "SCEVUDivExpr operand can't be pointer!");
3411 assert(LHS->getType() == RHS->getType() &&
3412 "SCEVUDivExpr operand types don't match!");
3413
3415 ID.AddInteger(scUDivExpr);
3416 ID.AddPointer(LHS);
3417 ID.AddPointer(RHS);
3418 void *IP = nullptr;
3419 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3420 return S;
3421
3422 // 0 udiv Y == 0
3423 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3424 if (LHSC->getValue()->isZero())
3425 return LHS;
3426
3427 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3428 if (RHSC->getValue()->isOne())
3429 return LHS; // X udiv 1 --> x
3430 // If the denominator is zero, the result of the udiv is undefined. Don't
3431 // try to analyze it, because the resolution chosen here may differ from
3432 // the resolution chosen in other parts of the compiler.
3433 if (!RHSC->getValue()->isZero()) {
3434 // Determine if the division can be folded into the operands of
3435 // its operands.
3436 // TODO: Generalize this to non-constants by using known-bits information.
3437 Type *Ty = LHS->getType();
3438 unsigned LZ = RHSC->getAPInt().countl_zero();
3439 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3440 // For non-power-of-two values, effectively round the value up to the
3441 // nearest power of two.
3442 if (!RHSC->getAPInt().isPowerOf2())
3443 ++MaxShiftAmt;
3444 IntegerType *ExtTy =
3445 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3446 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3447 if (const SCEVConstant *Step =
3448 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3449 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3450 const APInt &StepInt = Step->getAPInt();
3451 const APInt &DivInt = RHSC->getAPInt();
3452 if (!StepInt.urem(DivInt) &&
3453 getZeroExtendExpr(AR, ExtTy) ==
3454 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3455 getZeroExtendExpr(Step, ExtTy),
3456 AR->getLoop(), SCEV::FlagAnyWrap)) {
3458 for (const SCEV *Op : AR->operands())
3459 Operands.push_back(getUDivExpr(Op, RHS));
3460 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3461 }
3462 /// Get a canonical UDivExpr for a recurrence.
3463 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3464 // We can currently only fold X%N if X is constant.
3465 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3466 if (StartC && !DivInt.urem(StepInt) &&
3467 getZeroExtendExpr(AR, ExtTy) ==
3468 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3469 getZeroExtendExpr(Step, ExtTy),
3470 AR->getLoop(), SCEV::FlagAnyWrap)) {
3471 const APInt &StartInt = StartC->getAPInt();
3472 const APInt &StartRem = StartInt.urem(StepInt);
3473 if (StartRem != 0) {
3474 const SCEV *NewLHS =
3475 getAddRecExpr(getConstant(StartInt - StartRem), Step,
3476 AR->getLoop(), SCEV::FlagNW);
3477 if (LHS != NewLHS) {
3478 LHS = NewLHS;
3479
3480 // Reset the ID to include the new LHS, and check if it is
3481 // already cached.
3482 ID.clear();
3483 ID.AddInteger(scUDivExpr);
3484 ID.AddPointer(LHS);
3485 ID.AddPointer(RHS);
3486 IP = nullptr;
3487 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3488 return S;
3489 }
3490 }
3491 }
3492 }
3493 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3494 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3496 for (const SCEV *Op : M->operands())
3497 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3498 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3499 // Find an operand that's safely divisible.
3500 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3501 const SCEV *Op = M->getOperand(i);
3502 const SCEV *Div = getUDivExpr(Op, RHSC);
3503 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3504 Operands = SmallVector<const SCEV *, 4>(M->operands());
3505 Operands[i] = Div;
3506 return getMulExpr(Operands);
3507 }
3508 }
3509 }
3510
3511 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3512 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3513 if (auto *DivisorConstant =
3514 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3515 bool Overflow = false;
3516 APInt NewRHS =
3517 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3518 if (Overflow) {
3519 return getConstant(RHSC->getType(), 0, false);
3520 }
3521 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3522 }
3523 }
3524
3525 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3526 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3528 for (const SCEV *Op : A->operands())
3529 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3530 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3531 Operands.clear();
3532 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3533 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3534 if (isa<SCEVUDivExpr>(Op) ||
3535 getMulExpr(Op, RHS) != A->getOperand(i))
3536 break;
3537 Operands.push_back(Op);
3538 }
3539 if (Operands.size() == A->getNumOperands())
3540 return getAddExpr(Operands);
3541 }
3542 }
3543
3544 // Fold if both operands are constant.
3545 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3546 return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3547 }
3548 }
3549
3550 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3551 // changes). Make sure we get a new one.
3552 IP = nullptr;
3553 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3554 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3555 LHS, RHS);
3556 UniqueSCEVs.InsertNode(S, IP);
3557 registerUser(S, {LHS, RHS});
3558 return S;
3559}
3560
3561APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3562 APInt A = C1->getAPInt().abs();
3563 APInt B = C2->getAPInt().abs();
3564 uint32_t ABW = A.getBitWidth();
3565 uint32_t BBW = B.getBitWidth();
3566
3567 if (ABW > BBW)
3568 B = B.zext(ABW);
3569 else if (ABW < BBW)
3570 A = A.zext(BBW);
3571
3572 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3573}
3574
3575/// Get a canonical unsigned division expression, or something simpler if
3576/// possible. There is no representation for an exact udiv in SCEV IR, but we
3577/// can attempt to remove factors from the LHS and RHS. We can't do this when
3578/// it's not exact because the udiv may be clearing bits.
3580 const SCEV *RHS) {
3581 // TODO: we could try to find factors in all sorts of things, but for now we
3582 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3583 // end of this file for inspiration.
3584
3585 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3586 if (!Mul || !Mul->hasNoUnsignedWrap())
3587 return getUDivExpr(LHS, RHS);
3588
3589 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3590 // If the mulexpr multiplies by a constant, then that constant must be the
3591 // first element of the mulexpr.
3592 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3593 if (LHSCst == RHSCst) {
3595 return getMulExpr(Operands);
3596 }
3597
3598 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3599 // that there's a factor provided by one of the other terms. We need to
3600 // check.
3601 APInt Factor = gcd(LHSCst, RHSCst);
3602 if (!Factor.isIntN(1)) {
3603 LHSCst =
3604 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3605 RHSCst =
3606 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3608 Operands.push_back(LHSCst);
3609 append_range(Operands, Mul->operands().drop_front());
3611 RHS = RHSCst;
3612 Mul = dyn_cast<SCEVMulExpr>(LHS);
3613 if (!Mul)
3614 return getUDivExactExpr(LHS, RHS);
3615 }
3616 }
3617 }
3618
3619 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3620 if (Mul->getOperand(i) == RHS) {
3622 append_range(Operands, Mul->operands().take_front(i));
3623 append_range(Operands, Mul->operands().drop_front(i + 1));
3624 return getMulExpr(Operands);
3625 }
3626 }
3627
3628 return getUDivExpr(LHS, RHS);
3629}
3630
3631/// Get an add recurrence expression for the specified loop. Simplify the
3632/// expression as much as possible.
3633const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3634 const Loop *L,
3635 SCEV::NoWrapFlags Flags) {
3637 Operands.push_back(Start);
3638 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3639 if (StepChrec->getLoop() == L) {
3640 append_range(Operands, StepChrec->operands());
3641 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3642 }
3643
3644 Operands.push_back(Step);
3645 return getAddRecExpr(Operands, L, Flags);
3646}
3647
3648/// Get an add recurrence expression for the specified loop. Simplify the
3649/// expression as much as possible.
3650const SCEV *
3652 const Loop *L, SCEV::NoWrapFlags Flags) {
3653 if (Operands.size() == 1) return Operands[0];
3654#ifndef NDEBUG
3656 for (const SCEV *Op : llvm::drop_begin(Operands)) {
3657 assert(getEffectiveSCEVType(Op->getType()) == ETy &&
3658 "SCEVAddRecExpr operand types don't match!");
3659 assert(!Op->getType()->isPointerTy() && "Step must be integer");
3660 }
3661 for (const SCEV *Op : Operands)
3663 "SCEVAddRecExpr operand is not available at loop entry!");
3664#endif
3665
3666 if (Operands.back()->isZero()) {
3667 Operands.pop_back();
3668 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3669 }
3670
3671 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3672 // use that information to infer NUW and NSW flags. However, computing a
3673 // BE count requires calling getAddRecExpr, so we may not yet have a
3674 // meaningful BE count at this point (and if we don't, we'd be stuck
3675 // with a SCEVCouldNotCompute as the cached BE count).
3676
3677 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3678
3679 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3680 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3681 const Loop *NestedLoop = NestedAR->getLoop();
3682 if (L->contains(NestedLoop)
3683 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3684 : (!NestedLoop->contains(L) &&
3685 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3686 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands());
3687 Operands[0] = NestedAR->getStart();
3688 // AddRecs require their operands be loop-invariant with respect to their
3689 // loops. Don't perform this transformation if it would break this
3690 // requirement.
3691 bool AllInvariant = all_of(
3692 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3693
3694 if (AllInvariant) {
3695 // Create a recurrence for the outer loop with the same step size.
3696 //
3697 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3698 // inner recurrence has the same property.
3699 SCEV::NoWrapFlags OuterFlags =
3700 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3701
3702 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3703 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3704 return isLoopInvariant(Op, NestedLoop);
3705 });
3706
3707 if (AllInvariant) {
3708 // Ok, both add recurrences are valid after the transformation.
3709 //
3710 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3711 // the outer recurrence has the same property.
3712 SCEV::NoWrapFlags InnerFlags =
3713 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3714 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3715 }
3716 }
3717 // Reset Operands to its original state.
3718 Operands[0] = NestedAR;
3719 }
3720 }
3721
3722 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3723 // already have one, otherwise create a new one.
3724 return getOrCreateAddRecExpr(Operands, L, Flags);
3725}
3726
3727const SCEV *
3729 const SmallVectorImpl<const SCEV *> &IndexExprs) {
3730 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3731 // getSCEV(Base)->getType() has the same address space as Base->getType()
3732 // because SCEV::getType() preserves the address space.
3733 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3734 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
3735 if (NW != GEPNoWrapFlags::none()) {
3736 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3737 // but to do that, we have to ensure that said flag is valid in the entire
3738 // defined scope of the SCEV.
3739 // TODO: non-instructions have global scope. We might be able to prove
3740 // some global scope cases
3741 auto *GEPI = dyn_cast<Instruction>(GEP);
3742 if (!GEPI || !isSCEVExprNeverPoison(GEPI))
3743 NW = GEPNoWrapFlags::none();
3744 }
3745
3747 if (NW.hasNoUnsignedSignedWrap())
3748 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNSW);
3749 if (NW.hasNoUnsignedWrap())
3750 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNUW);
3751
3752 Type *CurTy = GEP->getType();
3753 bool FirstIter = true;
3755 for (const SCEV *IndexExpr : IndexExprs) {
3756 // Compute the (potentially symbolic) offset in bytes for this index.
3757 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3758 // For a struct, add the member offset.
3759 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3760 unsigned FieldNo = Index->getZExtValue();
3761 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3762 Offsets.push_back(FieldOffset);
3763
3764 // Update CurTy to the type of the field at Index.
3765 CurTy = STy->getTypeAtIndex(Index);
3766 } else {
3767 // Update CurTy to its element type.
3768 if (FirstIter) {
3769 assert(isa<PointerType>(CurTy) &&
3770 "The first index of a GEP indexes a pointer");
3771 CurTy = GEP->getSourceElementType();
3772 FirstIter = false;
3773 } else {
3775 }
3776 // For an array, add the element offset, explicitly scaled.
3777 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3778 // Getelementptr indices are signed.
3779 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3780
3781 // Multiply the index by the element size to compute the element offset.
3782 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3783 Offsets.push_back(LocalOffset);
3784 }
3785 }
3786
3787 // Handle degenerate case of GEP without offsets.
3788 if (Offsets.empty())
3789 return BaseExpr;
3790
3791 // Add the offsets together, assuming nsw if inbounds.
3792 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3793 // Add the base address and the offset. We cannot use the nsw flag, as the
3794 // base address is unsigned. However, if we know that the offset is
3795 // non-negative, we can use nuw.
3796 bool NUW = NW.hasNoUnsignedWrap() ||
3799 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3800 assert(BaseExpr->getType() == GEPExpr->getType() &&
3801 "GEP should not change type mid-flight.");
3802 return GEPExpr;
3803}
3804
3805SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3808 ID.AddInteger(SCEVType);
3809 for (const SCEV *Op : Ops)
3810 ID.AddPointer(Op);
3811 void *IP = nullptr;
3812 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3813}
3814
3815const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3817 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3818}
3819
3822 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3823 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3824 if (Ops.size() == 1) return Ops[0];
3825#ifndef NDEBUG
3826 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3827 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3828 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3829 "Operand types don't match!");
3830 assert(Ops[0]->getType()->isPointerTy() ==
3831 Ops[i]->getType()->isPointerTy() &&
3832 "min/max should be consistently pointerish");
3833 }
3834#endif
3835
3836 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3837 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3838
3839 const SCEV *Folded = constantFoldAndGroupOps(
3840 *this, LI, DT, Ops,
3841 [&](const APInt &C1, const APInt &C2) {
3842 switch (Kind) {
3843 case scSMaxExpr:
3844 return APIntOps::smax(C1, C2);
3845 case scSMinExpr:
3846 return APIntOps::smin(C1, C2);
3847 case scUMaxExpr:
3848 return APIntOps::umax(C1, C2);
3849 case scUMinExpr:
3850 return APIntOps::umin(C1, C2);
3851 default:
3852 llvm_unreachable("Unknown SCEV min/max opcode");
3853 }
3854 },
3855 [&](const APInt &C) {
3856 // identity
3857 if (IsMax)
3858 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3859 else
3860 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3861 },
3862 [&](const APInt &C) {
3863 // absorber
3864 if (IsMax)
3865 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3866 else
3867 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3868 });
3869 if (Folded)
3870 return Folded;
3871
3872 // Check if we have created the same expression before.
3873 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3874 return S;
3875 }
3876
3877 // Find the first operation of the same kind
3878 unsigned Idx = 0;
3879 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3880 ++Idx;
3881
3882 // Check to see if one of the operands is of the same kind. If so, expand its
3883 // operands onto our operand list, and recurse to simplify.
3884 if (Idx < Ops.size()) {
3885 bool DeletedAny = false;
3886 while (Ops[Idx]->getSCEVType() == Kind) {
3887 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3888 Ops.erase(Ops.begin()+Idx);
3889 append_range(Ops, SMME->operands());
3890 DeletedAny = true;
3891 }
3892
3893 if (DeletedAny)
3894 return getMinMaxExpr(Kind, Ops);
3895 }
3896
3897 // Okay, check to see if the same value occurs in the operand list twice. If
3898 // so, delete one. Since we sorted the list, these values are required to
3899 // be adjacent.
3904 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3905 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3906 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3907 if (Ops[i] == Ops[i + 1] ||
3908 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3909 // X op Y op Y --> X op Y
3910 // X op Y --> X, if we know X, Y are ordered appropriately
3911 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3912 --i;
3913 --e;
3914 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3915 Ops[i + 1])) {
3916 // X op Y --> Y, if we know X, Y are ordered appropriately
3917 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3918 --i;
3919 --e;
3920 }
3921 }
3922
3923 if (Ops.size() == 1) return Ops[0];
3924
3925 assert(!Ops.empty() && "Reduced smax down to nothing!");
3926
3927 // Okay, it looks like we really DO need an expr. Check to see if we
3928 // already have one, otherwise create a new one.
3930 ID.AddInteger(Kind);
3931 for (const SCEV *Op : Ops)
3932 ID.AddPointer(Op);
3933 void *IP = nullptr;
3934 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3935 if (ExistingSCEV)
3936 return ExistingSCEV;
3937 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3938 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3939 SCEV *S = new (SCEVAllocator)
3940 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3941
3942 UniqueSCEVs.InsertNode(S, IP);
3943 registerUser(S, Ops);
3944 return S;
3945}
3946
3947namespace {
3948
3949class SCEVSequentialMinMaxDeduplicatingVisitor final
3950 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
3951 std::optional<const SCEV *>> {
3952 using RetVal = std::optional<const SCEV *>;
3954
3955 ScalarEvolution &SE;
3956 const SCEVTypes RootKind; // Must be a sequential min/max expression.
3957 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
3959
3960 bool canRecurseInto(SCEVTypes Kind) const {
3961 // We can only recurse into the SCEV expression of the same effective type
3962 // as the type of our root SCEV expression.
3963 return RootKind == Kind || NonSequentialRootKind == Kind;
3964 };
3965
3966 RetVal visitAnyMinMaxExpr(const SCEV *S) {
3967 assert((isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) &&
3968 "Only for min/max expressions.");
3969 SCEVTypes Kind = S->getSCEVType();
3970
3971 if (!canRecurseInto(Kind))
3972 return S;
3973
3974 auto *NAry = cast<SCEVNAryExpr>(S);
3976 bool Changed = visit(Kind, NAry->operands(), NewOps);
3977
3978 if (!Changed)
3979 return S;
3980 if (NewOps.empty())
3981 return std::nullopt;
3982
3983 return isa<SCEVSequentialMinMaxExpr>(S)
3984 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
3985 : SE.getMinMaxExpr(Kind, NewOps);
3986 }
3987
3988 RetVal visit(const SCEV *S) {
3989 // Has the whole operand been seen already?
3990 if (!SeenOps.insert(S).second)
3991 return std::nullopt;
3992 return Base::visit(S);
3993 }
3994
3995public:
3996 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
3997 SCEVTypes RootKind)
3998 : SE(SE), RootKind(RootKind),
3999 NonSequentialRootKind(
4000 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4001 RootKind)) {}
4002
4003 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<const SCEV *> OrigOps,
4005 bool Changed = false;
4007 Ops.reserve(OrigOps.size());
4008
4009 for (const SCEV *Op : OrigOps) {
4010 RetVal NewOp = visit(Op);
4011 if (NewOp != Op)
4012 Changed = true;
4013 if (NewOp)
4014 Ops.emplace_back(*NewOp);
4015 }
4016
4017 if (Changed)
4018 NewOps = std::move(Ops);
4019 return Changed;
4020 }
4021
4022 RetVal visitConstant(const SCEVConstant *Constant) { return Constant; }
4023
4024 RetVal visitVScale(const SCEVVScale *VScale) { return VScale; }
4025
4026 RetVal visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) { return Expr; }
4027
4028 RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
4029
4030 RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; }
4031
4032 RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; }
4033
4034 RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; }
4035
4036 RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; }
4037
4038 RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
4039
4040 RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
4041
4042 RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) {
4043 return visitAnyMinMaxExpr(Expr);
4044 }
4045
4046 RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) {
4047 return visitAnyMinMaxExpr(Expr);
4048 }
4049
4050 RetVal visitSMinExpr(const SCEVSMinExpr *Expr) {
4051 return visitAnyMinMaxExpr(Expr);
4052 }
4053
4054 RetVal visitUMinExpr(const SCEVUMinExpr *Expr) {
4055 return visitAnyMinMaxExpr(Expr);
4056 }
4057
4058 RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
4059 return visitAnyMinMaxExpr(Expr);
4060 }
4061
4062 RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; }
4063
4064 RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; }
4065};
4066
4067} // namespace
4068
4070 switch (Kind) {
4071 case scConstant:
4072 case scVScale:
4073 case scTruncate:
4074 case scZeroExtend:
4075 case scSignExtend:
4076 case scPtrToInt:
4077 case scAddExpr:
4078 case scMulExpr:
4079 case scUDivExpr:
4080 case scAddRecExpr:
4081 case scUMaxExpr:
4082 case scSMaxExpr:
4083 case scUMinExpr:
4084 case scSMinExpr:
4085 case scUnknown:
4086 // If any operand is poison, the whole expression is poison.
4087 return true;
4089 // FIXME: if the *first* operand is poison, the whole expression is poison.
4090 return false; // Pessimistically, say that it does not propagate poison.
4091 case scCouldNotCompute:
4092 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4093 }
4094 llvm_unreachable("Unknown SCEV kind!");
4095}
4096
4097namespace {
4098// The only way poison may be introduced in a SCEV expression is from a
4099// poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4100// not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not*
4101// introduce poison -- they encode guaranteed, non-speculated knowledge.
4102//
4103// Additionally, all SCEV nodes propagate poison from inputs to outputs,
4104// with the notable exception of umin_seq, where only poison from the first
4105// operand is (unconditionally) propagated.
4106struct SCEVPoisonCollector {
4107 bool LookThroughMaybePoisonBlocking;
4109 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4110 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4111
4112 bool follow(const SCEV *S) {
4113 if (!LookThroughMaybePoisonBlocking &&
4115 return false;
4116
4117 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4118 if (!isGuaranteedNotToBePoison(SU->getValue()))
4119 MaybePoison.insert(SU);
4120 }
4121 return true;
4122 }
4123 bool isDone() const { return false; }
4124};
4125} // namespace
4126
4127/// Return true if V is poison given that AssumedPoison is already poison.
4128static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4129 // First collect all SCEVs that might result in AssumedPoison to be poison.
4130 // We need to look through potentially poison-blocking operations here,
4131 // because we want to find all SCEVs that *might* result in poison, not only
4132 // those that are *required* to.
4133 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4134 visitAll(AssumedPoison, PC1);
4135
4136 // AssumedPoison is never poison. As the assumption is false, the implication
4137 // is true. Don't bother walking the other SCEV in this case.
4138 if (PC1.MaybePoison.empty())
4139 return true;
4140
4141 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4142 // as well. We cannot look through potentially poison-blocking operations
4143 // here, as their arguments only *may* make the result poison.
4144 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4145 visitAll(S, PC2);
4146
4147 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4148 // it will also make S poison by being part of PC2.MaybePoison.
4149 return llvm::set_is_subset(PC1.MaybePoison, PC2.MaybePoison);
4150}
4151
4153 SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4154 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4155 visitAll(S, PC);
4156 for (const SCEVUnknown *SU : PC.MaybePoison)
4157 Result.insert(SU->getValue());
4158}
4159
4161 const SCEV *S, Instruction *I,
4162 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
4163 // If the instruction cannot be poison, it's always safe to reuse.
4165 return true;
4166
4167 // Otherwise, it is possible that I is more poisonous that S. Collect the
4168 // poison-contributors of S, and then check whether I has any additional
4169 // poison-contributors. Poison that is contributed through poison-generating
4170 // flags is handled by dropping those flags instead.
4172 getPoisonGeneratingValues(PoisonVals, S);
4173
4174 SmallVector<Value *> Worklist;
4176 Worklist.push_back(I);
4177 while (!Worklist.empty()) {
4178 Value *V = Worklist.pop_back_val();
4179 if (!Visited.insert(V).second)
4180 continue;
4181
4182 // Avoid walking large instruction graphs.
4183 if (Visited.size() > 16)
4184 return false;
4185
4186 // Either the value can't be poison, or the S would also be poison if it
4187 // is.
4188 if (PoisonVals.contains(V) || isGuaranteedNotToBePoison(V))
4189 continue;
4190
4191 auto *I = dyn_cast<Instruction>(V);
4192 if (!I)
4193 return false;
4194
4195 // Disjoint or instructions are interpreted as adds by SCEV. However, we
4196 // can't replace an arbitrary add with disjoint or, even if we drop the
4197 // flag. We would need to convert the or into an add.
4198 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
4199 if (PDI->isDisjoint())
4200 return false;
4201
4202 // FIXME: Ignore vscale, even though it technically could be poison. Do this
4203 // because SCEV currently assumes it can't be poison. Remove this special
4204 // case once we proper model when vscale can be poison.
4205 if (auto *II = dyn_cast<IntrinsicInst>(I);
4206 II && II->getIntrinsicID() == Intrinsic::vscale)
4207 continue;
4208
4209 if (canCreatePoison(cast<Operator>(I), /*ConsiderFlagsAndMetadata*/ false))
4210 return false;
4211
4212 // If the instruction can't create poison, we can recurse to its operands.
4213 if (I->hasPoisonGeneratingAnnotations())
4214 DropPoisonGeneratingInsts.push_back(I);
4215
4216 for (Value *Op : I->operands())
4217 Worklist.push_back(Op);
4218 }
4219 return true;
4220}
4221
4222const SCEV *
4225 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4226 "Not a SCEVSequentialMinMaxExpr!");
4227 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4228 if (Ops.size() == 1)
4229 return Ops[0];
4230#ifndef NDEBUG
4231 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4232 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4233 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4234 "Operand types don't match!");
4235 assert(Ops[0]->getType()->isPointerTy() ==
4236 Ops[i]->getType()->isPointerTy() &&
4237 "min/max should be consistently pointerish");
4238 }
4239#endif
4240
4241 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4242 // so we can *NOT* do any kind of sorting of the expressions!
4243
4244 // Check if we have created the same expression before.
4245 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4246 return S;
4247
4248 // FIXME: there are *some* simplifications that we can do here.
4249
4250 // Keep only the first instance of an operand.
4251 {
4252 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4253 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4254 if (Changed)
4255 return getSequentialMinMaxExpr(Kind, Ops);
4256 }
4257
4258 // Check to see if one of the operands is of the same kind. If so, expand its
4259 // operands onto our operand list, and recurse to simplify.
4260 {
4261 unsigned Idx = 0;
4262 bool DeletedAny = false;
4263 while (Idx < Ops.size()) {
4264 if (Ops[Idx]->getSCEVType() != Kind) {
4265 ++Idx;
4266 continue;
4267 }
4268 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4269 Ops.erase(Ops.begin() + Idx);
4270 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4271 SMME->operands().end());
4272 DeletedAny = true;
4273 }
4274
4275 if (DeletedAny)
4276 return getSequentialMinMaxExpr(Kind, Ops);
4277 }
4278
4279 const SCEV *SaturationPoint;
4281 switch (Kind) {
4283 SaturationPoint = getZero(Ops[0]->getType());
4284 Pred = ICmpInst::ICMP_ULE;
4285 break;
4286 default:
4287 llvm_unreachable("Not a sequential min/max type.");
4288 }
4289
4290 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4291 // We can replace %x umin_seq %y with %x umin %y if either:
4292 // * %y being poison implies %x is also poison.
4293 // * %x cannot be the saturating value (e.g. zero for umin).
4294 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4295 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4296 SaturationPoint)) {
4297 SmallVector<const SCEV *> SeqOps = {Ops[i - 1], Ops[i]};
4298 Ops[i - 1] = getMinMaxExpr(
4300 SeqOps);
4301 Ops.erase(Ops.begin() + i);
4302 return getSequentialMinMaxExpr(Kind, Ops);
4303 }
4304 // Fold %x umin_seq %y to %x if %x ule %y.
4305 // TODO: We might be able to prove the predicate for a later operand.
4306 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4307 Ops.erase(Ops.begin() + i);
4308 return getSequentialMinMaxExpr(Kind, Ops);
4309 }
4310 }
4311
4312 // Okay, it looks like we really DO need an expr. Check to see if we
4313 // already have one, otherwise create a new one.
4315 ID.AddInteger(Kind);
4316 for (const SCEV *Op : Ops)
4317 ID.AddPointer(Op);
4318 void *IP = nullptr;
4319 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4320 if (ExistingSCEV)
4321 return ExistingSCEV;
4322
4323 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
4324 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
4325 SCEV *S = new (SCEVAllocator)
4326 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4327
4328 UniqueSCEVs.InsertNode(S, IP);
4329 registerUser(S, Ops);
4330 return S;
4331}
4332
4333const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4335 return getSMaxExpr(Ops);
4336}
4337
4339 return getMinMaxExpr(scSMaxExpr, Ops);
4340}
4341
4342const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4344 return getUMaxExpr(Ops);
4345}
4346
4348 return getMinMaxExpr(scUMaxExpr, Ops);
4349}
4350
4352 const SCEV *RHS) {
4354 return getSMinExpr(Ops);
4355}
4356
4358 return getMinMaxExpr(scSMinExpr, Ops);
4359}
4360
4361const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, const SCEV *RHS,
4362 bool Sequential) {
4364 return getUMinExpr(Ops, Sequential);
4365}
4366
4368 bool Sequential) {
4369 return Sequential ? getSequentialMinMaxExpr(scSequentialUMinExpr, Ops)
4370 : getMinMaxExpr(scUMinExpr, Ops);
4371}
4372
4373const SCEV *
4375 const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4376 if (Size.isScalable())
4377 Res = getMulExpr(Res, getVScale(IntTy));
4378 return Res;
4379}
4380
4382 return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4383}
4384
4386 return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4387}
4388
4390 StructType *STy,
4391 unsigned FieldNo) {
4392 // We can bypass creating a target-independent constant expression and then
4393 // folding it back into a ConstantInt. This is just a compile-time
4394 // optimization.
4395 const StructLayout *SL = getDataLayout().getStructLayout(STy);
4396 assert(!SL->getSizeInBits().isScalable() &&
4397 "Cannot get offset for structure containing scalable vector types");
4398 return getConstant(IntTy, SL->getElementOffset(FieldNo));
4399}
4400
4402 // Don't attempt to do anything other than create a SCEVUnknown object
4403 // here. createSCEV only calls getUnknown after checking for all other
4404 // interesting possibilities, and any other code that calls getUnknown
4405 // is doing so in order to hide a value from SCEV canonicalization.
4406
4408 ID.AddInteger(scUnknown);
4409 ID.AddPointer(V);
4410 void *IP = nullptr;
4411 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
4412 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4413 "Stale SCEVUnknown in uniquing map!");
4414 return S;
4415 }
4416 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4417 FirstUnknown);
4418 FirstUnknown = cast<SCEVUnknown>(S);
4419 UniqueSCEVs.InsertNode(S, IP);
4420 return S;
4421}
4422
4423//===----------------------------------------------------------------------===//
4424// Basic SCEV Analysis and PHI Idiom Recognition Code
4425//
4426
4427/// Test if values of the given type are analyzable within the SCEV
4428/// framework. This primarily includes integer types, and it can optionally
4429/// include pointer types if the ScalarEvolution class has access to
4430/// target-specific information.
4432 // Integers and pointers are always SCEVable.
4433 return Ty->isIntOrPtrTy();
4434}
4435
4436/// Return the size in bits of the specified type, for which isSCEVable must
4437/// return true.
4439 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4440 if (Ty->isPointerTy())
4442 return getDataLayout().getTypeSizeInBits(Ty);
4443}
4444
4445/// Return a type with the same bitwidth as the given type and which represents
4446/// how SCEV will treat the given type, for which isSCEVable must return
4447/// true. For pointer types, this is the pointer index sized integer type.
4449 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4450
4451 if (Ty->isIntegerTy())
4452 return Ty;
4453
4454 // The only other support type is pointer.
4455 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4456 return getDataLayout().getIndexType(Ty);
4457}
4458
4460 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4461}
4462
4464 const SCEV *B) {
4465 /// For a valid use point to exist, the defining scope of one operand
4466 /// must dominate the other.
4467 bool PreciseA, PreciseB;
4468 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4469 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4470 if (!PreciseA || !PreciseB)
4471 // Can't tell.
4472 return false;
4473 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4474 DT.dominates(ScopeB, ScopeA);
4475}
4476
4478 return CouldNotCompute.get();
4479}
4480
4481bool ScalarEvolution::checkValidity(const SCEV *S) const {
4482 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4483 auto *SU = dyn_cast<SCEVUnknown>(S);
4484 return SU && SU->getValue() == nullptr;
4485 });
4486
4487 return !ContainsNulls;
4488}
4489
4490bool