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