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
60 #include "llvm/Analysis/ScalarEvolution.h"
61 #include "llvm/ADT/APInt.h"
62 #include "llvm/ADT/ArrayRef.h"
63 #include "llvm/ADT/DenseMap.h"
64 #include "llvm/ADT/DepthFirstIterator.h"
65 #include "llvm/ADT/EquivalenceClasses.h"
66 #include "llvm/ADT/FoldingSet.h"
67 #include "llvm/ADT/STLExtras.h"
68 #include "llvm/ADT/ScopeExit.h"
69 #include "llvm/ADT/Sequence.h"
70 #include "llvm/ADT/SmallPtrSet.h"
71 #include "llvm/ADT/SmallSet.h"
72 #include "llvm/ADT/SmallVector.h"
73 #include "llvm/ADT/Statistic.h"
74 #include "llvm/ADT/StringExtras.h"
75 #include "llvm/ADT/StringRef.h"
76 #include "llvm/Analysis/AssumptionCache.h"
77 #include "llvm/Analysis/ConstantFolding.h"
78 #include "llvm/Analysis/InstructionSimplify.h"
79 #include "llvm/Analysis/LoopInfo.h"
80 #include "llvm/Analysis/MemoryBuiltins.h"
81 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
82 #include "llvm/Analysis/TargetLibraryInfo.h"
83 #include "llvm/Analysis/ValueTracking.h"
84 #include "llvm/Config/llvm-config.h"
85 #include "llvm/IR/Argument.h"
86 #include "llvm/IR/BasicBlock.h"
87 #include "llvm/IR/CFG.h"
88 #include "llvm/IR/Constant.h"
89 #include "llvm/IR/ConstantRange.h"
90 #include "llvm/IR/Constants.h"
91 #include "llvm/IR/DataLayout.h"
92 #include "llvm/IR/DerivedTypes.h"
93 #include "llvm/IR/Dominators.h"
94 #include "llvm/IR/Function.h"
95 #include "llvm/IR/GlobalAlias.h"
96 #include "llvm/IR/GlobalValue.h"
97 #include "llvm/IR/InstIterator.h"
98 #include "llvm/IR/InstrTypes.h"
99 #include "llvm/IR/Instruction.h"
100 #include "llvm/IR/Instructions.h"
101 #include "llvm/IR/IntrinsicInst.h"
102 #include "llvm/IR/Intrinsics.h"
103 #include "llvm/IR/LLVMContext.h"
104 #include "llvm/IR/Operator.h"
105 #include "llvm/IR/PatternMatch.h"
106 #include "llvm/IR/Type.h"
107 #include "llvm/IR/Use.h"
108 #include "llvm/IR/User.h"
109 #include "llvm/IR/Value.h"
110 #include "llvm/IR/Verifier.h"
111 #include "llvm/InitializePasses.h"
112 #include "llvm/Pass.h"
113 #include "llvm/Support/Casting.h"
114 #include "llvm/Support/CommandLine.h"
115 #include "llvm/Support/Compiler.h"
116 #include "llvm/Support/Debug.h"
117 #include "llvm/Support/ErrorHandling.h"
118 #include "llvm/Support/KnownBits.h"
119 #include "llvm/Support/SaveAndRestore.h"
120 #include "llvm/Support/raw_ostream.h"
121 #include <algorithm>
122 #include <cassert>
123 #include <climits>
124 #include <cstdint>
125 #include <cstdlib>
126 #include <map>
127 #include <memory>
128 #include <numeric>
129 #include <optional>
130 #include <tuple>
131 #include <utility>
132 #include <vector>
133
134 using namespace llvm;
135 using namespace PatternMatch;
136
137 #define DEBUG_TYPE "scalar-evolution"
138
139 STATISTIC(NumExitCountsComputed,
140 "Number of loop exits with predictable exit counts");
141 STATISTIC(NumExitCountsNotComputed,
142 "Number of loop exits without predictable exit counts");
143 STATISTIC(NumBruteForceTripCountsComputed,
144 "Number of loops with trip counts computed by force");
145
146 #ifdef EXPENSIVE_CHECKS
147 bool llvm::VerifySCEV = true;
148 #else
149 bool llvm::VerifySCEV = false;
150 #endif
151
152 static cl::opt<unsigned>
153 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
154 cl::desc("Maximum number of iterations SCEV will "
155 "symbolically execute a constant "
156 "derived loop"),
157 cl::init(100));
158
159 static cl::opt<bool, true> VerifySCEVOpt(
160 "verify-scev", cl::Hidden, cl::location(VerifySCEV),
161 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
162 static cl::opt<bool> VerifySCEVStrict(
163 "verify-scev-strict", cl::Hidden,
164 cl::desc("Enable stricter verification with -verify-scev is passed"));
165
166 static cl::opt<bool> VerifyIR(
167 "scev-verify-ir", cl::Hidden,
168 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
169 cl::init(false));
170
171 static cl::opt<unsigned> MulOpsInlineThreshold(
172 "scev-mulops-inline-threshold", cl::Hidden,
173 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
174 cl::init(32));
175
176 static cl::opt<unsigned> AddOpsInlineThreshold(
177 "scev-addops-inline-threshold", cl::Hidden,
178 cl::desc("Threshold for inlining addition operands into a SCEV"),
179 cl::init(500));
180
181 static cl::opt<unsigned> MaxSCEVCompareDepth(
182 "scalar-evolution-max-scev-compare-depth", cl::Hidden,
183 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
184 cl::init(32));
185
186 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
187 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
188 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
189 cl::init(2));
190
191 static cl::opt<unsigned> MaxValueCompareDepth(
192 "scalar-evolution-max-value-compare-depth", cl::Hidden,
193 cl::desc("Maximum depth of recursive value complexity comparisons"),
194 cl::init(2));
195
196 static cl::opt<unsigned>
197 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
198 cl::desc("Maximum depth of recursive arithmetics"),
199 cl::init(32));
200
201 static cl::opt<unsigned> MaxConstantEvolvingDepth(
202 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
203 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
204
205 static cl::opt<unsigned>
206 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
207 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
208 cl::init(8));
209
210 static cl::opt<unsigned>
211 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
212 cl::desc("Max coefficients in AddRec during evolving"),
213 cl::init(8));
214
215 static cl::opt<unsigned>
216 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
217 cl::desc("Size of the expression which is considered huge"),
218 cl::init(4096));
219
220 static cl::opt<unsigned> RangeIterThreshold(
221 "scev-range-iter-threshold", cl::Hidden,
222 cl::desc("Threshold for switching to iteratively computing SCEV ranges"),
223 cl::init(32));
224
225 static cl::opt<bool>
226 ClassifyExpressions("scalar-evolution-classify-expressions",
227 cl::Hidden, cl::init(true),
228 cl::desc("When printing analysis, include information on every instruction"));
229
230 static cl::opt<bool> UseExpensiveRangeSharpening(
231 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
232 cl::init(false),
233 cl::desc("Use more powerful methods of sharpening expression ranges. May "
234 "be costly in terms of compile time"));
235
236 static cl::opt<unsigned> MaxPhiSCCAnalysisSize(
237 "scalar-evolution-max-scc-analysis-depth", cl::Hidden,
238 cl::desc("Maximum amount of nodes to process while searching SCEVUnknown "
239 "Phi strongly connected components"),
240 cl::init(8));
241
242 static cl::opt<bool>
243 EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
244 cl::desc("Handle <= and >= in finite loops"),
245 cl::init(true));
246
247 static cl::opt<bool> UseContextForNoWrapFlagInference(
248 "scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden,
249 cl::desc("Infer nuw/nsw flags using context where suitable"),
250 cl::init(true));
251
252 //===----------------------------------------------------------------------===//
253 // SCEV class definitions
254 //===----------------------------------------------------------------------===//
255
256 //===----------------------------------------------------------------------===//
257 // Implementation of the SCEV class.
258 //
259
260 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const261 LLVM_DUMP_METHOD void SCEV::dump() const {
262 print(dbgs());
263 dbgs() << '\n';
264 }
265 #endif
266
print(raw_ostream & OS) const267 void SCEV::print(raw_ostream &OS) const {
268 switch (getSCEVType()) {
269 case scConstant:
270 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
271 return;
272 case scVScale:
273 OS << "vscale";
274 return;
275 case scPtrToInt: {
276 const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this);
277 const SCEV *Op = PtrToInt->getOperand();
278 OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to "
279 << *PtrToInt->getType() << ")";
280 return;
281 }
282 case scTruncate: {
283 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
284 const SCEV *Op = Trunc->getOperand();
285 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
286 << *Trunc->getType() << ")";
287 return;
288 }
289 case scZeroExtend: {
290 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
291 const SCEV *Op = ZExt->getOperand();
292 OS << "(zext " << *Op->getType() << " " << *Op << " to "
293 << *ZExt->getType() << ")";
294 return;
295 }
296 case scSignExtend: {
297 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
298 const SCEV *Op = SExt->getOperand();
299 OS << "(sext " << *Op->getType() << " " << *Op << " to "
300 << *SExt->getType() << ")";
301 return;
302 }
303 case scAddRecExpr: {
304 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
305 OS << "{" << *AR->getOperand(0);
306 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
307 OS << ",+," << *AR->getOperand(i);
308 OS << "}<";
309 if (AR->hasNoUnsignedWrap())
310 OS << "nuw><";
311 if (AR->hasNoSignedWrap())
312 OS << "nsw><";
313 if (AR->hasNoSelfWrap() &&
314 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
315 OS << "nw><";
316 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
317 OS << ">";
318 return;
319 }
320 case scAddExpr:
321 case scMulExpr:
322 case scUMaxExpr:
323 case scSMaxExpr:
324 case scUMinExpr:
325 case scSMinExpr:
326 case scSequentialUMinExpr: {
327 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
328 const char *OpStr = nullptr;
329 switch (NAry->getSCEVType()) {
330 case scAddExpr: OpStr = " + "; break;
331 case scMulExpr: OpStr = " * "; break;
332 case scUMaxExpr: OpStr = " umax "; break;
333 case scSMaxExpr: OpStr = " smax "; break;
334 case scUMinExpr:
335 OpStr = " umin ";
336 break;
337 case scSMinExpr:
338 OpStr = " smin ";
339 break;
340 case scSequentialUMinExpr:
341 OpStr = " umin_seq ";
342 break;
343 default:
344 llvm_unreachable("There are no other nary expression types.");
345 }
346 OS << "(";
347 ListSeparator LS(OpStr);
348 for (const SCEV *Op : NAry->operands())
349 OS << LS << *Op;
350 OS << ")";
351 switch (NAry->getSCEVType()) {
352 case scAddExpr:
353 case scMulExpr:
354 if (NAry->hasNoUnsignedWrap())
355 OS << "<nuw>";
356 if (NAry->hasNoSignedWrap())
357 OS << "<nsw>";
358 break;
359 default:
360 // Nothing to print for other nary expressions.
361 break;
362 }
363 return;
364 }
365 case scUDivExpr: {
366 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
367 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
368 return;
369 }
370 case scUnknown:
371 cast<SCEVUnknown>(this)->getValue()->printAsOperand(OS, false);
372 return;
373 case scCouldNotCompute:
374 OS << "***COULDNOTCOMPUTE***";
375 return;
376 }
377 llvm_unreachable("Unknown SCEV kind!");
378 }
379
getType() const380 Type *SCEV::getType() const {
381 switch (getSCEVType()) {
382 case scConstant:
383 return cast<SCEVConstant>(this)->getType();
384 case scVScale:
385 return cast<SCEVVScale>(this)->getType();
386 case scPtrToInt:
387 case scTruncate:
388 case scZeroExtend:
389 case scSignExtend:
390 return cast<SCEVCastExpr>(this)->getType();
391 case scAddRecExpr:
392 return cast<SCEVAddRecExpr>(this)->getType();
393 case scMulExpr:
394 return cast<SCEVMulExpr>(this)->getType();
395 case scUMaxExpr:
396 case scSMaxExpr:
397 case scUMinExpr:
398 case scSMinExpr:
399 return cast<SCEVMinMaxExpr>(this)->getType();
400 case scSequentialUMinExpr:
401 return cast<SCEVSequentialMinMaxExpr>(this)->getType();
402 case scAddExpr:
403 return cast<SCEVAddExpr>(this)->getType();
404 case scUDivExpr:
405 return cast<SCEVUDivExpr>(this)->getType();
406 case scUnknown:
407 return cast<SCEVUnknown>(this)->getType();
408 case scCouldNotCompute:
409 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
410 }
411 llvm_unreachable("Unknown SCEV kind!");
412 }
413
operands() const414 ArrayRef<const SCEV *> SCEV::operands() const {
415 switch (getSCEVType()) {
416 case scConstant:
417 case scVScale:
418 case scUnknown:
419 return {};
420 case scPtrToInt:
421 case scTruncate:
422 case scZeroExtend:
423 case scSignExtend:
424 return cast<SCEVCastExpr>(this)->operands();
425 case scAddRecExpr:
426 case scAddExpr:
427 case scMulExpr:
428 case scUMaxExpr:
429 case scSMaxExpr:
430 case scUMinExpr:
431 case scSMinExpr:
432 case scSequentialUMinExpr:
433 return cast<SCEVNAryExpr>(this)->operands();
434 case scUDivExpr:
435 return cast<SCEVUDivExpr>(this)->operands();
436 case scCouldNotCompute:
437 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
438 }
439 llvm_unreachable("Unknown SCEV kind!");
440 }
441
isZero() const442 bool SCEV::isZero() const {
443 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
444 return SC->getValue()->isZero();
445 return false;
446 }
447
isOne() const448 bool SCEV::isOne() const {
449 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
450 return SC->getValue()->isOne();
451 return false;
452 }
453
isAllOnesValue() const454 bool SCEV::isAllOnesValue() const {
455 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
456 return SC->getValue()->isMinusOne();
457 return false;
458 }
459
isNonConstantNegative() const460 bool SCEV::isNonConstantNegative() const {
461 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
462 if (!Mul) return false;
463
464 // If there is a constant factor, it will be first.
465 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
466 if (!SC) return false;
467
468 // Return true if the value is negative, this matches things like (-42 * V).
469 return SC->getAPInt().isNegative();
470 }
471
SCEVCouldNotCompute()472 SCEVCouldNotCompute::SCEVCouldNotCompute() :
473 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
474
classof(const SCEV * S)475 bool SCEVCouldNotCompute::classof(const SCEV *S) {
476 return S->getSCEVType() == scCouldNotCompute;
477 }
478
getConstant(ConstantInt * V)479 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
480 FoldingSetNodeID ID;
481 ID.AddInteger(scConstant);
482 ID.AddPointer(V);
483 void *IP = nullptr;
484 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
485 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
486 UniqueSCEVs.InsertNode(S, IP);
487 return S;
488 }
489
getConstant(const APInt & Val)490 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
491 return getConstant(ConstantInt::get(getContext(), Val));
492 }
493
494 const SCEV *
getConstant(Type * Ty,uint64_t V,bool isSigned)495 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
496 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
497 return getConstant(ConstantInt::get(ITy, V, isSigned));
498 }
499
getVScale(Type * Ty)500 const SCEV *ScalarEvolution::getVScale(Type *Ty) {
501 FoldingSetNodeID ID;
502 ID.AddInteger(scVScale);
503 ID.AddPointer(Ty);
504 void *IP = nullptr;
505 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
506 return S;
507 SCEV *S = new (SCEVAllocator) SCEVVScale(ID.Intern(SCEVAllocator), Ty);
508 UniqueSCEVs.InsertNode(S, IP);
509 return S;
510 }
511
getElementCount(Type * Ty,ElementCount EC)512 const SCEV *ScalarEvolution::getElementCount(Type *Ty, ElementCount EC) {
513 const SCEV *Res = getConstant(Ty, EC.getKnownMinValue());
514 if (EC.isScalable())
515 Res = getMulExpr(Res, getVScale(Ty));
516 return Res;
517 }
518
SCEVCastExpr(const FoldingSetNodeIDRef ID,SCEVTypes SCEVTy,const SCEV * op,Type * ty)519 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
520 const SCEV *op, Type *ty)
521 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {}
522
SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID,const SCEV * Op,Type * ITy)523 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op,
524 Type *ITy)
525 : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
526 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
527 "Must be a non-bit-width-changing pointer-to-integer cast!");
528 }
529
SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,SCEVTypes SCEVTy,const SCEV * op,Type * ty)530 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,
531 SCEVTypes SCEVTy, const SCEV *op,
532 Type *ty)
533 : SCEVCastExpr(ID, SCEVTy, op, ty) {}
534
SCEVTruncateExpr(const FoldingSetNodeIDRef ID,const SCEV * op,Type * ty)535 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op,
536 Type *ty)
537 : SCEVIntegralCastExpr(ID, scTruncate, op, ty) {
538 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
539 "Cannot truncate non-integer value!");
540 }
541
SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,const SCEV * op,Type * ty)542 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
543 const SCEV *op, Type *ty)
544 : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) {
545 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
546 "Cannot zero extend non-integer value!");
547 }
548
SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,const SCEV * op,Type * ty)549 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
550 const SCEV *op, Type *ty)
551 : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) {
552 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
553 "Cannot sign extend non-integer value!");
554 }
555
deleted()556 void SCEVUnknown::deleted() {
557 // Clear this SCEVUnknown from various maps.
558 SE->forgetMemoizedResults(this);
559
560 // Remove this SCEVUnknown from the uniquing map.
561 SE->UniqueSCEVs.RemoveNode(this);
562
563 // Release the value.
564 setValPtr(nullptr);
565 }
566
allUsesReplacedWith(Value * New)567 void SCEVUnknown::allUsesReplacedWith(Value *New) {
568 // Clear this SCEVUnknown from various maps.
569 SE->forgetMemoizedResults(this);
570
571 // Remove this SCEVUnknown from the uniquing map.
572 SE->UniqueSCEVs.RemoveNode(this);
573
574 // Replace the value pointer in case someone is still using this SCEVUnknown.
575 setValPtr(New);
576 }
577
578 //===----------------------------------------------------------------------===//
579 // SCEV Utilities
580 //===----------------------------------------------------------------------===//
581
582 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
583 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
584 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that
585 /// have been previously deemed to be "equally complex" by this routine. It is
586 /// intended to avoid exponential time complexity in cases like:
587 ///
588 /// %a = f(%x, %y)
589 /// %b = f(%a, %a)
590 /// %c = f(%b, %b)
591 ///
592 /// %d = f(%x, %y)
593 /// %e = f(%d, %d)
594 /// %f = f(%e, %e)
595 ///
596 /// CompareValueComplexity(%f, %c)
597 ///
598 /// Since we do not continue running this routine on expression trees once we
599 /// have seen unequal values, there is no need to track them in the cache.
600 static int
CompareValueComplexity(EquivalenceClasses<const Value * > & EqCacheValue,const LoopInfo * const LI,Value * LV,Value * RV,unsigned Depth)601 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
602 const LoopInfo *const LI, Value *LV, Value *RV,
603 unsigned Depth) {
604 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
605 return 0;
606
607 // Order pointer values after integer values. This helps SCEVExpander form
608 // GEPs.
609 bool LIsPointer = LV->getType()->isPointerTy(),
610 RIsPointer = RV->getType()->isPointerTy();
611 if (LIsPointer != RIsPointer)
612 return (int)LIsPointer - (int)RIsPointer;
613
614 // Compare getValueID values.
615 unsigned LID = LV->getValueID(), RID = RV->getValueID();
616 if (LID != RID)
617 return (int)LID - (int)RID;
618
619 // Sort arguments by their position.
620 if (const auto *LA = dyn_cast<Argument>(LV)) {
621 const auto *RA = cast<Argument>(RV);
622 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
623 return (int)LArgNo - (int)RArgNo;
624 }
625
626 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
627 const auto *RGV = cast<GlobalValue>(RV);
628
629 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
630 auto LT = GV->getLinkage();
631 return !(GlobalValue::isPrivateLinkage(LT) ||
632 GlobalValue::isInternalLinkage(LT));
633 };
634
635 // Use the names to distinguish the two values, but only if the
636 // names are semantically important.
637 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
638 return LGV->getName().compare(RGV->getName());
639 }
640
641 // For instructions, compare their loop depth, and their operand count. This
642 // is pretty loose.
643 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
644 const auto *RInst = cast<Instruction>(RV);
645
646 // Compare loop depths.
647 const BasicBlock *LParent = LInst->getParent(),
648 *RParent = RInst->getParent();
649 if (LParent != RParent) {
650 unsigned LDepth = LI->getLoopDepth(LParent),
651 RDepth = LI->getLoopDepth(RParent);
652 if (LDepth != RDepth)
653 return (int)LDepth - (int)RDepth;
654 }
655
656 // Compare the number of operands.
657 unsigned LNumOps = LInst->getNumOperands(),
658 RNumOps = RInst->getNumOperands();
659 if (LNumOps != RNumOps)
660 return (int)LNumOps - (int)RNumOps;
661
662 for (unsigned Idx : seq(LNumOps)) {
663 int Result =
664 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
665 RInst->getOperand(Idx), Depth + 1);
666 if (Result != 0)
667 return Result;
668 }
669 }
670
671 EqCacheValue.unionSets(LV, RV);
672 return 0;
673 }
674
675 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
676 // than RHS, respectively. A three-way result allows recursive comparisons to be
677 // more efficient.
678 // If the max analysis depth was reached, return std::nullopt, assuming we do
679 // not know if they are equivalent for sure.
680 static std::optional<int>
CompareSCEVComplexity(EquivalenceClasses<const SCEV * > & EqCacheSCEV,EquivalenceClasses<const Value * > & EqCacheValue,const LoopInfo * const LI,const SCEV * LHS,const SCEV * RHS,DominatorTree & DT,unsigned Depth=0)681 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV,
682 EquivalenceClasses<const Value *> &EqCacheValue,
683 const LoopInfo *const LI, const SCEV *LHS,
684 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
685 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
686 if (LHS == RHS)
687 return 0;
688
689 // Primarily, sort the SCEVs by their getSCEVType().
690 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
691 if (LType != RType)
692 return (int)LType - (int)RType;
693
694 if (EqCacheSCEV.isEquivalent(LHS, RHS))
695 return 0;
696
697 if (Depth > MaxSCEVCompareDepth)
698 return std::nullopt;
699
700 // Aside from the getSCEVType() ordering, the particular ordering
701 // isn't very important except that it's beneficial to be consistent,
702 // so that (a + b) and (b + a) don't end up as different expressions.
703 switch (LType) {
704 case scUnknown: {
705 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
706 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
707
708 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
709 RU->getValue(), Depth + 1);
710 if (X == 0)
711 EqCacheSCEV.unionSets(LHS, RHS);
712 return X;
713 }
714
715 case scConstant: {
716 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
717 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
718
719 // Compare constant values.
720 const APInt &LA = LC->getAPInt();
721 const APInt &RA = RC->getAPInt();
722 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
723 if (LBitWidth != RBitWidth)
724 return (int)LBitWidth - (int)RBitWidth;
725 return LA.ult(RA) ? -1 : 1;
726 }
727
728 case scVScale: {
729 const auto *LTy = cast<IntegerType>(cast<SCEVVScale>(LHS)->getType());
730 const auto *RTy = cast<IntegerType>(cast<SCEVVScale>(RHS)->getType());
731 return LTy->getBitWidth() - RTy->getBitWidth();
732 }
733
734 case scAddRecExpr: {
735 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
736 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
737
738 // There is always a dominance between two recs that are used by one SCEV,
739 // so we can safely sort recs by loop header dominance. We require such
740 // order in getAddExpr.
741 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
742 if (LLoop != RLoop) {
743 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
744 assert(LHead != RHead && "Two loops share the same header?");
745 if (DT.dominates(LHead, RHead))
746 return 1;
747 assert(DT.dominates(RHead, LHead) &&
748 "No dominance between recurrences used by one SCEV?");
749 return -1;
750 }
751
752 [[fallthrough]];
753 }
754
755 case scTruncate:
756 case scZeroExtend:
757 case scSignExtend:
758 case scPtrToInt:
759 case scAddExpr:
760 case scMulExpr:
761 case scUDivExpr:
762 case scSMaxExpr:
763 case scUMaxExpr:
764 case scSMinExpr:
765 case scUMinExpr:
766 case scSequentialUMinExpr: {
767 ArrayRef<const SCEV *> LOps = LHS->operands();
768 ArrayRef<const SCEV *> ROps = RHS->operands();
769
770 // Lexicographically compare n-ary-like expressions.
771 unsigned LNumOps = LOps.size(), RNumOps = ROps.size();
772 if (LNumOps != RNumOps)
773 return (int)LNumOps - (int)RNumOps;
774
775 for (unsigned i = 0; i != LNumOps; ++i) {
776 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LOps[i],
777 ROps[i], DT, Depth + 1);
778 if (X != 0)
779 return X;
780 }
781 EqCacheSCEV.unionSets(LHS, RHS);
782 return 0;
783 }
784
785 case scCouldNotCompute:
786 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
787 }
788 llvm_unreachable("Unknown SCEV kind!");
789 }
790
791 /// Given a list of SCEV objects, order them by their complexity, and group
792 /// objects of the same complexity together by value. When this routine is
793 /// finished, we know that any duplicates in the vector are consecutive and that
794 /// complexity is monotonically increasing.
795 ///
796 /// Note that we go take special precautions to ensure that we get deterministic
797 /// results from this routine. In other words, we don't want the results of
798 /// this to depend on where the addresses of various SCEV objects happened to
799 /// land in memory.
GroupByComplexity(SmallVectorImpl<const SCEV * > & Ops,LoopInfo * LI,DominatorTree & DT)800 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
801 LoopInfo *LI, DominatorTree &DT) {
802 if (Ops.size() < 2) return; // Noop
803
804 EquivalenceClasses<const SCEV *> EqCacheSCEV;
805 EquivalenceClasses<const Value *> EqCacheValue;
806
807 // Whether LHS has provably less complexity than RHS.
808 auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) {
809 auto Complexity =
810 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT);
811 return Complexity && *Complexity < 0;
812 };
813 if (Ops.size() == 2) {
814 // This is the common case, which also happens to be trivially simple.
815 // Special case it.
816 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
817 if (IsLessComplex(RHS, LHS))
818 std::swap(LHS, RHS);
819 return;
820 }
821
822 // Do the rough sort by complexity.
823 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
824 return IsLessComplex(LHS, RHS);
825 });
826
827 // Now that we are sorted by complexity, group elements of the same
828 // complexity. Note that this is, at worst, N^2, but the vector is likely to
829 // be extremely short in practice. Note that we take this approach because we
830 // do not want to depend on the addresses of the objects we are grouping.
831 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
832 const SCEV *S = Ops[i];
833 unsigned Complexity = S->getSCEVType();
834
835 // If there are any objects of the same complexity and same value as this
836 // one, group them.
837 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
838 if (Ops[j] == S) { // Found a duplicate.
839 // Move it to immediately after i'th element.
840 std::swap(Ops[i+1], Ops[j]);
841 ++i; // no need to rescan it.
842 if (i == e-2) return; // Done!
843 }
844 }
845 }
846 }
847
848 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
849 /// least HugeExprThreshold nodes).
hasHugeExpression(ArrayRef<const SCEV * > Ops)850 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
851 return any_of(Ops, [](const SCEV *S) {
852 return S->getExpressionSize() >= HugeExprThreshold;
853 });
854 }
855
856 //===----------------------------------------------------------------------===//
857 // Simple SCEV method implementations
858 //===----------------------------------------------------------------------===//
859
860 /// Compute BC(It, K). The result has width W. Assume, K > 0.
BinomialCoefficient(const SCEV * It,unsigned K,ScalarEvolution & SE,Type * ResultTy)861 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
862 ScalarEvolution &SE,
863 Type *ResultTy) {
864 // Handle the simplest case efficiently.
865 if (K == 1)
866 return SE.getTruncateOrZeroExtend(It, ResultTy);
867
868 // We are using the following formula for BC(It, K):
869 //
870 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
871 //
872 // Suppose, W is the bitwidth of the return value. We must be prepared for
873 // overflow. Hence, we must assure that the result of our computation is
874 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
875 // safe in modular arithmetic.
876 //
877 // However, this code doesn't use exactly that formula; the formula it uses
878 // is something like the following, where T is the number of factors of 2 in
879 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
880 // exponentiation:
881 //
882 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
883 //
884 // This formula is trivially equivalent to the previous formula. However,
885 // this formula can be implemented much more efficiently. The trick is that
886 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
887 // arithmetic. To do exact division in modular arithmetic, all we have
888 // to do is multiply by the inverse. Therefore, this step can be done at
889 // width W.
890 //
891 // The next issue is how to safely do the division by 2^T. The way this
892 // is done is by doing the multiplication step at a width of at least W + T
893 // bits. This way, the bottom W+T bits of the product are accurate. Then,
894 // when we perform the division by 2^T (which is equivalent to a right shift
895 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
896 // truncated out after the division by 2^T.
897 //
898 // In comparison to just directly using the first formula, this technique
899 // is much more efficient; using the first formula requires W * K bits,
900 // but this formula less than W + K bits. Also, the first formula requires
901 // a division step, whereas this formula only requires multiplies and shifts.
902 //
903 // It doesn't matter whether the subtraction step is done in the calculation
904 // width or the input iteration count's width; if the subtraction overflows,
905 // the result must be zero anyway. We prefer here to do it in the width of
906 // the induction variable because it helps a lot for certain cases; CodeGen
907 // isn't smart enough to ignore the overflow, which leads to much less
908 // efficient code if the width of the subtraction is wider than the native
909 // register width.
910 //
911 // (It's possible to not widen at all by pulling out factors of 2 before
912 // the multiplication; for example, K=2 can be calculated as
913 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
914 // extra arithmetic, so it's not an obvious win, and it gets
915 // much more complicated for K > 3.)
916
917 // Protection from insane SCEVs; this bound is conservative,
918 // but it probably doesn't matter.
919 if (K > 1000)
920 return SE.getCouldNotCompute();
921
922 unsigned W = SE.getTypeSizeInBits(ResultTy);
923
924 // Calculate K! / 2^T and T; we divide out the factors of two before
925 // multiplying for calculating K! / 2^T to avoid overflow.
926 // Other overflow doesn't matter because we only care about the bottom
927 // W bits of the result.
928 APInt OddFactorial(W, 1);
929 unsigned T = 1;
930 for (unsigned i = 3; i <= K; ++i) {
931 unsigned TwoFactors = countr_zero(i);
932 T += TwoFactors;
933 OddFactorial *= (i >> TwoFactors);
934 }
935
936 // We need at least W + T bits for the multiplication step
937 unsigned CalculationBits = W + T;
938
939 // Calculate 2^T, at width T+W.
940 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
941
942 // Calculate the multiplicative inverse of K! / 2^T;
943 // this multiplication factor will perform the exact division by
944 // K! / 2^T.
945 APInt MultiplyFactor = OddFactorial.multiplicativeInverse();
946
947 // Calculate the product, at width T+W
948 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
949 CalculationBits);
950 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
951 for (unsigned i = 1; i != K; ++i) {
952 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
953 Dividend = SE.getMulExpr(Dividend,
954 SE.getTruncateOrZeroExtend(S, CalculationTy));
955 }
956
957 // Divide by 2^T
958 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
959
960 // Truncate the result, and divide by K! / 2^T.
961
962 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
963 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
964 }
965
966 /// Return the value of this chain of recurrences at the specified iteration
967 /// number. We can evaluate this recurrence by multiplying each element in the
968 /// chain by the binomial coefficient corresponding to it. In other words, we
969 /// can evaluate {A,+,B,+,C,+,D} as:
970 ///
971 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
972 ///
973 /// where BC(It, k) stands for binomial coefficient.
evaluateAtIteration(const SCEV * It,ScalarEvolution & SE) const974 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
975 ScalarEvolution &SE) const {
976 return evaluateAtIteration(operands(), It, SE);
977 }
978
979 const SCEV *
evaluateAtIteration(ArrayRef<const SCEV * > Operands,const SCEV * It,ScalarEvolution & SE)980 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands,
981 const SCEV *It, ScalarEvolution &SE) {
982 assert(Operands.size() > 0);
983 const SCEV *Result = Operands[0];
984 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
985 // The computation is correct in the face of overflow provided that the
986 // multiplication is performed _after_ the evaluation of the binomial
987 // coefficient.
988 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
989 if (isa<SCEVCouldNotCompute>(Coeff))
990 return Coeff;
991
992 Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff));
993 }
994 return Result;
995 }
996
997 //===----------------------------------------------------------------------===//
998 // SCEV Expression folder implementations
999 //===----------------------------------------------------------------------===//
1000
getLosslessPtrToIntExpr(const SCEV * Op,unsigned Depth)1001 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op,
1002 unsigned Depth) {
1003 assert(Depth <= 1 &&
1004 "getLosslessPtrToIntExpr() should self-recurse at most once.");
1005
1006 // We could be called with an integer-typed operands during SCEV rewrites.
1007 // Since the operand is an integer already, just perform zext/trunc/self cast.
1008 if (!Op->getType()->isPointerTy())
1009 return Op;
1010
1011 // What would be an ID for such a SCEV cast expression?
1012 FoldingSetNodeID ID;
1013 ID.AddInteger(scPtrToInt);
1014 ID.AddPointer(Op);
1015
1016 void *IP = nullptr;
1017
1018 // Is there already an expression for such a cast?
1019 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1020 return S;
1021
1022 // It isn't legal for optimizations to construct new ptrtoint expressions
1023 // for non-integral pointers.
1024 if (getDataLayout().isNonIntegralPointerType(Op->getType()))
1025 return getCouldNotCompute();
1026
1027 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1028
1029 // We can only trivially model ptrtoint if SCEV's effective (integer) type
1030 // is sufficiently wide to represent all possible pointer values.
1031 // We could theoretically teach SCEV to truncate wider pointers, but
1032 // that isn't implemented for now.
1033 if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) !=
1034 getDataLayout().getTypeSizeInBits(IntPtrTy))
1035 return getCouldNotCompute();
1036
1037 // If not, is this expression something we can't reduce any further?
1038 if (auto *U = dyn_cast<SCEVUnknown>(Op)) {
1039 // Perform some basic constant folding. If the operand of the ptr2int cast
1040 // is a null pointer, don't create a ptr2int SCEV expression (that will be
1041 // left as-is), but produce a zero constant.
1042 // NOTE: We could handle a more general case, but lack motivational cases.
1043 if (isa<ConstantPointerNull>(U->getValue()))
1044 return getZero(IntPtrTy);
1045
1046 // Create an explicit cast node.
1047 // We can reuse the existing insert position since if we get here,
1048 // we won't have made any changes which would invalidate it.
1049 SCEV *S = new (SCEVAllocator)
1050 SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1051 UniqueSCEVs.InsertNode(S, IP);
1052 registerUser(S, Op);
1053 return S;
1054 }
1055
1056 assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for "
1057 "non-SCEVUnknown's.");
1058
1059 // Otherwise, we've got some expression that is more complex than just a
1060 // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1061 // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1062 // only, and the expressions must otherwise be integer-typed.
1063 // So sink the cast down to the SCEVUnknown's.
1064
1065 /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1066 /// which computes a pointer-typed value, and rewrites the whole expression
1067 /// tree so that *all* the computations are done on integers, and the only
1068 /// pointer-typed operands in the expression are SCEVUnknown.
1069 class SCEVPtrToIntSinkingRewriter
1070 : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1071 using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>;
1072
1073 public:
1074 SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1075
1076 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1077 SCEVPtrToIntSinkingRewriter Rewriter(SE);
1078 return Rewriter.visit(Scev);
1079 }
1080
1081 const SCEV *visit(const SCEV *S) {
1082 Type *STy = S->getType();
1083 // If the expression is not pointer-typed, just keep it as-is.
1084 if (!STy->isPointerTy())
1085 return S;
1086 // Else, recursively sink the cast down into it.
1087 return Base::visit(S);
1088 }
1089
1090 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1091 SmallVector<const SCEV *, 2> Operands;
1092 bool Changed = false;
1093 for (const auto *Op : Expr->operands()) {
1094 Operands.push_back(visit(Op));
1095 Changed |= Op != Operands.back();
1096 }
1097 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1098 }
1099
1100 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1101 SmallVector<const SCEV *, 2> Operands;
1102 bool Changed = false;
1103 for (const auto *Op : Expr->operands()) {
1104 Operands.push_back(visit(Op));
1105 Changed |= Op != Operands.back();
1106 }
1107 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1108 }
1109
1110 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1111 assert(Expr->getType()->isPointerTy() &&
1112 "Should only reach pointer-typed SCEVUnknown's.");
1113 return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1);
1114 }
1115 };
1116
1117 // And actually perform the cast sinking.
1118 const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1119 assert(IntOp->getType()->isIntegerTy() &&
1120 "We must have succeeded in sinking the cast, "
1121 "and ending up with an integer-typed expression!");
1122 return IntOp;
1123 }
1124
getPtrToIntExpr(const SCEV * Op,Type * Ty)1125 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) {
1126 assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1127
1128 const SCEV *IntOp = getLosslessPtrToIntExpr(Op);
1129 if (isa<SCEVCouldNotCompute>(IntOp))
1130 return IntOp;
1131
1132 return getTruncateOrZeroExtend(IntOp, Ty);
1133 }
1134
getTruncateExpr(const SCEV * Op,Type * Ty,unsigned Depth)1135 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1136 unsigned Depth) {
1137 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1138 "This is not a truncating conversion!");
1139 assert(isSCEVable(Ty) &&
1140 "This is not a conversion to a SCEVable type!");
1141 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1142 Ty = getEffectiveSCEVType(Ty);
1143
1144 FoldingSetNodeID ID;
1145 ID.AddInteger(scTruncate);
1146 ID.AddPointer(Op);
1147 ID.AddPointer(Ty);
1148 void *IP = nullptr;
1149 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1150
1151 // Fold if the operand is constant.
1152 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1153 return getConstant(
1154 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1155
1156 // trunc(trunc(x)) --> trunc(x)
1157 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1158 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1159
1160 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1161 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1162 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1163
1164 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1165 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1166 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1167
1168 if (Depth > MaxCastDepth) {
1169 SCEV *S =
1170 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1171 UniqueSCEVs.InsertNode(S, IP);
1172 registerUser(S, Op);
1173 return S;
1174 }
1175
1176 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1177 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1178 // if after transforming we have at most one truncate, not counting truncates
1179 // that replace other casts.
1180 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1181 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1182 SmallVector<const SCEV *, 4> Operands;
1183 unsigned numTruncs = 0;
1184 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1185 ++i) {
1186 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1187 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1188 isa<SCEVTruncateExpr>(S))
1189 numTruncs++;
1190 Operands.push_back(S);
1191 }
1192 if (numTruncs < 2) {
1193 if (isa<SCEVAddExpr>(Op))
1194 return getAddExpr(Operands);
1195 if (isa<SCEVMulExpr>(Op))
1196 return getMulExpr(Operands);
1197 llvm_unreachable("Unexpected SCEV type for Op.");
1198 }
1199 // Although we checked in the beginning that ID is not in the cache, it is
1200 // possible that during recursion and different modification ID was inserted
1201 // into the cache. So if we find it, just return it.
1202 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1203 return S;
1204 }
1205
1206 // If the input value is a chrec scev, truncate the chrec's operands.
1207 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1208 SmallVector<const SCEV *, 4> Operands;
1209 for (const SCEV *Op : AddRec->operands())
1210 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1211 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1212 }
1213
1214 // Return zero if truncating to known zeros.
1215 uint32_t MinTrailingZeros = getMinTrailingZeros(Op);
1216 if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1217 return getZero(Ty);
1218
1219 // The cast wasn't folded; create an explicit cast node. We can reuse
1220 // the existing insert position since if we get here, we won't have
1221 // made any changes which would invalidate it.
1222 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1223 Op, Ty);
1224 UniqueSCEVs.InsertNode(S, IP);
1225 registerUser(S, Op);
1226 return S;
1227 }
1228
1229 // Get the limit of a recurrence such that incrementing by Step cannot cause
1230 // signed overflow as long as the value of the recurrence within the
1231 // loop does not exceed this limit before incrementing.
getSignedOverflowLimitForStep(const SCEV * Step,ICmpInst::Predicate * Pred,ScalarEvolution * SE)1232 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1233 ICmpInst::Predicate *Pred,
1234 ScalarEvolution *SE) {
1235 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1236 if (SE->isKnownPositive(Step)) {
1237 *Pred = ICmpInst::ICMP_SLT;
1238 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1239 SE->getSignedRangeMax(Step));
1240 }
1241 if (SE->isKnownNegative(Step)) {
1242 *Pred = ICmpInst::ICMP_SGT;
1243 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1244 SE->getSignedRangeMin(Step));
1245 }
1246 return nullptr;
1247 }
1248
1249 // Get the limit of a recurrence such that incrementing by Step cannot cause
1250 // unsigned overflow as long as the value of the recurrence within the loop does
1251 // not exceed this limit before incrementing.
getUnsignedOverflowLimitForStep(const SCEV * Step,ICmpInst::Predicate * Pred,ScalarEvolution * SE)1252 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1253 ICmpInst::Predicate *Pred,
1254 ScalarEvolution *SE) {
1255 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1256 *Pred = ICmpInst::ICMP_ULT;
1257
1258 return SE->getConstant(APInt::getMinValue(BitWidth) -
1259 SE->getUnsignedRangeMax(Step));
1260 }
1261
1262 namespace {
1263
1264 struct ExtendOpTraitsBase {
1265 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1266 unsigned);
1267 };
1268
1269 // Used to make code generic over signed and unsigned overflow.
1270 template <typename ExtendOp> struct ExtendOpTraits {
1271 // Members present:
1272 //
1273 // static const SCEV::NoWrapFlags WrapType;
1274 //
1275 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1276 //
1277 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1278 // ICmpInst::Predicate *Pred,
1279 // ScalarEvolution *SE);
1280 };
1281
1282 template <>
1283 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1284 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1285
1286 static const GetExtendExprTy GetExtendExpr;
1287
getOverflowLimitForStep__anon8884d99e0511::ExtendOpTraits1288 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1289 ICmpInst::Predicate *Pred,
1290 ScalarEvolution *SE) {
1291 return getSignedOverflowLimitForStep(Step, Pred, SE);
1292 }
1293 };
1294
1295 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1296 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1297
1298 template <>
1299 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1300 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1301
1302 static const GetExtendExprTy GetExtendExpr;
1303
getOverflowLimitForStep__anon8884d99e0511::ExtendOpTraits1304 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1305 ICmpInst::Predicate *Pred,
1306 ScalarEvolution *SE) {
1307 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1308 }
1309 };
1310
1311 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1312 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1313
1314 } // end anonymous namespace
1315
1316 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1317 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1318 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1319 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1320 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1321 // expression "Step + sext/zext(PreIncAR)" is congruent with
1322 // "sext/zext(PostIncAR)"
1323 template <typename ExtendOpTy>
getPreStartForExtend(const SCEVAddRecExpr * AR,Type * Ty,ScalarEvolution * SE,unsigned Depth)1324 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1325 ScalarEvolution *SE, unsigned Depth) {
1326 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1327 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1328
1329 const Loop *L = AR->getLoop();
1330 const SCEV *Start = AR->getStart();
1331 const SCEV *Step = AR->getStepRecurrence(*SE);
1332
1333 // Check for a simple looking step prior to loop entry.
1334 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1335 if (!SA)
1336 return nullptr;
1337
1338 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1339 // subtraction is expensive. For this purpose, perform a quick and dirty
1340 // difference, by checking for Step in the operand list. Note, that
1341 // SA might have repeated ops, like %a + %a + ..., so only remove one.
1342 SmallVector<const SCEV *, 4> DiffOps(SA->operands());
1343 for (auto It = DiffOps.begin(); It != DiffOps.end(); ++It)
1344 if (*It == Step) {
1345 DiffOps.erase(It);
1346 break;
1347 }
1348
1349 if (DiffOps.size() == SA->getNumOperands())
1350 return nullptr;
1351
1352 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1353 // `Step`:
1354
1355 // 1. NSW/NUW flags on the step increment.
1356 auto PreStartFlags =
1357 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1358 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1359 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1360 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1361
1362 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1363 // "S+X does not sign/unsign-overflow".
1364 //
1365
1366 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1367 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1368 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1369 return PreStart;
1370
1371 // 2. Direct overflow check on the step operation's expression.
1372 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1373 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1374 const SCEV *OperandExtendedStart =
1375 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1376 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1377 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1378 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1379 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1380 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1381 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1382 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1383 }
1384 return PreStart;
1385 }
1386
1387 // 3. Loop precondition.
1388 ICmpInst::Predicate Pred;
1389 const SCEV *OverflowLimit =
1390 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1391
1392 if (OverflowLimit &&
1393 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1394 return PreStart;
1395
1396 return nullptr;
1397 }
1398
1399 // Get the normalized zero or sign extended expression for this AddRec's Start.
1400 template <typename ExtendOpTy>
getExtendAddRecStart(const SCEVAddRecExpr * AR,Type * Ty,ScalarEvolution * SE,unsigned Depth)1401 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1402 ScalarEvolution *SE,
1403 unsigned Depth) {
1404 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1405
1406 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1407 if (!PreStart)
1408 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1409
1410 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1411 Depth),
1412 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1413 }
1414
1415 // Try to prove away overflow by looking at "nearby" add recurrences. A
1416 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1417 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1418 //
1419 // Formally:
1420 //
1421 // {S,+,X} == {S-T,+,X} + T
1422 // => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1423 //
1424 // If ({S-T,+,X} + T) does not overflow ... (1)
1425 //
1426 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1427 //
1428 // If {S-T,+,X} does not overflow ... (2)
1429 //
1430 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1431 // == {Ext(S-T)+Ext(T),+,Ext(X)}
1432 //
1433 // If (S-T)+T does not overflow ... (3)
1434 //
1435 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1436 // == {Ext(S),+,Ext(X)} == LHS
1437 //
1438 // Thus, if (1), (2) and (3) are true for some T, then
1439 // Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1440 //
1441 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1442 // does not overflow" restricted to the 0th iteration. Therefore we only need
1443 // to check for (1) and (2).
1444 //
1445 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1446 // is `Delta` (defined below).
1447 template <typename ExtendOpTy>
proveNoWrapByVaryingStart(const SCEV * Start,const SCEV * Step,const Loop * L)1448 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1449 const SCEV *Step,
1450 const Loop *L) {
1451 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1452
1453 // We restrict `Start` to a constant to prevent SCEV from spending too much
1454 // time here. It is correct (but more expensive) to continue with a
1455 // non-constant `Start` and do a general SCEV subtraction to compute
1456 // `PreStart` below.
1457 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1458 if (!StartC)
1459 return false;
1460
1461 APInt StartAI = StartC->getAPInt();
1462
1463 for (unsigned Delta : {-2, -1, 1, 2}) {
1464 const SCEV *PreStart = getConstant(StartAI - Delta);
1465
1466 FoldingSetNodeID ID;
1467 ID.AddInteger(scAddRecExpr);
1468 ID.AddPointer(PreStart);
1469 ID.AddPointer(Step);
1470 ID.AddPointer(L);
1471 void *IP = nullptr;
1472 const auto *PreAR =
1473 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1474
1475 // Give up if we don't already have the add recurrence we need because
1476 // actually constructing an add recurrence is relatively expensive.
1477 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1478 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1479 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1480 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1481 DeltaS, &Pred, this);
1482 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1483 return true;
1484 }
1485 }
1486
1487 return false;
1488 }
1489
1490 // Finds an integer D for an expression (C + x + y + ...) such that the top
1491 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1492 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1493 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1494 // the (C + x + y + ...) expression is \p WholeAddExpr.
extractConstantWithoutWrapping(ScalarEvolution & SE,const SCEVConstant * ConstantTerm,const SCEVAddExpr * WholeAddExpr)1495 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1496 const SCEVConstant *ConstantTerm,
1497 const SCEVAddExpr *WholeAddExpr) {
1498 const APInt &C = ConstantTerm->getAPInt();
1499 const unsigned BitWidth = C.getBitWidth();
1500 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1501 uint32_t TZ = BitWidth;
1502 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1503 TZ = std::min(TZ, SE.getMinTrailingZeros(WholeAddExpr->getOperand(I)));
1504 if (TZ) {
1505 // Set D to be as many least significant bits of C as possible while still
1506 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1507 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1508 }
1509 return APInt(BitWidth, 0);
1510 }
1511
1512 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1513 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1514 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1515 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
extractConstantWithoutWrapping(ScalarEvolution & SE,const APInt & ConstantStart,const SCEV * Step)1516 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1517 const APInt &ConstantStart,
1518 const SCEV *Step) {
1519 const unsigned BitWidth = ConstantStart.getBitWidth();
1520 const uint32_t TZ = SE.getMinTrailingZeros(Step);
1521 if (TZ)
1522 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1523 : ConstantStart;
1524 return APInt(BitWidth, 0);
1525 }
1526
insertFoldCacheEntry(const ScalarEvolution::FoldID & ID,const SCEV * S,DenseMap<ScalarEvolution::FoldID,const SCEV * > & FoldCache,DenseMap<const SCEV *,SmallVector<ScalarEvolution::FoldID,2>> & FoldCacheUser)1527 static void insertFoldCacheEntry(
1528 const ScalarEvolution::FoldID &ID, const SCEV *S,
1529 DenseMap<ScalarEvolution::FoldID, const SCEV *> &FoldCache,
1530 DenseMap<const SCEV *, SmallVector<ScalarEvolution::FoldID, 2>>
1531 &FoldCacheUser) {
1532 auto I = FoldCache.insert({ID, S});
1533 if (!I.second) {
1534 // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1535 // entry.
1536 auto &UserIDs = FoldCacheUser[I.first->second];
1537 assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
1538 for (unsigned I = 0; I != UserIDs.size(); ++I)
1539 if (UserIDs[I] == ID) {
1540 std::swap(UserIDs[I], UserIDs.back());
1541 break;
1542 }
1543 UserIDs.pop_back();
1544 I.first->second = S;
1545 }
1546 auto R = FoldCacheUser.insert({S, {}});
1547 R.first->second.push_back(ID);
1548 }
1549
1550 const SCEV *
getZeroExtendExpr(const SCEV * Op,Type * Ty,unsigned Depth)1551 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1552 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1553 "This is not an extending conversion!");
1554 assert(isSCEVable(Ty) &&
1555 "This is not a conversion to a SCEVable type!");
1556 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1557 Ty = getEffectiveSCEVType(Ty);
1558
1559 FoldID ID(scZeroExtend, Op, Ty);
1560 auto Iter = FoldCache.find(ID);
1561 if (Iter != FoldCache.end())
1562 return Iter->second;
1563
1564 const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1565 if (!isa<SCEVZeroExtendExpr>(S))
1566 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1567 return S;
1568 }
1569
getZeroExtendExprImpl(const SCEV * Op,Type * Ty,unsigned Depth)1570 const SCEV *ScalarEvolution::getZeroExtendExprImpl(const SCEV *Op, Type *Ty,
1571 unsigned Depth) {
1572 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1573 "This is not an extending conversion!");
1574 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1575 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1576
1577 // Fold if the operand is constant.
1578 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1579 return getConstant(SC->getAPInt().zext(getTypeSizeInBits(Ty)));
1580
1581 // zext(zext(x)) --> zext(x)
1582 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1583 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1584
1585 // Before doing any expensive analysis, check to see if we've already
1586 // computed a SCEV for this Op and Ty.
1587 FoldingSetNodeID ID;
1588 ID.AddInteger(scZeroExtend);
1589 ID.AddPointer(Op);
1590 ID.AddPointer(Ty);
1591 void *IP = nullptr;
1592 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1593 if (Depth > MaxCastDepth) {
1594 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1595 Op, Ty);
1596 UniqueSCEVs.InsertNode(S, IP);
1597 registerUser(S, Op);
1598 return S;
1599 }
1600
1601 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1602 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1603 // It's possible the bits taken off by the truncate were all zero bits. If
1604 // so, we should be able to simplify this further.
1605 const SCEV *X = ST->getOperand();
1606 ConstantRange CR = getUnsignedRange(X);
1607 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1608 unsigned NewBits = getTypeSizeInBits(Ty);
1609 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1610 CR.zextOrTrunc(NewBits)))
1611 return getTruncateOrZeroExtend(X, Ty, Depth);
1612 }
1613
1614 // If the input value is a chrec scev, and we can prove that the value
1615 // did not overflow the old, smaller, value, we can zero extend all of the
1616 // operands (often constants). This allows analysis of something like
1617 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1618 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1619 if (AR->isAffine()) {
1620 const SCEV *Start = AR->getStart();
1621 const SCEV *Step = AR->getStepRecurrence(*this);
1622 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1623 const Loop *L = AR->getLoop();
1624
1625 // If we have special knowledge that this addrec won't overflow,
1626 // we don't need to do any further analysis.
1627 if (AR->hasNoUnsignedWrap()) {
1628 Start =
1629 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1630 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1631 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1632 }
1633
1634 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1635 // Note that this serves two purposes: It filters out loops that are
1636 // simply not analyzable, and it covers the case where this code is
1637 // being called from within backedge-taken count analysis, such that
1638 // attempting to ask for the backedge-taken count would likely result
1639 // in infinite recursion. In the later case, the analysis code will
1640 // cope with a conservative value, and it will take care to purge
1641 // that value once it has finished.
1642 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1643 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1644 // Manually compute the final value for AR, checking for overflow.
1645
1646 // Check whether the backedge-taken count can be losslessly casted to
1647 // the addrec's type. The count is always unsigned.
1648 const SCEV *CastedMaxBECount =
1649 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1650 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1651 CastedMaxBECount, MaxBECount->getType(), Depth);
1652 if (MaxBECount == RecastedMaxBECount) {
1653 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1654 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1655 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1656 SCEV::FlagAnyWrap, Depth + 1);
1657 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1658 SCEV::FlagAnyWrap,
1659 Depth + 1),
1660 WideTy, Depth + 1);
1661 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1662 const SCEV *WideMaxBECount =
1663 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1664 const SCEV *OperandExtendedAdd =
1665 getAddExpr(WideStart,
1666 getMulExpr(WideMaxBECount,
1667 getZeroExtendExpr(Step, WideTy, Depth + 1),
1668 SCEV::FlagAnyWrap, Depth + 1),
1669 SCEV::FlagAnyWrap, Depth + 1);
1670 if (ZAdd == OperandExtendedAdd) {
1671 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1672 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1673 // Return the expression with the addrec on the outside.
1674 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1675 Depth + 1);
1676 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1677 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1678 }
1679 // Similar to above, only this time treat the step value as signed.
1680 // This covers loops that count down.
1681 OperandExtendedAdd =
1682 getAddExpr(WideStart,
1683 getMulExpr(WideMaxBECount,
1684 getSignExtendExpr(Step, WideTy, Depth + 1),
1685 SCEV::FlagAnyWrap, Depth + 1),
1686 SCEV::FlagAnyWrap, Depth + 1);
1687 if (ZAdd == OperandExtendedAdd) {
1688 // Cache knowledge of AR NW, which is propagated to this AddRec.
1689 // Negative step causes unsigned wrap, but it still can't self-wrap.
1690 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1691 // Return the expression with the addrec on the outside.
1692 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1693 Depth + 1);
1694 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1695 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1696 }
1697 }
1698 }
1699
1700 // Normally, in the cases we can prove no-overflow via a
1701 // backedge guarding condition, we can also compute a backedge
1702 // taken count for the loop. The exceptions are assumptions and
1703 // guards present in the loop -- SCEV is not great at exploiting
1704 // these to compute max backedge taken counts, but can still use
1705 // these to prove lack of overflow. Use this fact to avoid
1706 // doing extra work that may not pay off.
1707 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1708 !AC.assumptions().empty()) {
1709
1710 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1711 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1712 if (AR->hasNoUnsignedWrap()) {
1713 // Same as nuw case above - duplicated here to avoid a compile time
1714 // issue. It's not clear that the order of checks does matter, but
1715 // it's one of two issue possible causes for a change which was
1716 // reverted. Be conservative for the moment.
1717 Start =
1718 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1719 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1720 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1721 }
1722
1723 // For a negative step, we can extend the operands iff doing so only
1724 // traverses values in the range zext([0,UINT_MAX]).
1725 if (isKnownNegative(Step)) {
1726 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1727 getSignedRangeMin(Step));
1728 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1729 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1730 // Cache knowledge of AR NW, which is propagated to this
1731 // AddRec. Negative step causes unsigned wrap, but it
1732 // still can't self-wrap.
1733 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1734 // Return the expression with the addrec on the outside.
1735 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1736 Depth + 1);
1737 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1738 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1739 }
1740 }
1741 }
1742
1743 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1744 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1745 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1746 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1747 const APInt &C = SC->getAPInt();
1748 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1749 if (D != 0) {
1750 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1751 const SCEV *SResidual =
1752 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1753 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1754 return getAddExpr(SZExtD, SZExtR,
1755 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1756 Depth + 1);
1757 }
1758 }
1759
1760 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1761 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1762 Start =
1763 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1764 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1765 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1766 }
1767 }
1768
1769 // zext(A % B) --> zext(A) % zext(B)
1770 {
1771 const SCEV *LHS;
1772 const SCEV *RHS;
1773 if (matchURem(Op, LHS, RHS))
1774 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1775 getZeroExtendExpr(RHS, Ty, Depth + 1));
1776 }
1777
1778 // zext(A / B) --> zext(A) / zext(B).
1779 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1780 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1781 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1782
1783 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1784 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1785 if (SA->hasNoUnsignedWrap()) {
1786 // If the addition does not unsign overflow then we can, by definition,
1787 // commute the zero extension with the addition operation.
1788 SmallVector<const SCEV *, 4> Ops;
1789 for (const auto *Op : SA->operands())
1790 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1791 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1792 }
1793
1794 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1795 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1796 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1797 //
1798 // Often address arithmetics contain expressions like
1799 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1800 // This transformation is useful while proving that such expressions are
1801 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1802 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1803 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1804 if (D != 0) {
1805 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1806 const SCEV *SResidual =
1807 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1808 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1809 return getAddExpr(SZExtD, SZExtR,
1810 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1811 Depth + 1);
1812 }
1813 }
1814 }
1815
1816 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1817 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1818 if (SM->hasNoUnsignedWrap()) {
1819 // If the multiply does not unsign overflow then we can, by definition,
1820 // commute the zero extension with the multiply operation.
1821 SmallVector<const SCEV *, 4> Ops;
1822 for (const auto *Op : SM->operands())
1823 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1824 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1825 }
1826
1827 // zext(2^K * (trunc X to iN)) to iM ->
1828 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1829 //
1830 // Proof:
1831 //
1832 // zext(2^K * (trunc X to iN)) to iM
1833 // = zext((trunc X to iN) << K) to iM
1834 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1835 // (because shl removes the top K bits)
1836 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1837 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1838 //
1839 if (SM->getNumOperands() == 2)
1840 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1841 if (MulLHS->getAPInt().isPowerOf2())
1842 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1843 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1844 MulLHS->getAPInt().logBase2();
1845 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1846 return getMulExpr(
1847 getZeroExtendExpr(MulLHS, Ty),
1848 getZeroExtendExpr(
1849 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1850 SCEV::FlagNUW, Depth + 1);
1851 }
1852 }
1853
1854 // zext(umin(x, y)) -> umin(zext(x), zext(y))
1855 // zext(umax(x, y)) -> umax(zext(x), zext(y))
1856 if (isa<SCEVUMinExpr>(Op) || isa<SCEVUMaxExpr>(Op)) {
1857 auto *MinMax = cast<SCEVMinMaxExpr>(Op);
1858 SmallVector<const SCEV *, 4> Operands;
1859 for (auto *Operand : MinMax->operands())
1860 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1861 if (isa<SCEVUMinExpr>(MinMax))
1862 return getUMinExpr(Operands);
1863 return getUMaxExpr(Operands);
1864 }
1865
1866 // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
1867 if (auto *MinMax = dyn_cast<SCEVSequentialMinMaxExpr>(Op)) {
1868 assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!");
1869 SmallVector<const SCEV *, 4> Operands;
1870 for (auto *Operand : MinMax->operands())
1871 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1872 return getUMinExpr(Operands, /*Sequential*/ true);
1873 }
1874
1875 // The cast wasn't folded; create an explicit cast node.
1876 // Recompute the insert position, as it may have been invalidated.
1877 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1878 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1879 Op, Ty);
1880 UniqueSCEVs.InsertNode(S, IP);
1881 registerUser(S, Op);
1882 return S;
1883 }
1884
1885 const SCEV *
getSignExtendExpr(const SCEV * Op,Type * Ty,unsigned Depth)1886 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1887 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1888 "This is not an extending conversion!");
1889 assert(isSCEVable(Ty) &&
1890 "This is not a conversion to a SCEVable type!");
1891 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1892 Ty = getEffectiveSCEVType(Ty);
1893
1894 FoldID ID(scSignExtend, Op, Ty);
1895 auto Iter = FoldCache.find(ID);
1896 if (Iter != FoldCache.end())
1897 return Iter->second;
1898
1899 const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
1900 if (!isa<SCEVSignExtendExpr>(S))
1901 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1902 return S;
1903 }
1904
getSignExtendExprImpl(const SCEV * Op,Type * Ty,unsigned Depth)1905 const SCEV *ScalarEvolution::getSignExtendExprImpl(const SCEV *Op, Type *Ty,
1906 unsigned Depth) {
1907 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1908 "This is not an extending conversion!");
1909 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1910 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1911 Ty = getEffectiveSCEVType(Ty);
1912
1913 // Fold if the operand is constant.
1914 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1915 return getConstant(SC->getAPInt().sext(getTypeSizeInBits(Ty)));
1916
1917 // sext(sext(x)) --> sext(x)
1918 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1919 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1920
1921 // sext(zext(x)) --> zext(x)
1922 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1923 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1924
1925 // Before doing any expensive analysis, check to see if we've already
1926 // computed a SCEV for this Op and Ty.
1927 FoldingSetNodeID ID;
1928 ID.AddInteger(scSignExtend);
1929 ID.AddPointer(Op);
1930 ID.AddPointer(Ty);
1931 void *IP = nullptr;
1932 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1933 // Limit recursion depth.
1934 if (Depth > MaxCastDepth) {
1935 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1936 Op, Ty);
1937 UniqueSCEVs.InsertNode(S, IP);
1938 registerUser(S, Op);
1939 return S;
1940 }
1941
1942 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1943 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1944 // It's possible the bits taken off by the truncate were all sign bits. If
1945 // so, we should be able to simplify this further.
1946 const SCEV *X = ST->getOperand();
1947 ConstantRange CR = getSignedRange(X);
1948 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1949 unsigned NewBits = getTypeSizeInBits(Ty);
1950 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1951 CR.sextOrTrunc(NewBits)))
1952 return getTruncateOrSignExtend(X, Ty, Depth);
1953 }
1954
1955 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1956 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1957 if (SA->hasNoSignedWrap()) {
1958 // If the addition does not sign overflow then we can, by definition,
1959 // commute the sign extension with the addition operation.
1960 SmallVector<const SCEV *, 4> Ops;
1961 for (const auto *Op : SA->operands())
1962 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1963 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1964 }
1965
1966 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1967 // if D + (C - D + x + y + ...) could be proven to not signed wrap
1968 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1969 //
1970 // For instance, this will bring two seemingly different expressions:
1971 // 1 + sext(5 + 20 * %x + 24 * %y) and
1972 // sext(6 + 20 * %x + 24 * %y)
1973 // to the same form:
1974 // 2 + sext(4 + 20 * %x + 24 * %y)
1975 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1976 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1977 if (D != 0) {
1978 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1979 const SCEV *SResidual =
1980 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1981 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1982 return getAddExpr(SSExtD, SSExtR,
1983 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1984 Depth + 1);
1985 }
1986 }
1987 }
1988 // If the input value is a chrec scev, and we can prove that the value
1989 // did not overflow the old, smaller, value, we can sign extend all of the
1990 // operands (often constants). This allows analysis of something like
1991 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1992 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1993 if (AR->isAffine()) {
1994 const SCEV *Start = AR->getStart();
1995 const SCEV *Step = AR->getStepRecurrence(*this);
1996 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1997 const Loop *L = AR->getLoop();
1998
1999 // If we have special knowledge that this addrec won't overflow,
2000 // we don't need to do any further analysis.
2001 if (AR->hasNoSignedWrap()) {
2002 Start =
2003 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2004 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2005 return getAddRecExpr(Start, Step, L, SCEV::FlagNSW);
2006 }
2007
2008 // Check whether the backedge-taken count is SCEVCouldNotCompute.
2009 // Note that this serves two purposes: It filters out loops that are
2010 // simply not analyzable, and it covers the case where this code is
2011 // being called from within backedge-taken count analysis, such that
2012 // attempting to ask for the backedge-taken count would likely result
2013 // in infinite recursion. In the later case, the analysis code will
2014 // cope with a conservative value, and it will take care to purge
2015 // that value once it has finished.
2016 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2017 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2018 // Manually compute the final value for AR, checking for
2019 // overflow.
2020
2021 // Check whether the backedge-taken count can be losslessly casted to
2022 // the addrec's type. The count is always unsigned.
2023 const SCEV *CastedMaxBECount =
2024 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2025 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2026 CastedMaxBECount, MaxBECount->getType(), Depth);
2027 if (MaxBECount == RecastedMaxBECount) {
2028 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2029 // Check whether Start+Step*MaxBECount has no signed overflow.
2030 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2031 SCEV::FlagAnyWrap, Depth + 1);
2032 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2033 SCEV::FlagAnyWrap,
2034 Depth + 1),
2035 WideTy, Depth + 1);
2036 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2037 const SCEV *WideMaxBECount =
2038 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2039 const SCEV *OperandExtendedAdd =
2040 getAddExpr(WideStart,
2041 getMulExpr(WideMaxBECount,
2042 getSignExtendExpr(Step, WideTy, Depth + 1),
2043 SCEV::FlagAnyWrap, Depth + 1),
2044 SCEV::FlagAnyWrap, Depth + 1);
2045 if (SAdd == OperandExtendedAdd) {
2046 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2047 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2048 // Return the expression with the addrec on the outside.
2049 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2050 Depth + 1);
2051 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2052 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2053 }
2054 // Similar to above, only this time treat the step value as unsigned.
2055 // This covers loops that count up with an unsigned step.
2056 OperandExtendedAdd =
2057 getAddExpr(WideStart,
2058 getMulExpr(WideMaxBECount,
2059 getZeroExtendExpr(Step, WideTy, Depth + 1),
2060 SCEV::FlagAnyWrap, Depth + 1),
2061 SCEV::FlagAnyWrap, Depth + 1);
2062 if (SAdd == OperandExtendedAdd) {
2063 // If AR wraps around then
2064 //
2065 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2066 // => SAdd != OperandExtendedAdd
2067 //
2068 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2069 // (SAdd == OperandExtendedAdd => AR is NW)
2070
2071 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2072
2073 // Return the expression with the addrec on the outside.
2074 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2075 Depth + 1);
2076 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
2077 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2078 }
2079 }
2080 }
2081
2082 auto NewFlags = proveNoSignedWrapViaInduction(AR);
2083 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2084 if (AR->hasNoSignedWrap()) {
2085 // Same as nsw case above - duplicated here to avoid a compile time
2086 // issue. It's not clear that the order of checks does matter, but
2087 // it's one of two issue possible causes for a change which was
2088 // reverted. Be conservative for the moment.
2089 Start =
2090 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2091 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2092 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2093 }
2094
2095 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2096 // if D + (C - D + Step * n) could be proven to not signed wrap
2097 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2098 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2099 const APInt &C = SC->getAPInt();
2100 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2101 if (D != 0) {
2102 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2103 const SCEV *SResidual =
2104 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2105 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2106 return getAddExpr(SSExtD, SSExtR,
2107 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2108 Depth + 1);
2109 }
2110 }
2111
2112 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2113 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2114 Start =
2115 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2116 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2117 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2118 }
2119 }
2120
2121 // If the input value is provably positive and we could not simplify
2122 // away the sext build a zext instead.
2123 if (isKnownNonNegative(Op))
2124 return getZeroExtendExpr(Op, Ty, Depth + 1);
2125
2126 // sext(smin(x, y)) -> smin(sext(x), sext(y))
2127 // sext(smax(x, y)) -> smax(sext(x), sext(y))
2128 if (isa<SCEVSMinExpr>(Op) || isa<SCEVSMaxExpr>(Op)) {
2129 auto *MinMax = cast<SCEVMinMaxExpr>(Op);
2130 SmallVector<const SCEV *, 4> Operands;
2131 for (auto *Operand : MinMax->operands())
2132 Operands.push_back(getSignExtendExpr(Operand, Ty));
2133 if (isa<SCEVSMinExpr>(MinMax))
2134 return getSMinExpr(Operands);
2135 return getSMaxExpr(Operands);
2136 }
2137
2138 // The cast wasn't folded; create an explicit cast node.
2139 // Recompute the insert position, as it may have been invalidated.
2140 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2141 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2142 Op, Ty);
2143 UniqueSCEVs.InsertNode(S, IP);
2144 registerUser(S, { Op });
2145 return S;
2146 }
2147
getCastExpr(SCEVTypes Kind,const SCEV * Op,Type * Ty)2148 const SCEV *ScalarEvolution::getCastExpr(SCEVTypes Kind, const SCEV *Op,
2149 Type *Ty) {
2150 switch (Kind) {
2151 case scTruncate:
2152 return getTruncateExpr(Op, Ty);
2153 case scZeroExtend:
2154 return getZeroExtendExpr(Op, Ty);
2155 case scSignExtend:
2156 return getSignExtendExpr(Op, Ty);
2157 case scPtrToInt:
2158 return getPtrToIntExpr(Op, Ty);
2159 default:
2160 llvm_unreachable("Not a SCEV cast expression!");
2161 }
2162 }
2163
2164 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2165 /// unspecified bits out to the given type.
getAnyExtendExpr(const SCEV * Op,Type * Ty)2166 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2167 Type *Ty) {
2168 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2169 "This is not an extending conversion!");
2170 assert(isSCEVable(Ty) &&
2171 "This is not a conversion to a SCEVable type!");
2172 Ty = getEffectiveSCEVType(Ty);
2173
2174 // Sign-extend negative constants.
2175 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2176 if (SC->getAPInt().isNegative())
2177 return getSignExtendExpr(Op, Ty);
2178
2179 // Peel off a truncate cast.
2180 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2181 const SCEV *NewOp = T->getOperand();
2182 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2183 return getAnyExtendExpr(NewOp, Ty);
2184 return getTruncateOrNoop(NewOp, Ty);
2185 }
2186
2187 // Next try a zext cast. If the cast is folded, use it.
2188 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2189 if (!isa<SCEVZeroExtendExpr>(ZExt))
2190 return ZExt;
2191
2192 // Next try a sext cast. If the cast is folded, use it.
2193 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2194 if (!isa<SCEVSignExtendExpr>(SExt))
2195 return SExt;
2196
2197 // Force the cast to be folded into the operands of an addrec.
2198 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2199 SmallVector<const SCEV *, 4> Ops;
2200 for (const SCEV *Op : AR->operands())
2201 Ops.push_back(getAnyExtendExpr(Op, Ty));
2202 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2203 }
2204
2205 // If the expression is obviously signed, use the sext cast value.
2206 if (isa<SCEVSMaxExpr>(Op))
2207 return SExt;
2208
2209 // Absent any other information, use the zext cast value.
2210 return ZExt;
2211 }
2212
2213 /// Process the given Ops list, which is a list of operands to be added under
2214 /// the given scale, update the given map. This is a helper function for
2215 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2216 /// that would form an add expression like this:
2217 ///
2218 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2219 ///
2220 /// where A and B are constants, update the map with these values:
2221 ///
2222 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2223 ///
2224 /// and add 13 + A*B*29 to AccumulatedConstant.
2225 /// This will allow getAddRecExpr to produce this:
2226 ///
2227 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2228 ///
2229 /// This form often exposes folding opportunities that are hidden in
2230 /// the original operand list.
2231 ///
2232 /// Return true iff it appears that any interesting folding opportunities
2233 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2234 /// the common case where no interesting opportunities are present, and
2235 /// is also used as a check to avoid infinite recursion.
2236 static bool
CollectAddOperandsWithScales(DenseMap<const SCEV *,APInt> & M,SmallVectorImpl<const SCEV * > & NewOps,APInt & AccumulatedConstant,ArrayRef<const SCEV * > Ops,const APInt & Scale,ScalarEvolution & SE)2237 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2238 SmallVectorImpl<const SCEV *> &NewOps,
2239 APInt &AccumulatedConstant,
2240 ArrayRef<const SCEV *> Ops, const APInt &Scale,
2241 ScalarEvolution &SE) {
2242 bool Interesting = false;
2243
2244 // Iterate over the add operands. They are sorted, with constants first.
2245 unsigned i = 0;
2246 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2247 ++i;
2248 // Pull a buried constant out to the outside.
2249 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2250 Interesting = true;
2251 AccumulatedConstant += Scale * C->getAPInt();
2252 }
2253
2254 // Next comes everything else. We're especially interested in multiplies
2255 // here, but they're in the middle, so just visit the rest with one loop.
2256 for (; i != Ops.size(); ++i) {
2257 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2258 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2259 APInt NewScale =
2260 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2261 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2262 // A multiplication of a constant with another add; recurse.
2263 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2264 Interesting |=
2265 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2266 Add->operands(), NewScale, SE);
2267 } else {
2268 // A multiplication of a constant with some other value. Update
2269 // the map.
2270 SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands()));
2271 const SCEV *Key = SE.getMulExpr(MulOps);
2272 auto Pair = M.insert({Key, NewScale});
2273 if (Pair.second) {
2274 NewOps.push_back(Pair.first->first);
2275 } else {
2276 Pair.first->second += NewScale;
2277 // The map already had an entry for this value, which may indicate
2278 // a folding opportunity.
2279 Interesting = true;
2280 }
2281 }
2282 } else {
2283 // An ordinary operand. Update the map.
2284 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2285 M.insert({Ops[i], Scale});
2286 if (Pair.second) {
2287 NewOps.push_back(Pair.first->first);
2288 } else {
2289 Pair.first->second += Scale;
2290 // The map already had an entry for this value, which may indicate
2291 // a folding opportunity.
2292 Interesting = true;
2293 }
2294 }
2295 }
2296
2297 return Interesting;
2298 }
2299
willNotOverflow(Instruction::BinaryOps BinOp,bool Signed,const SCEV * LHS,const SCEV * RHS,const Instruction * CtxI)2300 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed,
2301 const SCEV *LHS, const SCEV *RHS,
2302 const Instruction *CtxI) {
2303 const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *,
2304 SCEV::NoWrapFlags, unsigned);
2305 switch (BinOp) {
2306 default:
2307 llvm_unreachable("Unsupported binary op");
2308 case Instruction::Add:
2309 Operation = &ScalarEvolution::getAddExpr;
2310 break;
2311 case Instruction::Sub:
2312 Operation = &ScalarEvolution::getMinusSCEV;
2313 break;
2314 case Instruction::Mul:
2315 Operation = &ScalarEvolution::getMulExpr;
2316 break;
2317 }
2318
2319 const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
2320 Signed ? &ScalarEvolution::getSignExtendExpr
2321 : &ScalarEvolution::getZeroExtendExpr;
2322
2323 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2324 auto *NarrowTy = cast<IntegerType>(LHS->getType());
2325 auto *WideTy =
2326 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2327
2328 const SCEV *A = (this->*Extension)(
2329 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2330 const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2331 const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2332 const SCEV *B = (this->*Operation)(LHSB, RHSB, SCEV::FlagAnyWrap, 0);
2333 if (A == B)
2334 return true;
2335 // Can we use context to prove the fact we need?
2336 if (!CtxI)
2337 return false;
2338 // TODO: Support mul.
2339 if (BinOp == Instruction::Mul)
2340 return false;
2341 auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2342 // TODO: Lift this limitation.
2343 if (!RHSC)
2344 return false;
2345 APInt C = RHSC->getAPInt();
2346 unsigned NumBits = C.getBitWidth();
2347 bool IsSub = (BinOp == Instruction::Sub);
2348 bool IsNegativeConst = (Signed && C.isNegative());
2349 // Compute the direction and magnitude by which we need to check overflow.
2350 bool OverflowDown = IsSub ^ IsNegativeConst;
2351 APInt Magnitude = C;
2352 if (IsNegativeConst) {
2353 if (C == APInt::getSignedMinValue(NumBits))
2354 // TODO: SINT_MIN on inversion gives the same negative value, we don't
2355 // want to deal with that.
2356 return false;
2357 Magnitude = -C;
2358 }
2359
2360 ICmpInst::Predicate Pred = Signed ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
2361 if (OverflowDown) {
2362 // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2363 APInt Min = Signed ? APInt::getSignedMinValue(NumBits)
2364 : APInt::getMinValue(NumBits);
2365 APInt Limit = Min + Magnitude;
2366 return isKnownPredicateAt(Pred, getConstant(Limit), LHS, CtxI);
2367 } else {
2368 // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2369 APInt Max = Signed ? APInt::getSignedMaxValue(NumBits)
2370 : APInt::getMaxValue(NumBits);
2371 APInt Limit = Max - Magnitude;
2372 return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2373 }
2374 }
2375
2376 std::optional<SCEV::NoWrapFlags>
getStrengthenedNoWrapFlagsFromBinOp(const OverflowingBinaryOperator * OBO)2377 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp(
2378 const OverflowingBinaryOperator *OBO) {
2379 // It cannot be done any better.
2380 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2381 return std::nullopt;
2382
2383 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2384
2385 if (OBO->hasNoUnsignedWrap())
2386 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2387 if (OBO->hasNoSignedWrap())
2388 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2389
2390 bool Deduced = false;
2391
2392 if (OBO->getOpcode() != Instruction::Add &&
2393 OBO->getOpcode() != Instruction::Sub &&
2394 OBO->getOpcode() != Instruction::Mul)
2395 return std::nullopt;
2396
2397 const SCEV *LHS = getSCEV(OBO->getOperand(0));
2398 const SCEV *RHS = getSCEV(OBO->getOperand(1));
2399
2400 const Instruction *CtxI =
2401 UseContextForNoWrapFlagInference ? dyn_cast<Instruction>(OBO) : nullptr;
2402 if (!OBO->hasNoUnsignedWrap() &&
2403 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2404 /* Signed */ false, LHS, RHS, CtxI)) {
2405 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2406 Deduced = true;
2407 }
2408
2409 if (!OBO->hasNoSignedWrap() &&
2410 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2411 /* Signed */ true, LHS, RHS, CtxI)) {
2412 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2413 Deduced = true;
2414 }
2415
2416 if (Deduced)
2417 return Flags;
2418 return std::nullopt;
2419 }
2420
2421 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2422 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2423 // can't-overflow flags for the operation if possible.
2424 static SCEV::NoWrapFlags
StrengthenNoWrapFlags(ScalarEvolution * SE,SCEVTypes Type,const ArrayRef<const SCEV * > Ops,SCEV::NoWrapFlags Flags)2425 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2426 const ArrayRef<const SCEV *> Ops,
2427 SCEV::NoWrapFlags Flags) {
2428 using namespace std::placeholders;
2429
2430 using OBO = OverflowingBinaryOperator;
2431
2432 bool CanAnalyze =
2433 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2434 (void)CanAnalyze;
2435 assert(CanAnalyze && "don't call from other places!");
2436
2437 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2438 SCEV::NoWrapFlags SignOrUnsignWrap =
2439 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2440
2441 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2442 auto IsKnownNonNegative = [&](const SCEV *S) {
2443 return SE->isKnownNonNegative(S);
2444 };
2445
2446 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2447 Flags =
2448 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2449
2450 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2451
2452 if (SignOrUnsignWrap != SignOrUnsignMask &&
2453 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2454 isa<SCEVConstant>(Ops[0])) {
2455
2456 auto Opcode = [&] {
2457 switch (Type) {
2458 case scAddExpr:
2459 return Instruction::Add;
2460 case scMulExpr:
2461 return Instruction::Mul;
2462 default:
2463 llvm_unreachable("Unexpected SCEV op.");
2464 }
2465 }();
2466
2467 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2468
2469 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2470 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2471 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2472 Opcode, C, OBO::NoSignedWrap);
2473 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2474 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2475 }
2476
2477 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2478 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2479 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2480 Opcode, C, OBO::NoUnsignedWrap);
2481 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2482 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2483 }
2484 }
2485
2486 // <0,+,nonnegative><nw> is also nuw
2487 // TODO: Add corresponding nsw case
2488 if (Type == scAddRecExpr && ScalarEvolution::hasFlags(Flags, SCEV::FlagNW) &&
2489 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2490 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2491 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2492
2493 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2494 if (Type == scMulExpr && !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) &&
2495 Ops.size() == 2) {
2496 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2497 if (UDiv->getOperand(1) == Ops[1])
2498 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2499 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2500 if (UDiv->getOperand(1) == Ops[0])
2501 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2502 }
2503
2504 return Flags;
2505 }
2506
isAvailableAtLoopEntry(const SCEV * S,const Loop * L)2507 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2508 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2509 }
2510
2511 /// Get a canonical add expression, or something simpler if possible.
getAddExpr(SmallVectorImpl<const SCEV * > & Ops,SCEV::NoWrapFlags OrigFlags,unsigned Depth)2512 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2513 SCEV::NoWrapFlags OrigFlags,
2514 unsigned Depth) {
2515 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2516 "only nuw or nsw allowed");
2517 assert(!Ops.empty() && "Cannot get empty add!");
2518 if (Ops.size() == 1) return Ops[0];
2519 #ifndef NDEBUG
2520 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2521 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2522 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2523 "SCEVAddExpr operand types don't match!");
2524 unsigned NumPtrs = count_if(
2525 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2526 assert(NumPtrs <= 1 && "add has at most one pointer operand");
2527 #endif
2528
2529 // Sort by complexity, this groups all similar expression types together.
2530 GroupByComplexity(Ops, &LI, DT);
2531
2532 // If there are any constants, fold them together.
2533 unsigned Idx = 0;
2534 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2535 ++Idx;
2536 assert(Idx < Ops.size());
2537 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2538 // We found two constants, fold them together!
2539 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2540 if (Ops.size() == 2) return Ops[0];
2541 Ops.erase(Ops.begin()+1); // Erase the folded element
2542 LHSC = cast<SCEVConstant>(Ops[0]);
2543 }
2544
2545 // If we are left with a constant zero being added, strip it off.
2546 if (LHSC->getValue()->isZero()) {
2547 Ops.erase(Ops.begin());
2548 --Idx;
2549 }
2550
2551 if (Ops.size() == 1) return Ops[0];
2552 }
2553
2554 // Delay expensive flag strengthening until necessary.
2555 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2556 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2557 };
2558
2559 // Limit recursion calls depth.
2560 if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2561 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2562
2563 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2564 // Don't strengthen flags if we have no new information.
2565 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2566 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2567 Add->setNoWrapFlags(ComputeFlags(Ops));
2568 return S;
2569 }
2570
2571 // Okay, check to see if the same value occurs in the operand list more than
2572 // once. If so, merge them together into an multiply expression. Since we
2573 // sorted the list, these values are required to be adjacent.
2574 Type *Ty = Ops[0]->getType();
2575 bool FoundMatch = false;
2576 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2577 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2578 // Scan ahead to count how many equal operands there are.
2579 unsigned Count = 2;
2580 while (i+Count != e && Ops[i+Count] == Ops[i])
2581 ++Count;
2582 // Merge the values into a multiply.
2583 const SCEV *Scale = getConstant(Ty, Count);
2584 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2585 if (Ops.size() == Count)
2586 return Mul;
2587 Ops[i] = Mul;
2588 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2589 --i; e -= Count - 1;
2590 FoundMatch = true;
2591 }
2592 if (FoundMatch)
2593 return getAddExpr(Ops, OrigFlags, Depth + 1);
2594
2595 // Check for truncates. If all the operands are truncated from the same
2596 // type, see if factoring out the truncate would permit the result to be
2597 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2598 // if the contents of the resulting outer trunc fold to something simple.
2599 auto FindTruncSrcType = [&]() -> Type * {
2600 // We're ultimately looking to fold an addrec of truncs and muls of only
2601 // constants and truncs, so if we find any other types of SCEV
2602 // as operands of the addrec then we bail and return nullptr here.
2603 // Otherwise, we return the type of the operand of a trunc that we find.
2604 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2605 return T->getOperand()->getType();
2606 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2607 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2608 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2609 return T->getOperand()->getType();
2610 }
2611 return nullptr;
2612 };
2613 if (auto *SrcType = FindTruncSrcType()) {
2614 SmallVector<const SCEV *, 8> LargeOps;
2615 bool Ok = true;
2616 // Check all the operands to see if they can be represented in the
2617 // source type of the truncate.
2618 for (const SCEV *Op : Ops) {
2619 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2620 if (T->getOperand()->getType() != SrcType) {
2621 Ok = false;
2622 break;
2623 }
2624 LargeOps.push_back(T->getOperand());
2625 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Op)) {
2626 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2627 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Op)) {
2628 SmallVector<const SCEV *, 8> LargeMulOps;
2629 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2630 if (const SCEVTruncateExpr *T =
2631 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2632 if (T->getOperand()->getType() != SrcType) {
2633 Ok = false;
2634 break;
2635 }
2636 LargeMulOps.push_back(T->getOperand());
2637 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2638 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2639 } else {
2640 Ok = false;
2641 break;
2642 }
2643 }
2644 if (Ok)
2645 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2646 } else {
2647 Ok = false;
2648 break;
2649 }
2650 }
2651 if (Ok) {
2652 // Evaluate the expression in the larger type.
2653 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2654 // If it folds to something simple, use it. Otherwise, don't.
2655 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2656 return getTruncateExpr(Fold, Ty);
2657 }
2658 }
2659
2660 if (Ops.size() == 2) {
2661 // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2662 // C2 can be folded in a way that allows retaining wrapping flags of (X +
2663 // C1).
2664 const SCEV *A = Ops[0];
2665 const SCEV *B = Ops[1];
2666 auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2667 auto *C = dyn_cast<SCEVConstant>(A);
2668 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2669 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2670 auto C2 = C->getAPInt();
2671 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2672
2673 APInt ConstAdd = C1 + C2;
2674 auto AddFlags = AddExpr->getNoWrapFlags();
2675 // Adding a smaller constant is NUW if the original AddExpr was NUW.
2676 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNUW) &&
2677 ConstAdd.ule(C1)) {
2678 PreservedFlags =
2679 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW);
2680 }
2681
2682 // Adding a constant with the same sign and small magnitude is NSW, if the
2683 // original AddExpr was NSW.
2684 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNSW) &&
2685 C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2686 ConstAdd.abs().ule(C1.abs())) {
2687 PreservedFlags =
2688 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW);
2689 }
2690
2691 if (PreservedFlags != SCEV::FlagAnyWrap) {
2692 SmallVector<const SCEV *, 4> NewOps(AddExpr->operands());
2693 NewOps[0] = getConstant(ConstAdd);
2694 return getAddExpr(NewOps, PreservedFlags);
2695 }
2696 }
2697 }
2698
2699 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2700 if (Ops.size() == 2) {
2701 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[0]);
2702 if (Mul && Mul->getNumOperands() == 2 &&
2703 Mul->getOperand(0)->isAllOnesValue()) {
2704 const SCEV *X;
2705 const SCEV *Y;
2706 if (matchURem(Mul->getOperand(1), X, Y) && X == Ops[1]) {
2707 return getMulExpr(Y, getUDivExpr(X, Y));
2708 }
2709 }
2710 }
2711
2712 // Skip past any other cast SCEVs.
2713 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2714 ++Idx;
2715
2716 // If there are add operands they would be next.
2717 if (Idx < Ops.size()) {
2718 bool DeletedAdd = false;
2719 // If the original flags and all inlined SCEVAddExprs are NUW, use the
2720 // common NUW flag for expression after inlining. Other flags cannot be
2721 // preserved, because they may depend on the original order of operations.
2722 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2723 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2724 if (Ops.size() > AddOpsInlineThreshold ||
2725 Add->getNumOperands() > AddOpsInlineThreshold)
2726 break;
2727 // If we have an add, expand the add operands onto the end of the operands
2728 // list.
2729 Ops.erase(Ops.begin()+Idx);
2730 append_range(Ops, Add->operands());
2731 DeletedAdd = true;
2732 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2733 }
2734
2735 // If we deleted at least one add, we added operands to the end of the list,
2736 // and they are not necessarily sorted. Recurse to resort and resimplify
2737 // any operands we just acquired.
2738 if (DeletedAdd)
2739 return getAddExpr(Ops, CommonFlags, Depth + 1);
2740 }
2741
2742 // Skip over the add expression until we get to a multiply.
2743 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2744 ++Idx;
2745
2746 // Check to see if there are any folding opportunities present with
2747 // operands multiplied by constant values.
2748 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2749 uint64_t BitWidth = getTypeSizeInBits(Ty);
2750 DenseMap<const SCEV *, APInt> M;
2751 SmallVector<const SCEV *, 8> NewOps;
2752 APInt AccumulatedConstant(BitWidth, 0);
2753 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2754 Ops, APInt(BitWidth, 1), *this)) {
2755 struct APIntCompare {
2756 bool operator()(const APInt &LHS, const APInt &RHS) const {
2757 return LHS.ult(RHS);
2758 }
2759 };
2760
2761 // Some interesting folding opportunity is present, so its worthwhile to
2762 // re-generate the operands list. Group the operands by constant scale,
2763 // to avoid multiplying by the same constant scale multiple times.
2764 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2765 for (const SCEV *NewOp : NewOps)
2766 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2767 // Re-generate the operands list.
2768 Ops.clear();
2769 if (AccumulatedConstant != 0)
2770 Ops.push_back(getConstant(AccumulatedConstant));
2771 for (auto &MulOp : MulOpLists) {
2772 if (MulOp.first == 1) {
2773 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2774 } else if (MulOp.first != 0) {
2775 Ops.push_back(getMulExpr(
2776 getConstant(MulOp.first),
2777 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2778 SCEV::FlagAnyWrap, Depth + 1));
2779 }
2780 }
2781 if (Ops.empty())
2782 return getZero(Ty);
2783 if (Ops.size() == 1)
2784 return Ops[0];
2785 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2786 }
2787 }
2788
2789 // If we are adding something to a multiply expression, make sure the
2790 // something is not already an operand of the multiply. If so, merge it into
2791 // the multiply.
2792 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2793 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2794 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2795 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2796 if (isa<SCEVConstant>(MulOpSCEV))
2797 continue;
2798 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2799 if (MulOpSCEV == Ops[AddOp]) {
2800 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2801 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2802 if (Mul->getNumOperands() != 2) {
2803 // If the multiply has more than two operands, we must get the
2804 // Y*Z term.
2805 SmallVector<const SCEV *, 4> MulOps(
2806 Mul->operands().take_front(MulOp));
2807 append_range(MulOps, Mul->operands().drop_front(MulOp + 1));
2808 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2809 }
2810 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2811 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2812 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2813 SCEV::FlagAnyWrap, Depth + 1);
2814 if (Ops.size() == 2) return OuterMul;
2815 if (AddOp < Idx) {
2816 Ops.erase(Ops.begin()+AddOp);
2817 Ops.erase(Ops.begin()+Idx-1);
2818 } else {
2819 Ops.erase(Ops.begin()+Idx);
2820 Ops.erase(Ops.begin()+AddOp-1);
2821 }
2822 Ops.push_back(OuterMul);
2823 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2824 }
2825
2826 // Check this multiply against other multiplies being added together.
2827 for (unsigned OtherMulIdx = Idx+1;
2828 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2829 ++OtherMulIdx) {
2830 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2831 // If MulOp occurs in OtherMul, we can fold the two multiplies
2832 // together.
2833 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2834 OMulOp != e; ++OMulOp)
2835 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2836 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2837 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2838 if (Mul->getNumOperands() != 2) {
2839 SmallVector<const SCEV *, 4> MulOps(
2840 Mul->operands().take_front(MulOp));
2841 append_range(MulOps, Mul->operands().drop_front(MulOp+1));
2842 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2843 }
2844 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2845 if (OtherMul->getNumOperands() != 2) {
2846 SmallVector<const SCEV *, 4> MulOps(
2847 OtherMul->operands().take_front(OMulOp));
2848 append_range(MulOps, OtherMul->operands().drop_front(OMulOp+1));
2849 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2850 }
2851 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2852 const SCEV *InnerMulSum =
2853 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2854 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2855 SCEV::FlagAnyWrap, Depth + 1);
2856 if (Ops.size() == 2) return OuterMul;
2857 Ops.erase(Ops.begin()+Idx);
2858 Ops.erase(Ops.begin()+OtherMulIdx-1);
2859 Ops.push_back(OuterMul);
2860 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2861 }
2862 }
2863 }
2864 }
2865
2866 // If there are any add recurrences in the operands list, see if any other
2867 // added values are loop invariant. If so, we can fold them into the
2868 // recurrence.
2869 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2870 ++Idx;
2871
2872 // Scan over all recurrences, trying to fold loop invariants into them.
2873 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2874 // Scan all of the other operands to this add and add them to the vector if
2875 // they are loop invariant w.r.t. the recurrence.
2876 SmallVector<const SCEV *, 8> LIOps;
2877 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2878 const Loop *AddRecLoop = AddRec->getLoop();
2879 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2880 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2881 LIOps.push_back(Ops[i]);
2882 Ops.erase(Ops.begin()+i);
2883 --i; --e;
2884 }
2885
2886 // If we found some loop invariants, fold them into the recurrence.
2887 if (!LIOps.empty()) {
2888 // Compute nowrap flags for the addition of the loop-invariant ops and
2889 // the addrec. Temporarily push it as an operand for that purpose. These
2890 // flags are valid in the scope of the addrec only.
2891 LIOps.push_back(AddRec);
2892 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2893 LIOps.pop_back();
2894
2895 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2896 LIOps.push_back(AddRec->getStart());
2897
2898 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2899
2900 // It is not in general safe to propagate flags valid on an add within
2901 // the addrec scope to one outside it. We must prove that the inner
2902 // scope is guaranteed to execute if the outer one does to be able to
2903 // safely propagate. We know the program is undefined if poison is
2904 // produced on the inner scoped addrec. We also know that *for this use*
2905 // the outer scoped add can't overflow (because of the flags we just
2906 // computed for the inner scoped add) without the program being undefined.
2907 // Proving that entry to the outer scope neccesitates entry to the inner
2908 // scope, thus proves the program undefined if the flags would be violated
2909 // in the outer scope.
2910 SCEV::NoWrapFlags AddFlags = Flags;
2911 if (AddFlags != SCEV::FlagAnyWrap) {
2912 auto *DefI = getDefiningScopeBound(LIOps);
2913 auto *ReachI = &*AddRecLoop->getHeader()->begin();
2914 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2915 AddFlags = SCEV::FlagAnyWrap;
2916 }
2917 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2918
2919 // Build the new addrec. Propagate the NUW and NSW flags if both the
2920 // outer add and the inner addrec are guaranteed to have no overflow.
2921 // Always propagate NW.
2922 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2923 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2924
2925 // If all of the other operands were loop invariant, we are done.
2926 if (Ops.size() == 1) return NewRec;
2927
2928 // Otherwise, add the folded AddRec by the non-invariant parts.
2929 for (unsigned i = 0;; ++i)
2930 if (Ops[i] == AddRec) {
2931 Ops[i] = NewRec;
2932 break;
2933 }
2934 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2935 }
2936
2937 // Okay, if there weren't any loop invariants to be folded, check to see if
2938 // there are multiple AddRec's with the same loop induction variable being
2939 // added together. If so, we can fold them.
2940 for (unsigned OtherIdx = Idx+1;
2941 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2942 ++OtherIdx) {
2943 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2944 // so that the 1st found AddRecExpr is dominated by all others.
2945 assert(DT.dominates(
2946 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2947 AddRec->getLoop()->getHeader()) &&
2948 "AddRecExprs are not sorted in reverse dominance order?");
2949 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2950 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2951 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2952 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2953 ++OtherIdx) {
2954 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2955 if (OtherAddRec->getLoop() == AddRecLoop) {
2956 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2957 i != e; ++i) {
2958 if (i >= AddRecOps.size()) {
2959 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
2960 break;
2961 }
2962 SmallVector<const SCEV *, 2> TwoOps = {
2963 AddRecOps[i], OtherAddRec->getOperand(i)};
2964 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2965 }
2966 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2967 }
2968 }
2969 // Step size has changed, so we cannot guarantee no self-wraparound.
2970 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2971 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2972 }
2973 }
2974
2975 // Otherwise couldn't fold anything into this recurrence. Move onto the
2976 // next one.
2977 }
2978
2979 // Okay, it looks like we really DO need an add expr. Check to see if we
2980 // already have one, otherwise create a new one.
2981 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2982 }
2983
2984 const SCEV *
getOrCreateAddExpr(ArrayRef<const SCEV * > Ops,SCEV::NoWrapFlags Flags)2985 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2986 SCEV::NoWrapFlags Flags) {
2987 FoldingSetNodeID ID;
2988 ID.AddInteger(scAddExpr);
2989 for (const SCEV *Op : Ops)
2990 ID.AddPointer(Op);
2991 void *IP = nullptr;
2992 SCEVAddExpr *S =
2993 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2994 if (!S) {
2995 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2996 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2997 S = new (SCEVAllocator)
2998 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2999 UniqueSCEVs.InsertNode(S, IP);
3000 registerUser(S, Ops);
3001 }
3002 S->setNoWrapFlags(Flags);
3003 return S;
3004 }
3005
3006 const SCEV *
getOrCreateAddRecExpr(ArrayRef<const SCEV * > Ops,const Loop * L,SCEV::NoWrapFlags Flags)3007 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
3008 const Loop *L, SCEV::NoWrapFlags Flags) {
3009 FoldingSetNodeID ID;
3010 ID.AddInteger(scAddRecExpr);
3011 for (const SCEV *Op : Ops)
3012 ID.AddPointer(Op);
3013 ID.AddPointer(L);
3014 void *IP = nullptr;
3015 SCEVAddRecExpr *S =
3016 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3017 if (!S) {
3018 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3019 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3020 S = new (SCEVAllocator)
3021 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
3022 UniqueSCEVs.InsertNode(S, IP);
3023 LoopUsers[L].push_back(S);
3024 registerUser(S, Ops);
3025 }
3026 setNoWrapFlags(S, Flags);
3027 return S;
3028 }
3029
3030 const SCEV *
getOrCreateMulExpr(ArrayRef<const SCEV * > Ops,SCEV::NoWrapFlags Flags)3031 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
3032 SCEV::NoWrapFlags Flags) {
3033 FoldingSetNodeID ID;
3034 ID.AddInteger(scMulExpr);
3035 for (const SCEV *Op : Ops)
3036 ID.AddPointer(Op);
3037 void *IP = nullptr;
3038 SCEVMulExpr *S =
3039 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3040 if (!S) {
3041 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3042 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3043 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
3044 O, Ops.size());
3045 UniqueSCEVs.InsertNode(S, IP);
3046 registerUser(S, Ops);
3047 }
3048 S->setNoWrapFlags(Flags);
3049 return S;
3050 }
3051
umul_ov(uint64_t i,uint64_t j,bool & Overflow)3052 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
3053 uint64_t k = i*j;
3054 if (j > 1 && k / j != i) Overflow = true;
3055 return k;
3056 }
3057
3058 /// Compute the result of "n choose k", the binomial coefficient. If an
3059 /// intermediate computation overflows, Overflow will be set and the return will
3060 /// be garbage. Overflow is not cleared on absence of overflow.
Choose(uint64_t n,uint64_t k,bool & Overflow)3061 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3062 // We use the multiplicative formula:
3063 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3064 // At each iteration, we take the n-th term of the numeral and divide by the
3065 // (k-n)th term of the denominator. This division will always produce an
3066 // integral result, and helps reduce the chance of overflow in the
3067 // intermediate computations. However, we can still overflow even when the
3068 // final result would fit.
3069
3070 if (n == 0 || n == k) return 1;
3071 if (k > n) return 0;
3072
3073 if (k > n/2)
3074 k = n-k;
3075
3076 uint64_t r = 1;
3077 for (uint64_t i = 1; i <= k; ++i) {
3078 r = umul_ov(r, n-(i-1), Overflow);
3079 r /= i;
3080 }
3081 return r;
3082 }
3083
3084 /// Determine if any of the operands in this SCEV are a constant or if
3085 /// any of the add or multiply expressions in this SCEV contain a constant.
containsConstantInAddMulChain(const SCEV * StartExpr)3086 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3087 struct FindConstantInAddMulChain {
3088 bool FoundConstant = false;
3089
3090 bool follow(const SCEV *S) {
3091 FoundConstant |= isa<SCEVConstant>(S);
3092 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3093 }
3094
3095 bool isDone() const {
3096 return FoundConstant;
3097 }
3098 };
3099
3100 FindConstantInAddMulChain F;
3101 SCEVTraversal<FindConstantInAddMulChain> ST(F);
3102 ST.visitAll(StartExpr);
3103 return F.FoundConstant;
3104 }
3105
3106 /// Get a canonical multiply expression, or something simpler if possible.
getMulExpr(SmallVectorImpl<const SCEV * > & Ops,SCEV::NoWrapFlags OrigFlags,unsigned Depth)3107 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
3108 SCEV::NoWrapFlags OrigFlags,
3109 unsigned Depth) {
3110 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3111 "only nuw or nsw allowed");
3112 assert(!Ops.empty() && "Cannot get empty mul!");
3113 if (Ops.size() == 1) return Ops[0];
3114 #ifndef NDEBUG
3115 Type *ETy = Ops[0]->getType();
3116 assert(!ETy->isPointerTy());
3117 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3118 assert(Ops[i]->getType() == ETy &&
3119 "SCEVMulExpr operand types don't match!");
3120 #endif
3121
3122 // Sort by complexity, this groups all similar expression types together.
3123 GroupByComplexity(Ops, &LI, DT);
3124
3125 // If there are any constants, fold them together.
3126 unsigned Idx = 0;
3127 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3128 ++Idx;
3129 assert(Idx < Ops.size());
3130 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3131 // We found two constants, fold them together!
3132 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
3133 if (Ops.size() == 2) return Ops[0];
3134 Ops.erase(Ops.begin()+1); // Erase the folded element
3135 LHSC = cast<SCEVConstant>(Ops[0]);
3136 }
3137
3138 // If we have a multiply of zero, it will always be zero.
3139 if (LHSC->getValue()->isZero())
3140 return LHSC;
3141
3142 // If we are left with a constant one being multiplied, strip it off.
3143 if (LHSC->getValue()->isOne()) {
3144 Ops.erase(Ops.begin());
3145 --Idx;
3146 }
3147
3148 if (Ops.size() == 1)
3149 return Ops[0];
3150 }
3151
3152 // Delay expensive flag strengthening until necessary.
3153 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
3154 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3155 };
3156
3157 // Limit recursion calls depth.
3158 if (Depth > MaxArithDepth || hasHugeExpression(Ops))
3159 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3160
3161 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3162 // Don't strengthen flags if we have no new information.
3163 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3164 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3165 Mul->setNoWrapFlags(ComputeFlags(Ops));
3166 return S;
3167 }
3168
3169 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3170 if (Ops.size() == 2) {
3171 // C1*(C2+V) -> C1*C2 + C1*V
3172 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
3173 // If any of Add's ops are Adds or Muls with a constant, apply this
3174 // transformation as well.
3175 //
3176 // TODO: There are some cases where this transformation is not
3177 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
3178 // this transformation should be narrowed down.
3179 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) {
3180 const SCEV *LHS = getMulExpr(LHSC, Add->getOperand(0),
3181 SCEV::FlagAnyWrap, Depth + 1);
3182 const SCEV *RHS = getMulExpr(LHSC, Add->getOperand(1),
3183 SCEV::FlagAnyWrap, Depth + 1);
3184 return getAddExpr(LHS, RHS, SCEV::FlagAnyWrap, Depth + 1);
3185 }
3186
3187 if (Ops[0]->isAllOnesValue()) {
3188 // If we have a mul by -1 of an add, try distributing the -1 among the
3189 // add operands.
3190 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3191 SmallVector<const SCEV *, 4> NewOps;
3192 bool AnyFolded = false;
3193 for (const SCEV *AddOp : Add->operands()) {
3194 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
3195 Depth + 1);
3196 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3197 NewOps.push_back(Mul);
3198 }
3199 if (AnyFolded)
3200 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3201 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3202 // Negation preserves a recurrence's no self-wrap property.
3203 SmallVector<const SCEV *, 4> Operands;
3204 for (const SCEV *AddRecOp : AddRec->operands())
3205 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
3206 Depth + 1));
3207 // Let M be the minimum representable signed value. AddRec with nsw
3208 // multiplied by -1 can have signed overflow if and only if it takes a
3209 // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3210 // maximum signed value. In all other cases signed overflow is
3211 // impossible.
3212 auto FlagsMask = SCEV::FlagNW;
3213 if (hasFlags(AddRec->getNoWrapFlags(), SCEV::FlagNSW)) {
3214 auto MinInt =
3215 APInt::getSignedMinValue(getTypeSizeInBits(AddRec->getType()));
3216 if (getSignedRangeMin(AddRec) != MinInt)
3217 FlagsMask = setFlags(FlagsMask, SCEV::FlagNSW);
3218 }
3219 return getAddRecExpr(Operands, AddRec->getLoop(),
3220 AddRec->getNoWrapFlags(FlagsMask));
3221 }
3222 }
3223 }
3224 }
3225
3226 // Skip over the add expression until we get to a multiply.
3227 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3228 ++Idx;
3229
3230 // If there are mul operands inline them all into this expression.
3231 if (Idx < Ops.size()) {
3232 bool DeletedMul = false;
3233 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3234 if (Ops.size() > MulOpsInlineThreshold)
3235 break;
3236 // If we have an mul, expand the mul operands onto the end of the
3237 // operands list.
3238 Ops.erase(Ops.begin()+Idx);
3239 append_range(Ops, Mul->operands());
3240 DeletedMul = true;
3241 }
3242
3243 // If we deleted at least one mul, we added operands to the end of the
3244 // list, and they are not necessarily sorted. Recurse to resort and
3245 // resimplify any operands we just acquired.
3246 if (DeletedMul)
3247 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3248 }
3249
3250 // If there are any add recurrences in the operands list, see if any other
3251 // added values are loop invariant. If so, we can fold them into the
3252 // recurrence.
3253 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3254 ++Idx;
3255
3256 // Scan over all recurrences, trying to fold loop invariants into them.
3257 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3258 // Scan all of the other operands to this mul and add them to the vector
3259 // if they are loop invariant w.r.t. the recurrence.
3260 SmallVector<const SCEV *, 8> LIOps;
3261 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3262 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3263 if (isAvailableAtLoopEntry(Ops[i], AddRec->getLoop())) {
3264 LIOps.push_back(Ops[i]);
3265 Ops.erase(Ops.begin()+i);
3266 --i; --e;
3267 }
3268
3269 // If we found some loop invariants, fold them into the recurrence.
3270 if (!LIOps.empty()) {
3271 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3272 SmallVector<const SCEV *, 4> NewOps;
3273 NewOps.reserve(AddRec->getNumOperands());
3274 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3275
3276 // If both the mul and addrec are nuw, we can preserve nuw.
3277 // If both the mul and addrec are nsw, we can only preserve nsw if either
3278 // a) they are also nuw, or
3279 // b) all multiplications of addrec operands with scale are nsw.
3280 SCEV::NoWrapFlags Flags =
3281 AddRec->getNoWrapFlags(ComputeFlags({Scale, AddRec}));
3282
3283 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3284 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3285 SCEV::FlagAnyWrap, Depth + 1));
3286
3287 if (hasFlags(Flags, SCEV::FlagNSW) && !hasFlags(Flags, SCEV::FlagNUW)) {
3288 ConstantRange NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3289 Instruction::Mul, getSignedRange(Scale),
3290 OverflowingBinaryOperator::NoSignedWrap);
3291 if (!NSWRegion.contains(getSignedRange(AddRec->getOperand(i))))
3292 Flags = clearFlags(Flags, SCEV::FlagNSW);
3293 }
3294 }
3295
3296 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(), Flags);
3297
3298 // If all of the other operands were loop invariant, we are done.
3299 if (Ops.size() == 1) return NewRec;
3300
3301 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3302 for (unsigned i = 0;; ++i)
3303 if (Ops[i] == AddRec) {
3304 Ops[i] = NewRec;
3305 break;
3306 }
3307 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3308 }
3309
3310 // Okay, if there weren't any loop invariants to be folded, check to see
3311 // if there are multiple AddRec's with the same loop induction variable
3312 // being multiplied together. If so, we can fold them.
3313
3314 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3315 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3316 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3317 // ]]],+,...up to x=2n}.
3318 // Note that the arguments to choose() are always integers with values
3319 // known at compile time, never SCEV objects.
3320 //
3321 // The implementation avoids pointless extra computations when the two
3322 // addrec's are of different length (mathematically, it's equivalent to
3323 // an infinite stream of zeros on the right).
3324 bool OpsModified = false;
3325 for (unsigned OtherIdx = Idx+1;
3326 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3327 ++OtherIdx) {
3328 const SCEVAddRecExpr *OtherAddRec =
3329 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3330 if (!OtherAddRec || OtherAddRec->getLoop() != AddRec->getLoop())
3331 continue;
3332
3333 // Limit max number of arguments to avoid creation of unreasonably big
3334 // SCEVAddRecs with very complex operands.
3335 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3336 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3337 continue;
3338
3339 bool Overflow = false;
3340 Type *Ty = AddRec->getType();
3341 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3342 SmallVector<const SCEV*, 7> AddRecOps;
3343 for (int x = 0, xe = AddRec->getNumOperands() +
3344 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3345 SmallVector <const SCEV *, 7> SumOps;
3346 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3347 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3348 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3349 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3350 z < ze && !Overflow; ++z) {
3351 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3352 uint64_t Coeff;
3353 if (LargerThan64Bits)
3354 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3355 else
3356 Coeff = Coeff1*Coeff2;
3357 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3358 const SCEV *Term1 = AddRec->getOperand(y-z);
3359 const SCEV *Term2 = OtherAddRec->getOperand(z);
3360 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3361 SCEV::FlagAnyWrap, Depth + 1));
3362 }
3363 }
3364 if (SumOps.empty())
3365 SumOps.push_back(getZero(Ty));
3366 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3367 }
3368 if (!Overflow) {
3369 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
3370 SCEV::FlagAnyWrap);
3371 if (Ops.size() == 2) return NewAddRec;
3372 Ops[Idx] = NewAddRec;
3373 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3374 OpsModified = true;
3375 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3376 if (!AddRec)
3377 break;
3378 }
3379 }
3380 if (OpsModified)
3381 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3382
3383 // Otherwise couldn't fold anything into this recurrence. Move onto the
3384 // next one.
3385 }
3386
3387 // Okay, it looks like we really DO need an mul expr. Check to see if we
3388 // already have one, otherwise create a new one.
3389 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3390 }
3391
3392 /// Represents an unsigned remainder expression based on unsigned division.
getURemExpr(const SCEV * LHS,const SCEV * RHS)3393 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3394 const SCEV *RHS) {
3395 assert(getEffectiveSCEVType(LHS->getType()) ==
3396 getEffectiveSCEVType(RHS->getType()) &&
3397 "SCEVURemExpr operand types don't match!");
3398
3399 // Short-circuit easy cases
3400 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3401 // If constant is one, the result is trivial
3402 if (RHSC->getValue()->isOne())
3403 return getZero(LHS->getType()); // X urem 1 --> 0
3404
3405 // If constant is a power of two, fold into a zext(trunc(LHS)).
3406 if (RHSC->getAPInt().isPowerOf2()) {
3407 Type *FullTy = LHS->getType();
3408 Type *TruncTy =
3409 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3410 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3411 }
3412 }
3413
3414 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3415 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3416 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3417 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3418 }
3419
3420 /// Get a canonical unsigned division expression, or something simpler if
3421 /// possible.
getUDivExpr(const SCEV * LHS,const SCEV * RHS)3422 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3423 const SCEV *RHS) {
3424 assert(!LHS->getType()->isPointerTy() &&
3425 "SCEVUDivExpr operand can't be pointer!");
3426 assert(LHS->getType() == RHS->getType() &&
3427 "SCEVUDivExpr operand types don't match!");
3428
3429 FoldingSetNodeID ID;
3430 ID.AddInteger(scUDivExpr);
3431 ID.AddPointer(LHS);
3432 ID.AddPointer(RHS);
3433 void *IP = nullptr;
3434 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3435 return S;
3436
3437 // 0 udiv Y == 0
3438 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3439 if (LHSC->getValue()->isZero())
3440 return LHS;
3441
3442 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3443 if (RHSC->getValue()->isOne())
3444 return LHS; // X udiv 1 --> x
3445 // If the denominator is zero, the result of the udiv is undefined. Don't
3446 // try to analyze it, because the resolution chosen here may differ from
3447 // the resolution chosen in other parts of the compiler.
3448 if (!RHSC->getValue()->isZero()) {
3449 // Determine if the division can be folded into the operands of
3450 // its operands.
3451 // TODO: Generalize this to non-constants by using known-bits information.
3452 Type *Ty = LHS->getType();
3453 unsigned LZ = RHSC->getAPInt().countl_zero();
3454 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3455 // For non-power-of-two values, effectively round the value up to the
3456 // nearest power of two.
3457 if (!RHSC->getAPInt().isPowerOf2())
3458 ++MaxShiftAmt;
3459 IntegerType *ExtTy =
3460 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3461 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3462 if (const SCEVConstant *Step =
3463 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3464 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3465 const APInt &StepInt = Step->getAPInt();
3466 const APInt &DivInt = RHSC->getAPInt();
3467 if (!StepInt.urem(DivInt) &&
3468 getZeroExtendExpr(AR, ExtTy) ==
3469 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3470 getZeroExtendExpr(Step, ExtTy),
3471 AR->getLoop(), SCEV::FlagAnyWrap)) {
3472 SmallVector<const SCEV *, 4> Operands;
3473 for (const SCEV *Op : AR->operands())
3474 Operands.push_back(getUDivExpr(Op, RHS));
3475 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3476 }
3477 /// Get a canonical UDivExpr for a recurrence.
3478 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3479 // We can currently only fold X%N if X is constant.
3480 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3481 if (StartC && !DivInt.urem(StepInt) &&
3482 getZeroExtendExpr(AR, ExtTy) ==
3483 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3484 getZeroExtendExpr(Step, ExtTy),
3485 AR->getLoop(), SCEV::FlagAnyWrap)) {
3486 const APInt &StartInt = StartC->getAPInt();
3487 const APInt &StartRem = StartInt.urem(StepInt);
3488 if (StartRem != 0) {
3489 const SCEV *NewLHS =
3490 getAddRecExpr(getConstant(StartInt - StartRem), Step,
3491 AR->getLoop(), SCEV::FlagNW);
3492 if (LHS != NewLHS) {
3493 LHS = NewLHS;
3494
3495 // Reset the ID to include the new LHS, and check if it is
3496 // already cached.
3497 ID.clear();
3498 ID.AddInteger(scUDivExpr);
3499 ID.AddPointer(LHS);
3500 ID.AddPointer(RHS);
3501 IP = nullptr;
3502 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3503 return S;
3504 }
3505 }
3506 }
3507 }
3508 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3509 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3510 SmallVector<const SCEV *, 4> Operands;
3511 for (const SCEV *Op : M->operands())
3512 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3513 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3514 // Find an operand that's safely divisible.
3515 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3516 const SCEV *Op = M->getOperand(i);
3517 const SCEV *Div = getUDivExpr(Op, RHSC);
3518 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3519 Operands = SmallVector<const SCEV *, 4>(M->operands());
3520 Operands[i] = Div;
3521 return getMulExpr(Operands);
3522 }
3523 }
3524 }
3525
3526 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3527 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3528 if (auto *DivisorConstant =
3529 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3530 bool Overflow = false;
3531 APInt NewRHS =
3532 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3533 if (Overflow) {
3534 return getConstant(RHSC->getType(), 0, false);
3535 }
3536 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3537 }
3538 }
3539
3540 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3541 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3542 SmallVector<const SCEV *, 4> Operands;
3543 for (const SCEV *Op : A->operands())
3544 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3545 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3546 Operands.clear();
3547 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3548 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3549 if (isa<SCEVUDivExpr>(Op) ||
3550 getMulExpr(Op, RHS) != A->getOperand(i))
3551 break;
3552 Operands.push_back(Op);
3553 }
3554 if (Operands.size() == A->getNumOperands())
3555 return getAddExpr(Operands);
3556 }
3557 }
3558
3559 // Fold if both operands are constant.
3560 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3561 return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3562 }
3563 }
3564
3565 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3566 // changes). Make sure we get a new one.
3567 IP = nullptr;
3568 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3569 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3570 LHS, RHS);
3571 UniqueSCEVs.InsertNode(S, IP);
3572 registerUser(S, {LHS, RHS});
3573 return S;
3574 }
3575
gcd(const SCEVConstant * C1,const SCEVConstant * C2)3576 APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3577 APInt A = C1->getAPInt().abs();
3578 APInt B = C2->getAPInt().abs();
3579 uint32_t ABW = A.getBitWidth();
3580 uint32_t BBW = B.getBitWidth();
3581
3582 if (ABW > BBW)
3583 B = B.zext(ABW);
3584 else if (ABW < BBW)
3585 A = A.zext(BBW);
3586
3587 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3588 }
3589
3590 /// Get a canonical unsigned division expression, or something simpler if
3591 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3592 /// can attempt to remove factors from the LHS and RHS. We can't do this when
3593 /// it's not exact because the udiv may be clearing bits.
getUDivExactExpr(const SCEV * LHS,const SCEV * RHS)3594 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3595 const SCEV *RHS) {
3596 // TODO: we could try to find factors in all sorts of things, but for now we
3597 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3598 // end of this file for inspiration.
3599
3600 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3601 if (!Mul || !Mul->hasNoUnsignedWrap())
3602 return getUDivExpr(LHS, RHS);
3603
3604 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3605 // If the mulexpr multiplies by a constant, then that constant must be the
3606 // first element of the mulexpr.
3607 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3608 if (LHSCst == RHSCst) {
3609 SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands()));
3610 return getMulExpr(Operands);
3611 }
3612
3613 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3614 // that there's a factor provided by one of the other terms. We need to
3615 // check.
3616 APInt Factor = gcd(LHSCst, RHSCst);
3617 if (!Factor.isIntN(1)) {
3618 LHSCst =
3619 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3620 RHSCst =
3621 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3622 SmallVector<const SCEV *, 2> Operands;
3623 Operands.push_back(LHSCst);
3624 append_range(Operands, Mul->operands().drop_front());
3625 LHS = getMulExpr(Operands);
3626 RHS = RHSCst;
3627 Mul = dyn_cast<SCEVMulExpr>(LHS);
3628 if (!Mul)
3629 return getUDivExactExpr(LHS, RHS);
3630 }
3631 }
3632 }
3633
3634 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3635 if (Mul->getOperand(i) == RHS) {
3636 SmallVector<const SCEV *, 2> Operands;
3637 append_range(Operands, Mul->operands().take_front(i));
3638 append_range(Operands, Mul->operands().drop_front(i + 1));
3639 return getMulExpr(Operands);
3640 }
3641 }
3642
3643 return getUDivExpr(LHS, RHS);
3644 }
3645
3646 /// Get an add recurrence expression for the specified loop. Simplify the
3647 /// expression as much as possible.
getAddRecExpr(const SCEV * Start,const SCEV * Step,const Loop * L,SCEV::NoWrapFlags Flags)3648 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3649 const Loop *L,
3650 SCEV::NoWrapFlags Flags) {
3651 SmallVector<const SCEV *, 4> Operands;
3652 Operands.push_back(Start);
3653 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3654 if (StepChrec->getLoop() == L) {
3655 append_range(Operands, StepChrec->operands());
3656 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3657 }
3658
3659 Operands.push_back(Step);
3660 return getAddRecExpr(Operands, L, Flags);
3661 }
3662
3663 /// Get an add recurrence expression for the specified loop. Simplify the
3664 /// expression as much as possible.
3665 const SCEV *
getAddRecExpr(SmallVectorImpl<const SCEV * > & Operands,const Loop * L,SCEV::NoWrapFlags Flags)3666 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3667 const Loop *L, SCEV::NoWrapFlags Flags) {
3668 if (Operands.size() == 1) return Operands[0];
3669 #ifndef NDEBUG
3670 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3671 for (const SCEV *Op : llvm::drop_begin(Operands)) {
3672 assert(getEffectiveSCEVType(Op->getType()) == ETy &&
3673 "SCEVAddRecExpr operand types don't match!");
3674 assert(!Op->getType()->isPointerTy() && "Step must be integer");
3675 }
3676 for (const SCEV *Op : Operands)
3677 assert(isAvailableAtLoopEntry(Op, L) &&
3678 "SCEVAddRecExpr operand is not available at loop entry!");
3679 #endif
3680
3681 if (Operands.back()->isZero()) {
3682 Operands.pop_back();
3683 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3684 }
3685
3686 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3687 // use that information to infer NUW and NSW flags. However, computing a
3688 // BE count requires calling getAddRecExpr, so we may not yet have a
3689 // meaningful BE count at this point (and if we don't, we'd be stuck
3690 // with a SCEVCouldNotCompute as the cached BE count).
3691
3692 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3693
3694 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3695 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3696 const Loop *NestedLoop = NestedAR->getLoop();
3697 if (L->contains(NestedLoop)
3698 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3699 : (!NestedLoop->contains(L) &&
3700 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3701 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands());
3702 Operands[0] = NestedAR->getStart();
3703 // AddRecs require their operands be loop-invariant with respect to their
3704 // loops. Don't perform this transformation if it would break this
3705 // requirement.
3706 bool AllInvariant = all_of(
3707 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3708
3709 if (AllInvariant) {
3710 // Create a recurrence for the outer loop with the same step size.
3711 //
3712 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3713 // inner recurrence has the same property.
3714 SCEV::NoWrapFlags OuterFlags =
3715 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3716
3717 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3718 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3719 return isLoopInvariant(Op, NestedLoop);
3720 });
3721
3722 if (AllInvariant) {
3723 // Ok, both add recurrences are valid after the transformation.
3724 //
3725 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3726 // the outer recurrence has the same property.
3727 SCEV::NoWrapFlags InnerFlags =
3728 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3729 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3730 }
3731 }
3732 // Reset Operands to its original state.
3733 Operands[0] = NestedAR;
3734 }
3735 }
3736
3737 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3738 // already have one, otherwise create a new one.
3739 return getOrCreateAddRecExpr(Operands, L, Flags);
3740 }
3741
3742 const SCEV *
getGEPExpr(GEPOperator * GEP,const SmallVectorImpl<const SCEV * > & IndexExprs)3743 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3744 const SmallVectorImpl<const SCEV *> &IndexExprs) {
3745 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3746 // getSCEV(Base)->getType() has the same address space as Base->getType()
3747 // because SCEV::getType() preserves the address space.
3748 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3749 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
3750 if (NW != GEPNoWrapFlags::none()) {
3751 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3752 // but to do that, we have to ensure that said flag is valid in the entire
3753 // defined scope of the SCEV.
3754 // TODO: non-instructions have global scope. We might be able to prove
3755 // some global scope cases
3756 auto *GEPI = dyn_cast<Instruction>(GEP);
3757 if (!GEPI || !isSCEVExprNeverPoison(GEPI))
3758 NW = GEPNoWrapFlags::none();
3759 }
3760
3761 SCEV::NoWrapFlags OffsetWrap = SCEV::FlagAnyWrap;
3762 if (NW.hasNoUnsignedSignedWrap())
3763 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNSW);
3764 if (NW.hasNoUnsignedWrap())
3765 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNUW);
3766
3767 Type *CurTy = GEP->getType();
3768 bool FirstIter = true;
3769 SmallVector<const SCEV *, 4> Offsets;
3770 for (const SCEV *IndexExpr : IndexExprs) {
3771 // Compute the (potentially symbolic) offset in bytes for this index.
3772 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3773 // For a struct, add the member offset.
3774 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3775 unsigned FieldNo = Index->getZExtValue();
3776 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3777 Offsets.push_back(FieldOffset);
3778
3779 // Update CurTy to the type of the field at Index.
3780 CurTy = STy->getTypeAtIndex(Index);
3781 } else {
3782 // Update CurTy to its element type.
3783 if (FirstIter) {
3784 assert(isa<PointerType>(CurTy) &&
3785 "The first index of a GEP indexes a pointer");
3786 CurTy = GEP->getSourceElementType();
3787 FirstIter = false;
3788 } else {
3789 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3790 }
3791 // For an array, add the element offset, explicitly scaled.
3792 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3793 // Getelementptr indices are signed.
3794 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3795
3796 // Multiply the index by the element size to compute the element offset.
3797 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3798 Offsets.push_back(LocalOffset);
3799 }
3800 }
3801
3802 // Handle degenerate case of GEP without offsets.
3803 if (Offsets.empty())
3804 return BaseExpr;
3805
3806 // Add the offsets together, assuming nsw if inbounds.
3807 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3808 // Add the base address and the offset. We cannot use the nsw flag, as the
3809 // base address is unsigned. However, if we know that the offset is
3810 // non-negative, we can use nuw.
3811 bool NUW = NW.hasNoUnsignedWrap() ||
3812 (NW.hasNoUnsignedSignedWrap() && isKnownNonNegative(Offset));
3813 SCEV::NoWrapFlags BaseWrap = NUW ? SCEV::FlagNUW : SCEV::FlagAnyWrap;
3814 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3815 assert(BaseExpr->getType() == GEPExpr->getType() &&
3816 "GEP should not change type mid-flight.");
3817 return GEPExpr;
3818 }
3819
findExistingSCEVInCache(SCEVTypes SCEVType,ArrayRef<const SCEV * > Ops)3820 SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3821 ArrayRef<const SCEV *> Ops) {
3822 FoldingSetNodeID ID;
3823 ID.AddInteger(SCEVType);
3824 for (const SCEV *Op : Ops)
3825 ID.AddPointer(Op);
3826 void *IP = nullptr;
3827 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3828 }
3829
getAbsExpr(const SCEV * Op,bool IsNSW)3830 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3831 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3832 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3833 }
3834
getMinMaxExpr(SCEVTypes Kind,SmallVectorImpl<const SCEV * > & Ops)3835 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
3836 SmallVectorImpl<const SCEV *> &Ops) {
3837 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3838 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3839 if (Ops.size() == 1) return Ops[0];
3840 #ifndef NDEBUG
3841 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3842 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3843 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3844 "Operand types don't match!");
3845 assert(Ops[0]->getType()->isPointerTy() ==
3846 Ops[i]->getType()->isPointerTy() &&
3847 "min/max should be consistently pointerish");
3848 }
3849 #endif
3850
3851 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3852 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3853
3854 // Sort by complexity, this groups all similar expression types together.
3855 GroupByComplexity(Ops, &LI, DT);
3856
3857 // Check if we have created the same expression before.
3858 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3859 return S;
3860 }
3861
3862 // If there are any constants, fold them together.
3863 unsigned Idx = 0;
3864 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3865 ++Idx;
3866 assert(Idx < Ops.size());
3867 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3868 switch (Kind) {
3869 case scSMaxExpr:
3870 return APIntOps::smax(LHS, RHS);
3871 case scSMinExpr:
3872 return APIntOps::smin(LHS, RHS);
3873 case scUMaxExpr:
3874 return APIntOps::umax(LHS, RHS);
3875 case scUMinExpr:
3876 return APIntOps::umin(LHS, RHS);
3877 default:
3878 llvm_unreachable("Unknown SCEV min/max opcode");
3879 }
3880 };
3881
3882 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3883 // We found two constants, fold them together!
3884 ConstantInt *Fold = ConstantInt::get(
3885 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3886 Ops[0] = getConstant(Fold);
3887 Ops.erase(Ops.begin()+1); // Erase the folded element
3888 if (Ops.size() == 1) return Ops[0];
3889 LHSC = cast<SCEVConstant>(Ops[0]);
3890 }
3891
3892 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3893 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3894
3895 if (IsMax ? IsMinV : IsMaxV) {
3896 // If we are left with a constant minimum(/maximum)-int, strip it off.
3897 Ops.erase(Ops.begin());
3898 --Idx;
3899 } else if (IsMax ? IsMaxV : IsMinV) {
3900 // If we have a max(/min) with a constant maximum(/minimum)-int,
3901 // it will always be the extremum.
3902 return LHSC;
3903 }
3904
3905 if (Ops.size() == 1) return Ops[0];
3906 }
3907
3908 // Find the first operation of the same kind
3909 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3910 ++Idx;
3911
3912 // Check to see if one of the operands is of the same kind. If so, expand its
3913 // operands onto our operand list, and recurse to simplify.
3914 if (Idx < Ops.size()) {
3915 bool DeletedAny = false;
3916 while (Ops[Idx]->getSCEVType() == Kind) {
3917 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3918 Ops.erase(Ops.begin()+Idx);
3919 append_range(Ops, SMME->operands());
3920 DeletedAny = true;
3921 }
3922
3923 if (DeletedAny)
3924 return getMinMaxExpr(Kind, Ops);
3925 }
3926
3927 // Okay, check to see if the same value occurs in the operand list twice. If
3928 // so, delete one. Since we sorted the list, these values are required to
3929 // be adjacent.
3930 llvm::CmpInst::Predicate GEPred =
3931 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3932 llvm::CmpInst::Predicate LEPred =
3933 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3934 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3935 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3936 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3937 if (Ops[i] == Ops[i + 1] ||
3938 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3939 // X op Y op Y --> X op Y
3940 // X op Y --> X, if we know X, Y are ordered appropriately
3941 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3942 --i;
3943 --e;
3944 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3945 Ops[i + 1])) {
3946 // X op Y --> Y, if we know X, Y are ordered appropriately
3947 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3948 --i;
3949 --e;
3950 }
3951 }
3952
3953 if (Ops.size() == 1) return Ops[0];
3954
3955 assert(!Ops.empty() && "Reduced smax down to nothing!");
3956
3957 // Okay, it looks like we really DO need an expr. Check to see if we
3958 // already have one, otherwise create a new one.
3959 FoldingSetNodeID ID;
3960 ID.AddInteger(Kind);
3961 for (const SCEV *Op : Ops)
3962 ID.AddPointer(Op);
3963 void *IP = nullptr;
3964 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3965 if (ExistingSCEV)
3966 return ExistingSCEV;
3967 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3968 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3969 SCEV *S = new (SCEVAllocator)
3970 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3971
3972 UniqueSCEVs.InsertNode(S, IP);
3973 registerUser(S, Ops);
3974 return S;
3975 }
3976
3977 namespace {
3978
3979 class SCEVSequentialMinMaxDeduplicatingVisitor final
3980 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
3981 std::optional<const SCEV *>> {
3982 using RetVal = std::optional<const SCEV *>;
3983 using Base = SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor, RetVal>;
3984
3985 ScalarEvolution &SE;
3986 const SCEVTypes RootKind; // Must be a sequential min/max expression.
3987 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
3988 SmallPtrSet<const SCEV *, 16> SeenOps;
3989
canRecurseInto(SCEVTypes Kind) const3990 bool canRecurseInto(SCEVTypes Kind) const {
3991 // We can only recurse into the SCEV expression of the same effective type
3992 // as the type of our root SCEV expression.
3993 return RootKind == Kind || NonSequentialRootKind == Kind;
3994 };
3995
visitAnyMinMaxExpr(const SCEV * S)3996 RetVal visitAnyMinMaxExpr(const SCEV *S) {
3997 assert((isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) &&
3998 "Only for min/max expressions.");
3999 SCEVTypes Kind = S->getSCEVType();
4000
4001 if (!canRecurseInto(Kind))
4002 return S;
4003
4004 auto *NAry = cast<SCEVNAryExpr>(S);
4005 SmallVector<const SCEV *> NewOps;
4006 bool Changed = visit(Kind, NAry->operands(), NewOps);
4007
4008 if (!Changed)
4009 return S;
4010 if (NewOps.empty())
4011 return std::nullopt;
4012
4013 return isa<SCEVSequentialMinMaxExpr>(S)
4014 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
4015 : SE.getMinMaxExpr(Kind, NewOps);
4016 }
4017
visit(const SCEV * S)4018 RetVal visit(const SCEV *S) {
4019 // Has the whole operand been seen already?
4020 if (!SeenOps.insert(S).second)
4021 return std::nullopt;
4022 return Base::visit(S);
4023 }
4024
4025 public:
SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution & SE,SCEVTypes RootKind)4026 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
4027 SCEVTypes RootKind)
4028 : SE(SE), RootKind(RootKind),
4029 NonSequentialRootKind(
4030 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4031 RootKind)) {}
4032
visit(SCEVTypes Kind,ArrayRef<const SCEV * > OrigOps,SmallVectorImpl<const SCEV * > & NewOps)4033 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<const SCEV *> OrigOps,
4034 SmallVectorImpl<const SCEV *> &NewOps) {
4035 bool Changed = false;
4036 SmallVector<const SCEV *> Ops;
4037 Ops.reserve(OrigOps.size());
4038
4039 for (const SCEV *Op : OrigOps) {
4040 RetVal NewOp = visit(Op);
4041 if (NewOp != Op)
4042 Changed = true;
4043 if (NewOp)
4044 Ops.emplace_back(*NewOp);
4045 }
4046
4047 if (Changed)
4048 NewOps = std::move(Ops);
4049 return Changed;
4050 }
4051
visitConstant(const SCEVConstant * Constant)4052 RetVal visitConstant(const SCEVConstant *Constant) { return Constant; }
4053
visitVScale(const SCEVVScale * VScale)4054 RetVal visitVScale(const SCEVVScale *VScale) { return VScale; }
4055
visitPtrToIntExpr(const SCEVPtrToIntExpr * Expr)4056 RetVal visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) { return Expr; }
4057
visitTruncateExpr(const SCEVTruncateExpr * Expr)4058 RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
4059
visitZeroExtendExpr(const SCEVZeroExtendExpr * Expr)4060 RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; }
4061
visitSignExtendExpr(const SCEVSignExtendExpr * Expr)4062 RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; }
4063
visitAddExpr(const SCEVAddExpr * Expr)4064 RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; }
4065
visitMulExpr(const SCEVMulExpr * Expr)4066 RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; }
4067
visitUDivExpr(const SCEVUDivExpr * Expr)4068 RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
4069
visitAddRecExpr(const SCEVAddRecExpr * Expr)4070 RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
4071
visitSMaxExpr(const SCEVSMaxExpr * Expr)4072 RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) {
4073 return visitAnyMinMaxExpr(Expr);
4074 }
4075
visitUMaxExpr(const SCEVUMaxExpr * Expr)4076 RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) {
4077 return visitAnyMinMaxExpr(Expr);
4078 }
4079
visitSMinExpr(const SCEVSMinExpr * Expr)4080 RetVal visitSMinExpr(const SCEVSMinExpr *Expr) {
4081 return visitAnyMinMaxExpr(Expr);
4082 }
4083
visitUMinExpr(const SCEVUMinExpr * Expr)4084 RetVal visitUMinExpr(const SCEVUMinExpr *Expr) {
4085 return visitAnyMinMaxExpr(Expr);
4086 }
4087
visitSequentialUMinExpr(const SCEVSequentialUMinExpr * Expr)4088 RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
4089 return visitAnyMinMaxExpr(Expr);
4090 }
4091
visitUnknown(const SCEVUnknown * Expr)4092 RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; }
4093
visitCouldNotCompute(const SCEVCouldNotCompute * Expr)4094 RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; }
4095 };
4096
4097 } // namespace
4098
scevUnconditionallyPropagatesPoisonFromOperands(SCEVTypes Kind)4099 static bool scevUnconditionallyPropagatesPoisonFromOperands(SCEVTypes Kind) {
4100 switch (Kind) {
4101 case scConstant:
4102 case scVScale:
4103 case scTruncate:
4104 case scZeroExtend:
4105 case scSignExtend:
4106 case scPtrToInt:
4107 case scAddExpr:
4108 case scMulExpr:
4109 case scUDivExpr:
4110 case scAddRecExpr:
4111 case scUMaxExpr:
4112 case scSMaxExpr:
4113 case scUMinExpr:
4114 case scSMinExpr:
4115 case scUnknown:
4116 // If any operand is poison, the whole expression is poison.
4117 return true;
4118 case scSequentialUMinExpr:
4119 // FIXME: if the *first* operand is poison, the whole expression is poison.
4120 return false; // Pessimistically, say that it does not propagate poison.
4121 case scCouldNotCompute:
4122 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4123 }
4124 llvm_unreachable("Unknown SCEV kind!");
4125 }
4126
4127 namespace {
4128 // The only way poison may be introduced in a SCEV expression is from a
4129 // poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4130 // not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not*
4131 // introduce poison -- they encode guaranteed, non-speculated knowledge.
4132 //
4133 // Additionally, all SCEV nodes propagate poison from inputs to outputs,
4134 // with the notable exception of umin_seq, where only poison from the first
4135 // operand is (unconditionally) propagated.
4136 struct SCEVPoisonCollector {
4137 bool LookThroughMaybePoisonBlocking;
4138 SmallPtrSet<const SCEVUnknown *, 4> MaybePoison;
SCEVPoisonCollector__anon8884d99e1011::SCEVPoisonCollector4139 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4140 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4141
follow__anon8884d99e1011::SCEVPoisonCollector4142 bool follow(const SCEV *S) {
4143 if (!LookThroughMaybePoisonBlocking &&
4144 !scevUnconditionallyPropagatesPoisonFromOperands(S->getSCEVType()))
4145 return false;
4146
4147 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4148 if (!isGuaranteedNotToBePoison(SU->getValue()))
4149 MaybePoison.insert(SU);
4150 }
4151 return true;
4152 }
isDone__anon8884d99e1011::SCEVPoisonCollector4153 bool isDone() const { return false; }
4154 };
4155 } // namespace
4156
4157 /// Return true if V is poison given that AssumedPoison is already poison.
impliesPoison(const SCEV * AssumedPoison,const SCEV * S)4158 static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4159 // First collect all SCEVs that might result in AssumedPoison to be poison.
4160 // We need to look through potentially poison-blocking operations here,
4161 // because we want to find all SCEVs that *might* result in poison, not only
4162 // those that are *required* to.
4163 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4164 visitAll(AssumedPoison, PC1);
4165
4166 // AssumedPoison is never poison. As the assumption is false, the implication
4167 // is true. Don't bother walking the other SCEV in this case.
4168 if (PC1.MaybePoison.empty())
4169 return true;
4170
4171 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4172 // as well. We cannot look through potentially poison-blocking operations
4173 // here, as their arguments only *may* make the result poison.
4174 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4175 visitAll(S, PC2);
4176
4177 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4178 // it will also make S poison by being part of PC2.MaybePoison.
4179 return all_of(PC1.MaybePoison, [&](const SCEVUnknown *S) {
4180 return PC2.MaybePoison.contains(S);
4181 });
4182 }
4183
getPoisonGeneratingValues(SmallPtrSetImpl<const Value * > & Result,const SCEV * S)4184 void ScalarEvolution::getPoisonGeneratingValues(
4185 SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4186 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4187 visitAll(S, PC);
4188 for (const SCEVUnknown *SU : PC.MaybePoison)
4189 Result.insert(SU->getValue());
4190 }
4191
canReuseInstruction(const SCEV * S,Instruction * I,SmallVectorImpl<Instruction * > & DropPoisonGeneratingInsts)4192 bool ScalarEvolution::canReuseInstruction(
4193 const SCEV *S, Instruction *I,
4194 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
4195 // If the instruction cannot be poison, it's always safe to reuse.
4196 if (programUndefinedIfPoison(I))
4197 return true;
4198
4199 // Otherwise, it is possible that I is more poisonous that S. Collect the
4200 // poison-contributors of S, and then check whether I has any additional
4201 // poison-contributors. Poison that is contributed through poison-generating
4202 // flags is handled by dropping those flags instead.
4203 SmallPtrSet<const Value *, 8> PoisonVals;
4204 getPoisonGeneratingValues(PoisonVals, S);
4205
4206 SmallVector<Value *> Worklist;
4207 SmallPtrSet<Value *, 8> Visited;
4208 Worklist.push_back(I);
4209 while (!Worklist.empty()) {
4210 Value *V = Worklist.pop_back_val();
4211 if (!Visited.insert(V).second)
4212 continue;
4213
4214 // Avoid walking large instruction graphs.
4215 if (Visited.size() > 16)
4216 return false;
4217
4218 // Either the value can't be poison, or the S would also be poison if it
4219 // is.
4220 if (PoisonVals.contains(V) || isGuaranteedNotToBePoison(V))
4221 continue;
4222
4223 auto *I = dyn_cast<Instruction>(V);
4224 if (!I)
4225 return false;
4226
4227 // Disjoint or instructions are interpreted as adds by SCEV. However, we
4228 // can't replace an arbitrary add with disjoint or, even if we drop the
4229 // flag. We would need to convert the or into an add.
4230 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
4231 if (PDI->isDisjoint())
4232 return false;
4233
4234 // FIXME: Ignore vscale, even though it technically could be poison. Do this
4235 // because SCEV currently assumes it can't be poison. Remove this special
4236 // case once we proper model when vscale can be poison.
4237 if (auto *II = dyn_cast<IntrinsicInst>(I);
4238 II && II->getIntrinsicID() == Intrinsic::vscale)
4239 continue;
4240
4241 if (canCreatePoison(cast<Operator>(I), /*ConsiderFlagsAndMetadata*/ false))
4242 return false;
4243
4244 // If the instruction can't create poison, we can recurse to its operands.
4245 if (I->hasPoisonGeneratingAnnotations())
4246 DropPoisonGeneratingInsts.push_back(I);
4247
4248 for (Value *Op : I->operands())
4249 Worklist.push_back(Op);
4250 }
4251 return true;
4252 }
4253
4254 const SCEV *
getSequentialMinMaxExpr(SCEVTypes Kind,SmallVectorImpl<const SCEV * > & Ops)4255 ScalarEvolution::getSequentialMinMaxExpr(SCEVTypes Kind,
4256 SmallVectorImpl<const SCEV *> &Ops) {
4257 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4258 "Not a SCEVSequentialMinMaxExpr!");
4259 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4260 if (Ops.size() == 1)
4261 return Ops[0];
4262 #ifndef NDEBUG
4263 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4264 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4265 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4266 "Operand types don't match!");
4267 assert(Ops[0]->getType()->isPointerTy() ==
4268 Ops[i]->getType()->isPointerTy() &&
4269 "min/max should be consistently pointerish");
4270 }
4271 #endif
4272
4273 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4274 // so we can *NOT* do any kind of sorting of the expressions!
4275
4276 // Check if we have created the same expression before.
4277 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4278 return S;
4279
4280 // FIXME: there are *some* simplifications that we can do here.
4281
4282 // Keep only the first instance of an operand.
4283 {
4284 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4285 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4286 if (Changed)
4287 return getSequentialMinMaxExpr(Kind, Ops);
4288 }
4289
4290 // Check to see if one of the operands is of the same kind. If so, expand its
4291 // operands onto our operand list, and recurse to simplify.
4292 {
4293 unsigned Idx = 0;
4294 bool DeletedAny = false;
4295 while (Idx < Ops.size()) {
4296 if (Ops[Idx]->getSCEVType() != Kind) {
4297 ++Idx;
4298 continue;
4299 }
4300 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4301 Ops.erase(Ops.begin() + Idx);
4302 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4303 SMME->operands().end());
4304 DeletedAny = true;
4305 }
4306
4307 if (DeletedAny)
4308 return getSequentialMinMaxExpr(Kind, Ops);
4309 }
4310
4311 const SCEV *SaturationPoint;
4312 ICmpInst::Predicate Pred;
4313 switch (Kind) {
4314 case scSequentialUMinExpr:
4315 SaturationPoint = getZero(Ops[0]->getType());
4316 Pred = ICmpInst::ICMP_ULE;
4317 break;
4318 default:
4319 llvm_unreachable("Not a sequential min/max type.");
4320 }
4321
4322 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4323 // We can replace %x umin_seq %y with %x umin %y if either:
4324 // * %y being poison implies %x is also poison.
4325 // * %x cannot be the saturating value (e.g. zero for umin).
4326 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4327 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4328 SaturationPoint)) {
4329 SmallVector<const SCEV *> SeqOps = {Ops[i - 1], Ops[i]};
4330 Ops[i - 1] = getMinMaxExpr(
4331 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(Kind),
4332 SeqOps);
4333 Ops.erase(Ops.begin() + i);
4334 return getSequentialMinMaxExpr(Kind, Ops);
4335 }
4336 // Fold %x umin_seq %y to %x if %x ule %y.
4337 // TODO: We might be able to prove the predicate for a later operand.
4338 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4339 Ops.erase(Ops.begin() + i);
4340 return getSequentialMinMaxExpr(Kind, Ops);
4341 }
4342 }
4343
4344 // Okay, it looks like we really DO need an expr. Check to see if we
4345 // already have one, otherwise create a new one.
4346 FoldingSetNodeID ID;
4347 ID.AddInteger(Kind);
4348 for (const SCEV *Op : Ops)
4349 ID.AddPointer(Op);
4350 void *IP = nullptr;
4351 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4352 if (ExistingSCEV)
4353 return ExistingSCEV;
4354
4355 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
4356 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
4357 SCEV *S = new (SCEVAllocator)
4358 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4359
4360 UniqueSCEVs.InsertNode(S, IP);
4361 registerUser(S, Ops);
4362 return S;
4363 }
4364
getSMaxExpr(const SCEV * LHS,const SCEV * RHS)4365 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4366 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
4367 return getSMaxExpr(Ops);
4368 }
4369
getSMaxExpr(SmallVectorImpl<const SCEV * > & Ops)4370 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
4371 return getMinMaxExpr(scSMaxExpr, Ops);
4372 }
4373
getUMaxExpr(const SCEV * LHS,const SCEV * RHS)4374 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4375 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
4376 return getUMaxExpr(Ops);
4377 }
4378
getUMaxExpr(SmallVectorImpl<const SCEV * > & Ops)4379 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
4380 return getMinMaxExpr(scUMaxExpr, Ops);
4381 }
4382
getSMinExpr(const SCEV * LHS,const SCEV * RHS)4383 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
4384 const SCEV *RHS) {
4385 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4386 return getSMinExpr(Ops);
4387 }
4388
getSMinExpr(SmallVectorImpl<const SCEV * > & Ops)4389 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
4390 return getMinMaxExpr(scSMinExpr, Ops);
4391 }
4392
getUMinExpr(const SCEV * LHS,const SCEV * RHS,bool Sequential)4393 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, const SCEV *RHS,
4394 bool Sequential) {
4395 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4396 return getUMinExpr(Ops, Sequential);
4397 }
4398
getUMinExpr(SmallVectorImpl<const SCEV * > & Ops,bool Sequential)4399 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops,
4400 bool Sequential) {
4401 return Sequential ? getSequentialMinMaxExpr(scSequentialUMinExpr, Ops)
4402 : getMinMaxExpr(scUMinExpr, Ops);
4403 }
4404
4405 const SCEV *
getSizeOfExpr(Type * IntTy,TypeSize Size)4406 ScalarEvolution::getSizeOfExpr(Type *IntTy, TypeSize Size) {
4407 const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4408 if (Size.isScalable())
4409 Res = getMulExpr(Res, getVScale(IntTy));
4410 return Res;
4411 }
4412
getSizeOfExpr(Type * IntTy,Type * AllocTy)4413 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
4414 return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4415 }
4416
getStoreSizeOfExpr(Type * IntTy,Type * StoreTy)4417 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) {
4418 return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4419 }
4420
getOffsetOfExpr(Type * IntTy,StructType * STy,unsigned FieldNo)4421 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
4422 StructType *STy,
4423 unsigned FieldNo) {
4424 // We can bypass creating a target-independent constant expression and then
4425 // folding it back into a ConstantInt. This is just a compile-time
4426 // optimization.
4427 const StructLayout *SL = getDataLayout().getStructLayout(STy);
4428 assert(!SL->getSizeInBits().isScalable() &&
4429 "Cannot get offset for structure containing scalable vector types");
4430 return getConstant(IntTy, SL->getElementOffset(FieldNo));
4431 }
4432
getUnknown(Value * V)4433 const SCEV *ScalarEvolution::getUnknown(Value *V) {
4434 // Don't attempt to do anything other than create a SCEVUnknown object
4435 // here. createSCEV only calls getUnknown after checking for all other
4436 // interesting possibilities, and any other code that calls getUnknown
4437 // is doing so in order to hide a value from SCEV canonicalization.
4438
4439 FoldingSetNodeID ID;
4440 ID.AddInteger(scUnknown);
4441 ID.AddPointer(V);
4442 void *IP = nullptr;
4443 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
4444 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4445 "Stale SCEVUnknown in uniquing map!");
4446 return S;
4447 }
4448 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4449 FirstUnknown);
4450 FirstUnknown = cast<SCEVUnknown>(S);
4451 UniqueSCEVs.InsertNode(S, IP);
4452 return S;
4453 }
4454
4455 //===----------------------------------------------------------------------===//
4456 // Basic SCEV Analysis and PHI Idiom Recognition Code
4457 //
4458
4459 /// Test if values of the given type are analyzable within the SCEV
4460 /// framework. This primarily includes integer types, and it can optionally
4461 /// include pointer types if the ScalarEvolution class has access to
4462 /// target-specific information.
isSCEVable(Type * Ty) const4463 bool ScalarEvolution::isSCEVable(Type *Ty) const {
4464 // Integers and pointers are always SCEVable.
4465 return Ty->isIntOrPtrTy();
4466 }
4467
4468 /// Return the size in bits of the specified type, for which isSCEVable must
4469 /// return true.
getTypeSizeInBits(Type * Ty) const4470 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
4471 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4472 if (Ty->isPointerTy())
4473 return getDataLayout().getIndexTypeSizeInBits(Ty);
4474 return getDataLayout().getTypeSizeInBits(Ty);
4475 }
4476
4477 /// Return a type with the same bitwidth as the given type and which represents
4478 /// how SCEV will treat the given type, for which isSCEVable must return
4479 /// true. For pointer types, this is the pointer index sized integer type.
getEffectiveSCEVType(Type * Ty) const4480 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
4481 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4482
4483 if (Ty->isIntegerTy())
4484 return Ty;
4485
4486 // The only other support type is pointer.
4487 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4488 return getDataLayout().getIndexType(Ty);
4489 }
4490
getWiderType(Type * T1,Type * T2) const4491 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
4492 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4493 }
4494
instructionCouldExistWithOperands(const SCEV * A,const SCEV * B)4495 bool ScalarEvolution::instructionCouldExistWithOperands(const SCEV *A,
4496 const SCEV *B) {
4497 /// For a valid use point to exist, the defining scope of one operand
4498 /// must dominate the other.
4499 bool PreciseA, PreciseB;
4500 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4501 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4502 if (!PreciseA || !PreciseB)
4503 // Can't tell.
4504 return false;
4505 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4506 DT.dominates(ScopeB, ScopeA);
4507 }
4508
getCouldNotCompute()4509 const SCEV *ScalarEvolution::getCouldNotCompute() {
4510 return CouldNotCompute.get();
4511 }
4512
checkValidity(const SCEV * S) const4513 bool ScalarEvolution::checkValidity(const SCEV *S) const {
4514 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4515 auto *SU = dyn_cast<SCEVUnknown>(S);
4516 return SU && SU->getValue() == nullptr;
4517 });
4518
4519 return !ContainsNulls;
4520 }
4521
containsAddRecurrence(const SCEV * S)4522 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
4523 HasRecMapType::iterator I = HasRecMap.find(S);
4524 if (I != HasRecMap.end())
4525 return I->second;
4526
4527 bool FoundAddRec =
4528 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4529 HasRecMap.insert({S, FoundAddRec});
4530 return FoundAddRec;
4531 }
4532
4533 /// Return the ValueOffsetPair set for \p S. \p S can be represented
4534 /// by the value and offset from any ValueOffsetPair in the set.
getSCEVValues(const SCEV * S)4535 ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4536 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4537 if (SI == ExprValueMap.end())
4538 return std::nullopt;
4539 return SI->second.getArrayRef();
4540 }
4541
4542 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4543 /// cannot be used separately. eraseValueFromMap should be used to remove
4544 /// V from ValueExprMap and ExprValueMap at the same time.
eraseValueFromMap(Value * V)4545 void ScalarEvolution::eraseValueFromMap(Value *V) {
4546 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4547 if (I != ValueExprMap.end()) {
4548 auto EVIt = ExprValueMap.find(I->second);
4549 bool Removed = EVIt->second.remove(V);
4550 (void) Removed;
4551 assert(Removed && "Value not in ExprValueMap?");
4552 ValueExprMap.erase(I);
4553 }
4554 }
4555
insertValueToMap(Value * V,const SCEV * S)4556 void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4557 // A recursive query may have already computed the SCEV. It should be
4558 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4559 // inferred nowrap flags.
4560 auto It = ValueExprMap.find_as(V);
4561 if (It == ValueExprMap.end()) {
4562 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4563 ExprValueMap[S].insert(V);
4564 }
4565 }
4566
4567 /// Return an existing SCEV if it exists, otherwise analyze the expression and
4568 /// create a new one.
getSCEV(Value * V)4569 const SCEV *ScalarEvolution::getSCEV(Value *V) {
4570 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4571
4572 if (const SCEV *S = getExistingSCEV(V))
4573 return S;
4574 return createSCEVIter(V);
4575 }
4576
getExistingSCEV(Value * V)4577 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
4578 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4579
4580 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4581 if (I != ValueExprMap.end()) {
4582 const SCEV *S = I->second;
4583 assert(checkValidity(S) &&
4584 "existing SCEV has not been properly invalidated");
4585 return S;
4586 }
4587 return nullptr;
4588 }
4589
4590 /// Return a SCEV corresponding to -V = -1*V
getNegativeSCEV(const SCEV * V,SCEV::NoWrapFlags Flags)4591 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
4592 SCEV::NoWrapFlags Flags) {
4593 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4594 return getConstant(
4595 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4596
4597 Type *Ty = V->getType();
4598 Ty = getEffectiveSCEVType(Ty);
4599 return getMulExpr(V, getMinusOne(Ty), Flags);
4600 }
4601
4602 /// If Expr computes ~A, return A else return nullptr
MatchNotExpr(const SCEV * Expr)4603 static const SCEV *MatchNotExpr(const SCEV *Expr) {
4604 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
4605 if (!Add || Add->getNumOperands() != 2 ||
4606 !Add->getOperand(0)->isAllOnesValue())
4607 return nullptr;
4608
4609 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
4610 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
4611 !AddRHS->getOperand(0)->isAllOnesValue())
4612 return nullptr;
4613
4614 return AddRHS->getOperand(1);
4615 }
4616
4617 /// Return a SCEV corresponding to ~V = -1-V
getNotSCEV(const SCEV * V)4618 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
4619 assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4620
4621 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4622 return getConstant(
4623 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4624
4625 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4626 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4627 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4628 SmallVector<const SCEV *, 2> MatchedOperands;
4629 for (const SCEV *Operand : MME->operands()) {
4630 const SCEV *Matched = MatchNotExpr(Operand);
4631 if (!Matched)
4632 return (const SCEV *)nullptr;
4633 MatchedOperands.push_back(Matched);
4634 }
4635 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4636 MatchedOperands);
4637 };
4638 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4639 return Replaced;
4640 }
4641
4642 Type *Ty = V->getType();
4643 Ty = getEffectiveSCEVType(Ty);
4644 return getMinusSCEV(getMinusOne(Ty), V);
4645 }
4646
removePointerBase(const SCEV * P)4647 const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) {
4648 assert(P->getType()->isPointerTy());
4649
4650 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4651 // The base of an AddRec is the first operand.
4652 SmallVector<const SCEV *> Ops{AddRec->operands()};
4653 Ops[0] = removePointerBase(Ops[0]);
4654 // Don't try to transfer nowrap flags for now. We could in some cases
4655 // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4656 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
4657 }
4658 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4659 // The base of an Add is the pointer operand.
4660 SmallVector<const SCEV *> Ops{Add->operands()};
4661 const SCEV **PtrOp = nullptr;
4662 for (const SCEV *&AddOp : Ops) {
4663 if (AddOp->getType()->isPointerTy()) {
4664 assert(!PtrOp && "Cannot have multiple pointer ops");
4665 PtrOp = &AddOp;
4666 }
4667 }
4668 *PtrOp = removePointerBase(*PtrOp);
4669 // Don't try to transfer nowrap flags for now. We could in some cases
4670 // (for example, if the pointer operand of the Add is a SCEVUnknown).
4671 return getAddExpr(Ops);
4672 }
4673 // Any other expression must be a pointer base.
4674 return getZero(P->getType());
4675 }
4676
getMinusSCEV(const SCEV * LHS,const SCEV * RHS,SCEV::NoWrapFlags Flags,unsigned Depth)4677 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
4678 SCEV::NoWrapFlags Flags,
4679 unsigned Depth) {
4680 // Fast path: X - X --> 0.
4681 if (LHS == RHS)
4682 return getZero(LHS->getType());
4683
4684 // If we subtract two pointers with different pointer bases, bail.
4685 // Eventually, we're going to add an assertion to getMulExpr that we
4686 // can't multiply by a pointer.
4687 if (RHS->getType()->isPointerTy()) {
4688 if (!LHS->getType()->isPointerTy() ||
4689 getPointerBase(LHS) != getPointerBase(RHS))
4690 return getCouldNotCompute();
4691 LHS = removePointerBase(LHS);
4692 RHS = removePointerBase(RHS);
4693 }
4694
4695 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4696 // makes it so that we cannot make much use of NUW.
4697 auto AddFlags = SCEV::FlagAnyWrap;
4698 const bool RHSIsNotMinSigned =
4699 !getSignedRangeMin(RHS).isMinSignedValue();
4700 if (hasFlags(Flags, SCEV::FlagNSW)) {
4701 // Let M be the minimum representable signed value. Then (-1)*RHS
4702 // signed-wraps if and only if RHS is M. That can happen even for
4703 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4704 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4705 // (-1)*RHS, we need to prove that RHS != M.
4706 //
4707 // If LHS is non-negative and we know that LHS - RHS does not
4708 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4709 // either by proving that RHS > M or that LHS >= 0.
4710 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4711 AddFlags = SCEV::FlagNSW;
4712 }
4713 }
4714
4715 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4716 // RHS is NSW and LHS >= 0.
4717 //
4718 // The difficulty here is that the NSW flag may have been proven
4719 // relative to a loop that is to be found in a recurrence in LHS and
4720 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4721 // larger scope than intended.
4722 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4723
4724 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4725 }
4726
getTruncateOrZeroExtend(const SCEV * V,Type * Ty,unsigned Depth)4727 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4728 unsigned Depth) {
4729 Type *SrcTy = V->getType();
4730 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4731 "Cannot truncate or zero extend with non-integer arguments!");
4732 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4733 return V; // No conversion
4734 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4735 return getTruncateExpr(V, Ty, Depth);
4736 return getZeroExtendExpr(V, Ty, Depth);
4737 }
4738
getTruncateOrSignExtend(const SCEV * V,Type * Ty,unsigned Depth)4739 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4740 unsigned Depth) {
4741 Type *SrcTy = V->getType();
4742 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4743 "Cannot truncate or zero extend with non-integer arguments!");
4744 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4745 return V; // No conversion
4746 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4747 return getTruncateExpr(V, Ty, Depth);
4748 return getSignExtendExpr(V, Ty, Depth);
4749 }
4750
4751 const SCEV *
getNoopOrZeroExtend(const SCEV * V,Type * Ty)4752 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4753 Type *SrcTy = V->getType();
4754 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4755 "Cannot noop or zero extend with non-integer arguments!");
4756 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4757 "getNoopOrZeroExtend cannot truncate!");
4758 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4759 return V; // No conversion
4760 return getZeroExtendExpr(V, Ty);
4761 }
4762
4763 const SCEV *
getNoopOrSignExtend(const SCEV * V,Type * Ty)4764 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4765 Type *SrcTy = V->getType();
4766 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4767 "Cannot noop or sign extend with non-integer arguments!");
4768 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4769 "getNoopOrSignExtend cannot truncate!");
4770 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4771 return V; // No conversion
4772 return getSignExtendExpr(V, Ty);
4773 }
4774
4775 const SCEV *
getNoopOrAnyExtend(const SCEV * V,Type * Ty)4776 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4777 Type *SrcTy = V->getType();
4778 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4779 "Cannot noop or any extend with non-integer arguments!");
4780 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4781 "getNoopOrAnyExtend cannot truncate!");
4782 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4783 return V; // No conversion
4784 return getAnyExtendExpr(V, Ty);
4785 }
4786
4787 const SCEV *
getTruncateOrNoop(const SCEV * V,Type * Ty)4788 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4789 Type *SrcTy = V->getType();
4790 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4791 "Cannot truncate or noop with non-integer arguments!");
4792 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4793 "getTruncateOrNoop cannot extend!");
4794 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4795 return V; // No conversion
4796 return getTruncateExpr(V, Ty);
4797 }
4798
getUMaxFromMismatchedTypes(const SCEV * LHS,const SCEV * RHS)4799 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4800 const SCEV *RHS) {
4801 const SCEV *PromotedLHS = LHS;
4802 const SCEV *PromotedRHS = RHS;
4803
4804 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4805 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4806 else
4807 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4808
4809 return getUMaxExpr(PromotedLHS, PromotedRHS);
4810 }
4811
getUMinFromMismatchedTypes(const SCEV * LHS,const SCEV * RHS,bool Sequential)4812 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4813 const SCEV *RHS,
4814 bool Sequential) {
4815 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4816 return getUMinFromMismatchedTypes(Ops, Sequential);
4817 }
4818
4819 const SCEV *
getUMinFromMismatchedTypes(SmallVectorImpl<const SCEV * > & Ops,bool Sequential)4820 ScalarEvolution::getUMinFromMismatchedTypes(SmallVectorImpl<const SCEV *> &Ops,
4821 bool Sequential) {
4822 assert(!Ops.empty() && "At least one operand must be!");
4823 // Trivial case.
4824 if (Ops.size() == 1)
4825 return Ops[0];
4826
4827 // Find the max type first.
4828 Type *MaxType = nullptr;
4829 for (const auto *S : Ops)
4830 if (MaxType)
4831 MaxType = getWiderType(MaxType, S->getType());
4832 else
4833 MaxType = S->getType();
4834 assert(MaxType && "Failed to find maximum type!");
4835
4836 // Extend all ops to max type.
4837 SmallVector<const SCEV *, 2> PromotedOps;
4838 for (const auto *S : Ops)
4839 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4840
4841 // Generate umin.
4842 return getUMinExpr(PromotedOps, Sequential);
4843 }
4844
getPointerBase(const SCEV * V)4845 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4846 // A pointer operand may evaluate to a nonpointer expression, such as null.
4847 if (!V->getType()->isPointerTy())
4848 return V;
4849
4850 while (true) {
4851 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4852 V = AddRec->getStart();
4853 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4854 const SCEV *PtrOp = nullptr;
4855 for (const SCEV *AddOp : Add->operands()) {
4856 if (AddOp->getType()->isPointerTy()) {
4857 assert(!PtrOp && "Cannot have multiple pointer ops");
4858 PtrOp = AddOp;
4859 }
4860 }
4861 assert(PtrOp && "Must have pointer op");
4862 V = PtrOp;
4863 } else // Not something we can look further into.
4864 return V;
4865 }
4866 }
4867
4868 /// Push users of the given Instruction onto the given Worklist.
PushDefUseChildren(Instruction * I,SmallVectorImpl<Instruction * > & Worklist,SmallPtrSetImpl<Instruction * > & Visited)4869 static void PushDefUseChildren(Instruction *I,
4870 SmallVectorImpl<Instruction *> &Worklist,
4871 SmallPtrSetImpl<Instruction *> &Visited) {
4872 // Push the def-use children onto the Worklist stack.
4873 for (User *U : I->users()) {
4874 auto *UserInsn = cast<Instruction>(U);
4875 if (Visited.insert(UserInsn).second)
4876 Worklist.push_back(UserInsn);
4877 }
4878 }
4879
4880 namespace {
4881
4882 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4883 /// expression in case its Loop is L. If it is not L then
4884 /// if IgnoreOtherLoops is true then use AddRec itself
4885 /// otherwise rewrite cannot be done.
4886 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4887 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4888 public:
rewrite(const SCEV * S,const Loop * L,ScalarEvolution & SE,bool IgnoreOtherLoops=true)4889 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4890 bool IgnoreOtherLoops = true) {
4891 SCEVInitRewriter Rewriter(L, SE);
4892 const SCEV *Result = Rewriter.visit(S);
4893 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4894 return SE.getCouldNotCompute();
4895 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4896 ? SE.getCouldNotCompute()
4897 : Result;
4898 }
4899
visitUnknown(const SCEVUnknown * Expr)4900 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4901 if (!SE.isLoopInvariant(Expr, L))
4902 SeenLoopVariantSCEVUnknown = true;
4903 return Expr;
4904 }
4905
visitAddRecExpr(const SCEVAddRecExpr * Expr)4906 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4907 // Only re-write AddRecExprs for this loop.
4908 if (Expr->getLoop() == L)
4909 return Expr->getStart();
4910 SeenOtherLoops = true;
4911 return Expr;
4912 }
4913
hasSeenLoopVariantSCEVUnknown()4914 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4915
hasSeenOtherLoops()4916 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4917
4918 private:
SCEVInitRewriter(const Loop * L,ScalarEvolution & SE)4919 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4920 : SCEVRewriteVisitor(SE), L(L) {}
4921
4922 const Loop *L;
4923 bool SeenLoopVariantSCEVUnknown = false;
4924 bool SeenOtherLoops = false;
4925 };
4926
4927 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4928 /// increment expression in case its Loop is L. If it is not L then
4929 /// use AddRec itself.
4930 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4931 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4932 public:
rewrite(const SCEV * S,const Loop * L,ScalarEvolution & SE)4933 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4934 SCEVPostIncRewriter Rewriter(L, SE);
4935 const SCEV *Result = Rewriter.visit(S);
4936 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4937 ? SE.getCouldNotCompute()
4938 : Result;
4939 }
4940
visitUnknown(const SCEVUnknown * Expr)4941 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4942 if (!SE.isLoopInvariant(Expr, L))
4943 SeenLoopVariantSCEVUnknown = true;
4944 return Expr;
4945 }
4946
visitAddRecExpr(const SCEVAddRecExpr * Expr)4947 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4948 // Only re-write AddRecExprs for this loop.
4949 if (Expr->getLoop() == L)
4950 return Expr->getPostIncExpr(SE);
4951 SeenOtherLoops = true;
4952 return Expr;
4953 }
4954
hasSeenLoopVariantSCEVUnknown()4955 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4956
hasSeenOtherLoops()4957 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4958
4959 private:
SCEVPostIncRewriter(const Loop * L,ScalarEvolution & SE)4960 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4961 : SCEVRewriteVisitor(SE), L(L) {}
4962
4963 const Loop *L;
4964 bool SeenLoopVariantSCEVUnknown = false;
4965 bool SeenOtherLoops = false;
4966 };
4967
4968 /// This class evaluates the compare condition by matching it against the
4969 /// condition of loop latch. If there is a match we assume a true value
4970 /// for the condition while building SCEV nodes.
4971 class SCEVBackedgeConditionFolder
4972 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4973 public:
rewrite(const SCEV * S,const Loop * L,ScalarEvolution & SE)4974 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4975 ScalarEvolution &SE) {
4976 bool IsPosBECond = false;
4977 Value *BECond = nullptr;
4978 if (BasicBlock *Latch = L->getLoopLatch()) {
4979 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4980 if (BI && BI->isConditional()) {
4981 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4982 "Both outgoing branches should not target same header!");
4983 BECond = BI->getCondition();
4984 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4985 } else {
4986 return S;
4987 }
4988 }
4989 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4990 return Rewriter.visit(S);
4991 }
4992
visitUnknown(const SCEVUnknown * Expr)4993 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4994 const SCEV *Result = Expr;
4995 bool InvariantF = SE.isLoopInvariant(Expr, L);
4996
4997 if (!InvariantF) {
4998 Instruction *I = cast<Instruction>(Expr->getValue());
4999 switch (I->getOpcode()) {
5000 case Instruction::Select: {
5001 SelectInst *SI = cast<SelectInst>(I);
5002 std::optional<const SCEV *> Res =
5003 compareWithBackedgeCondition(SI->getCondition());
5004 if (Res) {
5005 bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
5006 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
5007 }
5008 break;
5009 }
5010 default: {
5011 std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
5012 if (Res)
5013 Result = *Res;
5014 break;
5015 }
5016 }
5017 }
5018 return Result;
5019 }
5020
5021 private:
SCEVBackedgeConditionFolder(const Loop * L,Value * BECond,bool IsPosBECond,ScalarEvolution & SE)5022 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
5023 bool IsPosBECond, ScalarEvolution &SE)
5024 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
5025 IsPositiveBECond(IsPosBECond) {}
5026
5027 std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
5028
5029 const Loop *L;
5030 /// Loop back condition.
5031 Value *BackedgeCond = nullptr;
5032 /// Set to true if loop back is on positive branch condition.
5033 bool IsPositiveBECond;
5034 };
5035
5036 std::optional<const SCEV *>
compareWithBackedgeCondition(Value * IC)5037 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
5038
5039 // If value matches the backedge condition for loop latch,
5040 // then return a constant evolution node based on loopback
5041 // branch taken.
5042 if (BackedgeCond == IC)
5043 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
5044 : SE.getZero(Type::getInt1Ty(SE.getContext()));
5045 return std::nullopt;
5046 }
5047
5048 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
5049 public:
rewrite(const SCEV * S,const Loop * L,ScalarEvolution & SE)5050 static const SCEV *rewrite(const SCEV *S, const Loop *L,
5051 ScalarEvolution &SE) {
5052 SCEVShiftRewriter Rewriter(L, SE);
5053 const SCEV *Result = Rewriter.visit(S);
5054 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
5055 }
5056
visitUnknown(const SCEVUnknown * Expr)5057 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5058 // Only allow AddRecExprs for this loop.
5059 if (!SE.isLoopInvariant(Expr, L))
5060 Valid = false;
5061 return Expr;
5062 }
5063
visitAddRecExpr(const SCEVAddRecExpr * Expr)5064 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5065 if (Expr->getLoop() == L && Expr->isAffine())
5066 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
5067 Valid = false;
5068 return Expr;
5069 }
5070
isValid()5071 bool isValid() { return Valid; }
5072
5073 private:
SCEVShiftRewriter(const Loop * L,ScalarEvolution & SE)5074 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
5075 : SCEVRewriteVisitor(SE), L(L) {}
5076
5077 const Loop *L;
5078 bool Valid = true;
5079 };
5080
5081 } // end anonymous namespace
5082
5083 SCEV::NoWrapFlags
proveNoWrapViaConstantRanges(const SCEVAddRecExpr * AR)5084 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
5085 if (!AR->isAffine())
5086 return SCEV::FlagAnyWrap;
5087
5088 using OBO = OverflowingBinaryOperator;
5089
5090 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
5091
5092 if (!AR->hasNoSelfWrap()) {
5093 const SCEV *BECount = getConstantMaxBackedgeTakenCount(AR->getLoop());
5094 if (const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(BECount)) {
5095 ConstantRange StepCR = getSignedRange(AR->getStepRecurrence(*this));
5096 const APInt &BECountAP = BECountMax->getAPInt();
5097 unsigned NoOverflowBitWidth =
5098 BECountAP.getActiveBits() + StepCR.getMinSignedBits();
5099 if (NoOverflowBitWidth <= getTypeSizeInBits(AR->getType()))
5100 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNW);
5101 }
5102 }
5103
5104 if (!AR->hasNoSignedWrap()) {
5105 ConstantRange AddRecRange = getSignedRange(AR);
5106 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
5107
5108 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
5109 Instruction::Add, IncRange, OBO::NoSignedWrap);
5110 if (NSWRegion.contains(AddRecRange))
5111 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
5112 }
5113
5114 if (!AR->hasNoUnsignedWrap()) {
5115 ConstantRange AddRecRange = getUnsignedRange(AR);
5116 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
5117
5118 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
5119 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
5120 if (NUWRegion.contains(AddRecRange))
5121 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
5122 }
5123
5124 return Result;
5125 }
5126
5127 SCEV::NoWrapFlags
proveNoSignedWrapViaInduction(const SCEVAddRecExpr * AR)5128 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5129 SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
5130
5131 if (AR->hasNoSignedWrap())
5132 return Result;
5133
5134 if (!AR->isAffine())
5135 return Result;
5136
5137 // This function can be expensive, only try to prove NSW once per AddRec.
5138 if (!SignedWrapViaInductionTried.insert(AR).second)
5139 return Result;
5140
5141 const SCEV *Step = AR->getStepRecurrence(*this);
5142 const Loop *L = AR->getLoop();
5143
5144 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5145 // Note that this serves two purposes: It filters out loops that are
5146 // simply not analyzable, and it covers the case where this code is
5147 // being called from within backedge-taken count analysis, such that
5148 // attempting to ask for the backedge-taken count would likely result
5149 // in infinite recursion. In the later case, the analysis code will
5150 // cope with a conservative value, and it will take care to purge
5151 // that value once it has finished.
5152 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5153
5154 // Normally, in the cases we can prove no-overflow via a
5155 // backedge guarding condition, we can also compute a backedge
5156 // taken count for the loop. The exceptions are assumptions and
5157 // guards present in the loop -- SCEV is not great at exploiting
5158 // these to compute max backedge taken counts, but can still use
5159 // these to prove lack of overflow. Use this fact to avoid
5160 // doing extra work that may not pay off.
5161
5162 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5163 AC.assumptions().empty())
5164 return Result;
5165
5166 // If the backedge is guarded by a comparison with the pre-inc value the
5167 // addrec is safe. Also, if the entry is guarded by a comparison with the
5168 // start value and the backedge is guarded by a comparison with the post-inc
5169 // value, the addrec is safe.
5170 ICmpInst::Predicate Pred;
5171 const SCEV *OverflowLimit =
5172 getSignedOverflowLimitForStep(Step, &Pred, this);
5173 if (OverflowLimit &&
5174 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5175 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
5176 Result = setFlags(Result, SCEV::FlagNSW);
5177 }
5178 return Result;
5179 }
5180 SCEV::NoWrapFlags
proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr * AR)5181 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5182 SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
5183
5184 if (AR->hasNoUnsignedWrap())
5185 return Result;
5186
5187 if (!AR->isAffine())
5188 return Result;
5189
5190 // This function can be expensive, only try to prove NUW once per AddRec.
5191 if (!UnsignedWrapViaInductionTried.insert(AR).second)
5192 return Result;
5193
5194 const SCEV *Step = AR->getStepRecurrence(*this);
5195 unsigned BitWidth = getTypeSizeInBits(AR->getType());
5196 const Loop *L = AR->getLoop();
5197
5198 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5199 // Note that this serves two purposes: It filters out loops that are
5200 // simply not analyzable, and it covers the case where this code is
5201 // being called from within backedge-taken count analysis, such that
5202 // attempting to ask for the backedge-taken count would likely result
5203 // in infinite recursion. In the later case, the analysis code will
5204 // cope with a conservative value, and it will take care to purge
5205 // that value once it has finished.
5206 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5207
5208 // Normally, in the cases we can prove no-overflow via a
5209 // backedge guarding condition, we can also compute a backedge
5210 // taken count for the loop. The exceptions are assumptions and
5211 // guards present in the loop -- SCEV is not great at exploiting
5212 // these to compute max backedge taken counts, but can still use
5213 // these to prove lack of overflow. Use this fact to avoid
5214 // doing extra work that may not pay off.
5215
5216 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5217 AC.assumptions().empty())
5218 return Result;
5219
5220 // If the backedge is guarded by a comparison with the pre-inc value the
5221 // addrec is safe. Also, if the entry is guarded by a comparison with the
5222 // start value and the backedge is guarded by a comparison with the post-inc
5223 // value, the addrec is safe.
5224 if (isKnownPositive(Step)) {
5225 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
5226 getUnsignedRangeMax(Step));
5227 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
5228 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
5229 Result = setFlags(Result, SCEV::FlagNUW);
5230 }
5231 }
5232
5233 return Result;
5234 }
5235
5236 namespace {
5237
5238 /// Represents an abstract binary operation. This may exist as a
5239 /// normal instruction or constant expression, or may have been
5240 /// derived from an expression tree.
5241 struct BinaryOp {
5242 unsigned Opcode;
5243 Value *LHS;
5244 Value *RHS;
5245 bool IsNSW = false;
5246 bool IsNUW = false;
5247
5248 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5249 /// constant expression.
5250 Operator *Op = nullptr;
5251
BinaryOp__anon8884d99e1611::BinaryOp5252 explicit BinaryOp(Operator *Op)
5253 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5254 Op(Op) {
5255 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5256 IsNSW = OBO->hasNoSignedWrap();
5257 IsNUW = OBO->hasNoUnsignedWrap();
5258 }
5259 }
5260
BinaryOp__anon8884d99e1611::BinaryOp5261 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5262 bool IsNUW = false)
5263 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5264 };
5265
5266 } // end anonymous namespace
5267
5268 /// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
MatchBinaryOp(Value * V,const DataLayout & DL,AssumptionCache & AC,const DominatorTree & DT,const Instruction * CxtI)5269 static std::optional<BinaryOp> MatchBinaryOp(Value *V, const DataLayout &DL,
5270 AssumptionCache &AC,
5271 const DominatorTree &DT,
5272 const Instruction *CxtI) {
5273 auto *Op = dyn_cast<Operator>(V);
5274 if (!Op)
5275 return std::nullopt;
5276
5277 // Implementation detail: all the cleverness here should happen without
5278 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5279 // SCEV expressions when possible, and we should not break that.
5280
5281 switch (Op->getOpcode()) {
5282 case Instruction::Add:
5283 case Instruction::Sub:
5284 case Instruction::Mul:
5285 case Instruction::UDiv:
5286 case Instruction::URem:
5287 case Instruction::And:
5288 case Instruction::AShr:
5289 case Instruction::Shl:
5290 return BinaryOp(Op);
5291
5292 case Instruction::Or: {
5293 // Convert or disjoint into add nuw nsw.
5294 if (cast<PossiblyDisjointInst>(Op)->isDisjoint())
5295 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
5296 /*IsNSW=*/true, /*IsNUW=*/true);
5297 return BinaryOp(Op);
5298 }
5299
5300 case Instruction::Xor:
5301 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5302 // If the RHS of the xor is a signmask, then this is just an add.
5303 // Instcombine turns add of signmask into xor as a strength reduction step.
5304 if (RHSC->getValue().isSignMask())
5305 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5306 // Binary `xor` is a bit-wise `add`.
5307 if (V->getType()->isIntegerTy(1))
5308 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5309 return BinaryOp(Op);
5310
5311 case Instruction::LShr:
5312 // Turn logical shift right of a constant into a unsigned divide.
5313 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5314 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5315
5316 // If the shift count is not less than the bitwidth, the result of
5317 // the shift is undefined. Don't try to analyze it, because the
5318 // resolution chosen here may differ from the resolution chosen in
5319 // other parts of the compiler.
5320 if (SA->getValue().ult(BitWidth)) {
5321 Constant *X =
5322 ConstantInt::get(SA->getContext(),
5323 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5324 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5325 }
5326 }
5327 return BinaryOp(Op);
5328
5329 case Instruction::ExtractValue: {
5330 auto *EVI = cast<ExtractValueInst>(Op);
5331 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5332 break;
5333
5334 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5335 if (!WO)
5336 break;
5337
5338 Instruction::BinaryOps BinOp = WO->getBinaryOp();
5339 bool Signed = WO->isSigned();
5340 // TODO: Should add nuw/nsw flags for mul as well.
5341 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5342 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5343
5344 // Now that we know that all uses of the arithmetic-result component of
5345 // CI are guarded by the overflow check, we can go ahead and pretend
5346 // that the arithmetic is non-overflowing.
5347 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5348 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5349 }
5350
5351 default:
5352 break;
5353 }
5354
5355 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5356 // semantics as a Sub, return a binary sub expression.
5357 if (auto *II = dyn_cast<IntrinsicInst>(V))
5358 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5359 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5360
5361 return std::nullopt;
5362 }
5363
5364 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
5365 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5366 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5367 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5368 /// follows one of the following patterns:
5369 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5370 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5371 /// If the SCEV expression of \p Op conforms with one of the expected patterns
5372 /// we return the type of the truncation operation, and indicate whether the
5373 /// truncated type should be treated as signed/unsigned by setting
5374 /// \p Signed to true/false, respectively.
isSimpleCastedPHI(const SCEV * Op,const SCEVUnknown * SymbolicPHI,bool & Signed,ScalarEvolution & SE)5375 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5376 bool &Signed, ScalarEvolution &SE) {
5377 // The case where Op == SymbolicPHI (that is, with no type conversions on
5378 // the way) is handled by the regular add recurrence creating logic and
5379 // would have already been triggered in createAddRecForPHI. Reaching it here
5380 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5381 // because one of the other operands of the SCEVAddExpr updating this PHI is
5382 // not invariant).
5383 //
5384 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5385 // this case predicates that allow us to prove that Op == SymbolicPHI will
5386 // be added.
5387 if (Op == SymbolicPHI)
5388 return nullptr;
5389
5390 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5391 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5392 if (SourceBits != NewBits)
5393 return nullptr;
5394
5395 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
5396 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
5397 if (!SExt && !ZExt)
5398 return nullptr;
5399 const SCEVTruncateExpr *Trunc =
5400 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
5401 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
5402 if (!Trunc)
5403 return nullptr;
5404 const SCEV *X = Trunc->getOperand();
5405 if (X != SymbolicPHI)
5406 return nullptr;
5407 Signed = SExt != nullptr;
5408 return Trunc->getType();
5409 }
5410
isIntegerLoopHeaderPHI(const PHINode * PN,LoopInfo & LI)5411 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5412 if (!PN->getType()->isIntegerTy())
5413 return nullptr;
5414 const Loop *L = LI.getLoopFor(PN->getParent());
5415 if (!L || L->getHeader() != PN->getParent())
5416 return nullptr;
5417 return L;
5418 }
5419
5420 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5421 // computation that updates the phi follows the following pattern:
5422 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5423 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
5424 // If so, try to see if it can be rewritten as an AddRecExpr under some
5425 // Predicates. If successful, return them as a pair. Also cache the results
5426 // of the analysis.
5427 //
5428 // Example usage scenario:
5429 // Say the Rewriter is called for the following SCEV:
5430 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5431 // where:
5432 // %X = phi i64 (%Start, %BEValue)
5433 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5434 // and call this function with %SymbolicPHI = %X.
5435 //
5436 // The analysis will find that the value coming around the backedge has
5437 // the following SCEV:
5438 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5439 // Upon concluding that this matches the desired pattern, the function
5440 // will return the pair {NewAddRec, SmallPredsVec} where:
5441 // NewAddRec = {%Start,+,%Step}
5442 // SmallPredsVec = {P1, P2, P3} as follows:
5443 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5444 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5445 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5446 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5447 // under the predicates {P1,P2,P3}.
5448 // This predicated rewrite will be cached in PredicatedSCEVRewrites:
5449 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5450 //
5451 // TODO's:
5452 //
5453 // 1) Extend the Induction descriptor to also support inductions that involve
5454 // casts: When needed (namely, when we are called in the context of the
5455 // vectorizer induction analysis), a Set of cast instructions will be
5456 // populated by this method, and provided back to isInductionPHI. This is
5457 // needed to allow the vectorizer to properly record them to be ignored by
5458 // the cost model and to avoid vectorizing them (otherwise these casts,
5459 // which are redundant under the runtime overflow checks, will be
5460 // vectorized, which can be costly).
5461 //
5462 // 2) Support additional induction/PHISCEV patterns: We also want to support
5463 // inductions where the sext-trunc / zext-trunc operations (partly) occur
5464 // after the induction update operation (the induction increment):
5465 //
5466 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5467 // which correspond to a phi->add->trunc->sext/zext->phi update chain.
5468 //
5469 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5470 // which correspond to a phi->trunc->add->sext/zext->phi update chain.
5471 //
5472 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
5473 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
createAddRecFromPHIWithCastsImpl(const SCEVUnknown * SymbolicPHI)5474 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5475 SmallVector<const SCEVPredicate *, 3> Predicates;
5476
5477 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5478 // return an AddRec expression under some predicate.
5479
5480 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5481 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5482 assert(L && "Expecting an integer loop header phi");
5483
5484 // The loop may have multiple entrances or multiple exits; we can analyze
5485 // this phi as an addrec if it has a unique entry value and a unique
5486 // backedge value.
5487 Value *BEValueV = nullptr, *StartValueV = nullptr;
5488 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5489 Value *V = PN->getIncomingValue(i);
5490 if (L->contains(PN->getIncomingBlock(i))) {
5491 if (!BEValueV) {
5492 BEValueV = V;
5493 } else if (BEValueV != V) {
5494 BEValueV = nullptr;
5495 break;
5496 }
5497 } else if (!StartValueV) {
5498 StartValueV = V;
5499 } else if (StartValueV != V) {
5500 StartValueV = nullptr;
5501 break;
5502 }
5503 }
5504 if (!BEValueV || !StartValueV)
5505 return std::nullopt;
5506
5507 const SCEV *BEValue = getSCEV(BEValueV);
5508
5509 // If the value coming around the backedge is an add with the symbolic
5510 // value we just inserted, possibly with casts that we can ignore under
5511 // an appropriate runtime guard, then we found a simple induction variable!
5512 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5513 if (!Add)
5514 return std::nullopt;
5515
5516 // If there is a single occurrence of the symbolic value, possibly
5517 // casted, replace it with a recurrence.
5518 unsigned FoundIndex = Add->getNumOperands();
5519 Type *TruncTy = nullptr;
5520 bool Signed;
5521 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5522 if ((TruncTy =
5523 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5524 if (FoundIndex == e) {
5525 FoundIndex = i;
5526 break;
5527 }
5528
5529 if (FoundIndex == Add->getNumOperands())
5530 return std::nullopt;
5531
5532 // Create an add with everything but the specified operand.
5533 SmallVector<const SCEV *, 8> Ops;
5534 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5535 if (i != FoundIndex)
5536 Ops.push_back(Add->getOperand(i));
5537 const SCEV *Accum = getAddExpr(Ops);
5538
5539 // The runtime checks will not be valid if the step amount is
5540 // varying inside the loop.
5541 if (!isLoopInvariant(Accum, L))
5542 return std::nullopt;
5543
5544 // *** Part2: Create the predicates
5545
5546 // Analysis was successful: we have a phi-with-cast pattern for which we
5547 // can return an AddRec expression under the following predicates:
5548 //
5549 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5550 // fits within the truncated type (does not overflow) for i = 0 to n-1.
5551 // P2: An Equal predicate that guarantees that
5552 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5553 // P3: An Equal predicate that guarantees that
5554 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5555 //
5556 // As we next prove, the above predicates guarantee that:
5557 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5558 //
5559 //
5560 // More formally, we want to prove that:
5561 // Expr(i+1) = Start + (i+1) * Accum
5562 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5563 //
5564 // Given that:
5565 // 1) Expr(0) = Start
5566 // 2) Expr(1) = Start + Accum
5567 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5568 // 3) Induction hypothesis (step i):
5569 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5570 //
5571 // Proof:
5572 // Expr(i+1) =
5573 // = Start + (i+1)*Accum
5574 // = (Start + i*Accum) + Accum
5575 // = Expr(i) + Accum
5576 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5577 // :: from step i
5578 //
5579 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5580 //
5581 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5582 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
5583 // + Accum :: from P3
5584 //
5585 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5586 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5587 //
5588 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5589 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5590 //
5591 // By induction, the same applies to all iterations 1<=i<n:
5592 //
5593
5594 // Create a truncated addrec for which we will add a no overflow check (P1).
5595 const SCEV *StartVal = getSCEV(StartValueV);
5596 const SCEV *PHISCEV =
5597 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5598 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5599
5600 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5601 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5602 // will be constant.
5603 //
5604 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5605 // add P1.
5606 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5607 SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
5608 Signed ? SCEVWrapPredicate::IncrementNSSW
5609 : SCEVWrapPredicate::IncrementNUSW;
5610 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5611 Predicates.push_back(AddRecPred);
5612 }
5613
5614 // Create the Equal Predicates P2,P3:
5615
5616 // It is possible that the predicates P2 and/or P3 are computable at
5617 // compile time due to StartVal and/or Accum being constants.
5618 // If either one is, then we can check that now and escape if either P2
5619 // or P3 is false.
5620
5621 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5622 // for each of StartVal and Accum
5623 auto getExtendedExpr = [&](const SCEV *Expr,
5624 bool CreateSignExtend) -> const SCEV * {
5625 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5626 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5627 const SCEV *ExtendedExpr =
5628 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5629 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5630 return ExtendedExpr;
5631 };
5632
5633 // Given:
5634 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5635 // = getExtendedExpr(Expr)
5636 // Determine whether the predicate P: Expr == ExtendedExpr
5637 // is known to be false at compile time
5638 auto PredIsKnownFalse = [&](const SCEV *Expr,
5639 const SCEV *ExtendedExpr) -> bool {
5640 return Expr != ExtendedExpr &&
5641 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5642 };
5643
5644 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5645 if (PredIsKnownFalse(StartVal, StartExtended)) {
5646 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5647 return std::nullopt;
5648 }
5649
5650 // The Step is always Signed (because the overflow checks are either
5651 // NSSW or NUSW)
5652 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5653 if (PredIsKnownFalse(Accum, AccumExtended)) {
5654 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5655 return std::nullopt;
5656 }
5657
5658 auto AppendPredicate = [&](const SCEV *Expr,
5659 const SCEV *ExtendedExpr) -> void {
5660 if (Expr != ExtendedExpr &&
5661 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5662 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5663 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5664 Predicates.push_back(Pred);
5665 }
5666 };
5667
5668 AppendPredicate(StartVal, StartExtended);
5669 AppendPredicate(Accum, AccumExtended);
5670
5671 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5672 // which the casts had been folded away. The caller can rewrite SymbolicPHI
5673 // into NewAR if it will also add the runtime overflow checks specified in
5674 // Predicates.
5675 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5676
5677 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5678 std::make_pair(NewAR, Predicates);
5679 // Remember the result of the analysis for this SCEV at this locayyytion.
5680 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5681 return PredRewrite;
5682 }
5683
5684 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
createAddRecFromPHIWithCasts(const SCEVUnknown * SymbolicPHI)5685 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
5686 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5687 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5688 if (!L)
5689 return std::nullopt;
5690
5691 // Check to see if we already analyzed this PHI.
5692 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5693 if (I != PredicatedSCEVRewrites.end()) {
5694 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5695 I->second;
5696 // Analysis was done before and failed to create an AddRec:
5697 if (Rewrite.first == SymbolicPHI)
5698 return std::nullopt;
5699 // Analysis was done before and succeeded to create an AddRec under
5700 // a predicate:
5701 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5702 assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5703 return Rewrite;
5704 }
5705
5706 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5707 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5708
5709 // Record in the cache that the analysis failed
5710 if (!Rewrite) {
5711 SmallVector<const SCEVPredicate *, 3> Predicates;
5712 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5713 return std::nullopt;
5714 }
5715
5716 return Rewrite;
5717 }
5718
5719 // FIXME: This utility is currently required because the Rewriter currently
5720 // does not rewrite this expression:
5721 // {0, +, (sext ix (trunc iy to ix) to iy)}
5722 // into {0, +, %step},
5723 // even when the following Equal predicate exists:
5724 // "%step == (sext ix (trunc iy to ix) to iy)".
areAddRecsEqualWithPreds(const SCEVAddRecExpr * AR1,const SCEVAddRecExpr * AR2) const5725 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5726 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
5727 if (AR1 == AR2)
5728 return true;
5729
5730 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5731 if (Expr1 != Expr2 && !Preds->implies(SE.getEqualPredicate(Expr1, Expr2)) &&
5732 !Preds->implies(SE.getEqualPredicate(Expr2, Expr1)))
5733 return false;
5734 return true;
5735 };
5736
5737 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5738 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5739 return false;
5740 return true;
5741 }
5742
5743 /// A helper function for createAddRecFromPHI to handle simple cases.
5744 ///
5745 /// This function tries to find an AddRec expression for the simplest (yet most
5746 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5747 /// If it fails, createAddRecFromPHI will use a more general, but slow,
5748 /// technique for finding the AddRec expression.
createSimpleAffineAddRec(PHINode * PN,Value * BEValueV,Value * StartValueV)5749 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5750 Value *BEValueV,
5751 Value *StartValueV) {
5752 const Loop *L = LI.getLoopFor(PN->getParent());
5753 assert(L && L->getHeader() == PN->getParent());
5754 assert(BEValueV && StartValueV);
5755
5756 auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN);
5757 if (!BO)
5758 return nullptr;
5759
5760 if (BO->Opcode != Instruction::Add)
5761 return nullptr;
5762
5763 const SCEV *Accum = nullptr;
5764 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5765 Accum = getSCEV(BO->RHS);
5766 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5767 Accum = getSCEV(BO->LHS);
5768
5769 if (!Accum)
5770 return nullptr;
5771
5772 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5773 if (BO->IsNUW)
5774 Flags = setFlags(Flags, SCEV::FlagNUW);
5775 if (BO->IsNSW)
5776 Flags = setFlags(Flags, SCEV::FlagNSW);
5777
5778 const SCEV *StartVal = getSCEV(StartValueV);
5779 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5780 insertValueToMap(PN, PHISCEV);
5781
5782 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5783 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR),
5784 (SCEV::NoWrapFlags)(AR->getNoWrapFlags() |
5785 proveNoWrapViaConstantRanges(AR)));
5786 }
5787
5788 // We can add Flags to the post-inc expression only if we
5789 // know that it is *undefined behavior* for BEValueV to
5790 // overflow.
5791 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5792 assert(isLoopInvariant(Accum, L) &&
5793 "Accum is defined outside L, but is not invariant?");
5794 if (isAddRecNeverPoison(BEInst, L))
5795 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5796 }
5797
5798 return PHISCEV;
5799 }
5800
createAddRecFromPHI(PHINode * PN)5801 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5802 const Loop *L = LI.getLoopFor(PN->getParent());
5803 if (!L || L->getHeader() != PN->getParent())
5804 return nullptr;
5805
5806 // The loop may have multiple entrances or multiple exits; we can analyze
5807 // this phi as an addrec if it has a unique entry value and a unique
5808 // backedge value.
5809 Value *BEValueV = nullptr, *StartValueV = nullptr;
5810 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5811 Value *V = PN->getIncomingValue(i);
5812 if (L->contains(PN->getIncomingBlock(i))) {
5813 if (!BEValueV) {
5814 BEValueV = V;
5815 } else if (BEValueV != V) {
5816 BEValueV = nullptr;
5817 break;
5818 }
5819 } else if (!StartValueV) {
5820 StartValueV = V;
5821 } else if (StartValueV != V) {
5822 StartValueV = nullptr;
5823 break;
5824 }
5825 }
5826 if (!BEValueV || !StartValueV)
5827 return nullptr;
5828
5829 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5830 "PHI node already processed?");
5831
5832 // First, try to find AddRec expression without creating a fictituos symbolic
5833 // value for PN.
5834 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5835 return S;
5836
5837 // Handle PHI node value symbolically.
5838 const SCEV *SymbolicName = getUnknown(PN);
5839 insertValueToMap(PN, SymbolicName);
5840
5841 // Using this symbolic name for the PHI, analyze the value coming around
5842 // the back-edge.
5843 const SCEV *BEValue = getSCEV(BEValueV);
5844
5845 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5846 // has a special value for the first iteration of the loop.
5847
5848 // If the value coming around the backedge is an add with the symbolic
5849 // value we just inserted, then we found a simple induction variable!
5850 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5851 // If there is a single occurrence of the symbolic value, replace it
5852 // with a recurrence.
5853 unsigned FoundIndex = Add->getNumOperands();
5854 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5855 if (Add->getOperand(i) == SymbolicName)
5856 if (FoundIndex == e) {
5857 FoundIndex = i;
5858 break;
5859 }
5860
5861 if (FoundIndex != Add->getNumOperands()) {
5862 // Create an add with everything but the specified operand.
5863 SmallVector<const SCEV *, 8> Ops;
5864 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5865 if (i != FoundIndex)
5866 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5867 L, *this));
5868 const SCEV *Accum = getAddExpr(Ops);
5869
5870 // This is not a valid addrec if the step amount is varying each
5871 // loop iteration, but is not itself an addrec in this loop.
5872 if (isLoopInvariant(Accum, L) ||
5873 (isa<SCEVAddRecExpr>(Accum) &&
5874 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5875 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5876
5877 if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
5878 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5879 if (BO->IsNUW)
5880 Flags = setFlags(Flags, SCEV::FlagNUW);
5881 if (BO->IsNSW)
5882 Flags = setFlags(Flags, SCEV::FlagNSW);
5883 }
5884 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5885 if (GEP->getOperand(0) == PN) {
5886 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
5887 // If the increment has any nowrap flags, then we know the address
5888 // space cannot be wrapped around.
5889 if (NW != GEPNoWrapFlags::none())
5890 Flags = setFlags(Flags, SCEV::FlagNW);
5891 // If the GEP is nuw or nusw with non-negative offset, we know that
5892 // no unsigned wrap occurs. We cannot set the nsw flag as only the
5893 // offset is treated as signed, while the base is unsigned.
5894 if (NW.hasNoUnsignedWrap() ||
5895 (NW.hasNoUnsignedSignedWrap() && isKnownNonNegative(Accum)))
5896 Flags = setFlags(Flags, SCEV::FlagNUW);
5897 }
5898
5899 // We cannot transfer nuw and nsw flags from subtraction
5900 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5901 // for instance.
5902 }
5903
5904 const SCEV *StartVal = getSCEV(StartValueV);
5905 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5906
5907 // Okay, for the entire analysis of this edge we assumed the PHI
5908 // to be symbolic. We now need to go back and purge all of the
5909 // entries for the scalars that use the symbolic expression.
5910 forgetMemoizedResults(SymbolicName);
5911 insertValueToMap(PN, PHISCEV);
5912
5913 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5914 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR),
5915 (SCEV::NoWrapFlags)(AR->getNoWrapFlags() |
5916 proveNoWrapViaConstantRanges(AR)));
5917 }
5918
5919 // We can add Flags to the post-inc expression only if we
5920 // know that it is *undefined behavior* for BEValueV to
5921 // overflow.
5922 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5923 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5924 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5925
5926 return PHISCEV;
5927 }
5928 }
5929 } else {
5930 // Otherwise, this could be a loop like this:
5931 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5932 // In this case, j = {1,+,1} and BEValue is j.
5933 // Because the other in-value of i (0) fits the evolution of BEValue
5934 // i really is an addrec evolution.
5935 //
5936 // We can generalize this saying that i is the shifted value of BEValue
5937 // by one iteration:
5938 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5939 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5940 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5941 if (Shifted != getCouldNotCompute() &&
5942 Start != getCouldNotCompute()) {
5943 const SCEV *StartVal = getSCEV(StartValueV);
5944 if (Start == StartVal) {
5945 // Okay, for the entire analysis of this edge we assumed the PHI
5946 // to be symbolic. We now need to go back and purge all of the
5947 // entries for the scalars that use the symbolic expression.
5948 forgetMemoizedResults(SymbolicName);
5949 insertValueToMap(PN, Shifted);
5950 return Shifted;
5951 }
5952 }
5953 }
5954
5955 // Remove the temporary PHI node SCEV that has been inserted while intending
5956 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5957 // as it will prevent later (possibly simpler) SCEV expressions to be added
5958 // to the ValueExprMap.
5959 eraseValueFromMap(PN);
5960
5961 return nullptr;
5962 }
5963
5964 // Try to match a control flow sequence that branches out at BI and merges back
5965 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5966 // match.
BrPHIToSelect(DominatorTree & DT,BranchInst * BI,PHINode * Merge,Value * & C,Value * & LHS,Value * & RHS)5967 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5968 Value *&C, Value *&LHS, Value *&RHS) {
5969 C = BI->getCondition();
5970
5971 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5972 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5973
5974 if (!LeftEdge.isSingleEdge())
5975 return false;
5976
5977 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5978
5979 Use &LeftUse = Merge->getOperandUse(0);
5980 Use &RightUse = Merge->getOperandUse(1);
5981
5982 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5983 LHS = LeftUse;
5984 RHS = RightUse;
5985 return true;
5986 }
5987
5988 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5989 LHS = RightUse;
5990 RHS = LeftUse;
5991 return true;
5992 }
5993
5994 return false;
5995 }
5996
createNodeFromSelectLikePHI(PHINode * PN)5997 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5998 auto IsReachable =
5999 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
6000 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
6001 // Try to match
6002 //
6003 // br %cond, label %left, label %right
6004 // left:
6005 // br label %merge
6006 // right:
6007 // br label %merge
6008 // merge:
6009 // V = phi [ %x, %left ], [ %y, %right ]
6010 //
6011 // as "select %cond, %x, %y"
6012
6013 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
6014 assert(IDom && "At least the entry block should dominate PN");
6015
6016 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
6017 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6018
6019 if (BI && BI->isConditional() &&
6020 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
6021 properlyDominates(getSCEV(LHS), PN->getParent()) &&
6022 properlyDominates(getSCEV(RHS), PN->getParent()))
6023 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
6024 }
6025
6026 return nullptr;
6027 }
6028
createNodeForPHI(PHINode * PN)6029 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
6030 if (const SCEV *S = createAddRecFromPHI(PN))
6031 return S;
6032
6033 if (Value *V = simplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
6034 return getSCEV(V);
6035
6036 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
6037 return S;
6038
6039 // If it's not a loop phi, we can't handle it yet.
6040 return getUnknown(PN);
6041 }
6042
SCEVMinMaxExprContains(const SCEV * Root,const SCEV * OperandToFind,SCEVTypes RootKind)6043 bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
6044 SCEVTypes RootKind) {
6045 struct FindClosure {
6046 const SCEV *OperandToFind;
6047 const SCEVTypes RootKind; // Must be a sequential min/max expression.
6048 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
6049
6050 bool Found = false;
6051
6052 bool canRecurseInto(SCEVTypes Kind) const {
6053 // We can only recurse into the SCEV expression of the same effective type
6054 // as the type of our root SCEV expression, and into zero-extensions.
6055 return RootKind == Kind || NonSequentialRootKind == Kind ||
6056 scZeroExtend == Kind;
6057 };
6058
6059 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
6060 : OperandToFind(OperandToFind), RootKind(RootKind),
6061 NonSequentialRootKind(
6062 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
6063 RootKind)) {}
6064
6065 bool follow(const SCEV *S) {
6066 Found = S == OperandToFind;
6067
6068 return !isDone() && canRecurseInto(S->getSCEVType());
6069 }
6070
6071 bool isDone() const { return Found; }
6072 };
6073
6074 FindClosure FC(OperandToFind, RootKind);
6075 visitAll(Root, FC);
6076 return FC.Found;
6077 }
6078
6079 std::optional<const SCEV *>
createNodeForSelectOrPHIInstWithICmpInstCond(Type * Ty,ICmpInst * Cond,Value * TrueVal,Value * FalseVal)6080 ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
6081 ICmpInst *Cond,
6082 Value *TrueVal,
6083 Value *FalseVal) {
6084 // Try to match some simple smax or umax patterns.
6085 auto *ICI = Cond;
6086
6087 Value *LHS = ICI->getOperand(0);
6088 Value *RHS = ICI->getOperand(1);
6089
6090 switch (ICI->getPredicate()) {
6091 case ICmpInst::ICMP_SLT:
6092 case ICmpInst::ICMP_SLE:
6093 case ICmpInst::ICMP_ULT:
6094 case ICmpInst::ICMP_ULE:
6095 std::swap(LHS, RHS);
6096 [[fallthrough]];
6097 case ICmpInst::ICMP_SGT:
6098 case ICmpInst::ICMP_SGE:
6099 case ICmpInst::ICMP_UGT:
6100 case ICmpInst::ICMP_UGE:
6101 // a > b ? a+x : b+x -> max(a, b)+x
6102 // a > b ? b+x : a+x -> min(a, b)+x
6103 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(Ty)) {
6104 bool Signed = ICI->isSigned();
6105 const SCEV *LA = getSCEV(TrueVal);
6106 const SCEV *RA = getSCEV(FalseVal);
6107 const SCEV *LS = getSCEV(LHS);
6108 const SCEV *RS = getSCEV(RHS);
6109 if (LA->getType()->isPointerTy()) {
6110 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6111 // Need to make sure we can't produce weird expressions involving
6112 // negated pointers.
6113 if (LA == LS && RA == RS)
6114 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6115 if (LA == RS && RA == LS)
6116 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6117 }
6118 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6119 if (Op->getType()->isPointerTy()) {
6120 Op = getLosslessPtrToIntExpr(Op);
6121 if (isa<SCEVCouldNotCompute>(Op))
6122 return Op;
6123 }
6124 if (Signed)
6125 Op = getNoopOrSignExtend(Op, Ty);
6126 else
6127 Op = getNoopOrZeroExtend(Op, Ty);
6128 return Op;
6129 };
6130 LS = CoerceOperand(LS);
6131 RS = CoerceOperand(RS);
6132 if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS))
6133 break;
6134 const SCEV *LDiff = getMinusSCEV(LA, LS);
6135 const SCEV *RDiff = getMinusSCEV(RA, RS);
6136 if (LDiff == RDiff)
6137 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6138 LDiff);
6139 LDiff = getMinusSCEV(LA, RS);
6140 RDiff = getMinusSCEV(RA, LS);
6141 if (LDiff == RDiff)
6142 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6143 LDiff);
6144 }
6145 break;
6146 case ICmpInst::ICMP_NE:
6147 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
6148 std::swap(TrueVal, FalseVal);
6149 [[fallthrough]];
6150 case ICmpInst::ICMP_EQ:
6151 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
6152 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(Ty) &&
6153 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
6154 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6155 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y
6156 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y
6157 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6158 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y
6159 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6160 return getAddExpr(getUMaxExpr(X, C), Y);
6161 }
6162 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
6163 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
6164 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
6165 // -> umin_seq(x, umin (..., umin_seq(...), ...))
6166 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero() &&
6167 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6168 const SCEV *X = getSCEV(LHS);
6169 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6170 X = ZExt->getOperand();
6171 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6172 const SCEV *FalseValExpr = getSCEV(FalseVal);
6173 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6174 return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6175 /*Sequential=*/true);
6176 }
6177 }
6178 break;
6179 default:
6180 break;
6181 }
6182
6183 return std::nullopt;
6184 }
6185
6186 static std::optional<const SCEV *>
createNodeForSelectViaUMinSeq(ScalarEvolution * SE,const SCEV * CondExpr,const SCEV * TrueExpr,const SCEV * FalseExpr)6187 createNodeForSelectViaUMinSeq(ScalarEvolution *SE, const SCEV *CondExpr,
6188 const SCEV *TrueExpr, const SCEV *FalseExpr) {
6189 assert(CondExpr->getType()->isIntegerTy(1) &&
6190 TrueExpr->getType() == FalseExpr->getType() &&
6191 TrueExpr->getType()->isIntegerTy(1) &&
6192 "Unexpected operands of a select.");
6193
6194 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
6195 // --> C + (umin_seq cond, x - C)
6196 //
6197 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
6198 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6199 // --> C + (umin_seq ~cond, x - C)
6200
6201 // FIXME: while we can't legally model the case where both of the hands
6202 // are fully variable, we only require that the *difference* is constant.
6203 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6204 return std::nullopt;
6205
6206 const SCEV *X, *C;
6207 if (isa<SCEVConstant>(TrueExpr)) {
6208 CondExpr = SE->getNotSCEV(CondExpr);
6209 X = FalseExpr;
6210 C = TrueExpr;
6211 } else {
6212 X = TrueExpr;
6213 C = FalseExpr;
6214 }
6215 return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6216 /*Sequential=*/true));
6217 }
6218
6219 static std::optional<const SCEV *>
createNodeForSelectViaUMinSeq(ScalarEvolution * SE,Value * Cond,Value * TrueVal,Value * FalseVal)6220 createNodeForSelectViaUMinSeq(ScalarEvolution *SE, Value *Cond, Value *TrueVal,
6221 Value *FalseVal) {
6222 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6223 return std::nullopt;
6224
6225 const auto *SECond = SE->getSCEV(Cond);
6226 const auto *SETrue = SE->getSCEV(TrueVal);
6227 const auto *SEFalse = SE->getSCEV(FalseVal);
6228 return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6229 }
6230
createNodeForSelectOrPHIViaUMinSeq(Value * V,Value * Cond,Value * TrueVal,Value * FalseVal)6231 const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6232 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6233 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6234 assert(TrueVal->getType() == FalseVal->getType() &&
6235 V->getType() == TrueVal->getType() &&
6236 "Types of select hands and of the result must match.");
6237
6238 // For now, only deal with i1-typed `select`s.
6239 if (!V->getType()->isIntegerTy(1))
6240 return getUnknown(V);
6241
6242 if (std::optional<const SCEV *> S =
6243 createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6244 return *S;
6245
6246 return getUnknown(V);
6247 }
6248
createNodeForSelectOrPHI(Value * V,Value * Cond,Value * TrueVal,Value * FalseVal)6249 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6250 Value *TrueVal,
6251 Value *FalseVal) {
6252 // Handle "constant" branch or select. This can occur for instance when a
6253 // loop pass transforms an inner loop and moves on to process the outer loop.
6254 if (auto *CI = dyn_cast<ConstantInt>(Cond))
6255 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6256
6257 if (auto *I = dyn_cast<Instruction>(V)) {
6258 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6259 if (std::optional<const SCEV *> S =
6260 createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6261 TrueVal, FalseVal))
6262 return *S;
6263 }
6264 }
6265
6266 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6267 }
6268
6269 /// Expand GEP instructions into add and multiply operations. This allows them
6270 /// to be analyzed by regular SCEV code.
createNodeForGEP(GEPOperator * GEP)6271 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6272 assert(GEP->getSourceElementType()->isSized() &&
6273 "GEP source element type must be sized");
6274
6275 SmallVector<const SCEV *, 4> IndexExprs;
6276 for (Value *Index : GEP->indices())
6277 IndexExprs.push_back(getSCEV(Index));
6278 return getGEPExpr(GEP, IndexExprs);
6279 }
6280
getConstantMultipleImpl(const SCEV * S)6281 APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S) {
6282 uint64_t BitWidth = getTypeSizeInBits(S->getType());
6283 auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6284 return TrailingZeros >= BitWidth
6285 ? APInt::getZero(BitWidth)
6286 : APInt::getOneBitSet(BitWidth, TrailingZeros);
6287 };
6288 auto GetGCDMultiple = [this](const SCEVNAryExpr *N) {
6289 // The result is GCD of all operands results.
6290 APInt Res = getConstantMultiple(N->getOperand(0));
6291 for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6292 Res = APIntOps::GreatestCommonDivisor(
6293 Res, getConstantMultiple(N->getOperand(I)));
6294 return Res;
6295 };
6296
6297 switch (S->getSCEVType()) {
6298 case scConstant:
6299 return cast<SCEVConstant>(S)->getAPInt();
6300 case scPtrToInt:
6301 return getConstantMultiple(cast<SCEVPtrToIntExpr>(S)->getOperand());
6302 case scUDivExpr:
6303 case scVScale:
6304 return APInt(BitWidth, 1);
6305 case scTruncate: {
6306 // Only multiples that are a power of 2 will hold after truncation.
6307 const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6308 uint32_t TZ = getMinTrailingZeros(T->getOperand());
6309 return GetShiftedByZeros(TZ);
6310 }
6311 case scZeroExtend: {
6312 const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(S);
6313 return getConstantMultiple(Z->getOperand()).zext(BitWidth);
6314 }
6315 case scSignExtend: {
6316 // Only multiples that are a power of 2 will hold after sext.
6317 const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6318 uint32_t TZ = getMinTrailingZeros(E->getOperand());
6319 return GetShiftedByZeros(TZ);
6320 }
6321 case scMulExpr: {
6322 const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6323 if (M->hasNoUnsignedWrap()) {
6324 // The result is the product of all operand results.
6325 APInt Res = getConstantMultiple(M->getOperand(0));
6326 for (const SCEV *Operand : M->operands().drop_front())
6327 Res = Res * getConstantMultiple(Operand);
6328 return Res;
6329 }
6330
6331 // If there are no wrap guarentees, find the trailing zeros, which is the
6332 // sum of trailing zeros for all its operands.
6333 uint32_t TZ = 0;
6334 for (const SCEV *Operand : M->operands())
6335 TZ += getMinTrailingZeros(Operand);
6336 return GetShiftedByZeros(TZ);
6337 }
6338 case scAddExpr:
6339 case scAddRecExpr: {
6340 const SCEVNAryExpr *N = cast<SCEVNAryExpr>(S);
6341 if (N->hasNoUnsignedWrap())
6342 return GetGCDMultiple(N);
6343 // Find the trailing bits, which is the minimum of its operands.
6344 uint32_t TZ = getMinTrailingZeros(N->getOperand(0));
6345 for (const SCEV *Operand : N->operands().drop_front())
6346 TZ = std::min(TZ, getMinTrailingZeros(Operand));
6347 return GetShiftedByZeros(TZ);
6348 }
6349 case scUMaxExpr:
6350 case scSMaxExpr:
6351 case scUMinExpr:
6352 case scSMinExpr:
6353 case scSequentialUMinExpr:
6354 return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6355 case scUnknown: {
6356 // ask ValueTracking for known bits
6357 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6358 unsigned Known =
6359 computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT)
6360 .countMinTrailingZeros();
6361 return GetShiftedByZeros(Known);
6362 }
6363 case scCouldNotCompute:
6364 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6365 }
6366 llvm_unreachable("Unknown SCEV kind!");
6367 }
6368
getConstantMultiple(const SCEV * S)6369 APInt ScalarEvolution::getConstantMultiple(const SCEV *S) {
6370 auto I = ConstantMultipleCache.find(S);
6371 if (I != ConstantMultipleCache.end())
6372 return I->second;
6373
6374 APInt Result = getConstantMultipleImpl(S);
6375 auto InsertPair = ConstantMultipleCache.insert({S, Result});
6376 assert(InsertPair.second && "Should insert a new key");
6377 return InsertPair.first->second;
6378 }
6379
getNonZeroConstantMultiple(const SCEV * S)6380 APInt ScalarEvolution::getNonZeroConstantMultiple(const SCEV *S) {
6381 APInt Multiple = getConstantMultiple(S);
6382 return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6383 }
6384
getMinTrailingZeros(const SCEV * S)6385 uint32_t ScalarEvolution::getMinTrailingZeros(const SCEV *S) {
6386 return std::min(getConstantMultiple(S).countTrailingZeros(),
6387 (unsigned)getTypeSizeInBits(S->getType()));
6388 }
6389
6390 /// Helper method to assign a range to V from metadata present in the IR.
GetRangeFromMetadata(Value * V)6391 static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6392 if (Instruction *I = dyn_cast<Instruction>(V)) {
6393 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6394 return getConstantRangeFromMetadata(*MD);
6395 if (const auto *CB = dyn_cast<CallBase>(V))
6396 if (std::optional<ConstantRange> Range = CB->getRange())
6397 return Range;
6398 }
6399 if (auto *A = dyn_cast<Argument>(V))
6400 if (std::optional<ConstantRange> Range = A->getRange())
6401 return Range;
6402
6403 return std::nullopt;
6404 }
6405
setNoWrapFlags(SCEVAddRecExpr * AddRec,SCEV::NoWrapFlags Flags)6406 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
6407 SCEV::NoWrapFlags Flags) {
6408 if (AddRec->getNoWrapFlags(Flags) != Flags) {
6409 AddRec->setNoWrapFlags(Flags);
6410 UnsignedRanges.erase(AddRec);
6411 SignedRanges.erase(AddRec);
6412 ConstantMultipleCache.erase(AddRec);
6413 }
6414 }
6415
6416 ConstantRange ScalarEvolution::
getRangeForUnknownRecurrence(const SCEVUnknown * U)6417 getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6418 const DataLayout &DL = getDataLayout();
6419
6420 unsigned BitWidth = getTypeSizeInBits(U->getType());
6421 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6422
6423 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6424 // use information about the trip count to improve our available range. Note
6425 // that the trip count independent cases are already handled by known bits.
6426 // WARNING: The definition of recurrence used here is subtly different than
6427 // the one used by AddRec (and thus most of this file). Step is allowed to
6428 // be arbitrarily loop varying here, where AddRec allows only loop invariant
6429 // and other addrecs in the same loop (for non-affine addrecs). The code
6430 // below intentionally handles the case where step is not loop invariant.
6431 auto *P = dyn_cast<PHINode>(U->getValue());
6432 if (!P)
6433 return FullSet;
6434
6435 // Make sure that no Phi input comes from an unreachable block. Otherwise,
6436 // even the values that are not available in these blocks may come from them,
6437 // and this leads to false-positive recurrence test.
6438 for (auto *Pred : predecessors(P->getParent()))
6439 if (!DT.isReachableFromEntry(Pred))
6440 return FullSet;
6441
6442 BinaryOperator *BO;
6443 Value *Start, *Step;
6444 if (!matchSimpleRecurrence(P, BO, Start, Step))
6445 return FullSet;
6446
6447 // If we found a recurrence in reachable code, we must be in a loop. Note
6448 // that BO might be in some subloop of L, and that's completely okay.
6449 auto *L = LI.getLoopFor(P->getParent());
6450 assert(L && L->getHeader() == P->getParent());
6451 if (!L->contains(BO->getParent()))
6452 // NOTE: This bailout should be an assert instead. However, asserting
6453 // the condition here exposes a case where LoopFusion is querying SCEV
6454 // with malformed loop information during the midst of the transform.
6455 // There doesn't appear to be an obvious fix, so for the moment bailout
6456 // until the caller issue can be fixed. PR49566 tracks the bug.
6457 return FullSet;
6458
6459 // TODO: Extend to other opcodes such as mul, and div
6460 switch (BO->getOpcode()) {
6461 default:
6462 return FullSet;
6463 case Instruction::AShr:
6464 case Instruction::LShr:
6465 case Instruction::Shl:
6466 break;
6467 };
6468
6469 if (BO->getOperand(0) != P)
6470 // TODO: Handle the power function forms some day.
6471 return FullSet;
6472
6473 unsigned TC = getSmallConstantMaxTripCount(L);
6474 if (!TC || TC >= BitWidth)
6475 return FullSet;
6476
6477 auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT);
6478 auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT);
6479 assert(KnownStart.getBitWidth() == BitWidth &&
6480 KnownStep.getBitWidth() == BitWidth);
6481
6482 // Compute total shift amount, being careful of overflow and bitwidths.
6483 auto MaxShiftAmt = KnownStep.getMaxValue();
6484 APInt TCAP(BitWidth, TC-1);
6485 bool Overflow = false;
6486 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6487 if (Overflow)
6488 return FullSet;
6489
6490 switch (BO->getOpcode()) {
6491 default:
6492 llvm_unreachable("filtered out above");
6493 case Instruction::AShr: {
6494 // For each ashr, three cases:
6495 // shift = 0 => unchanged value
6496 // saturation => 0 or -1
6497 // other => a value closer to zero (of the same sign)
6498 // Thus, the end value is closer to zero than the start.
6499 auto KnownEnd = KnownBits::ashr(KnownStart,
6500 KnownBits::makeConstant(TotalShift));
6501 if (KnownStart.isNonNegative())
6502 // Analogous to lshr (simply not yet canonicalized)
6503 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6504 KnownStart.getMaxValue() + 1);
6505 if (KnownStart.isNegative())
6506 // End >=u Start && End <=s Start
6507 return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6508 KnownEnd.getMaxValue() + 1);
6509 break;
6510 }
6511 case Instruction::LShr: {
6512 // For each lshr, three cases:
6513 // shift = 0 => unchanged value
6514 // saturation => 0
6515 // other => a smaller positive number
6516 // Thus, the low end of the unsigned range is the last value produced.
6517 auto KnownEnd = KnownBits::lshr(KnownStart,
6518 KnownBits::makeConstant(TotalShift));
6519 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6520 KnownStart.getMaxValue() + 1);
6521 }
6522 case Instruction::Shl: {
6523 // Iff no bits are shifted out, value increases on every shift.
6524 auto KnownEnd = KnownBits::shl(KnownStart,
6525 KnownBits::makeConstant(TotalShift));
6526 if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6527 return ConstantRange(KnownStart.getMinValue(),
6528 KnownEnd.getMaxValue() + 1);
6529 break;
6530 }
6531 };
6532 return FullSet;
6533 }
6534
6535 const ConstantRange &
getRangeRefIter(const SCEV * S,ScalarEvolution::RangeSignHint SignHint)6536 ScalarEvolution::getRangeRefIter(const SCEV *S,
6537 ScalarEvolution::RangeSignHint SignHint) {
6538 DenseMap<const SCEV *, ConstantRange> &Cache =
6539 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6540 : SignedRanges;
6541 SmallVector<const SCEV *> WorkList;
6542 SmallPtrSet<const SCEV *, 8> Seen;
6543
6544 // Add Expr to the worklist, if Expr is either an N-ary expression or a
6545 // SCEVUnknown PHI node.
6546 auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6547 if (!Seen.insert(Expr).second)
6548 return;
6549 if (Cache.contains(Expr))
6550 return;
6551 switch (Expr->getSCEVType()) {
6552 case scUnknown:
6553 if (!isa<PHINode>(cast<SCEVUnknown>(Expr)->getValue()))
6554 break;
6555 [[fallthrough]];
6556 case scConstant:
6557 case scVScale:
6558 case scTruncate:
6559 case scZeroExtend:
6560 case scSignExtend:
6561 case scPtrToInt:
6562 case scAddExpr:
6563 case scMulExpr:
6564 case scUDivExpr:
6565 case scAddRecExpr:
6566 case scUMaxExpr:
6567 case scSMaxExpr:
6568 case scUMinExpr:
6569 case scSMinExpr:
6570 case scSequentialUMinExpr:
6571 WorkList.push_back(Expr);
6572 break;
6573 case scCouldNotCompute:
6574 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6575 }
6576 };
6577 AddToWorklist(S);
6578
6579 // Build worklist by queuing operands of N-ary expressions and phi nodes.
6580 for (unsigned I = 0; I != WorkList.size(); ++I) {
6581 const SCEV *P = WorkList[I];
6582 auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6583 // If it is not a `SCEVUnknown`, just recurse into operands.
6584 if (!UnknownS) {
6585 for (const SCEV *Op : P->operands())
6586 AddToWorklist(Op);
6587 continue;
6588 }
6589 // `SCEVUnknown`'s require special treatment.
6590 if (const PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6591 if (!PendingPhiRangesIter.insert(P).second)
6592 continue;
6593 for (auto &Op : reverse(P->operands()))
6594 AddToWorklist(getSCEV(Op));
6595 }
6596 }
6597
6598 if (!WorkList.empty()) {
6599 // Use getRangeRef to compute ranges for items in the worklist in reverse
6600 // order. This will force ranges for earlier operands to be computed before
6601 // their users in most cases.
6602 for (const SCEV *P : reverse(drop_begin(WorkList))) {
6603 getRangeRef(P, SignHint);
6604
6605 if (auto *UnknownS = dyn_cast<SCEVUnknown>(P))
6606 if (const PHINode *P = dyn_cast<PHINode>(UnknownS->getValue()))
6607 PendingPhiRangesIter.erase(P);
6608 }
6609 }
6610
6611 return getRangeRef(S, SignHint, 0);
6612 }
6613
6614 /// Determine the range for a particular SCEV. If SignHint is
6615 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6616 /// with a "cleaner" unsigned (resp. signed) representation.
getRangeRef(const SCEV * S,ScalarEvolution::RangeSignHint SignHint,unsigned Depth)6617 const ConstantRange &ScalarEvolution::getRangeRef(
6618 const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6619 DenseMap<const SCEV *, ConstantRange> &Cache =
6620 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6621 : SignedRanges;
6622 ConstantRange::PreferredRangeType RangeType =
6623 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6624 : ConstantRange::Signed;
6625
6626 // See if we've computed this range already.
6627 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
6628 if (I != Cache.end())
6629 return I->second;
6630
6631 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6632 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6633
6634 // Switch to iteratively computing the range for S, if it is part of a deeply
6635 // nested expression.
6636 if (Depth > RangeIterThreshold)
6637 return getRangeRefIter(S, SignHint);
6638
6639 unsigned BitWidth = getTypeSizeInBits(S->getType());
6640 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6641 using OBO = OverflowingBinaryOperator;
6642
6643 // If the value has known zeros, the maximum value will have those known zeros
6644 // as well.
6645 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6646 APInt Multiple = getNonZeroConstantMultiple(S);
6647 APInt Remainder = APInt::getMaxValue(BitWidth).urem(Multiple);
6648 if (!Remainder.isZero())
6649 ConservativeResult =
6650 ConstantRange(APInt::getMinValue(BitWidth),
6651 APInt::getMaxValue(BitWidth) - Remainder + 1);
6652 }
6653 else {
6654 uint32_t TZ = getMinTrailingZeros(S);
6655 if (TZ != 0) {
6656 ConservativeResult = ConstantRange(
6657 APInt::getSignedMinValue(BitWidth),
6658 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6659 }
6660 }
6661
6662 switch (S->getSCEVType()) {
6663 case scConstant:
6664 llvm_unreachable("Already handled above.");
6665 case scVScale:
6666 return setRange(S, SignHint, getVScaleRange(&F, BitWidth));
6667 case scTruncate: {
6668 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6669 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6670 return setRange(
6671 Trunc, SignHint,
6672 ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6673 }
6674 case scZeroExtend: {
6675 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6676 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6677 return setRange(
6678 ZExt, SignHint,
6679 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6680 }
6681 case scSignExtend: {
6682 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6683 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6684 return setRange(
6685 SExt, SignHint,
6686 ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6687 }
6688 case scPtrToInt: {
6689 const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(S);
6690 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint, Depth + 1);
6691 return setRange(PtrToInt, SignHint, X);
6692 }
6693 case scAddExpr: {
6694 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6695 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6696 unsigned WrapType = OBO::AnyWrap;
6697 if (Add->hasNoSignedWrap())
6698 WrapType |= OBO::NoSignedWrap;
6699 if (Add->hasNoUnsignedWrap())
6700 WrapType |= OBO::NoUnsignedWrap;
6701 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
6702 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint, Depth + 1),
6703 WrapType, RangeType);
6704 return setRange(Add, SignHint,
6705 ConservativeResult.intersectWith(X, RangeType));
6706 }
6707 case scMulExpr: {
6708 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6709 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6710 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
6711 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint, Depth + 1));
6712 return setRange(Mul, SignHint,
6713 ConservativeResult.intersectWith(X, RangeType));
6714 }
6715 case scUDivExpr: {
6716 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6717 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6718 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6719 return setRange(UDiv, SignHint,
6720 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6721 }
6722 case scAddRecExpr: {
6723 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6724 // If there's no unsigned wrap, the value will never be less than its
6725 // initial value.
6726 if (AddRec->hasNoUnsignedWrap()) {
6727 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6728 if (!UnsignedMinValue.isZero())
6729 ConservativeResult = ConservativeResult.intersectWith(
6730 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6731 }
6732
6733 // If there's no signed wrap, and all the operands except initial value have
6734 // the same sign or zero, the value won't ever be:
6735 // 1: smaller than initial value if operands are non negative,
6736 // 2: bigger than initial value if operands are non positive.
6737 // For both cases, value can not cross signed min/max boundary.
6738 if (AddRec->hasNoSignedWrap()) {
6739 bool AllNonNeg = true;
6740 bool AllNonPos = true;
6741 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6742 if (!isKnownNonNegative(AddRec->getOperand(i)))
6743 AllNonNeg = false;
6744 if (!isKnownNonPositive(AddRec->getOperand(i)))
6745 AllNonPos = false;
6746 }
6747 if (AllNonNeg)
6748 ConservativeResult = ConservativeResult.intersectWith(
6749 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
6750 APInt::getSignedMinValue(BitWidth)),
6751 RangeType);
6752 else if (AllNonPos)
6753 ConservativeResult = ConservativeResult.intersectWith(
6754 ConstantRange::getNonEmpty(APInt::getSignedMinValue(BitWidth),
6755 getSignedRangeMax(AddRec->getStart()) +
6756 1),
6757 RangeType);
6758 }
6759
6760 // TODO: non-affine addrec
6761 if (AddRec->isAffine()) {
6762 const SCEV *MaxBEScev =
6763 getConstantMaxBackedgeTakenCount(AddRec->getLoop());
6764 if (!isa<SCEVCouldNotCompute>(MaxBEScev)) {
6765 APInt MaxBECount = cast<SCEVConstant>(MaxBEScev)->getAPInt();
6766
6767 // Adjust MaxBECount to the same bitwidth as AddRec. We can truncate if
6768 // MaxBECount's active bits are all <= AddRec's bit width.
6769 if (MaxBECount.getBitWidth() > BitWidth &&
6770 MaxBECount.getActiveBits() <= BitWidth)
6771 MaxBECount = MaxBECount.trunc(BitWidth);
6772 else if (MaxBECount.getBitWidth() < BitWidth)
6773 MaxBECount = MaxBECount.zext(BitWidth);
6774
6775 if (MaxBECount.getBitWidth() == BitWidth) {
6776 auto RangeFromAffine = getRangeForAffineAR(
6777 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6778 ConservativeResult =
6779 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6780
6781 auto RangeFromFactoring = getRangeViaFactoring(
6782 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6783 ConservativeResult =
6784 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6785 }
6786 }
6787
6788 // Now try symbolic BE count and more powerful methods.
6789 if (UseExpensiveRangeSharpening) {
6790 const SCEV *SymbolicMaxBECount =
6791 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
6792 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6793 getTypeSizeInBits(MaxBEScev->getType()) <= BitWidth &&
6794 AddRec->hasNoSelfWrap()) {
6795 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6796 AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6797 ConservativeResult =
6798 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6799 }
6800 }
6801 }
6802
6803 return setRange(AddRec, SignHint, std::move(ConservativeResult));
6804 }
6805 case scUMaxExpr:
6806 case scSMaxExpr:
6807 case scUMinExpr:
6808 case scSMinExpr:
6809 case scSequentialUMinExpr: {
6810 Intrinsic::ID ID;
6811 switch (S->getSCEVType()) {
6812 case scUMaxExpr:
6813 ID = Intrinsic::umax;
6814 break;
6815 case scSMaxExpr:
6816 ID = Intrinsic::smax;
6817 break;
6818 case scUMinExpr:
6819 case scSequentialUMinExpr:
6820 ID = Intrinsic::umin;
6821 break;
6822 case scSMinExpr:
6823 ID = Intrinsic::smin;
6824 break;
6825 default:
6826 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6827 }
6828
6829 const auto *NAry = cast<SCEVNAryExpr>(S);
6830 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
6831 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6832 X = X.intrinsic(
6833 ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
6834 return setRange(S, SignHint,
6835 ConservativeResult.intersectWith(X, RangeType));
6836 }
6837 case scUnknown: {
6838 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6839 Value *V = U->getValue();
6840
6841 // Check if the IR explicitly contains !range metadata.
6842 std::optional<ConstantRange> MDRange = GetRangeFromMetadata(V);
6843 if (MDRange)
6844 ConservativeResult =
6845 ConservativeResult.intersectWith(*MDRange, RangeType);
6846
6847 // Use facts about recurrences in the underlying IR. Note that add
6848 // recurrences are AddRecExprs and thus don't hit this path. This
6849 // primarily handles shift recurrences.
6850 auto CR = getRangeForUnknownRecurrence(U);
6851 ConservativeResult = ConservativeResult.intersectWith(CR);
6852
6853 // See if ValueTracking can give us a useful range.
6854 const DataLayout &DL = getDataLayout();
6855 KnownBits Known = computeKnownBits(V, DL, 0, &AC, nullptr, &DT);
6856 if (Known.getBitWidth() != BitWidth)
6857 Known = Known.zextOrTrunc(BitWidth);
6858
6859 // ValueTracking may be able to compute a tighter result for the number of
6860 // sign bits than for the value of those sign bits.
6861 unsigned NS = ComputeNumSignBits(V, DL, 0, &AC, nullptr, &DT);
6862 if (U->getType()->isPointerTy()) {
6863 // If the pointer size is larger than the index size type, this can cause
6864 // NS to be larger than BitWidth. So compensate for this.
6865 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
6866 int ptrIdxDiff = ptrSize - BitWidth;
6867 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
6868 NS -= ptrIdxDiff;
6869 }
6870
6871 if (NS > 1) {
6872 // If we know any of the sign bits, we know all of the sign bits.
6873 if (!Known.Zero.getHiBits(NS).isZero())
6874 Known.Zero.setHighBits(NS);
6875 if (!Known.One.getHiBits(NS).isZero())
6876 Known.One.setHighBits(NS);
6877 }
6878
6879 if (Known.getMinValue() != Known.getMaxValue() + 1)
6880 ConservativeResult = ConservativeResult.intersectWith(
6881 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6882 RangeType);
6883 if (NS > 1)
6884 ConservativeResult = ConservativeResult.intersectWith(
6885 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6886 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6887 RangeType);
6888
6889 if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
6890 // Strengthen the range if the underlying IR value is a
6891 // global/alloca/heap allocation using the size of the object.
6892 ObjectSizeOpts Opts;
6893 Opts.RoundToAlign = false;
6894 Opts.NullIsUnknownSize = true;
6895 uint64_t ObjSize;
6896 if ((isa<GlobalVariable>(V) || isa<AllocaInst>(V) ||
6897 isAllocationFn(V, &TLI)) &&
6898 getObjectSize(V, ObjSize, DL, &TLI, Opts) && ObjSize > 1) {
6899 // The highest address the object can start is ObjSize bytes before the
6900 // end (unsigned max value). If this value is not a multiple of the
6901 // alignment, the last possible start value is the next lowest multiple
6902 // of the alignment. Note: The computations below cannot overflow,
6903 // because if they would there's no possible start address for the
6904 // object.
6905 APInt MaxVal = APInt::getMaxValue(BitWidth) - APInt(BitWidth, ObjSize);
6906 uint64_t Align = U->getValue()->getPointerAlignment(DL).value();
6907 uint64_t Rem = MaxVal.urem(Align);
6908 MaxVal -= APInt(BitWidth, Rem);
6909 APInt MinVal = APInt::getZero(BitWidth);
6910 if (llvm::isKnownNonZero(V, DL))
6911 MinVal = Align;
6912 ConservativeResult = ConservativeResult.intersectWith(
6913 ConstantRange::getNonEmpty(MinVal, MaxVal + 1), RangeType);
6914 }
6915 }
6916
6917 // A range of Phi is a subset of union of all ranges of its input.
6918 if (PHINode *Phi = dyn_cast<PHINode>(V)) {
6919 // Make sure that we do not run over cycled Phis.
6920 if (PendingPhiRanges.insert(Phi).second) {
6921 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6922
6923 for (const auto &Op : Phi->operands()) {
6924 auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
6925 RangeFromOps = RangeFromOps.unionWith(OpRange);
6926 // No point to continue if we already have a full set.
6927 if (RangeFromOps.isFullSet())
6928 break;
6929 }
6930 ConservativeResult =
6931 ConservativeResult.intersectWith(RangeFromOps, RangeType);
6932 bool Erased = PendingPhiRanges.erase(Phi);
6933 assert(Erased && "Failed to erase Phi properly?");
6934 (void)Erased;
6935 }
6936 }
6937
6938 // vscale can't be equal to zero
6939 if (const auto *II = dyn_cast<IntrinsicInst>(V))
6940 if (II->getIntrinsicID() == Intrinsic::vscale) {
6941 ConstantRange Disallowed = APInt::getZero(BitWidth);
6942 ConservativeResult = ConservativeResult.difference(Disallowed);
6943 }
6944
6945 return setRange(U, SignHint, std::move(ConservativeResult));
6946 }
6947 case scCouldNotCompute:
6948 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6949 }
6950
6951 return setRange(S, SignHint, std::move(ConservativeResult));
6952 }
6953
6954 // Given a StartRange, Step and MaxBECount for an expression compute a range of
6955 // values that the expression can take. Initially, the expression has a value
6956 // from StartRange and then is changed by Step up to MaxBECount times. Signed
6957 // argument defines if we treat Step as signed or unsigned.
getRangeForAffineARHelper(APInt Step,const ConstantRange & StartRange,const APInt & MaxBECount,bool Signed)6958 static ConstantRange getRangeForAffineARHelper(APInt Step,
6959 const ConstantRange &StartRange,
6960 const APInt &MaxBECount,
6961 bool Signed) {
6962 unsigned BitWidth = Step.getBitWidth();
6963 assert(BitWidth == StartRange.getBitWidth() &&
6964 BitWidth == MaxBECount.getBitWidth() && "mismatched bit widths");
6965 // If either Step or MaxBECount is 0, then the expression won't change, and we
6966 // just need to return the initial range.
6967 if (Step == 0 || MaxBECount == 0)
6968 return StartRange;
6969
6970 // If we don't know anything about the initial value (i.e. StartRange is
6971 // FullRange), then we don't know anything about the final range either.
6972 // Return FullRange.
6973 if (StartRange.isFullSet())
6974 return ConstantRange::getFull(BitWidth);
6975
6976 // If Step is signed and negative, then we use its absolute value, but we also
6977 // note that we're moving in the opposite direction.
6978 bool Descending = Signed && Step.isNegative();
6979
6980 if (Signed)
6981 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
6982 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
6983 // This equations hold true due to the well-defined wrap-around behavior of
6984 // APInt.
6985 Step = Step.abs();
6986
6987 // Check if Offset is more than full span of BitWidth. If it is, the
6988 // expression is guaranteed to overflow.
6989 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
6990 return ConstantRange::getFull(BitWidth);
6991
6992 // Offset is by how much the expression can change. Checks above guarantee no
6993 // overflow here.
6994 APInt Offset = Step * MaxBECount;
6995
6996 // Minimum value of the final range will match the minimal value of StartRange
6997 // if the expression is increasing and will be decreased by Offset otherwise.
6998 // Maximum value of the final range will match the maximal value of StartRange
6999 // if the expression is decreasing and will be increased by Offset otherwise.
7000 APInt StartLower = StartRange.getLower();
7001 APInt StartUpper = StartRange.getUpper() - 1;
7002 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
7003 : (StartUpper + std::move(Offset));
7004
7005 // It's possible that the new minimum/maximum value will fall into the initial
7006 // range (due to wrap around). This means that the expression can take any
7007 // value in this bitwidth, and we have to return full range.
7008 if (StartRange.contains(MovedBoundary))
7009 return ConstantRange::getFull(BitWidth);
7010
7011 APInt NewLower =
7012 Descending ? std::move(MovedBoundary) : std::move(StartLower);
7013 APInt NewUpper =
7014 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
7015 NewUpper += 1;
7016
7017 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
7018 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
7019 }
7020
getRangeForAffineAR(const SCEV * Start,const SCEV * Step,const APInt & MaxBECount)7021 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
7022 const SCEV *Step,
7023 const APInt &MaxBECount) {
7024 assert(getTypeSizeInBits(Start->getType()) ==
7025 getTypeSizeInBits(Step->getType()) &&
7026 getTypeSizeInBits(Start->getType()) == MaxBECount.getBitWidth() &&
7027 "mismatched bit widths");
7028
7029 // First, consider step signed.
7030 ConstantRange StartSRange = getSignedRange(Start);
7031 ConstantRange StepSRange = getSignedRange(Step);
7032
7033 // If Step can be both positive and negative, we need to find ranges for the
7034 // maximum absolute step values in both directions and union them.
7035 ConstantRange SR = getRangeForAffineARHelper(
7036 StepSRange.getSignedMin(), StartSRange, MaxBECount, /* Signed = */ true);
7037 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
7038 StartSRange, MaxBECount,
7039 /* Signed = */ true));
7040
7041 // Next, consider step unsigned.
7042 ConstantRange UR = getRangeForAffineARHelper(
7043 getUnsignedRangeMax(Step), getUnsignedRange(Start), MaxBECount,
7044 /* Signed = */ false);
7045
7046 // Finally, intersect signed and unsigned ranges.
7047 return SR.intersectWith(UR, ConstantRange::Smallest);
7048 }
7049
getRangeForAffineNoSelfWrappingAR(const SCEVAddRecExpr * AddRec,const SCEV * MaxBECount,unsigned BitWidth,ScalarEvolution::RangeSignHint SignHint)7050 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
7051 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
7052 ScalarEvolution::RangeSignHint SignHint) {
7053 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
7054 assert(AddRec->hasNoSelfWrap() &&
7055 "This only works for non-self-wrapping AddRecs!");
7056 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
7057 const SCEV *Step = AddRec->getStepRecurrence(*this);
7058 // Only deal with constant step to save compile time.
7059 if (!isa<SCEVConstant>(Step))
7060 return ConstantRange::getFull(BitWidth);
7061 // Let's make sure that we can prove that we do not self-wrap during
7062 // MaxBECount iterations. We need this because MaxBECount is a maximum
7063 // iteration count estimate, and we might infer nw from some exit for which we
7064 // do not know max exit count (or any other side reasoning).
7065 // TODO: Turn into assert at some point.
7066 if (getTypeSizeInBits(MaxBECount->getType()) >
7067 getTypeSizeInBits(AddRec->getType()))
7068 return ConstantRange::getFull(BitWidth);
7069 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
7070 const SCEV *RangeWidth = getMinusOne(AddRec->getType());
7071 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
7072 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
7073 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
7074 MaxItersWithoutWrap))
7075 return ConstantRange::getFull(BitWidth);
7076
7077 ICmpInst::Predicate LEPred =
7078 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
7079 ICmpInst::Predicate GEPred =
7080 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
7081 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7082
7083 // We know that there is no self-wrap. Let's take Start and End values and
7084 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7085 // the iteration. They either lie inside the range [Min(Start, End),
7086 // Max(Start, End)] or outside it:
7087 //
7088 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
7089 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
7090 //
7091 // No self wrap flag guarantees that the intermediate values cannot be BOTH
7092 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7093 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7094 // Start <= End and step is positive, or Start >= End and step is negative.
7095 const SCEV *Start = applyLoopGuards(AddRec->getStart(), AddRec->getLoop());
7096 ConstantRange StartRange = getRangeRef(Start, SignHint);
7097 ConstantRange EndRange = getRangeRef(End, SignHint);
7098 ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7099 // If they already cover full iteration space, we will know nothing useful
7100 // even if we prove what we want to prove.
7101 if (RangeBetween.isFullSet())
7102 return RangeBetween;
7103 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7104 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7105 : RangeBetween.isWrappedSet();
7106 if (IsWrappedSet)
7107 return ConstantRange::getFull(BitWidth);
7108
7109 if (isKnownPositive(Step) &&
7110 isKnownPredicateViaConstantRanges(LEPred, Start, End))
7111 return RangeBetween;
7112 if (isKnownNegative(Step) &&
7113 isKnownPredicateViaConstantRanges(GEPred, Start, End))
7114 return RangeBetween;
7115 return ConstantRange::getFull(BitWidth);
7116 }
7117
getRangeViaFactoring(const SCEV * Start,const SCEV * Step,const APInt & MaxBECount)7118 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7119 const SCEV *Step,
7120 const APInt &MaxBECount) {
7121 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7122 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7123
7124 unsigned BitWidth = MaxBECount.getBitWidth();
7125 assert(getTypeSizeInBits(Start->getType()) == BitWidth &&
7126 getTypeSizeInBits(Step->getType()) == BitWidth &&
7127 "mismatched bit widths");
7128
7129 struct SelectPattern {
7130 Value *Condition = nullptr;
7131 APInt TrueValue;
7132 APInt FalseValue;
7133
7134 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7135 const SCEV *S) {
7136 std::optional<unsigned> CastOp;
7137 APInt Offset(BitWidth, 0);
7138
7139 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
7140 "Should be!");
7141
7142 // Peel off a constant offset:
7143 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
7144 // In the future we could consider being smarter here and handle
7145 // {Start+Step,+,Step} too.
7146 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
7147 return;
7148
7149 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
7150 S = SA->getOperand(1);
7151 }
7152
7153 // Peel off a cast operation
7154 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7155 CastOp = SCast->getSCEVType();
7156 S = SCast->getOperand();
7157 }
7158
7159 using namespace llvm::PatternMatch;
7160
7161 auto *SU = dyn_cast<SCEVUnknown>(S);
7162 const APInt *TrueVal, *FalseVal;
7163 if (!SU ||
7164 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7165 m_APInt(FalseVal)))) {
7166 Condition = nullptr;
7167 return;
7168 }
7169
7170 TrueValue = *TrueVal;
7171 FalseValue = *FalseVal;
7172
7173 // Re-apply the cast we peeled off earlier
7174 if (CastOp)
7175 switch (*CastOp) {
7176 default:
7177 llvm_unreachable("Unknown SCEV cast type!");
7178
7179 case scTruncate:
7180 TrueValue = TrueValue.trunc(BitWidth);
7181 FalseValue = FalseValue.trunc(BitWidth);
7182 break;
7183 case scZeroExtend:
7184 TrueValue = TrueValue.zext(BitWidth);
7185 FalseValue = FalseValue.zext(BitWidth);
7186 break;
7187 case scSignExtend:
7188 TrueValue = TrueValue.sext(BitWidth);
7189 FalseValue = FalseValue.sext(BitWidth);
7190 break;
7191 }
7192
7193 // Re-apply the constant offset we peeled off earlier
7194 TrueValue += Offset;
7195 FalseValue += Offset;
7196 }
7197
7198 bool isRecognized() { return Condition != nullptr; }
7199 };
7200
7201 SelectPattern StartPattern(*this, BitWidth, Start);
7202 if (!StartPattern.isRecognized())
7203 return ConstantRange::getFull(BitWidth);
7204
7205 SelectPattern StepPattern(*this, BitWidth, Step);
7206 if (!StepPattern.isRecognized())
7207 return ConstantRange::getFull(BitWidth);
7208
7209 if (StartPattern.Condition != StepPattern.Condition) {
7210 // We don't handle this case today; but we could, by considering four
7211 // possibilities below instead of two. I'm not sure if there are cases where
7212 // that will help over what getRange already does, though.
7213 return ConstantRange::getFull(BitWidth);
7214 }
7215
7216 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7217 // construct arbitrary general SCEV expressions here. This function is called
7218 // from deep in the call stack, and calling getSCEV (on a sext instruction,
7219 // say) can end up caching a suboptimal value.
7220
7221 // FIXME: without the explicit `this` receiver below, MSVC errors out with
7222 // C2352 and C2512 (otherwise it isn't needed).
7223
7224 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7225 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7226 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7227 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7228
7229 ConstantRange TrueRange =
7230 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount);
7231 ConstantRange FalseRange =
7232 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount);
7233
7234 return TrueRange.unionWith(FalseRange);
7235 }
7236
getNoWrapFlagsFromUB(const Value * V)7237 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7238 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
7239 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7240
7241 // Return early if there are no flags to propagate to the SCEV.
7242 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
7243 if (BinOp->hasNoUnsignedWrap())
7244 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
7245 if (BinOp->hasNoSignedWrap())
7246 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
7247 if (Flags == SCEV::FlagAnyWrap)
7248 return SCEV::FlagAnyWrap;
7249
7250 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
7251 }
7252
7253 const Instruction *
getNonTrivialDefiningScopeBound(const SCEV * S)7254 ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7255 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7256 return &*AddRec->getLoop()->getHeader()->begin();
7257 if (auto *U = dyn_cast<SCEVUnknown>(S))
7258 if (auto *I = dyn_cast<Instruction>(U->getValue()))
7259 return I;
7260 return nullptr;
7261 }
7262
7263 const Instruction *
getDefiningScopeBound(ArrayRef<const SCEV * > Ops,bool & Precise)7264 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops,
7265 bool &Precise) {
7266 Precise = true;
7267 // Do a bounded search of the def relation of the requested SCEVs.
7268 SmallSet<const SCEV *, 16> Visited;
7269 SmallVector<const SCEV *> Worklist;
7270 auto pushOp = [&](const SCEV *S) {
7271 if (!Visited.insert(S).second)
7272 return;
7273 // Threshold of 30 here is arbitrary.
7274 if (Visited.size() > 30) {
7275 Precise = false;
7276 return;
7277 }
7278 Worklist.push_back(S);
7279 };
7280
7281 for (const auto *S : Ops)
7282 pushOp(S);
7283
7284 const Instruction *Bound = nullptr;
7285 while (!Worklist.empty()) {
7286 auto *S = Worklist.pop_back_val();
7287 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7288 if (!Bound || DT.dominates(Bound, DefI))
7289 Bound = DefI;
7290 } else {
7291 for (const auto *Op : S->operands())
7292 pushOp(Op);
7293 }
7294 }
7295 return Bound ? Bound : &*F.getEntryBlock().begin();
7296 }
7297
7298 const Instruction *
getDefiningScopeBound(ArrayRef<const SCEV * > Ops)7299 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops) {
7300 bool Discard;
7301 return getDefiningScopeBound(Ops, Discard);
7302 }
7303
isGuaranteedToTransferExecutionTo(const Instruction * A,const Instruction * B)7304 bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7305 const Instruction *B) {
7306 if (A->getParent() == B->getParent() &&
7307 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
7308 B->getIterator()))
7309 return true;
7310
7311 auto *BLoop = LI.getLoopFor(B->getParent());
7312 if (BLoop && BLoop->getHeader() == B->getParent() &&
7313 BLoop->getLoopPreheader() == A->getParent() &&
7314 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
7315 A->getParent()->end()) &&
7316 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7317 B->getIterator()))
7318 return true;
7319 return false;
7320 }
7321
7322
isSCEVExprNeverPoison(const Instruction * I)7323 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7324 // Only proceed if we can prove that I does not yield poison.
7325 if (!programUndefinedIfPoison(I))
7326 return false;
7327
7328 // At this point we know that if I is executed, then it does not wrap
7329 // according to at least one of NSW or NUW. If I is not executed, then we do
7330 // not know if the calculation that I represents would wrap. Multiple
7331 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7332 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7333 // derived from other instructions that map to the same SCEV. We cannot make
7334 // that guarantee for cases where I is not executed. So we need to find a
7335 // upper bound on the defining scope for the SCEV, and prove that I is
7336 // executed every time we enter that scope. When the bounding scope is a
7337 // loop (the common case), this is equivalent to proving I executes on every
7338 // iteration of that loop.
7339 SmallVector<const SCEV *> SCEVOps;
7340 for (const Use &Op : I->operands()) {
7341 // I could be an extractvalue from a call to an overflow intrinsic.
7342 // TODO: We can do better here in some cases.
7343 if (isSCEVable(Op->getType()))
7344 SCEVOps.push_back(getSCEV(Op));
7345 }
7346 auto *DefI = getDefiningScopeBound(SCEVOps);
7347 return isGuaranteedToTransferExecutionTo(DefI, I);
7348 }
7349
isAddRecNeverPoison(const Instruction * I,const Loop * L)7350 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7351 // If we know that \c I can never be poison period, then that's enough.
7352 if (isSCEVExprNeverPoison(I))
7353 return true;
7354
7355 // If the loop only has one exit, then we know that, if the loop is entered,
7356 // any instruction dominating that exit will be executed. If any such
7357 // instruction would result in UB, the addrec cannot be poison.
7358 //
7359 // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7360 // also handles uses outside the loop header (they just need to dominate the
7361 // single exit).
7362
7363 auto *ExitingBB = L->getExitingBlock();
7364 if (!ExitingBB || !loopHasNoAbnormalExits(L))
7365 return false;
7366
7367 SmallPtrSet<const Value *, 16> KnownPoison;
7368 SmallVector<const Instruction *, 8> Worklist;
7369
7370 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
7371 // things that are known to be poison under that assumption go on the
7372 // Worklist.
7373 KnownPoison.insert(I);
7374 Worklist.push_back(I);
7375
7376 while (!Worklist.empty()) {
7377 const Instruction *Poison = Worklist.pop_back_val();
7378
7379 for (const Use &U : Poison->uses()) {
7380 const Instruction *PoisonUser = cast<Instruction>(U.getUser());
7381 if (mustTriggerUB(PoisonUser, KnownPoison) &&
7382 DT.dominates(PoisonUser->getParent(), ExitingBB))
7383 return true;
7384
7385 if (propagatesPoison(U) && L->contains(PoisonUser))
7386 if (KnownPoison.insert(PoisonUser).second)
7387 Worklist.push_back(PoisonUser);
7388 }
7389 }
7390
7391 return false;
7392 }
7393
7394 ScalarEvolution::LoopProperties
getLoopProperties(const Loop * L)7395 ScalarEvolution::getLoopProperties(const Loop *L) {
7396 using LoopProperties = ScalarEvolution::LoopProperties;
7397
7398 auto Itr = LoopPropertiesCache.find(L);
7399 if (Itr == LoopPropertiesCache.end()) {
7400 auto HasSideEffects = [](Instruction *I) {
7401 if (auto *SI = dyn_cast<StoreInst>(I))
7402 return !SI->isSimple();
7403
7404 return I->mayThrow() || I->mayWriteToMemory();
7405 };
7406
7407 LoopProperties LP = {/* HasNoAbnormalExits */ true,
7408 /*HasNoSideEffects*/ true};
7409
7410 for (auto *BB : L->getBlocks())
7411 for (auto &I : *BB) {
7412 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
7413 LP.HasNoAbnormalExits = false;
7414 if (HasSideEffects(&I))
7415 LP.HasNoSideEffects = false;
7416 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7417 break; // We're already as pessimistic as we can get.
7418 }
7419
7420 auto InsertPair = LoopPropertiesCache.insert({L, LP});
7421 assert(InsertPair.second && "We just checked!");
7422 Itr = InsertPair.first;
7423 }
7424
7425 return Itr->second;
7426 }
7427
loopIsFiniteByAssumption(const Loop * L)7428 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) {
7429 // A mustprogress loop without side effects must be finite.
7430 // TODO: The check used here is very conservative. It's only *specific*
7431 // side effects which are well defined in infinite loops.
7432 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7433 }
7434
createSCEVIter(Value * V)7435 const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7436 // Worklist item with a Value and a bool indicating whether all operands have
7437 // been visited already.
7438 using PointerTy = PointerIntPair<Value *, 1, bool>;
7439 SmallVector<PointerTy> Stack;
7440
7441 Stack.emplace_back(V, true);
7442 Stack.emplace_back(V, false);
7443 while (!Stack.empty()) {
7444 auto E = Stack.pop_back_val();
7445 Value *CurV = E.getPointer();
7446
7447 if (getExistingSCEV(CurV))
7448 continue;
7449
7450 SmallVector<Value *> Ops;
7451 const SCEV *CreatedSCEV = nullptr;
7452 // If all operands have been visited already, create the SCEV.
7453 if (E.getInt()) {
7454 CreatedSCEV = createSCEV(CurV);
7455 } else {
7456 // Otherwise get the operands we need to create SCEV's for before creating
7457 // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7458 // just use it.
7459 CreatedSCEV = getOperandsToCreate(CurV, Ops);
7460 }
7461
7462 if (CreatedSCEV) {
7463 insertValueToMap(CurV, CreatedSCEV);
7464 } else {
7465 // Queue CurV for SCEV creation, followed by its's operands which need to
7466 // be constructed first.
7467 Stack.emplace_back(CurV, true);
7468 for (Value *Op : Ops)
7469 Stack.emplace_back(Op, false);
7470 }
7471 }
7472
7473 return getExistingSCEV(V);
7474 }
7475
7476 const SCEV *
getOperandsToCreate(Value * V,SmallVectorImpl<Value * > & Ops)7477 ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7478 if (!isSCEVable(V->getType()))
7479 return getUnknown(V);
7480
7481 if (Instruction *I = dyn_cast<Instruction>(V)) {
7482 // Don't attempt to analyze instructions in blocks that aren't
7483 // reachable. Such instructions don't matter, and they aren't required
7484 // to obey basic rules for definitions dominating uses which this
7485 // analysis depends on.
7486 if (!DT.isReachableFromEntry(I->getParent()))
7487 return getUnknown(PoisonValue::get(V->getType()));
7488 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7489 return getConstant(CI);
7490 else if (isa<GlobalAlias>(V))
7491 return getUnknown(V);
7492 else if (!isa<ConstantExpr>(V))
7493 return getUnknown(V);
7494
7495 Operator *U = cast<Operator>(V);
7496 if (auto BO =
7497 MatchBinaryOp(U, getDataLayout(), AC, DT, dyn_cast<Instruction>(V))) {
7498 bool IsConstArg = isa<ConstantInt>(BO->RHS);
7499 switch (BO->Opcode) {
7500 case Instruction::Add:
7501 case Instruction::Mul: {
7502 // For additions and multiplications, traverse add/mul chains for which we
7503 // can potentially create a single SCEV, to reduce the number of
7504 // get{Add,Mul}Expr calls.
7505 do {
7506 if (BO->Op) {
7507 if (BO->Op != V && getExistingSCEV(BO->Op)) {
7508 Ops.push_back(BO->Op);
7509 break;
7510 }
7511 }
7512 Ops.push_back(BO->RHS);
7513 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7514 dyn_cast<Instruction>(V));
7515 if (!NewBO ||
7516 (BO->Opcode == Instruction::Add &&
7517 (NewBO->Opcode != Instruction::Add &&
7518 NewBO->Opcode != Instruction::Sub)) ||
7519 (BO->Opcode == Instruction::Mul &&
7520 NewBO->Opcode != Instruction::Mul)) {
7521 Ops.push_back(BO->LHS);
7522 break;
7523 }
7524 // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7525 // requires a SCEV for the LHS.
7526 if (BO->Op && (BO->IsNSW || BO->IsNUW)) {
7527 auto *I = dyn_cast<Instruction>(BO->Op);
7528 if (I && programUndefinedIfPoison(I)) {
7529 Ops.push_back(BO->LHS);
7530 break;
7531 }
7532 }
7533 BO = NewBO;
7534 } while (true);
7535 return nullptr;
7536 }
7537 case Instruction::Sub:
7538 case Instruction::UDiv:
7539 case Instruction::URem:
7540 break;
7541 case Instruction::AShr:
7542 case Instruction::Shl:
7543 case Instruction::Xor:
7544 if (!IsConstArg)
7545 return nullptr;
7546 break;
7547 case Instruction::And:
7548 case Instruction::Or:
7549 if (!IsConstArg && !BO->LHS->getType()->isIntegerTy(1))
7550 return nullptr;
7551 break;
7552 case Instruction::LShr:
7553 return getUnknown(V);
7554 default:
7555 llvm_unreachable("Unhandled binop");
7556 break;
7557 }
7558
7559 Ops.push_back(BO->LHS);
7560 Ops.push_back(BO->RHS);
7561 return nullptr;
7562 }
7563
7564 switch (U->getOpcode()) {
7565 case Instruction::Trunc:
7566 case Instruction::ZExt:
7567 case Instruction::SExt:
7568 case Instruction::PtrToInt:
7569 Ops.push_back(U->getOperand(0));
7570 return nullptr;
7571
7572 case Instruction::BitCast:
7573 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
7574 Ops.push_back(U->getOperand(0));
7575 return nullptr;
7576 }
7577 return getUnknown(V);
7578
7579 case Instruction::SDiv:
7580 case Instruction::SRem:
7581 Ops.push_back(U->getOperand(0));
7582 Ops.push_back(U->getOperand(1));
7583 return nullptr;
7584
7585 case Instruction::GetElementPtr:
7586 assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7587 "GEP source element type must be sized");
7588 for (Value *Index : U->operands())
7589 Ops.push_back(Index);
7590 return nullptr;
7591
7592 case Instruction::IntToPtr:
7593 return getUnknown(V);
7594
7595 case Instruction::PHI:
7596 // Keep constructing SCEVs' for phis recursively for now.
7597 return nullptr;
7598
7599 case Instruction::Select: {
7600 // Check if U is a select that can be simplified to a SCEVUnknown.
7601 auto CanSimplifyToUnknown = [this, U]() {
7602 if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
7603 return false;
7604
7605 auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
7606 if (!ICI)
7607 return false;
7608 Value *LHS = ICI->getOperand(0);
7609 Value *RHS = ICI->getOperand(1);
7610 if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7611 ICI->getPredicate() == CmpInst::ICMP_NE) {
7612 if (!(isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()))
7613 return true;
7614 } else if (getTypeSizeInBits(LHS->getType()) >
7615 getTypeSizeInBits(U->getType()))
7616 return true;
7617 return false;
7618 };
7619 if (CanSimplifyToUnknown())
7620 return getUnknown(U);
7621
7622 for (Value *Inc : U->operands())
7623 Ops.push_back(Inc);
7624 return nullptr;
7625 break;
7626 }
7627 case Instruction::Call:
7628 case Instruction::Invoke:
7629 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7630 Ops.push_back(RV);
7631 return nullptr;
7632 }
7633
7634 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7635 switch (II->getIntrinsicID()) {
7636 case Intrinsic::abs:
7637 Ops.push_back(II->getArgOperand(0));
7638 return nullptr;
7639 case Intrinsic::umax:
7640 case Intrinsic::umin:
7641 case Intrinsic::smax:
7642 case Intrinsic::smin:
7643 case Intrinsic::usub_sat:
7644 case Intrinsic::uadd_sat:
7645 Ops.push_back(II->getArgOperand(0));
7646 Ops.push_back(II->getArgOperand(1));
7647 return nullptr;
7648 case Intrinsic::start_loop_iterations:
7649 case Intrinsic::annotation:
7650 case Intrinsic::ptr_annotation:
7651 Ops.push_back(II->getArgOperand(0));
7652 return nullptr;
7653 default:
7654 break;
7655 }
7656 }
7657 break;
7658 }
7659
7660 return nullptr;
7661 }
7662
createSCEV(Value * V)7663 const SCEV *ScalarEvolution::createSCEV(Value *V) {
7664 if (!isSCEVable(V->getType()))
7665 return getUnknown(V);
7666
7667 if (Instruction *I = dyn_cast<Instruction>(V)) {
7668 // Don't attempt to analyze instructions in blocks that aren't
7669 // reachable. Such instructions don't matter, and they aren't required
7670 // to obey basic rules for definitions dominating uses which this
7671 // analysis depends on.
7672 if (!DT.isReachableFromEntry(I->getParent()))
7673 return getUnknown(PoisonValue::get(V->getType()));
7674 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7675 return getConstant(CI);
7676 else if (isa<GlobalAlias>(V))
7677 return getUnknown(V);
7678 else if (!isa<ConstantExpr>(V))
7679 return getUnknown(V);
7680
7681 const SCEV *LHS;
7682 const SCEV *RHS;
7683
7684 Operator *U = cast<Operator>(V);
7685 if (auto BO =
7686 MatchBinaryOp(U, getDataLayout(), AC, DT, dyn_cast<Instruction>(V))) {
7687 switch (BO->Opcode) {
7688 case Instruction::Add: {
7689 // The simple thing to do would be to just call getSCEV on both operands
7690 // and call getAddExpr with the result. However if we're looking at a
7691 // bunch of things all added together, this can be quite inefficient,
7692 // because it leads to N-1 getAddExpr calls for N ultimate operands.
7693 // Instead, gather up all the operands and make a single getAddExpr call.
7694 // LLVM IR canonical form means we need only traverse the left operands.
7695 SmallVector<const SCEV *, 4> AddOps;
7696 do {
7697 if (BO->Op) {
7698 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7699 AddOps.push_back(OpSCEV);
7700 break;
7701 }
7702
7703 // If a NUW or NSW flag can be applied to the SCEV for this
7704 // addition, then compute the SCEV for this addition by itself
7705 // with a separate call to getAddExpr. We need to do that
7706 // instead of pushing the operands of the addition onto AddOps,
7707 // since the flags are only known to apply to this particular
7708 // addition - they may not apply to other additions that can be
7709 // formed with operands from AddOps.
7710 const SCEV *RHS = getSCEV(BO->RHS);
7711 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7712 if (Flags != SCEV::FlagAnyWrap) {
7713 const SCEV *LHS = getSCEV(BO->LHS);
7714 if (BO->Opcode == Instruction::Sub)
7715 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7716 else
7717 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7718 break;
7719 }
7720 }
7721
7722 if (BO->Opcode == Instruction::Sub)
7723 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7724 else
7725 AddOps.push_back(getSCEV(BO->RHS));
7726
7727 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7728 dyn_cast<Instruction>(V));
7729 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7730 NewBO->Opcode != Instruction::Sub)) {
7731 AddOps.push_back(getSCEV(BO->LHS));
7732 break;
7733 }
7734 BO = NewBO;
7735 } while (true);
7736
7737 return getAddExpr(AddOps);
7738 }
7739
7740 case Instruction::Mul: {
7741 SmallVector<const SCEV *, 4> MulOps;
7742 do {
7743 if (BO->Op) {
7744 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7745 MulOps.push_back(OpSCEV);
7746 break;
7747 }
7748
7749 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7750 if (Flags != SCEV::FlagAnyWrap) {
7751 LHS = getSCEV(BO->LHS);
7752 RHS = getSCEV(BO->RHS);
7753 MulOps.push_back(getMulExpr(LHS, RHS, Flags));
7754 break;
7755 }
7756 }
7757
7758 MulOps.push_back(getSCEV(BO->RHS));
7759 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7760 dyn_cast<Instruction>(V));
7761 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7762 MulOps.push_back(getSCEV(BO->LHS));
7763 break;
7764 }
7765 BO = NewBO;
7766 } while (true);
7767
7768 return getMulExpr(MulOps);
7769 }
7770 case Instruction::UDiv:
7771 LHS = getSCEV(BO->LHS);
7772 RHS = getSCEV(BO->RHS);
7773 return getUDivExpr(LHS, RHS);
7774 case Instruction::URem:
7775 LHS = getSCEV(BO->LHS);
7776 RHS = getSCEV(BO->RHS);
7777 return getURemExpr(LHS, RHS);
7778 case Instruction::Sub: {
7779 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
7780 if (BO->Op)
7781 Flags = getNoWrapFlagsFromUB(BO->Op);
7782 LHS = getSCEV(BO->LHS);
7783 RHS = getSCEV(BO->RHS);
7784 return getMinusSCEV(LHS, RHS, Flags);
7785 }
7786 case Instruction::And:
7787 // For an expression like x&255 that merely masks off the high bits,
7788 // use zext(trunc(x)) as the SCEV expression.
7789 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7790 if (CI->isZero())
7791 return getSCEV(BO->RHS);
7792 if (CI->isMinusOne())
7793 return getSCEV(BO->LHS);
7794 const APInt &A = CI->getValue();
7795
7796 // Instcombine's ShrinkDemandedConstant may strip bits out of
7797 // constants, obscuring what would otherwise be a low-bits mask.
7798 // Use computeKnownBits to compute what ShrinkDemandedConstant
7799 // knew about to reconstruct a low-bits mask value.
7800 unsigned LZ = A.countl_zero();
7801 unsigned TZ = A.countr_zero();
7802 unsigned BitWidth = A.getBitWidth();
7803 KnownBits Known(BitWidth);
7804 computeKnownBits(BO->LHS, Known, getDataLayout(),
7805 0, &AC, nullptr, &DT);
7806
7807 APInt EffectiveMask =
7808 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
7809 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
7810 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
7811 const SCEV *LHS = getSCEV(BO->LHS);
7812 const SCEV *ShiftedLHS = nullptr;
7813 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
7814 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
7815 // For an expression like (x * 8) & 8, simplify the multiply.
7816 unsigned MulZeros = OpC->getAPInt().countr_zero();
7817 unsigned GCD = std::min(MulZeros, TZ);
7818 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
7819 SmallVector<const SCEV*, 4> MulOps;
7820 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
7821 append_range(MulOps, LHSMul->operands().drop_front());
7822 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
7823 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
7824 }
7825 }
7826 if (!ShiftedLHS)
7827 ShiftedLHS = getUDivExpr(LHS, MulCount);
7828 return getMulExpr(
7829 getZeroExtendExpr(
7830 getTruncateExpr(ShiftedLHS,
7831 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
7832 BO->LHS->getType()),
7833 MulCount);
7834 }
7835 }
7836 // Binary `and` is a bit-wise `umin`.
7837 if (BO->LHS->getType()->isIntegerTy(1)) {
7838 LHS = getSCEV(BO->LHS);
7839 RHS = getSCEV(BO->RHS);
7840 return getUMinExpr(LHS, RHS);
7841 }
7842 break;
7843
7844 case Instruction::Or:
7845 // Binary `or` is a bit-wise `umax`.
7846 if (BO->LHS->getType()->isIntegerTy(1)) {
7847 LHS = getSCEV(BO->LHS);
7848 RHS = getSCEV(BO->RHS);
7849 return getUMaxExpr(LHS, RHS);
7850 }
7851 break;
7852
7853 case Instruction::Xor:
7854 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7855 // If the RHS of xor is -1, then this is a not operation.
7856 if (CI->isMinusOne())
7857 return getNotSCEV(getSCEV(BO->LHS));
7858
7859 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
7860 // This is a variant of the check for xor with -1, and it handles
7861 // the case where instcombine has trimmed non-demanded bits out
7862 // of an xor with -1.
7863 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
7864 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
7865 if (LBO->getOpcode() == Instruction::And &&
7866 LCI->getValue() == CI->getValue())
7867 if (const SCEVZeroExtendExpr *Z =
7868 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
7869 Type *UTy = BO->LHS->getType();
7870 const SCEV *Z0 = Z->getOperand();
7871 Type *Z0Ty = Z0->getType();
7872 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
7873
7874 // If C is a low-bits mask, the zero extend is serving to
7875 // mask off the high bits. Complement the operand and
7876 // re-apply the zext.
7877 if (CI->getValue().isMask(Z0TySize))
7878 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
7879
7880 // If C is a single bit, it may be in the sign-bit position
7881 // before the zero-extend. In this case, represent the xor
7882 // using an add, which is equivalent, and re-apply the zext.
7883 APInt Trunc = CI->getValue().trunc(Z0TySize);
7884 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
7885 Trunc.isSignMask())
7886 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
7887 UTy);
7888 }
7889 }
7890 break;
7891
7892 case Instruction::Shl:
7893 // Turn shift left of a constant amount into a multiply.
7894 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
7895 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
7896
7897 // If the shift count is not less than the bitwidth, the result of
7898 // the shift is undefined. Don't try to analyze it, because the
7899 // resolution chosen here may differ from the resolution chosen in
7900 // other parts of the compiler.
7901 if (SA->getValue().uge(BitWidth))
7902 break;
7903
7904 // We can safely preserve the nuw flag in all cases. It's also safe to
7905 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
7906 // requires special handling. It can be preserved as long as we're not
7907 // left shifting by bitwidth - 1.
7908 auto Flags = SCEV::FlagAnyWrap;
7909 if (BO->Op) {
7910 auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
7911 if ((MulFlags & SCEV::FlagNSW) &&
7912 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
7913 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
7914 if (MulFlags & SCEV::FlagNUW)
7915 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
7916 }
7917
7918 ConstantInt *X = ConstantInt::get(
7919 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
7920 return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
7921 }
7922 break;
7923
7924 case Instruction::AShr:
7925 // AShr X, C, where C is a constant.
7926 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
7927 if (!CI)
7928 break;
7929
7930 Type *OuterTy = BO->LHS->getType();
7931 uint64_t BitWidth = getTypeSizeInBits(OuterTy);
7932 // If the shift count is not less than the bitwidth, the result of
7933 // the shift is undefined. Don't try to analyze it, because the
7934 // resolution chosen here may differ from the resolution chosen in
7935 // other parts of the compiler.
7936 if (CI->getValue().uge(BitWidth))
7937 break;
7938
7939 if (CI->isZero())
7940 return getSCEV(BO->LHS); // shift by zero --> noop
7941
7942 uint64_t AShrAmt = CI->getZExtValue();
7943 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
7944
7945 Operator *L = dyn_cast<Operator>(BO->LHS);
7946 const SCEV *AddTruncateExpr = nullptr;
7947 ConstantInt *ShlAmtCI = nullptr;
7948 const SCEV *AddConstant = nullptr;
7949
7950 if (L && L->getOpcode() == Instruction::Add) {
7951 // X = Shl A, n
7952 // Y = Add X, c
7953 // Z = AShr Y, m
7954 // n, c and m are constants.
7955
7956 Operator *LShift = dyn_cast<Operator>(L->getOperand(0));
7957 ConstantInt *AddOperandCI = dyn_cast<ConstantInt>(L->getOperand(1));
7958 if (LShift && LShift->getOpcode() == Instruction::Shl) {
7959 if (AddOperandCI) {
7960 const SCEV *ShlOp0SCEV = getSCEV(LShift->getOperand(0));
7961 ShlAmtCI = dyn_cast<ConstantInt>(LShift->getOperand(1));
7962 // since we truncate to TruncTy, the AddConstant should be of the
7963 // same type, so create a new Constant with type same as TruncTy.
7964 // Also, the Add constant should be shifted right by AShr amount.
7965 APInt AddOperand = AddOperandCI->getValue().ashr(AShrAmt);
7966 AddConstant = getConstant(AddOperand.trunc(BitWidth - AShrAmt));
7967 // we model the expression as sext(add(trunc(A), c << n)), since the
7968 // sext(trunc) part is already handled below, we create a
7969 // AddExpr(TruncExp) which will be used later.
7970 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
7971 }
7972 }
7973 } else if (L && L->getOpcode() == Instruction::Shl) {
7974 // X = Shl A, n
7975 // Y = AShr X, m
7976 // Both n and m are constant.
7977
7978 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
7979 ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
7980 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
7981 }
7982
7983 if (AddTruncateExpr && ShlAmtCI) {
7984 // We can merge the two given cases into a single SCEV statement,
7985 // incase n = m, the mul expression will be 2^0, so it gets resolved to
7986 // a simpler case. The following code handles the two cases:
7987 //
7988 // 1) For a two-shift sext-inreg, i.e. n = m,
7989 // use sext(trunc(x)) as the SCEV expression.
7990 //
7991 // 2) When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
7992 // expression. We already checked that ShlAmt < BitWidth, so
7993 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
7994 // ShlAmt - AShrAmt < Amt.
7995 const APInt &ShlAmt = ShlAmtCI->getValue();
7996 if (ShlAmt.ult(BitWidth) && ShlAmt.uge(AShrAmt)) {
7997 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
7998 ShlAmtCI->getZExtValue() - AShrAmt);
7999 const SCEV *CompositeExpr =
8000 getMulExpr(AddTruncateExpr, getConstant(Mul));
8001 if (L->getOpcode() != Instruction::Shl)
8002 CompositeExpr = getAddExpr(CompositeExpr, AddConstant);
8003
8004 return getSignExtendExpr(CompositeExpr, OuterTy);
8005 }
8006 }
8007 break;
8008 }
8009 }
8010
8011 switch (U->getOpcode()) {
8012 case Instruction::Trunc:
8013 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
8014
8015 case Instruction::ZExt:
8016 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8017
8018 case Instruction::SExt:
8019 if (auto BO = MatchBinaryOp(U->getOperand(0), getDataLayout(), AC, DT,
8020 dyn_cast<Instruction>(V))) {
8021 // The NSW flag of a subtract does not always survive the conversion to
8022 // A + (-1)*B. By pushing sign extension onto its operands we are much
8023 // more likely to preserve NSW and allow later AddRec optimisations.
8024 //
8025 // NOTE: This is effectively duplicating this logic from getSignExtend:
8026 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
8027 // but by that point the NSW information has potentially been lost.
8028 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
8029 Type *Ty = U->getType();
8030 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
8031 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
8032 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
8033 }
8034 }
8035 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8036
8037 case Instruction::BitCast:
8038 // BitCasts are no-op casts so we just eliminate the cast.
8039 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
8040 return getSCEV(U->getOperand(0));
8041 break;
8042
8043 case Instruction::PtrToInt: {
8044 // Pointer to integer cast is straight-forward, so do model it.
8045 const SCEV *Op = getSCEV(U->getOperand(0));
8046 Type *DstIntTy = U->getType();
8047 // But only if effective SCEV (integer) type is wide enough to represent
8048 // all possible pointer values.
8049 const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy);
8050 if (isa<SCEVCouldNotCompute>(IntOp))
8051 return getUnknown(V);
8052 return IntOp;
8053 }
8054 case Instruction::IntToPtr:
8055 // Just don't deal with inttoptr casts.
8056 return getUnknown(V);
8057
8058 case Instruction::SDiv:
8059 // If both operands are non-negative, this is just an udiv.
8060 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8061 isKnownNonNegative(getSCEV(U->getOperand(1))))
8062 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8063 break;
8064
8065 case Instruction::SRem:
8066 // If both operands are non-negative, this is just an urem.
8067 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8068 isKnownNonNegative(getSCEV(U->getOperand(1))))
8069 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8070 break;
8071
8072 case Instruction::GetElementPtr:
8073 return createNodeForGEP(cast<GEPOperator>(U));
8074
8075 case Instruction::PHI:
8076 return createNodeForPHI(cast<PHINode>(U));
8077
8078 case Instruction::Select:
8079 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
8080 U->getOperand(2));
8081
8082 case Instruction::Call:
8083 case Instruction::Invoke:
8084 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
8085 return getSCEV(RV);
8086
8087 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
8088 switch (II->getIntrinsicID()) {
8089 case Intrinsic::abs:
8090 return getAbsExpr(
8091 getSCEV(II->getArgOperand(0)),
8092 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
8093 case Intrinsic::umax:
8094 LHS = getSCEV(II->getArgOperand(0));
8095 RHS = getSCEV(II->getArgOperand(1));
8096 return getUMaxExpr(LHS, RHS);
8097 case Intrinsic::umin:
8098 LHS = getSCEV(II->getArgOperand(0));
8099 RHS = getSCEV(II->getArgOperand(1));
8100 return getUMinExpr(LHS, RHS);
8101 case Intrinsic::smax:
8102 LHS = getSCEV(II->getArgOperand(0));
8103 RHS = getSCEV(II->getArgOperand(1));
8104 return getSMaxExpr(LHS, RHS);
8105 case Intrinsic::smin:
8106 LHS = getSCEV(II->getArgOperand(0));
8107 RHS = getSCEV(II->getArgOperand(1));
8108 return getSMinExpr(LHS, RHS);
8109 case Intrinsic::usub_sat: {
8110 const SCEV *X = getSCEV(II->getArgOperand(0));
8111 const SCEV *Y = getSCEV(II->getArgOperand(1));
8112 const SCEV *ClampedY = getUMinExpr(X, Y);
8113 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
8114 }
8115 case Intrinsic::uadd_sat: {
8116 const SCEV *X = getSCEV(II->getArgOperand(0));
8117 const SCEV *Y = getSCEV(II->getArgOperand(1));
8118 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
8119 return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
8120 }
8121 case Intrinsic::start_loop_iterations:
8122 case Intrinsic::annotation:
8123 case Intrinsic::ptr_annotation:
8124 // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8125 // just eqivalent to the first operand for SCEV purposes.
8126 return getSCEV(II->getArgOperand(0));
8127 case Intrinsic::vscale:
8128 return getVScale(II->getType());
8129 default:
8130 break;
8131 }
8132 }
8133 break;
8134 }
8135
8136 return getUnknown(V);
8137 }
8138
8139 //===----------------------------------------------------------------------===//
8140 // Iteration Count Computation Code
8141 //
8142
getTripCountFromExitCount(const SCEV * ExitCount)8143 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount) {
8144 if (isa<SCEVCouldNotCompute>(ExitCount))
8145 return getCouldNotCompute();
8146
8147 auto *ExitCountType = ExitCount->getType();
8148 assert(ExitCountType->isIntegerTy());
8149 auto *EvalTy = Type::getIntNTy(ExitCountType->getContext(),
8150 1 + ExitCountType->getScalarSizeInBits());
8151 return getTripCountFromExitCount(ExitCount, EvalTy, nullptr);
8152 }
8153
getTripCountFromExitCount(const SCEV * ExitCount,Type * EvalTy,const Loop * L)8154 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount,
8155 Type *EvalTy,
8156 const Loop *L) {
8157 if (isa<SCEVCouldNotCompute>(ExitCount))
8158 return getCouldNotCompute();
8159
8160 unsigned ExitCountSize = getTypeSizeInBits(ExitCount->getType());
8161 unsigned EvalSize = EvalTy->getPrimitiveSizeInBits();
8162
8163 auto CanAddOneWithoutOverflow = [&]() {
8164 ConstantRange ExitCountRange =
8165 getRangeRef(ExitCount, RangeSignHint::HINT_RANGE_UNSIGNED);
8166 if (!ExitCountRange.contains(APInt::getMaxValue(ExitCountSize)))
8167 return true;
8168
8169 return L && isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
8170 getMinusOne(ExitCount->getType()));
8171 };
8172
8173 // If we need to zero extend the backedge count, check if we can add one to
8174 // it prior to zero extending without overflow. Provided this is safe, it
8175 // allows better simplification of the +1.
8176 if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8177 return getZeroExtendExpr(
8178 getAddExpr(ExitCount, getOne(ExitCount->getType())), EvalTy);
8179
8180 // Get the total trip count from the count by adding 1. This may wrap.
8181 return getAddExpr(getTruncateOrZeroExtend(ExitCount, EvalTy), getOne(EvalTy));
8182 }
8183
getConstantTripCount(const SCEVConstant * ExitCount)8184 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8185 if (!ExitCount)
8186 return 0;
8187
8188 ConstantInt *ExitConst = ExitCount->getValue();
8189
8190 // Guard against huge trip counts.
8191 if (ExitConst->getValue().getActiveBits() > 32)
8192 return 0;
8193
8194 // In case of integer overflow, this returns 0, which is correct.
8195 return ((unsigned)ExitConst->getZExtValue()) + 1;
8196 }
8197
getSmallConstantTripCount(const Loop * L)8198 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
8199 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
8200 return getConstantTripCount(ExitCount);
8201 }
8202
8203 unsigned
getSmallConstantTripCount(const Loop * L,const BasicBlock * ExitingBlock)8204 ScalarEvolution::getSmallConstantTripCount(const Loop *L,
8205 const BasicBlock *ExitingBlock) {
8206 assert(ExitingBlock && "Must pass a non-null exiting block!");
8207 assert(L->isLoopExiting(ExitingBlock) &&
8208 "Exiting block must actually branch out of the loop!");
8209 const SCEVConstant *ExitCount =
8210 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
8211 return getConstantTripCount(ExitCount);
8212 }
8213
getSmallConstantMaxTripCount(const Loop * L)8214 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
8215 const auto *MaxExitCount =
8216 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
8217 return getConstantTripCount(MaxExitCount);
8218 }
8219
getSmallConstantTripMultiple(const Loop * L)8220 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
8221 SmallVector<BasicBlock *, 8> ExitingBlocks;
8222 L->getExitingBlocks(ExitingBlocks);
8223
8224 std::optional<unsigned> Res;
8225 for (auto *ExitingBB : ExitingBlocks) {
8226 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
8227 if (!Res)
8228 Res = Multiple;
8229 Res = (unsigned)std::gcd(*Res, Multiple);
8230 }
8231 return Res.value_or(1);
8232 }
8233
getSmallConstantTripMultiple(const Loop * L,const SCEV * ExitCount)8234 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
8235 const SCEV *ExitCount) {
8236 if (ExitCount == getCouldNotCompute())
8237 return 1;
8238
8239 // Get the trip count
8240 const SCEV *TCExpr = getTripCountFromExitCount(applyLoopGuards(ExitCount, L));
8241
8242 APInt Multiple = getNonZeroConstantMultiple(TCExpr);
8243 // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8244 // the greatest power of 2 divisor less than 2^32.
8245 return Multiple.getActiveBits() > 32
8246 ? 1U << std::min((unsigned)31, Multiple.countTrailingZeros())
8247 : (unsigned)Multiple.zextOrTrunc(32).getZExtValue();
8248 }
8249
8250 /// Returns the largest constant divisor of the trip count of this loop as a
8251 /// normal unsigned value, if possible. This means that the actual trip count is
8252 /// always a multiple of the returned value (don't forget the trip count could
8253 /// very well be zero as well!).
8254 ///
8255 /// Returns 1 if the trip count is unknown or not guaranteed to be the
8256 /// multiple of a constant (which is also the case if the trip count is simply
8257 /// constant, use getSmallConstantTripCount for that case), Will also return 1
8258 /// if the trip count is very large (>= 2^32).
8259 ///
8260 /// As explained in the comments for getSmallConstantTripCount, this assumes
8261 /// that control exits the loop via ExitingBlock.
8262 unsigned
getSmallConstantTripMultiple(const Loop * L,const BasicBlock * ExitingBlock)8263 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
8264 const BasicBlock *ExitingBlock) {
8265 assert(ExitingBlock && "Must pass a non-null exiting block!");
8266 assert(L->isLoopExiting(ExitingBlock) &&
8267 "Exiting block must actually branch out of the loop!");
8268 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8269 return getSmallConstantTripMultiple(L, ExitCount);
8270 }
8271
getExitCount(const Loop * L,const BasicBlock * ExitingBlock,ExitCountKind Kind)8272 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
8273 const BasicBlock *ExitingBlock,
8274 ExitCountKind Kind) {
8275 switch (Kind) {
8276 case Exact:
8277 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8278 case SymbolicMaximum:
8279 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8280 case ConstantMaximum:
8281 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8282 };
8283 llvm_unreachable("Invalid ExitCountKind!");
8284 }
8285
8286 const SCEV *
getPredicatedBackedgeTakenCount(const Loop * L,SmallVector<const SCEVPredicate *,4> & Preds)8287 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
8288 SmallVector<const SCEVPredicate *, 4> &Preds) {
8289 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8290 }
8291
getBackedgeTakenCount(const Loop * L,ExitCountKind Kind)8292 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
8293 ExitCountKind Kind) {
8294 switch (Kind) {
8295 case Exact:
8296 return getBackedgeTakenInfo(L).getExact(L, this);
8297 case ConstantMaximum:
8298 return getBackedgeTakenInfo(L).getConstantMax(this);
8299 case SymbolicMaximum:
8300 return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8301 };
8302 llvm_unreachable("Invalid ExitCountKind!");
8303 }
8304
getPredicatedSymbolicMaxBackedgeTakenCount(const Loop * L,SmallVector<const SCEVPredicate *,4> & Preds)8305 const SCEV *ScalarEvolution::getPredicatedSymbolicMaxBackedgeTakenCount(
8306 const Loop *L, SmallVector<const SCEVPredicate *, 4> &Preds) {
8307 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(L, this, &Preds);
8308 }
8309
isBackedgeTakenCountMaxOrZero(const Loop * L)8310 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
8311 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8312 }
8313
8314 /// Push PHI nodes in the header of the given loop onto the given Worklist.
PushLoopPHIs(const Loop * L,SmallVectorImpl<Instruction * > & Worklist,SmallPtrSetImpl<Instruction * > & Visited)8315 static void PushLoopPHIs(const Loop *L,
8316 SmallVectorImpl<Instruction *> &Worklist,
8317 SmallPtrSetImpl<Instruction *> &Visited) {
8318 BasicBlock *Header = L->getHeader();
8319
8320 // Push all Loop-header PHIs onto the Worklist stack.
8321 for (PHINode &PN : Header->phis())
8322 if (Visited.insert(&PN).second)
8323 Worklist.push_back(&PN);
8324 }
8325
8326 ScalarEvolution::BackedgeTakenInfo &
getPredicatedBackedgeTakenInfo(const Loop * L)8327 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8328 auto &BTI = getBackedgeTakenInfo(L);
8329 if (BTI.hasFullInfo())
8330 return BTI;
8331
8332 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
8333
8334 if (!Pair.second)
8335 return Pair.first->second;
8336
8337 BackedgeTakenInfo Result =
8338 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8339
8340 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8341 }
8342
8343 ScalarEvolution::BackedgeTakenInfo &
getBackedgeTakenInfo(const Loop * L)8344 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8345 // Initially insert an invalid entry for this loop. If the insertion
8346 // succeeds, proceed to actually compute a backedge-taken count and
8347 // update the value. The temporary CouldNotCompute value tells SCEV
8348 // code elsewhere that it shouldn't attempt to request a new
8349 // backedge-taken count, which could result in infinite recursion.
8350 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8351 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
8352 if (!Pair.second)
8353 return Pair.first->second;
8354
8355 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8356 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8357 // must be cleared in this scope.
8358 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8359
8360 // Now that we know more about the trip count for this loop, forget any
8361 // existing SCEV values for PHI nodes in this loop since they are only
8362 // conservative estimates made without the benefit of trip count
8363 // information. This invalidation is not necessary for correctness, and is
8364 // only done to produce more precise results.
8365 if (Result.hasAnyInfo()) {
8366 // Invalidate any expression using an addrec in this loop.
8367 SmallVector<const SCEV *, 8> ToForget;
8368 auto LoopUsersIt = LoopUsers.find(L);
8369 if (LoopUsersIt != LoopUsers.end())
8370 append_range(ToForget, LoopUsersIt->second);
8371 forgetMemoizedResults(ToForget);
8372
8373 // Invalidate constant-evolved loop header phis.
8374 for (PHINode &PN : L->getHeader()->phis())
8375 ConstantEvolutionLoopExitValue.erase(&PN);
8376 }
8377
8378 // Re-lookup the insert position, since the call to
8379 // computeBackedgeTakenCount above could result in a
8380 // recusive call to getBackedgeTakenInfo (on a different
8381 // loop), which would invalidate the iterator computed
8382 // earlier.
8383 return BackedgeTakenCounts.find(L)->second = std::move(Result);
8384 }
8385
forgetAllLoops()8386 void ScalarEvolution::forgetAllLoops() {
8387 // This method is intended to forget all info about loops. It should
8388 // invalidate caches as if the following happened:
8389 // - The trip counts of all loops have changed arbitrarily
8390 // - Every llvm::Value has been updated in place to produce a different
8391 // result.
8392 BackedgeTakenCounts.clear();
8393 PredicatedBackedgeTakenCounts.clear();
8394 BECountUsers.clear();
8395 LoopPropertiesCache.clear();
8396 ConstantEvolutionLoopExitValue.clear();
8397 ValueExprMap.clear();
8398 ValuesAtScopes.clear();
8399 ValuesAtScopesUsers.clear();
8400 LoopDispositions.clear();
8401 BlockDispositions.clear();
8402 UnsignedRanges.clear();
8403 SignedRanges.clear();
8404 ExprValueMap.clear();
8405 HasRecMap.clear();
8406 ConstantMultipleCache.clear();
8407 PredicatedSCEVRewrites.clear();
8408 FoldCache.clear();
8409 FoldCacheUser.clear();
8410 }
visitAndClearUsers(SmallVectorImpl<Instruction * > & Worklist,SmallPtrSetImpl<Instruction * > & Visited,SmallVectorImpl<const SCEV * > & ToForget)8411 void ScalarEvolution::visitAndClearUsers(
8412 SmallVectorImpl<Instruction *> &Worklist,
8413 SmallPtrSetImpl<Instruction *> &Visited,
8414 SmallVectorImpl<const SCEV *> &ToForget) {
8415 while (!Worklist.empty()) {
8416 Instruction *I = Worklist.pop_back_val();
8417 if (!isSCEVable(I->getType()) && !isa<WithOverflowInst>(I))
8418 continue;
8419
8420 ValueExprMapType::iterator It =
8421 ValueExprMap.find_as(static_cast<Value *>(I));
8422 if (It != ValueExprMap.end()) {
8423 eraseValueFromMap(It->first);
8424 ToForget.push_back(It->second);
8425 if (PHINode *PN = dyn_cast<PHINode>(I))
8426 ConstantEvolutionLoopExitValue.erase(PN);
8427 }
8428
8429 PushDefUseChildren(I, Worklist, Visited);
8430 }
8431 }
8432
forgetLoop(const Loop * L)8433 void ScalarEvolution::forgetLoop(const Loop *L) {
8434 SmallVector<const Loop *, 16> LoopWorklist(1, L);
8435 SmallVector<Instruction *, 32> Worklist;
8436 SmallPtrSet<Instruction *, 16> Visited;
8437 SmallVector<const SCEV *, 16> ToForget;
8438
8439 // Iterate over all the loops and sub-loops to drop SCEV information.
8440 while (!LoopWorklist.empty()) {
8441 auto *CurrL = LoopWorklist.pop_back_val();
8442
8443 // Drop any stored trip count value.
8444 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8445 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8446
8447 // Drop information about predicated SCEV rewrites for this loop.
8448 for (auto I = PredicatedSCEVRewrites.begin();
8449 I != PredicatedSCEVRewrites.end();) {
8450 std::pair<const SCEV *, const Loop *> Entry = I->first;
8451 if (Entry.second == CurrL)
8452 PredicatedSCEVRewrites.erase(I++);
8453 else
8454 ++I;
8455 }
8456
8457 auto LoopUsersItr = LoopUsers.find(CurrL);
8458 if (LoopUsersItr != LoopUsers.end()) {
8459 ToForget.insert(ToForget.end(), LoopUsersItr->second.begin(),
8460 LoopUsersItr->second.end());
8461 }
8462
8463 // Drop information about expressions based on loop-header PHIs.
8464 PushLoopPHIs(CurrL, Worklist, Visited);
8465 visitAndClearUsers(Worklist, Visited, ToForget);
8466
8467 LoopPropertiesCache.erase(CurrL);
8468 // Forget all contained loops too, to avoid dangling entries in the
8469 // ValuesAtScopes map.
8470 LoopWorklist.append(CurrL->begin(), CurrL->end());
8471 }
8472 forgetMemoizedResults(ToForget);
8473 }
8474
forgetTopmostLoop(const Loop * L)8475 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
8476 forgetLoop(L->getOutermostLoop());
8477 }
8478
forgetValue(Value * V)8479 void ScalarEvolution::forgetValue(Value *V) {
8480 Instruction *I = dyn_cast<Instruction>(V);
8481 if (!I) return;
8482
8483 // Drop information about expressions based on loop-header PHIs.
8484 SmallVector<Instruction *, 16> Worklist;
8485 SmallPtrSet<Instruction *, 8> Visited;
8486 SmallVector<const SCEV *, 8> ToForget;
8487 Worklist.push_back(I);
8488 Visited.insert(I);
8489 visitAndClearUsers(Worklist, Visited, ToForget);
8490
8491 forgetMemoizedResults(ToForget);
8492 }
8493
forgetLcssaPhiWithNewPredecessor(Loop * L,PHINode * V)8494 void ScalarEvolution::forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V) {
8495 if (!isSCEVable(V->getType()))
8496 return;
8497
8498 // If SCEV looked through a trivial LCSSA phi node, we might have SCEV's
8499 // directly using a SCEVUnknown/SCEVAddRec defined in the loop. After an
8500 // extra predecessor is added, this is no longer valid. Find all Unknowns and
8501 // AddRecs defined in the loop and invalidate any SCEV's making use of them.
8502 if (const SCEV *S = getExistingSCEV(V)) {
8503 struct InvalidationRootCollector {
8504 Loop *L;
8505 SmallVector<const SCEV *, 8> Roots;
8506
8507 InvalidationRootCollector(Loop *L) : L(L) {}
8508
8509 bool follow(const SCEV *S) {
8510 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
8511 if (auto *I = dyn_cast<Instruction>(SU->getValue()))
8512 if (L->contains(I))
8513 Roots.push_back(S);
8514 } else if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
8515 if (L->contains(AddRec->getLoop()))
8516 Roots.push_back(S);
8517 }
8518 return true;
8519 }
8520 bool isDone() const { return false; }
8521 };
8522
8523 InvalidationRootCollector C(L);
8524 visitAll(S, C);
8525 forgetMemoizedResults(C.Roots);
8526 }
8527
8528 // Also perform the normal invalidation.
8529 forgetValue(V);
8530 }
8531
forgetLoopDispositions()8532 void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8533
forgetBlockAndLoopDispositions(Value * V)8534 void ScalarEvolution::forgetBlockAndLoopDispositions(Value *V) {
8535 // Unless a specific value is passed to invalidation, completely clear both
8536 // caches.
8537 if (!V) {
8538 BlockDispositions.clear();
8539 LoopDispositions.clear();
8540 return;
8541 }
8542
8543 if (!isSCEVable(V->getType()))
8544 return;
8545
8546 const SCEV *S = getExistingSCEV(V);
8547 if (!S)
8548 return;
8549
8550 // Invalidate the block and loop dispositions cached for S. Dispositions of
8551 // S's users may change if S's disposition changes (i.e. a user may change to
8552 // loop-invariant, if S changes to loop invariant), so also invalidate
8553 // dispositions of S's users recursively.
8554 SmallVector<const SCEV *, 8> Worklist = {S};
8555 SmallPtrSet<const SCEV *, 8> Seen = {S};
8556 while (!Worklist.empty()) {
8557 const SCEV *Curr = Worklist.pop_back_val();
8558 bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8559 bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8560 if (!LoopDispoRemoved && !BlockDispoRemoved)
8561 continue;
8562 auto Users = SCEVUsers.find(Curr);
8563 if (Users != SCEVUsers.end())
8564 for (const auto *User : Users->second)
8565 if (Seen.insert(User).second)
8566 Worklist.push_back(User);
8567 }
8568 }
8569
8570 /// Get the exact loop backedge taken count considering all loop exits. A
8571 /// computable result can only be returned for loops with all exiting blocks
8572 /// dominating the latch. howFarToZero assumes that the limit of each loop test
8573 /// is never skipped. This is a valid assumption as long as the loop exits via
8574 /// that test. For precise results, it is the caller's responsibility to specify
8575 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
8576 const SCEV *
getExact(const Loop * L,ScalarEvolution * SE,SmallVector<const SCEVPredicate *,4> * Preds) const8577 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
8578 SmallVector<const SCEVPredicate *, 4> *Preds) const {
8579 // If any exits were not computable, the loop is not computable.
8580 if (!isComplete() || ExitNotTaken.empty())
8581 return SE->getCouldNotCompute();
8582
8583 const BasicBlock *Latch = L->getLoopLatch();
8584 // All exiting blocks we have collected must dominate the only backedge.
8585 if (!Latch)
8586 return SE->getCouldNotCompute();
8587
8588 // All exiting blocks we have gathered dominate loop's latch, so exact trip
8589 // count is simply a minimum out of all these calculated exit counts.
8590 SmallVector<const SCEV *, 2> Ops;
8591 for (const auto &ENT : ExitNotTaken) {
8592 const SCEV *BECount = ENT.ExactNotTaken;
8593 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8594 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8595 "We should only have known counts for exiting blocks that dominate "
8596 "latch!");
8597
8598 Ops.push_back(BECount);
8599
8600 if (Preds)
8601 for (const auto *P : ENT.Predicates)
8602 Preds->push_back(P);
8603
8604 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8605 "Predicate should be always true!");
8606 }
8607
8608 // If an earlier exit exits on the first iteration (exit count zero), then
8609 // a later poison exit count should not propagate into the result. This are
8610 // exactly the semantics provided by umin_seq.
8611 return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8612 }
8613
8614 /// Get the exact not taken count for this loop exit.
8615 const SCEV *
getExact(const BasicBlock * ExitingBlock,ScalarEvolution * SE) const8616 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
8617 ScalarEvolution *SE) const {
8618 for (const auto &ENT : ExitNotTaken)
8619 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8620 return ENT.ExactNotTaken;
8621
8622 return SE->getCouldNotCompute();
8623 }
8624
getConstantMax(const BasicBlock * ExitingBlock,ScalarEvolution * SE) const8625 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8626 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
8627 for (const auto &ENT : ExitNotTaken)
8628 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8629 return ENT.ConstantMaxNotTaken;
8630
8631 return SE->getCouldNotCompute();
8632 }
8633
getSymbolicMax(const BasicBlock * ExitingBlock,ScalarEvolution * SE) const8634 const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8635 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
8636 for (const auto &ENT : ExitNotTaken)
8637 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8638 return ENT.SymbolicMaxNotTaken;
8639
8640 return SE->getCouldNotCompute();
8641 }
8642
8643 /// getConstantMax - Get the constant max backedge taken count for the loop.
8644 const SCEV *
getConstantMax(ScalarEvolution * SE) const8645 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
8646 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8647 return !ENT.hasAlwaysTruePredicate();
8648 };
8649
8650 if (!getConstantMax() || any_of(ExitNotTaken, PredicateNotAlwaysTrue))
8651 return SE->getCouldNotCompute();
8652
8653 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8654 isa<SCEVConstant>(getConstantMax())) &&
8655 "No point in having a non-constant max backedge taken count!");
8656 return getConstantMax();
8657 }
8658
getSymbolicMax(const Loop * L,ScalarEvolution * SE,SmallVector<const SCEVPredicate *,4> * Predicates)8659 const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8660 const Loop *L, ScalarEvolution *SE,
8661 SmallVector<const SCEVPredicate *, 4> *Predicates) {
8662 if (!SymbolicMax) {
8663 // Form an expression for the maximum exit count possible for this loop. We
8664 // merge the max and exact information to approximate a version of
8665 // getConstantMaxBackedgeTakenCount which isn't restricted to just
8666 // constants.
8667 SmallVector<const SCEV *, 4> ExitCounts;
8668
8669 for (const auto &ENT : ExitNotTaken) {
8670 const SCEV *ExitCount = ENT.SymbolicMaxNotTaken;
8671 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
8672 assert(SE->DT.dominates(ENT.ExitingBlock, L->getLoopLatch()) &&
8673 "We should only have known counts for exiting blocks that "
8674 "dominate latch!");
8675 ExitCounts.push_back(ExitCount);
8676 if (Predicates)
8677 for (const auto *P : ENT.Predicates)
8678 Predicates->push_back(P);
8679
8680 assert((Predicates || ENT.hasAlwaysTruePredicate()) &&
8681 "Predicate should be always true!");
8682 }
8683 }
8684 if (ExitCounts.empty())
8685 SymbolicMax = SE->getCouldNotCompute();
8686 else
8687 SymbolicMax =
8688 SE->getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
8689 }
8690 return SymbolicMax;
8691 }
8692
isConstantMaxOrZero(ScalarEvolution * SE) const8693 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8694 ScalarEvolution *SE) const {
8695 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8696 return !ENT.hasAlwaysTruePredicate();
8697 };
8698 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8699 }
8700
ExitLimit(const SCEV * E)8701 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
8702 : ExitLimit(E, E, E, false, std::nullopt) {}
8703
ExitLimit(const SCEV * E,const SCEV * ConstantMaxNotTaken,const SCEV * SymbolicMaxNotTaken,bool MaxOrZero,ArrayRef<const SmallPtrSetImpl<const SCEVPredicate * > * > PredSetList)8704 ScalarEvolution::ExitLimit::ExitLimit(
8705 const SCEV *E, const SCEV *ConstantMaxNotTaken,
8706 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8707 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
8708 : ExactNotTaken(E), ConstantMaxNotTaken(ConstantMaxNotTaken),
8709 SymbolicMaxNotTaken(SymbolicMaxNotTaken), MaxOrZero(MaxOrZero) {
8710 // If we prove the max count is zero, so is the symbolic bound. This happens
8711 // in practice due to differences in a) how context sensitive we've chosen
8712 // to be and b) how we reason about bounds implied by UB.
8713 if (ConstantMaxNotTaken->isZero()) {
8714 this->ExactNotTaken = E = ConstantMaxNotTaken;
8715 this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
8716 }
8717
8718 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
8719 !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) &&
8720 "Exact is not allowed to be less precise than Constant Max");
8721 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
8722 !isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken)) &&
8723 "Exact is not allowed to be less precise than Symbolic Max");
8724 assert((isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken) ||
8725 !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) &&
8726 "Symbolic Max is not allowed to be less precise than Constant Max");
8727 assert((isa<SCEVCouldNotCompute>(ConstantMaxNotTaken) ||
8728 isa<SCEVConstant>(ConstantMaxNotTaken)) &&
8729 "No point in having a non-constant max backedge taken count!");
8730 for (const auto *PredSet : PredSetList)
8731 for (const auto *P : *PredSet)
8732 addPredicate(P);
8733 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8734 "Backedge count should be int");
8735 assert((isa<SCEVCouldNotCompute>(ConstantMaxNotTaken) ||
8736 !ConstantMaxNotTaken->getType()->isPointerTy()) &&
8737 "Max backedge count should be int");
8738 }
8739
ExitLimit(const SCEV * E,const SCEV * ConstantMaxNotTaken,const SCEV * SymbolicMaxNotTaken,bool MaxOrZero,const SmallPtrSetImpl<const SCEVPredicate * > & PredSet)8740 ScalarEvolution::ExitLimit::ExitLimit(
8741 const SCEV *E, const SCEV *ConstantMaxNotTaken,
8742 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8743 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
8744 : ExitLimit(E, ConstantMaxNotTaken, SymbolicMaxNotTaken, MaxOrZero,
8745 { &PredSet }) {}
8746
8747 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8748 /// computable exit into a persistent ExitNotTakenInfo array.
BackedgeTakenInfo(ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,bool IsComplete,const SCEV * ConstantMax,bool MaxOrZero)8749 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8750 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
8751 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
8752 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8753 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8754
8755 ExitNotTaken.reserve(ExitCounts.size());
8756 std::transform(ExitCounts.begin(), ExitCounts.end(),
8757 std::back_inserter(ExitNotTaken),
8758 [&](const EdgeExitInfo &EEI) {
8759 BasicBlock *ExitBB = EEI.first;
8760 const ExitLimit &EL = EEI.second;
8761 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
8762 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
8763 EL.Predicates);
8764 });
8765 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
8766 isa<SCEVConstant>(ConstantMax)) &&
8767 "No point in having a non-constant max backedge taken count!");
8768 }
8769
8770 /// Compute the number of times the backedge of the specified loop will execute.
8771 ScalarEvolution::BackedgeTakenInfo
computeBackedgeTakenCount(const Loop * L,bool AllowPredicates)8772 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
8773 bool AllowPredicates) {
8774 SmallVector<BasicBlock *, 8> ExitingBlocks;
8775 L->getExitingBlocks(ExitingBlocks);
8776
8777 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8778
8779 SmallVector<EdgeExitInfo, 4> ExitCounts;
8780 bool CouldComputeBECount = true;
8781 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
8782 const SCEV *MustExitMaxBECount = nullptr;
8783 const SCEV *MayExitMaxBECount = nullptr;
8784 bool MustExitMaxOrZero = false;
8785 bool IsOnlyExit = ExitingBlocks.size() == 1;
8786
8787 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
8788 // and compute maxBECount.
8789 // Do a union of all the predicates here.
8790 for (BasicBlock *ExitBB : ExitingBlocks) {
8791 // We canonicalize untaken exits to br (constant), ignore them so that
8792 // proving an exit untaken doesn't negatively impact our ability to reason
8793 // about the loop as whole.
8794 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
8795 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
8796 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8797 if (ExitIfTrue == CI->isZero())
8798 continue;
8799 }
8800
8801 ExitLimit EL = computeExitLimit(L, ExitBB, IsOnlyExit, AllowPredicates);
8802
8803 assert((AllowPredicates || EL.Predicates.empty()) &&
8804 "Predicated exit limit when predicates are not allowed!");
8805
8806 // 1. For each exit that can be computed, add an entry to ExitCounts.
8807 // CouldComputeBECount is true only if all exits can be computed.
8808 if (EL.ExactNotTaken != getCouldNotCompute())
8809 ++NumExitCountsComputed;
8810 else
8811 // We couldn't compute an exact value for this exit, so
8812 // we won't be able to compute an exact value for the loop.
8813 CouldComputeBECount = false;
8814 // Remember exit count if either exact or symbolic is known. Because
8815 // Exact always implies symbolic, only check symbolic.
8816 if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
8817 ExitCounts.emplace_back(ExitBB, EL);
8818 else {
8819 assert(EL.ExactNotTaken == getCouldNotCompute() &&
8820 "Exact is known but symbolic isn't?");
8821 ++NumExitCountsNotComputed;
8822 }
8823
8824 // 2. Derive the loop's MaxBECount from each exit's max number of
8825 // non-exiting iterations. Partition the loop exits into two kinds:
8826 // LoopMustExits and LoopMayExits.
8827 //
8828 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
8829 // is a LoopMayExit. If any computable LoopMustExit is found, then
8830 // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
8831 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
8832 // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
8833 // any
8834 // computable EL.ConstantMaxNotTaken.
8835 if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
8836 DT.dominates(ExitBB, Latch)) {
8837 if (!MustExitMaxBECount) {
8838 MustExitMaxBECount = EL.ConstantMaxNotTaken;
8839 MustExitMaxOrZero = EL.MaxOrZero;
8840 } else {
8841 MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
8842 EL.ConstantMaxNotTaken);
8843 }
8844 } else if (MayExitMaxBECount != getCouldNotCompute()) {
8845 if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
8846 MayExitMaxBECount = EL.ConstantMaxNotTaken;
8847 else {
8848 MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
8849 EL.ConstantMaxNotTaken);
8850 }
8851 }
8852 }
8853 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
8854 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
8855 // The loop backedge will be taken the maximum or zero times if there's
8856 // a single exit that must be taken the maximum or zero times.
8857 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
8858
8859 // Remember which SCEVs are used in exit limits for invalidation purposes.
8860 // We only care about non-constant SCEVs here, so we can ignore
8861 // EL.ConstantMaxNotTaken
8862 // and MaxBECount, which must be SCEVConstant.
8863 for (const auto &Pair : ExitCounts) {
8864 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
8865 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
8866 if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
8867 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
8868 {L, AllowPredicates});
8869 }
8870 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
8871 MaxBECount, MaxOrZero);
8872 }
8873
8874 ScalarEvolution::ExitLimit
computeExitLimit(const Loop * L,BasicBlock * ExitingBlock,bool IsOnlyExit,bool AllowPredicates)8875 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
8876 bool IsOnlyExit, bool AllowPredicates) {
8877 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
8878 // If our exiting block does not dominate the latch, then its connection with
8879 // loop's exit limit may be far from trivial.
8880 const BasicBlock *Latch = L->getLoopLatch();
8881 if (!Latch || !DT.dominates(ExitingBlock, Latch))
8882 return getCouldNotCompute();
8883
8884 Instruction *Term = ExitingBlock->getTerminator();
8885 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
8886 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
8887 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8888 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
8889 "It should have one successor in loop and one exit block!");
8890 // Proceed to the next level to examine the exit condition expression.
8891 return computeExitLimitFromCond(L, BI->getCondition(), ExitIfTrue,
8892 /*ControlsOnlyExit=*/IsOnlyExit,
8893 AllowPredicates);
8894 }
8895
8896 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
8897 // For switch, make sure that there is a single exit from the loop.
8898 BasicBlock *Exit = nullptr;
8899 for (auto *SBB : successors(ExitingBlock))
8900 if (!L->contains(SBB)) {
8901 if (Exit) // Multiple exit successors.
8902 return getCouldNotCompute();
8903 Exit = SBB;
8904 }
8905 assert(Exit && "Exiting block must have at least one exit");
8906 return computeExitLimitFromSingleExitSwitch(
8907 L, SI, Exit, /*ControlsOnlyExit=*/IsOnlyExit);
8908 }
8909
8910 return getCouldNotCompute();
8911 }
8912
computeExitLimitFromCond(const Loop * L,Value * ExitCond,bool ExitIfTrue,bool ControlsOnlyExit,bool AllowPredicates)8913 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
8914 const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
8915 bool AllowPredicates) {
8916 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
8917 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
8918 ControlsOnlyExit, AllowPredicates);
8919 }
8920
8921 std::optional<ScalarEvolution::ExitLimit>
find(const Loop * L,Value * ExitCond,bool ExitIfTrue,bool ControlsOnlyExit,bool AllowPredicates)8922 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
8923 bool ExitIfTrue, bool ControlsOnlyExit,
8924 bool AllowPredicates) {
8925 (void)this->L;
8926 (void)this->ExitIfTrue;
8927 (void)this->AllowPredicates;
8928
8929 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8930 this->AllowPredicates == AllowPredicates &&
8931 "Variance in assumed invariant key components!");
8932 auto Itr = TripCountMap.find({ExitCond, ControlsOnlyExit});
8933 if (Itr == TripCountMap.end())
8934 return std::nullopt;
8935 return Itr->second;
8936 }
8937
insert(const Loop * L,Value * ExitCond,bool ExitIfTrue,bool ControlsOnlyExit,bool AllowPredicates,const ExitLimit & EL)8938 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
8939 bool ExitIfTrue,
8940 bool ControlsOnlyExit,
8941 bool AllowPredicates,
8942 const ExitLimit &EL) {
8943 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8944 this->AllowPredicates == AllowPredicates &&
8945 "Variance in assumed invariant key components!");
8946
8947 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsOnlyExit}, EL});
8948 assert(InsertResult.second && "Expected successful insertion!");
8949 (void)InsertResult;
8950 (void)ExitIfTrue;
8951 }
8952
computeExitLimitFromCondCached(ExitLimitCacheTy & Cache,const Loop * L,Value * ExitCond,bool ExitIfTrue,bool ControlsOnlyExit,bool AllowPredicates)8953 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
8954 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8955 bool ControlsOnlyExit, bool AllowPredicates) {
8956
8957 if (auto MaybeEL = Cache.find(L, ExitCond, ExitIfTrue, ControlsOnlyExit,
8958 AllowPredicates))
8959 return *MaybeEL;
8960
8961 ExitLimit EL = computeExitLimitFromCondImpl(
8962 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates);
8963 Cache.insert(L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates, EL);
8964 return EL;
8965 }
8966
computeExitLimitFromCondImpl(ExitLimitCacheTy & Cache,const Loop * L,Value * ExitCond,bool ExitIfTrue,bool ControlsOnlyExit,bool AllowPredicates)8967 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
8968 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8969 bool ControlsOnlyExit, bool AllowPredicates) {
8970 // Handle BinOp conditions (And, Or).
8971 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
8972 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates))
8973 return *LimitFromBinOp;
8974
8975 // With an icmp, it may be feasible to compute an exact backedge-taken count.
8976 // Proceed to the next level to examine the icmp.
8977 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
8978 ExitLimit EL =
8979 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsOnlyExit);
8980 if (EL.hasFullInfo() || !AllowPredicates)
8981 return EL;
8982
8983 // Try again, but use SCEV predicates this time.
8984 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue,
8985 ControlsOnlyExit,
8986 /*AllowPredicates=*/true);
8987 }
8988
8989 // Check for a constant condition. These are normally stripped out by
8990 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
8991 // preserve the CFG and is temporarily leaving constant conditions
8992 // in place.
8993 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
8994 if (ExitIfTrue == !CI->getZExtValue())
8995 // The backedge is always taken.
8996 return getCouldNotCompute();
8997 // The backedge is never taken.
8998 return getZero(CI->getType());
8999 }
9000
9001 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
9002 // with a constant step, we can form an equivalent icmp predicate and figure
9003 // out how many iterations will be taken before we exit.
9004 const WithOverflowInst *WO;
9005 const APInt *C;
9006 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
9007 match(WO->getRHS(), m_APInt(C))) {
9008 ConstantRange NWR =
9009 ConstantRange::makeExactNoWrapRegion(WO->getBinaryOp(), *C,
9010 WO->getNoWrapKind());
9011 CmpInst::Predicate Pred;
9012 APInt NewRHSC, Offset;
9013 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
9014 if (!ExitIfTrue)
9015 Pred = ICmpInst::getInversePredicate(Pred);
9016 auto *LHS = getSCEV(WO->getLHS());
9017 if (Offset != 0)
9018 LHS = getAddExpr(LHS, getConstant(Offset));
9019 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
9020 ControlsOnlyExit, AllowPredicates);
9021 if (EL.hasAnyInfo())
9022 return EL;
9023 }
9024
9025 // If it's not an integer or pointer comparison then compute it the hard way.
9026 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9027 }
9028
9029 std::optional<ScalarEvolution::ExitLimit>
computeExitLimitFromCondFromBinOp(ExitLimitCacheTy & Cache,const Loop * L,Value * ExitCond,bool ExitIfTrue,bool ControlsOnlyExit,bool AllowPredicates)9030 ScalarEvolution::computeExitLimitFromCondFromBinOp(
9031 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9032 bool ControlsOnlyExit, bool AllowPredicates) {
9033 // Check if the controlling expression for this loop is an And or Or.
9034 Value *Op0, *Op1;
9035 bool IsAnd = false;
9036 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
9037 IsAnd = true;
9038 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
9039 IsAnd = false;
9040 else
9041 return std::nullopt;
9042
9043 // EitherMayExit is true in these two cases:
9044 // br (and Op0 Op1), loop, exit
9045 // br (or Op0 Op1), exit, loop
9046 bool EitherMayExit = IsAnd ^ ExitIfTrue;
9047 ExitLimit EL0 = computeExitLimitFromCondCached(
9048 Cache, L, Op0, ExitIfTrue, ControlsOnlyExit && !EitherMayExit,
9049 AllowPredicates);
9050 ExitLimit EL1 = computeExitLimitFromCondCached(
9051 Cache, L, Op1, ExitIfTrue, ControlsOnlyExit && !EitherMayExit,
9052 AllowPredicates);
9053
9054 // Be robust against unsimplified IR for the form "op i1 X, NeutralElement"
9055 const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd);
9056 if (isa<ConstantInt>(Op1))
9057 return Op1 == NeutralElement ? EL0 : EL1;
9058 if (isa<ConstantInt>(Op0))
9059 return Op0 == NeutralElement ? EL1 : EL0;
9060
9061 const SCEV *BECount = getCouldNotCompute();
9062 const SCEV *ConstantMaxBECount = getCouldNotCompute();
9063 const SCEV *SymbolicMaxBECount = getCouldNotCompute();
9064 if (EitherMayExit) {
9065 bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
9066 // Both conditions must be same for the loop to continue executing.
9067 // Choose the less conservative count.
9068 if (EL0.ExactNotTaken != getCouldNotCompute() &&
9069 EL1.ExactNotTaken != getCouldNotCompute()) {
9070 BECount = getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken,
9071 UseSequentialUMin);
9072 }
9073 if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
9074 ConstantMaxBECount = EL1.ConstantMaxNotTaken;
9075 else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
9076 ConstantMaxBECount = EL0.ConstantMaxNotTaken;
9077 else
9078 ConstantMaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
9079 EL1.ConstantMaxNotTaken);
9080 if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
9081 SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
9082 else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
9083 SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
9084 else
9085 SymbolicMaxBECount = getUMinFromMismatchedTypes(
9086 EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
9087 } else {
9088 // Both conditions must be same at the same time for the loop to exit.
9089 // For now, be conservative.
9090 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
9091 BECount = EL0.ExactNotTaken;
9092 }
9093
9094 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
9095 // to be more aggressive when computing BECount than when computing
9096 // ConstantMaxBECount. In these cases it is possible for EL0.ExactNotTaken
9097 // and
9098 // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
9099 // EL1.ConstantMaxNotTaken to not.
9100 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
9101 !isa<SCEVCouldNotCompute>(BECount))
9102 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
9103 if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
9104 SymbolicMaxBECount =
9105 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
9106 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
9107 { &EL0.Predicates, &EL1.Predicates });
9108 }
9109
computeExitLimitFromICmp(const Loop * L,ICmpInst * ExitCond,bool ExitIfTrue,bool ControlsOnlyExit,bool AllowPredicates)9110 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9111 const Loop *L, ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9112 bool AllowPredicates) {
9113 // If the condition was exit on true, convert the condition to exit on false
9114 ICmpInst::Predicate Pred;
9115 if (!ExitIfTrue)
9116 Pred = ExitCond->getPredicate();
9117 else
9118 Pred = ExitCond->getInversePredicate();
9119 const ICmpInst::Predicate OriginalPred = Pred;
9120
9121 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
9122 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
9123
9124 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsOnlyExit,
9125 AllowPredicates);
9126 if (EL.hasAnyInfo())
9127 return EL;
9128
9129 auto *ExhaustiveCount =
9130 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9131
9132 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
9133 return ExhaustiveCount;
9134
9135 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
9136 ExitCond->getOperand(1), L, OriginalPred);
9137 }
computeExitLimitFromICmp(const Loop * L,ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,bool ControlsOnlyExit,bool AllowPredicates)9138 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9139 const Loop *L, ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
9140 bool ControlsOnlyExit, bool AllowPredicates) {
9141
9142 // Try to evaluate any dependencies out of the loop.
9143 LHS = getSCEVAtScope(LHS, L);
9144 RHS = getSCEVAtScope(RHS, L);
9145
9146 // At this point, we would like to compute how many iterations of the
9147 // loop the predicate will return true for these inputs.
9148 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
9149 // If there is a loop-invariant, force it into the RHS.
9150 std::swap(LHS, RHS);
9151 Pred = ICmpInst::getSwappedPredicate(Pred);
9152 }
9153
9154 bool ControllingFiniteLoop = ControlsOnlyExit && loopHasNoAbnormalExits(L) &&
9155 loopIsFiniteByAssumption(L);
9156 // Simplify the operands before analyzing them.
9157 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0);
9158
9159 // If we have a comparison of a chrec against a constant, try to use value
9160 // ranges to answer this query.
9161 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
9162 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
9163 if (AddRec->getLoop() == L) {
9164 // Form the constant range.
9165 ConstantRange CompRange =
9166 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
9167
9168 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
9169 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
9170 }
9171
9172 // If this loop must exit based on this condition (or execute undefined
9173 // behaviour), and we can prove the test sequence produced must repeat
9174 // the same values on self-wrap of the IV, then we can infer that IV
9175 // doesn't self wrap because if it did, we'd have an infinite (undefined)
9176 // loop.
9177 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
9178 // TODO: We can peel off any functions which are invertible *in L*. Loop
9179 // invariant terms are effectively constants for our purposes here.
9180 auto *InnerLHS = LHS;
9181 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
9182 InnerLHS = ZExt->getOperand();
9183 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS)) {
9184 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
9185 if (!AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
9186 StrideC && StrideC->getAPInt().isPowerOf2()) {
9187 auto Flags = AR->getNoWrapFlags();
9188 Flags = setFlags(Flags, SCEV::FlagNW);
9189 SmallVector<const SCEV*> Operands{AR->operands()};
9190 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
9191 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9192 }
9193 }
9194 }
9195
9196 switch (Pred) {
9197 case ICmpInst::ICMP_NE: { // while (X != Y)
9198 // Convert to: while (X-Y != 0)
9199 if (LHS->getType()->isPointerTy()) {
9200 LHS = getLosslessPtrToIntExpr(LHS);
9201 if (isa<SCEVCouldNotCompute>(LHS))
9202 return LHS;
9203 }
9204 if (RHS->getType()->isPointerTy()) {
9205 RHS = getLosslessPtrToIntExpr(RHS);
9206 if (isa<SCEVCouldNotCompute>(RHS))
9207 return RHS;
9208 }
9209 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit,
9210 AllowPredicates);
9211 if (EL.hasAnyInfo())
9212 return EL;
9213 break;
9214 }
9215 case ICmpInst::ICMP_EQ: { // while (X == Y)
9216 // Convert to: while (X-Y == 0)
9217 if (LHS->getType()->isPointerTy()) {
9218 LHS = getLosslessPtrToIntExpr(LHS);
9219 if (isa<SCEVCouldNotCompute>(LHS))
9220 return LHS;
9221 }
9222 if (RHS->getType()->isPointerTy()) {
9223 RHS = getLosslessPtrToIntExpr(RHS);
9224 if (isa<SCEVCouldNotCompute>(RHS))
9225 return RHS;
9226 }
9227 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
9228 if (EL.hasAnyInfo()) return EL;
9229 break;
9230 }
9231 case ICmpInst::ICMP_SLE:
9232 case ICmpInst::ICMP_ULE:
9233 // Since the loop is finite, an invariant RHS cannot include the boundary
9234 // value, otherwise it would loop forever.
9235 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9236 !isLoopInvariant(RHS, L)) {
9237 // Otherwise, perform the addition in a wider type, to avoid overflow.
9238 // If the LHS is an addrec with the appropriate nowrap flag, the
9239 // extension will be sunk into it and the exit count can be analyzed.
9240 auto *OldType = dyn_cast<IntegerType>(LHS->getType());
9241 if (!OldType)
9242 break;
9243 // Prefer doubling the bitwidth over adding a single bit to make it more
9244 // likely that we use a legal type.
9245 auto *NewType =
9246 Type::getIntNTy(OldType->getContext(), OldType->getBitWidth() * 2);
9247 if (ICmpInst::isSigned(Pred)) {
9248 LHS = getSignExtendExpr(LHS, NewType);
9249 RHS = getSignExtendExpr(RHS, NewType);
9250 } else {
9251 LHS = getZeroExtendExpr(LHS, NewType);
9252 RHS = getZeroExtendExpr(RHS, NewType);
9253 }
9254 }
9255 RHS = getAddExpr(getOne(RHS->getType()), RHS);
9256 [[fallthrough]];
9257 case ICmpInst::ICMP_SLT:
9258 case ICmpInst::ICMP_ULT: { // while (X < Y)
9259 bool IsSigned = ICmpInst::isSigned(Pred);
9260 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9261 AllowPredicates);
9262 if (EL.hasAnyInfo())
9263 return EL;
9264 break;
9265 }
9266 case ICmpInst::ICMP_SGE:
9267 case ICmpInst::ICMP_UGE:
9268 // Since the loop is finite, an invariant RHS cannot include the boundary
9269 // value, otherwise it would loop forever.
9270 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9271 !isLoopInvariant(RHS, L))
9272 break;
9273 RHS = getAddExpr(getMinusOne(RHS->getType()), RHS);
9274 [[fallthrough]];
9275 case ICmpInst::ICMP_SGT:
9276 case ICmpInst::ICMP_UGT: { // while (X > Y)
9277 bool IsSigned = ICmpInst::isSigned(Pred);
9278 ExitLimit EL = howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9279 AllowPredicates);
9280 if (EL.hasAnyInfo())
9281 return EL;
9282 break;
9283 }
9284 default:
9285 break;
9286 }
9287
9288 return getCouldNotCompute();
9289 }
9290
9291 ScalarEvolution::ExitLimit
computeExitLimitFromSingleExitSwitch(const Loop * L,SwitchInst * Switch,BasicBlock * ExitingBlock,bool ControlsOnlyExit)9292 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
9293 SwitchInst *Switch,
9294 BasicBlock *ExitingBlock,
9295 bool ControlsOnlyExit) {
9296 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
9297
9298 // Give up if the exit is the default dest of a switch.
9299 if (Switch->getDefaultDest() == ExitingBlock)
9300 return getCouldNotCompute();
9301
9302 assert(L->contains(Switch->getDefaultDest()) &&
9303 "Default case must not exit the loop!");
9304 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
9305 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
9306
9307 // while (X != Y) --> while (X-Y != 0)
9308 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit);
9309 if (EL.hasAnyInfo())
9310 return EL;
9311
9312 return getCouldNotCompute();
9313 }
9314
9315 static ConstantInt *
EvaluateConstantChrecAtConstant(const SCEVAddRecExpr * AddRec,ConstantInt * C,ScalarEvolution & SE)9316 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
9317 ScalarEvolution &SE) {
9318 const SCEV *InVal = SE.getConstant(C);
9319 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
9320 assert(isa<SCEVConstant>(Val) &&
9321 "Evaluation of SCEV at constant didn't fold correctly?");
9322 return cast<SCEVConstant>(Val)->getValue();
9323 }
9324
computeShiftCompareExitLimit(Value * LHS,Value * RHSV,const Loop * L,ICmpInst::Predicate Pred)9325 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
9326 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
9327 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
9328 if (!RHS)
9329 return getCouldNotCompute();
9330
9331 const BasicBlock *Latch = L->getLoopLatch();
9332 if (!Latch)
9333 return getCouldNotCompute();
9334
9335 const BasicBlock *Predecessor = L->getLoopPredecessor();
9336 if (!Predecessor)
9337 return getCouldNotCompute();
9338
9339 // Return true if V is of the form "LHS `shift_op` <positive constant>".
9340 // Return LHS in OutLHS and shift_opt in OutOpCode.
9341 auto MatchPositiveShift =
9342 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
9343
9344 using namespace PatternMatch;
9345
9346 ConstantInt *ShiftAmt;
9347 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9348 OutOpCode = Instruction::LShr;
9349 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9350 OutOpCode = Instruction::AShr;
9351 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9352 OutOpCode = Instruction::Shl;
9353 else
9354 return false;
9355
9356 return ShiftAmt->getValue().isStrictlyPositive();
9357 };
9358
9359 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
9360 //
9361 // loop:
9362 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
9363 // %iv.shifted = lshr i32 %iv, <positive constant>
9364 //
9365 // Return true on a successful match. Return the corresponding PHI node (%iv
9366 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
9367 auto MatchShiftRecurrence =
9368 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
9369 std::optional<Instruction::BinaryOps> PostShiftOpCode;
9370
9371 {
9372 Instruction::BinaryOps OpC;
9373 Value *V;
9374
9375 // If we encounter a shift instruction, "peel off" the shift operation,
9376 // and remember that we did so. Later when we inspect %iv's backedge
9377 // value, we will make sure that the backedge value uses the same
9378 // operation.
9379 //
9380 // Note: the peeled shift operation does not have to be the same
9381 // instruction as the one feeding into the PHI's backedge value. We only
9382 // really care about it being the same *kind* of shift instruction --
9383 // that's all that is required for our later inferences to hold.
9384 if (MatchPositiveShift(LHS, V, OpC)) {
9385 PostShiftOpCode = OpC;
9386 LHS = V;
9387 }
9388 }
9389
9390 PNOut = dyn_cast<PHINode>(LHS);
9391 if (!PNOut || PNOut->getParent() != L->getHeader())
9392 return false;
9393
9394 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
9395 Value *OpLHS;
9396
9397 return
9398 // The backedge value for the PHI node must be a shift by a positive
9399 // amount
9400 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
9401
9402 // of the PHI node itself
9403 OpLHS == PNOut &&
9404
9405 // and the kind of shift should be match the kind of shift we peeled
9406 // off, if any.
9407 (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9408 };
9409
9410 PHINode *PN;
9411 Instruction::BinaryOps OpCode;
9412 if (!MatchShiftRecurrence(LHS, PN, OpCode))
9413 return getCouldNotCompute();
9414
9415 const DataLayout &DL = getDataLayout();
9416
9417 // The key rationale for this optimization is that for some kinds of shift
9418 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
9419 // within a finite number of iterations. If the condition guarding the
9420 // backedge (in the sense that the backedge is taken if the condition is true)
9421 // is false for the value the shift recurrence stabilizes to, then we know
9422 // that the backedge is taken only a finite number of times.
9423
9424 ConstantInt *StableValue = nullptr;
9425 switch (OpCode) {
9426 default:
9427 llvm_unreachable("Impossible case!");
9428
9429 case Instruction::AShr: {
9430 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
9431 // bitwidth(K) iterations.
9432 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
9433 KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC,
9434 Predecessor->getTerminator(), &DT);
9435 auto *Ty = cast<IntegerType>(RHS->getType());
9436 if (Known.isNonNegative())
9437 StableValue = ConstantInt::get(Ty, 0);
9438 else if (Known.isNegative())
9439 StableValue = ConstantInt::get(Ty, -1, true);
9440 else
9441 return getCouldNotCompute();
9442
9443 break;
9444 }
9445 case Instruction::LShr:
9446 case Instruction::Shl:
9447 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
9448 // stabilize to 0 in at most bitwidth(K) iterations.
9449 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
9450 break;
9451 }
9452
9453 auto *Result =
9454 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
9455 assert(Result->getType()->isIntegerTy(1) &&
9456 "Otherwise cannot be an operand to a branch instruction");
9457
9458 if (Result->isZeroValue()) {
9459 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9460 const SCEV *UpperBound =
9461 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
9462 return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
9463 }
9464
9465 return getCouldNotCompute();
9466 }
9467
9468 /// Return true if we can constant fold an instruction of the specified type,
9469 /// assuming that all operands were constants.
CanConstantFold(const Instruction * I)9470 static bool CanConstantFold(const Instruction *I) {
9471 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
9472 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
9473 isa<LoadInst>(I) || isa<ExtractValueInst>(I))
9474 return true;
9475
9476 if (const CallInst *CI = dyn_cast<CallInst>(I))
9477 if (const Function *F = CI->getCalledFunction())
9478 return canConstantFoldCallTo(CI, F);
9479 return false;
9480 }
9481
9482 /// Determine whether this instruction can constant evolve within this loop
9483 /// assuming its operands can all constant evolve.
canConstantEvolve(Instruction * I,const Loop * L)9484 static bool canConstantEvolve(Instruction *I, const Loop *L) {
9485 // An instruction outside of the loop can't be derived from a loop PHI.
9486 if (!L->contains(I)) return false;
9487
9488 if (isa<PHINode>(I)) {
9489 // We don't currently keep track of the control flow needed to evaluate
9490 // PHIs, so we cannot handle PHIs inside of loops.
9491 return L->getHeader() == I->getParent();
9492 }
9493
9494 // If we won't be able to constant fold this expression even if the operands
9495 // are constants, bail early.
9496 return CanConstantFold(I);
9497 }
9498
9499 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
9500 /// recursing through each instruction operand until reaching a loop header phi.
9501 static PHINode *
getConstantEvolvingPHIOperands(Instruction * UseInst,const Loop * L,DenseMap<Instruction *,PHINode * > & PHIMap,unsigned Depth)9502 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
9503 DenseMap<Instruction *, PHINode *> &PHIMap,
9504 unsigned Depth) {
9505 if (Depth > MaxConstantEvolvingDepth)
9506 return nullptr;
9507
9508 // Otherwise, we can evaluate this instruction if all of its operands are
9509 // constant or derived from a PHI node themselves.
9510 PHINode *PHI = nullptr;
9511 for (Value *Op : UseInst->operands()) {
9512 if (isa<Constant>(Op)) continue;
9513
9514 Instruction *OpInst = dyn_cast<Instruction>(Op);
9515 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
9516
9517 PHINode *P = dyn_cast<PHINode>(OpInst);
9518 if (!P)
9519 // If this operand is already visited, reuse the prior result.
9520 // We may have P != PHI if this is the deepest point at which the
9521 // inconsistent paths meet.
9522 P = PHIMap.lookup(OpInst);
9523 if (!P) {
9524 // Recurse and memoize the results, whether a phi is found or not.
9525 // This recursive call invalidates pointers into PHIMap.
9526 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
9527 PHIMap[OpInst] = P;
9528 }
9529 if (!P)
9530 return nullptr; // Not evolving from PHI
9531 if (PHI && PHI != P)
9532 return nullptr; // Evolving from multiple different PHIs.
9533 PHI = P;
9534 }
9535 // This is a expression evolving from a constant PHI!
9536 return PHI;
9537 }
9538
9539 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9540 /// in the loop that V is derived from. We allow arbitrary operations along the
9541 /// way, but the operands of an operation must either be constants or a value
9542 /// derived from a constant PHI. If this expression does not fit with these
9543 /// constraints, return null.
getConstantEvolvingPHI(Value * V,const Loop * L)9544 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
9545 Instruction *I = dyn_cast<Instruction>(V);
9546 if (!I || !canConstantEvolve(I, L)) return nullptr;
9547
9548 if (PHINode *PN = dyn_cast<PHINode>(I))
9549 return PN;
9550
9551 // Record non-constant instructions contained by the loop.
9552 DenseMap<Instruction *, PHINode *> PHIMap;
9553 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
9554 }
9555
9556 /// EvaluateExpression - Given an expression that passes the
9557 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9558 /// in the loop has the value PHIVal. If we can't fold this expression for some
9559 /// reason, return null.
EvaluateExpression(Value * V,const Loop * L,DenseMap<Instruction *,Constant * > & Vals,const DataLayout & DL,const TargetLibraryInfo * TLI)9560 static Constant *EvaluateExpression(Value *V, const Loop *L,
9561 DenseMap<Instruction *, Constant *> &Vals,
9562 const DataLayout &DL,
9563 const TargetLibraryInfo *TLI) {
9564 // Convenient constant check, but redundant for recursive calls.
9565 if (Constant *C = dyn_cast<Constant>(V)) return C;
9566 Instruction *I = dyn_cast<Instruction>(V);
9567 if (!I) return nullptr;
9568
9569 if (Constant *C = Vals.lookup(I)) return C;
9570
9571 // An instruction inside the loop depends on a value outside the loop that we
9572 // weren't given a mapping for, or a value such as a call inside the loop.
9573 if (!canConstantEvolve(I, L)) return nullptr;
9574
9575 // An unmapped PHI can be due to a branch or another loop inside this loop,
9576 // or due to this not being the initial iteration through a loop where we
9577 // couldn't compute the evolution of this particular PHI last time.
9578 if (isa<PHINode>(I)) return nullptr;
9579
9580 std::vector<Constant*> Operands(I->getNumOperands());
9581
9582 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9583 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9584 if (!Operand) {
9585 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9586 if (!Operands[i]) return nullptr;
9587 continue;
9588 }
9589 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9590 Vals[Operand] = C;
9591 if (!C) return nullptr;
9592 Operands[i] = C;
9593 }
9594
9595 return ConstantFoldInstOperands(I, Operands, DL, TLI,
9596 /*AllowNonDeterministic=*/false);
9597 }
9598
9599
9600 // If every incoming value to PN except the one for BB is a specific Constant,
9601 // return that, else return nullptr.
getOtherIncomingValue(PHINode * PN,BasicBlock * BB)9602 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
9603 Constant *IncomingVal = nullptr;
9604
9605 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9606 if (PN->getIncomingBlock(i) == BB)
9607 continue;
9608
9609 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
9610 if (!CurrentVal)
9611 return nullptr;
9612
9613 if (IncomingVal != CurrentVal) {
9614 if (IncomingVal)
9615 return nullptr;
9616 IncomingVal = CurrentVal;
9617 }
9618 }
9619
9620 return IncomingVal;
9621 }
9622
9623 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9624 /// in the header of its containing loop, we know the loop executes a
9625 /// constant number of times, and the PHI node is just a recurrence
9626 /// involving constants, fold it.
9627 Constant *
getConstantEvolutionLoopExitValue(PHINode * PN,const APInt & BEs,const Loop * L)9628 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9629 const APInt &BEs,
9630 const Loop *L) {
9631 auto I = ConstantEvolutionLoopExitValue.find(PN);
9632 if (I != ConstantEvolutionLoopExitValue.end())
9633 return I->second;
9634
9635 if (BEs.ugt(MaxBruteForceIterations))
9636 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
9637
9638 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
9639
9640 DenseMap<Instruction *, Constant *> CurrentIterVals;
9641 BasicBlock *Header = L->getHeader();
9642 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9643
9644 BasicBlock *Latch = L->getLoopLatch();
9645 if (!Latch)
9646 return nullptr;
9647
9648 for (PHINode &PHI : Header->phis()) {
9649 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9650 CurrentIterVals[&PHI] = StartCST;
9651 }
9652 if (!CurrentIterVals.count(PN))
9653 return RetVal = nullptr;
9654
9655 Value *BEValue = PN->getIncomingValueForBlock(Latch);
9656
9657 // Execute the loop symbolically to determine the exit value.
9658 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
9659 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
9660
9661 unsigned NumIterations = BEs.getZExtValue(); // must be in range
9662 unsigned IterationNum = 0;
9663 const DataLayout &DL = getDataLayout();
9664 for (; ; ++IterationNum) {
9665 if (IterationNum == NumIterations)
9666 return RetVal = CurrentIterVals[PN]; // Got exit value!
9667
9668 // Compute the value of the PHIs for the next iteration.
9669 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9670 DenseMap<Instruction *, Constant *> NextIterVals;
9671 Constant *NextPHI =
9672 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9673 if (!NextPHI)
9674 return nullptr; // Couldn't evaluate!
9675 NextIterVals[PN] = NextPHI;
9676
9677 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9678
9679 // Also evaluate the other PHI nodes. However, we don't get to stop if we
9680 // cease to be able to evaluate one of them or if they stop evolving,
9681 // because that doesn't necessarily prevent us from computing PN.
9682 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
9683 for (const auto &I : CurrentIterVals) {
9684 PHINode *PHI = dyn_cast<PHINode>(I.first);
9685 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
9686 PHIsToCompute.emplace_back(PHI, I.second);
9687 }
9688 // We use two distinct loops because EvaluateExpression may invalidate any
9689 // iterators into CurrentIterVals.
9690 for (const auto &I : PHIsToCompute) {
9691 PHINode *PHI = I.first;
9692 Constant *&NextPHI = NextIterVals[PHI];
9693 if (!NextPHI) { // Not already computed.
9694 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9695 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9696 }
9697 if (NextPHI != I.second)
9698 StoppedEvolving = false;
9699 }
9700
9701 // If all entries in CurrentIterVals == NextIterVals then we can stop
9702 // iterating, the loop can't continue to change.
9703 if (StoppedEvolving)
9704 return RetVal = CurrentIterVals[PN];
9705
9706 CurrentIterVals.swap(NextIterVals);
9707 }
9708 }
9709
computeExitCountExhaustively(const Loop * L,Value * Cond,bool ExitWhen)9710 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
9711 Value *Cond,
9712 bool ExitWhen) {
9713 PHINode *PN = getConstantEvolvingPHI(Cond, L);
9714 if (!PN) return getCouldNotCompute();
9715
9716 // If the loop is canonicalized, the PHI will have exactly two entries.
9717 // That's the only form we support here.
9718 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
9719
9720 DenseMap<Instruction *, Constant *> CurrentIterVals;
9721 BasicBlock *Header = L->getHeader();
9722 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9723
9724 BasicBlock *Latch = L->getLoopLatch();
9725 assert(Latch && "Should follow from NumIncomingValues == 2!");
9726
9727 for (PHINode &PHI : Header->phis()) {
9728 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9729 CurrentIterVals[&PHI] = StartCST;
9730 }
9731 if (!CurrentIterVals.count(PN))
9732 return getCouldNotCompute();
9733
9734 // Okay, we find a PHI node that defines the trip count of this loop. Execute
9735 // the loop symbolically to determine when the condition gets a value of
9736 // "ExitWhen".
9737 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
9738 const DataLayout &DL = getDataLayout();
9739 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
9740 auto *CondVal = dyn_cast_or_null<ConstantInt>(
9741 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
9742
9743 // Couldn't symbolically evaluate.
9744 if (!CondVal) return getCouldNotCompute();
9745
9746 if (CondVal->getValue() == uint64_t(ExitWhen)) {
9747 ++NumBruteForceTripCountsComputed;
9748 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
9749 }
9750
9751 // Update all the PHI nodes for the next iteration.
9752 DenseMap<Instruction *, Constant *> NextIterVals;
9753
9754 // Create a list of which PHIs we need to compute. We want to do this before
9755 // calling EvaluateExpression on them because that may invalidate iterators
9756 // into CurrentIterVals.
9757 SmallVector<PHINode *, 8> PHIsToCompute;
9758 for (const auto &I : CurrentIterVals) {
9759 PHINode *PHI = dyn_cast<PHINode>(I.first);
9760 if (!PHI || PHI->getParent() != Header) continue;
9761 PHIsToCompute.push_back(PHI);
9762 }
9763 for (PHINode *PHI : PHIsToCompute) {
9764 Constant *&NextPHI = NextIterVals[PHI];
9765 if (NextPHI) continue; // Already computed!
9766
9767 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9768 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9769 }
9770 CurrentIterVals.swap(NextIterVals);
9771 }
9772
9773 // Too many iterations were needed to evaluate.
9774 return getCouldNotCompute();
9775 }
9776
getSCEVAtScope(const SCEV * V,const Loop * L)9777 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
9778 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
9779 ValuesAtScopes[V];
9780 // Check to see if we've folded this expression at this loop before.
9781 for (auto &LS : Values)
9782 if (LS.first == L)
9783 return LS.second ? LS.second : V;
9784
9785 Values.emplace_back(L, nullptr);
9786
9787 // Otherwise compute it.
9788 const SCEV *C = computeSCEVAtScope(V, L);
9789 for (auto &LS : reverse(ValuesAtScopes[V]))
9790 if (LS.first == L) {
9791 LS.second = C;
9792 if (!isa<SCEVConstant>(C))
9793 ValuesAtScopesUsers[C].push_back({L, V});
9794 break;
9795 }
9796 return C;
9797 }
9798
9799 /// This builds up a Constant using the ConstantExpr interface. That way, we
9800 /// will return Constants for objects which aren't represented by a
9801 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
9802 /// Returns NULL if the SCEV isn't representable as a Constant.
BuildConstantFromSCEV(const SCEV * V)9803 static Constant *BuildConstantFromSCEV(const SCEV *V) {
9804 switch (V->getSCEVType()) {
9805 case scCouldNotCompute:
9806 case scAddRecExpr:
9807 case scVScale:
9808 return nullptr;
9809 case scConstant:
9810 return cast<SCEVConstant>(V)->getValue();
9811 case scUnknown:
9812 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
9813 case scPtrToInt: {
9814 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
9815 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
9816 return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
9817
9818 return nullptr;
9819 }
9820 case scTruncate: {
9821 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
9822 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
9823 return ConstantExpr::getTrunc(CastOp, ST->getType());
9824 return nullptr;
9825 }
9826 case scAddExpr: {
9827 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
9828 Constant *C = nullptr;
9829 for (const SCEV *Op : SA->operands()) {
9830 Constant *OpC = BuildConstantFromSCEV(Op);
9831 if (!OpC)
9832 return nullptr;
9833 if (!C) {
9834 C = OpC;
9835 continue;
9836 }
9837 assert(!C->getType()->isPointerTy() &&
9838 "Can only have one pointer, and it must be last");
9839 if (OpC->getType()->isPointerTy()) {
9840 // The offsets have been converted to bytes. We can add bytes using
9841 // an i8 GEP.
9842 C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()),
9843 OpC, C);
9844 } else {
9845 C = ConstantExpr::getAdd(C, OpC);
9846 }
9847 }
9848 return C;
9849 }
9850 case scMulExpr:
9851 case scSignExtend:
9852 case scZeroExtend:
9853 case scUDivExpr:
9854 case scSMaxExpr:
9855 case scUMaxExpr:
9856 case scSMinExpr:
9857 case scUMinExpr:
9858 case scSequentialUMinExpr:
9859 return nullptr;
9860 }
9861 llvm_unreachable("Unknown SCEV kind!");
9862 }
9863
9864 const SCEV *
getWithOperands(const SCEV * S,SmallVectorImpl<const SCEV * > & NewOps)9865 ScalarEvolution::getWithOperands(const SCEV *S,
9866 SmallVectorImpl<const SCEV *> &NewOps) {
9867 switch (S->getSCEVType()) {
9868 case scTruncate:
9869 case scZeroExtend:
9870 case scSignExtend:
9871 case scPtrToInt:
9872 return getCastExpr(S->getSCEVType(), NewOps[0], S->getType());
9873 case scAddRecExpr: {
9874 auto *AddRec = cast<SCEVAddRecExpr>(S);
9875 return getAddRecExpr(NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags());
9876 }
9877 case scAddExpr:
9878 return getAddExpr(NewOps, cast<SCEVAddExpr>(S)->getNoWrapFlags());
9879 case scMulExpr:
9880 return getMulExpr(NewOps, cast<SCEVMulExpr>(S)->getNoWrapFlags());
9881 case scUDivExpr:
9882 return getUDivExpr(NewOps[0], NewOps[1]);
9883 case scUMaxExpr:
9884 case scSMaxExpr:
9885 case scUMinExpr:
9886 case scSMinExpr:
9887 return getMinMaxExpr(S->getSCEVType(), NewOps);
9888 case scSequentialUMinExpr:
9889 return getSequentialMinMaxExpr(S->getSCEVType(), NewOps);
9890 case scConstant:
9891 case scVScale:
9892 case scUnknown:
9893 return S;
9894 case scCouldNotCompute:
9895 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
9896 }
9897 llvm_unreachable("Unknown SCEV kind!");
9898 }
9899
computeSCEVAtScope(const SCEV * V,const Loop * L)9900 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
9901 switch (V->getSCEVType()) {
9902 case scConstant:
9903 case scVScale:
9904 return V;
9905 case scAddRecExpr: {
9906 // If this is a loop recurrence for a loop that does not contain L, then we
9907 // are dealing with the final value computed by the loop.
9908 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(V);
9909 // First, attempt to evaluate each operand.
9910 // Avoid performing the look-up in the common case where the specified
9911 // expression has no loop-variant portions.
9912 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
9913 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
9914 if (OpAtScope == AddRec->getOperand(i))
9915 continue;
9916
9917 // Okay, at least one of these operands is loop variant but might be
9918 // foldable. Build a new instance of the folded commutative expression.
9919 SmallVector<const SCEV *, 8> NewOps;
9920 NewOps.reserve(AddRec->getNumOperands());
9921 append_range(NewOps, AddRec->operands().take_front(i));
9922 NewOps.push_back(OpAtScope);
9923 for (++i; i != e; ++i)
9924 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
9925
9926 const SCEV *FoldedRec = getAddRecExpr(
9927 NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags(SCEV::FlagNW));
9928 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
9929 // The addrec may be folded to a nonrecurrence, for example, if the
9930 // induction variable is multiplied by zero after constant folding. Go
9931 // ahead and return the folded value.
9932 if (!AddRec)
9933 return FoldedRec;
9934 break;
9935 }
9936
9937 // If the scope is outside the addrec's loop, evaluate it by using the
9938 // loop exit value of the addrec.
9939 if (!AddRec->getLoop()->contains(L)) {
9940 // To evaluate this recurrence, we need to know how many times the AddRec
9941 // loop iterates. Compute this now.
9942 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
9943 if (BackedgeTakenCount == getCouldNotCompute())
9944 return AddRec;
9945
9946 // Then, evaluate the AddRec.
9947 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
9948 }
9949
9950 return AddRec;
9951 }
9952 case scTruncate:
9953 case scZeroExtend:
9954 case scSignExtend:
9955 case scPtrToInt:
9956 case scAddExpr:
9957 case scMulExpr:
9958 case scUDivExpr:
9959 case scUMaxExpr:
9960 case scSMaxExpr:
9961 case scUMinExpr:
9962 case scSMinExpr:
9963 case scSequentialUMinExpr: {
9964 ArrayRef<const SCEV *> Ops = V->operands();
9965 // Avoid performing the look-up in the common case where the specified
9966 // expression has no loop-variant portions.
9967 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
9968 const SCEV *OpAtScope = getSCEVAtScope(Ops[i], L);
9969 if (OpAtScope != Ops[i]) {
9970 // Okay, at least one of these operands is loop variant but might be
9971 // foldable. Build a new instance of the folded commutative expression.
9972 SmallVector<const SCEV *, 8> NewOps;
9973 NewOps.reserve(Ops.size());
9974 append_range(NewOps, Ops.take_front(i));
9975 NewOps.push_back(OpAtScope);
9976
9977 for (++i; i != e; ++i) {
9978 OpAtScope = getSCEVAtScope(Ops[i], L);
9979 NewOps.push_back(OpAtScope);
9980 }
9981
9982 return getWithOperands(V, NewOps);
9983 }
9984 }
9985 // If we got here, all operands are loop invariant.
9986 return V;
9987 }
9988 case scUnknown: {
9989 // If this instruction is evolved from a constant-evolving PHI, compute the
9990 // exit value from the loop without using SCEVs.
9991 const SCEVUnknown *SU = cast<SCEVUnknown>(V);
9992 Instruction *I = dyn_cast<Instruction>(SU->getValue());
9993 if (!I)
9994 return V; // This is some other type of SCEVUnknown, just return it.
9995
9996 if (PHINode *PN = dyn_cast<PHINode>(I)) {
9997 const Loop *CurrLoop = this->LI[I->getParent()];
9998 // Looking for loop exit value.
9999 if (CurrLoop && CurrLoop->getParentLoop() == L &&
10000 PN->getParent() == CurrLoop->getHeader()) {
10001 // Okay, there is no closed form solution for the PHI node. Check
10002 // to see if the loop that contains it has a known backedge-taken
10003 // count. If so, we may be able to force computation of the exit
10004 // value.
10005 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
10006 // This trivial case can show up in some degenerate cases where
10007 // the incoming IR has not yet been fully simplified.
10008 if (BackedgeTakenCount->isZero()) {
10009 Value *InitValue = nullptr;
10010 bool MultipleInitValues = false;
10011 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
10012 if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
10013 if (!InitValue)
10014 InitValue = PN->getIncomingValue(i);
10015 else if (InitValue != PN->getIncomingValue(i)) {
10016 MultipleInitValues = true;
10017 break;
10018 }
10019 }
10020 }
10021 if (!MultipleInitValues && InitValue)
10022 return getSCEV(InitValue);
10023 }
10024 // Do we have a loop invariant value flowing around the backedge
10025 // for a loop which must execute the backedge?
10026 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
10027 isKnownNonZero(BackedgeTakenCount) &&
10028 PN->getNumIncomingValues() == 2) {
10029
10030 unsigned InLoopPred =
10031 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
10032 Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
10033 if (CurrLoop->isLoopInvariant(BackedgeVal))
10034 return getSCEV(BackedgeVal);
10035 }
10036 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
10037 // Okay, we know how many times the containing loop executes. If
10038 // this is a constant evolving PHI node, get the final value at
10039 // the specified iteration number.
10040 Constant *RV =
10041 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
10042 if (RV)
10043 return getSCEV(RV);
10044 }
10045 }
10046 }
10047
10048 // Okay, this is an expression that we cannot symbolically evaluate
10049 // into a SCEV. Check to see if it's possible to symbolically evaluate
10050 // the arguments into constants, and if so, try to constant propagate the
10051 // result. This is particularly useful for computing loop exit values.
10052 if (!CanConstantFold(I))
10053 return V; // This is some other type of SCEVUnknown, just return it.
10054
10055 SmallVector<Constant *, 4> Operands;
10056 Operands.reserve(I->getNumOperands());
10057 bool MadeImprovement = false;
10058 for (Value *Op : I->operands()) {
10059 if (Constant *C = dyn_cast<Constant>(Op)) {
10060 Operands.push_back(C);
10061 continue;
10062 }
10063
10064 // If any of the operands is non-constant and if they are
10065 // non-integer and non-pointer, don't even try to analyze them
10066 // with scev techniques.
10067 if (!isSCEVable(Op->getType()))
10068 return V;
10069
10070 const SCEV *OrigV = getSCEV(Op);
10071 const SCEV *OpV = getSCEVAtScope(OrigV, L);
10072 MadeImprovement |= OrigV != OpV;
10073
10074 Constant *C = BuildConstantFromSCEV(OpV);
10075 if (!C)
10076 return V;
10077 assert(C->getType() == Op->getType() && "Type mismatch");
10078 Operands.push_back(C);
10079 }
10080
10081 // Check to see if getSCEVAtScope actually made an improvement.
10082 if (!MadeImprovement)
10083 return V; // This is some other type of SCEVUnknown, just return it.
10084
10085 Constant *C = nullptr;
10086 const DataLayout &DL = getDataLayout();
10087 C = ConstantFoldInstOperands(I, Operands, DL, &TLI,
10088 /*AllowNonDeterministic=*/false);
10089 if (!C)
10090 return V;
10091 return getSCEV(C);
10092 }
10093 case scCouldNotCompute:
10094 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10095 }
10096 llvm_unreachable("Unknown SCEV type!");
10097 }
10098
getSCEVAtScope(Value * V,const Loop * L)10099 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
10100 return getSCEVAtScope(getSCEV(V), L);
10101 }
10102
stripInjectiveFunctions(const SCEV * S) const10103 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
10104 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
10105 return stripInjectiveFunctions(ZExt->getOperand());
10106 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
10107 return stripInjectiveFunctions(SExt->getOperand());
10108 return S;
10109 }
10110
10111 /// Finds the minimum unsigned root of the following equation:
10112 ///
10113 /// A * X = B (mod N)
10114 ///
10115 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
10116 /// A and B isn't important.
10117 ///
10118 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
SolveLinEquationWithOverflow(const APInt & A,const SCEV * B,ScalarEvolution & SE)10119 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
10120 ScalarEvolution &SE) {
10121 uint32_t BW = A.getBitWidth();
10122 assert(BW == SE.getTypeSizeInBits(B->getType()));
10123 assert(A != 0 && "A must be non-zero.");
10124
10125 // 1. D = gcd(A, N)
10126 //
10127 // The gcd of A and N may have only one prime factor: 2. The number of
10128 // trailing zeros in A is its multiplicity
10129 uint32_t Mult2 = A.countr_zero();
10130 // D = 2^Mult2
10131
10132 // 2. Check if B is divisible by D.
10133 //
10134 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
10135 // is not less than multiplicity of this prime factor for D.
10136 if (SE.getMinTrailingZeros(B) < Mult2)
10137 return SE.getCouldNotCompute();
10138
10139 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
10140 // modulo (N / D).
10141 //
10142 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
10143 // (N / D) in general. The inverse itself always fits into BW bits, though,
10144 // so we immediately truncate it.
10145 APInt AD = A.lshr(Mult2).trunc(BW - Mult2); // AD = A / D
10146 APInt I = AD.multiplicativeInverse().zext(BW);
10147
10148 // 4. Compute the minimum unsigned root of the equation:
10149 // I * (B / D) mod (N / D)
10150 // To simplify the computation, we factor out the divide by D:
10151 // (I * B mod N) / D
10152 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
10153 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
10154 }
10155
10156 /// For a given quadratic addrec, generate coefficients of the corresponding
10157 /// quadratic equation, multiplied by a common value to ensure that they are
10158 /// integers.
10159 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
10160 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
10161 /// were multiplied by, and BitWidth is the bit width of the original addrec
10162 /// coefficients.
10163 /// This function returns std::nullopt if the addrec coefficients are not
10164 /// compile- time constants.
10165 static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
GetQuadraticEquation(const SCEVAddRecExpr * AddRec)10166 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
10167 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
10168 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
10169 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
10170 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
10171 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
10172 << *AddRec << '\n');
10173
10174 // We currently can only solve this if the coefficients are constants.
10175 if (!LC || !MC || !NC) {
10176 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
10177 return std::nullopt;
10178 }
10179
10180 APInt L = LC->getAPInt();
10181 APInt M = MC->getAPInt();
10182 APInt N = NC->getAPInt();
10183 assert(!N.isZero() && "This is not a quadratic addrec");
10184
10185 unsigned BitWidth = LC->getAPInt().getBitWidth();
10186 unsigned NewWidth = BitWidth + 1;
10187 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
10188 << BitWidth << '\n');
10189 // The sign-extension (as opposed to a zero-extension) here matches the
10190 // extension used in SolveQuadraticEquationWrap (with the same motivation).
10191 N = N.sext(NewWidth);
10192 M = M.sext(NewWidth);
10193 L = L.sext(NewWidth);
10194
10195 // The increments are M, M+N, M+2N, ..., so the accumulated values are
10196 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
10197 // L+M, L+2M+N, L+3M+3N, ...
10198 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
10199 //
10200 // The equation Acc = 0 is then
10201 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
10202 // In a quadratic form it becomes:
10203 // N n^2 + (2M-N) n + 2L = 0.
10204
10205 APInt A = N;
10206 APInt B = 2 * M - A;
10207 APInt C = 2 * L;
10208 APInt T = APInt(NewWidth, 2);
10209 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
10210 << "x + " << C << ", coeff bw: " << NewWidth
10211 << ", multiplied by " << T << '\n');
10212 return std::make_tuple(A, B, C, T, BitWidth);
10213 }
10214
10215 /// Helper function to compare optional APInts:
10216 /// (a) if X and Y both exist, return min(X, Y),
10217 /// (b) if neither X nor Y exist, return std::nullopt,
10218 /// (c) if exactly one of X and Y exists, return that value.
MinOptional(std::optional<APInt> X,std::optional<APInt> Y)10219 static std::optional<APInt> MinOptional(std::optional<APInt> X,
10220 std::optional<APInt> Y) {
10221 if (X && Y) {
10222 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
10223 APInt XW = X->sext(W);
10224 APInt YW = Y->sext(W);
10225 return XW.slt(YW) ? *X : *Y;
10226 }
10227 if (!X && !Y)
10228 return std::nullopt;
10229 return X ? *X : *Y;
10230 }
10231
10232 /// Helper function to truncate an optional APInt to a given BitWidth.
10233 /// When solving addrec-related equations, it is preferable to return a value
10234 /// that has the same bit width as the original addrec's coefficients. If the
10235 /// solution fits in the original bit width, truncate it (except for i1).
10236 /// Returning a value of a different bit width may inhibit some optimizations.
10237 ///
10238 /// In general, a solution to a quadratic equation generated from an addrec
10239 /// may require BW+1 bits, where BW is the bit width of the addrec's
10240 /// coefficients. The reason is that the coefficients of the quadratic
10241 /// equation are BW+1 bits wide (to avoid truncation when converting from
10242 /// the addrec to the equation).
TruncIfPossible(std::optional<APInt> X,unsigned BitWidth)10243 static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
10244 unsigned BitWidth) {
10245 if (!X)
10246 return std::nullopt;
10247 unsigned W = X->getBitWidth();
10248 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
10249 return X->trunc(BitWidth);
10250 return X;
10251 }
10252
10253 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
10254 /// iterations. The values L, M, N are assumed to be signed, and they
10255 /// should all have the same bit widths.
10256 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
10257 /// where BW is the bit width of the addrec's coefficients.
10258 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
10259 /// returned as such, otherwise the bit width of the returned value may
10260 /// be greater than BW.
10261 ///
10262 /// This function returns std::nullopt if
10263 /// (a) the addrec coefficients are not constant, or
10264 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
10265 /// like x^2 = 5, no integer solutions exist, in other cases an integer
10266 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
10267 static std::optional<APInt>
SolveQuadraticAddRecExact(const SCEVAddRecExpr * AddRec,ScalarEvolution & SE)10268 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
10269 APInt A, B, C, M;
10270 unsigned BitWidth;
10271 auto T = GetQuadraticEquation(AddRec);
10272 if (!T)
10273 return std::nullopt;
10274
10275 std::tie(A, B, C, M, BitWidth) = *T;
10276 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
10277 std::optional<APInt> X =
10278 APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth + 1);
10279 if (!X)
10280 return std::nullopt;
10281
10282 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
10283 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
10284 if (!V->isZero())
10285 return std::nullopt;
10286
10287 return TruncIfPossible(X, BitWidth);
10288 }
10289
10290 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
10291 /// iterations. The values M, N are assumed to be signed, and they
10292 /// should all have the same bit widths.
10293 /// Find the least n such that c(n) does not belong to the given range,
10294 /// while c(n-1) does.
10295 ///
10296 /// This function returns std::nullopt if
10297 /// (a) the addrec coefficients are not constant, or
10298 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
10299 /// bounds of the range.
10300 static std::optional<APInt>
SolveQuadraticAddRecRange(const SCEVAddRecExpr * AddRec,const ConstantRange & Range,ScalarEvolution & SE)10301 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
10302 const ConstantRange &Range, ScalarEvolution &SE) {
10303 assert(AddRec->getOperand(0)->isZero() &&
10304 "Starting value of addrec should be 0");
10305 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
10306 << Range << ", addrec " << *AddRec << '\n');
10307 // This case is handled in getNumIterationsInRange. Here we can assume that
10308 // we start in the range.
10309 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
10310 "Addrec's initial value should be in range");
10311
10312 APInt A, B, C, M;
10313 unsigned BitWidth;
10314 auto T = GetQuadraticEquation(AddRec);
10315 if (!T)
10316 return std::nullopt;
10317
10318 // Be careful about the return value: there can be two reasons for not
10319 // returning an actual number. First, if no solutions to the equations
10320 // were found, and second, if the solutions don't leave the given range.
10321 // The first case means that the actual solution is "unknown", the second
10322 // means that it's known, but not valid. If the solution is unknown, we
10323 // cannot make any conclusions.
10324 // Return a pair: the optional solution and a flag indicating if the
10325 // solution was found.
10326 auto SolveForBoundary =
10327 [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
10328 // Solve for signed overflow and unsigned overflow, pick the lower
10329 // solution.
10330 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
10331 << Bound << " (before multiplying by " << M << ")\n");
10332 Bound *= M; // The quadratic equation multiplier.
10333
10334 std::optional<APInt> SO;
10335 if (BitWidth > 1) {
10336 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10337 "signed overflow\n");
10338 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
10339 }
10340 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10341 "unsigned overflow\n");
10342 std::optional<APInt> UO =
10343 APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth + 1);
10344
10345 auto LeavesRange = [&] (const APInt &X) {
10346 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
10347 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
10348 if (Range.contains(V0->getValue()))
10349 return false;
10350 // X should be at least 1, so X-1 is non-negative.
10351 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
10352 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
10353 if (Range.contains(V1->getValue()))
10354 return true;
10355 return false;
10356 };
10357
10358 // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
10359 // can be a solution, but the function failed to find it. We cannot treat it
10360 // as "no solution".
10361 if (!SO || !UO)
10362 return {std::nullopt, false};
10363
10364 // Check the smaller value first to see if it leaves the range.
10365 // At this point, both SO and UO must have values.
10366 std::optional<APInt> Min = MinOptional(SO, UO);
10367 if (LeavesRange(*Min))
10368 return { Min, true };
10369 std::optional<APInt> Max = Min == SO ? UO : SO;
10370 if (LeavesRange(*Max))
10371 return { Max, true };
10372
10373 // Solutions were found, but were eliminated, hence the "true".
10374 return {std::nullopt, true};
10375 };
10376
10377 std::tie(A, B, C, M, BitWidth) = *T;
10378 // Lower bound is inclusive, subtract 1 to represent the exiting value.
10379 APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
10380 APInt Upper = Range.getUpper().sext(A.getBitWidth());
10381 auto SL = SolveForBoundary(Lower);
10382 auto SU = SolveForBoundary(Upper);
10383 // If any of the solutions was unknown, no meaninigful conclusions can
10384 // be made.
10385 if (!SL.second || !SU.second)
10386 return std::nullopt;
10387
10388 // Claim: The correct solution is not some value between Min and Max.
10389 //
10390 // Justification: Assuming that Min and Max are different values, one of
10391 // them is when the first signed overflow happens, the other is when the
10392 // first unsigned overflow happens. Crossing the range boundary is only
10393 // possible via an overflow (treating 0 as a special case of it, modeling
10394 // an overflow as crossing k*2^W for some k).
10395 //
10396 // The interesting case here is when Min was eliminated as an invalid
10397 // solution, but Max was not. The argument is that if there was another
10398 // overflow between Min and Max, it would also have been eliminated if
10399 // it was considered.
10400 //
10401 // For a given boundary, it is possible to have two overflows of the same
10402 // type (signed/unsigned) without having the other type in between: this
10403 // can happen when the vertex of the parabola is between the iterations
10404 // corresponding to the overflows. This is only possible when the two
10405 // overflows cross k*2^W for the same k. In such case, if the second one
10406 // left the range (and was the first one to do so), the first overflow
10407 // would have to enter the range, which would mean that either we had left
10408 // the range before or that we started outside of it. Both of these cases
10409 // are contradictions.
10410 //
10411 // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
10412 // solution is not some value between the Max for this boundary and the
10413 // Min of the other boundary.
10414 //
10415 // Justification: Assume that we had such Max_A and Min_B corresponding
10416 // to range boundaries A and B and such that Max_A < Min_B. If there was
10417 // a solution between Max_A and Min_B, it would have to be caused by an
10418 // overflow corresponding to either A or B. It cannot correspond to B,
10419 // since Min_B is the first occurrence of such an overflow. If it
10420 // corresponded to A, it would have to be either a signed or an unsigned
10421 // overflow that is larger than both eliminated overflows for A. But
10422 // between the eliminated overflows and this overflow, the values would
10423 // cover the entire value space, thus crossing the other boundary, which
10424 // is a contradiction.
10425
10426 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
10427 }
10428
howFarToZero(const SCEV * V,const Loop * L,bool ControlsOnlyExit,bool AllowPredicates)10429 ScalarEvolution::ExitLimit ScalarEvolution::howFarToZero(const SCEV *V,
10430 const Loop *L,
10431 bool ControlsOnlyExit,
10432 bool AllowPredicates) {
10433
10434 // This is only used for loops with a "x != y" exit test. The exit condition
10435 // is now expressed as a single expression, V = x-y. So the exit test is
10436 // effectively V != 0. We know and take advantage of the fact that this
10437 // expression only being used in a comparison by zero context.
10438
10439 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10440 // If the value is a constant
10441 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10442 // If the value is already zero, the branch will execute zero times.
10443 if (C->getValue()->isZero()) return C;
10444 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10445 }
10446
10447 const SCEVAddRecExpr *AddRec =
10448 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
10449
10450 if (!AddRec && AllowPredicates)
10451 // Try to make this an AddRec using runtime tests, in the first X
10452 // iterations of this loop, where X is the SCEV expression found by the
10453 // algorithm below.
10454 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
10455
10456 if (!AddRec || AddRec->getLoop() != L)
10457 return getCouldNotCompute();
10458
10459 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
10460 // the quadratic equation to solve it.
10461 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
10462 // We can only use this value if the chrec ends up with an exact zero
10463 // value at this index. When solving for "X*X != 5", for example, we
10464 // should not accept a root of 2.
10465 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
10466 const auto *R = cast<SCEVConstant>(getConstant(*S));
10467 return ExitLimit(R, R, R, false, Predicates);
10468 }
10469 return getCouldNotCompute();
10470 }
10471
10472 // Otherwise we can only handle this if it is affine.
10473 if (!AddRec->isAffine())
10474 return getCouldNotCompute();
10475
10476 // If this is an affine expression, the execution count of this branch is
10477 // the minimum unsigned root of the following equation:
10478 //
10479 // Start + Step*N = 0 (mod 2^BW)
10480 //
10481 // equivalent to:
10482 //
10483 // Step*N = -Start (mod 2^BW)
10484 //
10485 // where BW is the common bit width of Start and Step.
10486
10487 // Get the initial value for the loop.
10488 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
10489 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
10490 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
10491
10492 if (!isLoopInvariant(Step, L))
10493 return getCouldNotCompute();
10494
10495 LoopGuards Guards = LoopGuards::collect(L, *this);
10496 // Specialize step for this loop so we get context sensitive facts below.
10497 const SCEV *StepWLG = applyLoopGuards(Step, Guards);
10498
10499 // For positive steps (counting up until unsigned overflow):
10500 // N = -Start/Step (as unsigned)
10501 // For negative steps (counting down to zero):
10502 // N = Start/-Step
10503 // First compute the unsigned distance from zero in the direction of Step.
10504 bool CountDown = isKnownNegative(StepWLG);
10505 if (!CountDown && !isKnownNonNegative(StepWLG))
10506 return getCouldNotCompute();
10507
10508 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
10509 // Handle unitary steps, which cannot wraparound.
10510 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10511 // N = Distance (as unsigned)
10512 if (StepC &&
10513 (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne())) {
10514 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, Guards));
10515 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
10516
10517 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10518 // we end up with a loop whose backedge-taken count is n - 1. Detect this
10519 // case, and see if we can improve the bound.
10520 //
10521 // Explicitly handling this here is necessary because getUnsignedRange
10522 // isn't context-sensitive; it doesn't know that we only care about the
10523 // range inside the loop.
10524 const SCEV *Zero = getZero(Distance->getType());
10525 const SCEV *One = getOne(Distance->getType());
10526 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
10527 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
10528 // If Distance + 1 doesn't overflow, we can compute the maximum distance
10529 // as "unsigned_max(Distance + 1) - 1".
10530 ConstantRange CR = getUnsignedRange(DistancePlusOne);
10531 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
10532 }
10533 return ExitLimit(Distance, getConstant(MaxBECount), Distance, false,
10534 Predicates);
10535 }
10536
10537 // If the condition controls loop exit (the loop exits only if the expression
10538 // is true) and the addition is no-wrap we can use unsigned divide to
10539 // compute the backedge count. In this case, the step may not divide the
10540 // distance, but we don't care because if the condition is "missed" the loop
10541 // will have undefined behavior due to wrapping.
10542 if (ControlsOnlyExit && AddRec->hasNoSelfWrap() &&
10543 loopHasNoAbnormalExits(AddRec->getLoop())) {
10544
10545 // If the stride is zero, the loop must be infinite. In C++, most loops
10546 // are finite by assumption, in which case the step being zero implies
10547 // UB must execute if the loop is entered.
10548 if (!loopIsFiniteByAssumption(L) && !isKnownNonZero(StepWLG))
10549 return getCouldNotCompute();
10550
10551 const SCEV *Exact =
10552 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10553 const SCEV *ConstantMax = getCouldNotCompute();
10554 if (Exact != getCouldNotCompute()) {
10555 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, Guards));
10556 ConstantMax =
10557 getConstant(APIntOps::umin(MaxInt, getUnsignedRangeMax(Exact)));
10558 }
10559 const SCEV *SymbolicMax =
10560 isa<SCEVCouldNotCompute>(Exact) ? ConstantMax : Exact;
10561 return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
10562 }
10563
10564 // Solve the general equation.
10565 if (!StepC || StepC->getValue()->isZero())
10566 return getCouldNotCompute();
10567 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
10568 getNegativeSCEV(Start), *this);
10569
10570 const SCEV *M = E;
10571 if (E != getCouldNotCompute()) {
10572 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, Guards));
10573 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
10574 }
10575 auto *S = isa<SCEVCouldNotCompute>(E) ? M : E;
10576 return ExitLimit(E, M, S, false, Predicates);
10577 }
10578
10579 ScalarEvolution::ExitLimit
howFarToNonZero(const SCEV * V,const Loop * L)10580 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10581 // Loops that look like: while (X == 0) are very strange indeed. We don't
10582 // handle them yet except for the trivial case. This could be expanded in the
10583 // future as needed.
10584
10585 // If the value is a constant, check to see if it is known to be non-zero
10586 // already. If so, the backedge will execute zero times.
10587 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10588 if (!C->getValue()->isZero())
10589 return getZero(C->getType());
10590 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10591 }
10592
10593 // We could implement others, but I really doubt anyone writes loops like
10594 // this, and if they did, they would already be constant folded.
10595 return getCouldNotCompute();
10596 }
10597
10598 std::pair<const BasicBlock *, const BasicBlock *>
getPredecessorWithUniqueSuccessorForBB(const BasicBlock * BB) const10599 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10600 const {
10601 // If the block has a unique predecessor, then there is no path from the
10602 // predecessor to the block that does not go through the direct edge
10603 // from the predecessor to the block.
10604 if (const BasicBlock *Pred = BB->getSinglePredecessor())
10605 return {Pred, BB};
10606
10607 // A loop's header is defined to be a block that dominates the loop.
10608 // If the header has a unique predecessor outside the loop, it must be
10609 // a block that has exactly one successor that can reach the loop.
10610 if (const Loop *L = LI.getLoopFor(BB))
10611 return {L->getLoopPredecessor(), L->getHeader()};
10612
10613 return {nullptr, nullptr};
10614 }
10615
10616 /// SCEV structural equivalence is usually sufficient for testing whether two
10617 /// expressions are equal, however for the purposes of looking for a condition
10618 /// guarding a loop, it can be useful to be a little more general, since a
10619 /// front-end may have replicated the controlling expression.
HasSameValue(const SCEV * A,const SCEV * B)10620 static bool HasSameValue(const SCEV *A, const SCEV *B) {
10621 // Quick check to see if they are the same SCEV.
10622 if (A == B) return true;
10623
10624 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10625 // Not all instructions that are "identical" compute the same value. For
10626 // instance, two distinct alloca instructions allocating the same type are
10627 // identical and do not read memory; but compute distinct values.
10628 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
10629 };
10630
10631 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10632 // two different instructions with the same value. Check for this case.
10633 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
10634 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
10635 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
10636 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
10637 if (ComputesEqualValues(AI, BI))
10638 return true;
10639
10640 // Otherwise assume they may have a different value.
10641 return false;
10642 }
10643
MatchBinarySub(const SCEV * S,const SCEV * & LHS,const SCEV * & RHS)10644 static bool MatchBinarySub(const SCEV *S, const SCEV *&LHS, const SCEV *&RHS) {
10645 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S);
10646 if (!Add || Add->getNumOperands() != 2)
10647 return false;
10648 if (auto *ME = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
10649 ME && ME->getNumOperands() == 2 && ME->getOperand(0)->isAllOnesValue()) {
10650 LHS = Add->getOperand(1);
10651 RHS = ME->getOperand(1);
10652 return true;
10653 }
10654 if (auto *ME = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
10655 ME && ME->getNumOperands() == 2 && ME->getOperand(0)->isAllOnesValue()) {
10656 LHS = Add->getOperand(0);
10657 RHS = ME->getOperand(1);
10658 return true;
10659 }
10660 return false;
10661 }
10662
SimplifyICmpOperands(ICmpInst::Predicate & Pred,const SCEV * & LHS,const SCEV * & RHS,unsigned Depth)10663 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
10664 const SCEV *&LHS, const SCEV *&RHS,
10665 unsigned Depth) {
10666 bool Changed = false;
10667 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
10668 // '0 != 0'.
10669 auto TrivialCase = [&](bool TriviallyTrue) {
10670 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
10671 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
10672 return true;
10673 };
10674 // If we hit the max recursion limit bail out.
10675 if (Depth >= 3)
10676 return false;
10677
10678 // Canonicalize a constant to the right side.
10679 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
10680 // Check for both operands constant.
10681 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
10682 if (!ICmpInst::compare(LHSC->getAPInt(), RHSC->getAPInt(), Pred))
10683 return TrivialCase(false);
10684 return TrivialCase(true);
10685 }
10686 // Otherwise swap the operands to put the constant on the right.
10687 std::swap(LHS, RHS);
10688 Pred = ICmpInst::getSwappedPredicate(Pred);
10689 Changed = true;
10690 }
10691
10692 // If we're comparing an addrec with a value which is loop-invariant in the
10693 // addrec's loop, put the addrec on the left. Also make a dominance check,
10694 // as both operands could be addrecs loop-invariant in each other's loop.
10695 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
10696 const Loop *L = AR->getLoop();
10697 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
10698 std::swap(LHS, RHS);
10699 Pred = ICmpInst::getSwappedPredicate(Pred);
10700 Changed = true;
10701 }
10702 }
10703
10704 // If there's a constant operand, canonicalize comparisons with boundary
10705 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
10706 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
10707 const APInt &RA = RC->getAPInt();
10708
10709 bool SimplifiedByConstantRange = false;
10710
10711 if (!ICmpInst::isEquality(Pred)) {
10712 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
10713 if (ExactCR.isFullSet())
10714 return TrivialCase(true);
10715 if (ExactCR.isEmptySet())
10716 return TrivialCase(false);
10717
10718 APInt NewRHS;
10719 CmpInst::Predicate NewPred;
10720 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
10721 ICmpInst::isEquality(NewPred)) {
10722 // We were able to convert an inequality to an equality.
10723 Pred = NewPred;
10724 RHS = getConstant(NewRHS);
10725 Changed = SimplifiedByConstantRange = true;
10726 }
10727 }
10728
10729 if (!SimplifiedByConstantRange) {
10730 switch (Pred) {
10731 default:
10732 break;
10733 case ICmpInst::ICMP_EQ:
10734 case ICmpInst::ICMP_NE:
10735 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
10736 if (RA.isZero() && MatchBinarySub(LHS, LHS, RHS))
10737 Changed = true;
10738 break;
10739
10740 // The "Should have been caught earlier!" messages refer to the fact
10741 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
10742 // should have fired on the corresponding cases, and canonicalized the
10743 // check to trivial case.
10744
10745 case ICmpInst::ICMP_UGE:
10746 assert(!RA.isMinValue() && "Should have been caught earlier!");
10747 Pred = ICmpInst::ICMP_UGT;
10748 RHS = getConstant(RA - 1);
10749 Changed = true;
10750 break;
10751 case ICmpInst::ICMP_ULE:
10752 assert(!RA.isMaxValue() && "Should have been caught earlier!");
10753 Pred = ICmpInst::ICMP_ULT;
10754 RHS = getConstant(RA + 1);
10755 Changed = true;
10756 break;
10757 case ICmpInst::ICMP_SGE:
10758 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
10759 Pred = ICmpInst::ICMP_SGT;
10760 RHS = getConstant(RA - 1);
10761 Changed = true;
10762 break;
10763 case ICmpInst::ICMP_SLE:
10764 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
10765 Pred = ICmpInst::ICMP_SLT;
10766 RHS = getConstant(RA + 1);
10767 Changed = true;
10768 break;
10769 }
10770 }
10771 }
10772
10773 // Check for obvious equality.
10774 if (HasSameValue(LHS, RHS)) {
10775 if (ICmpInst::isTrueWhenEqual(Pred))
10776 return TrivialCase(true);
10777 if (ICmpInst::isFalseWhenEqual(Pred))
10778 return TrivialCase(false);
10779 }
10780
10781 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
10782 // adding or subtracting 1 from one of the operands.
10783 switch (Pred) {
10784 case ICmpInst::ICMP_SLE:
10785 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
10786 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
10787 SCEV::FlagNSW);
10788 Pred = ICmpInst::ICMP_SLT;
10789 Changed = true;
10790 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
10791 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
10792 SCEV::FlagNSW);
10793 Pred = ICmpInst::ICMP_SLT;
10794 Changed = true;
10795 }
10796 break;
10797 case ICmpInst::ICMP_SGE:
10798 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
10799 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
10800 SCEV::FlagNSW);
10801 Pred = ICmpInst::ICMP_SGT;
10802 Changed = true;
10803 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
10804 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
10805 SCEV::FlagNSW);
10806 Pred = ICmpInst::ICMP_SGT;
10807 Changed = true;
10808 }
10809 break;
10810 case ICmpInst::ICMP_ULE:
10811 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
10812 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
10813 SCEV::FlagNUW);
10814 Pred = ICmpInst::ICMP_ULT;
10815 Changed = true;
10816 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
10817 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
10818 Pred = ICmpInst::ICMP_ULT;
10819 Changed = true;
10820 }
10821 break;
10822 case ICmpInst::ICMP_UGE:
10823 if (!getUnsignedRangeMin(RHS).isMinValue()) {
10824 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
10825 Pred = ICmpInst::ICMP_UGT;
10826 Changed = true;
10827 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
10828 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
10829 SCEV::FlagNUW);
10830 Pred = ICmpInst::ICMP_UGT;
10831 Changed = true;
10832 }
10833 break;
10834 default:
10835 break;
10836 }
10837
10838 // TODO: More simplifications are possible here.
10839
10840 // Recursively simplify until we either hit a recursion limit or nothing
10841 // changes.
10842 if (Changed)
10843 return SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1);
10844
10845 return Changed;
10846 }
10847
isKnownNegative(const SCEV * S)10848 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
10849 return getSignedRangeMax(S).isNegative();
10850 }
10851
isKnownPositive(const SCEV * S)10852 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
10853 return getSignedRangeMin(S).isStrictlyPositive();
10854 }
10855
isKnownNonNegative(const SCEV * S)10856 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
10857 return !getSignedRangeMin(S).isNegative();
10858 }
10859
isKnownNonPositive(const SCEV * S)10860 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
10861 return !getSignedRangeMax(S).isStrictlyPositive();
10862 }
10863
isKnownNonZero(const SCEV * S)10864 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
10865 // Query push down for cases where the unsigned range is
10866 // less than sufficient.
10867 if (const auto *SExt = dyn_cast<SCEVSignExtendExpr>(S))
10868 return isKnownNonZero(SExt->getOperand(0));
10869 return getUnsignedRangeMin(S) != 0;
10870 }
10871
10872 std::pair<const SCEV *, const SCEV *>
SplitIntoInitAndPostInc(const Loop * L,const SCEV * S)10873 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
10874 // Compute SCEV on entry of loop L.
10875 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
10876 if (Start == getCouldNotCompute())
10877 return { Start, Start };
10878 // Compute post increment SCEV for loop L.
10879 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
10880 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
10881 return { Start, PostInc };
10882 }
10883
isKnownViaInduction(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)10884 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
10885 const SCEV *LHS, const SCEV *RHS) {
10886 // First collect all loops.
10887 SmallPtrSet<const Loop *, 8> LoopsUsed;
10888 getUsedLoops(LHS, LoopsUsed);
10889 getUsedLoops(RHS, LoopsUsed);
10890
10891 if (LoopsUsed.empty())
10892 return false;
10893
10894 // Domination relationship must be a linear order on collected loops.
10895 #ifndef NDEBUG
10896 for (const auto *L1 : LoopsUsed)
10897 for (const auto *L2 : LoopsUsed)
10898 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
10899 DT.dominates(L2->getHeader(), L1->getHeader())) &&
10900 "Domination relationship is not a linear order");
10901 #endif
10902
10903 const Loop *MDL =
10904 *llvm::max_element(LoopsUsed, [&](const Loop *L1, const Loop *L2) {
10905 return DT.properlyDominates(L1->getHeader(), L2->getHeader());
10906 });
10907
10908 // Get init and post increment value for LHS.
10909 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
10910 // if LHS contains unknown non-invariant SCEV then bail out.
10911 if (SplitLHS.first == getCouldNotCompute())
10912 return false;
10913 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
10914 // Get init and post increment value for RHS.
10915 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
10916 // if RHS contains unknown non-invariant SCEV then bail out.
10917 if (SplitRHS.first == getCouldNotCompute())
10918 return false;
10919 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
10920 // It is possible that init SCEV contains an invariant load but it does
10921 // not dominate MDL and is not available at MDL loop entry, so we should
10922 // check it here.
10923 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
10924 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
10925 return false;
10926
10927 // It seems backedge guard check is faster than entry one so in some cases
10928 // it can speed up whole estimation by short circuit
10929 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
10930 SplitRHS.second) &&
10931 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
10932 }
10933
isKnownPredicate(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)10934 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
10935 const SCEV *LHS, const SCEV *RHS) {
10936 // Canonicalize the inputs first.
10937 (void)SimplifyICmpOperands(Pred, LHS, RHS);
10938
10939 if (isKnownViaInduction(Pred, LHS, RHS))
10940 return true;
10941
10942 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
10943 return true;
10944
10945 // Otherwise see what can be done with some simple reasoning.
10946 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
10947 }
10948
evaluatePredicate(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)10949 std::optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred,
10950 const SCEV *LHS,
10951 const SCEV *RHS) {
10952 if (isKnownPredicate(Pred, LHS, RHS))
10953 return true;
10954 if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS))
10955 return false;
10956 return std::nullopt;
10957 }
10958
isKnownPredicateAt(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const Instruction * CtxI)10959 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
10960 const SCEV *LHS, const SCEV *RHS,
10961 const Instruction *CtxI) {
10962 // TODO: Analyze guards and assumes from Context's block.
10963 return isKnownPredicate(Pred, LHS, RHS) ||
10964 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
10965 }
10966
10967 std::optional<bool>
evaluatePredicateAt(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const Instruction * CtxI)10968 ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, const SCEV *LHS,
10969 const SCEV *RHS, const Instruction *CtxI) {
10970 std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
10971 if (KnownWithoutContext)
10972 return KnownWithoutContext;
10973
10974 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
10975 return true;
10976 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(),
10977 ICmpInst::getInversePredicate(Pred),
10978 LHS, RHS))
10979 return false;
10980 return std::nullopt;
10981 }
10982
isKnownOnEveryIteration(ICmpInst::Predicate Pred,const SCEVAddRecExpr * LHS,const SCEV * RHS)10983 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
10984 const SCEVAddRecExpr *LHS,
10985 const SCEV *RHS) {
10986 const Loop *L = LHS->getLoop();
10987 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
10988 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
10989 }
10990
10991 std::optional<ScalarEvolution::MonotonicPredicateType>
getMonotonicPredicateType(const SCEVAddRecExpr * LHS,ICmpInst::Predicate Pred)10992 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
10993 ICmpInst::Predicate Pred) {
10994 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
10995
10996 #ifndef NDEBUG
10997 // Verify an invariant: inverting the predicate should turn a monotonically
10998 // increasing change to a monotonically decreasing one, and vice versa.
10999 if (Result) {
11000 auto ResultSwapped =
11001 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
11002
11003 assert(*ResultSwapped != *Result &&
11004 "monotonicity should flip as we flip the predicate");
11005 }
11006 #endif
11007
11008 return Result;
11009 }
11010
11011 std::optional<ScalarEvolution::MonotonicPredicateType>
getMonotonicPredicateTypeImpl(const SCEVAddRecExpr * LHS,ICmpInst::Predicate Pred)11012 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
11013 ICmpInst::Predicate Pred) {
11014 // A zero step value for LHS means the induction variable is essentially a
11015 // loop invariant value. We don't really depend on the predicate actually
11016 // flipping from false to true (for increasing predicates, and the other way
11017 // around for decreasing predicates), all we care about is that *if* the
11018 // predicate changes then it only changes from false to true.
11019 //
11020 // A zero step value in itself is not very useful, but there may be places
11021 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
11022 // as general as possible.
11023
11024 // Only handle LE/LT/GE/GT predicates.
11025 if (!ICmpInst::isRelational(Pred))
11026 return std::nullopt;
11027
11028 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
11029 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
11030 "Should be greater or less!");
11031
11032 // Check that AR does not wrap.
11033 if (ICmpInst::isUnsigned(Pred)) {
11034 if (!LHS->hasNoUnsignedWrap())
11035 return std::nullopt;
11036 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
11037 }
11038 assert(ICmpInst::isSigned(Pred) &&
11039 "Relational predicate is either signed or unsigned!");
11040 if (!LHS->hasNoSignedWrap())
11041 return std::nullopt;
11042
11043 const SCEV *Step = LHS->getStepRecurrence(*this);
11044
11045 if (isKnownNonNegative(Step))
11046 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
11047
11048 if (isKnownNonPositive(Step))
11049 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
11050
11051 return std::nullopt;
11052 }
11053
11054 std::optional<ScalarEvolution::LoopInvariantPredicate>
getLoopInvariantPredicate(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const Loop * L,const Instruction * CtxI)11055 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
11056 const SCEV *LHS, const SCEV *RHS,
11057 const Loop *L,
11058 const Instruction *CtxI) {
11059 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11060 if (!isLoopInvariant(RHS, L)) {
11061 if (!isLoopInvariant(LHS, L))
11062 return std::nullopt;
11063
11064 std::swap(LHS, RHS);
11065 Pred = ICmpInst::getSwappedPredicate(Pred);
11066 }
11067
11068 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11069 if (!ArLHS || ArLHS->getLoop() != L)
11070 return std::nullopt;
11071
11072 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
11073 if (!MonotonicType)
11074 return std::nullopt;
11075 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
11076 // true as the loop iterates, and the backedge is control dependent on
11077 // "ArLHS `Pred` RHS" == true then we can reason as follows:
11078 //
11079 // * if the predicate was false in the first iteration then the predicate
11080 // is never evaluated again, since the loop exits without taking the
11081 // backedge.
11082 // * if the predicate was true in the first iteration then it will
11083 // continue to be true for all future iterations since it is
11084 // monotonically increasing.
11085 //
11086 // For both the above possibilities, we can replace the loop varying
11087 // predicate with its value on the first iteration of the loop (which is
11088 // loop invariant).
11089 //
11090 // A similar reasoning applies for a monotonically decreasing predicate, by
11091 // replacing true with false and false with true in the above two bullets.
11092 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
11093 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
11094
11095 if (isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
11096 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(),
11097 RHS);
11098
11099 if (!CtxI)
11100 return std::nullopt;
11101 // Try to prove via context.
11102 // TODO: Support other cases.
11103 switch (Pred) {
11104 default:
11105 break;
11106 case ICmpInst::ICMP_ULE:
11107 case ICmpInst::ICMP_ULT: {
11108 assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!");
11109 // Given preconditions
11110 // (1) ArLHS does not cross the border of positive and negative parts of
11111 // range because of:
11112 // - Positive step; (TODO: lift this limitation)
11113 // - nuw - does not cross zero boundary;
11114 // - nsw - does not cross SINT_MAX boundary;
11115 // (2) ArLHS <s RHS
11116 // (3) RHS >=s 0
11117 // we can replace the loop variant ArLHS <u RHS condition with loop
11118 // invariant Start(ArLHS) <u RHS.
11119 //
11120 // Because of (1) there are two options:
11121 // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
11122 // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
11123 // It means that ArLHS <s RHS <=> ArLHS <u RHS.
11124 // Because of (2) ArLHS <u RHS is trivially true.
11125 // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
11126 // We can strengthen this to Start(ArLHS) <u RHS.
11127 auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
11128 if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
11129 isKnownPositive(ArLHS->getStepRecurrence(*this)) &&
11130 isKnownNonNegative(RHS) &&
11131 isKnownPredicateAt(SignFlippedPred, ArLHS, RHS, CtxI))
11132 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(),
11133 RHS);
11134 }
11135 }
11136
11137 return std::nullopt;
11138 }
11139
11140 std::optional<ScalarEvolution::LoopInvariantPredicate>
getLoopInvariantExitCondDuringFirstIterations(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const Loop * L,const Instruction * CtxI,const SCEV * MaxIter)11141 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
11142 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11143 const Instruction *CtxI, const SCEV *MaxIter) {
11144 if (auto LIP = getLoopInvariantExitCondDuringFirstIterationsImpl(
11145 Pred, LHS, RHS, L, CtxI, MaxIter))
11146 return LIP;
11147 if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
11148 // Number of iterations expressed as UMIN isn't always great for expressing
11149 // the value on the last iteration. If the straightforward approach didn't
11150 // work, try the following trick: if the a predicate is invariant for X, it
11151 // is also invariant for umin(X, ...). So try to find something that works
11152 // among subexpressions of MaxIter expressed as umin.
11153 for (auto *Op : UMin->operands())
11154 if (auto LIP = getLoopInvariantExitCondDuringFirstIterationsImpl(
11155 Pred, LHS, RHS, L, CtxI, Op))
11156 return LIP;
11157 return std::nullopt;
11158 }
11159
11160 std::optional<ScalarEvolution::LoopInvariantPredicate>
getLoopInvariantExitCondDuringFirstIterationsImpl(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const Loop * L,const Instruction * CtxI,const SCEV * MaxIter)11161 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterationsImpl(
11162 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11163 const Instruction *CtxI, const SCEV *MaxIter) {
11164 // Try to prove the following set of facts:
11165 // - The predicate is monotonic in the iteration space.
11166 // - If the check does not fail on the 1st iteration:
11167 // - No overflow will happen during first MaxIter iterations;
11168 // - It will not fail on the MaxIter'th iteration.
11169 // If the check does fail on the 1st iteration, we leave the loop and no
11170 // other checks matter.
11171
11172 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11173 if (!isLoopInvariant(RHS, L)) {
11174 if (!isLoopInvariant(LHS, L))
11175 return std::nullopt;
11176
11177 std::swap(LHS, RHS);
11178 Pred = ICmpInst::getSwappedPredicate(Pred);
11179 }
11180
11181 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
11182 if (!AR || AR->getLoop() != L)
11183 return std::nullopt;
11184
11185 // The predicate must be relational (i.e. <, <=, >=, >).
11186 if (!ICmpInst::isRelational(Pred))
11187 return std::nullopt;
11188
11189 // TODO: Support steps other than +/- 1.
11190 const SCEV *Step = AR->getStepRecurrence(*this);
11191 auto *One = getOne(Step->getType());
11192 auto *MinusOne = getNegativeSCEV(One);
11193 if (Step != One && Step != MinusOne)
11194 return std::nullopt;
11195
11196 // Type mismatch here means that MaxIter is potentially larger than max
11197 // unsigned value in start type, which mean we cannot prove no wrap for the
11198 // indvar.
11199 if (AR->getType() != MaxIter->getType())
11200 return std::nullopt;
11201
11202 // Value of IV on suggested last iteration.
11203 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
11204 // Does it still meet the requirement?
11205 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
11206 return std::nullopt;
11207 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
11208 // not exceed max unsigned value of this type), this effectively proves
11209 // that there is no wrap during the iteration. To prove that there is no
11210 // signed/unsigned wrap, we need to check that
11211 // Start <= Last for step = 1 or Start >= Last for step = -1.
11212 ICmpInst::Predicate NoOverflowPred =
11213 CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
11214 if (Step == MinusOne)
11215 NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
11216 const SCEV *Start = AR->getStart();
11217 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
11218 return std::nullopt;
11219
11220 // Everything is fine.
11221 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
11222 }
11223
isKnownPredicateViaConstantRanges(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)11224 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
11225 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
11226 if (HasSameValue(LHS, RHS))
11227 return ICmpInst::isTrueWhenEqual(Pred);
11228
11229 // This code is split out from isKnownPredicate because it is called from
11230 // within isLoopEntryGuardedByCond.
11231
11232 auto CheckRanges = [&](const ConstantRange &RangeLHS,
11233 const ConstantRange &RangeRHS) {
11234 return RangeLHS.icmp(Pred, RangeRHS);
11235 };
11236
11237 // The check at the top of the function catches the case where the values are
11238 // known to be equal.
11239 if (Pred == CmpInst::ICMP_EQ)
11240 return false;
11241
11242 if (Pred == CmpInst::ICMP_NE) {
11243 auto SL = getSignedRange(LHS);
11244 auto SR = getSignedRange(RHS);
11245 if (CheckRanges(SL, SR))
11246 return true;
11247 auto UL = getUnsignedRange(LHS);
11248 auto UR = getUnsignedRange(RHS);
11249 if (CheckRanges(UL, UR))
11250 return true;
11251 auto *Diff = getMinusSCEV(LHS, RHS);
11252 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
11253 }
11254
11255 if (CmpInst::isSigned(Pred)) {
11256 auto SL = getSignedRange(LHS);
11257 auto SR = getSignedRange(RHS);
11258 return CheckRanges(SL, SR);
11259 }
11260
11261 auto UL = getUnsignedRange(LHS);
11262 auto UR = getUnsignedRange(RHS);
11263 return CheckRanges(UL, UR);
11264 }
11265
isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)11266 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
11267 const SCEV *LHS,
11268 const SCEV *RHS) {
11269 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
11270 // C1 and C2 are constant integers. If either X or Y are not add expressions,
11271 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
11272 // OutC1 and OutC2.
11273 auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y,
11274 APInt &OutC1, APInt &OutC2,
11275 SCEV::NoWrapFlags ExpectedFlags) {
11276 const SCEV *XNonConstOp, *XConstOp;
11277 const SCEV *YNonConstOp, *YConstOp;
11278 SCEV::NoWrapFlags XFlagsPresent;
11279 SCEV::NoWrapFlags YFlagsPresent;
11280
11281 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
11282 XConstOp = getZero(X->getType());
11283 XNonConstOp = X;
11284 XFlagsPresent = ExpectedFlags;
11285 }
11286 if (!isa<SCEVConstant>(XConstOp) ||
11287 (XFlagsPresent & ExpectedFlags) != ExpectedFlags)
11288 return false;
11289
11290 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
11291 YConstOp = getZero(Y->getType());
11292 YNonConstOp = Y;
11293 YFlagsPresent = ExpectedFlags;
11294 }
11295
11296 if (!isa<SCEVConstant>(YConstOp) ||
11297 (YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11298 return false;
11299
11300 if (YNonConstOp != XNonConstOp)
11301 return false;
11302
11303 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
11304 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
11305
11306 return true;
11307 };
11308
11309 APInt C1;
11310 APInt C2;
11311
11312 switch (Pred) {
11313 default:
11314 break;
11315
11316 case ICmpInst::ICMP_SGE:
11317 std::swap(LHS, RHS);
11318 [[fallthrough]];
11319 case ICmpInst::ICMP_SLE:
11320 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
11321 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
11322 return true;
11323
11324 break;
11325
11326 case ICmpInst::ICMP_SGT:
11327 std::swap(LHS, RHS);
11328 [[fallthrough]];
11329 case ICmpInst::ICMP_SLT:
11330 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
11331 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
11332 return true;
11333
11334 break;
11335
11336 case ICmpInst::ICMP_UGE:
11337 std::swap(LHS, RHS);
11338 [[fallthrough]];
11339 case ICmpInst::ICMP_ULE:
11340 // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2.
11341 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ule(C2))
11342 return true;
11343
11344 break;
11345
11346 case ICmpInst::ICMP_UGT:
11347 std::swap(LHS, RHS);
11348 [[fallthrough]];
11349 case ICmpInst::ICMP_ULT:
11350 // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2.
11351 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ult(C2))
11352 return true;
11353 break;
11354 }
11355
11356 return false;
11357 }
11358
isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)11359 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
11360 const SCEV *LHS,
11361 const SCEV *RHS) {
11362 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
11363 return false;
11364
11365 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
11366 // the stack can result in exponential time complexity.
11367 SaveAndRestore Restore(ProvingSplitPredicate, true);
11368
11369 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
11370 //
11371 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
11372 // isKnownPredicate. isKnownPredicate is more powerful, but also more
11373 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
11374 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
11375 // use isKnownPredicate later if needed.
11376 return isKnownNonNegative(RHS) &&
11377 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
11378 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
11379 }
11380
isImpliedViaGuard(const BasicBlock * BB,ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)11381 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
11382 ICmpInst::Predicate Pred,
11383 const SCEV *LHS, const SCEV *RHS) {
11384 // No need to even try if we know the module has no guards.
11385 if (!HasGuards)
11386 return false;
11387
11388 return any_of(*BB, [&](const Instruction &I) {
11389 using namespace llvm::PatternMatch;
11390
11391 Value *Condition;
11392 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
11393 m_Value(Condition))) &&
11394 isImpliedCond(Pred, LHS, RHS, Condition, false);
11395 });
11396 }
11397
11398 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
11399 /// protected by a conditional between LHS and RHS. This is used to
11400 /// to eliminate casts.
11401 bool
isLoopBackedgeGuardedByCond(const Loop * L,ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)11402 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
11403 ICmpInst::Predicate Pred,
11404 const SCEV *LHS, const SCEV *RHS) {
11405 // Interpret a null as meaning no loop, where there is obviously no guard
11406 // (interprocedural conditions notwithstanding). Do not bother about
11407 // unreachable loops.
11408 if (!L || !DT.isReachableFromEntry(L->getHeader()))
11409 return true;
11410
11411 if (VerifyIR)
11412 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
11413 "This cannot be done on broken IR!");
11414
11415
11416 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11417 return true;
11418
11419 BasicBlock *Latch = L->getLoopLatch();
11420 if (!Latch)
11421 return false;
11422
11423 BranchInst *LoopContinuePredicate =
11424 dyn_cast<BranchInst>(Latch->getTerminator());
11425 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
11426 isImpliedCond(Pred, LHS, RHS,
11427 LoopContinuePredicate->getCondition(),
11428 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
11429 return true;
11430
11431 // We don't want more than one activation of the following loops on the stack
11432 // -- that can lead to O(n!) time complexity.
11433 if (WalkingBEDominatingConds)
11434 return false;
11435
11436 SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
11437
11438 // See if we can exploit a trip count to prove the predicate.
11439 const auto &BETakenInfo = getBackedgeTakenInfo(L);
11440 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
11441 if (LatchBECount != getCouldNotCompute()) {
11442 // We know that Latch branches back to the loop header exactly
11443 // LatchBECount times. This means the backdege condition at Latch is
11444 // equivalent to "{0,+,1} u< LatchBECount".
11445 Type *Ty = LatchBECount->getType();
11446 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
11447 const SCEV *LoopCounter =
11448 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
11449 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
11450 LatchBECount))
11451 return true;
11452 }
11453
11454 // Check conditions due to any @llvm.assume intrinsics.
11455 for (auto &AssumeVH : AC.assumptions()) {
11456 if (!AssumeVH)
11457 continue;
11458 auto *CI = cast<CallInst>(AssumeVH);
11459 if (!DT.dominates(CI, Latch->getTerminator()))
11460 continue;
11461
11462 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
11463 return true;
11464 }
11465
11466 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
11467 return true;
11468
11469 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
11470 DTN != HeaderDTN; DTN = DTN->getIDom()) {
11471 assert(DTN && "should reach the loop header before reaching the root!");
11472
11473 BasicBlock *BB = DTN->getBlock();
11474 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
11475 return true;
11476
11477 BasicBlock *PBB = BB->getSinglePredecessor();
11478 if (!PBB)
11479 continue;
11480
11481 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
11482 if (!ContinuePredicate || !ContinuePredicate->isConditional())
11483 continue;
11484
11485 Value *Condition = ContinuePredicate->getCondition();
11486
11487 // If we have an edge `E` within the loop body that dominates the only
11488 // latch, the condition guarding `E` also guards the backedge. This
11489 // reasoning works only for loops with a single latch.
11490
11491 BasicBlockEdge DominatingEdge(PBB, BB);
11492 if (DominatingEdge.isSingleEdge()) {
11493 // We're constructively (and conservatively) enumerating edges within the
11494 // loop body that dominate the latch. The dominator tree better agree
11495 // with us on this:
11496 assert(DT.dominates(DominatingEdge, Latch) && "should be!");
11497
11498 if (isImpliedCond(Pred, LHS, RHS, Condition,
11499 BB != ContinuePredicate->getSuccessor(0)))
11500 return true;
11501 }
11502 }
11503
11504 return false;
11505 }
11506
isBasicBlockEntryGuardedByCond(const BasicBlock * BB,ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)11507 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
11508 ICmpInst::Predicate Pred,
11509 const SCEV *LHS,
11510 const SCEV *RHS) {
11511 // Do not bother proving facts for unreachable code.
11512 if (!DT.isReachableFromEntry(BB))
11513 return true;
11514 if (VerifyIR)
11515 assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
11516 "This cannot be done on broken IR!");
11517
11518 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
11519 // the facts (a >= b && a != b) separately. A typical situation is when the
11520 // non-strict comparison is known from ranges and non-equality is known from
11521 // dominating predicates. If we are proving strict comparison, we always try
11522 // to prove non-equality and non-strict comparison separately.
11523 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
11524 const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
11525 bool ProvedNonStrictComparison = false;
11526 bool ProvedNonEquality = false;
11527
11528 auto SplitAndProve =
11529 [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool {
11530 if (!ProvedNonStrictComparison)
11531 ProvedNonStrictComparison = Fn(NonStrictPredicate);
11532 if (!ProvedNonEquality)
11533 ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
11534 if (ProvedNonStrictComparison && ProvedNonEquality)
11535 return true;
11536 return false;
11537 };
11538
11539 if (ProvingStrictComparison) {
11540 auto ProofFn = [&](ICmpInst::Predicate P) {
11541 return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
11542 };
11543 if (SplitAndProve(ProofFn))
11544 return true;
11545 }
11546
11547 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
11548 auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
11549 const Instruction *CtxI = &BB->front();
11550 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
11551 return true;
11552 if (ProvingStrictComparison) {
11553 auto ProofFn = [&](ICmpInst::Predicate P) {
11554 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
11555 };
11556 if (SplitAndProve(ProofFn))
11557 return true;
11558 }
11559 return false;
11560 };
11561
11562 // Starting at the block's predecessor, climb up the predecessor chain, as long
11563 // as there are predecessors that can be found that have unique successors
11564 // leading to the original block.
11565 const Loop *ContainingLoop = LI.getLoopFor(BB);
11566 const BasicBlock *PredBB;
11567 if (ContainingLoop && ContainingLoop->getHeader() == BB)
11568 PredBB = ContainingLoop->getLoopPredecessor();
11569 else
11570 PredBB = BB->getSinglePredecessor();
11571 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
11572 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
11573 const BranchInst *BlockEntryPredicate =
11574 dyn_cast<BranchInst>(Pair.first->getTerminator());
11575 if (!BlockEntryPredicate || BlockEntryPredicate->isUnconditional())
11576 continue;
11577
11578 if (ProveViaCond(BlockEntryPredicate->getCondition(),
11579 BlockEntryPredicate->getSuccessor(0) != Pair.second))
11580 return true;
11581 }
11582
11583 // Check conditions due to any @llvm.assume intrinsics.
11584 for (auto &AssumeVH : AC.assumptions()) {
11585 if (!AssumeVH)
11586 continue;
11587 auto *CI = cast<CallInst>(AssumeVH);
11588 if (!DT.dominates(CI, BB))
11589 continue;
11590
11591 if (ProveViaCond(CI->getArgOperand(0), false))
11592 return true;
11593 }
11594
11595 // Check conditions due to any @llvm.experimental.guard intrinsics.
11596 auto *GuardDecl = F.getParent()->getFunction(
11597 Intrinsic::getName(Intrinsic::experimental_guard));
11598 if (GuardDecl)
11599 for (const auto *GU : GuardDecl->users())
11600 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
11601 if (Guard->getFunction() == BB->getParent() && DT.dominates(Guard, BB))
11602 if (ProveViaCond(Guard->getArgOperand(0), false))
11603 return true;
11604 return false;
11605 }
11606
isLoopEntryGuardedByCond(const Loop * L,ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)11607 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
11608 ICmpInst::Predicate Pred,
11609 const SCEV *LHS,
11610 const SCEV *RHS) {
11611 // Interpret a null as meaning no loop, where there is obviously no guard
11612 // (interprocedural conditions notwithstanding).
11613 if (!L)
11614 return false;
11615
11616 // Both LHS and RHS must be available at loop entry.
11617 assert(isAvailableAtLoopEntry(LHS, L) &&
11618 "LHS is not available at Loop Entry");
11619 assert(isAvailableAtLoopEntry(RHS, L) &&
11620 "RHS is not available at Loop Entry");
11621
11622 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11623 return true;
11624
11625 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
11626 }
11627
isImpliedCond(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const Value * FoundCondValue,bool Inverse,const Instruction * CtxI)11628 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
11629 const SCEV *RHS,
11630 const Value *FoundCondValue, bool Inverse,
11631 const Instruction *CtxI) {
11632 // False conditions implies anything. Do not bother analyzing it further.
11633 if (FoundCondValue ==
11634 ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
11635 return true;
11636
11637 if (!PendingLoopPredicates.insert(FoundCondValue).second)
11638 return false;
11639
11640 auto ClearOnExit =
11641 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
11642
11643 // Recursively handle And and Or conditions.
11644 const Value *Op0, *Op1;
11645 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
11646 if (!Inverse)
11647 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
11648 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
11649 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
11650 if (Inverse)
11651 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
11652 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
11653 }
11654
11655 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
11656 if (!ICI) return false;
11657
11658 // Now that we found a conditional branch that dominates the loop or controls
11659 // the loop latch. Check to see if it is the comparison we are looking for.
11660 ICmpInst::Predicate FoundPred;
11661 if (Inverse)
11662 FoundPred = ICI->getInversePredicate();
11663 else
11664 FoundPred = ICI->getPredicate();
11665
11666 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
11667 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
11668
11669 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
11670 }
11671
isImpliedCond(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,ICmpInst::Predicate FoundPred,const SCEV * FoundLHS,const SCEV * FoundRHS,const Instruction * CtxI)11672 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
11673 const SCEV *RHS,
11674 ICmpInst::Predicate FoundPred,
11675 const SCEV *FoundLHS, const SCEV *FoundRHS,
11676 const Instruction *CtxI) {
11677 // Balance the types.
11678 if (getTypeSizeInBits(LHS->getType()) <
11679 getTypeSizeInBits(FoundLHS->getType())) {
11680 // For unsigned and equality predicates, try to prove that both found
11681 // operands fit into narrow unsigned range. If so, try to prove facts in
11682 // narrow types.
11683 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
11684 !FoundRHS->getType()->isPointerTy()) {
11685 auto *NarrowType = LHS->getType();
11686 auto *WideType = FoundLHS->getType();
11687 auto BitWidth = getTypeSizeInBits(NarrowType);
11688 const SCEV *MaxValue = getZeroExtendExpr(
11689 getConstant(APInt::getMaxValue(BitWidth)), WideType);
11690 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
11691 MaxValue) &&
11692 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
11693 MaxValue)) {
11694 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
11695 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
11696 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
11697 TruncFoundRHS, CtxI))
11698 return true;
11699 }
11700 }
11701
11702 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
11703 return false;
11704 if (CmpInst::isSigned(Pred)) {
11705 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
11706 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
11707 } else {
11708 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
11709 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
11710 }
11711 } else if (getTypeSizeInBits(LHS->getType()) >
11712 getTypeSizeInBits(FoundLHS->getType())) {
11713 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
11714 return false;
11715 if (CmpInst::isSigned(FoundPred)) {
11716 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
11717 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
11718 } else {
11719 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
11720 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
11721 }
11722 }
11723 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
11724 FoundRHS, CtxI);
11725 }
11726
isImpliedCondBalancedTypes(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,ICmpInst::Predicate FoundPred,const SCEV * FoundLHS,const SCEV * FoundRHS,const Instruction * CtxI)11727 bool ScalarEvolution::isImpliedCondBalancedTypes(
11728 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11729 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
11730 const Instruction *CtxI) {
11731 assert(getTypeSizeInBits(LHS->getType()) ==
11732 getTypeSizeInBits(FoundLHS->getType()) &&
11733 "Types should be balanced!");
11734 // Canonicalize the query to match the way instcombine will have
11735 // canonicalized the comparison.
11736 if (SimplifyICmpOperands(Pred, LHS, RHS))
11737 if (LHS == RHS)
11738 return CmpInst::isTrueWhenEqual(Pred);
11739 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
11740 if (FoundLHS == FoundRHS)
11741 return CmpInst::isFalseWhenEqual(FoundPred);
11742
11743 // Check to see if we can make the LHS or RHS match.
11744 if (LHS == FoundRHS || RHS == FoundLHS) {
11745 if (isa<SCEVConstant>(RHS)) {
11746 std::swap(FoundLHS, FoundRHS);
11747 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
11748 } else {
11749 std::swap(LHS, RHS);
11750 Pred = ICmpInst::getSwappedPredicate(Pred);
11751 }
11752 }
11753
11754 // Check whether the found predicate is the same as the desired predicate.
11755 if (FoundPred == Pred)
11756 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
11757
11758 // Check whether swapping the found predicate makes it the same as the
11759 // desired predicate.
11760 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
11761 // We can write the implication
11762 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS
11763 // using one of the following ways:
11764 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS
11765 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS
11766 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS
11767 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS
11768 // Forms 1. and 2. require swapping the operands of one condition. Don't
11769 // do this if it would break canonical constant/addrec ordering.
11770 if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS))
11771 return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS,
11772 CtxI);
11773 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
11774 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI);
11775
11776 // There's no clear preference between forms 3. and 4., try both. Avoid
11777 // forming getNotSCEV of pointer values as the resulting subtract is
11778 // not legal.
11779 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() &&
11780 isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS),
11781 FoundLHS, FoundRHS, CtxI))
11782 return true;
11783
11784 if (!FoundLHS->getType()->isPointerTy() &&
11785 !FoundRHS->getType()->isPointerTy() &&
11786 isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS),
11787 getNotSCEV(FoundRHS), CtxI))
11788 return true;
11789
11790 return false;
11791 }
11792
11793 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
11794 CmpInst::Predicate P2) {
11795 assert(P1 != P2 && "Handled earlier!");
11796 return CmpInst::isRelational(P2) &&
11797 P1 == CmpInst::getFlippedSignednessPredicate(P2);
11798 };
11799 if (IsSignFlippedPredicate(Pred, FoundPred)) {
11800 // Unsigned comparison is the same as signed comparison when both the
11801 // operands are non-negative or negative.
11802 if ((isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) ||
11803 (isKnownNegative(FoundLHS) && isKnownNegative(FoundRHS)))
11804 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
11805 // Create local copies that we can freely swap and canonicalize our
11806 // conditions to "le/lt".
11807 ICmpInst::Predicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
11808 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
11809 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
11810 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
11811 CanonicalPred = ICmpInst::getSwappedPredicate(CanonicalPred);
11812 CanonicalFoundPred = ICmpInst::getSwappedPredicate(CanonicalFoundPred);
11813 std::swap(CanonicalLHS, CanonicalRHS);
11814 std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
11815 }
11816 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
11817 "Must be!");
11818 assert((ICmpInst::isLT(CanonicalFoundPred) ||
11819 ICmpInst::isLE(CanonicalFoundPred)) &&
11820 "Must be!");
11821 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
11822 // Use implication:
11823 // x <u y && y >=s 0 --> x <s y.
11824 // If we can prove the left part, the right part is also proven.
11825 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
11826 CanonicalRHS, CanonicalFoundLHS,
11827 CanonicalFoundRHS);
11828 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
11829 // Use implication:
11830 // x <s y && y <s 0 --> x <u y.
11831 // If we can prove the left part, the right part is also proven.
11832 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
11833 CanonicalRHS, CanonicalFoundLHS,
11834 CanonicalFoundRHS);
11835 }
11836
11837 // Check if we can make progress by sharpening ranges.
11838 if (FoundPred == ICmpInst::ICMP_NE &&
11839 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
11840
11841 const SCEVConstant *C = nullptr;
11842 const SCEV *V = nullptr;
11843
11844 if (isa<SCEVConstant>(FoundLHS)) {
11845 C = cast<SCEVConstant>(FoundLHS);
11846 V = FoundRHS;
11847 } else {
11848 C = cast<SCEVConstant>(FoundRHS);
11849 V = FoundLHS;
11850 }
11851
11852 // The guarding predicate tells us that C != V. If the known range
11853 // of V is [C, t), we can sharpen the range to [C + 1, t). The
11854 // range we consider has to correspond to same signedness as the
11855 // predicate we're interested in folding.
11856
11857 APInt Min = ICmpInst::isSigned(Pred) ?
11858 getSignedRangeMin(V) : getUnsignedRangeMin(V);
11859
11860 if (Min == C->getAPInt()) {
11861 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
11862 // This is true even if (Min + 1) wraps around -- in case of
11863 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
11864
11865 APInt SharperMin = Min + 1;
11866
11867 switch (Pred) {
11868 case ICmpInst::ICMP_SGE:
11869 case ICmpInst::ICMP_UGE:
11870 // We know V `Pred` SharperMin. If this implies LHS `Pred`
11871 // RHS, we're done.
11872 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
11873 CtxI))
11874 return true;
11875 [[fallthrough]];
11876
11877 case ICmpInst::ICMP_SGT:
11878 case ICmpInst::ICMP_UGT:
11879 // We know from the range information that (V `Pred` Min ||
11880 // V == Min). We know from the guarding condition that !(V
11881 // == Min). This gives us
11882 //
11883 // V `Pred` Min || V == Min && !(V == Min)
11884 // => V `Pred` Min
11885 //
11886 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
11887
11888 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
11889 return true;
11890 break;
11891
11892 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
11893 case ICmpInst::ICMP_SLE:
11894 case ICmpInst::ICMP_ULE:
11895 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
11896 LHS, V, getConstant(SharperMin), CtxI))
11897 return true;
11898 [[fallthrough]];
11899
11900 case ICmpInst::ICMP_SLT:
11901 case ICmpInst::ICMP_ULT:
11902 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
11903 LHS, V, getConstant(Min), CtxI))
11904 return true;
11905 break;
11906
11907 default:
11908 // No change
11909 break;
11910 }
11911 }
11912 }
11913
11914 // Check whether the actual condition is beyond sufficient.
11915 if (FoundPred == ICmpInst::ICMP_EQ)
11916 if (ICmpInst::isTrueWhenEqual(Pred))
11917 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
11918 return true;
11919 if (Pred == ICmpInst::ICMP_NE)
11920 if (!ICmpInst::isTrueWhenEqual(FoundPred))
11921 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
11922 return true;
11923
11924 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS))
11925 return true;
11926
11927 // Otherwise assume the worst.
11928 return false;
11929 }
11930
splitBinaryAdd(const SCEV * Expr,const SCEV * & L,const SCEV * & R,SCEV::NoWrapFlags & Flags)11931 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
11932 const SCEV *&L, const SCEV *&R,
11933 SCEV::NoWrapFlags &Flags) {
11934 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
11935 if (!AE || AE->getNumOperands() != 2)
11936 return false;
11937
11938 L = AE->getOperand(0);
11939 R = AE->getOperand(1);
11940 Flags = AE->getNoWrapFlags();
11941 return true;
11942 }
11943
11944 std::optional<APInt>
computeConstantDifference(const SCEV * More,const SCEV * Less)11945 ScalarEvolution::computeConstantDifference(const SCEV *More, const SCEV *Less) {
11946 // We avoid subtracting expressions here because this function is usually
11947 // fairly deep in the call stack (i.e. is called many times).
11948
11949 // X - X = 0.
11950 if (More == Less)
11951 return APInt(getTypeSizeInBits(More->getType()), 0);
11952
11953 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
11954 const auto *LAR = cast<SCEVAddRecExpr>(Less);
11955 const auto *MAR = cast<SCEVAddRecExpr>(More);
11956
11957 if (LAR->getLoop() != MAR->getLoop())
11958 return std::nullopt;
11959
11960 // We look at affine expressions only; not for correctness but to keep
11961 // getStepRecurrence cheap.
11962 if (!LAR->isAffine() || !MAR->isAffine())
11963 return std::nullopt;
11964
11965 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
11966 return std::nullopt;
11967
11968 Less = LAR->getStart();
11969 More = MAR->getStart();
11970
11971 // fall through
11972 }
11973
11974 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
11975 const auto &M = cast<SCEVConstant>(More)->getAPInt();
11976 const auto &L = cast<SCEVConstant>(Less)->getAPInt();
11977 return M - L;
11978 }
11979
11980 SCEV::NoWrapFlags Flags;
11981 const SCEV *LLess = nullptr, *RLess = nullptr;
11982 const SCEV *LMore = nullptr, *RMore = nullptr;
11983 const SCEVConstant *C1 = nullptr, *C2 = nullptr;
11984 // Compare (X + C1) vs X.
11985 if (splitBinaryAdd(Less, LLess, RLess, Flags))
11986 if ((C1 = dyn_cast<SCEVConstant>(LLess)))
11987 if (RLess == More)
11988 return -(C1->getAPInt());
11989
11990 // Compare X vs (X + C2).
11991 if (splitBinaryAdd(More, LMore, RMore, Flags))
11992 if ((C2 = dyn_cast<SCEVConstant>(LMore)))
11993 if (RMore == Less)
11994 return C2->getAPInt();
11995
11996 // Compare (X + C1) vs (X + C2).
11997 if (C1 && C2 && RLess == RMore)
11998 return C2->getAPInt() - C1->getAPInt();
11999
12000 return std::nullopt;
12001 }
12002
isImpliedCondOperandsViaAddRecStart(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const SCEV * FoundLHS,const SCEV * FoundRHS,const Instruction * CtxI)12003 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
12004 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
12005 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *CtxI) {
12006 // Try to recognize the following pattern:
12007 //
12008 // FoundRHS = ...
12009 // ...
12010 // loop:
12011 // FoundLHS = {Start,+,W}
12012 // context_bb: // Basic block from the same loop
12013 // known(Pred, FoundLHS, FoundRHS)
12014 //
12015 // If some predicate is known in the context of a loop, it is also known on
12016 // each iteration of this loop, including the first iteration. Therefore, in
12017 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
12018 // prove the original pred using this fact.
12019 if (!CtxI)
12020 return false;
12021 const BasicBlock *ContextBB = CtxI->getParent();
12022 // Make sure AR varies in the context block.
12023 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
12024 const Loop *L = AR->getLoop();
12025 // Make sure that context belongs to the loop and executes on 1st iteration
12026 // (if it ever executes at all).
12027 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
12028 return false;
12029 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
12030 return false;
12031 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
12032 }
12033
12034 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
12035 const Loop *L = AR->getLoop();
12036 // Make sure that context belongs to the loop and executes on 1st iteration
12037 // (if it ever executes at all).
12038 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
12039 return false;
12040 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
12041 return false;
12042 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
12043 }
12044
12045 return false;
12046 }
12047
isImpliedCondOperandsViaNoOverflow(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const SCEV * FoundLHS,const SCEV * FoundRHS)12048 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
12049 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
12050 const SCEV *FoundLHS, const SCEV *FoundRHS) {
12051 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
12052 return false;
12053
12054 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
12055 if (!AddRecLHS)
12056 return false;
12057
12058 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12059 if (!AddRecFoundLHS)
12060 return false;
12061
12062 // We'd like to let SCEV reason about control dependencies, so we constrain
12063 // both the inequalities to be about add recurrences on the same loop. This
12064 // way we can use isLoopEntryGuardedByCond later.
12065
12066 const Loop *L = AddRecFoundLHS->getLoop();
12067 if (L != AddRecLHS->getLoop())
12068 return false;
12069
12070 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
12071 //
12072 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
12073 // ... (2)
12074 //
12075 // Informal proof for (2), assuming (1) [*]:
12076 //
12077 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
12078 //
12079 // Then
12080 //
12081 // FoundLHS s< FoundRHS s< INT_MIN - C
12082 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
12083 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
12084 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
12085 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
12086 // <=> FoundLHS + C s< FoundRHS + C
12087 //
12088 // [*]: (1) can be proved by ruling out overflow.
12089 //
12090 // [**]: This can be proved by analyzing all the four possibilities:
12091 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
12092 // (A s>= 0, B s>= 0).
12093 //
12094 // Note:
12095 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
12096 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
12097 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
12098 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
12099 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
12100 // C)".
12101
12102 std::optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
12103 std::optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
12104 if (!LDiff || !RDiff || *LDiff != *RDiff)
12105 return false;
12106
12107 if (LDiff->isMinValue())
12108 return true;
12109
12110 APInt FoundRHSLimit;
12111
12112 if (Pred == CmpInst::ICMP_ULT) {
12113 FoundRHSLimit = -(*RDiff);
12114 } else {
12115 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
12116 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
12117 }
12118
12119 // Try to prove (1) or (2), as needed.
12120 return isAvailableAtLoopEntry(FoundRHS, L) &&
12121 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
12122 getConstant(FoundRHSLimit));
12123 }
12124
isImpliedViaMerge(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const SCEV * FoundLHS,const SCEV * FoundRHS,unsigned Depth)12125 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
12126 const SCEV *LHS, const SCEV *RHS,
12127 const SCEV *FoundLHS,
12128 const SCEV *FoundRHS, unsigned Depth) {
12129 const PHINode *LPhi = nullptr, *RPhi = nullptr;
12130
12131 auto ClearOnExit = make_scope_exit([&]() {
12132 if (LPhi) {
12133 bool Erased = PendingMerges.erase(LPhi);
12134 assert(Erased && "Failed to erase LPhi!");
12135 (void)Erased;
12136 }
12137 if (RPhi) {
12138 bool Erased = PendingMerges.erase(RPhi);
12139 assert(Erased && "Failed to erase RPhi!");
12140 (void)Erased;
12141 }
12142 });
12143
12144 // Find respective Phis and check that they are not being pending.
12145 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
12146 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
12147 if (!PendingMerges.insert(Phi).second)
12148 return false;
12149 LPhi = Phi;
12150 }
12151 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
12152 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
12153 // If we detect a loop of Phi nodes being processed by this method, for
12154 // example:
12155 //
12156 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
12157 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
12158 //
12159 // we don't want to deal with a case that complex, so return conservative
12160 // answer false.
12161 if (!PendingMerges.insert(Phi).second)
12162 return false;
12163 RPhi = Phi;
12164 }
12165
12166 // If none of LHS, RHS is a Phi, nothing to do here.
12167 if (!LPhi && !RPhi)
12168 return false;
12169
12170 // If there is a SCEVUnknown Phi we are interested in, make it left.
12171 if (!LPhi) {
12172 std::swap(LHS, RHS);
12173 std::swap(FoundLHS, FoundRHS);
12174 std::swap(LPhi, RPhi);
12175 Pred = ICmpInst::getSwappedPredicate(Pred);
12176 }
12177
12178 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
12179 const BasicBlock *LBB = LPhi->getParent();
12180 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12181
12182 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
12183 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
12184 isImpliedCondOperandsViaRanges(Pred, S1, S2, Pred, FoundLHS, FoundRHS) ||
12185 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
12186 };
12187
12188 if (RPhi && RPhi->getParent() == LBB) {
12189 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
12190 // If we compare two Phis from the same block, and for each entry block
12191 // the predicate is true for incoming values from this block, then the
12192 // predicate is also true for the Phis.
12193 for (const BasicBlock *IncBB : predecessors(LBB)) {
12194 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12195 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
12196 if (!ProvedEasily(L, R))
12197 return false;
12198 }
12199 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
12200 // Case two: RHS is also a Phi from the same basic block, and it is an
12201 // AddRec. It means that there is a loop which has both AddRec and Unknown
12202 // PHIs, for it we can compare incoming values of AddRec from above the loop
12203 // and latch with their respective incoming values of LPhi.
12204 // TODO: Generalize to handle loops with many inputs in a header.
12205 if (LPhi->getNumIncomingValues() != 2) return false;
12206
12207 auto *RLoop = RAR->getLoop();
12208 auto *Predecessor = RLoop->getLoopPredecessor();
12209 assert(Predecessor && "Loop with AddRec with no predecessor?");
12210 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
12211 if (!ProvedEasily(L1, RAR->getStart()))
12212 return false;
12213 auto *Latch = RLoop->getLoopLatch();
12214 assert(Latch && "Loop with AddRec with no latch?");
12215 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
12216 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
12217 return false;
12218 } else {
12219 // In all other cases go over inputs of LHS and compare each of them to RHS,
12220 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
12221 // At this point RHS is either a non-Phi, or it is a Phi from some block
12222 // different from LBB.
12223 for (const BasicBlock *IncBB : predecessors(LBB)) {
12224 // Check that RHS is available in this block.
12225 if (!dominates(RHS, IncBB))
12226 return false;
12227 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12228 // Make sure L does not refer to a value from a potentially previous
12229 // iteration of a loop.
12230 if (!properlyDominates(L, LBB))
12231 return false;
12232 if (!ProvedEasily(L, RHS))
12233 return false;
12234 }
12235 }
12236 return true;
12237 }
12238
isImpliedCondOperandsViaShift(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const SCEV * FoundLHS,const SCEV * FoundRHS)12239 bool ScalarEvolution::isImpliedCondOperandsViaShift(ICmpInst::Predicate Pred,
12240 const SCEV *LHS,
12241 const SCEV *RHS,
12242 const SCEV *FoundLHS,
12243 const SCEV *FoundRHS) {
12244 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make
12245 // sure that we are dealing with same LHS.
12246 if (RHS == FoundRHS) {
12247 std::swap(LHS, RHS);
12248 std::swap(FoundLHS, FoundRHS);
12249 Pred = ICmpInst::getSwappedPredicate(Pred);
12250 }
12251 if (LHS != FoundLHS)
12252 return false;
12253
12254 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
12255 if (!SUFoundRHS)
12256 return false;
12257
12258 Value *Shiftee, *ShiftValue;
12259
12260 using namespace PatternMatch;
12261 if (match(SUFoundRHS->getValue(),
12262 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
12263 auto *ShifteeS = getSCEV(Shiftee);
12264 // Prove one of the following:
12265 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
12266 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
12267 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12268 // ---> LHS <s RHS
12269 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12270 // ---> LHS <=s RHS
12271 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
12272 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
12273 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
12274 if (isKnownNonNegative(ShifteeS))
12275 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
12276 }
12277
12278 return false;
12279 }
12280
isImpliedCondOperands(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const SCEV * FoundLHS,const SCEV * FoundRHS,const Instruction * CtxI)12281 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
12282 const SCEV *LHS, const SCEV *RHS,
12283 const SCEV *FoundLHS,
12284 const SCEV *FoundRHS,
12285 const Instruction *CtxI) {
12286 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, Pred, FoundLHS, FoundRHS))
12287 return true;
12288
12289 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
12290 return true;
12291
12292 if (isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS))
12293 return true;
12294
12295 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12296 CtxI))
12297 return true;
12298
12299 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
12300 FoundLHS, FoundRHS);
12301 }
12302
12303 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
12304 template <typename MinMaxExprType>
IsMinMaxConsistingOf(const SCEV * MaybeMinMaxExpr,const SCEV * Candidate)12305 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
12306 const SCEV *Candidate) {
12307 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12308 if (!MinMaxExpr)
12309 return false;
12310
12311 return is_contained(MinMaxExpr->operands(), Candidate);
12312 }
12313
IsKnownPredicateViaAddRecStart(ScalarEvolution & SE,ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)12314 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
12315 ICmpInst::Predicate Pred,
12316 const SCEV *LHS, const SCEV *RHS) {
12317 // If both sides are affine addrecs for the same loop, with equal
12318 // steps, and we know the recurrences don't wrap, then we only
12319 // need to check the predicate on the starting values.
12320
12321 if (!ICmpInst::isRelational(Pred))
12322 return false;
12323
12324 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
12325 if (!LAR)
12326 return false;
12327 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12328 if (!RAR)
12329 return false;
12330 if (LAR->getLoop() != RAR->getLoop())
12331 return false;
12332 if (!LAR->isAffine() || !RAR->isAffine())
12333 return false;
12334
12335 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
12336 return false;
12337
12338 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
12339 SCEV::FlagNSW : SCEV::FlagNUW;
12340 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
12341 return false;
12342
12343 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
12344 }
12345
12346 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
12347 /// expression?
IsKnownPredicateViaMinOrMax(ScalarEvolution & SE,ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)12348 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
12349 ICmpInst::Predicate Pred,
12350 const SCEV *LHS, const SCEV *RHS) {
12351 switch (Pred) {
12352 default:
12353 return false;
12354
12355 case ICmpInst::ICMP_SGE:
12356 std::swap(LHS, RHS);
12357 [[fallthrough]];
12358 case ICmpInst::ICMP_SLE:
12359 return
12360 // min(A, ...) <= A
12361 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
12362 // A <= max(A, ...)
12363 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
12364
12365 case ICmpInst::ICMP_UGE:
12366 std::swap(LHS, RHS);
12367 [[fallthrough]];
12368 case ICmpInst::ICMP_ULE:
12369 return
12370 // min(A, ...) <= A
12371 // FIXME: what about umin_seq?
12372 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
12373 // A <= max(A, ...)
12374 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
12375 }
12376
12377 llvm_unreachable("covered switch fell through?!");
12378 }
12379
isImpliedViaOperations(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const SCEV * FoundLHS,const SCEV * FoundRHS,unsigned Depth)12380 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
12381 const SCEV *LHS, const SCEV *RHS,
12382 const SCEV *FoundLHS,
12383 const SCEV *FoundRHS,
12384 unsigned Depth) {
12385 assert(getTypeSizeInBits(LHS->getType()) ==
12386 getTypeSizeInBits(RHS->getType()) &&
12387 "LHS and RHS have different sizes?");
12388 assert(getTypeSizeInBits(FoundLHS->getType()) ==
12389 getTypeSizeInBits(FoundRHS->getType()) &&
12390 "FoundLHS and FoundRHS have different sizes?");
12391 // We want to avoid hurting the compile time with analysis of too big trees.
12392 if (Depth > MaxSCEVOperationsImplicationDepth)
12393 return false;
12394
12395 // We only want to work with GT comparison so far.
12396 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
12397 Pred = CmpInst::getSwappedPredicate(Pred);
12398 std::swap(LHS, RHS);
12399 std::swap(FoundLHS, FoundRHS);
12400 }
12401
12402 // For unsigned, try to reduce it to corresponding signed comparison.
12403 if (Pred == ICmpInst::ICMP_UGT)
12404 // We can replace unsigned predicate with its signed counterpart if all
12405 // involved values are non-negative.
12406 // TODO: We could have better support for unsigned.
12407 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
12408 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
12409 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
12410 // use this fact to prove that LHS and RHS are non-negative.
12411 const SCEV *MinusOne = getMinusOne(LHS->getType());
12412 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
12413 FoundRHS) &&
12414 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
12415 FoundRHS))
12416 Pred = ICmpInst::ICMP_SGT;
12417 }
12418
12419 if (Pred != ICmpInst::ICMP_SGT)
12420 return false;
12421
12422 auto GetOpFromSExt = [&](const SCEV *S) {
12423 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
12424 return Ext->getOperand();
12425 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
12426 // the constant in some cases.
12427 return S;
12428 };
12429
12430 // Acquire values from extensions.
12431 auto *OrigLHS = LHS;
12432 auto *OrigFoundLHS = FoundLHS;
12433 LHS = GetOpFromSExt(LHS);
12434 FoundLHS = GetOpFromSExt(FoundLHS);
12435
12436 // Is the SGT predicate can be proved trivially or using the found context.
12437 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
12438 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
12439 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
12440 FoundRHS, Depth + 1);
12441 };
12442
12443 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
12444 // We want to avoid creation of any new non-constant SCEV. Since we are
12445 // going to compare the operands to RHS, we should be certain that we don't
12446 // need any size extensions for this. So let's decline all cases when the
12447 // sizes of types of LHS and RHS do not match.
12448 // TODO: Maybe try to get RHS from sext to catch more cases?
12449 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
12450 return false;
12451
12452 // Should not overflow.
12453 if (!LHSAddExpr->hasNoSignedWrap())
12454 return false;
12455
12456 auto *LL = LHSAddExpr->getOperand(0);
12457 auto *LR = LHSAddExpr->getOperand(1);
12458 auto *MinusOne = getMinusOne(RHS->getType());
12459
12460 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
12461 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
12462 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
12463 };
12464 // Try to prove the following rule:
12465 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
12466 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
12467 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
12468 return true;
12469 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
12470 Value *LL, *LR;
12471 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
12472
12473 using namespace llvm::PatternMatch;
12474
12475 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
12476 // Rules for division.
12477 // We are going to perform some comparisons with Denominator and its
12478 // derivative expressions. In general case, creating a SCEV for it may
12479 // lead to a complex analysis of the entire graph, and in particular it
12480 // can request trip count recalculation for the same loop. This would
12481 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
12482 // this, we only want to create SCEVs that are constants in this section.
12483 // So we bail if Denominator is not a constant.
12484 if (!isa<ConstantInt>(LR))
12485 return false;
12486
12487 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
12488
12489 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
12490 // then a SCEV for the numerator already exists and matches with FoundLHS.
12491 auto *Numerator = getExistingSCEV(LL);
12492 if (!Numerator || Numerator->getType() != FoundLHS->getType())
12493 return false;
12494
12495 // Make sure that the numerator matches with FoundLHS and the denominator
12496 // is positive.
12497 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
12498 return false;
12499
12500 auto *DTy = Denominator->getType();
12501 auto *FRHSTy = FoundRHS->getType();
12502 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
12503 // One of types is a pointer and another one is not. We cannot extend
12504 // them properly to a wider type, so let us just reject this case.
12505 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
12506 // to avoid this check.
12507 return false;
12508
12509 // Given that:
12510 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
12511 auto *WTy = getWiderType(DTy, FRHSTy);
12512 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
12513 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
12514
12515 // Try to prove the following rule:
12516 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
12517 // For example, given that FoundLHS > 2. It means that FoundLHS is at
12518 // least 3. If we divide it by Denominator < 4, we will have at least 1.
12519 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
12520 if (isKnownNonPositive(RHS) &&
12521 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
12522 return true;
12523
12524 // Try to prove the following rule:
12525 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
12526 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
12527 // If we divide it by Denominator > 2, then:
12528 // 1. If FoundLHS is negative, then the result is 0.
12529 // 2. If FoundLHS is non-negative, then the result is non-negative.
12530 // Anyways, the result is non-negative.
12531 auto *MinusOne = getMinusOne(WTy);
12532 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
12533 if (isKnownNegative(RHS) &&
12534 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
12535 return true;
12536 }
12537 }
12538
12539 // If our expression contained SCEVUnknown Phis, and we split it down and now
12540 // need to prove something for them, try to prove the predicate for every
12541 // possible incoming values of those Phis.
12542 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
12543 return true;
12544
12545 return false;
12546 }
12547
isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)12548 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
12549 const SCEV *LHS, const SCEV *RHS) {
12550 // zext x u<= sext x, sext x s<= zext x
12551 switch (Pred) {
12552 case ICmpInst::ICMP_SGE:
12553 std::swap(LHS, RHS);
12554 [[fallthrough]];
12555 case ICmpInst::ICMP_SLE: {
12556 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt.
12557 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
12558 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
12559 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
12560 return true;
12561 break;
12562 }
12563 case ICmpInst::ICMP_UGE:
12564 std::swap(LHS, RHS);
12565 [[fallthrough]];
12566 case ICmpInst::ICMP_ULE: {
12567 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt.
12568 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
12569 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
12570 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
12571 return true;
12572 break;
12573 }
12574 default:
12575 break;
12576 };
12577 return false;
12578 }
12579
12580 bool
isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)12581 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
12582 const SCEV *LHS, const SCEV *RHS) {
12583 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
12584 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
12585 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
12586 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
12587 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
12588 }
12589
12590 bool
isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const SCEV * FoundLHS,const SCEV * FoundRHS)12591 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
12592 const SCEV *LHS, const SCEV *RHS,
12593 const SCEV *FoundLHS,
12594 const SCEV *FoundRHS) {
12595 switch (Pred) {
12596 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
12597 case ICmpInst::ICMP_EQ:
12598 case ICmpInst::ICMP_NE:
12599 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
12600 return true;
12601 break;
12602 case ICmpInst::ICMP_SLT:
12603 case ICmpInst::ICMP_SLE:
12604 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
12605 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
12606 return true;
12607 break;
12608 case ICmpInst::ICMP_SGT:
12609 case ICmpInst::ICMP_SGE:
12610 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
12611 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
12612 return true;
12613 break;
12614 case ICmpInst::ICMP_ULT:
12615 case ICmpInst::ICMP_ULE:
12616 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
12617 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
12618 return true;
12619 break;
12620 case ICmpInst::ICMP_UGT:
12621 case ICmpInst::ICMP_UGE:
12622 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
12623 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
12624 return true;
12625 break;
12626 }
12627
12628 // Maybe it can be proved via operations?
12629 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
12630 return true;
12631
12632 return false;
12633 }
12634
isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,ICmpInst::Predicate FoundPred,const SCEV * FoundLHS,const SCEV * FoundRHS)12635 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
12636 const SCEV *LHS,
12637 const SCEV *RHS,
12638 ICmpInst::Predicate FoundPred,
12639 const SCEV *FoundLHS,
12640 const SCEV *FoundRHS) {
12641 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
12642 // The restriction on `FoundRHS` be lifted easily -- it exists only to
12643 // reduce the compile time impact of this optimization.
12644 return false;
12645
12646 std::optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
12647 if (!Addend)
12648 return false;
12649
12650 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
12651
12652 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
12653 // antecedent "`FoundLHS` `FoundPred` `FoundRHS`".
12654 ConstantRange FoundLHSRange =
12655 ConstantRange::makeExactICmpRegion(FoundPred, ConstFoundRHS);
12656
12657 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
12658 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
12659
12660 // We can also compute the range of values for `LHS` that satisfy the
12661 // consequent, "`LHS` `Pred` `RHS`":
12662 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
12663 // The antecedent implies the consequent if every value of `LHS` that
12664 // satisfies the antecedent also satisfies the consequent.
12665 return LHSRange.icmp(Pred, ConstRHS);
12666 }
12667
canIVOverflowOnLT(const SCEV * RHS,const SCEV * Stride,bool IsSigned)12668 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
12669 bool IsSigned) {
12670 assert(isKnownPositive(Stride) && "Positive stride expected!");
12671
12672 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
12673 const SCEV *One = getOne(Stride->getType());
12674
12675 if (IsSigned) {
12676 APInt MaxRHS = getSignedRangeMax(RHS);
12677 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
12678 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
12679
12680 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
12681 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
12682 }
12683
12684 APInt MaxRHS = getUnsignedRangeMax(RHS);
12685 APInt MaxValue = APInt::getMaxValue(BitWidth);
12686 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
12687
12688 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
12689 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
12690 }
12691
canIVOverflowOnGT(const SCEV * RHS,const SCEV * Stride,bool IsSigned)12692 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
12693 bool IsSigned) {
12694
12695 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
12696 const SCEV *One = getOne(Stride->getType());
12697
12698 if (IsSigned) {
12699 APInt MinRHS = getSignedRangeMin(RHS);
12700 APInt MinValue = APInt::getSignedMinValue(BitWidth);
12701 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
12702
12703 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
12704 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
12705 }
12706
12707 APInt MinRHS = getUnsignedRangeMin(RHS);
12708 APInt MinValue = APInt::getMinValue(BitWidth);
12709 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
12710
12711 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
12712 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
12713 }
12714
getUDivCeilSCEV(const SCEV * N,const SCEV * D)12715 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) {
12716 // umin(N, 1) + floor((N - umin(N, 1)) / D)
12717 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
12718 // expression fixes the case of N=0.
12719 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
12720 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
12721 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
12722 }
12723
computeMaxBECountForLT(const SCEV * Start,const SCEV * Stride,const SCEV * End,unsigned BitWidth,bool IsSigned)12724 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
12725 const SCEV *Stride,
12726 const SCEV *End,
12727 unsigned BitWidth,
12728 bool IsSigned) {
12729 // The logic in this function assumes we can represent a positive stride.
12730 // If we can't, the backedge-taken count must be zero.
12731 if (IsSigned && BitWidth == 1)
12732 return getZero(Stride->getType());
12733
12734 // This code below only been closely audited for negative strides in the
12735 // unsigned comparison case, it may be correct for signed comparison, but
12736 // that needs to be established.
12737 if (IsSigned && isKnownNegative(Stride))
12738 return getCouldNotCompute();
12739
12740 // Calculate the maximum backedge count based on the range of values
12741 // permitted by Start, End, and Stride.
12742 APInt MinStart =
12743 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
12744
12745 APInt MinStride =
12746 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
12747
12748 // We assume either the stride is positive, or the backedge-taken count
12749 // is zero. So force StrideForMaxBECount to be at least one.
12750 APInt One(BitWidth, 1);
12751 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
12752 : APIntOps::umax(One, MinStride);
12753
12754 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
12755 : APInt::getMaxValue(BitWidth);
12756 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
12757
12758 // Although End can be a MAX expression we estimate MaxEnd considering only
12759 // the case End = RHS of the loop termination condition. This is safe because
12760 // in the other case (End - Start) is zero, leading to a zero maximum backedge
12761 // taken count.
12762 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
12763 : APIntOps::umin(getUnsignedRangeMax(End), Limit);
12764
12765 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
12766 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
12767 : APIntOps::umax(MaxEnd, MinStart);
12768
12769 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */,
12770 getConstant(StrideForMaxBECount) /* Step */);
12771 }
12772
12773 ScalarEvolution::ExitLimit
howManyLessThans(const SCEV * LHS,const SCEV * RHS,const Loop * L,bool IsSigned,bool ControlsOnlyExit,bool AllowPredicates)12774 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
12775 const Loop *L, bool IsSigned,
12776 bool ControlsOnlyExit, bool AllowPredicates) {
12777 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
12778
12779 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
12780 bool PredicatedIV = false;
12781
12782 auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) {
12783 // Can we prove this loop *must* be UB if overflow of IV occurs?
12784 // Reasoning goes as follows:
12785 // * Suppose the IV did self wrap.
12786 // * If Stride evenly divides the iteration space, then once wrap
12787 // occurs, the loop must revisit the same values.
12788 // * We know that RHS is invariant, and that none of those values
12789 // caused this exit to be taken previously. Thus, this exit is
12790 // dynamically dead.
12791 // * If this is the sole exit, then a dead exit implies the loop
12792 // must be infinite if there are no abnormal exits.
12793 // * If the loop were infinite, then it must either not be mustprogress
12794 // or have side effects. Otherwise, it must be UB.
12795 // * It can't (by assumption), be UB so we have contradicted our
12796 // premise and can conclude the IV did not in fact self-wrap.
12797 if (!isLoopInvariant(RHS, L))
12798 return false;
12799
12800 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
12801 if (!StrideC || !StrideC->getAPInt().isPowerOf2())
12802 return false;
12803
12804 if (!ControlsOnlyExit || !loopHasNoAbnormalExits(L))
12805 return false;
12806
12807 return loopIsFiniteByAssumption(L);
12808 };
12809
12810 if (!IV) {
12811 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
12812 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
12813 if (AR && AR->getLoop() == L && AR->isAffine()) {
12814 auto canProveNUW = [&]() {
12815 // We can use the comparison to infer no-wrap flags only if it fully
12816 // controls the loop exit.
12817 if (!ControlsOnlyExit)
12818 return false;
12819
12820 if (!isLoopInvariant(RHS, L))
12821 return false;
12822
12823 if (!isKnownNonZero(AR->getStepRecurrence(*this)))
12824 // We need the sequence defined by AR to strictly increase in the
12825 // unsigned integer domain for the logic below to hold.
12826 return false;
12827
12828 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
12829 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
12830 // If RHS <=u Limit, then there must exist a value V in the sequence
12831 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
12832 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned
12833 // overflow occurs. This limit also implies that a signed comparison
12834 // (in the wide bitwidth) is equivalent to an unsigned comparison as
12835 // the high bits on both sides must be zero.
12836 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
12837 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
12838 Limit = Limit.zext(OuterBitWidth);
12839 return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit);
12840 };
12841 auto Flags = AR->getNoWrapFlags();
12842 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
12843 Flags = setFlags(Flags, SCEV::FlagNUW);
12844
12845 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
12846 if (AR->hasNoUnsignedWrap()) {
12847 // Emulate what getZeroExtendExpr would have done during construction
12848 // if we'd been able to infer the fact just above at that time.
12849 const SCEV *Step = AR->getStepRecurrence(*this);
12850 Type *Ty = ZExt->getType();
12851 auto *S = getAddRecExpr(
12852 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0),
12853 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
12854 IV = dyn_cast<SCEVAddRecExpr>(S);
12855 }
12856 }
12857 }
12858 }
12859
12860
12861 if (!IV && AllowPredicates) {
12862 // Try to make this an AddRec using runtime tests, in the first X
12863 // iterations of this loop, where X is the SCEV expression found by the
12864 // algorithm below.
12865 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
12866 PredicatedIV = true;
12867 }
12868
12869 // Avoid weird loops
12870 if (!IV || IV->getLoop() != L || !IV->isAffine())
12871 return getCouldNotCompute();
12872
12873 // A precondition of this method is that the condition being analyzed
12874 // reaches an exiting branch which dominates the latch. Given that, we can
12875 // assume that an increment which violates the nowrap specification and
12876 // produces poison must cause undefined behavior when the resulting poison
12877 // value is branched upon and thus we can conclude that the backedge is
12878 // taken no more often than would be required to produce that poison value.
12879 // Note that a well defined loop can exit on the iteration which violates
12880 // the nowrap specification if there is another exit (either explicit or
12881 // implicit/exceptional) which causes the loop to execute before the
12882 // exiting instruction we're analyzing would trigger UB.
12883 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
12884 bool NoWrap = ControlsOnlyExit && IV->getNoWrapFlags(WrapType);
12885 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
12886
12887 const SCEV *Stride = IV->getStepRecurrence(*this);
12888
12889 bool PositiveStride = isKnownPositive(Stride);
12890
12891 // Avoid negative or zero stride values.
12892 if (!PositiveStride) {
12893 // We can compute the correct backedge taken count for loops with unknown
12894 // strides if we can prove that the loop is not an infinite loop with side
12895 // effects. Here's the loop structure we are trying to handle -
12896 //
12897 // i = start
12898 // do {
12899 // A[i] = i;
12900 // i += s;
12901 // } while (i < end);
12902 //
12903 // The backedge taken count for such loops is evaluated as -
12904 // (max(end, start + stride) - start - 1) /u stride
12905 //
12906 // The additional preconditions that we need to check to prove correctness
12907 // of the above formula is as follows -
12908 //
12909 // a) IV is either nuw or nsw depending upon signedness (indicated by the
12910 // NoWrap flag).
12911 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
12912 // no side effects within the loop)
12913 // c) loop has a single static exit (with no abnormal exits)
12914 //
12915 // Precondition a) implies that if the stride is negative, this is a single
12916 // trip loop. The backedge taken count formula reduces to zero in this case.
12917 //
12918 // Precondition b) and c) combine to imply that if rhs is invariant in L,
12919 // then a zero stride means the backedge can't be taken without executing
12920 // undefined behavior.
12921 //
12922 // The positive stride case is the same as isKnownPositive(Stride) returning
12923 // true (original behavior of the function).
12924 //
12925 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
12926 !loopHasNoAbnormalExits(L))
12927 return getCouldNotCompute();
12928
12929 if (!isKnownNonZero(Stride)) {
12930 // If we have a step of zero, and RHS isn't invariant in L, we don't know
12931 // if it might eventually be greater than start and if so, on which
12932 // iteration. We can't even produce a useful upper bound.
12933 if (!isLoopInvariant(RHS, L))
12934 return getCouldNotCompute();
12935
12936 // We allow a potentially zero stride, but we need to divide by stride
12937 // below. Since the loop can't be infinite and this check must control
12938 // the sole exit, we can infer the exit must be taken on the first
12939 // iteration (e.g. backedge count = 0) if the stride is zero. Given that,
12940 // we know the numerator in the divides below must be zero, so we can
12941 // pick an arbitrary non-zero value for the denominator (e.g. stride)
12942 // and produce the right result.
12943 // FIXME: Handle the case where Stride is poison?
12944 auto wouldZeroStrideBeUB = [&]() {
12945 // Proof by contradiction. Suppose the stride were zero. If we can
12946 // prove that the backedge *is* taken on the first iteration, then since
12947 // we know this condition controls the sole exit, we must have an
12948 // infinite loop. We can't have a (well defined) infinite loop per
12949 // check just above.
12950 // Note: The (Start - Stride) term is used to get the start' term from
12951 // (start' + stride,+,stride). Remember that we only care about the
12952 // result of this expression when stride == 0 at runtime.
12953 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
12954 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
12955 };
12956 if (!wouldZeroStrideBeUB()) {
12957 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
12958 }
12959 }
12960 } else if (!Stride->isOne() && !NoWrap) {
12961 auto isUBOnWrap = [&]() {
12962 // From no-self-wrap, we need to then prove no-(un)signed-wrap. This
12963 // follows trivially from the fact that every (un)signed-wrapped, but
12964 // not self-wrapped value must be LT than the last value before
12965 // (un)signed wrap. Since we know that last value didn't exit, nor
12966 // will any smaller one.
12967 return canAssumeNoSelfWrap(IV);
12968 };
12969
12970 // Avoid proven overflow cases: this will ensure that the backedge taken
12971 // count will not generate any unsigned overflow. Relaxed no-overflow
12972 // conditions exploit NoWrapFlags, allowing to optimize in presence of
12973 // undefined behaviors like the case of C language.
12974 if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap())
12975 return getCouldNotCompute();
12976 }
12977
12978 // On all paths just preceeding, we established the following invariant:
12979 // IV can be assumed not to overflow up to and including the exiting
12980 // iteration. We proved this in one of two ways:
12981 // 1) We can show overflow doesn't occur before the exiting iteration
12982 // 1a) canIVOverflowOnLT, and b) step of one
12983 // 2) We can show that if overflow occurs, the loop must execute UB
12984 // before any possible exit.
12985 // Note that we have not yet proved RHS invariant (in general).
12986
12987 const SCEV *Start = IV->getStart();
12988
12989 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
12990 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
12991 // Use integer-typed versions for actual computation; we can't subtract
12992 // pointers in general.
12993 const SCEV *OrigStart = Start;
12994 const SCEV *OrigRHS = RHS;
12995 if (Start->getType()->isPointerTy()) {
12996 Start = getLosslessPtrToIntExpr(Start);
12997 if (isa<SCEVCouldNotCompute>(Start))
12998 return Start;
12999 }
13000 if (RHS->getType()->isPointerTy()) {
13001 RHS = getLosslessPtrToIntExpr(RHS);
13002 if (isa<SCEVCouldNotCompute>(RHS))
13003 return RHS;
13004 }
13005
13006 const SCEV *End = nullptr, *BECount = nullptr,
13007 *BECountIfBackedgeTaken = nullptr;
13008 if (!isLoopInvariant(RHS, L)) {
13009 const auto *RHSAddRec = dyn_cast<SCEVAddRecExpr>(RHS);
13010 if (PositiveStride && RHSAddRec != nullptr && RHSAddRec->getLoop() == L &&
13011 RHSAddRec->getNoWrapFlags()) {
13012 // The structure of loop we are trying to calculate backedge count of:
13013 //
13014 // left = left_start
13015 // right = right_start
13016 //
13017 // while(left < right){
13018 // ... do something here ...
13019 // left += s1; // stride of left is s1 (s1 > 0)
13020 // right += s2; // stride of right is s2 (s2 < 0)
13021 // }
13022 //
13023
13024 const SCEV *RHSStart = RHSAddRec->getStart();
13025 const SCEV *RHSStride = RHSAddRec->getStepRecurrence(*this);
13026
13027 // If Stride - RHSStride is positive and does not overflow, we can write
13028 // backedge count as ->
13029 // ceil((End - Start) /u (Stride - RHSStride))
13030 // Where, End = max(RHSStart, Start)
13031
13032 // Check if RHSStride < 0 and Stride - RHSStride will not overflow.
13033 if (isKnownNegative(RHSStride) &&
13034 willNotOverflow(Instruction::Sub, /*Signed=*/true, Stride,
13035 RHSStride)) {
13036
13037 const SCEV *Denominator = getMinusSCEV(Stride, RHSStride);
13038 if (isKnownPositive(Denominator)) {
13039 End = IsSigned ? getSMaxExpr(RHSStart, Start)
13040 : getUMaxExpr(RHSStart, Start);
13041
13042 // We can do this because End >= Start, as End = max(RHSStart, Start)
13043 const SCEV *Delta = getMinusSCEV(End, Start);
13044
13045 BECount = getUDivCeilSCEV(Delta, Denominator);
13046 BECountIfBackedgeTaken =
13047 getUDivCeilSCEV(getMinusSCEV(RHSStart, Start), Denominator);
13048 }
13049 }
13050 }
13051 if (BECount == nullptr) {
13052 // If we cannot calculate ExactBECount, we can calculate the MaxBECount,
13053 // given the start, stride and max value for the end bound of the
13054 // loop (RHS), and the fact that IV does not overflow (which is
13055 // checked above).
13056 const SCEV *MaxBECount = computeMaxBECountForLT(
13057 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
13058 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
13059 MaxBECount, false /*MaxOrZero*/, Predicates);
13060 }
13061 } else {
13062 // We use the expression (max(End,Start)-Start)/Stride to describe the
13063 // backedge count, as if the backedge is taken at least once
13064 // max(End,Start) is End and so the result is as above, and if not
13065 // max(End,Start) is Start so we get a backedge count of zero.
13066 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
13067 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!");
13068 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
13069 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
13070 // Can we prove (max(RHS,Start) > Start - Stride?
13071 if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) &&
13072 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
13073 // In this case, we can use a refined formula for computing backedge
13074 // taken count. The general formula remains:
13075 // "End-Start /uceiling Stride" where "End = max(RHS,Start)"
13076 // We want to use the alternate formula:
13077 // "((End - 1) - (Start - Stride)) /u Stride"
13078 // Let's do a quick case analysis to show these are equivalent under
13079 // our precondition that max(RHS,Start) > Start - Stride.
13080 // * For RHS <= Start, the backedge-taken count must be zero.
13081 // "((End - 1) - (Start - Stride)) /u Stride" reduces to
13082 // "((Start - 1) - (Start - Stride)) /u Stride" which simplies to
13083 // "Stride - 1 /u Stride" which is indeed zero for all non-zero values
13084 // of Stride. For 0 stride, we've use umin(1,Stride) above,
13085 // reducing this to the stride of 1 case.
13086 // * For RHS >= Start, the backedge count must be "RHS-Start /uceil
13087 // Stride".
13088 // "((End - 1) - (Start - Stride)) /u Stride" reduces to
13089 // "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to
13090 // "((RHS - (Start - Stride) - 1) /u Stride".
13091 // Our preconditions trivially imply no overflow in that form.
13092 const SCEV *MinusOne = getMinusOne(Stride->getType());
13093 const SCEV *Numerator =
13094 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
13095 BECount = getUDivExpr(Numerator, Stride);
13096 }
13097
13098 if (!BECount) {
13099 auto canProveRHSGreaterThanEqualStart = [&]() {
13100 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
13101 const SCEV *GuardedRHS = applyLoopGuards(OrigRHS, L);
13102 const SCEV *GuardedStart = applyLoopGuards(OrigStart, L);
13103
13104 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart) ||
13105 isKnownPredicate(CondGE, GuardedRHS, GuardedStart))
13106 return true;
13107
13108 // (RHS > Start - 1) implies RHS >= Start.
13109 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
13110 // "Start - 1" doesn't overflow.
13111 // * For signed comparison, if Start - 1 does overflow, it's equal
13112 // to INT_MAX, and "RHS >s INT_MAX" is trivially false.
13113 // * For unsigned comparison, if Start - 1 does overflow, it's equal
13114 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
13115 //
13116 // FIXME: Should isLoopEntryGuardedByCond do this for us?
13117 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13118 auto *StartMinusOne =
13119 getAddExpr(OrigStart, getMinusOne(OrigStart->getType()));
13120 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
13121 };
13122
13123 // If we know that RHS >= Start in the context of loop, then we know
13124 // that max(RHS, Start) = RHS at this point.
13125 if (canProveRHSGreaterThanEqualStart()) {
13126 End = RHS;
13127 } else {
13128 // If RHS < Start, the backedge will be taken zero times. So in
13129 // general, we can write the backedge-taken count as:
13130 //
13131 // RHS >= Start ? ceil(RHS - Start) / Stride : 0
13132 //
13133 // We convert it to the following to make it more convenient for SCEV:
13134 //
13135 // ceil(max(RHS, Start) - Start) / Stride
13136 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
13137
13138 // See what would happen if we assume the backedge is taken. This is
13139 // used to compute MaxBECount.
13140 BECountIfBackedgeTaken =
13141 getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
13142 }
13143
13144 // At this point, we know:
13145 //
13146 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
13147 // 2. The index variable doesn't overflow.
13148 //
13149 // Therefore, we know N exists such that
13150 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
13151 // doesn't overflow.
13152 //
13153 // Using this information, try to prove whether the addition in
13154 // "(Start - End) + (Stride - 1)" has unsigned overflow.
13155 const SCEV *One = getOne(Stride->getType());
13156 bool MayAddOverflow = [&] {
13157 if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) {
13158 if (StrideC->getAPInt().isPowerOf2()) {
13159 // Suppose Stride is a power of two, and Start/End are unsigned
13160 // integers. Let UMAX be the largest representable unsigned
13161 // integer.
13162 //
13163 // By the preconditions of this function, we know
13164 // "(Start + Stride * N) >= End", and this doesn't overflow.
13165 // As a formula:
13166 //
13167 // End <= (Start + Stride * N) <= UMAX
13168 //
13169 // Subtracting Start from all the terms:
13170 //
13171 // End - Start <= Stride * N <= UMAX - Start
13172 //
13173 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore:
13174 //
13175 // End - Start <= Stride * N <= UMAX
13176 //
13177 // Stride * N is a multiple of Stride. Therefore,
13178 //
13179 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
13180 //
13181 // Since Stride is a power of two, UMAX + 1 is divisible by
13182 // Stride. Therefore, UMAX mod Stride == Stride - 1. So we can
13183 // write:
13184 //
13185 // End - Start <= Stride * N <= UMAX - Stride - 1
13186 //
13187 // Dropping the middle term:
13188 //
13189 // End - Start <= UMAX - Stride - 1
13190 //
13191 // Adding Stride - 1 to both sides:
13192 //
13193 // (End - Start) + (Stride - 1) <= UMAX
13194 //
13195 // In other words, the addition doesn't have unsigned overflow.
13196 //
13197 // A similar proof works if we treat Start/End as signed values.
13198 // Just rewrite steps before "End - Start <= Stride * N <= UMAX"
13199 // to use signed max instead of unsigned max. Note that we're
13200 // trying to prove a lack of unsigned overflow in either case.
13201 return false;
13202 }
13203 }
13204 if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
13205 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End
13206 // - 1. If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1
13207 // <u End. If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End -
13208 // 1 <s End.
13209 //
13210 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 ==
13211 // End.
13212 return false;
13213 }
13214 return true;
13215 }();
13216
13217 const SCEV *Delta = getMinusSCEV(End, Start);
13218 if (!MayAddOverflow) {
13219 // floor((D + (S - 1)) / S)
13220 // We prefer this formulation if it's legal because it's fewer
13221 // operations.
13222 BECount =
13223 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13224 } else {
13225 BECount = getUDivCeilSCEV(Delta, Stride);
13226 }
13227 }
13228 }
13229
13230 const SCEV *ConstantMaxBECount;
13231 bool MaxOrZero = false;
13232 if (isa<SCEVConstant>(BECount)) {
13233 ConstantMaxBECount = BECount;
13234 } else if (BECountIfBackedgeTaken &&
13235 isa<SCEVConstant>(BECountIfBackedgeTaken)) {
13236 // If we know exactly how many times the backedge will be taken if it's
13237 // taken at least once, then the backedge count will either be that or
13238 // zero.
13239 ConstantMaxBECount = BECountIfBackedgeTaken;
13240 MaxOrZero = true;
13241 } else {
13242 ConstantMaxBECount = computeMaxBECountForLT(
13243 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
13244 }
13245
13246 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
13247 !isa<SCEVCouldNotCompute>(BECount))
13248 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
13249
13250 const SCEV *SymbolicMaxBECount =
13251 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13252 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
13253 Predicates);
13254 }
13255
howManyGreaterThans(const SCEV * LHS,const SCEV * RHS,const Loop * L,bool IsSigned,bool ControlsOnlyExit,bool AllowPredicates)13256 ScalarEvolution::ExitLimit ScalarEvolution::howManyGreaterThans(
13257 const SCEV *LHS, const SCEV *RHS, const Loop *L, bool IsSigned,
13258 bool ControlsOnlyExit, bool AllowPredicates) {
13259 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
13260 // We handle only IV > Invariant
13261 if (!isLoopInvariant(RHS, L))
13262 return getCouldNotCompute();
13263
13264 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
13265 if (!IV && AllowPredicates)
13266 // Try to make this an AddRec using runtime tests, in the first X
13267 // iterations of this loop, where X is the SCEV expression found by the
13268 // algorithm below.
13269 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13270
13271 // Avoid weird loops
13272 if (!IV || IV->getLoop() != L || !IV->isAffine())
13273 return getCouldNotCompute();
13274
13275 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13276 bool NoWrap = ControlsOnlyExit && IV->getNoWrapFlags(WrapType);
13277 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13278
13279 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
13280
13281 // Avoid negative or zero stride values
13282 if (!isKnownPositive(Stride))
13283 return getCouldNotCompute();
13284
13285 // Avoid proven overflow cases: this will ensure that the backedge taken count
13286 // will not generate any unsigned overflow. Relaxed no-overflow conditions
13287 // exploit NoWrapFlags, allowing to optimize in presence of undefined
13288 // behaviors like the case of C language.
13289 if (!Stride->isOne() && !NoWrap)
13290 if (canIVOverflowOnGT(RHS, Stride, IsSigned))
13291 return getCouldNotCompute();
13292
13293 const SCEV *Start = IV->getStart();
13294 const SCEV *End = RHS;
13295 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
13296 // If we know that Start >= RHS in the context of loop, then we know that
13297 // min(RHS, Start) = RHS at this point.
13298 if (isLoopEntryGuardedByCond(
13299 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
13300 End = RHS;
13301 else
13302 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
13303 }
13304
13305 if (Start->getType()->isPointerTy()) {
13306 Start = getLosslessPtrToIntExpr(Start);
13307 if (isa<SCEVCouldNotCompute>(Start))
13308 return Start;
13309 }
13310 if (End->getType()->isPointerTy()) {
13311 End = getLosslessPtrToIntExpr(End);
13312 if (isa<SCEVCouldNotCompute>(End))
13313 return End;
13314 }
13315
13316 // Compute ((Start - End) + (Stride - 1)) / Stride.
13317 // FIXME: This can overflow. Holding off on fixing this for now;
13318 // howManyGreaterThans will hopefully be gone soon.
13319 const SCEV *One = getOne(Stride->getType());
13320 const SCEV *BECount = getUDivExpr(
13321 getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride);
13322
13323 APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
13324 : getUnsignedRangeMax(Start);
13325
13326 APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
13327 : getUnsignedRangeMin(Stride);
13328
13329 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
13330 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
13331 : APInt::getMinValue(BitWidth) + (MinStride - 1);
13332
13333 // Although End can be a MIN expression we estimate MinEnd considering only
13334 // the case End = RHS. This is safe because in the other case (Start - End)
13335 // is zero, leading to a zero maximum backedge taken count.
13336 APInt MinEnd =
13337 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
13338 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
13339
13340 const SCEV *ConstantMaxBECount =
13341 isa<SCEVConstant>(BECount)
13342 ? BECount
13343 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd),
13344 getConstant(MinStride));
13345
13346 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount))
13347 ConstantMaxBECount = BECount;
13348 const SCEV *SymbolicMaxBECount =
13349 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13350
13351 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
13352 Predicates);
13353 }
13354
getNumIterationsInRange(const ConstantRange & Range,ScalarEvolution & SE) const13355 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
13356 ScalarEvolution &SE) const {
13357 if (Range.isFullSet()) // Infinite loop.
13358 return SE.getCouldNotCompute();
13359
13360 // If the start is a non-zero constant, shift the range to simplify things.
13361 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
13362 if (!SC->getValue()->isZero()) {
13363 SmallVector<const SCEV *, 4> Operands(operands());
13364 Operands[0] = SE.getZero(SC->getType());
13365 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
13366 getNoWrapFlags(FlagNW));
13367 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
13368 return ShiftedAddRec->getNumIterationsInRange(
13369 Range.subtract(SC->getAPInt()), SE);
13370 // This is strange and shouldn't happen.
13371 return SE.getCouldNotCompute();
13372 }
13373
13374 // The only time we can solve this is when we have all constant indices.
13375 // Otherwise, we cannot determine the overflow conditions.
13376 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
13377 return SE.getCouldNotCompute();
13378
13379 // Okay at this point we know that all elements of the chrec are constants and
13380 // that the start element is zero.
13381
13382 // First check to see if the range contains zero. If not, the first
13383 // iteration exits.
13384 unsigned BitWidth = SE.getTypeSizeInBits(getType());
13385 if (!Range.contains(APInt(BitWidth, 0)))
13386 return SE.getZero(getType());
13387
13388 if (isAffine()) {
13389 // If this is an affine expression then we have this situation:
13390 // Solve {0,+,A} in Range === Ax in Range
13391
13392 // We know that zero is in the range. If A is positive then we know that
13393 // the upper value of the range must be the first possible exit value.
13394 // If A is negative then the lower of the range is the last possible loop
13395 // value. Also note that we already checked for a full range.
13396 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
13397 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
13398
13399 // The exit value should be (End+A)/A.
13400 APInt ExitVal = (End + A).udiv(A);
13401 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
13402
13403 // Evaluate at the exit value. If we really did fall out of the valid
13404 // range, then we computed our trip count, otherwise wrap around or other
13405 // things must have happened.
13406 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
13407 if (Range.contains(Val->getValue()))
13408 return SE.getCouldNotCompute(); // Something strange happened
13409
13410 // Ensure that the previous value is in the range.
13411 assert(Range.contains(
13412 EvaluateConstantChrecAtConstant(this,
13413 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
13414 "Linear scev computation is off in a bad way!");
13415 return SE.getConstant(ExitValue);
13416 }
13417
13418 if (isQuadratic()) {
13419 if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
13420 return SE.getConstant(*S);
13421 }
13422
13423 return SE.getCouldNotCompute();
13424 }
13425
13426 const SCEVAddRecExpr *
getPostIncExpr(ScalarEvolution & SE) const13427 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
13428 assert(getNumOperands() > 1 && "AddRec with zero step?");
13429 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
13430 // but in this case we cannot guarantee that the value returned will be an
13431 // AddRec because SCEV does not have a fixed point where it stops
13432 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
13433 // may happen if we reach arithmetic depth limit while simplifying. So we
13434 // construct the returned value explicitly.
13435 SmallVector<const SCEV *, 3> Ops;
13436 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
13437 // (this + Step) is {A+B,+,B+C,+...,+,N}.
13438 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
13439 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
13440 // We know that the last operand is not a constant zero (otherwise it would
13441 // have been popped out earlier). This guarantees us that if the result has
13442 // the same last operand, then it will also not be popped out, meaning that
13443 // the returned value will be an AddRec.
13444 const SCEV *Last = getOperand(getNumOperands() - 1);
13445 assert(!Last->isZero() && "Recurrency with zero step?");
13446 Ops.push_back(Last);
13447 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
13448 SCEV::FlagAnyWrap));
13449 }
13450
13451 // Return true when S contains at least an undef value.
containsUndefs(const SCEV * S) const13452 bool ScalarEvolution::containsUndefs(const SCEV *S) const {
13453 return SCEVExprContains(S, [](const SCEV *S) {
13454 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
13455 return isa<UndefValue>(SU->getValue());
13456 return false;
13457 });
13458 }
13459
13460 // Return true when S contains a value that is a nullptr.
containsErasedValue(const SCEV * S) const13461 bool ScalarEvolution::containsErasedValue(const SCEV *S) const {
13462 return SCEVExprContains(S, [](const SCEV *S) {
13463 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
13464 return SU->getValue() == nullptr;
13465 return false;
13466 });
13467 }
13468
13469 /// Return the size of an element read or written by Inst.
getElementSize(Instruction * Inst)13470 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
13471 Type *Ty;
13472 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
13473 Ty = Store->getValueOperand()->getType();
13474 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
13475 Ty = Load->getType();
13476 else
13477 return nullptr;
13478
13479 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
13480 return getSizeOfExpr(ETy, Ty);
13481 }
13482
13483 //===----------------------------------------------------------------------===//
13484 // SCEVCallbackVH Class Implementation
13485 //===----------------------------------------------------------------------===//
13486
deleted()13487 void ScalarEvolution::SCEVCallbackVH::deleted() {
13488 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
13489 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
13490 SE->ConstantEvolutionLoopExitValue.erase(PN);
13491 SE->eraseValueFromMap(getValPtr());
13492 // this now dangles!
13493 }
13494
allUsesReplacedWith(Value * V)13495 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
13496 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
13497
13498 // Forget all the expressions associated with users of the old value,
13499 // so that future queries will recompute the expressions using the new
13500 // value.
13501 SE->forgetValue(getValPtr());
13502 // this now dangles!
13503 }
13504
SCEVCallbackVH(Value * V,ScalarEvolution * se)13505 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
13506 : CallbackVH(V), SE(se) {}
13507
13508 //===----------------------------------------------------------------------===//
13509 // ScalarEvolution Class Implementation
13510 //===----------------------------------------------------------------------===//
13511
ScalarEvolution(Function & F,TargetLibraryInfo & TLI,AssumptionCache & AC,DominatorTree & DT,LoopInfo & LI)13512 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
13513 AssumptionCache &AC, DominatorTree &DT,
13514 LoopInfo &LI)
13515 : F(F), DL(F.getDataLayout()), TLI(TLI), AC(AC), DT(DT), LI(LI),
13516 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
13517 LoopDispositions(64), BlockDispositions(64) {
13518 // To use guards for proving predicates, we need to scan every instruction in
13519 // relevant basic blocks, and not just terminators. Doing this is a waste of
13520 // time if the IR does not actually contain any calls to
13521 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
13522 //
13523 // This pessimizes the case where a pass that preserves ScalarEvolution wants
13524 // to _add_ guards to the module when there weren't any before, and wants
13525 // ScalarEvolution to optimize based on those guards. For now we prefer to be
13526 // efficient in lieu of being smart in that rather obscure case.
13527
13528 auto *GuardDecl = F.getParent()->getFunction(
13529 Intrinsic::getName(Intrinsic::experimental_guard));
13530 HasGuards = GuardDecl && !GuardDecl->use_empty();
13531 }
13532
ScalarEvolution(ScalarEvolution && Arg)13533 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
13534 : F(Arg.F), DL(Arg.DL), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC),
13535 DT(Arg.DT), LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
13536 ValueExprMap(std::move(Arg.ValueExprMap)),
13537 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
13538 PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
13539 PendingMerges(std::move(Arg.PendingMerges)),
13540 ConstantMultipleCache(std::move(Arg.ConstantMultipleCache)),
13541 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
13542 PredicatedBackedgeTakenCounts(
13543 std::move(Arg.PredicatedBackedgeTakenCounts)),
13544 BECountUsers(std::move(Arg.BECountUsers)),
13545 ConstantEvolutionLoopExitValue(
13546 std::move(Arg.ConstantEvolutionLoopExitValue)),
13547 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
13548 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
13549 LoopDispositions(std::move(Arg.LoopDispositions)),
13550 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
13551 BlockDispositions(std::move(Arg.BlockDispositions)),
13552 SCEVUsers(std::move(Arg.SCEVUsers)),
13553 UnsignedRanges(std::move(Arg.UnsignedRanges)),
13554 SignedRanges(std::move(Arg.SignedRanges)),
13555 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
13556 UniquePreds(std::move(Arg.UniquePreds)),
13557 SCEVAllocator(std::move(Arg.SCEVAllocator)),
13558 LoopUsers(std::move(Arg.LoopUsers)),
13559 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
13560 FirstUnknown(Arg.FirstUnknown) {
13561 Arg.FirstUnknown = nullptr;
13562 }
13563
~ScalarEvolution()13564 ScalarEvolution::~ScalarEvolution() {
13565 // Iterate through all the SCEVUnknown instances and call their
13566 // destructors, so that they release their references to their values.
13567 for (SCEVUnknown *U = FirstUnknown; U;) {
13568 SCEVUnknown *Tmp = U;
13569 U = U->Next;
13570 Tmp->~SCEVUnknown();
13571 }
13572 FirstUnknown = nullptr;
13573
13574 ExprValueMap.clear();
13575 ValueExprMap.clear();
13576 HasRecMap.clear();
13577 BackedgeTakenCounts.clear();
13578 PredicatedBackedgeTakenCounts.clear();
13579
13580 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
13581 assert(PendingPhiRanges.empty() && "getRangeRef garbage");
13582 assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
13583 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
13584 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
13585 }
13586
hasLoopInvariantBackedgeTakenCount(const Loop * L)13587 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
13588 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
13589 }
13590
13591 /// When printing a top-level SCEV for trip counts, it's helpful to include
13592 /// a type for constants which are otherwise hard to disambiguate.
PrintSCEVWithTypeHint(raw_ostream & OS,const SCEV * S)13593 static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV* S) {
13594 if (isa<SCEVConstant>(S))
13595 OS << *S->getType() << " ";
13596 OS << *S;
13597 }
13598
PrintLoopInfo(raw_ostream & OS,ScalarEvolution * SE,const Loop * L)13599 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
13600 const Loop *L) {
13601 // Print all inner loops first
13602 for (Loop *I : *L)
13603 PrintLoopInfo(OS, SE, I);
13604
13605 OS << "Loop ";
13606 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13607 OS << ": ";
13608
13609 SmallVector<BasicBlock *, 8> ExitingBlocks;
13610 L->getExitingBlocks(ExitingBlocks);
13611 if (ExitingBlocks.size() != 1)
13612 OS << "<multiple exits> ";
13613
13614 auto *BTC = SE->getBackedgeTakenCount(L);
13615 if (!isa<SCEVCouldNotCompute>(BTC)) {
13616 OS << "backedge-taken count is ";
13617 PrintSCEVWithTypeHint(OS, BTC);
13618 } else
13619 OS << "Unpredictable backedge-taken count.";
13620 OS << "\n";
13621
13622 if (ExitingBlocks.size() > 1)
13623 for (BasicBlock *ExitingBlock : ExitingBlocks) {
13624 OS << " exit count for " << ExitingBlock->getName() << ": ";
13625 PrintSCEVWithTypeHint(OS, SE->getExitCount(L, ExitingBlock));
13626 OS << "\n";
13627 }
13628
13629 OS << "Loop ";
13630 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13631 OS << ": ";
13632
13633 auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
13634 if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
13635 OS << "constant max backedge-taken count is ";
13636 PrintSCEVWithTypeHint(OS, ConstantBTC);
13637 if (SE->isBackedgeTakenCountMaxOrZero(L))
13638 OS << ", actual taken count either this or zero.";
13639 } else {
13640 OS << "Unpredictable constant max backedge-taken count. ";
13641 }
13642
13643 OS << "\n"
13644 "Loop ";
13645 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13646 OS << ": ";
13647
13648 auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
13649 if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
13650 OS << "symbolic max backedge-taken count is ";
13651 PrintSCEVWithTypeHint(OS, SymbolicBTC);
13652 if (SE->isBackedgeTakenCountMaxOrZero(L))
13653 OS << ", actual taken count either this or zero.";
13654 } else {
13655 OS << "Unpredictable symbolic max backedge-taken count. ";
13656 }
13657 OS << "\n";
13658
13659 if (ExitingBlocks.size() > 1)
13660 for (BasicBlock *ExitingBlock : ExitingBlocks) {
13661 OS << " symbolic max exit count for " << ExitingBlock->getName() << ": ";
13662 auto *ExitBTC = SE->getExitCount(L, ExitingBlock,
13663 ScalarEvolution::SymbolicMaximum);
13664 PrintSCEVWithTypeHint(OS, ExitBTC);
13665 OS << "\n";
13666 }
13667
13668 SmallVector<const SCEVPredicate *, 4> Preds;
13669 auto *PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
13670 if (PBT != BTC || !Preds.empty()) {
13671 OS << "Loop ";
13672 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13673 OS << ": ";
13674 if (!isa<SCEVCouldNotCompute>(PBT)) {
13675 OS << "Predicated backedge-taken count is ";
13676 PrintSCEVWithTypeHint(OS, PBT);
13677 } else
13678 OS << "Unpredictable predicated backedge-taken count.";
13679 OS << "\n";
13680 OS << " Predicates:\n";
13681 for (const auto *P : Preds)
13682 P->print(OS, 4);
13683 }
13684
13685 Preds.clear();
13686 auto *PredSymbolicMax =
13687 SE->getPredicatedSymbolicMaxBackedgeTakenCount(L, Preds);
13688 if (SymbolicBTC != PredSymbolicMax) {
13689 OS << "Loop ";
13690 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13691 OS << ": ";
13692 if (!isa<SCEVCouldNotCompute>(PredSymbolicMax)) {
13693 OS << "Predicated symbolic max backedge-taken count is ";
13694 PrintSCEVWithTypeHint(OS, PredSymbolicMax);
13695 } else
13696 OS << "Unpredictable predicated symbolic max backedge-taken count.";
13697 OS << "\n";
13698 OS << " Predicates:\n";
13699 for (const auto *P : Preds)
13700 P->print(OS, 4);
13701 }
13702
13703 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
13704 OS << "Loop ";
13705 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13706 OS << ": ";
13707 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
13708 }
13709 }
13710
13711 namespace llvm {
operator <<(raw_ostream & OS,ScalarEvolution::LoopDisposition LD)13712 raw_ostream &operator<<(raw_ostream &OS, ScalarEvolution::LoopDisposition LD) {
13713 switch (LD) {
13714 case ScalarEvolution::LoopVariant:
13715 OS << "Variant";
13716 break;
13717 case ScalarEvolution::LoopInvariant:
13718 OS << "Invariant";
13719 break;
13720 case ScalarEvolution::LoopComputable:
13721 OS << "Computable";
13722 break;
13723 }
13724 return OS;
13725 }
13726
operator <<(raw_ostream & OS,ScalarEvolution::BlockDisposition BD)13727 raw_ostream &operator<<(raw_ostream &OS, ScalarEvolution::BlockDisposition BD) {
13728 switch (BD) {
13729 case ScalarEvolution::DoesNotDominateBlock:
13730 OS << "DoesNotDominate";
13731 break;
13732 case ScalarEvolution::DominatesBlock:
13733 OS << "Dominates";
13734 break;
13735 case ScalarEvolution::ProperlyDominatesBlock:
13736 OS << "ProperlyDominates";
13737 break;
13738 }
13739 return OS;
13740 }
13741 } // namespace llvm
13742
print(raw_ostream & OS) const13743 void ScalarEvolution::print(raw_ostream &OS) const {
13744 // ScalarEvolution's implementation of the print method is to print
13745 // out SCEV values of all instructions that are interesting. Doing
13746 // this potentially causes it to create new SCEV objects though,
13747 // which technically conflicts with the const qualifier. This isn't
13748 // observable from outside the class though, so casting away the
13749 // const isn't dangerous.
13750 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
13751
13752 if (ClassifyExpressions) {
13753 OS << "Classifying expressions for: ";
13754 F.printAsOperand(OS, /*PrintType=*/false);
13755 OS << "\n";
13756 for (Instruction &I : instructions(F))
13757 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
13758 OS << I << '\n';
13759 OS << " --> ";
13760 const SCEV *SV = SE.getSCEV(&I);
13761 SV->print(OS);
13762 if (!isa<SCEVCouldNotCompute>(SV)) {
13763 OS << " U: ";
13764 SE.getUnsignedRange(SV).print(OS);
13765 OS << " S: ";
13766 SE.getSignedRange(SV).print(OS);
13767 }
13768
13769 const Loop *L = LI.getLoopFor(I.getParent());
13770
13771 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
13772 if (AtUse != SV) {
13773 OS << " --> ";
13774 AtUse->print(OS);
13775 if (!isa<SCEVCouldNotCompute>(AtUse)) {
13776 OS << " U: ";
13777 SE.getUnsignedRange(AtUse).print(OS);
13778 OS << " S: ";
13779 SE.getSignedRange(AtUse).print(OS);
13780 }
13781 }
13782
13783 if (L) {
13784 OS << "\t\t" "Exits: ";
13785 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
13786 if (!SE.isLoopInvariant(ExitValue, L)) {
13787 OS << "<<Unknown>>";
13788 } else {
13789 OS << *ExitValue;
13790 }
13791
13792 bool First = true;
13793 for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
13794 if (First) {
13795 OS << "\t\t" "LoopDispositions: { ";
13796 First = false;
13797 } else {
13798 OS << ", ";
13799 }
13800
13801 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13802 OS << ": " << SE.getLoopDisposition(SV, Iter);
13803 }
13804
13805 for (const auto *InnerL : depth_first(L)) {
13806 if (InnerL == L)
13807 continue;
13808 if (First) {
13809 OS << "\t\t" "LoopDispositions: { ";
13810 First = false;
13811 } else {
13812 OS << ", ";
13813 }
13814
13815 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13816 OS << ": " << SE.getLoopDisposition(SV, InnerL);
13817 }
13818
13819 OS << " }";
13820 }
13821
13822 OS << "\n";
13823 }
13824 }
13825
13826 OS << "Determining loop execution counts for: ";
13827 F.printAsOperand(OS, /*PrintType=*/false);
13828 OS << "\n";
13829 for (Loop *I : LI)
13830 PrintLoopInfo(OS, &SE, I);
13831 }
13832
13833 ScalarEvolution::LoopDisposition
getLoopDisposition(const SCEV * S,const Loop * L)13834 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
13835 auto &Values = LoopDispositions[S];
13836 for (auto &V : Values) {
13837 if (V.getPointer() == L)
13838 return V.getInt();
13839 }
13840 Values.emplace_back(L, LoopVariant);
13841 LoopDisposition D = computeLoopDisposition(S, L);
13842 auto &Values2 = LoopDispositions[S];
13843 for (auto &V : llvm::reverse(Values2)) {
13844 if (V.getPointer() == L) {
13845 V.setInt(D);
13846 break;
13847 }
13848 }
13849 return D;
13850 }
13851
13852 ScalarEvolution::LoopDisposition
computeLoopDisposition(const SCEV * S,const Loop * L)13853 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
13854 switch (S->getSCEVType()) {
13855 case scConstant:
13856 case scVScale:
13857 return LoopInvariant;
13858 case scAddRecExpr: {
13859 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
13860
13861 // If L is the addrec's loop, it's computable.
13862 if (AR->getLoop() == L)
13863 return LoopComputable;
13864
13865 // Add recurrences are never invariant in the function-body (null loop).
13866 if (!L)
13867 return LoopVariant;
13868
13869 // Everything that is not defined at loop entry is variant.
13870 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
13871 return LoopVariant;
13872 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
13873 " dominate the contained loop's header?");
13874
13875 // This recurrence is invariant w.r.t. L if AR's loop contains L.
13876 if (AR->getLoop()->contains(L))
13877 return LoopInvariant;
13878
13879 // This recurrence is variant w.r.t. L if any of its operands
13880 // are variant.
13881 for (const auto *Op : AR->operands())
13882 if (!isLoopInvariant(Op, L))
13883 return LoopVariant;
13884
13885 // Otherwise it's loop-invariant.
13886 return LoopInvariant;
13887 }
13888 case scTruncate:
13889 case scZeroExtend:
13890 case scSignExtend:
13891 case scPtrToInt:
13892 case scAddExpr:
13893 case scMulExpr:
13894 case scUDivExpr:
13895 case scUMaxExpr:
13896 case scSMaxExpr:
13897 case scUMinExpr:
13898 case scSMinExpr:
13899 case scSequentialUMinExpr: {
13900 bool HasVarying = false;
13901 for (const auto *Op : S->operands()) {
13902 LoopDisposition D = getLoopDisposition(Op, L);
13903 if (D == LoopVariant)
13904 return LoopVariant;
13905 if (D == LoopComputable)
13906 HasVarying = true;
13907 }
13908 return HasVarying ? LoopComputable : LoopInvariant;
13909 }
13910 case scUnknown:
13911 // All non-instruction values are loop invariant. All instructions are loop
13912 // invariant if they are not contained in the specified loop.
13913 // Instructions are never considered invariant in the function body
13914 // (null loop) because they are defined within the "loop".
13915 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
13916 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
13917 return LoopInvariant;
13918 case scCouldNotCompute:
13919 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
13920 }
13921 llvm_unreachable("Unknown SCEV kind!");
13922 }
13923
isLoopInvariant(const SCEV * S,const Loop * L)13924 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
13925 return getLoopDisposition(S, L) == LoopInvariant;
13926 }
13927
hasComputableLoopEvolution(const SCEV * S,const Loop * L)13928 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
13929 return getLoopDisposition(S, L) == LoopComputable;
13930 }
13931
13932 ScalarEvolution::BlockDisposition
getBlockDisposition(const SCEV * S,const BasicBlock * BB)13933 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
13934 auto &Values = BlockDispositions[S];
13935 for (auto &V : Values) {
13936 if (V.getPointer() == BB)
13937 return V.getInt();
13938 }
13939 Values.emplace_back(BB, DoesNotDominateBlock);
13940 BlockDisposition D = computeBlockDisposition(S, BB);
13941 auto &Values2 = BlockDispositions[S];
13942 for (auto &V : llvm::reverse(Values2)) {
13943 if (V.getPointer() == BB) {
13944 V.setInt(D);
13945 break;
13946 }
13947 }
13948 return D;
13949 }
13950
13951 ScalarEvolution::BlockDisposition
computeBlockDisposition(const SCEV * S,const BasicBlock * BB)13952 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
13953 switch (S->getSCEVType()) {
13954 case scConstant:
13955 case scVScale:
13956 return ProperlyDominatesBlock;
13957 case scAddRecExpr: {
13958 // This uses a "dominates" query instead of "properly dominates" query
13959 // to test for proper dominance too, because the instruction which
13960 // produces the addrec's value is a PHI, and a PHI effectively properly
13961 // dominates its entire containing block.
13962 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
13963 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
13964 return DoesNotDominateBlock;
13965
13966 // Fall through into SCEVNAryExpr handling.
13967 [[fallthrough]];
13968 }
13969 case scTruncate:
13970 case scZeroExtend:
13971 case scSignExtend:
13972 case scPtrToInt:
13973 case scAddExpr:
13974 case scMulExpr:
13975 case scUDivExpr:
13976 case scUMaxExpr:
13977 case scSMaxExpr:
13978 case scUMinExpr:
13979 case scSMinExpr:
13980 case scSequentialUMinExpr: {
13981 bool Proper = true;
13982 for (const SCEV *NAryOp : S->operands()) {
13983 BlockDisposition D = getBlockDisposition(NAryOp, BB);
13984 if (D == DoesNotDominateBlock)
13985 return DoesNotDominateBlock;
13986 if (D == DominatesBlock)
13987 Proper = false;
13988 }
13989 return Proper ? ProperlyDominatesBlock : DominatesBlock;
13990 }
13991 case scUnknown:
13992 if (Instruction *I =
13993 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
13994 if (I->getParent() == BB)
13995 return DominatesBlock;
13996 if (DT.properlyDominates(I->getParent(), BB))
13997 return ProperlyDominatesBlock;
13998 return DoesNotDominateBlock;
13999 }
14000 return ProperlyDominatesBlock;
14001 case scCouldNotCompute:
14002 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14003 }
14004 llvm_unreachable("Unknown SCEV kind!");
14005 }
14006
dominates(const SCEV * S,const BasicBlock * BB)14007 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
14008 return getBlockDisposition(S, BB) >= DominatesBlock;
14009 }
14010
properlyDominates(const SCEV * S,const BasicBlock * BB)14011 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
14012 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
14013 }
14014
hasOperand(const SCEV * S,const SCEV * Op) const14015 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
14016 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
14017 }
14018
forgetBackedgeTakenCounts(const Loop * L,bool Predicated)14019 void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
14020 bool Predicated) {
14021 auto &BECounts =
14022 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14023 auto It = BECounts.find(L);
14024 if (It != BECounts.end()) {
14025 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
14026 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14027 if (!isa<SCEVConstant>(S)) {
14028 auto UserIt = BECountUsers.find(S);
14029 assert(UserIt != BECountUsers.end());
14030 UserIt->second.erase({L, Predicated});
14031 }
14032 }
14033 }
14034 BECounts.erase(It);
14035 }
14036 }
14037
forgetMemoizedResults(ArrayRef<const SCEV * > SCEVs)14038 void ScalarEvolution::forgetMemoizedResults(ArrayRef<const SCEV *> SCEVs) {
14039 SmallPtrSet<const SCEV *, 8> ToForget(SCEVs.begin(), SCEVs.end());
14040 SmallVector<const SCEV *, 8> Worklist(ToForget.begin(), ToForget.end());
14041
14042 while (!Worklist.empty()) {
14043 const SCEV *Curr = Worklist.pop_back_val();
14044 auto Users = SCEVUsers.find(Curr);
14045 if (Users != SCEVUsers.end())
14046 for (const auto *User : Users->second)
14047 if (ToForget.insert(User).second)
14048 Worklist.push_back(User);
14049 }
14050
14051 for (const auto *S : ToForget)
14052 forgetMemoizedResultsImpl(S);
14053
14054 for (auto I = PredicatedSCEVRewrites.begin();
14055 I != PredicatedSCEVRewrites.end();) {
14056 std::pair<const SCEV *, const Loop *> Entry = I->first;
14057 if (ToForget.count(Entry.first))
14058 PredicatedSCEVRewrites.erase(I++);
14059 else
14060 ++I;
14061 }
14062 }
14063
forgetMemoizedResultsImpl(const SCEV * S)14064 void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
14065 LoopDispositions.erase(S);
14066 BlockDispositions.erase(S);
14067 UnsignedRanges.erase(S);
14068 SignedRanges.erase(S);
14069 HasRecMap.erase(S);
14070 ConstantMultipleCache.erase(S);
14071
14072 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
14073 UnsignedWrapViaInductionTried.erase(AR);
14074 SignedWrapViaInductionTried.erase(AR);
14075 }
14076
14077 auto ExprIt = ExprValueMap.find(S);
14078 if (ExprIt != ExprValueMap.end()) {
14079 for (Value *V : ExprIt->second) {
14080 auto ValueIt = ValueExprMap.find_as(V);
14081 if (ValueIt != ValueExprMap.end())
14082 ValueExprMap.erase(ValueIt);
14083 }
14084 ExprValueMap.erase(ExprIt);
14085 }
14086
14087 auto ScopeIt = ValuesAtScopes.find(S);
14088 if (ScopeIt != ValuesAtScopes.end()) {
14089 for (const auto &Pair : ScopeIt->second)
14090 if (!isa_and_nonnull<SCEVConstant>(Pair.second))
14091 llvm::erase(ValuesAtScopesUsers[Pair.second],
14092 std::make_pair(Pair.first, S));
14093 ValuesAtScopes.erase(ScopeIt);
14094 }
14095
14096 auto ScopeUserIt = ValuesAtScopesUsers.find(S);
14097 if (ScopeUserIt != ValuesAtScopesUsers.end()) {
14098 for (const auto &Pair : ScopeUserIt->second)
14099 llvm::erase(ValuesAtScopes[Pair.second], std::make_pair(Pair.first, S));
14100 ValuesAtScopesUsers.erase(ScopeUserIt);
14101 }
14102
14103 auto BEUsersIt = BECountUsers.find(S);
14104 if (BEUsersIt != BECountUsers.end()) {
14105 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
14106 auto Copy = BEUsersIt->second;
14107 for (const auto &Pair : Copy)
14108 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
14109 BECountUsers.erase(BEUsersIt);
14110 }
14111
14112 auto FoldUser = FoldCacheUser.find(S);
14113 if (FoldUser != FoldCacheUser.end())
14114 for (auto &KV : FoldUser->second)
14115 FoldCache.erase(KV);
14116 FoldCacheUser.erase(S);
14117 }
14118
14119 void
getUsedLoops(const SCEV * S,SmallPtrSetImpl<const Loop * > & LoopsUsed)14120 ScalarEvolution::getUsedLoops(const SCEV *S,
14121 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
14122 struct FindUsedLoops {
14123 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
14124 : LoopsUsed(LoopsUsed) {}
14125 SmallPtrSetImpl<const Loop *> &LoopsUsed;
14126 bool follow(const SCEV *S) {
14127 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
14128 LoopsUsed.insert(AR->getLoop());
14129 return true;
14130 }
14131
14132 bool isDone() const { return false; }
14133 };
14134
14135 FindUsedLoops F(LoopsUsed);
14136 SCEVTraversal<FindUsedLoops>(F).visitAll(S);
14137 }
14138
getReachableBlocks(SmallPtrSetImpl<BasicBlock * > & Reachable,Function & F)14139 void ScalarEvolution::getReachableBlocks(
14140 SmallPtrSetImpl<BasicBlock *> &Reachable, Function &F) {
14141 SmallVector<BasicBlock *> Worklist;
14142 Worklist.push_back(&F.getEntryBlock());
14143 while (!Worklist.empty()) {
14144 BasicBlock *BB = Worklist.pop_back_val();
14145 if (!Reachable.insert(BB).second)
14146 continue;
14147
14148 Value *Cond;
14149 BasicBlock *TrueBB, *FalseBB;
14150 if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
14151 m_BasicBlock(FalseBB)))) {
14152 if (auto *C = dyn_cast<ConstantInt>(Cond)) {
14153 Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
14154 continue;
14155 }
14156
14157 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14158 const SCEV *L = getSCEV(Cmp->getOperand(0));
14159 const SCEV *R = getSCEV(Cmp->getOperand(1));
14160 if (isKnownPredicateViaConstantRanges(Cmp->getPredicate(), L, R)) {
14161 Worklist.push_back(TrueBB);
14162 continue;
14163 }
14164 if (isKnownPredicateViaConstantRanges(Cmp->getInversePredicate(), L,
14165 R)) {
14166 Worklist.push_back(FalseBB);
14167 continue;
14168 }
14169 }
14170 }
14171
14172 append_range(Worklist, successors(BB));
14173 }
14174 }
14175
verify() const14176 void ScalarEvolution::verify() const {
14177 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14178 ScalarEvolution SE2(F, TLI, AC, DT, LI);
14179
14180 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
14181
14182 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
14183 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
14184 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
14185
14186 const SCEV *visitConstant(const SCEVConstant *Constant) {
14187 return SE.getConstant(Constant->getAPInt());
14188 }
14189
14190 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14191 return SE.getUnknown(Expr->getValue());
14192 }
14193
14194 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
14195 return SE.getCouldNotCompute();
14196 }
14197 };
14198
14199 SCEVMapper SCM(SE2);
14200 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
14201 SE2.getReachableBlocks(ReachableBlocks, F);
14202
14203 auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
14204 if (containsUndefs(Old) || containsUndefs(New)) {
14205 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
14206 // not propagate undef aggressively). This means we can (and do) fail
14207 // verification in cases where a transform makes a value go from "undef"
14208 // to "undef+1" (say). The transform is fine, since in both cases the
14209 // result is "undef", but SCEV thinks the value increased by 1.
14210 return nullptr;
14211 }
14212
14213 // Unless VerifySCEVStrict is set, we only compare constant deltas.
14214 const SCEV *Delta = SE2.getMinusSCEV(Old, New);
14215 if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
14216 return nullptr;
14217
14218 return Delta;
14219 };
14220
14221 while (!LoopStack.empty()) {
14222 auto *L = LoopStack.pop_back_val();
14223 llvm::append_range(LoopStack, *L);
14224
14225 // Only verify BECounts in reachable loops. For an unreachable loop,
14226 // any BECount is legal.
14227 if (!ReachableBlocks.contains(L->getHeader()))
14228 continue;
14229
14230 // Only verify cached BECounts. Computing new BECounts may change the
14231 // results of subsequent SCEV uses.
14232 auto It = BackedgeTakenCounts.find(L);
14233 if (It == BackedgeTakenCounts.end())
14234 continue;
14235
14236 auto *CurBECount =
14237 SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
14238 auto *NewBECount = SE2.getBackedgeTakenCount(L);
14239
14240 if (CurBECount == SE2.getCouldNotCompute() ||
14241 NewBECount == SE2.getCouldNotCompute()) {
14242 // NB! This situation is legal, but is very suspicious -- whatever pass
14243 // change the loop to make a trip count go from could not compute to
14244 // computable or vice-versa *should have* invalidated SCEV. However, we
14245 // choose not to assert here (for now) since we don't want false
14246 // positives.
14247 continue;
14248 }
14249
14250 if (SE.getTypeSizeInBits(CurBECount->getType()) >
14251 SE.getTypeSizeInBits(NewBECount->getType()))
14252 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
14253 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
14254 SE.getTypeSizeInBits(NewBECount->getType()))
14255 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
14256
14257 const SCEV *Delta = GetDelta(CurBECount, NewBECount);
14258 if (Delta && !Delta->isZero()) {
14259 dbgs() << "Trip Count for " << *L << " Changed!\n";
14260 dbgs() << "Old: " << *CurBECount << "\n";
14261 dbgs() << "New: " << *NewBECount << "\n";
14262 dbgs() << "Delta: " << *Delta << "\n";
14263 std::abort();
14264 }
14265 }
14266
14267 // Collect all valid loops currently in LoopInfo.
14268 SmallPtrSet<Loop *, 32> ValidLoops;
14269 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
14270 while (!Worklist.empty()) {
14271 Loop *L = Worklist.pop_back_val();
14272 if (ValidLoops.insert(L).second)
14273 Worklist.append(L->begin(), L->end());
14274 }
14275 for (const auto &KV : ValueExprMap) {
14276 #ifndef NDEBUG
14277 // Check for SCEV expressions referencing invalid/deleted loops.
14278 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14279 assert(ValidLoops.contains(AR->getLoop()) &&
14280 "AddRec references invalid loop");
14281 }
14282 #endif
14283
14284 // Check that the value is also part of the reverse map.
14285 auto It = ExprValueMap.find(KV.second);
14286 if (It == ExprValueMap.end() || !It->second.contains(KV.first)) {
14287 dbgs() << "Value " << *KV.first
14288 << " is in ValueExprMap but not in ExprValueMap\n";
14289 std::abort();
14290 }
14291
14292 if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
14293 if (!ReachableBlocks.contains(I->getParent()))
14294 continue;
14295 const SCEV *OldSCEV = SCM.visit(KV.second);
14296 const SCEV *NewSCEV = SE2.getSCEV(I);
14297 const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14298 if (Delta && !Delta->isZero()) {
14299 dbgs() << "SCEV for value " << *I << " changed!\n"
14300 << "Old: " << *OldSCEV << "\n"
14301 << "New: " << *NewSCEV << "\n"
14302 << "Delta: " << *Delta << "\n";
14303 std::abort();
14304 }
14305 }
14306 }
14307
14308 for (const auto &KV : ExprValueMap) {
14309 for (Value *V : KV.second) {
14310 auto It = ValueExprMap.find_as(V);
14311 if (It == ValueExprMap.end()) {
14312 dbgs() << "Value " << *V
14313 << " is in ExprValueMap but not in ValueExprMap\n";
14314 std::abort();
14315 }
14316 if (It->second != KV.first) {
14317 dbgs() << "Value " << *V << " mapped to " << *It->second
14318 << " rather than " << *KV.first << "\n";
14319 std::abort();
14320 }
14321 }
14322 }
14323
14324 // Verify integrity of SCEV users.
14325 for (const auto &S : UniqueSCEVs) {
14326 for (const auto *Op : S.operands()) {
14327 // We do not store dependencies of constants.
14328 if (isa<SCEVConstant>(Op))
14329 continue;
14330 auto It = SCEVUsers.find(Op);
14331 if (It != SCEVUsers.end() && It->second.count(&S))
14332 continue;
14333 dbgs() << "Use of operand " << *Op << " by user " << S
14334 << " is not being tracked!\n";
14335 std::abort();
14336 }
14337 }
14338
14339 // Verify integrity of ValuesAtScopes users.
14340 for (const auto &ValueAndVec : ValuesAtScopes) {
14341 const SCEV *Value = ValueAndVec.first;
14342 for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
14343 const Loop *L = LoopAndValueAtScope.first;
14344 const SCEV *ValueAtScope = LoopAndValueAtScope.second;
14345 if (!isa<SCEVConstant>(ValueAtScope)) {
14346 auto It = ValuesAtScopesUsers.find(ValueAtScope);
14347 if (It != ValuesAtScopesUsers.end() &&
14348 is_contained(It->second, std::make_pair(L, Value)))
14349 continue;
14350 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14351 << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
14352 std::abort();
14353 }
14354 }
14355 }
14356
14357 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
14358 const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
14359 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
14360 const Loop *L = LoopAndValue.first;
14361 const SCEV *Value = LoopAndValue.second;
14362 assert(!isa<SCEVConstant>(Value));
14363 auto It = ValuesAtScopes.find(Value);
14364 if (It != ValuesAtScopes.end() &&
14365 is_contained(It->second, std::make_pair(L, ValueAtScope)))
14366 continue;
14367 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14368 << *ValueAtScope << " missing in ValuesAtScopes\n";
14369 std::abort();
14370 }
14371 }
14372
14373 // Verify integrity of BECountUsers.
14374 auto VerifyBECountUsers = [&](bool Predicated) {
14375 auto &BECounts =
14376 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14377 for (const auto &LoopAndBEInfo : BECounts) {
14378 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
14379 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14380 if (!isa<SCEVConstant>(S)) {
14381 auto UserIt = BECountUsers.find(S);
14382 if (UserIt != BECountUsers.end() &&
14383 UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
14384 continue;
14385 dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
14386 << " missing from BECountUsers\n";
14387 std::abort();
14388 }
14389 }
14390 }
14391 }
14392 };
14393 VerifyBECountUsers(/* Predicated */ false);
14394 VerifyBECountUsers(/* Predicated */ true);
14395
14396 // Verify intergity of loop disposition cache.
14397 for (auto &[S, Values] : LoopDispositions) {
14398 for (auto [Loop, CachedDisposition] : Values) {
14399 const auto RecomputedDisposition = SE2.getLoopDisposition(S, Loop);
14400 if (CachedDisposition != RecomputedDisposition) {
14401 dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
14402 << " is incorrect: cached " << CachedDisposition << ", actual "
14403 << RecomputedDisposition << "\n";
14404 std::abort();
14405 }
14406 }
14407 }
14408
14409 // Verify integrity of the block disposition cache.
14410 for (auto &[S, Values] : BlockDispositions) {
14411 for (auto [BB, CachedDisposition] : Values) {
14412 const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
14413 if (CachedDisposition != RecomputedDisposition) {
14414 dbgs() << "Cached disposition of " << *S << " for block %"
14415 << BB->getName() << " is incorrect: cached " << CachedDisposition
14416 << ", actual " << RecomputedDisposition << "\n";
14417 std::abort();
14418 }
14419 }
14420 }
14421
14422 // Verify FoldCache/FoldCacheUser caches.
14423 for (auto [FoldID, Expr] : FoldCache) {
14424 auto I = FoldCacheUser.find(Expr);
14425 if (I == FoldCacheUser.end()) {
14426 dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
14427 << "!\n";
14428 std::abort();
14429 }
14430 if (!is_contained(I->second, FoldID)) {
14431 dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
14432 std::abort();
14433 }
14434 }
14435 for (auto [Expr, IDs] : FoldCacheUser) {
14436 for (auto &FoldID : IDs) {
14437 auto I = FoldCache.find(FoldID);
14438 if (I == FoldCache.end()) {
14439 dbgs() << "Missing entry in FoldCache for expression " << *Expr
14440 << "!\n";
14441 std::abort();
14442 }
14443 if (I->second != Expr) {
14444 dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: "
14445 << *I->second << " != " << *Expr << "!\n";
14446 std::abort();
14447 }
14448 }
14449 }
14450
14451 // Verify that ConstantMultipleCache computations are correct. We check that
14452 // cached multiples and recomputed multiples are multiples of each other to
14453 // verify correctness. It is possible that a recomputed multiple is different
14454 // from the cached multiple due to strengthened no wrap flags or changes in
14455 // KnownBits computations.
14456 for (auto [S, Multiple] : ConstantMultipleCache) {
14457 APInt RecomputedMultiple = SE2.getConstantMultiple(S);
14458 if ((Multiple != 0 && RecomputedMultiple != 0 &&
14459 Multiple.urem(RecomputedMultiple) != 0 &&
14460 RecomputedMultiple.urem(Multiple) != 0)) {
14461 dbgs() << "Incorrect cached computation in ConstantMultipleCache for "
14462 << *S << " : Computed " << RecomputedMultiple
14463 << " but cache contains " << Multiple << "!\n";
14464 std::abort();
14465 }
14466 }
14467 }
14468
invalidate(Function & F,const PreservedAnalyses & PA,FunctionAnalysisManager::Invalidator & Inv)14469 bool ScalarEvolution::invalidate(
14470 Function &F, const PreservedAnalyses &PA,
14471 FunctionAnalysisManager::Invalidator &Inv) {
14472 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
14473 // of its dependencies is invalidated.
14474 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
14475 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
14476 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
14477 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
14478 Inv.invalidate<LoopAnalysis>(F, PA);
14479 }
14480
14481 AnalysisKey ScalarEvolutionAnalysis::Key;
14482
run(Function & F,FunctionAnalysisManager & AM)14483 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
14484 FunctionAnalysisManager &AM) {
14485 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
14486 auto &AC = AM.getResult<AssumptionAnalysis>(F);
14487 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
14488 auto &LI = AM.getResult<LoopAnalysis>(F);
14489 return ScalarEvolution(F, TLI, AC, DT, LI);
14490 }
14491
14492 PreservedAnalyses
run(Function & F,FunctionAnalysisManager & AM)14493 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
14494 AM.getResult<ScalarEvolutionAnalysis>(F).verify();
14495 return PreservedAnalyses::all();
14496 }
14497
14498 PreservedAnalyses
run(Function & F,FunctionAnalysisManager & AM)14499 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
14500 // For compatibility with opt's -analyze feature under legacy pass manager
14501 // which was not ported to NPM. This keeps tests using
14502 // update_analyze_test_checks.py working.
14503 OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
14504 << F.getName() << "':\n";
14505 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
14506 return PreservedAnalyses::all();
14507 }
14508
14509 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
14510 "Scalar Evolution Analysis", false, true)
14511 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
14512 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
14513 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
14514 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
14515 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
14516 "Scalar Evolution Analysis", false, true)
14517
14518 char ScalarEvolutionWrapperPass::ID = 0;
14519
ScalarEvolutionWrapperPass()14520 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
14521 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
14522 }
14523
runOnFunction(Function & F)14524 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
14525 SE.reset(new ScalarEvolution(
14526 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
14527 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
14528 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
14529 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
14530 return false;
14531 }
14532
releaseMemory()14533 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
14534
print(raw_ostream & OS,const Module *) const14535 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
14536 SE->print(OS);
14537 }
14538
verifyAnalysis() const14539 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
14540 if (!VerifySCEV)
14541 return;
14542
14543 SE->verify();
14544 }
14545
getAnalysisUsage(AnalysisUsage & AU) const14546 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
14547 AU.setPreservesAll();
14548 AU.addRequiredTransitive<AssumptionCacheTracker>();
14549 AU.addRequiredTransitive<LoopInfoWrapperPass>();
14550 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
14551 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
14552 }
14553
getEqualPredicate(const SCEV * LHS,const SCEV * RHS)14554 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
14555 const SCEV *RHS) {
14556 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
14557 }
14558
14559 const SCEVPredicate *
getComparePredicate(const ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)14560 ScalarEvolution::getComparePredicate(const ICmpInst::Predicate Pred,
14561 const SCEV *LHS, const SCEV *RHS) {
14562 FoldingSetNodeID ID;
14563 assert(LHS->getType() == RHS->getType() &&
14564 "Type mismatch between LHS and RHS");
14565 // Unique this node based on the arguments
14566 ID.AddInteger(SCEVPredicate::P_Compare);
14567 ID.AddInteger(Pred);
14568 ID.AddPointer(LHS);
14569 ID.AddPointer(RHS);
14570 void *IP = nullptr;
14571 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
14572 return S;
14573 SCEVComparePredicate *Eq = new (SCEVAllocator)
14574 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
14575 UniquePreds.InsertNode(Eq, IP);
14576 return Eq;
14577 }
14578
getWrapPredicate(const SCEVAddRecExpr * AR,SCEVWrapPredicate::IncrementWrapFlags AddedFlags)14579 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
14580 const SCEVAddRecExpr *AR,
14581 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
14582 FoldingSetNodeID ID;
14583 // Unique this node based on the arguments
14584 ID.AddInteger(SCEVPredicate::P_Wrap);
14585 ID.AddPointer(AR);
14586 ID.AddInteger(AddedFlags);
14587 void *IP = nullptr;
14588 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
14589 return S;
14590 auto *OF = new (SCEVAllocator)
14591 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
14592 UniquePreds.InsertNode(OF, IP);
14593 return OF;
14594 }
14595
14596 namespace {
14597
14598 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
14599 public:
14600
14601 /// Rewrites \p S in the context of a loop L and the SCEV predication
14602 /// infrastructure.
14603 ///
14604 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
14605 /// equivalences present in \p Pred.
14606 ///
14607 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
14608 /// \p NewPreds such that the result will be an AddRecExpr.
rewrite(const SCEV * S,const Loop * L,ScalarEvolution & SE,SmallPtrSetImpl<const SCEVPredicate * > * NewPreds,const SCEVPredicate * Pred)14609 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
14610 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
14611 const SCEVPredicate *Pred) {
14612 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
14613 return Rewriter.visit(S);
14614 }
14615
visitUnknown(const SCEVUnknown * Expr)14616 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14617 if (Pred) {
14618 if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
14619 for (const auto *Pred : U->getPredicates())
14620 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
14621 if (IPred->getLHS() == Expr &&
14622 IPred->getPredicate() == ICmpInst::ICMP_EQ)
14623 return IPred->getRHS();
14624 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
14625 if (IPred->getLHS() == Expr &&
14626 IPred->getPredicate() == ICmpInst::ICMP_EQ)
14627 return IPred->getRHS();
14628 }
14629 }
14630 return convertToAddRecWithPreds(Expr);
14631 }
14632
visitZeroExtendExpr(const SCEVZeroExtendExpr * Expr)14633 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
14634 const SCEV *Operand = visit(Expr->getOperand());
14635 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
14636 if (AR && AR->getLoop() == L && AR->isAffine()) {
14637 // This couldn't be folded because the operand didn't have the nuw
14638 // flag. Add the nusw flag as an assumption that we could make.
14639 const SCEV *Step = AR->getStepRecurrence(SE);
14640 Type *Ty = Expr->getType();
14641 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
14642 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
14643 SE.getSignExtendExpr(Step, Ty), L,
14644 AR->getNoWrapFlags());
14645 }
14646 return SE.getZeroExtendExpr(Operand, Expr->getType());
14647 }
14648
visitSignExtendExpr(const SCEVSignExtendExpr * Expr)14649 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
14650 const SCEV *Operand = visit(Expr->getOperand());
14651 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
14652 if (AR && AR->getLoop() == L && AR->isAffine()) {
14653 // This couldn't be folded because the operand didn't have the nsw
14654 // flag. Add the nssw flag as an assumption that we could make.
14655 const SCEV *Step = AR->getStepRecurrence(SE);
14656 Type *Ty = Expr->getType();
14657 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
14658 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
14659 SE.getSignExtendExpr(Step, Ty), L,
14660 AR->getNoWrapFlags());
14661 }
14662 return SE.getSignExtendExpr(Operand, Expr->getType());
14663 }
14664
14665 private:
SCEVPredicateRewriter(const Loop * L,ScalarEvolution & SE,SmallPtrSetImpl<const SCEVPredicate * > * NewPreds,const SCEVPredicate * Pred)14666 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
14667 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
14668 const SCEVPredicate *Pred)
14669 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
14670
addOverflowAssumption(const SCEVPredicate * P)14671 bool addOverflowAssumption(const SCEVPredicate *P) {
14672 if (!NewPreds) {
14673 // Check if we've already made this assumption.
14674 return Pred && Pred->implies(P);
14675 }
14676 NewPreds->insert(P);
14677 return true;
14678 }
14679
addOverflowAssumption(const SCEVAddRecExpr * AR,SCEVWrapPredicate::IncrementWrapFlags AddedFlags)14680 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
14681 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
14682 auto *A = SE.getWrapPredicate(AR, AddedFlags);
14683 return addOverflowAssumption(A);
14684 }
14685
14686 // If \p Expr represents a PHINode, we try to see if it can be represented
14687 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
14688 // to add this predicate as a runtime overflow check, we return the AddRec.
14689 // If \p Expr does not meet these conditions (is not a PHI node, or we
14690 // couldn't create an AddRec for it, or couldn't add the predicate), we just
14691 // return \p Expr.
convertToAddRecWithPreds(const SCEVUnknown * Expr)14692 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
14693 if (!isa<PHINode>(Expr->getValue()))
14694 return Expr;
14695 std::optional<
14696 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
14697 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
14698 if (!PredicatedRewrite)
14699 return Expr;
14700 for (const auto *P : PredicatedRewrite->second){
14701 // Wrap predicates from outer loops are not supported.
14702 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
14703 if (L != WP->getExpr()->getLoop())
14704 return Expr;
14705 }
14706 if (!addOverflowAssumption(P))
14707 return Expr;
14708 }
14709 return PredicatedRewrite->first;
14710 }
14711
14712 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
14713 const SCEVPredicate *Pred;
14714 const Loop *L;
14715 };
14716
14717 } // end anonymous namespace
14718
14719 const SCEV *
rewriteUsingPredicate(const SCEV * S,const Loop * L,const SCEVPredicate & Preds)14720 ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
14721 const SCEVPredicate &Preds) {
14722 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
14723 }
14724
convertSCEVToAddRecWithPredicates(const SCEV * S,const Loop * L,SmallPtrSetImpl<const SCEVPredicate * > & Preds)14725 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
14726 const SCEV *S, const Loop *L,
14727 SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
14728 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
14729 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
14730 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
14731
14732 if (!AddRec)
14733 return nullptr;
14734
14735 // Since the transformation was successful, we can now transfer the SCEV
14736 // predicates.
14737 for (const auto *P : TransformPreds)
14738 Preds.insert(P);
14739
14740 return AddRec;
14741 }
14742
14743 /// SCEV predicates
SCEVPredicate(const FoldingSetNodeIDRef ID,SCEVPredicateKind Kind)14744 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
14745 SCEVPredicateKind Kind)
14746 : FastID(ID), Kind(Kind) {}
14747
SCEVComparePredicate(const FoldingSetNodeIDRef ID,const ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)14748 SCEVComparePredicate::SCEVComparePredicate(const FoldingSetNodeIDRef ID,
14749 const ICmpInst::Predicate Pred,
14750 const SCEV *LHS, const SCEV *RHS)
14751 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
14752 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
14753 assert(LHS != RHS && "LHS and RHS are the same SCEV");
14754 }
14755
implies(const SCEVPredicate * N) const14756 bool SCEVComparePredicate::implies(const SCEVPredicate *N) const {
14757 const auto *Op = dyn_cast<SCEVComparePredicate>(N);
14758
14759 if (!Op)
14760 return false;
14761
14762 if (Pred != ICmpInst::ICMP_EQ)
14763 return false;
14764
14765 return Op->LHS == LHS && Op->RHS == RHS;
14766 }
14767
isAlwaysTrue() const14768 bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
14769
print(raw_ostream & OS,unsigned Depth) const14770 void SCEVComparePredicate::print(raw_ostream &OS, unsigned Depth) const {
14771 if (Pred == ICmpInst::ICMP_EQ)
14772 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
14773 else
14774 OS.indent(Depth) << "Compare predicate: " << *LHS << " " << Pred << ") "
14775 << *RHS << "\n";
14776
14777 }
14778
SCEVWrapPredicate(const FoldingSetNodeIDRef ID,const SCEVAddRecExpr * AR,IncrementWrapFlags Flags)14779 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
14780 const SCEVAddRecExpr *AR,
14781 IncrementWrapFlags Flags)
14782 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
14783
getExpr() const14784 const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
14785
implies(const SCEVPredicate * N) const14786 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
14787 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
14788
14789 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
14790 }
14791
isAlwaysTrue() const14792 bool SCEVWrapPredicate::isAlwaysTrue() const {
14793 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
14794 IncrementWrapFlags IFlags = Flags;
14795
14796 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
14797 IFlags = clearFlags(IFlags, IncrementNSSW);
14798
14799 return IFlags == IncrementAnyWrap;
14800 }
14801
print(raw_ostream & OS,unsigned Depth) const14802 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
14803 OS.indent(Depth) << *getExpr() << " Added Flags: ";
14804 if (SCEVWrapPredicate::IncrementNUSW & getFlags())
14805 OS << "<nusw>";
14806 if (SCEVWrapPredicate::IncrementNSSW & getFlags())
14807 OS << "<nssw>";
14808 OS << "\n";
14809 }
14810
14811 SCEVWrapPredicate::IncrementWrapFlags
getImpliedFlags(const SCEVAddRecExpr * AR,ScalarEvolution & SE)14812 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
14813 ScalarEvolution &SE) {
14814 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
14815 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
14816
14817 // We can safely transfer the NSW flag as NSSW.
14818 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
14819 ImpliedFlags = IncrementNSSW;
14820
14821 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
14822 // If the increment is positive, the SCEV NUW flag will also imply the
14823 // WrapPredicate NUSW flag.
14824 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
14825 if (Step->getValue()->getValue().isNonNegative())
14826 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
14827 }
14828
14829 return ImpliedFlags;
14830 }
14831
14832 /// Union predicates don't get cached so create a dummy set ID for it.
SCEVUnionPredicate(ArrayRef<const SCEVPredicate * > Preds)14833 SCEVUnionPredicate::SCEVUnionPredicate(ArrayRef<const SCEVPredicate *> Preds)
14834 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {
14835 for (const auto *P : Preds)
14836 add(P);
14837 }
14838
isAlwaysTrue() const14839 bool SCEVUnionPredicate::isAlwaysTrue() const {
14840 return all_of(Preds,
14841 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
14842 }
14843
implies(const SCEVPredicate * N) const14844 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
14845 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
14846 return all_of(Set->Preds,
14847 [this](const SCEVPredicate *I) { return this->implies(I); });
14848
14849 return any_of(Preds,
14850 [N](const SCEVPredicate *I) { return I->implies(N); });
14851 }
14852
print(raw_ostream & OS,unsigned Depth) const14853 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
14854 for (const auto *Pred : Preds)
14855 Pred->print(OS, Depth);
14856 }
14857
add(const SCEVPredicate * N)14858 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
14859 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
14860 for (const auto *Pred : Set->Preds)
14861 add(Pred);
14862 return;
14863 }
14864
14865 // Only add predicate if it is not already implied by this union predicate.
14866 if (!implies(N))
14867 Preds.push_back(N);
14868 }
14869
PredicatedScalarEvolution(ScalarEvolution & SE,Loop & L)14870 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
14871 Loop &L)
14872 : SE(SE), L(L) {
14873 SmallVector<const SCEVPredicate*, 4> Empty;
14874 Preds = std::make_unique<SCEVUnionPredicate>(Empty);
14875 }
14876
registerUser(const SCEV * User,ArrayRef<const SCEV * > Ops)14877 void ScalarEvolution::registerUser(const SCEV *User,
14878 ArrayRef<const SCEV *> Ops) {
14879 for (const auto *Op : Ops)
14880 // We do not expect that forgetting cached data for SCEVConstants will ever
14881 // open any prospects for sharpening or introduce any correctness issues,
14882 // so we don't bother storing their dependencies.
14883 if (!isa<SCEVConstant>(Op))
14884 SCEVUsers[Op].insert(User);
14885 }
14886
getSCEV(Value * V)14887 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
14888 const SCEV *Expr = SE.getSCEV(V);
14889 RewriteEntry &Entry = RewriteMap[Expr];
14890
14891 // If we already have an entry and the version matches, return it.
14892 if (Entry.second && Generation == Entry.first)
14893 return Entry.second;
14894
14895 // We found an entry but it's stale. Rewrite the stale entry
14896 // according to the current predicate.
14897 if (Entry.second)
14898 Expr = Entry.second;
14899
14900 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
14901 Entry = {Generation, NewSCEV};
14902
14903 return NewSCEV;
14904 }
14905
getBackedgeTakenCount()14906 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
14907 if (!BackedgeCount) {
14908 SmallVector<const SCEVPredicate *, 4> Preds;
14909 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
14910 for (const auto *P : Preds)
14911 addPredicate(*P);
14912 }
14913 return BackedgeCount;
14914 }
14915
getSymbolicMaxBackedgeTakenCount()14916 const SCEV *PredicatedScalarEvolution::getSymbolicMaxBackedgeTakenCount() {
14917 if (!SymbolicMaxBackedgeCount) {
14918 SmallVector<const SCEVPredicate *, 4> Preds;
14919 SymbolicMaxBackedgeCount =
14920 SE.getPredicatedSymbolicMaxBackedgeTakenCount(&L, Preds);
14921 for (const auto *P : Preds)
14922 addPredicate(*P);
14923 }
14924 return SymbolicMaxBackedgeCount;
14925 }
14926
addPredicate(const SCEVPredicate & Pred)14927 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
14928 if (Preds->implies(&Pred))
14929 return;
14930
14931 auto &OldPreds = Preds->getPredicates();
14932 SmallVector<const SCEVPredicate*, 4> NewPreds(OldPreds.begin(), OldPreds.end());
14933 NewPreds.push_back(&Pred);
14934 Preds = std::make_unique<SCEVUnionPredicate>(NewPreds);
14935 updateGeneration();
14936 }
14937
getPredicate() const14938 const SCEVPredicate &PredicatedScalarEvolution::getPredicate() const {
14939 return *Preds;
14940 }
14941
updateGeneration()14942 void PredicatedScalarEvolution::updateGeneration() {
14943 // If the generation number wrapped recompute everything.
14944 if (++Generation == 0) {
14945 for (auto &II : RewriteMap) {
14946 const SCEV *Rewritten = II.second.second;
14947 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
14948 }
14949 }
14950 }
14951
setNoOverflow(Value * V,SCEVWrapPredicate::IncrementWrapFlags Flags)14952 void PredicatedScalarEvolution::setNoOverflow(
14953 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
14954 const SCEV *Expr = getSCEV(V);
14955 const auto *AR = cast<SCEVAddRecExpr>(Expr);
14956
14957 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
14958
14959 // Clear the statically implied flags.
14960 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
14961 addPredicate(*SE.getWrapPredicate(AR, Flags));
14962
14963 auto II = FlagsMap.insert({V, Flags});
14964 if (!II.second)
14965 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
14966 }
14967
hasNoOverflow(Value * V,SCEVWrapPredicate::IncrementWrapFlags Flags)14968 bool PredicatedScalarEvolution::hasNoOverflow(
14969 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
14970 const SCEV *Expr = getSCEV(V);
14971 const auto *AR = cast<SCEVAddRecExpr>(Expr);
14972
14973 Flags = SCEVWrapPredicate::clearFlags(
14974 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
14975
14976 auto II = FlagsMap.find(V);
14977
14978 if (II != FlagsMap.end())
14979 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
14980
14981 return Flags == SCEVWrapPredicate::IncrementAnyWrap;
14982 }
14983
getAsAddRec(Value * V)14984 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
14985 const SCEV *Expr = this->getSCEV(V);
14986 SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
14987 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
14988
14989 if (!New)
14990 return nullptr;
14991
14992 for (const auto *P : NewPreds)
14993 addPredicate(*P);
14994
14995 RewriteMap[SE.getSCEV(V)] = {Generation, New};
14996 return New;
14997 }
14998
PredicatedScalarEvolution(const PredicatedScalarEvolution & Init)14999 PredicatedScalarEvolution::PredicatedScalarEvolution(
15000 const PredicatedScalarEvolution &Init)
15001 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
15002 Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates())),
15003 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
15004 for (auto I : Init.FlagsMap)
15005 FlagsMap.insert(I);
15006 }
15007
print(raw_ostream & OS,unsigned Depth) const15008 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
15009 // For each block.
15010 for (auto *BB : L.getBlocks())
15011 for (auto &I : *BB) {
15012 if (!SE.isSCEVable(I.getType()))
15013 continue;
15014
15015 auto *Expr = SE.getSCEV(&I);
15016 auto II = RewriteMap.find(Expr);
15017
15018 if (II == RewriteMap.end())
15019 continue;
15020
15021 // Don't print things that are not interesting.
15022 if (II->second.second == Expr)
15023 continue;
15024
15025 OS.indent(Depth) << "[PSE]" << I << ":\n";
15026 OS.indent(Depth + 2) << *Expr << "\n";
15027 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
15028 }
15029 }
15030
15031 // Match the mathematical pattern A - (A / B) * B, where A and B can be
15032 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
15033 // for URem with constant power-of-2 second operands.
15034 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
15035 // 4, A / B becomes X / 8).
matchURem(const SCEV * Expr,const SCEV * & LHS,const SCEV * & RHS)15036 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
15037 const SCEV *&RHS) {
15038 if (Expr->getType()->isPointerTy())
15039 return false;
15040
15041 // Try to match 'zext (trunc A to iB) to iY', which is used
15042 // for URem with constant power-of-2 second operands. Make sure the size of
15043 // the operand A matches the size of the whole expressions.
15044 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
15045 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
15046 LHS = Trunc->getOperand();
15047 // Bail out if the type of the LHS is larger than the type of the
15048 // expression for now.
15049 if (getTypeSizeInBits(LHS->getType()) >
15050 getTypeSizeInBits(Expr->getType()))
15051 return false;
15052 if (LHS->getType() != Expr->getType())
15053 LHS = getZeroExtendExpr(LHS, Expr->getType());
15054 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
15055 << getTypeSizeInBits(Trunc->getType()));
15056 return true;
15057 }
15058 const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
15059 if (Add == nullptr || Add->getNumOperands() != 2)
15060 return false;
15061
15062 const SCEV *A = Add->getOperand(1);
15063 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
15064
15065 if (Mul == nullptr)
15066 return false;
15067
15068 const auto MatchURemWithDivisor = [&](const SCEV *B) {
15069 // (SomeExpr + (-(SomeExpr / B) * B)).
15070 if (Expr == getURemExpr(A, B)) {
15071 LHS = A;
15072 RHS = B;
15073 return true;
15074 }
15075 return false;
15076 };
15077
15078 // (SomeExpr + (-1 * (SomeExpr / B) * B)).
15079 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
15080 return MatchURemWithDivisor(Mul->getOperand(1)) ||
15081 MatchURemWithDivisor(Mul->getOperand(2));
15082
15083 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
15084 if (Mul->getNumOperands() == 2)
15085 return MatchURemWithDivisor(Mul->getOperand(1)) ||
15086 MatchURemWithDivisor(Mul->getOperand(0)) ||
15087 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
15088 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
15089 return false;
15090 }
15091
15092 ScalarEvolution::LoopGuards
collect(const Loop * L,ScalarEvolution & SE)15093 ScalarEvolution::LoopGuards::collect(const Loop *L, ScalarEvolution &SE) {
15094 LoopGuards Guards(SE);
15095 SmallVector<const SCEV *> ExprsToRewrite;
15096 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
15097 const SCEV *RHS,
15098 DenseMap<const SCEV *, const SCEV *>
15099 &RewriteMap) {
15100 // WARNING: It is generally unsound to apply any wrap flags to the proposed
15101 // replacement SCEV which isn't directly implied by the structure of that
15102 // SCEV. In particular, using contextual facts to imply flags is *NOT*
15103 // legal. See the scoping rules for flags in the header to understand why.
15104
15105 // If LHS is a constant, apply information to the other expression.
15106 if (isa<SCEVConstant>(LHS)) {
15107 std::swap(LHS, RHS);
15108 Predicate = CmpInst::getSwappedPredicate(Predicate);
15109 }
15110
15111 // Check for a condition of the form (-C1 + X < C2). InstCombine will
15112 // create this form when combining two checks of the form (X u< C2 + C1) and
15113 // (X >=u C1).
15114 auto MatchRangeCheckIdiom = [&SE, Predicate, LHS, RHS, &RewriteMap,
15115 &ExprsToRewrite]() {
15116 auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS);
15117 if (!AddExpr || AddExpr->getNumOperands() != 2)
15118 return false;
15119
15120 auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0));
15121 auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1));
15122 auto *C2 = dyn_cast<SCEVConstant>(RHS);
15123 if (!C1 || !C2 || !LHSUnknown)
15124 return false;
15125
15126 auto ExactRegion =
15127 ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt())
15128 .sub(C1->getAPInt());
15129
15130 // Bail out, unless we have a non-wrapping, monotonic range.
15131 if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet())
15132 return false;
15133 auto I = RewriteMap.find(LHSUnknown);
15134 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown;
15135 RewriteMap[LHSUnknown] = SE.getUMaxExpr(
15136 SE.getConstant(ExactRegion.getUnsignedMin()),
15137 SE.getUMinExpr(RewrittenLHS,
15138 SE.getConstant(ExactRegion.getUnsignedMax())));
15139 ExprsToRewrite.push_back(LHSUnknown);
15140 return true;
15141 };
15142 if (MatchRangeCheckIdiom())
15143 return;
15144
15145 // Return true if \p Expr is a MinMax SCEV expression with a non-negative
15146 // constant operand. If so, return in \p SCTy the SCEV type and in \p RHS
15147 // the non-constant operand and in \p LHS the constant operand.
15148 auto IsMinMaxSCEVWithNonNegativeConstant =
15149 [&](const SCEV *Expr, SCEVTypes &SCTy, const SCEV *&LHS,
15150 const SCEV *&RHS) {
15151 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr)) {
15152 if (MinMax->getNumOperands() != 2)
15153 return false;
15154 if (auto *C = dyn_cast<SCEVConstant>(MinMax->getOperand(0))) {
15155 if (C->getAPInt().isNegative())
15156 return false;
15157 SCTy = MinMax->getSCEVType();
15158 LHS = MinMax->getOperand(0);
15159 RHS = MinMax->getOperand(1);
15160 return true;
15161 }
15162 }
15163 return false;
15164 };
15165
15166 // Checks whether Expr is a non-negative constant, and Divisor is a positive
15167 // constant, and returns their APInt in ExprVal and in DivisorVal.
15168 auto GetNonNegExprAndPosDivisor = [&](const SCEV *Expr, const SCEV *Divisor,
15169 APInt &ExprVal, APInt &DivisorVal) {
15170 auto *ConstExpr = dyn_cast<SCEVConstant>(Expr);
15171 auto *ConstDivisor = dyn_cast<SCEVConstant>(Divisor);
15172 if (!ConstExpr || !ConstDivisor)
15173 return false;
15174 ExprVal = ConstExpr->getAPInt();
15175 DivisorVal = ConstDivisor->getAPInt();
15176 return ExprVal.isNonNegative() && !DivisorVal.isNonPositive();
15177 };
15178
15179 // Return a new SCEV that modifies \p Expr to the closest number divides by
15180 // \p Divisor and greater or equal than Expr.
15181 // For now, only handle constant Expr and Divisor.
15182 auto GetNextSCEVDividesByDivisor = [&](const SCEV *Expr,
15183 const SCEV *Divisor) {
15184 APInt ExprVal;
15185 APInt DivisorVal;
15186 if (!GetNonNegExprAndPosDivisor(Expr, Divisor, ExprVal, DivisorVal))
15187 return Expr;
15188 APInt Rem = ExprVal.urem(DivisorVal);
15189 if (!Rem.isZero())
15190 // return the SCEV: Expr + Divisor - Expr % Divisor
15191 return SE.getConstant(ExprVal + DivisorVal - Rem);
15192 return Expr;
15193 };
15194
15195 // Return a new SCEV that modifies \p Expr to the closest number divides by
15196 // \p Divisor and less or equal than Expr.
15197 // For now, only handle constant Expr and Divisor.
15198 auto GetPreviousSCEVDividesByDivisor = [&](const SCEV *Expr,
15199 const SCEV *Divisor) {
15200 APInt ExprVal;
15201 APInt DivisorVal;
15202 if (!GetNonNegExprAndPosDivisor(Expr, Divisor, ExprVal, DivisorVal))
15203 return Expr;
15204 APInt Rem = ExprVal.urem(DivisorVal);
15205 // return the SCEV: Expr - Expr % Divisor
15206 return SE.getConstant(ExprVal - Rem);
15207 };
15208
15209 // Apply divisibilty by \p Divisor on MinMaxExpr with constant values,
15210 // recursively. This is done by aligning up/down the constant value to the
15211 // Divisor.
15212 std::function<const SCEV *(const SCEV *, const SCEV *)>
15213 ApplyDivisibiltyOnMinMaxExpr = [&](const SCEV *MinMaxExpr,
15214 const SCEV *Divisor) {
15215 const SCEV *MinMaxLHS = nullptr, *MinMaxRHS = nullptr;
15216 SCEVTypes SCTy;
15217 if (!IsMinMaxSCEVWithNonNegativeConstant(MinMaxExpr, SCTy, MinMaxLHS,
15218 MinMaxRHS))
15219 return MinMaxExpr;
15220 auto IsMin =
15221 isa<SCEVSMinExpr>(MinMaxExpr) || isa<SCEVUMinExpr>(MinMaxExpr);
15222 assert(SE.isKnownNonNegative(MinMaxLHS) &&
15223 "Expected non-negative operand!");
15224 auto *DivisibleExpr =
15225 IsMin ? GetPreviousSCEVDividesByDivisor(MinMaxLHS, Divisor)
15226 : GetNextSCEVDividesByDivisor(MinMaxLHS, Divisor);
15227 SmallVector<const SCEV *> Ops = {
15228 ApplyDivisibiltyOnMinMaxExpr(MinMaxRHS, Divisor), DivisibleExpr};
15229 return SE.getMinMaxExpr(SCTy, Ops);
15230 };
15231
15232 // If we have LHS == 0, check if LHS is computing a property of some unknown
15233 // SCEV %v which we can rewrite %v to express explicitly.
15234 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
15235 if (Predicate == CmpInst::ICMP_EQ && RHSC &&
15236 RHSC->getValue()->isNullValue()) {
15237 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
15238 // explicitly express that.
15239 const SCEV *URemLHS = nullptr;
15240 const SCEV *URemRHS = nullptr;
15241 if (SE.matchURem(LHS, URemLHS, URemRHS)) {
15242 if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) {
15243 auto I = RewriteMap.find(LHSUnknown);
15244 const SCEV *RewrittenLHS =
15245 I != RewriteMap.end() ? I->second : LHSUnknown;
15246 RewrittenLHS = ApplyDivisibiltyOnMinMaxExpr(RewrittenLHS, URemRHS);
15247 const auto *Multiple =
15248 SE.getMulExpr(SE.getUDivExpr(RewrittenLHS, URemRHS), URemRHS);
15249 RewriteMap[LHSUnknown] = Multiple;
15250 ExprsToRewrite.push_back(LHSUnknown);
15251 return;
15252 }
15253 }
15254 }
15255
15256 // Do not apply information for constants or if RHS contains an AddRec.
15257 if (isa<SCEVConstant>(LHS) || SE.containsAddRecurrence(RHS))
15258 return;
15259
15260 // If RHS is SCEVUnknown, make sure the information is applied to it.
15261 if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) {
15262 std::swap(LHS, RHS);
15263 Predicate = CmpInst::getSwappedPredicate(Predicate);
15264 }
15265
15266 // Puts rewrite rule \p From -> \p To into the rewrite map. Also if \p From
15267 // and \p FromRewritten are the same (i.e. there has been no rewrite
15268 // registered for \p From), then puts this value in the list of rewritten
15269 // expressions.
15270 auto AddRewrite = [&](const SCEV *From, const SCEV *FromRewritten,
15271 const SCEV *To) {
15272 if (From == FromRewritten)
15273 ExprsToRewrite.push_back(From);
15274 RewriteMap[From] = To;
15275 };
15276
15277 // Checks whether \p S has already been rewritten. In that case returns the
15278 // existing rewrite because we want to chain further rewrites onto the
15279 // already rewritten value. Otherwise returns \p S.
15280 auto GetMaybeRewritten = [&](const SCEV *S) {
15281 auto I = RewriteMap.find(S);
15282 return I != RewriteMap.end() ? I->second : S;
15283 };
15284
15285 // Check for the SCEV expression (A /u B) * B while B is a constant, inside
15286 // \p Expr. The check is done recuresively on \p Expr, which is assumed to
15287 // be a composition of Min/Max SCEVs. Return whether the SCEV expression (A
15288 // /u B) * B was found, and return the divisor B in \p DividesBy. For
15289 // example, if Expr = umin (umax ((A /u 8) * 8, 16), 64), return true since
15290 // (A /u 8) * 8 matched the pattern, and return the constant SCEV 8 in \p
15291 // DividesBy.
15292 std::function<bool(const SCEV *, const SCEV *&)> HasDivisibiltyInfo =
15293 [&](const SCEV *Expr, const SCEV *&DividesBy) {
15294 if (auto *Mul = dyn_cast<SCEVMulExpr>(Expr)) {
15295 if (Mul->getNumOperands() != 2)
15296 return false;
15297 auto *MulLHS = Mul->getOperand(0);
15298 auto *MulRHS = Mul->getOperand(1);
15299 if (isa<SCEVConstant>(MulLHS))
15300 std::swap(MulLHS, MulRHS);
15301 if (auto *Div = dyn_cast<SCEVUDivExpr>(MulLHS))
15302 if (Div->getOperand(1) == MulRHS) {
15303 DividesBy = MulRHS;
15304 return true;
15305 }
15306 }
15307 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr))
15308 return HasDivisibiltyInfo(MinMax->getOperand(0), DividesBy) ||
15309 HasDivisibiltyInfo(MinMax->getOperand(1), DividesBy);
15310 return false;
15311 };
15312
15313 // Return true if Expr known to divide by \p DividesBy.
15314 std::function<bool(const SCEV *, const SCEV *&)> IsKnownToDivideBy =
15315 [&](const SCEV *Expr, const SCEV *DividesBy) {
15316 if (SE.getURemExpr(Expr, DividesBy)->isZero())
15317 return true;
15318 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr))
15319 return IsKnownToDivideBy(MinMax->getOperand(0), DividesBy) &&
15320 IsKnownToDivideBy(MinMax->getOperand(1), DividesBy);
15321 return false;
15322 };
15323
15324 const SCEV *RewrittenLHS = GetMaybeRewritten(LHS);
15325 const SCEV *DividesBy = nullptr;
15326 if (HasDivisibiltyInfo(RewrittenLHS, DividesBy))
15327 // Check that the whole expression is divided by DividesBy
15328 DividesBy =
15329 IsKnownToDivideBy(RewrittenLHS, DividesBy) ? DividesBy : nullptr;
15330
15331 // Collect rewrites for LHS and its transitive operands based on the
15332 // condition.
15333 // For min/max expressions, also apply the guard to its operands:
15334 // 'min(a, b) >= c' -> '(a >= c) and (b >= c)',
15335 // 'min(a, b) > c' -> '(a > c) and (b > c)',
15336 // 'max(a, b) <= c' -> '(a <= c) and (b <= c)',
15337 // 'max(a, b) < c' -> '(a < c) and (b < c)'.
15338
15339 // We cannot express strict predicates in SCEV, so instead we replace them
15340 // with non-strict ones against plus or minus one of RHS depending on the
15341 // predicate.
15342 const SCEV *One = SE.getOne(RHS->getType());
15343 switch (Predicate) {
15344 case CmpInst::ICMP_ULT:
15345 if (RHS->getType()->isPointerTy())
15346 return;
15347 RHS = SE.getUMaxExpr(RHS, One);
15348 [[fallthrough]];
15349 case CmpInst::ICMP_SLT: {
15350 RHS = SE.getMinusSCEV(RHS, One);
15351 RHS = DividesBy ? GetPreviousSCEVDividesByDivisor(RHS, DividesBy) : RHS;
15352 break;
15353 }
15354 case CmpInst::ICMP_UGT:
15355 case CmpInst::ICMP_SGT:
15356 RHS = SE.getAddExpr(RHS, One);
15357 RHS = DividesBy ? GetNextSCEVDividesByDivisor(RHS, DividesBy) : RHS;
15358 break;
15359 case CmpInst::ICMP_ULE:
15360 case CmpInst::ICMP_SLE:
15361 RHS = DividesBy ? GetPreviousSCEVDividesByDivisor(RHS, DividesBy) : RHS;
15362 break;
15363 case CmpInst::ICMP_UGE:
15364 case CmpInst::ICMP_SGE:
15365 RHS = DividesBy ? GetNextSCEVDividesByDivisor(RHS, DividesBy) : RHS;
15366 break;
15367 default:
15368 break;
15369 }
15370
15371 SmallVector<const SCEV *, 16> Worklist(1, LHS);
15372 SmallPtrSet<const SCEV *, 16> Visited;
15373
15374 auto EnqueueOperands = [&Worklist](const SCEVNAryExpr *S) {
15375 append_range(Worklist, S->operands());
15376 };
15377
15378 while (!Worklist.empty()) {
15379 const SCEV *From = Worklist.pop_back_val();
15380 if (isa<SCEVConstant>(From))
15381 continue;
15382 if (!Visited.insert(From).second)
15383 continue;
15384 const SCEV *FromRewritten = GetMaybeRewritten(From);
15385 const SCEV *To = nullptr;
15386
15387 switch (Predicate) {
15388 case CmpInst::ICMP_ULT:
15389 case CmpInst::ICMP_ULE:
15390 To = SE.getUMinExpr(FromRewritten, RHS);
15391 if (auto *UMax = dyn_cast<SCEVUMaxExpr>(FromRewritten))
15392 EnqueueOperands(UMax);
15393 break;
15394 case CmpInst::ICMP_SLT:
15395 case CmpInst::ICMP_SLE:
15396 To = SE.getSMinExpr(FromRewritten, RHS);
15397 if (auto *SMax = dyn_cast<SCEVSMaxExpr>(FromRewritten))
15398 EnqueueOperands(SMax);
15399 break;
15400 case CmpInst::ICMP_UGT:
15401 case CmpInst::ICMP_UGE:
15402 To = SE.getUMaxExpr(FromRewritten, RHS);
15403 if (auto *UMin = dyn_cast<SCEVUMinExpr>(FromRewritten))
15404 EnqueueOperands(UMin);
15405 break;
15406 case CmpInst::ICMP_SGT:
15407 case CmpInst::ICMP_SGE:
15408 To = SE.getSMaxExpr(FromRewritten, RHS);
15409 if (auto *SMin = dyn_cast<SCEVSMinExpr>(FromRewritten))
15410 EnqueueOperands(SMin);
15411 break;
15412 case CmpInst::ICMP_EQ:
15413 if (isa<SCEVConstant>(RHS))
15414 To = RHS;
15415 break;
15416 case CmpInst::ICMP_NE:
15417 if (isa<SCEVConstant>(RHS) &&
15418 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) {
15419 const SCEV *OneAlignedUp =
15420 DividesBy ? GetNextSCEVDividesByDivisor(One, DividesBy) : One;
15421 To = SE.getUMaxExpr(FromRewritten, OneAlignedUp);
15422 }
15423 break;
15424 default:
15425 break;
15426 }
15427
15428 if (To)
15429 AddRewrite(From, FromRewritten, To);
15430 }
15431 };
15432
15433 BasicBlock *Header = L->getHeader();
15434 SmallVector<PointerIntPair<Value *, 1, bool>> Terms;
15435 // First, collect information from assumptions dominating the loop.
15436 for (auto &AssumeVH : SE.AC.assumptions()) {
15437 if (!AssumeVH)
15438 continue;
15439 auto *AssumeI = cast<CallInst>(AssumeVH);
15440 if (!SE.DT.dominates(AssumeI, Header))
15441 continue;
15442 Terms.emplace_back(AssumeI->getOperand(0), true);
15443 }
15444
15445 // Second, collect information from llvm.experimental.guards dominating the loop.
15446 auto *GuardDecl = SE.F.getParent()->getFunction(
15447 Intrinsic::getName(Intrinsic::experimental_guard));
15448 if (GuardDecl)
15449 for (const auto *GU : GuardDecl->users())
15450 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
15451 if (Guard->getFunction() == Header->getParent() &&
15452 SE.DT.dominates(Guard, Header))
15453 Terms.emplace_back(Guard->getArgOperand(0), true);
15454
15455 // Third, collect conditions from dominating branches. Starting at the loop
15456 // predecessor, climb up the predecessor chain, as long as there are
15457 // predecessors that can be found that have unique successors leading to the
15458 // original header.
15459 // TODO: share this logic with isLoopEntryGuardedByCond.
15460 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
15461 L->getLoopPredecessor(), Header);
15462 Pair.first;
15463 Pair = SE.getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
15464
15465 const BranchInst *LoopEntryPredicate =
15466 dyn_cast<BranchInst>(Pair.first->getTerminator());
15467 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
15468 continue;
15469
15470 Terms.emplace_back(LoopEntryPredicate->getCondition(),
15471 LoopEntryPredicate->getSuccessor(0) == Pair.second);
15472 }
15473
15474 // Now apply the information from the collected conditions to
15475 // Guards.RewriteMap. Conditions are processed in reverse order, so the
15476 // earliest conditions is processed first. This ensures the SCEVs with the
15477 // shortest dependency chains are constructed first.
15478 for (auto [Term, EnterIfTrue] : reverse(Terms)) {
15479 SmallVector<Value *, 8> Worklist;
15480 SmallPtrSet<Value *, 8> Visited;
15481 Worklist.push_back(Term);
15482 while (!Worklist.empty()) {
15483 Value *Cond = Worklist.pop_back_val();
15484 if (!Visited.insert(Cond).second)
15485 continue;
15486
15487 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
15488 auto Predicate =
15489 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
15490 const auto *LHS = SE.getSCEV(Cmp->getOperand(0));
15491 const auto *RHS = SE.getSCEV(Cmp->getOperand(1));
15492 CollectCondition(Predicate, LHS, RHS, Guards.RewriteMap);
15493 continue;
15494 }
15495
15496 Value *L, *R;
15497 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
15498 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
15499 Worklist.push_back(L);
15500 Worklist.push_back(R);
15501 }
15502 }
15503 }
15504
15505 // Let the rewriter preserve NUW/NSW flags if the unsigned/signed ranges of
15506 // the replacement expressions are contained in the ranges of the replaced
15507 // expressions.
15508 Guards.PreserveNUW = true;
15509 Guards.PreserveNSW = true;
15510 for (const SCEV *Expr : ExprsToRewrite) {
15511 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
15512 Guards.PreserveNUW &=
15513 SE.getUnsignedRange(Expr).contains(SE.getUnsignedRange(RewriteTo));
15514 Guards.PreserveNSW &=
15515 SE.getSignedRange(Expr).contains(SE.getSignedRange(RewriteTo));
15516 }
15517
15518 // Now that all rewrite information is collect, rewrite the collected
15519 // expressions with the information in the map. This applies information to
15520 // sub-expressions.
15521 if (ExprsToRewrite.size() > 1) {
15522 for (const SCEV *Expr : ExprsToRewrite) {
15523 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
15524 Guards.RewriteMap.erase(Expr);
15525 Guards.RewriteMap.insert({Expr, Guards.rewrite(RewriteTo)});
15526 }
15527 }
15528 return Guards;
15529 }
15530
rewrite(const SCEV * Expr) const15531 const SCEV *ScalarEvolution::LoopGuards::rewrite(const SCEV *Expr) const {
15532 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
15533 /// in the map. It skips AddRecExpr because we cannot guarantee that the
15534 /// replacement is loop invariant in the loop of the AddRec.
15535 class SCEVLoopGuardRewriter
15536 : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
15537 const DenseMap<const SCEV *, const SCEV *> ⤅
15538
15539 SCEV::NoWrapFlags FlagMask = SCEV::FlagAnyWrap;
15540
15541 public:
15542 SCEVLoopGuardRewriter(ScalarEvolution &SE,
15543 const ScalarEvolution::LoopGuards &Guards)
15544 : SCEVRewriteVisitor(SE), Map(Guards.RewriteMap) {
15545 if (Guards.PreserveNUW)
15546 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNUW);
15547 if (Guards.PreserveNSW)
15548 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNSW);
15549 }
15550
15551 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
15552
15553 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
15554 auto I = Map.find(Expr);
15555 if (I == Map.end())
15556 return Expr;
15557 return I->second;
15558 }
15559
15560 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
15561 auto I = Map.find(Expr);
15562 if (I == Map.end()) {
15563 // If we didn't find the extact ZExt expr in the map, check if there's
15564 // an entry for a smaller ZExt we can use instead.
15565 Type *Ty = Expr->getType();
15566 const SCEV *Op = Expr->getOperand(0);
15567 unsigned Bitwidth = Ty->getScalarSizeInBits() / 2;
15568 while (Bitwidth % 8 == 0 && Bitwidth >= 8 &&
15569 Bitwidth > Op->getType()->getScalarSizeInBits()) {
15570 Type *NarrowTy = IntegerType::get(SE.getContext(), Bitwidth);
15571 auto *NarrowExt = SE.getZeroExtendExpr(Op, NarrowTy);
15572 auto I = Map.find(NarrowExt);
15573 if (I != Map.end())
15574 return SE.getZeroExtendExpr(I->second, Ty);
15575 Bitwidth = Bitwidth / 2;
15576 }
15577
15578 return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitZeroExtendExpr(
15579 Expr);
15580 }
15581 return I->second;
15582 }
15583
15584 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
15585 auto I = Map.find(Expr);
15586 if (I == Map.end())
15587 return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitSignExtendExpr(
15588 Expr);
15589 return I->second;
15590 }
15591
15592 const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
15593 auto I = Map.find(Expr);
15594 if (I == Map.end())
15595 return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitUMinExpr(Expr);
15596 return I->second;
15597 }
15598
15599 const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
15600 auto I = Map.find(Expr);
15601 if (I == Map.end())
15602 return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitSMinExpr(Expr);
15603 return I->second;
15604 }
15605
15606 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
15607 SmallVector<const SCEV *, 2> Operands;
15608 bool Changed = false;
15609 for (const auto *Op : Expr->operands()) {
15610 Operands.push_back(
15611 SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visit(Op));
15612 Changed |= Op != Operands.back();
15613 }
15614 // We are only replacing operands with equivalent values, so transfer the
15615 // flags from the original expression.
15616 return !Changed ? Expr
15617 : SE.getAddExpr(Operands,
15618 ScalarEvolution::maskFlags(
15619 Expr->getNoWrapFlags(), FlagMask));
15620 }
15621
15622 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
15623 SmallVector<const SCEV *, 2> Operands;
15624 bool Changed = false;
15625 for (const auto *Op : Expr->operands()) {
15626 Operands.push_back(
15627 SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visit(Op));
15628 Changed |= Op != Operands.back();
15629 }
15630 // We are only replacing operands with equivalent values, so transfer the
15631 // flags from the original expression.
15632 return !Changed ? Expr
15633 : SE.getMulExpr(Operands,
15634 ScalarEvolution::maskFlags(
15635 Expr->getNoWrapFlags(), FlagMask));
15636 }
15637 };
15638
15639 if (RewriteMap.empty())
15640 return Expr;
15641
15642 SCEVLoopGuardRewriter Rewriter(SE, *this);
15643 return Rewriter.visit(Expr);
15644 }
15645
applyLoopGuards(const SCEV * Expr,const Loop * L)15646 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
15647 return applyLoopGuards(Expr, LoopGuards::collect(L, *this));
15648 }
15649
applyLoopGuards(const SCEV * Expr,const LoopGuards & Guards)15650 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr,
15651 const LoopGuards &Guards) {
15652 return Guards.rewrite(Expr);
15653 }
15654