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/StringRef.h"
75 #include "llvm/Analysis/AssumptionCache.h"
76 #include "llvm/Analysis/ConstantFolding.h"
77 #include "llvm/Analysis/InstructionSimplify.h"
78 #include "llvm/Analysis/LoopInfo.h"
79 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
80 #include "llvm/Analysis/TargetLibraryInfo.h"
81 #include "llvm/Analysis/ValueTracking.h"
82 #include "llvm/Config/llvm-config.h"
83 #include "llvm/IR/Argument.h"
84 #include "llvm/IR/BasicBlock.h"
85 #include "llvm/IR/CFG.h"
86 #include "llvm/IR/Constant.h"
87 #include "llvm/IR/ConstantRange.h"
88 #include "llvm/IR/Constants.h"
89 #include "llvm/IR/DataLayout.h"
90 #include "llvm/IR/DerivedTypes.h"
91 #include "llvm/IR/Dominators.h"
92 #include "llvm/IR/Function.h"
93 #include "llvm/IR/GlobalAlias.h"
94 #include "llvm/IR/GlobalValue.h"
95 #include "llvm/IR/InstIterator.h"
96 #include "llvm/IR/InstrTypes.h"
97 #include "llvm/IR/Instruction.h"
98 #include "llvm/IR/Instructions.h"
99 #include "llvm/IR/IntrinsicInst.h"
100 #include "llvm/IR/Intrinsics.h"
101 #include "llvm/IR/LLVMContext.h"
102 #include "llvm/IR/Operator.h"
103 #include "llvm/IR/PatternMatch.h"
104 #include "llvm/IR/Type.h"
105 #include "llvm/IR/Use.h"
106 #include "llvm/IR/User.h"
107 #include "llvm/IR/Value.h"
108 #include "llvm/IR/Verifier.h"
109 #include "llvm/InitializePasses.h"
110 #include "llvm/Pass.h"
111 #include "llvm/Support/Casting.h"
112 #include "llvm/Support/CommandLine.h"
113 #include "llvm/Support/Compiler.h"
114 #include "llvm/Support/Debug.h"
115 #include "llvm/Support/ErrorHandling.h"
116 #include "llvm/Support/KnownBits.h"
117 #include "llvm/Support/SaveAndRestore.h"
118 #include "llvm/Support/raw_ostream.h"
119 #include <algorithm>
120 #include <cassert>
121 #include <climits>
122 #include <cstdint>
123 #include <cstdlib>
124 #include <map>
125 #include <memory>
126 #include <numeric>
127 #include <optional>
128 #include <tuple>
129 #include <utility>
130 #include <vector>
131
132 using namespace llvm;
133 using namespace PatternMatch;
134
135 #define DEBUG_TYPE "scalar-evolution"
136
137 STATISTIC(NumTripCountsComputed,
138 "Number of loops with predictable loop counts");
139 STATISTIC(NumTripCountsNotComputed,
140 "Number of loops without predictable loop counts");
141 STATISTIC(NumBruteForceTripCountsComputed,
142 "Number of loops with trip counts computed by force");
143
144 #ifdef EXPENSIVE_CHECKS
145 bool llvm::VerifySCEV = true;
146 #else
147 bool llvm::VerifySCEV = false;
148 #endif
149
150 static cl::opt<unsigned>
151 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
152 cl::desc("Maximum number of iterations SCEV will "
153 "symbolically execute a constant "
154 "derived loop"),
155 cl::init(100));
156
157 static cl::opt<bool, true> VerifySCEVOpt(
158 "verify-scev", cl::Hidden, cl::location(VerifySCEV),
159 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
160 static cl::opt<bool> VerifySCEVStrict(
161 "verify-scev-strict", cl::Hidden,
162 cl::desc("Enable stricter verification with -verify-scev is passed"));
163 static cl::opt<bool>
164 VerifySCEVMap("verify-scev-maps", cl::Hidden,
165 cl::desc("Verify no dangling value in ScalarEvolution's "
166 "ExprValueMap (slow)"));
167
168 static cl::opt<bool> VerifyIR(
169 "scev-verify-ir", cl::Hidden,
170 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
171 cl::init(false));
172
173 static cl::opt<unsigned> MulOpsInlineThreshold(
174 "scev-mulops-inline-threshold", cl::Hidden,
175 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
176 cl::init(32));
177
178 static cl::opt<unsigned> AddOpsInlineThreshold(
179 "scev-addops-inline-threshold", cl::Hidden,
180 cl::desc("Threshold for inlining addition operands into a SCEV"),
181 cl::init(500));
182
183 static cl::opt<unsigned> MaxSCEVCompareDepth(
184 "scalar-evolution-max-scev-compare-depth", cl::Hidden,
185 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
186 cl::init(32));
187
188 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
189 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
190 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
191 cl::init(2));
192
193 static cl::opt<unsigned> MaxValueCompareDepth(
194 "scalar-evolution-max-value-compare-depth", cl::Hidden,
195 cl::desc("Maximum depth of recursive value complexity comparisons"),
196 cl::init(2));
197
198 static cl::opt<unsigned>
199 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
200 cl::desc("Maximum depth of recursive arithmetics"),
201 cl::init(32));
202
203 static cl::opt<unsigned> MaxConstantEvolvingDepth(
204 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
205 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
206
207 static cl::opt<unsigned>
208 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
209 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
210 cl::init(8));
211
212 static cl::opt<unsigned>
213 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
214 cl::desc("Max coefficients in AddRec during evolving"),
215 cl::init(8));
216
217 static cl::opt<unsigned>
218 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
219 cl::desc("Size of the expression which is considered huge"),
220 cl::init(4096));
221
222 static cl::opt<unsigned> RangeIterThreshold(
223 "scev-range-iter-threshold", cl::Hidden,
224 cl::desc("Threshold for switching to iteratively computing SCEV ranges"),
225 cl::init(32));
226
227 static cl::opt<bool>
228 ClassifyExpressions("scalar-evolution-classify-expressions",
229 cl::Hidden, cl::init(true),
230 cl::desc("When printing analysis, include information on every instruction"));
231
232 static cl::opt<bool> UseExpensiveRangeSharpening(
233 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
234 cl::init(false),
235 cl::desc("Use more powerful methods of sharpening expression ranges. May "
236 "be costly in terms of compile time"));
237
238 static cl::opt<unsigned> MaxPhiSCCAnalysisSize(
239 "scalar-evolution-max-scc-analysis-depth", cl::Hidden,
240 cl::desc("Maximum amount of nodes to process while searching SCEVUnknown "
241 "Phi strongly connected components"),
242 cl::init(8));
243
244 static cl::opt<bool>
245 EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
246 cl::desc("Handle <= and >= in finite loops"),
247 cl::init(true));
248
249 static cl::opt<bool> UseContextForNoWrapFlagInference(
250 "scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden,
251 cl::desc("Infer nuw/nsw flags using context where suitable"),
252 cl::init(true));
253
254 //===----------------------------------------------------------------------===//
255 // SCEV class definitions
256 //===----------------------------------------------------------------------===//
257
258 //===----------------------------------------------------------------------===//
259 // Implementation of the SCEV class.
260 //
261
262 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const263 LLVM_DUMP_METHOD void SCEV::dump() const {
264 print(dbgs());
265 dbgs() << '\n';
266 }
267 #endif
268
print(raw_ostream & OS) const269 void SCEV::print(raw_ostream &OS) const {
270 switch (getSCEVType()) {
271 case scConstant:
272 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
273 return;
274 case scPtrToInt: {
275 const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this);
276 const SCEV *Op = PtrToInt->getOperand();
277 OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to "
278 << *PtrToInt->getType() << ")";
279 return;
280 }
281 case scTruncate: {
282 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
283 const SCEV *Op = Trunc->getOperand();
284 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
285 << *Trunc->getType() << ")";
286 return;
287 }
288 case scZeroExtend: {
289 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
290 const SCEV *Op = ZExt->getOperand();
291 OS << "(zext " << *Op->getType() << " " << *Op << " to "
292 << *ZExt->getType() << ")";
293 return;
294 }
295 case scSignExtend: {
296 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
297 const SCEV *Op = SExt->getOperand();
298 OS << "(sext " << *Op->getType() << " " << *Op << " to "
299 << *SExt->getType() << ")";
300 return;
301 }
302 case scAddRecExpr: {
303 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
304 OS << "{" << *AR->getOperand(0);
305 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
306 OS << ",+," << *AR->getOperand(i);
307 OS << "}<";
308 if (AR->hasNoUnsignedWrap())
309 OS << "nuw><";
310 if (AR->hasNoSignedWrap())
311 OS << "nsw><";
312 if (AR->hasNoSelfWrap() &&
313 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
314 OS << "nw><";
315 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
316 OS << ">";
317 return;
318 }
319 case scAddExpr:
320 case scMulExpr:
321 case scUMaxExpr:
322 case scSMaxExpr:
323 case scUMinExpr:
324 case scSMinExpr:
325 case scSequentialUMinExpr: {
326 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
327 const char *OpStr = nullptr;
328 switch (NAry->getSCEVType()) {
329 case scAddExpr: OpStr = " + "; break;
330 case scMulExpr: OpStr = " * "; break;
331 case scUMaxExpr: OpStr = " umax "; break;
332 case scSMaxExpr: OpStr = " smax "; break;
333 case scUMinExpr:
334 OpStr = " umin ";
335 break;
336 case scSMinExpr:
337 OpStr = " smin ";
338 break;
339 case scSequentialUMinExpr:
340 OpStr = " umin_seq ";
341 break;
342 default:
343 llvm_unreachable("There are no other nary expression types.");
344 }
345 OS << "(";
346 ListSeparator LS(OpStr);
347 for (const SCEV *Op : NAry->operands())
348 OS << LS << *Op;
349 OS << ")";
350 switch (NAry->getSCEVType()) {
351 case scAddExpr:
352 case scMulExpr:
353 if (NAry->hasNoUnsignedWrap())
354 OS << "<nuw>";
355 if (NAry->hasNoSignedWrap())
356 OS << "<nsw>";
357 break;
358 default:
359 // Nothing to print for other nary expressions.
360 break;
361 }
362 return;
363 }
364 case scUDivExpr: {
365 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
366 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
367 return;
368 }
369 case scUnknown: {
370 const SCEVUnknown *U = cast<SCEVUnknown>(this);
371 Type *AllocTy;
372 if (U->isSizeOf(AllocTy)) {
373 OS << "sizeof(" << *AllocTy << ")";
374 return;
375 }
376 if (U->isAlignOf(AllocTy)) {
377 OS << "alignof(" << *AllocTy << ")";
378 return;
379 }
380
381 Type *CTy;
382 Constant *FieldNo;
383 if (U->isOffsetOf(CTy, FieldNo)) {
384 OS << "offsetof(" << *CTy << ", ";
385 FieldNo->printAsOperand(OS, false);
386 OS << ")";
387 return;
388 }
389
390 // Otherwise just print it normally.
391 U->getValue()->printAsOperand(OS, false);
392 return;
393 }
394 case scCouldNotCompute:
395 OS << "***COULDNOTCOMPUTE***";
396 return;
397 }
398 llvm_unreachable("Unknown SCEV kind!");
399 }
400
getType() const401 Type *SCEV::getType() const {
402 switch (getSCEVType()) {
403 case scConstant:
404 return cast<SCEVConstant>(this)->getType();
405 case scPtrToInt:
406 case scTruncate:
407 case scZeroExtend:
408 case scSignExtend:
409 return cast<SCEVCastExpr>(this)->getType();
410 case scAddRecExpr:
411 return cast<SCEVAddRecExpr>(this)->getType();
412 case scMulExpr:
413 return cast<SCEVMulExpr>(this)->getType();
414 case scUMaxExpr:
415 case scSMaxExpr:
416 case scUMinExpr:
417 case scSMinExpr:
418 return cast<SCEVMinMaxExpr>(this)->getType();
419 case scSequentialUMinExpr:
420 return cast<SCEVSequentialMinMaxExpr>(this)->getType();
421 case scAddExpr:
422 return cast<SCEVAddExpr>(this)->getType();
423 case scUDivExpr:
424 return cast<SCEVUDivExpr>(this)->getType();
425 case scUnknown:
426 return cast<SCEVUnknown>(this)->getType();
427 case scCouldNotCompute:
428 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
429 }
430 llvm_unreachable("Unknown SCEV kind!");
431 }
432
operands() const433 ArrayRef<const SCEV *> SCEV::operands() const {
434 switch (getSCEVType()) {
435 case scConstant:
436 case scUnknown:
437 return {};
438 case scPtrToInt:
439 case scTruncate:
440 case scZeroExtend:
441 case scSignExtend:
442 return cast<SCEVCastExpr>(this)->operands();
443 case scAddRecExpr:
444 case scAddExpr:
445 case scMulExpr:
446 case scUMaxExpr:
447 case scSMaxExpr:
448 case scUMinExpr:
449 case scSMinExpr:
450 case scSequentialUMinExpr:
451 return cast<SCEVNAryExpr>(this)->operands();
452 case scUDivExpr:
453 return cast<SCEVUDivExpr>(this)->operands();
454 case scCouldNotCompute:
455 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
456 }
457 llvm_unreachable("Unknown SCEV kind!");
458 }
459
isZero() const460 bool SCEV::isZero() const {
461 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
462 return SC->getValue()->isZero();
463 return false;
464 }
465
isOne() const466 bool SCEV::isOne() const {
467 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
468 return SC->getValue()->isOne();
469 return false;
470 }
471
isAllOnesValue() const472 bool SCEV::isAllOnesValue() const {
473 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
474 return SC->getValue()->isMinusOne();
475 return false;
476 }
477
isNonConstantNegative() const478 bool SCEV::isNonConstantNegative() const {
479 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
480 if (!Mul) return false;
481
482 // If there is a constant factor, it will be first.
483 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
484 if (!SC) return false;
485
486 // Return true if the value is negative, this matches things like (-42 * V).
487 return SC->getAPInt().isNegative();
488 }
489
SCEVCouldNotCompute()490 SCEVCouldNotCompute::SCEVCouldNotCompute() :
491 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
492
classof(const SCEV * S)493 bool SCEVCouldNotCompute::classof(const SCEV *S) {
494 return S->getSCEVType() == scCouldNotCompute;
495 }
496
getConstant(ConstantInt * V)497 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
498 FoldingSetNodeID ID;
499 ID.AddInteger(scConstant);
500 ID.AddPointer(V);
501 void *IP = nullptr;
502 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
503 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
504 UniqueSCEVs.InsertNode(S, IP);
505 return S;
506 }
507
getConstant(const APInt & Val)508 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
509 return getConstant(ConstantInt::get(getContext(), Val));
510 }
511
512 const SCEV *
getConstant(Type * Ty,uint64_t V,bool isSigned)513 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
514 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
515 return getConstant(ConstantInt::get(ITy, V, isSigned));
516 }
517
SCEVCastExpr(const FoldingSetNodeIDRef ID,SCEVTypes SCEVTy,const SCEV * op,Type * ty)518 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
519 const SCEV *op, Type *ty)
520 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {}
521
SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID,const SCEV * Op,Type * ITy)522 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op,
523 Type *ITy)
524 : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
525 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
526 "Must be a non-bit-width-changing pointer-to-integer cast!");
527 }
528
SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,SCEVTypes SCEVTy,const SCEV * op,Type * ty)529 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,
530 SCEVTypes SCEVTy, const SCEV *op,
531 Type *ty)
532 : SCEVCastExpr(ID, SCEVTy, op, ty) {}
533
SCEVTruncateExpr(const FoldingSetNodeIDRef ID,const SCEV * op,Type * ty)534 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op,
535 Type *ty)
536 : SCEVIntegralCastExpr(ID, scTruncate, op, ty) {
537 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
538 "Cannot truncate non-integer value!");
539 }
540
SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,const SCEV * op,Type * ty)541 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
542 const SCEV *op, Type *ty)
543 : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) {
544 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
545 "Cannot zero extend non-integer value!");
546 }
547
SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,const SCEV * op,Type * ty)548 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
549 const SCEV *op, Type *ty)
550 : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) {
551 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
552 "Cannot sign extend non-integer value!");
553 }
554
deleted()555 void SCEVUnknown::deleted() {
556 // Clear this SCEVUnknown from various maps.
557 SE->forgetMemoizedResults(this);
558
559 // Remove this SCEVUnknown from the uniquing map.
560 SE->UniqueSCEVs.RemoveNode(this);
561
562 // Release the value.
563 setValPtr(nullptr);
564 }
565
allUsesReplacedWith(Value * New)566 void SCEVUnknown::allUsesReplacedWith(Value *New) {
567 // Clear this SCEVUnknown from various maps.
568 SE->forgetMemoizedResults(this);
569
570 // Remove this SCEVUnknown from the uniquing map.
571 SE->UniqueSCEVs.RemoveNode(this);
572
573 // Replace the value pointer in case someone is still using this SCEVUnknown.
574 setValPtr(New);
575 }
576
isSizeOf(Type * & AllocTy) const577 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
578 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
579 if (VCE->getOpcode() == Instruction::PtrToInt)
580 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
581 if (CE->getOpcode() == Instruction::GetElementPtr &&
582 CE->getOperand(0)->isNullValue() &&
583 CE->getNumOperands() == 2)
584 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
585 if (CI->isOne()) {
586 AllocTy = cast<GEPOperator>(CE)->getSourceElementType();
587 return true;
588 }
589
590 return false;
591 }
592
isAlignOf(Type * & AllocTy) const593 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
594 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
595 if (VCE->getOpcode() == Instruction::PtrToInt)
596 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
597 if (CE->getOpcode() == Instruction::GetElementPtr &&
598 CE->getOperand(0)->isNullValue()) {
599 Type *Ty = cast<GEPOperator>(CE)->getSourceElementType();
600 if (StructType *STy = dyn_cast<StructType>(Ty))
601 if (!STy->isPacked() &&
602 CE->getNumOperands() == 3 &&
603 CE->getOperand(1)->isNullValue()) {
604 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
605 if (CI->isOne() &&
606 STy->getNumElements() == 2 &&
607 STy->getElementType(0)->isIntegerTy(1)) {
608 AllocTy = STy->getElementType(1);
609 return true;
610 }
611 }
612 }
613
614 return false;
615 }
616
isOffsetOf(Type * & CTy,Constant * & FieldNo) const617 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
618 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
619 if (VCE->getOpcode() == Instruction::PtrToInt)
620 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
621 if (CE->getOpcode() == Instruction::GetElementPtr &&
622 CE->getNumOperands() == 3 &&
623 CE->getOperand(0)->isNullValue() &&
624 CE->getOperand(1)->isNullValue()) {
625 Type *Ty = cast<GEPOperator>(CE)->getSourceElementType();
626 // Ignore vector types here so that ScalarEvolutionExpander doesn't
627 // emit getelementptrs that index into vectors.
628 if (Ty->isStructTy() || Ty->isArrayTy()) {
629 CTy = Ty;
630 FieldNo = CE->getOperand(2);
631 return true;
632 }
633 }
634
635 return false;
636 }
637
638 //===----------------------------------------------------------------------===//
639 // SCEV Utilities
640 //===----------------------------------------------------------------------===//
641
642 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
643 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
644 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that
645 /// have been previously deemed to be "equally complex" by this routine. It is
646 /// intended to avoid exponential time complexity in cases like:
647 ///
648 /// %a = f(%x, %y)
649 /// %b = f(%a, %a)
650 /// %c = f(%b, %b)
651 ///
652 /// %d = f(%x, %y)
653 /// %e = f(%d, %d)
654 /// %f = f(%e, %e)
655 ///
656 /// CompareValueComplexity(%f, %c)
657 ///
658 /// Since we do not continue running this routine on expression trees once we
659 /// have seen unequal values, there is no need to track them in the cache.
660 static int
CompareValueComplexity(EquivalenceClasses<const Value * > & EqCacheValue,const LoopInfo * const LI,Value * LV,Value * RV,unsigned Depth)661 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
662 const LoopInfo *const LI, Value *LV, Value *RV,
663 unsigned Depth) {
664 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
665 return 0;
666
667 // Order pointer values after integer values. This helps SCEVExpander form
668 // GEPs.
669 bool LIsPointer = LV->getType()->isPointerTy(),
670 RIsPointer = RV->getType()->isPointerTy();
671 if (LIsPointer != RIsPointer)
672 return (int)LIsPointer - (int)RIsPointer;
673
674 // Compare getValueID values.
675 unsigned LID = LV->getValueID(), RID = RV->getValueID();
676 if (LID != RID)
677 return (int)LID - (int)RID;
678
679 // Sort arguments by their position.
680 if (const auto *LA = dyn_cast<Argument>(LV)) {
681 const auto *RA = cast<Argument>(RV);
682 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
683 return (int)LArgNo - (int)RArgNo;
684 }
685
686 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
687 const auto *RGV = cast<GlobalValue>(RV);
688
689 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
690 auto LT = GV->getLinkage();
691 return !(GlobalValue::isPrivateLinkage(LT) ||
692 GlobalValue::isInternalLinkage(LT));
693 };
694
695 // Use the names to distinguish the two values, but only if the
696 // names are semantically important.
697 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
698 return LGV->getName().compare(RGV->getName());
699 }
700
701 // For instructions, compare their loop depth, and their operand count. This
702 // is pretty loose.
703 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
704 const auto *RInst = cast<Instruction>(RV);
705
706 // Compare loop depths.
707 const BasicBlock *LParent = LInst->getParent(),
708 *RParent = RInst->getParent();
709 if (LParent != RParent) {
710 unsigned LDepth = LI->getLoopDepth(LParent),
711 RDepth = LI->getLoopDepth(RParent);
712 if (LDepth != RDepth)
713 return (int)LDepth - (int)RDepth;
714 }
715
716 // Compare the number of operands.
717 unsigned LNumOps = LInst->getNumOperands(),
718 RNumOps = RInst->getNumOperands();
719 if (LNumOps != RNumOps)
720 return (int)LNumOps - (int)RNumOps;
721
722 for (unsigned Idx : seq(0u, LNumOps)) {
723 int Result =
724 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
725 RInst->getOperand(Idx), Depth + 1);
726 if (Result != 0)
727 return Result;
728 }
729 }
730
731 EqCacheValue.unionSets(LV, RV);
732 return 0;
733 }
734
735 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
736 // than RHS, respectively. A three-way result allows recursive comparisons to be
737 // more efficient.
738 // If the max analysis depth was reached, return std::nullopt, assuming we do
739 // not know if they are equivalent for sure.
740 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)741 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV,
742 EquivalenceClasses<const Value *> &EqCacheValue,
743 const LoopInfo *const LI, const SCEV *LHS,
744 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
745 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
746 if (LHS == RHS)
747 return 0;
748
749 // Primarily, sort the SCEVs by their getSCEVType().
750 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
751 if (LType != RType)
752 return (int)LType - (int)RType;
753
754 if (EqCacheSCEV.isEquivalent(LHS, RHS))
755 return 0;
756
757 if (Depth > MaxSCEVCompareDepth)
758 return std::nullopt;
759
760 // Aside from the getSCEVType() ordering, the particular ordering
761 // isn't very important except that it's beneficial to be consistent,
762 // so that (a + b) and (b + a) don't end up as different expressions.
763 switch (LType) {
764 case scUnknown: {
765 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
766 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
767
768 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
769 RU->getValue(), Depth + 1);
770 if (X == 0)
771 EqCacheSCEV.unionSets(LHS, RHS);
772 return X;
773 }
774
775 case scConstant: {
776 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
777 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
778
779 // Compare constant values.
780 const APInt &LA = LC->getAPInt();
781 const APInt &RA = RC->getAPInt();
782 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
783 if (LBitWidth != RBitWidth)
784 return (int)LBitWidth - (int)RBitWidth;
785 return LA.ult(RA) ? -1 : 1;
786 }
787
788 case scAddRecExpr: {
789 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
790 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
791
792 // There is always a dominance between two recs that are used by one SCEV,
793 // so we can safely sort recs by loop header dominance. We require such
794 // order in getAddExpr.
795 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
796 if (LLoop != RLoop) {
797 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
798 assert(LHead != RHead && "Two loops share the same header?");
799 if (DT.dominates(LHead, RHead))
800 return 1;
801 else
802 assert(DT.dominates(RHead, LHead) &&
803 "No dominance between recurrences used by one SCEV?");
804 return -1;
805 }
806
807 [[fallthrough]];
808 }
809
810 case scTruncate:
811 case scZeroExtend:
812 case scSignExtend:
813 case scPtrToInt:
814 case scAddExpr:
815 case scMulExpr:
816 case scUDivExpr:
817 case scSMaxExpr:
818 case scUMaxExpr:
819 case scSMinExpr:
820 case scUMinExpr:
821 case scSequentialUMinExpr: {
822 ArrayRef<const SCEV *> LOps = LHS->operands();
823 ArrayRef<const SCEV *> ROps = RHS->operands();
824
825 // Lexicographically compare n-ary-like expressions.
826 unsigned LNumOps = LOps.size(), RNumOps = ROps.size();
827 if (LNumOps != RNumOps)
828 return (int)LNumOps - (int)RNumOps;
829
830 for (unsigned i = 0; i != LNumOps; ++i) {
831 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LOps[i],
832 ROps[i], DT, Depth + 1);
833 if (X != 0)
834 return X;
835 }
836 EqCacheSCEV.unionSets(LHS, RHS);
837 return 0;
838 }
839
840 case scCouldNotCompute:
841 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
842 }
843 llvm_unreachable("Unknown SCEV kind!");
844 }
845
846 /// Given a list of SCEV objects, order them by their complexity, and group
847 /// objects of the same complexity together by value. When this routine is
848 /// finished, we know that any duplicates in the vector are consecutive and that
849 /// complexity is monotonically increasing.
850 ///
851 /// Note that we go take special precautions to ensure that we get deterministic
852 /// results from this routine. In other words, we don't want the results of
853 /// this to depend on where the addresses of various SCEV objects happened to
854 /// land in memory.
GroupByComplexity(SmallVectorImpl<const SCEV * > & Ops,LoopInfo * LI,DominatorTree & DT)855 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
856 LoopInfo *LI, DominatorTree &DT) {
857 if (Ops.size() < 2) return; // Noop
858
859 EquivalenceClasses<const SCEV *> EqCacheSCEV;
860 EquivalenceClasses<const Value *> EqCacheValue;
861
862 // Whether LHS has provably less complexity than RHS.
863 auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) {
864 auto Complexity =
865 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT);
866 return Complexity && *Complexity < 0;
867 };
868 if (Ops.size() == 2) {
869 // This is the common case, which also happens to be trivially simple.
870 // Special case it.
871 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
872 if (IsLessComplex(RHS, LHS))
873 std::swap(LHS, RHS);
874 return;
875 }
876
877 // Do the rough sort by complexity.
878 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
879 return IsLessComplex(LHS, RHS);
880 });
881
882 // Now that we are sorted by complexity, group elements of the same
883 // complexity. Note that this is, at worst, N^2, but the vector is likely to
884 // be extremely short in practice. Note that we take this approach because we
885 // do not want to depend on the addresses of the objects we are grouping.
886 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
887 const SCEV *S = Ops[i];
888 unsigned Complexity = S->getSCEVType();
889
890 // If there are any objects of the same complexity and same value as this
891 // one, group them.
892 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
893 if (Ops[j] == S) { // Found a duplicate.
894 // Move it to immediately after i'th element.
895 std::swap(Ops[i+1], Ops[j]);
896 ++i; // no need to rescan it.
897 if (i == e-2) return; // Done!
898 }
899 }
900 }
901 }
902
903 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
904 /// least HugeExprThreshold nodes).
hasHugeExpression(ArrayRef<const SCEV * > Ops)905 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
906 return any_of(Ops, [](const SCEV *S) {
907 return S->getExpressionSize() >= HugeExprThreshold;
908 });
909 }
910
911 //===----------------------------------------------------------------------===//
912 // Simple SCEV method implementations
913 //===----------------------------------------------------------------------===//
914
915 /// Compute BC(It, K). The result has width W. Assume, K > 0.
BinomialCoefficient(const SCEV * It,unsigned K,ScalarEvolution & SE,Type * ResultTy)916 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
917 ScalarEvolution &SE,
918 Type *ResultTy) {
919 // Handle the simplest case efficiently.
920 if (K == 1)
921 return SE.getTruncateOrZeroExtend(It, ResultTy);
922
923 // We are using the following formula for BC(It, K):
924 //
925 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
926 //
927 // Suppose, W is the bitwidth of the return value. We must be prepared for
928 // overflow. Hence, we must assure that the result of our computation is
929 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
930 // safe in modular arithmetic.
931 //
932 // However, this code doesn't use exactly that formula; the formula it uses
933 // is something like the following, where T is the number of factors of 2 in
934 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
935 // exponentiation:
936 //
937 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
938 //
939 // This formula is trivially equivalent to the previous formula. However,
940 // this formula can be implemented much more efficiently. The trick is that
941 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
942 // arithmetic. To do exact division in modular arithmetic, all we have
943 // to do is multiply by the inverse. Therefore, this step can be done at
944 // width W.
945 //
946 // The next issue is how to safely do the division by 2^T. The way this
947 // is done is by doing the multiplication step at a width of at least W + T
948 // bits. This way, the bottom W+T bits of the product are accurate. Then,
949 // when we perform the division by 2^T (which is equivalent to a right shift
950 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
951 // truncated out after the division by 2^T.
952 //
953 // In comparison to just directly using the first formula, this technique
954 // is much more efficient; using the first formula requires W * K bits,
955 // but this formula less than W + K bits. Also, the first formula requires
956 // a division step, whereas this formula only requires multiplies and shifts.
957 //
958 // It doesn't matter whether the subtraction step is done in the calculation
959 // width or the input iteration count's width; if the subtraction overflows,
960 // the result must be zero anyway. We prefer here to do it in the width of
961 // the induction variable because it helps a lot for certain cases; CodeGen
962 // isn't smart enough to ignore the overflow, which leads to much less
963 // efficient code if the width of the subtraction is wider than the native
964 // register width.
965 //
966 // (It's possible to not widen at all by pulling out factors of 2 before
967 // the multiplication; for example, K=2 can be calculated as
968 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
969 // extra arithmetic, so it's not an obvious win, and it gets
970 // much more complicated for K > 3.)
971
972 // Protection from insane SCEVs; this bound is conservative,
973 // but it probably doesn't matter.
974 if (K > 1000)
975 return SE.getCouldNotCompute();
976
977 unsigned W = SE.getTypeSizeInBits(ResultTy);
978
979 // Calculate K! / 2^T and T; we divide out the factors of two before
980 // multiplying for calculating K! / 2^T to avoid overflow.
981 // Other overflow doesn't matter because we only care about the bottom
982 // W bits of the result.
983 APInt OddFactorial(W, 1);
984 unsigned T = 1;
985 for (unsigned i = 3; i <= K; ++i) {
986 APInt Mult(W, i);
987 unsigned TwoFactors = Mult.countTrailingZeros();
988 T += TwoFactors;
989 Mult.lshrInPlace(TwoFactors);
990 OddFactorial *= Mult;
991 }
992
993 // We need at least W + T bits for the multiplication step
994 unsigned CalculationBits = W + T;
995
996 // Calculate 2^T, at width T+W.
997 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
998
999 // Calculate the multiplicative inverse of K! / 2^T;
1000 // this multiplication factor will perform the exact division by
1001 // K! / 2^T.
1002 APInt Mod = APInt::getSignedMinValue(W+1);
1003 APInt MultiplyFactor = OddFactorial.zext(W+1);
1004 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1005 MultiplyFactor = MultiplyFactor.trunc(W);
1006
1007 // Calculate the product, at width T+W
1008 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1009 CalculationBits);
1010 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1011 for (unsigned i = 1; i != K; ++i) {
1012 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1013 Dividend = SE.getMulExpr(Dividend,
1014 SE.getTruncateOrZeroExtend(S, CalculationTy));
1015 }
1016
1017 // Divide by 2^T
1018 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1019
1020 // Truncate the result, and divide by K! / 2^T.
1021
1022 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1023 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1024 }
1025
1026 /// Return the value of this chain of recurrences at the specified iteration
1027 /// number. We can evaluate this recurrence by multiplying each element in the
1028 /// chain by the binomial coefficient corresponding to it. In other words, we
1029 /// can evaluate {A,+,B,+,C,+,D} as:
1030 ///
1031 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1032 ///
1033 /// where BC(It, k) stands for binomial coefficient.
evaluateAtIteration(const SCEV * It,ScalarEvolution & SE) const1034 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1035 ScalarEvolution &SE) const {
1036 return evaluateAtIteration(operands(), It, SE);
1037 }
1038
1039 const SCEV *
evaluateAtIteration(ArrayRef<const SCEV * > Operands,const SCEV * It,ScalarEvolution & SE)1040 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands,
1041 const SCEV *It, ScalarEvolution &SE) {
1042 assert(Operands.size() > 0);
1043 const SCEV *Result = Operands[0];
1044 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1045 // The computation is correct in the face of overflow provided that the
1046 // multiplication is performed _after_ the evaluation of the binomial
1047 // coefficient.
1048 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
1049 if (isa<SCEVCouldNotCompute>(Coeff))
1050 return Coeff;
1051
1052 Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff));
1053 }
1054 return Result;
1055 }
1056
1057 //===----------------------------------------------------------------------===//
1058 // SCEV Expression folder implementations
1059 //===----------------------------------------------------------------------===//
1060
getLosslessPtrToIntExpr(const SCEV * Op,unsigned Depth)1061 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op,
1062 unsigned Depth) {
1063 assert(Depth <= 1 &&
1064 "getLosslessPtrToIntExpr() should self-recurse at most once.");
1065
1066 // We could be called with an integer-typed operands during SCEV rewrites.
1067 // Since the operand is an integer already, just perform zext/trunc/self cast.
1068 if (!Op->getType()->isPointerTy())
1069 return Op;
1070
1071 // What would be an ID for such a SCEV cast expression?
1072 FoldingSetNodeID ID;
1073 ID.AddInteger(scPtrToInt);
1074 ID.AddPointer(Op);
1075
1076 void *IP = nullptr;
1077
1078 // Is there already an expression for such a cast?
1079 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1080 return S;
1081
1082 // It isn't legal for optimizations to construct new ptrtoint expressions
1083 // for non-integral pointers.
1084 if (getDataLayout().isNonIntegralPointerType(Op->getType()))
1085 return getCouldNotCompute();
1086
1087 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1088
1089 // We can only trivially model ptrtoint if SCEV's effective (integer) type
1090 // is sufficiently wide to represent all possible pointer values.
1091 // We could theoretically teach SCEV to truncate wider pointers, but
1092 // that isn't implemented for now.
1093 if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) !=
1094 getDataLayout().getTypeSizeInBits(IntPtrTy))
1095 return getCouldNotCompute();
1096
1097 // If not, is this expression something we can't reduce any further?
1098 if (auto *U = dyn_cast<SCEVUnknown>(Op)) {
1099 // Perform some basic constant folding. If the operand of the ptr2int cast
1100 // is a null pointer, don't create a ptr2int SCEV expression (that will be
1101 // left as-is), but produce a zero constant.
1102 // NOTE: We could handle a more general case, but lack motivational cases.
1103 if (isa<ConstantPointerNull>(U->getValue()))
1104 return getZero(IntPtrTy);
1105
1106 // Create an explicit cast node.
1107 // We can reuse the existing insert position since if we get here,
1108 // we won't have made any changes which would invalidate it.
1109 SCEV *S = new (SCEVAllocator)
1110 SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1111 UniqueSCEVs.InsertNode(S, IP);
1112 registerUser(S, Op);
1113 return S;
1114 }
1115
1116 assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for "
1117 "non-SCEVUnknown's.");
1118
1119 // Otherwise, we've got some expression that is more complex than just a
1120 // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1121 // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1122 // only, and the expressions must otherwise be integer-typed.
1123 // So sink the cast down to the SCEVUnknown's.
1124
1125 /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1126 /// which computes a pointer-typed value, and rewrites the whole expression
1127 /// tree so that *all* the computations are done on integers, and the only
1128 /// pointer-typed operands in the expression are SCEVUnknown.
1129 class SCEVPtrToIntSinkingRewriter
1130 : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1131 using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>;
1132
1133 public:
1134 SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1135
1136 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1137 SCEVPtrToIntSinkingRewriter Rewriter(SE);
1138 return Rewriter.visit(Scev);
1139 }
1140
1141 const SCEV *visit(const SCEV *S) {
1142 Type *STy = S->getType();
1143 // If the expression is not pointer-typed, just keep it as-is.
1144 if (!STy->isPointerTy())
1145 return S;
1146 // Else, recursively sink the cast down into it.
1147 return Base::visit(S);
1148 }
1149
1150 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1151 SmallVector<const SCEV *, 2> Operands;
1152 bool Changed = false;
1153 for (const auto *Op : Expr->operands()) {
1154 Operands.push_back(visit(Op));
1155 Changed |= Op != Operands.back();
1156 }
1157 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1158 }
1159
1160 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1161 SmallVector<const SCEV *, 2> Operands;
1162 bool Changed = false;
1163 for (const auto *Op : Expr->operands()) {
1164 Operands.push_back(visit(Op));
1165 Changed |= Op != Operands.back();
1166 }
1167 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1168 }
1169
1170 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1171 assert(Expr->getType()->isPointerTy() &&
1172 "Should only reach pointer-typed SCEVUnknown's.");
1173 return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1);
1174 }
1175 };
1176
1177 // And actually perform the cast sinking.
1178 const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1179 assert(IntOp->getType()->isIntegerTy() &&
1180 "We must have succeeded in sinking the cast, "
1181 "and ending up with an integer-typed expression!");
1182 return IntOp;
1183 }
1184
getPtrToIntExpr(const SCEV * Op,Type * Ty)1185 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) {
1186 assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1187
1188 const SCEV *IntOp = getLosslessPtrToIntExpr(Op);
1189 if (isa<SCEVCouldNotCompute>(IntOp))
1190 return IntOp;
1191
1192 return getTruncateOrZeroExtend(IntOp, Ty);
1193 }
1194
getTruncateExpr(const SCEV * Op,Type * Ty,unsigned Depth)1195 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1196 unsigned Depth) {
1197 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1198 "This is not a truncating conversion!");
1199 assert(isSCEVable(Ty) &&
1200 "This is not a conversion to a SCEVable type!");
1201 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1202 Ty = getEffectiveSCEVType(Ty);
1203
1204 FoldingSetNodeID ID;
1205 ID.AddInteger(scTruncate);
1206 ID.AddPointer(Op);
1207 ID.AddPointer(Ty);
1208 void *IP = nullptr;
1209 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1210
1211 // Fold if the operand is constant.
1212 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1213 return getConstant(
1214 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1215
1216 // trunc(trunc(x)) --> trunc(x)
1217 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1218 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1219
1220 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1221 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1222 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1223
1224 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1225 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1226 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1227
1228 if (Depth > MaxCastDepth) {
1229 SCEV *S =
1230 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1231 UniqueSCEVs.InsertNode(S, IP);
1232 registerUser(S, Op);
1233 return S;
1234 }
1235
1236 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1237 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1238 // if after transforming we have at most one truncate, not counting truncates
1239 // that replace other casts.
1240 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1241 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1242 SmallVector<const SCEV *, 4> Operands;
1243 unsigned numTruncs = 0;
1244 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1245 ++i) {
1246 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1247 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1248 isa<SCEVTruncateExpr>(S))
1249 numTruncs++;
1250 Operands.push_back(S);
1251 }
1252 if (numTruncs < 2) {
1253 if (isa<SCEVAddExpr>(Op))
1254 return getAddExpr(Operands);
1255 else if (isa<SCEVMulExpr>(Op))
1256 return getMulExpr(Operands);
1257 else
1258 llvm_unreachable("Unexpected SCEV type for Op.");
1259 }
1260 // Although we checked in the beginning that ID is not in the cache, it is
1261 // possible that during recursion and different modification ID was inserted
1262 // into the cache. So if we find it, just return it.
1263 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1264 return S;
1265 }
1266
1267 // If the input value is a chrec scev, truncate the chrec's operands.
1268 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1269 SmallVector<const SCEV *, 4> Operands;
1270 for (const SCEV *Op : AddRec->operands())
1271 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1272 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1273 }
1274
1275 // Return zero if truncating to known zeros.
1276 uint32_t MinTrailingZeros = GetMinTrailingZeros(Op);
1277 if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1278 return getZero(Ty);
1279
1280 // The cast wasn't folded; create an explicit cast node. We can reuse
1281 // the existing insert position since if we get here, we won't have
1282 // made any changes which would invalidate it.
1283 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1284 Op, Ty);
1285 UniqueSCEVs.InsertNode(S, IP);
1286 registerUser(S, Op);
1287 return S;
1288 }
1289
1290 // Get the limit of a recurrence such that incrementing by Step cannot cause
1291 // signed overflow as long as the value of the recurrence within the
1292 // loop does not exceed this limit before incrementing.
getSignedOverflowLimitForStep(const SCEV * Step,ICmpInst::Predicate * Pred,ScalarEvolution * SE)1293 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1294 ICmpInst::Predicate *Pred,
1295 ScalarEvolution *SE) {
1296 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1297 if (SE->isKnownPositive(Step)) {
1298 *Pred = ICmpInst::ICMP_SLT;
1299 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1300 SE->getSignedRangeMax(Step));
1301 }
1302 if (SE->isKnownNegative(Step)) {
1303 *Pred = ICmpInst::ICMP_SGT;
1304 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1305 SE->getSignedRangeMin(Step));
1306 }
1307 return nullptr;
1308 }
1309
1310 // Get the limit of a recurrence such that incrementing by Step cannot cause
1311 // unsigned overflow as long as the value of the recurrence within the loop does
1312 // not exceed this limit before incrementing.
getUnsignedOverflowLimitForStep(const SCEV * Step,ICmpInst::Predicate * Pred,ScalarEvolution * SE)1313 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1314 ICmpInst::Predicate *Pred,
1315 ScalarEvolution *SE) {
1316 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1317 *Pred = ICmpInst::ICMP_ULT;
1318
1319 return SE->getConstant(APInt::getMinValue(BitWidth) -
1320 SE->getUnsignedRangeMax(Step));
1321 }
1322
1323 namespace {
1324
1325 struct ExtendOpTraitsBase {
1326 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1327 unsigned);
1328 };
1329
1330 // Used to make code generic over signed and unsigned overflow.
1331 template <typename ExtendOp> struct ExtendOpTraits {
1332 // Members present:
1333 //
1334 // static const SCEV::NoWrapFlags WrapType;
1335 //
1336 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1337 //
1338 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1339 // ICmpInst::Predicate *Pred,
1340 // ScalarEvolution *SE);
1341 };
1342
1343 template <>
1344 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1345 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1346
1347 static const GetExtendExprTy GetExtendExpr;
1348
getOverflowLimitForStep__anon70687fab0511::ExtendOpTraits1349 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1350 ICmpInst::Predicate *Pred,
1351 ScalarEvolution *SE) {
1352 return getSignedOverflowLimitForStep(Step, Pred, SE);
1353 }
1354 };
1355
1356 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1357 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1358
1359 template <>
1360 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1361 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1362
1363 static const GetExtendExprTy GetExtendExpr;
1364
getOverflowLimitForStep__anon70687fab0511::ExtendOpTraits1365 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1366 ICmpInst::Predicate *Pred,
1367 ScalarEvolution *SE) {
1368 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1369 }
1370 };
1371
1372 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1373 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1374
1375 } // end anonymous namespace
1376
1377 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1378 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1379 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1380 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1381 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1382 // expression "Step + sext/zext(PreIncAR)" is congruent with
1383 // "sext/zext(PostIncAR)"
1384 template <typename ExtendOpTy>
getPreStartForExtend(const SCEVAddRecExpr * AR,Type * Ty,ScalarEvolution * SE,unsigned Depth)1385 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1386 ScalarEvolution *SE, unsigned Depth) {
1387 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1388 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1389
1390 const Loop *L = AR->getLoop();
1391 const SCEV *Start = AR->getStart();
1392 const SCEV *Step = AR->getStepRecurrence(*SE);
1393
1394 // Check for a simple looking step prior to loop entry.
1395 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1396 if (!SA)
1397 return nullptr;
1398
1399 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1400 // subtraction is expensive. For this purpose, perform a quick and dirty
1401 // difference, by checking for Step in the operand list.
1402 SmallVector<const SCEV *, 4> DiffOps;
1403 for (const SCEV *Op : SA->operands())
1404 if (Op != Step)
1405 DiffOps.push_back(Op);
1406
1407 if (DiffOps.size() == SA->getNumOperands())
1408 return nullptr;
1409
1410 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1411 // `Step`:
1412
1413 // 1. NSW/NUW flags on the step increment.
1414 auto PreStartFlags =
1415 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1416 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1417 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1418 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1419
1420 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1421 // "S+X does not sign/unsign-overflow".
1422 //
1423
1424 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1425 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1426 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1427 return PreStart;
1428
1429 // 2. Direct overflow check on the step operation's expression.
1430 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1431 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1432 const SCEV *OperandExtendedStart =
1433 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1434 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1435 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1436 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1437 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1438 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1439 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1440 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1441 }
1442 return PreStart;
1443 }
1444
1445 // 3. Loop precondition.
1446 ICmpInst::Predicate Pred;
1447 const SCEV *OverflowLimit =
1448 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1449
1450 if (OverflowLimit &&
1451 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1452 return PreStart;
1453
1454 return nullptr;
1455 }
1456
1457 // Get the normalized zero or sign extended expression for this AddRec's Start.
1458 template <typename ExtendOpTy>
getExtendAddRecStart(const SCEVAddRecExpr * AR,Type * Ty,ScalarEvolution * SE,unsigned Depth)1459 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1460 ScalarEvolution *SE,
1461 unsigned Depth) {
1462 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1463
1464 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1465 if (!PreStart)
1466 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1467
1468 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1469 Depth),
1470 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1471 }
1472
1473 // Try to prove away overflow by looking at "nearby" add recurrences. A
1474 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1475 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1476 //
1477 // Formally:
1478 //
1479 // {S,+,X} == {S-T,+,X} + T
1480 // => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1481 //
1482 // If ({S-T,+,X} + T) does not overflow ... (1)
1483 //
1484 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1485 //
1486 // If {S-T,+,X} does not overflow ... (2)
1487 //
1488 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1489 // == {Ext(S-T)+Ext(T),+,Ext(X)}
1490 //
1491 // If (S-T)+T does not overflow ... (3)
1492 //
1493 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1494 // == {Ext(S),+,Ext(X)} == LHS
1495 //
1496 // Thus, if (1), (2) and (3) are true for some T, then
1497 // Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1498 //
1499 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1500 // does not overflow" restricted to the 0th iteration. Therefore we only need
1501 // to check for (1) and (2).
1502 //
1503 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1504 // is `Delta` (defined below).
1505 template <typename ExtendOpTy>
proveNoWrapByVaryingStart(const SCEV * Start,const SCEV * Step,const Loop * L)1506 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1507 const SCEV *Step,
1508 const Loop *L) {
1509 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1510
1511 // We restrict `Start` to a constant to prevent SCEV from spending too much
1512 // time here. It is correct (but more expensive) to continue with a
1513 // non-constant `Start` and do a general SCEV subtraction to compute
1514 // `PreStart` below.
1515 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1516 if (!StartC)
1517 return false;
1518
1519 APInt StartAI = StartC->getAPInt();
1520
1521 for (unsigned Delta : {-2, -1, 1, 2}) {
1522 const SCEV *PreStart = getConstant(StartAI - Delta);
1523
1524 FoldingSetNodeID ID;
1525 ID.AddInteger(scAddRecExpr);
1526 ID.AddPointer(PreStart);
1527 ID.AddPointer(Step);
1528 ID.AddPointer(L);
1529 void *IP = nullptr;
1530 const auto *PreAR =
1531 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1532
1533 // Give up if we don't already have the add recurrence we need because
1534 // actually constructing an add recurrence is relatively expensive.
1535 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1536 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1537 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1538 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1539 DeltaS, &Pred, this);
1540 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1541 return true;
1542 }
1543 }
1544
1545 return false;
1546 }
1547
1548 // Finds an integer D for an expression (C + x + y + ...) such that the top
1549 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1550 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1551 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1552 // the (C + x + y + ...) expression is \p WholeAddExpr.
extractConstantWithoutWrapping(ScalarEvolution & SE,const SCEVConstant * ConstantTerm,const SCEVAddExpr * WholeAddExpr)1553 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1554 const SCEVConstant *ConstantTerm,
1555 const SCEVAddExpr *WholeAddExpr) {
1556 const APInt &C = ConstantTerm->getAPInt();
1557 const unsigned BitWidth = C.getBitWidth();
1558 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1559 uint32_t TZ = BitWidth;
1560 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1561 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1562 if (TZ) {
1563 // Set D to be as many least significant bits of C as possible while still
1564 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1565 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1566 }
1567 return APInt(BitWidth, 0);
1568 }
1569
1570 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1571 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1572 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1573 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
extractConstantWithoutWrapping(ScalarEvolution & SE,const APInt & ConstantStart,const SCEV * Step)1574 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1575 const APInt &ConstantStart,
1576 const SCEV *Step) {
1577 const unsigned BitWidth = ConstantStart.getBitWidth();
1578 const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1579 if (TZ)
1580 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1581 : ConstantStart;
1582 return APInt(BitWidth, 0);
1583 }
1584
insertFoldCacheEntry(const ScalarEvolution::FoldID & ID,const SCEV * S,DenseMap<ScalarEvolution::FoldID,const SCEV * > & FoldCache,DenseMap<const SCEV *,SmallVector<ScalarEvolution::FoldID,2>> & FoldCacheUser)1585 static void insertFoldCacheEntry(
1586 const ScalarEvolution::FoldID &ID, const SCEV *S,
1587 DenseMap<ScalarEvolution::FoldID, const SCEV *> &FoldCache,
1588 DenseMap<const SCEV *, SmallVector<ScalarEvolution::FoldID, 2>>
1589 &FoldCacheUser) {
1590 auto I = FoldCache.insert({ID, S});
1591 if (!I.second) {
1592 // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1593 // entry.
1594 auto &UserIDs = FoldCacheUser[I.first->second];
1595 assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
1596 for (unsigned I = 0; I != UserIDs.size(); ++I)
1597 if (UserIDs[I] == ID) {
1598 std::swap(UserIDs[I], UserIDs.back());
1599 break;
1600 }
1601 UserIDs.pop_back();
1602 I.first->second = S;
1603 }
1604 auto R = FoldCacheUser.insert({S, {}});
1605 R.first->second.push_back(ID);
1606 }
1607
1608 const SCEV *
getZeroExtendExpr(const SCEV * Op,Type * Ty,unsigned Depth)1609 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1610 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1611 "This is not an extending conversion!");
1612 assert(isSCEVable(Ty) &&
1613 "This is not a conversion to a SCEVable type!");
1614 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1615 Ty = getEffectiveSCEVType(Ty);
1616
1617 FoldID ID;
1618 ID.addInteger(scZeroExtend);
1619 ID.addPointer(Op);
1620 ID.addPointer(Ty);
1621 auto Iter = FoldCache.find(ID);
1622 if (Iter != FoldCache.end())
1623 return Iter->second;
1624
1625 const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1626 if (!isa<SCEVZeroExtendExpr>(S))
1627 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1628 return S;
1629 }
1630
getZeroExtendExprImpl(const SCEV * Op,Type * Ty,unsigned Depth)1631 const SCEV *ScalarEvolution::getZeroExtendExprImpl(const SCEV *Op, Type *Ty,
1632 unsigned Depth) {
1633 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1634 "This is not an extending conversion!");
1635 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1636 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1637
1638 // Fold if the operand is constant.
1639 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1640 return getConstant(
1641 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1642
1643 // zext(zext(x)) --> zext(x)
1644 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1645 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1646
1647 // Before doing any expensive analysis, check to see if we've already
1648 // computed a SCEV for this Op and Ty.
1649 FoldingSetNodeID ID;
1650 ID.AddInteger(scZeroExtend);
1651 ID.AddPointer(Op);
1652 ID.AddPointer(Ty);
1653 void *IP = nullptr;
1654 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1655 if (Depth > MaxCastDepth) {
1656 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1657 Op, Ty);
1658 UniqueSCEVs.InsertNode(S, IP);
1659 registerUser(S, Op);
1660 return S;
1661 }
1662
1663 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1664 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1665 // It's possible the bits taken off by the truncate were all zero bits. If
1666 // so, we should be able to simplify this further.
1667 const SCEV *X = ST->getOperand();
1668 ConstantRange CR = getUnsignedRange(X);
1669 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1670 unsigned NewBits = getTypeSizeInBits(Ty);
1671 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1672 CR.zextOrTrunc(NewBits)))
1673 return getTruncateOrZeroExtend(X, Ty, Depth);
1674 }
1675
1676 // If the input value is a chrec scev, and we can prove that the value
1677 // did not overflow the old, smaller, value, we can zero extend all of the
1678 // operands (often constants). This allows analysis of something like
1679 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1680 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1681 if (AR->isAffine()) {
1682 const SCEV *Start = AR->getStart();
1683 const SCEV *Step = AR->getStepRecurrence(*this);
1684 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1685 const Loop *L = AR->getLoop();
1686
1687 if (!AR->hasNoUnsignedWrap()) {
1688 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1689 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1690 }
1691
1692 // If we have special knowledge that this addrec won't overflow,
1693 // we don't need to do any further analysis.
1694 if (AR->hasNoUnsignedWrap()) {
1695 Start =
1696 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1697 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1698 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1699 }
1700
1701 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1702 // Note that this serves two purposes: It filters out loops that are
1703 // simply not analyzable, and it covers the case where this code is
1704 // being called from within backedge-taken count analysis, such that
1705 // attempting to ask for the backedge-taken count would likely result
1706 // in infinite recursion. In the later case, the analysis code will
1707 // cope with a conservative value, and it will take care to purge
1708 // that value once it has finished.
1709 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1710 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1711 // Manually compute the final value for AR, checking for overflow.
1712
1713 // Check whether the backedge-taken count can be losslessly casted to
1714 // the addrec's type. The count is always unsigned.
1715 const SCEV *CastedMaxBECount =
1716 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1717 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1718 CastedMaxBECount, MaxBECount->getType(), Depth);
1719 if (MaxBECount == RecastedMaxBECount) {
1720 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1721 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1722 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1723 SCEV::FlagAnyWrap, Depth + 1);
1724 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1725 SCEV::FlagAnyWrap,
1726 Depth + 1),
1727 WideTy, Depth + 1);
1728 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1729 const SCEV *WideMaxBECount =
1730 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1731 const SCEV *OperandExtendedAdd =
1732 getAddExpr(WideStart,
1733 getMulExpr(WideMaxBECount,
1734 getZeroExtendExpr(Step, WideTy, Depth + 1),
1735 SCEV::FlagAnyWrap, Depth + 1),
1736 SCEV::FlagAnyWrap, Depth + 1);
1737 if (ZAdd == OperandExtendedAdd) {
1738 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1739 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1740 // Return the expression with the addrec on the outside.
1741 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1742 Depth + 1);
1743 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1744 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1745 }
1746 // Similar to above, only this time treat the step value as signed.
1747 // This covers loops that count down.
1748 OperandExtendedAdd =
1749 getAddExpr(WideStart,
1750 getMulExpr(WideMaxBECount,
1751 getSignExtendExpr(Step, WideTy, Depth + 1),
1752 SCEV::FlagAnyWrap, Depth + 1),
1753 SCEV::FlagAnyWrap, Depth + 1);
1754 if (ZAdd == OperandExtendedAdd) {
1755 // Cache knowledge of AR NW, which is propagated to this AddRec.
1756 // Negative step causes unsigned wrap, but it still can't self-wrap.
1757 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1758 // Return the expression with the addrec on the outside.
1759 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1760 Depth + 1);
1761 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1762 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1763 }
1764 }
1765 }
1766
1767 // Normally, in the cases we can prove no-overflow via a
1768 // backedge guarding condition, we can also compute a backedge
1769 // taken count for the loop. The exceptions are assumptions and
1770 // guards present in the loop -- SCEV is not great at exploiting
1771 // these to compute max backedge taken counts, but can still use
1772 // these to prove lack of overflow. Use this fact to avoid
1773 // doing extra work that may not pay off.
1774 if (!isa<SCEVCouldNotCompute>(MaxBECount) || !AC.assumptions().empty()) {
1775
1776 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1777 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1778 if (AR->hasNoUnsignedWrap()) {
1779 // Same as nuw case above - duplicated here to avoid a compile time
1780 // issue. It's not clear that the order of checks does matter, but
1781 // it's one of two issue possible causes for a change which was
1782 // reverted. Be conservative for the moment.
1783 Start =
1784 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1785 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1786 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1787 }
1788
1789 // For a negative step, we can extend the operands iff doing so only
1790 // traverses values in the range zext([0,UINT_MAX]).
1791 if (isKnownNegative(Step)) {
1792 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1793 getSignedRangeMin(Step));
1794 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1795 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1796 // Cache knowledge of AR NW, which is propagated to this
1797 // AddRec. Negative step causes unsigned wrap, but it
1798 // still can't self-wrap.
1799 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1800 // Return the expression with the addrec on the outside.
1801 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1802 Depth + 1);
1803 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1804 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1805 }
1806 }
1807 }
1808
1809 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1810 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1811 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1812 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1813 const APInt &C = SC->getAPInt();
1814 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1815 if (D != 0) {
1816 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1817 const SCEV *SResidual =
1818 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1819 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1820 return getAddExpr(SZExtD, SZExtR,
1821 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1822 Depth + 1);
1823 }
1824 }
1825
1826 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1827 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1828 Start =
1829 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1830 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1831 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1832 }
1833 }
1834
1835 // zext(A % B) --> zext(A) % zext(B)
1836 {
1837 const SCEV *LHS;
1838 const SCEV *RHS;
1839 if (matchURem(Op, LHS, RHS))
1840 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1841 getZeroExtendExpr(RHS, Ty, Depth + 1));
1842 }
1843
1844 // zext(A / B) --> zext(A) / zext(B).
1845 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1846 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1847 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1848
1849 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1850 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1851 if (SA->hasNoUnsignedWrap()) {
1852 // If the addition does not unsign overflow then we can, by definition,
1853 // commute the zero extension with the addition operation.
1854 SmallVector<const SCEV *, 4> Ops;
1855 for (const auto *Op : SA->operands())
1856 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1857 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1858 }
1859
1860 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1861 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1862 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1863 //
1864 // Often address arithmetics contain expressions like
1865 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1866 // This transformation is useful while proving that such expressions are
1867 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1868 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1869 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1870 if (D != 0) {
1871 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1872 const SCEV *SResidual =
1873 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1874 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1875 return getAddExpr(SZExtD, SZExtR,
1876 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1877 Depth + 1);
1878 }
1879 }
1880 }
1881
1882 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1883 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1884 if (SM->hasNoUnsignedWrap()) {
1885 // If the multiply does not unsign overflow then we can, by definition,
1886 // commute the zero extension with the multiply operation.
1887 SmallVector<const SCEV *, 4> Ops;
1888 for (const auto *Op : SM->operands())
1889 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1890 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1891 }
1892
1893 // zext(2^K * (trunc X to iN)) to iM ->
1894 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1895 //
1896 // Proof:
1897 //
1898 // zext(2^K * (trunc X to iN)) to iM
1899 // = zext((trunc X to iN) << K) to iM
1900 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1901 // (because shl removes the top K bits)
1902 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1903 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1904 //
1905 if (SM->getNumOperands() == 2)
1906 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1907 if (MulLHS->getAPInt().isPowerOf2())
1908 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1909 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1910 MulLHS->getAPInt().logBase2();
1911 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1912 return getMulExpr(
1913 getZeroExtendExpr(MulLHS, Ty),
1914 getZeroExtendExpr(
1915 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1916 SCEV::FlagNUW, Depth + 1);
1917 }
1918 }
1919
1920 // The cast wasn't folded; create an explicit cast node.
1921 // Recompute the insert position, as it may have been invalidated.
1922 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1923 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1924 Op, Ty);
1925 UniqueSCEVs.InsertNode(S, IP);
1926 registerUser(S, Op);
1927 return S;
1928 }
1929
1930 const SCEV *
getSignExtendExpr(const SCEV * Op,Type * Ty,unsigned Depth)1931 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1932 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1933 "This is not an extending conversion!");
1934 assert(isSCEVable(Ty) &&
1935 "This is not a conversion to a SCEVable type!");
1936 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1937 Ty = getEffectiveSCEVType(Ty);
1938
1939 FoldID ID;
1940 ID.addInteger(scSignExtend);
1941 ID.addPointer(Op);
1942 ID.addPointer(Ty);
1943 auto Iter = FoldCache.find(ID);
1944 if (Iter != FoldCache.end())
1945 return Iter->second;
1946
1947 const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
1948 if (!isa<SCEVSignExtendExpr>(S))
1949 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1950 return S;
1951 }
1952
getSignExtendExprImpl(const SCEV * Op,Type * Ty,unsigned Depth)1953 const SCEV *ScalarEvolution::getSignExtendExprImpl(const SCEV *Op, Type *Ty,
1954 unsigned Depth) {
1955 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1956 "This is not an extending conversion!");
1957 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1958 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1959 Ty = getEffectiveSCEVType(Ty);
1960
1961 // Fold if the operand is constant.
1962 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1963 return getConstant(
1964 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1965
1966 // sext(sext(x)) --> sext(x)
1967 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1968 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1969
1970 // sext(zext(x)) --> zext(x)
1971 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1972 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1973
1974 // Before doing any expensive analysis, check to see if we've already
1975 // computed a SCEV for this Op and Ty.
1976 FoldingSetNodeID ID;
1977 ID.AddInteger(scSignExtend);
1978 ID.AddPointer(Op);
1979 ID.AddPointer(Ty);
1980 void *IP = nullptr;
1981 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1982 // Limit recursion depth.
1983 if (Depth > MaxCastDepth) {
1984 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1985 Op, Ty);
1986 UniqueSCEVs.InsertNode(S, IP);
1987 registerUser(S, Op);
1988 return S;
1989 }
1990
1991 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1992 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1993 // It's possible the bits taken off by the truncate were all sign bits. If
1994 // so, we should be able to simplify this further.
1995 const SCEV *X = ST->getOperand();
1996 ConstantRange CR = getSignedRange(X);
1997 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1998 unsigned NewBits = getTypeSizeInBits(Ty);
1999 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
2000 CR.sextOrTrunc(NewBits)))
2001 return getTruncateOrSignExtend(X, Ty, Depth);
2002 }
2003
2004 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
2005 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
2006 if (SA->hasNoSignedWrap()) {
2007 // If the addition does not sign overflow then we can, by definition,
2008 // commute the sign extension with the addition operation.
2009 SmallVector<const SCEV *, 4> Ops;
2010 for (const auto *Op : SA->operands())
2011 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
2012 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
2013 }
2014
2015 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
2016 // if D + (C - D + x + y + ...) could be proven to not signed wrap
2017 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
2018 //
2019 // For instance, this will bring two seemingly different expressions:
2020 // 1 + sext(5 + 20 * %x + 24 * %y) and
2021 // sext(6 + 20 * %x + 24 * %y)
2022 // to the same form:
2023 // 2 + sext(4 + 20 * %x + 24 * %y)
2024 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
2025 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
2026 if (D != 0) {
2027 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2028 const SCEV *SResidual =
2029 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
2030 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2031 return getAddExpr(SSExtD, SSExtR,
2032 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2033 Depth + 1);
2034 }
2035 }
2036 }
2037 // If the input value is a chrec scev, and we can prove that the value
2038 // did not overflow the old, smaller, value, we can sign extend all of the
2039 // operands (often constants). This allows analysis of something like
2040 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
2041 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
2042 if (AR->isAffine()) {
2043 const SCEV *Start = AR->getStart();
2044 const SCEV *Step = AR->getStepRecurrence(*this);
2045 unsigned BitWidth = getTypeSizeInBits(AR->getType());
2046 const Loop *L = AR->getLoop();
2047
2048 if (!AR->hasNoSignedWrap()) {
2049 auto NewFlags = proveNoWrapViaConstantRanges(AR);
2050 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2051 }
2052
2053 // If we have special knowledge that this addrec won't overflow,
2054 // we don't need to do any further analysis.
2055 if (AR->hasNoSignedWrap()) {
2056 Start =
2057 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2058 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2059 return getAddRecExpr(Start, Step, L, SCEV::FlagNSW);
2060 }
2061
2062 // Check whether the backedge-taken count is SCEVCouldNotCompute.
2063 // Note that this serves two purposes: It filters out loops that are
2064 // simply not analyzable, and it covers the case where this code is
2065 // being called from within backedge-taken count analysis, such that
2066 // attempting to ask for the backedge-taken count would likely result
2067 // in infinite recursion. In the later case, the analysis code will
2068 // cope with a conservative value, and it will take care to purge
2069 // that value once it has finished.
2070 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2071 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2072 // Manually compute the final value for AR, checking for
2073 // overflow.
2074
2075 // Check whether the backedge-taken count can be losslessly casted to
2076 // the addrec's type. The count is always unsigned.
2077 const SCEV *CastedMaxBECount =
2078 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2079 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2080 CastedMaxBECount, MaxBECount->getType(), Depth);
2081 if (MaxBECount == RecastedMaxBECount) {
2082 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2083 // Check whether Start+Step*MaxBECount has no signed overflow.
2084 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2085 SCEV::FlagAnyWrap, Depth + 1);
2086 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2087 SCEV::FlagAnyWrap,
2088 Depth + 1),
2089 WideTy, Depth + 1);
2090 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2091 const SCEV *WideMaxBECount =
2092 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2093 const SCEV *OperandExtendedAdd =
2094 getAddExpr(WideStart,
2095 getMulExpr(WideMaxBECount,
2096 getSignExtendExpr(Step, WideTy, Depth + 1),
2097 SCEV::FlagAnyWrap, Depth + 1),
2098 SCEV::FlagAnyWrap, Depth + 1);
2099 if (SAdd == OperandExtendedAdd) {
2100 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2101 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2102 // Return the expression with the addrec on the outside.
2103 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2104 Depth + 1);
2105 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2106 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2107 }
2108 // Similar to above, only this time treat the step value as unsigned.
2109 // This covers loops that count up with an unsigned step.
2110 OperandExtendedAdd =
2111 getAddExpr(WideStart,
2112 getMulExpr(WideMaxBECount,
2113 getZeroExtendExpr(Step, WideTy, Depth + 1),
2114 SCEV::FlagAnyWrap, Depth + 1),
2115 SCEV::FlagAnyWrap, Depth + 1);
2116 if (SAdd == OperandExtendedAdd) {
2117 // If AR wraps around then
2118 //
2119 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2120 // => SAdd != OperandExtendedAdd
2121 //
2122 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2123 // (SAdd == OperandExtendedAdd => AR is NW)
2124
2125 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2126
2127 // Return the expression with the addrec on the outside.
2128 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2129 Depth + 1);
2130 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
2131 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2132 }
2133 }
2134 }
2135
2136 auto NewFlags = proveNoSignedWrapViaInduction(AR);
2137 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2138 if (AR->hasNoSignedWrap()) {
2139 // Same as nsw case above - duplicated here to avoid a compile time
2140 // issue. It's not clear that the order of checks does matter, but
2141 // it's one of two issue possible causes for a change which was
2142 // reverted. Be conservative for the moment.
2143 Start =
2144 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2145 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2146 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2147 }
2148
2149 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2150 // if D + (C - D + Step * n) could be proven to not signed wrap
2151 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2152 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2153 const APInt &C = SC->getAPInt();
2154 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2155 if (D != 0) {
2156 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2157 const SCEV *SResidual =
2158 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2159 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2160 return getAddExpr(SSExtD, SSExtR,
2161 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2162 Depth + 1);
2163 }
2164 }
2165
2166 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2167 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2168 Start =
2169 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2170 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2171 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2172 }
2173 }
2174
2175 // If the input value is provably positive and we could not simplify
2176 // away the sext build a zext instead.
2177 if (isKnownNonNegative(Op))
2178 return getZeroExtendExpr(Op, Ty, Depth + 1);
2179
2180 // The cast wasn't folded; create an explicit cast node.
2181 // Recompute the insert position, as it may have been invalidated.
2182 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2183 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2184 Op, Ty);
2185 UniqueSCEVs.InsertNode(S, IP);
2186 registerUser(S, { Op });
2187 return S;
2188 }
2189
getCastExpr(SCEVTypes Kind,const SCEV * Op,Type * Ty)2190 const SCEV *ScalarEvolution::getCastExpr(SCEVTypes Kind, const SCEV *Op,
2191 Type *Ty) {
2192 switch (Kind) {
2193 case scTruncate:
2194 return getTruncateExpr(Op, Ty);
2195 case scZeroExtend:
2196 return getZeroExtendExpr(Op, Ty);
2197 case scSignExtend:
2198 return getSignExtendExpr(Op, Ty);
2199 case scPtrToInt:
2200 return getPtrToIntExpr(Op, Ty);
2201 default:
2202 llvm_unreachable("Not a SCEV cast expression!");
2203 }
2204 }
2205
2206 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2207 /// unspecified bits out to the given type.
getAnyExtendExpr(const SCEV * Op,Type * Ty)2208 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2209 Type *Ty) {
2210 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2211 "This is not an extending conversion!");
2212 assert(isSCEVable(Ty) &&
2213 "This is not a conversion to a SCEVable type!");
2214 Ty = getEffectiveSCEVType(Ty);
2215
2216 // Sign-extend negative constants.
2217 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2218 if (SC->getAPInt().isNegative())
2219 return getSignExtendExpr(Op, Ty);
2220
2221 // Peel off a truncate cast.
2222 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2223 const SCEV *NewOp = T->getOperand();
2224 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2225 return getAnyExtendExpr(NewOp, Ty);
2226 return getTruncateOrNoop(NewOp, Ty);
2227 }
2228
2229 // Next try a zext cast. If the cast is folded, use it.
2230 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2231 if (!isa<SCEVZeroExtendExpr>(ZExt))
2232 return ZExt;
2233
2234 // Next try a sext cast. If the cast is folded, use it.
2235 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2236 if (!isa<SCEVSignExtendExpr>(SExt))
2237 return SExt;
2238
2239 // Force the cast to be folded into the operands of an addrec.
2240 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2241 SmallVector<const SCEV *, 4> Ops;
2242 for (const SCEV *Op : AR->operands())
2243 Ops.push_back(getAnyExtendExpr(Op, Ty));
2244 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2245 }
2246
2247 // If the expression is obviously signed, use the sext cast value.
2248 if (isa<SCEVSMaxExpr>(Op))
2249 return SExt;
2250
2251 // Absent any other information, use the zext cast value.
2252 return ZExt;
2253 }
2254
2255 /// Process the given Ops list, which is a list of operands to be added under
2256 /// the given scale, update the given map. This is a helper function for
2257 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2258 /// that would form an add expression like this:
2259 ///
2260 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2261 ///
2262 /// where A and B are constants, update the map with these values:
2263 ///
2264 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2265 ///
2266 /// and add 13 + A*B*29 to AccumulatedConstant.
2267 /// This will allow getAddRecExpr to produce this:
2268 ///
2269 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2270 ///
2271 /// This form often exposes folding opportunities that are hidden in
2272 /// the original operand list.
2273 ///
2274 /// Return true iff it appears that any interesting folding opportunities
2275 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2276 /// the common case where no interesting opportunities are present, and
2277 /// is also used as a check to avoid infinite recursion.
2278 static bool
CollectAddOperandsWithScales(DenseMap<const SCEV *,APInt> & M,SmallVectorImpl<const SCEV * > & NewOps,APInt & AccumulatedConstant,ArrayRef<const SCEV * > Ops,const APInt & Scale,ScalarEvolution & SE)2279 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2280 SmallVectorImpl<const SCEV *> &NewOps,
2281 APInt &AccumulatedConstant,
2282 ArrayRef<const SCEV *> Ops, const APInt &Scale,
2283 ScalarEvolution &SE) {
2284 bool Interesting = false;
2285
2286 // Iterate over the add operands. They are sorted, with constants first.
2287 unsigned i = 0;
2288 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2289 ++i;
2290 // Pull a buried constant out to the outside.
2291 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2292 Interesting = true;
2293 AccumulatedConstant += Scale * C->getAPInt();
2294 }
2295
2296 // Next comes everything else. We're especially interested in multiplies
2297 // here, but they're in the middle, so just visit the rest with one loop.
2298 for (; i != Ops.size(); ++i) {
2299 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2300 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2301 APInt NewScale =
2302 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2303 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2304 // A multiplication of a constant with another add; recurse.
2305 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2306 Interesting |=
2307 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2308 Add->operands(), NewScale, SE);
2309 } else {
2310 // A multiplication of a constant with some other value. Update
2311 // the map.
2312 SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands()));
2313 const SCEV *Key = SE.getMulExpr(MulOps);
2314 auto Pair = M.insert({Key, NewScale});
2315 if (Pair.second) {
2316 NewOps.push_back(Pair.first->first);
2317 } else {
2318 Pair.first->second += NewScale;
2319 // The map already had an entry for this value, which may indicate
2320 // a folding opportunity.
2321 Interesting = true;
2322 }
2323 }
2324 } else {
2325 // An ordinary operand. Update the map.
2326 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2327 M.insert({Ops[i], Scale});
2328 if (Pair.second) {
2329 NewOps.push_back(Pair.first->first);
2330 } else {
2331 Pair.first->second += Scale;
2332 // The map already had an entry for this value, which may indicate
2333 // a folding opportunity.
2334 Interesting = true;
2335 }
2336 }
2337 }
2338
2339 return Interesting;
2340 }
2341
willNotOverflow(Instruction::BinaryOps BinOp,bool Signed,const SCEV * LHS,const SCEV * RHS,const Instruction * CtxI)2342 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed,
2343 const SCEV *LHS, const SCEV *RHS,
2344 const Instruction *CtxI) {
2345 const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *,
2346 SCEV::NoWrapFlags, unsigned);
2347 switch (BinOp) {
2348 default:
2349 llvm_unreachable("Unsupported binary op");
2350 case Instruction::Add:
2351 Operation = &ScalarEvolution::getAddExpr;
2352 break;
2353 case Instruction::Sub:
2354 Operation = &ScalarEvolution::getMinusSCEV;
2355 break;
2356 case Instruction::Mul:
2357 Operation = &ScalarEvolution::getMulExpr;
2358 break;
2359 }
2360
2361 const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
2362 Signed ? &ScalarEvolution::getSignExtendExpr
2363 : &ScalarEvolution::getZeroExtendExpr;
2364
2365 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2366 auto *NarrowTy = cast<IntegerType>(LHS->getType());
2367 auto *WideTy =
2368 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2369
2370 const SCEV *A = (this->*Extension)(
2371 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2372 const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2373 const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2374 const SCEV *B = (this->*Operation)(LHSB, RHSB, SCEV::FlagAnyWrap, 0);
2375 if (A == B)
2376 return true;
2377 // Can we use context to prove the fact we need?
2378 if (!CtxI)
2379 return false;
2380 // We can prove that add(x, constant) doesn't wrap if isKnownPredicateAt can
2381 // guarantee that x <= max_int - constant at the given context.
2382 // TODO: Support other operations.
2383 if (BinOp != Instruction::Add)
2384 return false;
2385 auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2386 // TODO: Lift this limitation.
2387 if (!RHSC)
2388 return false;
2389 APInt C = RHSC->getAPInt();
2390 // TODO: Also lift this limitation.
2391 if (Signed && C.isNegative())
2392 return false;
2393 unsigned NumBits = C.getBitWidth();
2394 APInt Max =
2395 Signed ? APInt::getSignedMaxValue(NumBits) : APInt::getMaxValue(NumBits);
2396 APInt Limit = Max - C;
2397 ICmpInst::Predicate Pred = Signed ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
2398 return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2399 }
2400
2401 std::optional<SCEV::NoWrapFlags>
getStrengthenedNoWrapFlagsFromBinOp(const OverflowingBinaryOperator * OBO)2402 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp(
2403 const OverflowingBinaryOperator *OBO) {
2404 // It cannot be done any better.
2405 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2406 return std::nullopt;
2407
2408 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2409
2410 if (OBO->hasNoUnsignedWrap())
2411 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2412 if (OBO->hasNoSignedWrap())
2413 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2414
2415 bool Deduced = false;
2416
2417 if (OBO->getOpcode() != Instruction::Add &&
2418 OBO->getOpcode() != Instruction::Sub &&
2419 OBO->getOpcode() != Instruction::Mul)
2420 return std::nullopt;
2421
2422 const SCEV *LHS = getSCEV(OBO->getOperand(0));
2423 const SCEV *RHS = getSCEV(OBO->getOperand(1));
2424
2425 const Instruction *CtxI =
2426 UseContextForNoWrapFlagInference ? dyn_cast<Instruction>(OBO) : nullptr;
2427 if (!OBO->hasNoUnsignedWrap() &&
2428 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2429 /* Signed */ false, LHS, RHS, CtxI)) {
2430 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2431 Deduced = true;
2432 }
2433
2434 if (!OBO->hasNoSignedWrap() &&
2435 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2436 /* Signed */ true, LHS, RHS, CtxI)) {
2437 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2438 Deduced = true;
2439 }
2440
2441 if (Deduced)
2442 return Flags;
2443 return std::nullopt;
2444 }
2445
2446 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2447 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2448 // can't-overflow flags for the operation if possible.
2449 static SCEV::NoWrapFlags
StrengthenNoWrapFlags(ScalarEvolution * SE,SCEVTypes Type,const ArrayRef<const SCEV * > Ops,SCEV::NoWrapFlags Flags)2450 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2451 const ArrayRef<const SCEV *> Ops,
2452 SCEV::NoWrapFlags Flags) {
2453 using namespace std::placeholders;
2454
2455 using OBO = OverflowingBinaryOperator;
2456
2457 bool CanAnalyze =
2458 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2459 (void)CanAnalyze;
2460 assert(CanAnalyze && "don't call from other places!");
2461
2462 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2463 SCEV::NoWrapFlags SignOrUnsignWrap =
2464 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2465
2466 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2467 auto IsKnownNonNegative = [&](const SCEV *S) {
2468 return SE->isKnownNonNegative(S);
2469 };
2470
2471 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2472 Flags =
2473 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2474
2475 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2476
2477 if (SignOrUnsignWrap != SignOrUnsignMask &&
2478 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2479 isa<SCEVConstant>(Ops[0])) {
2480
2481 auto Opcode = [&] {
2482 switch (Type) {
2483 case scAddExpr:
2484 return Instruction::Add;
2485 case scMulExpr:
2486 return Instruction::Mul;
2487 default:
2488 llvm_unreachable("Unexpected SCEV op.");
2489 }
2490 }();
2491
2492 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2493
2494 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2495 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2496 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2497 Opcode, C, OBO::NoSignedWrap);
2498 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2499 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2500 }
2501
2502 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2503 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2504 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2505 Opcode, C, OBO::NoUnsignedWrap);
2506 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2507 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2508 }
2509 }
2510
2511 // <0,+,nonnegative><nw> is also nuw
2512 // TODO: Add corresponding nsw case
2513 if (Type == scAddRecExpr && ScalarEvolution::hasFlags(Flags, SCEV::FlagNW) &&
2514 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2515 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2516 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2517
2518 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2519 if (Type == scMulExpr && !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) &&
2520 Ops.size() == 2) {
2521 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2522 if (UDiv->getOperand(1) == Ops[1])
2523 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2524 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2525 if (UDiv->getOperand(1) == Ops[0])
2526 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2527 }
2528
2529 return Flags;
2530 }
2531
isAvailableAtLoopEntry(const SCEV * S,const Loop * L)2532 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2533 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2534 }
2535
2536 /// Get a canonical add expression, or something simpler if possible.
getAddExpr(SmallVectorImpl<const SCEV * > & Ops,SCEV::NoWrapFlags OrigFlags,unsigned Depth)2537 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2538 SCEV::NoWrapFlags OrigFlags,
2539 unsigned Depth) {
2540 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2541 "only nuw or nsw allowed");
2542 assert(!Ops.empty() && "Cannot get empty add!");
2543 if (Ops.size() == 1) return Ops[0];
2544 #ifndef NDEBUG
2545 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2546 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2547 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2548 "SCEVAddExpr operand types don't match!");
2549 unsigned NumPtrs = count_if(
2550 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2551 assert(NumPtrs <= 1 && "add has at most one pointer operand");
2552 #endif
2553
2554 // Sort by complexity, this groups all similar expression types together.
2555 GroupByComplexity(Ops, &LI, DT);
2556
2557 // If there are any constants, fold them together.
2558 unsigned Idx = 0;
2559 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2560 ++Idx;
2561 assert(Idx < Ops.size());
2562 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2563 // We found two constants, fold them together!
2564 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2565 if (Ops.size() == 2) return Ops[0];
2566 Ops.erase(Ops.begin()+1); // Erase the folded element
2567 LHSC = cast<SCEVConstant>(Ops[0]);
2568 }
2569
2570 // If we are left with a constant zero being added, strip it off.
2571 if (LHSC->getValue()->isZero()) {
2572 Ops.erase(Ops.begin());
2573 --Idx;
2574 }
2575
2576 if (Ops.size() == 1) return Ops[0];
2577 }
2578
2579 // Delay expensive flag strengthening until necessary.
2580 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2581 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2582 };
2583
2584 // Limit recursion calls depth.
2585 if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2586 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2587
2588 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2589 // Don't strengthen flags if we have no new information.
2590 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2591 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2592 Add->setNoWrapFlags(ComputeFlags(Ops));
2593 return S;
2594 }
2595
2596 // Okay, check to see if the same value occurs in the operand list more than
2597 // once. If so, merge them together into an multiply expression. Since we
2598 // sorted the list, these values are required to be adjacent.
2599 Type *Ty = Ops[0]->getType();
2600 bool FoundMatch = false;
2601 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2602 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2603 // Scan ahead to count how many equal operands there are.
2604 unsigned Count = 2;
2605 while (i+Count != e && Ops[i+Count] == Ops[i])
2606 ++Count;
2607 // Merge the values into a multiply.
2608 const SCEV *Scale = getConstant(Ty, Count);
2609 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2610 if (Ops.size() == Count)
2611 return Mul;
2612 Ops[i] = Mul;
2613 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2614 --i; e -= Count - 1;
2615 FoundMatch = true;
2616 }
2617 if (FoundMatch)
2618 return getAddExpr(Ops, OrigFlags, Depth + 1);
2619
2620 // Check for truncates. If all the operands are truncated from the same
2621 // type, see if factoring out the truncate would permit the result to be
2622 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2623 // if the contents of the resulting outer trunc fold to something simple.
2624 auto FindTruncSrcType = [&]() -> Type * {
2625 // We're ultimately looking to fold an addrec of truncs and muls of only
2626 // constants and truncs, so if we find any other types of SCEV
2627 // as operands of the addrec then we bail and return nullptr here.
2628 // Otherwise, we return the type of the operand of a trunc that we find.
2629 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2630 return T->getOperand()->getType();
2631 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2632 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2633 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2634 return T->getOperand()->getType();
2635 }
2636 return nullptr;
2637 };
2638 if (auto *SrcType = FindTruncSrcType()) {
2639 SmallVector<const SCEV *, 8> LargeOps;
2640 bool Ok = true;
2641 // Check all the operands to see if they can be represented in the
2642 // source type of the truncate.
2643 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2644 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2645 if (T->getOperand()->getType() != SrcType) {
2646 Ok = false;
2647 break;
2648 }
2649 LargeOps.push_back(T->getOperand());
2650 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2651 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2652 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2653 SmallVector<const SCEV *, 8> LargeMulOps;
2654 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2655 if (const SCEVTruncateExpr *T =
2656 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2657 if (T->getOperand()->getType() != SrcType) {
2658 Ok = false;
2659 break;
2660 }
2661 LargeMulOps.push_back(T->getOperand());
2662 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2663 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2664 } else {
2665 Ok = false;
2666 break;
2667 }
2668 }
2669 if (Ok)
2670 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2671 } else {
2672 Ok = false;
2673 break;
2674 }
2675 }
2676 if (Ok) {
2677 // Evaluate the expression in the larger type.
2678 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2679 // If it folds to something simple, use it. Otherwise, don't.
2680 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2681 return getTruncateExpr(Fold, Ty);
2682 }
2683 }
2684
2685 if (Ops.size() == 2) {
2686 // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2687 // C2 can be folded in a way that allows retaining wrapping flags of (X +
2688 // C1).
2689 const SCEV *A = Ops[0];
2690 const SCEV *B = Ops[1];
2691 auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2692 auto *C = dyn_cast<SCEVConstant>(A);
2693 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2694 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2695 auto C2 = C->getAPInt();
2696 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2697
2698 APInt ConstAdd = C1 + C2;
2699 auto AddFlags = AddExpr->getNoWrapFlags();
2700 // Adding a smaller constant is NUW if the original AddExpr was NUW.
2701 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNUW) &&
2702 ConstAdd.ule(C1)) {
2703 PreservedFlags =
2704 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW);
2705 }
2706
2707 // Adding a constant with the same sign and small magnitude is NSW, if the
2708 // original AddExpr was NSW.
2709 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNSW) &&
2710 C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2711 ConstAdd.abs().ule(C1.abs())) {
2712 PreservedFlags =
2713 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW);
2714 }
2715
2716 if (PreservedFlags != SCEV::FlagAnyWrap) {
2717 SmallVector<const SCEV *, 4> NewOps(AddExpr->operands());
2718 NewOps[0] = getConstant(ConstAdd);
2719 return getAddExpr(NewOps, PreservedFlags);
2720 }
2721 }
2722 }
2723
2724 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2725 if (Ops.size() == 2) {
2726 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[0]);
2727 if (Mul && Mul->getNumOperands() == 2 &&
2728 Mul->getOperand(0)->isAllOnesValue()) {
2729 const SCEV *X;
2730 const SCEV *Y;
2731 if (matchURem(Mul->getOperand(1), X, Y) && X == Ops[1]) {
2732 return getMulExpr(Y, getUDivExpr(X, Y));
2733 }
2734 }
2735 }
2736
2737 // Skip past any other cast SCEVs.
2738 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2739 ++Idx;
2740
2741 // If there are add operands they would be next.
2742 if (Idx < Ops.size()) {
2743 bool DeletedAdd = false;
2744 // If the original flags and all inlined SCEVAddExprs are NUW, use the
2745 // common NUW flag for expression after inlining. Other flags cannot be
2746 // preserved, because they may depend on the original order of operations.
2747 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2748 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2749 if (Ops.size() > AddOpsInlineThreshold ||
2750 Add->getNumOperands() > AddOpsInlineThreshold)
2751 break;
2752 // If we have an add, expand the add operands onto the end of the operands
2753 // list.
2754 Ops.erase(Ops.begin()+Idx);
2755 append_range(Ops, Add->operands());
2756 DeletedAdd = true;
2757 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2758 }
2759
2760 // If we deleted at least one add, we added operands to the end of the list,
2761 // and they are not necessarily sorted. Recurse to resort and resimplify
2762 // any operands we just acquired.
2763 if (DeletedAdd)
2764 return getAddExpr(Ops, CommonFlags, Depth + 1);
2765 }
2766
2767 // Skip over the add expression until we get to a multiply.
2768 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2769 ++Idx;
2770
2771 // Check to see if there are any folding opportunities present with
2772 // operands multiplied by constant values.
2773 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2774 uint64_t BitWidth = getTypeSizeInBits(Ty);
2775 DenseMap<const SCEV *, APInt> M;
2776 SmallVector<const SCEV *, 8> NewOps;
2777 APInt AccumulatedConstant(BitWidth, 0);
2778 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2779 Ops, APInt(BitWidth, 1), *this)) {
2780 struct APIntCompare {
2781 bool operator()(const APInt &LHS, const APInt &RHS) const {
2782 return LHS.ult(RHS);
2783 }
2784 };
2785
2786 // Some interesting folding opportunity is present, so its worthwhile to
2787 // re-generate the operands list. Group the operands by constant scale,
2788 // to avoid multiplying by the same constant scale multiple times.
2789 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2790 for (const SCEV *NewOp : NewOps)
2791 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2792 // Re-generate the operands list.
2793 Ops.clear();
2794 if (AccumulatedConstant != 0)
2795 Ops.push_back(getConstant(AccumulatedConstant));
2796 for (auto &MulOp : MulOpLists) {
2797 if (MulOp.first == 1) {
2798 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2799 } else if (MulOp.first != 0) {
2800 Ops.push_back(getMulExpr(
2801 getConstant(MulOp.first),
2802 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2803 SCEV::FlagAnyWrap, Depth + 1));
2804 }
2805 }
2806 if (Ops.empty())
2807 return getZero(Ty);
2808 if (Ops.size() == 1)
2809 return Ops[0];
2810 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2811 }
2812 }
2813
2814 // If we are adding something to a multiply expression, make sure the
2815 // something is not already an operand of the multiply. If so, merge it into
2816 // the multiply.
2817 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2818 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2819 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2820 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2821 if (isa<SCEVConstant>(MulOpSCEV))
2822 continue;
2823 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2824 if (MulOpSCEV == Ops[AddOp]) {
2825 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2826 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2827 if (Mul->getNumOperands() != 2) {
2828 // If the multiply has more than two operands, we must get the
2829 // Y*Z term.
2830 SmallVector<const SCEV *, 4> MulOps(
2831 Mul->operands().take_front(MulOp));
2832 append_range(MulOps, Mul->operands().drop_front(MulOp + 1));
2833 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2834 }
2835 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2836 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2837 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2838 SCEV::FlagAnyWrap, Depth + 1);
2839 if (Ops.size() == 2) return OuterMul;
2840 if (AddOp < Idx) {
2841 Ops.erase(Ops.begin()+AddOp);
2842 Ops.erase(Ops.begin()+Idx-1);
2843 } else {
2844 Ops.erase(Ops.begin()+Idx);
2845 Ops.erase(Ops.begin()+AddOp-1);
2846 }
2847 Ops.push_back(OuterMul);
2848 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2849 }
2850
2851 // Check this multiply against other multiplies being added together.
2852 for (unsigned OtherMulIdx = Idx+1;
2853 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2854 ++OtherMulIdx) {
2855 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2856 // If MulOp occurs in OtherMul, we can fold the two multiplies
2857 // together.
2858 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2859 OMulOp != e; ++OMulOp)
2860 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2861 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2862 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2863 if (Mul->getNumOperands() != 2) {
2864 SmallVector<const SCEV *, 4> MulOps(
2865 Mul->operands().take_front(MulOp));
2866 append_range(MulOps, Mul->operands().drop_front(MulOp+1));
2867 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2868 }
2869 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2870 if (OtherMul->getNumOperands() != 2) {
2871 SmallVector<const SCEV *, 4> MulOps(
2872 OtherMul->operands().take_front(OMulOp));
2873 append_range(MulOps, OtherMul->operands().drop_front(OMulOp+1));
2874 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2875 }
2876 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2877 const SCEV *InnerMulSum =
2878 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2879 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2880 SCEV::FlagAnyWrap, Depth + 1);
2881 if (Ops.size() == 2) return OuterMul;
2882 Ops.erase(Ops.begin()+Idx);
2883 Ops.erase(Ops.begin()+OtherMulIdx-1);
2884 Ops.push_back(OuterMul);
2885 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2886 }
2887 }
2888 }
2889 }
2890
2891 // If there are any add recurrences in the operands list, see if any other
2892 // added values are loop invariant. If so, we can fold them into the
2893 // recurrence.
2894 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2895 ++Idx;
2896
2897 // Scan over all recurrences, trying to fold loop invariants into them.
2898 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2899 // Scan all of the other operands to this add and add them to the vector if
2900 // they are loop invariant w.r.t. the recurrence.
2901 SmallVector<const SCEV *, 8> LIOps;
2902 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2903 const Loop *AddRecLoop = AddRec->getLoop();
2904 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2905 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2906 LIOps.push_back(Ops[i]);
2907 Ops.erase(Ops.begin()+i);
2908 --i; --e;
2909 }
2910
2911 // If we found some loop invariants, fold them into the recurrence.
2912 if (!LIOps.empty()) {
2913 // Compute nowrap flags for the addition of the loop-invariant ops and
2914 // the addrec. Temporarily push it as an operand for that purpose. These
2915 // flags are valid in the scope of the addrec only.
2916 LIOps.push_back(AddRec);
2917 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2918 LIOps.pop_back();
2919
2920 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2921 LIOps.push_back(AddRec->getStart());
2922
2923 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2924
2925 // It is not in general safe to propagate flags valid on an add within
2926 // the addrec scope to one outside it. We must prove that the inner
2927 // scope is guaranteed to execute if the outer one does to be able to
2928 // safely propagate. We know the program is undefined if poison is
2929 // produced on the inner scoped addrec. We also know that *for this use*
2930 // the outer scoped add can't overflow (because of the flags we just
2931 // computed for the inner scoped add) without the program being undefined.
2932 // Proving that entry to the outer scope neccesitates entry to the inner
2933 // scope, thus proves the program undefined if the flags would be violated
2934 // in the outer scope.
2935 SCEV::NoWrapFlags AddFlags = Flags;
2936 if (AddFlags != SCEV::FlagAnyWrap) {
2937 auto *DefI = getDefiningScopeBound(LIOps);
2938 auto *ReachI = &*AddRecLoop->getHeader()->begin();
2939 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2940 AddFlags = SCEV::FlagAnyWrap;
2941 }
2942 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2943
2944 // Build the new addrec. Propagate the NUW and NSW flags if both the
2945 // outer add and the inner addrec are guaranteed to have no overflow.
2946 // Always propagate NW.
2947 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2948 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2949
2950 // If all of the other operands were loop invariant, we are done.
2951 if (Ops.size() == 1) return NewRec;
2952
2953 // Otherwise, add the folded AddRec by the non-invariant parts.
2954 for (unsigned i = 0;; ++i)
2955 if (Ops[i] == AddRec) {
2956 Ops[i] = NewRec;
2957 break;
2958 }
2959 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2960 }
2961
2962 // Okay, if there weren't any loop invariants to be folded, check to see if
2963 // there are multiple AddRec's with the same loop induction variable being
2964 // added together. If so, we can fold them.
2965 for (unsigned OtherIdx = Idx+1;
2966 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2967 ++OtherIdx) {
2968 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2969 // so that the 1st found AddRecExpr is dominated by all others.
2970 assert(DT.dominates(
2971 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2972 AddRec->getLoop()->getHeader()) &&
2973 "AddRecExprs are not sorted in reverse dominance order?");
2974 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2975 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2976 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2977 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2978 ++OtherIdx) {
2979 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2980 if (OtherAddRec->getLoop() == AddRecLoop) {
2981 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2982 i != e; ++i) {
2983 if (i >= AddRecOps.size()) {
2984 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
2985 break;
2986 }
2987 SmallVector<const SCEV *, 2> TwoOps = {
2988 AddRecOps[i], OtherAddRec->getOperand(i)};
2989 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2990 }
2991 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2992 }
2993 }
2994 // Step size has changed, so we cannot guarantee no self-wraparound.
2995 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2996 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2997 }
2998 }
2999
3000 // Otherwise couldn't fold anything into this recurrence. Move onto the
3001 // next one.
3002 }
3003
3004 // Okay, it looks like we really DO need an add expr. Check to see if we
3005 // already have one, otherwise create a new one.
3006 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
3007 }
3008
3009 const SCEV *
getOrCreateAddExpr(ArrayRef<const SCEV * > Ops,SCEV::NoWrapFlags Flags)3010 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
3011 SCEV::NoWrapFlags Flags) {
3012 FoldingSetNodeID ID;
3013 ID.AddInteger(scAddExpr);
3014 for (const SCEV *Op : Ops)
3015 ID.AddPointer(Op);
3016 void *IP = nullptr;
3017 SCEVAddExpr *S =
3018 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3019 if (!S) {
3020 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3021 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3022 S = new (SCEVAllocator)
3023 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
3024 UniqueSCEVs.InsertNode(S, IP);
3025 registerUser(S, Ops);
3026 }
3027 S->setNoWrapFlags(Flags);
3028 return S;
3029 }
3030
3031 const SCEV *
getOrCreateAddRecExpr(ArrayRef<const SCEV * > Ops,const Loop * L,SCEV::NoWrapFlags Flags)3032 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
3033 const Loop *L, SCEV::NoWrapFlags Flags) {
3034 FoldingSetNodeID ID;
3035 ID.AddInteger(scAddRecExpr);
3036 for (const SCEV *Op : Ops)
3037 ID.AddPointer(Op);
3038 ID.AddPointer(L);
3039 void *IP = nullptr;
3040 SCEVAddRecExpr *S =
3041 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3042 if (!S) {
3043 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3044 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3045 S = new (SCEVAllocator)
3046 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
3047 UniqueSCEVs.InsertNode(S, IP);
3048 LoopUsers[L].push_back(S);
3049 registerUser(S, Ops);
3050 }
3051 setNoWrapFlags(S, Flags);
3052 return S;
3053 }
3054
3055 const SCEV *
getOrCreateMulExpr(ArrayRef<const SCEV * > Ops,SCEV::NoWrapFlags Flags)3056 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
3057 SCEV::NoWrapFlags Flags) {
3058 FoldingSetNodeID ID;
3059 ID.AddInteger(scMulExpr);
3060 for (const SCEV *Op : Ops)
3061 ID.AddPointer(Op);
3062 void *IP = nullptr;
3063 SCEVMulExpr *S =
3064 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3065 if (!S) {
3066 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3067 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3068 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
3069 O, Ops.size());
3070 UniqueSCEVs.InsertNode(S, IP);
3071 registerUser(S, Ops);
3072 }
3073 S->setNoWrapFlags(Flags);
3074 return S;
3075 }
3076
umul_ov(uint64_t i,uint64_t j,bool & Overflow)3077 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
3078 uint64_t k = i*j;
3079 if (j > 1 && k / j != i) Overflow = true;
3080 return k;
3081 }
3082
3083 /// Compute the result of "n choose k", the binomial coefficient. If an
3084 /// intermediate computation overflows, Overflow will be set and the return will
3085 /// be garbage. Overflow is not cleared on absence of overflow.
Choose(uint64_t n,uint64_t k,bool & Overflow)3086 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3087 // We use the multiplicative formula:
3088 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3089 // At each iteration, we take the n-th term of the numeral and divide by the
3090 // (k-n)th term of the denominator. This division will always produce an
3091 // integral result, and helps reduce the chance of overflow in the
3092 // intermediate computations. However, we can still overflow even when the
3093 // final result would fit.
3094
3095 if (n == 0 || n == k) return 1;
3096 if (k > n) return 0;
3097
3098 if (k > n/2)
3099 k = n-k;
3100
3101 uint64_t r = 1;
3102 for (uint64_t i = 1; i <= k; ++i) {
3103 r = umul_ov(r, n-(i-1), Overflow);
3104 r /= i;
3105 }
3106 return r;
3107 }
3108
3109 /// Determine if any of the operands in this SCEV are a constant or if
3110 /// any of the add or multiply expressions in this SCEV contain a constant.
containsConstantInAddMulChain(const SCEV * StartExpr)3111 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3112 struct FindConstantInAddMulChain {
3113 bool FoundConstant = false;
3114
3115 bool follow(const SCEV *S) {
3116 FoundConstant |= isa<SCEVConstant>(S);
3117 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3118 }
3119
3120 bool isDone() const {
3121 return FoundConstant;
3122 }
3123 };
3124
3125 FindConstantInAddMulChain F;
3126 SCEVTraversal<FindConstantInAddMulChain> ST(F);
3127 ST.visitAll(StartExpr);
3128 return F.FoundConstant;
3129 }
3130
3131 /// Get a canonical multiply expression, or something simpler if possible.
getMulExpr(SmallVectorImpl<const SCEV * > & Ops,SCEV::NoWrapFlags OrigFlags,unsigned Depth)3132 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
3133 SCEV::NoWrapFlags OrigFlags,
3134 unsigned Depth) {
3135 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3136 "only nuw or nsw allowed");
3137 assert(!Ops.empty() && "Cannot get empty mul!");
3138 if (Ops.size() == 1) return Ops[0];
3139 #ifndef NDEBUG
3140 Type *ETy = Ops[0]->getType();
3141 assert(!ETy->isPointerTy());
3142 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3143 assert(Ops[i]->getType() == ETy &&
3144 "SCEVMulExpr operand types don't match!");
3145 #endif
3146
3147 // Sort by complexity, this groups all similar expression types together.
3148 GroupByComplexity(Ops, &LI, DT);
3149
3150 // If there are any constants, fold them together.
3151 unsigned Idx = 0;
3152 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3153 ++Idx;
3154 assert(Idx < Ops.size());
3155 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3156 // We found two constants, fold them together!
3157 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
3158 if (Ops.size() == 2) return Ops[0];
3159 Ops.erase(Ops.begin()+1); // Erase the folded element
3160 LHSC = cast<SCEVConstant>(Ops[0]);
3161 }
3162
3163 // If we have a multiply of zero, it will always be zero.
3164 if (LHSC->getValue()->isZero())
3165 return LHSC;
3166
3167 // If we are left with a constant one being multiplied, strip it off.
3168 if (LHSC->getValue()->isOne()) {
3169 Ops.erase(Ops.begin());
3170 --Idx;
3171 }
3172
3173 if (Ops.size() == 1)
3174 return Ops[0];
3175 }
3176
3177 // Delay expensive flag strengthening until necessary.
3178 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
3179 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3180 };
3181
3182 // Limit recursion calls depth.
3183 if (Depth > MaxArithDepth || hasHugeExpression(Ops))
3184 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3185
3186 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3187 // Don't strengthen flags if we have no new information.
3188 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3189 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3190 Mul->setNoWrapFlags(ComputeFlags(Ops));
3191 return S;
3192 }
3193
3194 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3195 if (Ops.size() == 2) {
3196 // C1*(C2+V) -> C1*C2 + C1*V
3197 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
3198 // If any of Add's ops are Adds or Muls with a constant, apply this
3199 // transformation as well.
3200 //
3201 // TODO: There are some cases where this transformation is not
3202 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
3203 // this transformation should be narrowed down.
3204 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) {
3205 const SCEV *LHS = getMulExpr(LHSC, Add->getOperand(0),
3206 SCEV::FlagAnyWrap, Depth + 1);
3207 const SCEV *RHS = getMulExpr(LHSC, Add->getOperand(1),
3208 SCEV::FlagAnyWrap, Depth + 1);
3209 return getAddExpr(LHS, RHS, SCEV::FlagAnyWrap, Depth + 1);
3210 }
3211
3212 if (Ops[0]->isAllOnesValue()) {
3213 // If we have a mul by -1 of an add, try distributing the -1 among the
3214 // add operands.
3215 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3216 SmallVector<const SCEV *, 4> NewOps;
3217 bool AnyFolded = false;
3218 for (const SCEV *AddOp : Add->operands()) {
3219 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
3220 Depth + 1);
3221 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3222 NewOps.push_back(Mul);
3223 }
3224 if (AnyFolded)
3225 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3226 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3227 // Negation preserves a recurrence's no self-wrap property.
3228 SmallVector<const SCEV *, 4> Operands;
3229 for (const SCEV *AddRecOp : AddRec->operands())
3230 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
3231 Depth + 1));
3232
3233 return getAddRecExpr(Operands, AddRec->getLoop(),
3234 AddRec->getNoWrapFlags(SCEV::FlagNW));
3235 }
3236 }
3237 }
3238 }
3239
3240 // Skip over the add expression until we get to a multiply.
3241 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3242 ++Idx;
3243
3244 // If there are mul operands inline them all into this expression.
3245 if (Idx < Ops.size()) {
3246 bool DeletedMul = false;
3247 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3248 if (Ops.size() > MulOpsInlineThreshold)
3249 break;
3250 // If we have an mul, expand the mul operands onto the end of the
3251 // operands list.
3252 Ops.erase(Ops.begin()+Idx);
3253 append_range(Ops, Mul->operands());
3254 DeletedMul = true;
3255 }
3256
3257 // If we deleted at least one mul, we added operands to the end of the
3258 // list, and they are not necessarily sorted. Recurse to resort and
3259 // resimplify any operands we just acquired.
3260 if (DeletedMul)
3261 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3262 }
3263
3264 // If there are any add recurrences in the operands list, see if any other
3265 // added values are loop invariant. If so, we can fold them into the
3266 // recurrence.
3267 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3268 ++Idx;
3269
3270 // Scan over all recurrences, trying to fold loop invariants into them.
3271 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3272 // Scan all of the other operands to this mul and add them to the vector
3273 // if they are loop invariant w.r.t. the recurrence.
3274 SmallVector<const SCEV *, 8> LIOps;
3275 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3276 const Loop *AddRecLoop = AddRec->getLoop();
3277 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3278 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
3279 LIOps.push_back(Ops[i]);
3280 Ops.erase(Ops.begin()+i);
3281 --i; --e;
3282 }
3283
3284 // If we found some loop invariants, fold them into the recurrence.
3285 if (!LIOps.empty()) {
3286 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3287 SmallVector<const SCEV *, 4> NewOps;
3288 NewOps.reserve(AddRec->getNumOperands());
3289 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3290 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
3291 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3292 SCEV::FlagAnyWrap, Depth + 1));
3293
3294 // Build the new addrec. Propagate the NUW and NSW flags if both the
3295 // outer mul and the inner addrec are guaranteed to have no overflow.
3296 //
3297 // No self-wrap cannot be guaranteed after changing the step size, but
3298 // will be inferred if either NUW or NSW is true.
3299 SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec});
3300 const SCEV *NewRec = getAddRecExpr(
3301 NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags));
3302
3303 // If all of the other operands were loop invariant, we are done.
3304 if (Ops.size() == 1) return NewRec;
3305
3306 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3307 for (unsigned i = 0;; ++i)
3308 if (Ops[i] == AddRec) {
3309 Ops[i] = NewRec;
3310 break;
3311 }
3312 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3313 }
3314
3315 // Okay, if there weren't any loop invariants to be folded, check to see
3316 // if there are multiple AddRec's with the same loop induction variable
3317 // being multiplied together. If so, we can fold them.
3318
3319 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3320 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3321 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3322 // ]]],+,...up to x=2n}.
3323 // Note that the arguments to choose() are always integers with values
3324 // known at compile time, never SCEV objects.
3325 //
3326 // The implementation avoids pointless extra computations when the two
3327 // addrec's are of different length (mathematically, it's equivalent to
3328 // an infinite stream of zeros on the right).
3329 bool OpsModified = false;
3330 for (unsigned OtherIdx = Idx+1;
3331 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3332 ++OtherIdx) {
3333 const SCEVAddRecExpr *OtherAddRec =
3334 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3335 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3336 continue;
3337
3338 // Limit max number of arguments to avoid creation of unreasonably big
3339 // SCEVAddRecs with very complex operands.
3340 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3341 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3342 continue;
3343
3344 bool Overflow = false;
3345 Type *Ty = AddRec->getType();
3346 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3347 SmallVector<const SCEV*, 7> AddRecOps;
3348 for (int x = 0, xe = AddRec->getNumOperands() +
3349 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3350 SmallVector <const SCEV *, 7> SumOps;
3351 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3352 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3353 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3354 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3355 z < ze && !Overflow; ++z) {
3356 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3357 uint64_t Coeff;
3358 if (LargerThan64Bits)
3359 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3360 else
3361 Coeff = Coeff1*Coeff2;
3362 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3363 const SCEV *Term1 = AddRec->getOperand(y-z);
3364 const SCEV *Term2 = OtherAddRec->getOperand(z);
3365 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3366 SCEV::FlagAnyWrap, Depth + 1));
3367 }
3368 }
3369 if (SumOps.empty())
3370 SumOps.push_back(getZero(Ty));
3371 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3372 }
3373 if (!Overflow) {
3374 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3375 SCEV::FlagAnyWrap);
3376 if (Ops.size() == 2) return NewAddRec;
3377 Ops[Idx] = NewAddRec;
3378 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3379 OpsModified = true;
3380 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3381 if (!AddRec)
3382 break;
3383 }
3384 }
3385 if (OpsModified)
3386 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3387
3388 // Otherwise couldn't fold anything into this recurrence. Move onto the
3389 // next one.
3390 }
3391
3392 // Okay, it looks like we really DO need an mul expr. Check to see if we
3393 // already have one, otherwise create a new one.
3394 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3395 }
3396
3397 /// Represents an unsigned remainder expression based on unsigned division.
getURemExpr(const SCEV * LHS,const SCEV * RHS)3398 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3399 const SCEV *RHS) {
3400 assert(getEffectiveSCEVType(LHS->getType()) ==
3401 getEffectiveSCEVType(RHS->getType()) &&
3402 "SCEVURemExpr operand types don't match!");
3403
3404 // Short-circuit easy cases
3405 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3406 // If constant is one, the result is trivial
3407 if (RHSC->getValue()->isOne())
3408 return getZero(LHS->getType()); // X urem 1 --> 0
3409
3410 // If constant is a power of two, fold into a zext(trunc(LHS)).
3411 if (RHSC->getAPInt().isPowerOf2()) {
3412 Type *FullTy = LHS->getType();
3413 Type *TruncTy =
3414 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3415 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3416 }
3417 }
3418
3419 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3420 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3421 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3422 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3423 }
3424
3425 /// Get a canonical unsigned division expression, or something simpler if
3426 /// possible.
getUDivExpr(const SCEV * LHS,const SCEV * RHS)3427 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3428 const SCEV *RHS) {
3429 assert(!LHS->getType()->isPointerTy() &&
3430 "SCEVUDivExpr operand can't be pointer!");
3431 assert(LHS->getType() == RHS->getType() &&
3432 "SCEVUDivExpr operand types don't match!");
3433
3434 FoldingSetNodeID ID;
3435 ID.AddInteger(scUDivExpr);
3436 ID.AddPointer(LHS);
3437 ID.AddPointer(RHS);
3438 void *IP = nullptr;
3439 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3440 return S;
3441
3442 // 0 udiv Y == 0
3443 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3444 if (LHSC->getValue()->isZero())
3445 return LHS;
3446
3447 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3448 if (RHSC->getValue()->isOne())
3449 return LHS; // X udiv 1 --> x
3450 // If the denominator is zero, the result of the udiv is undefined. Don't
3451 // try to analyze it, because the resolution chosen here may differ from
3452 // the resolution chosen in other parts of the compiler.
3453 if (!RHSC->getValue()->isZero()) {
3454 // Determine if the division can be folded into the operands of
3455 // its operands.
3456 // TODO: Generalize this to non-constants by using known-bits information.
3457 Type *Ty = LHS->getType();
3458 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3459 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3460 // For non-power-of-two values, effectively round the value up to the
3461 // nearest power of two.
3462 if (!RHSC->getAPInt().isPowerOf2())
3463 ++MaxShiftAmt;
3464 IntegerType *ExtTy =
3465 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3466 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3467 if (const SCEVConstant *Step =
3468 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3469 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3470 const APInt &StepInt = Step->getAPInt();
3471 const APInt &DivInt = RHSC->getAPInt();
3472 if (!StepInt.urem(DivInt) &&
3473 getZeroExtendExpr(AR, ExtTy) ==
3474 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3475 getZeroExtendExpr(Step, ExtTy),
3476 AR->getLoop(), SCEV::FlagAnyWrap)) {
3477 SmallVector<const SCEV *, 4> Operands;
3478 for (const SCEV *Op : AR->operands())
3479 Operands.push_back(getUDivExpr(Op, RHS));
3480 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3481 }
3482 /// Get a canonical UDivExpr for a recurrence.
3483 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3484 // We can currently only fold X%N if X is constant.
3485 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3486 if (StartC && !DivInt.urem(StepInt) &&
3487 getZeroExtendExpr(AR, ExtTy) ==
3488 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3489 getZeroExtendExpr(Step, ExtTy),
3490 AR->getLoop(), SCEV::FlagAnyWrap)) {
3491 const APInt &StartInt = StartC->getAPInt();
3492 const APInt &StartRem = StartInt.urem(StepInt);
3493 if (StartRem != 0) {
3494 const SCEV *NewLHS =
3495 getAddRecExpr(getConstant(StartInt - StartRem), Step,
3496 AR->getLoop(), SCEV::FlagNW);
3497 if (LHS != NewLHS) {
3498 LHS = NewLHS;
3499
3500 // Reset the ID to include the new LHS, and check if it is
3501 // already cached.
3502 ID.clear();
3503 ID.AddInteger(scUDivExpr);
3504 ID.AddPointer(LHS);
3505 ID.AddPointer(RHS);
3506 IP = nullptr;
3507 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3508 return S;
3509 }
3510 }
3511 }
3512 }
3513 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3514 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3515 SmallVector<const SCEV *, 4> Operands;
3516 for (const SCEV *Op : M->operands())
3517 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3518 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3519 // Find an operand that's safely divisible.
3520 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3521 const SCEV *Op = M->getOperand(i);
3522 const SCEV *Div = getUDivExpr(Op, RHSC);
3523 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3524 Operands = SmallVector<const SCEV *, 4>(M->operands());
3525 Operands[i] = Div;
3526 return getMulExpr(Operands);
3527 }
3528 }
3529 }
3530
3531 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3532 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3533 if (auto *DivisorConstant =
3534 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3535 bool Overflow = false;
3536 APInt NewRHS =
3537 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3538 if (Overflow) {
3539 return getConstant(RHSC->getType(), 0, false);
3540 }
3541 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3542 }
3543 }
3544
3545 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3546 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3547 SmallVector<const SCEV *, 4> Operands;
3548 for (const SCEV *Op : A->operands())
3549 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3550 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3551 Operands.clear();
3552 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3553 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3554 if (isa<SCEVUDivExpr>(Op) ||
3555 getMulExpr(Op, RHS) != A->getOperand(i))
3556 break;
3557 Operands.push_back(Op);
3558 }
3559 if (Operands.size() == A->getNumOperands())
3560 return getAddExpr(Operands);
3561 }
3562 }
3563
3564 // Fold if both operands are constant.
3565 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3566 return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3567 }
3568 }
3569
3570 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3571 // changes). Make sure we get a new one.
3572 IP = nullptr;
3573 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3574 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3575 LHS, RHS);
3576 UniqueSCEVs.InsertNode(S, IP);
3577 registerUser(S, {LHS, RHS});
3578 return S;
3579 }
3580
gcd(const SCEVConstant * C1,const SCEVConstant * C2)3581 APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3582 APInt A = C1->getAPInt().abs();
3583 APInt B = C2->getAPInt().abs();
3584 uint32_t ABW = A.getBitWidth();
3585 uint32_t BBW = B.getBitWidth();
3586
3587 if (ABW > BBW)
3588 B = B.zext(ABW);
3589 else if (ABW < BBW)
3590 A = A.zext(BBW);
3591
3592 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3593 }
3594
3595 /// Get a canonical unsigned division expression, or something simpler if
3596 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3597 /// can attempt to remove factors from the LHS and RHS. We can't do this when
3598 /// it's not exact because the udiv may be clearing bits.
getUDivExactExpr(const SCEV * LHS,const SCEV * RHS)3599 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3600 const SCEV *RHS) {
3601 // TODO: we could try to find factors in all sorts of things, but for now we
3602 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3603 // end of this file for inspiration.
3604
3605 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3606 if (!Mul || !Mul->hasNoUnsignedWrap())
3607 return getUDivExpr(LHS, RHS);
3608
3609 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3610 // If the mulexpr multiplies by a constant, then that constant must be the
3611 // first element of the mulexpr.
3612 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3613 if (LHSCst == RHSCst) {
3614 SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands()));
3615 return getMulExpr(Operands);
3616 }
3617
3618 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3619 // that there's a factor provided by one of the other terms. We need to
3620 // check.
3621 APInt Factor = gcd(LHSCst, RHSCst);
3622 if (!Factor.isIntN(1)) {
3623 LHSCst =
3624 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3625 RHSCst =
3626 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3627 SmallVector<const SCEV *, 2> Operands;
3628 Operands.push_back(LHSCst);
3629 append_range(Operands, Mul->operands().drop_front());
3630 LHS = getMulExpr(Operands);
3631 RHS = RHSCst;
3632 Mul = dyn_cast<SCEVMulExpr>(LHS);
3633 if (!Mul)
3634 return getUDivExactExpr(LHS, RHS);
3635 }
3636 }
3637 }
3638
3639 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3640 if (Mul->getOperand(i) == RHS) {
3641 SmallVector<const SCEV *, 2> Operands;
3642 append_range(Operands, Mul->operands().take_front(i));
3643 append_range(Operands, Mul->operands().drop_front(i + 1));
3644 return getMulExpr(Operands);
3645 }
3646 }
3647
3648 return getUDivExpr(LHS, RHS);
3649 }
3650
3651 /// Get an add recurrence expression for the specified loop. Simplify the
3652 /// expression as much as possible.
getAddRecExpr(const SCEV * Start,const SCEV * Step,const Loop * L,SCEV::NoWrapFlags Flags)3653 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3654 const Loop *L,
3655 SCEV::NoWrapFlags Flags) {
3656 SmallVector<const SCEV *, 4> Operands;
3657 Operands.push_back(Start);
3658 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3659 if (StepChrec->getLoop() == L) {
3660 append_range(Operands, StepChrec->operands());
3661 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3662 }
3663
3664 Operands.push_back(Step);
3665 return getAddRecExpr(Operands, L, Flags);
3666 }
3667
3668 /// Get an add recurrence expression for the specified loop. Simplify the
3669 /// expression as much as possible.
3670 const SCEV *
getAddRecExpr(SmallVectorImpl<const SCEV * > & Operands,const Loop * L,SCEV::NoWrapFlags Flags)3671 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3672 const Loop *L, SCEV::NoWrapFlags Flags) {
3673 if (Operands.size() == 1) return Operands[0];
3674 #ifndef NDEBUG
3675 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3676 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
3677 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3678 "SCEVAddRecExpr operand types don't match!");
3679 assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer");
3680 }
3681 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3682 assert(isLoopInvariant(Operands[i], L) &&
3683 "SCEVAddRecExpr operand is not loop-invariant!");
3684 #endif
3685
3686 if (Operands.back()->isZero()) {
3687 Operands.pop_back();
3688 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3689 }
3690
3691 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3692 // use that information to infer NUW and NSW flags. However, computing a
3693 // BE count requires calling getAddRecExpr, so we may not yet have a
3694 // meaningful BE count at this point (and if we don't, we'd be stuck
3695 // with a SCEVCouldNotCompute as the cached BE count).
3696
3697 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3698
3699 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3700 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3701 const Loop *NestedLoop = NestedAR->getLoop();
3702 if (L->contains(NestedLoop)
3703 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3704 : (!NestedLoop->contains(L) &&
3705 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3706 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands());
3707 Operands[0] = NestedAR->getStart();
3708 // AddRecs require their operands be loop-invariant with respect to their
3709 // loops. Don't perform this transformation if it would break this
3710 // requirement.
3711 bool AllInvariant = all_of(
3712 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3713
3714 if (AllInvariant) {
3715 // Create a recurrence for the outer loop with the same step size.
3716 //
3717 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3718 // inner recurrence has the same property.
3719 SCEV::NoWrapFlags OuterFlags =
3720 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3721
3722 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3723 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3724 return isLoopInvariant(Op, NestedLoop);
3725 });
3726
3727 if (AllInvariant) {
3728 // Ok, both add recurrences are valid after the transformation.
3729 //
3730 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3731 // the outer recurrence has the same property.
3732 SCEV::NoWrapFlags InnerFlags =
3733 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3734 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3735 }
3736 }
3737 // Reset Operands to its original state.
3738 Operands[0] = NestedAR;
3739 }
3740 }
3741
3742 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3743 // already have one, otherwise create a new one.
3744 return getOrCreateAddRecExpr(Operands, L, Flags);
3745 }
3746
3747 const SCEV *
getGEPExpr(GEPOperator * GEP,const SmallVectorImpl<const SCEV * > & IndexExprs)3748 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3749 const SmallVectorImpl<const SCEV *> &IndexExprs) {
3750 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3751 // getSCEV(Base)->getType() has the same address space as Base->getType()
3752 // because SCEV::getType() preserves the address space.
3753 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3754 const bool AssumeInBoundsFlags = [&]() {
3755 if (!GEP->isInBounds())
3756 return false;
3757
3758 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3759 // but to do that, we have to ensure that said flag is valid in the entire
3760 // defined scope of the SCEV.
3761 auto *GEPI = dyn_cast<Instruction>(GEP);
3762 // TODO: non-instructions have global scope. We might be able to prove
3763 // some global scope cases
3764 return GEPI && isSCEVExprNeverPoison(GEPI);
3765 }();
3766
3767 SCEV::NoWrapFlags OffsetWrap =
3768 AssumeInBoundsFlags ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3769
3770 Type *CurTy = GEP->getType();
3771 bool FirstIter = true;
3772 SmallVector<const SCEV *, 4> Offsets;
3773 for (const SCEV *IndexExpr : IndexExprs) {
3774 // Compute the (potentially symbolic) offset in bytes for this index.
3775 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3776 // For a struct, add the member offset.
3777 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3778 unsigned FieldNo = Index->getZExtValue();
3779 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3780 Offsets.push_back(FieldOffset);
3781
3782 // Update CurTy to the type of the field at Index.
3783 CurTy = STy->getTypeAtIndex(Index);
3784 } else {
3785 // Update CurTy to its element type.
3786 if (FirstIter) {
3787 assert(isa<PointerType>(CurTy) &&
3788 "The first index of a GEP indexes a pointer");
3789 CurTy = GEP->getSourceElementType();
3790 FirstIter = false;
3791 } else {
3792 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3793 }
3794 // For an array, add the element offset, explicitly scaled.
3795 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3796 // Getelementptr indices are signed.
3797 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3798
3799 // Multiply the index by the element size to compute the element offset.
3800 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3801 Offsets.push_back(LocalOffset);
3802 }
3803 }
3804
3805 // Handle degenerate case of GEP without offsets.
3806 if (Offsets.empty())
3807 return BaseExpr;
3808
3809 // Add the offsets together, assuming nsw if inbounds.
3810 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3811 // Add the base address and the offset. We cannot use the nsw flag, as the
3812 // base address is unsigned. However, if we know that the offset is
3813 // non-negative, we can use nuw.
3814 SCEV::NoWrapFlags BaseWrap = AssumeInBoundsFlags && isKnownNonNegative(Offset)
3815 ? SCEV::FlagNUW : SCEV::FlagAnyWrap;
3816 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3817 assert(BaseExpr->getType() == GEPExpr->getType() &&
3818 "GEP should not change type mid-flight.");
3819 return GEPExpr;
3820 }
3821
findExistingSCEVInCache(SCEVTypes SCEVType,ArrayRef<const SCEV * > Ops)3822 SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3823 ArrayRef<const SCEV *> Ops) {
3824 FoldingSetNodeID ID;
3825 ID.AddInteger(SCEVType);
3826 for (const SCEV *Op : Ops)
3827 ID.AddPointer(Op);
3828 void *IP = nullptr;
3829 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3830 }
3831
getAbsExpr(const SCEV * Op,bool IsNSW)3832 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3833 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3834 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3835 }
3836
getMinMaxExpr(SCEVTypes Kind,SmallVectorImpl<const SCEV * > & Ops)3837 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
3838 SmallVectorImpl<const SCEV *> &Ops) {
3839 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3840 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3841 if (Ops.size() == 1) return Ops[0];
3842 #ifndef NDEBUG
3843 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3844 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3845 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3846 "Operand types don't match!");
3847 assert(Ops[0]->getType()->isPointerTy() ==
3848 Ops[i]->getType()->isPointerTy() &&
3849 "min/max should be consistently pointerish");
3850 }
3851 #endif
3852
3853 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3854 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3855
3856 // Sort by complexity, this groups all similar expression types together.
3857 GroupByComplexity(Ops, &LI, DT);
3858
3859 // Check if we have created the same expression before.
3860 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3861 return S;
3862 }
3863
3864 // If there are any constants, fold them together.
3865 unsigned Idx = 0;
3866 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3867 ++Idx;
3868 assert(Idx < Ops.size());
3869 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3870 if (Kind == scSMaxExpr)
3871 return APIntOps::smax(LHS, RHS);
3872 else if (Kind == scSMinExpr)
3873 return APIntOps::smin(LHS, RHS);
3874 else if (Kind == scUMaxExpr)
3875 return APIntOps::umax(LHS, RHS);
3876 else if (Kind == scUMinExpr)
3877 return APIntOps::umin(LHS, RHS);
3878 llvm_unreachable("Unknown SCEV min/max opcode");
3879 };
3880
3881 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3882 // We found two constants, fold them together!
3883 ConstantInt *Fold = ConstantInt::get(
3884 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3885 Ops[0] = getConstant(Fold);
3886 Ops.erase(Ops.begin()+1); // Erase the folded element
3887 if (Ops.size() == 1) return Ops[0];
3888 LHSC = cast<SCEVConstant>(Ops[0]);
3889 }
3890
3891 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3892 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3893
3894 if (IsMax ? IsMinV : IsMaxV) {
3895 // If we are left with a constant minimum(/maximum)-int, strip it off.
3896 Ops.erase(Ops.begin());
3897 --Idx;
3898 } else if (IsMax ? IsMaxV : IsMinV) {
3899 // If we have a max(/min) with a constant maximum(/minimum)-int,
3900 // it will always be the extremum.
3901 return LHSC;
3902 }
3903
3904 if (Ops.size() == 1) return Ops[0];
3905 }
3906
3907 // Find the first operation of the same kind
3908 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3909 ++Idx;
3910
3911 // Check to see if one of the operands is of the same kind. If so, expand its
3912 // operands onto our operand list, and recurse to simplify.
3913 if (Idx < Ops.size()) {
3914 bool DeletedAny = false;
3915 while (Ops[Idx]->getSCEVType() == Kind) {
3916 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3917 Ops.erase(Ops.begin()+Idx);
3918 append_range(Ops, SMME->operands());
3919 DeletedAny = true;
3920 }
3921
3922 if (DeletedAny)
3923 return getMinMaxExpr(Kind, Ops);
3924 }
3925
3926 // Okay, check to see if the same value occurs in the operand list twice. If
3927 // so, delete one. Since we sorted the list, these values are required to
3928 // be adjacent.
3929 llvm::CmpInst::Predicate GEPred =
3930 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3931 llvm::CmpInst::Predicate LEPred =
3932 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3933 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3934 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3935 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3936 if (Ops[i] == Ops[i + 1] ||
3937 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3938 // X op Y op Y --> X op Y
3939 // X op Y --> X, if we know X, Y are ordered appropriately
3940 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3941 --i;
3942 --e;
3943 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3944 Ops[i + 1])) {
3945 // X op Y --> Y, if we know X, Y are ordered appropriately
3946 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3947 --i;
3948 --e;
3949 }
3950 }
3951
3952 if (Ops.size() == 1) return Ops[0];
3953
3954 assert(!Ops.empty() && "Reduced smax down to nothing!");
3955
3956 // Okay, it looks like we really DO need an expr. Check to see if we
3957 // already have one, otherwise create a new one.
3958 FoldingSetNodeID ID;
3959 ID.AddInteger(Kind);
3960 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3961 ID.AddPointer(Ops[i]);
3962 void *IP = nullptr;
3963 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3964 if (ExistingSCEV)
3965 return ExistingSCEV;
3966 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3967 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3968 SCEV *S = new (SCEVAllocator)
3969 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3970
3971 UniqueSCEVs.InsertNode(S, IP);
3972 registerUser(S, Ops);
3973 return S;
3974 }
3975
3976 namespace {
3977
3978 class SCEVSequentialMinMaxDeduplicatingVisitor final
3979 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
3980 std::optional<const SCEV *>> {
3981 using RetVal = std::optional<const SCEV *>;
3982 using Base = SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor, RetVal>;
3983
3984 ScalarEvolution &SE;
3985 const SCEVTypes RootKind; // Must be a sequential min/max expression.
3986 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
3987 SmallPtrSet<const SCEV *, 16> SeenOps;
3988
canRecurseInto(SCEVTypes Kind) const3989 bool canRecurseInto(SCEVTypes Kind) const {
3990 // We can only recurse into the SCEV expression of the same effective type
3991 // as the type of our root SCEV expression.
3992 return RootKind == Kind || NonSequentialRootKind == Kind;
3993 };
3994
visitAnyMinMaxExpr(const SCEV * S)3995 RetVal visitAnyMinMaxExpr(const SCEV *S) {
3996 assert((isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) &&
3997 "Only for min/max expressions.");
3998 SCEVTypes Kind = S->getSCEVType();
3999
4000 if (!canRecurseInto(Kind))
4001 return S;
4002
4003 auto *NAry = cast<SCEVNAryExpr>(S);
4004 SmallVector<const SCEV *> NewOps;
4005 bool Changed = visit(Kind, NAry->operands(), NewOps);
4006
4007 if (!Changed)
4008 return S;
4009 if (NewOps.empty())
4010 return std::nullopt;
4011
4012 return isa<SCEVSequentialMinMaxExpr>(S)
4013 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
4014 : SE.getMinMaxExpr(Kind, NewOps);
4015 }
4016
visit(const SCEV * S)4017 RetVal visit(const SCEV *S) {
4018 // Has the whole operand been seen already?
4019 if (!SeenOps.insert(S).second)
4020 return std::nullopt;
4021 return Base::visit(S);
4022 }
4023
4024 public:
SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution & SE,SCEVTypes RootKind)4025 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
4026 SCEVTypes RootKind)
4027 : SE(SE), RootKind(RootKind),
4028 NonSequentialRootKind(
4029 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4030 RootKind)) {}
4031
visit(SCEVTypes Kind,ArrayRef<const SCEV * > OrigOps,SmallVectorImpl<const SCEV * > & NewOps)4032 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<const SCEV *> OrigOps,
4033 SmallVectorImpl<const SCEV *> &NewOps) {
4034 bool Changed = false;
4035 SmallVector<const SCEV *> Ops;
4036 Ops.reserve(OrigOps.size());
4037
4038 for (const SCEV *Op : OrigOps) {
4039 RetVal NewOp = visit(Op);
4040 if (NewOp != Op)
4041 Changed = true;
4042 if (NewOp)
4043 Ops.emplace_back(*NewOp);
4044 }
4045
4046 if (Changed)
4047 NewOps = std::move(Ops);
4048 return Changed;
4049 }
4050
visitConstant(const SCEVConstant * Constant)4051 RetVal visitConstant(const SCEVConstant *Constant) { return Constant; }
4052
visitPtrToIntExpr(const SCEVPtrToIntExpr * Expr)4053 RetVal visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) { return Expr; }
4054
visitTruncateExpr(const SCEVTruncateExpr * Expr)4055 RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
4056
visitZeroExtendExpr(const SCEVZeroExtendExpr * Expr)4057 RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; }
4058
visitSignExtendExpr(const SCEVSignExtendExpr * Expr)4059 RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; }
4060
visitAddExpr(const SCEVAddExpr * Expr)4061 RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; }
4062
visitMulExpr(const SCEVMulExpr * Expr)4063 RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; }
4064
visitUDivExpr(const SCEVUDivExpr * Expr)4065 RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
4066
visitAddRecExpr(const SCEVAddRecExpr * Expr)4067 RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
4068
visitSMaxExpr(const SCEVSMaxExpr * Expr)4069 RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) {
4070 return visitAnyMinMaxExpr(Expr);
4071 }
4072
visitUMaxExpr(const SCEVUMaxExpr * Expr)4073 RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) {
4074 return visitAnyMinMaxExpr(Expr);
4075 }
4076
visitSMinExpr(const SCEVSMinExpr * Expr)4077 RetVal visitSMinExpr(const SCEVSMinExpr *Expr) {
4078 return visitAnyMinMaxExpr(Expr);
4079 }
4080
visitUMinExpr(const SCEVUMinExpr * Expr)4081 RetVal visitUMinExpr(const SCEVUMinExpr *Expr) {
4082 return visitAnyMinMaxExpr(Expr);
4083 }
4084
visitSequentialUMinExpr(const SCEVSequentialUMinExpr * Expr)4085 RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
4086 return visitAnyMinMaxExpr(Expr);
4087 }
4088
visitUnknown(const SCEVUnknown * Expr)4089 RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; }
4090
visitCouldNotCompute(const SCEVCouldNotCompute * Expr)4091 RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; }
4092 };
4093
4094 } // namespace
4095
scevUnconditionallyPropagatesPoisonFromOperands(SCEVTypes Kind)4096 static bool scevUnconditionallyPropagatesPoisonFromOperands(SCEVTypes Kind) {
4097 switch (Kind) {
4098 case scConstant:
4099 case scTruncate:
4100 case scZeroExtend:
4101 case scSignExtend:
4102 case scPtrToInt:
4103 case scAddExpr:
4104 case scMulExpr:
4105 case scUDivExpr:
4106 case scAddRecExpr:
4107 case scUMaxExpr:
4108 case scSMaxExpr:
4109 case scUMinExpr:
4110 case scSMinExpr:
4111 case scUnknown:
4112 // If any operand is poison, the whole expression is poison.
4113 return true;
4114 case scSequentialUMinExpr:
4115 // FIXME: if the *first* operand is poison, the whole expression is poison.
4116 return false; // Pessimistically, say that it does not propagate poison.
4117 case scCouldNotCompute:
4118 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4119 }
4120 llvm_unreachable("Unknown SCEV kind!");
4121 }
4122
4123 /// Return true if V is poison given that AssumedPoison is already poison.
impliesPoison(const SCEV * AssumedPoison,const SCEV * S)4124 static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4125 // The only way poison may be introduced in a SCEV expression is from a
4126 // poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4127 // not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not*
4128 // introduce poison -- they encode guaranteed, non-speculated knowledge.
4129 //
4130 // Additionally, all SCEV nodes propagate poison from inputs to outputs,
4131 // with the notable exception of umin_seq, where only poison from the first
4132 // operand is (unconditionally) propagated.
4133 struct SCEVPoisonCollector {
4134 bool LookThroughSeq;
4135 SmallPtrSet<const SCEV *, 4> MaybePoison;
4136 SCEVPoisonCollector(bool LookThroughSeq) : LookThroughSeq(LookThroughSeq) {}
4137
4138 bool follow(const SCEV *S) {
4139 if (!scevUnconditionallyPropagatesPoisonFromOperands(S->getSCEVType())) {
4140 switch (S->getSCEVType()) {
4141 case scConstant:
4142 case scTruncate:
4143 case scZeroExtend:
4144 case scSignExtend:
4145 case scPtrToInt:
4146 case scAddExpr:
4147 case scMulExpr:
4148 case scUDivExpr:
4149 case scAddRecExpr:
4150 case scUMaxExpr:
4151 case scSMaxExpr:
4152 case scUMinExpr:
4153 case scSMinExpr:
4154 case scUnknown:
4155 llvm_unreachable("These all unconditionally propagate poison.");
4156 case scSequentialUMinExpr:
4157 // TODO: We can always follow the first operand,
4158 // but the SCEVTraversal API doesn't support this.
4159 if (!LookThroughSeq)
4160 return false;
4161 break;
4162 case scCouldNotCompute:
4163 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4164 }
4165 }
4166
4167 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4168 if (!isGuaranteedNotToBePoison(SU->getValue()))
4169 MaybePoison.insert(S);
4170 }
4171 return true;
4172 }
4173 bool isDone() const { return false; }
4174 };
4175
4176 // First collect all SCEVs that might result in AssumedPoison to be poison.
4177 // We need to look through umin_seq here, because we want to find all SCEVs
4178 // that *might* result in poison, not only those that are *required* to.
4179 SCEVPoisonCollector PC1(/* LookThroughSeq */ true);
4180 visitAll(AssumedPoison, PC1);
4181
4182 // AssumedPoison is never poison. As the assumption is false, the implication
4183 // is true. Don't bother walking the other SCEV in this case.
4184 if (PC1.MaybePoison.empty())
4185 return true;
4186
4187 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4188 // as well. We cannot look through umin_seq here, as its argument only *may*
4189 // make the result poison.
4190 SCEVPoisonCollector PC2(/* LookThroughSeq */ false);
4191 visitAll(S, PC2);
4192
4193 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4194 // it will also make S poison by being part of PC2.MaybePoison.
4195 return all_of(PC1.MaybePoison,
4196 [&](const SCEV *S) { return PC2.MaybePoison.contains(S); });
4197 }
4198
4199 const SCEV *
getSequentialMinMaxExpr(SCEVTypes Kind,SmallVectorImpl<const SCEV * > & Ops)4200 ScalarEvolution::getSequentialMinMaxExpr(SCEVTypes Kind,
4201 SmallVectorImpl<const SCEV *> &Ops) {
4202 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4203 "Not a SCEVSequentialMinMaxExpr!");
4204 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4205 if (Ops.size() == 1)
4206 return Ops[0];
4207 #ifndef NDEBUG
4208 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4209 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4210 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4211 "Operand types don't match!");
4212 assert(Ops[0]->getType()->isPointerTy() ==
4213 Ops[i]->getType()->isPointerTy() &&
4214 "min/max should be consistently pointerish");
4215 }
4216 #endif
4217
4218 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4219 // so we can *NOT* do any kind of sorting of the expressions!
4220
4221 // Check if we have created the same expression before.
4222 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4223 return S;
4224
4225 // FIXME: there are *some* simplifications that we can do here.
4226
4227 // Keep only the first instance of an operand.
4228 {
4229 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4230 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4231 if (Changed)
4232 return getSequentialMinMaxExpr(Kind, Ops);
4233 }
4234
4235 // Check to see if one of the operands is of the same kind. If so, expand its
4236 // operands onto our operand list, and recurse to simplify.
4237 {
4238 unsigned Idx = 0;
4239 bool DeletedAny = false;
4240 while (Idx < Ops.size()) {
4241 if (Ops[Idx]->getSCEVType() != Kind) {
4242 ++Idx;
4243 continue;
4244 }
4245 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4246 Ops.erase(Ops.begin() + Idx);
4247 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4248 SMME->operands().end());
4249 DeletedAny = true;
4250 }
4251
4252 if (DeletedAny)
4253 return getSequentialMinMaxExpr(Kind, Ops);
4254 }
4255
4256 const SCEV *SaturationPoint;
4257 ICmpInst::Predicate Pred;
4258 switch (Kind) {
4259 case scSequentialUMinExpr:
4260 SaturationPoint = getZero(Ops[0]->getType());
4261 Pred = ICmpInst::ICMP_ULE;
4262 break;
4263 default:
4264 llvm_unreachable("Not a sequential min/max type.");
4265 }
4266
4267 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4268 // We can replace %x umin_seq %y with %x umin %y if either:
4269 // * %y being poison implies %x is also poison.
4270 // * %x cannot be the saturating value (e.g. zero for umin).
4271 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4272 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4273 SaturationPoint)) {
4274 SmallVector<const SCEV *> SeqOps = {Ops[i - 1], Ops[i]};
4275 Ops[i - 1] = getMinMaxExpr(
4276 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(Kind),
4277 SeqOps);
4278 Ops.erase(Ops.begin() + i);
4279 return getSequentialMinMaxExpr(Kind, Ops);
4280 }
4281 // Fold %x umin_seq %y to %x if %x ule %y.
4282 // TODO: We might be able to prove the predicate for a later operand.
4283 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4284 Ops.erase(Ops.begin() + i);
4285 return getSequentialMinMaxExpr(Kind, Ops);
4286 }
4287 }
4288
4289 // Okay, it looks like we really DO need an expr. Check to see if we
4290 // already have one, otherwise create a new one.
4291 FoldingSetNodeID ID;
4292 ID.AddInteger(Kind);
4293 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
4294 ID.AddPointer(Ops[i]);
4295 void *IP = nullptr;
4296 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4297 if (ExistingSCEV)
4298 return ExistingSCEV;
4299
4300 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
4301 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
4302 SCEV *S = new (SCEVAllocator)
4303 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4304
4305 UniqueSCEVs.InsertNode(S, IP);
4306 registerUser(S, Ops);
4307 return S;
4308 }
4309
getSMaxExpr(const SCEV * LHS,const SCEV * RHS)4310 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4311 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
4312 return getSMaxExpr(Ops);
4313 }
4314
getSMaxExpr(SmallVectorImpl<const SCEV * > & Ops)4315 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
4316 return getMinMaxExpr(scSMaxExpr, Ops);
4317 }
4318
getUMaxExpr(const SCEV * LHS,const SCEV * RHS)4319 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4320 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
4321 return getUMaxExpr(Ops);
4322 }
4323
getUMaxExpr(SmallVectorImpl<const SCEV * > & Ops)4324 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
4325 return getMinMaxExpr(scUMaxExpr, Ops);
4326 }
4327
getSMinExpr(const SCEV * LHS,const SCEV * RHS)4328 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
4329 const SCEV *RHS) {
4330 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4331 return getSMinExpr(Ops);
4332 }
4333
getSMinExpr(SmallVectorImpl<const SCEV * > & Ops)4334 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
4335 return getMinMaxExpr(scSMinExpr, Ops);
4336 }
4337
getUMinExpr(const SCEV * LHS,const SCEV * RHS,bool Sequential)4338 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, const SCEV *RHS,
4339 bool Sequential) {
4340 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4341 return getUMinExpr(Ops, Sequential);
4342 }
4343
getUMinExpr(SmallVectorImpl<const SCEV * > & Ops,bool Sequential)4344 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops,
4345 bool Sequential) {
4346 return Sequential ? getSequentialMinMaxExpr(scSequentialUMinExpr, Ops)
4347 : getMinMaxExpr(scUMinExpr, Ops);
4348 }
4349
4350 const SCEV *
getSizeOfScalableVectorExpr(Type * IntTy,ScalableVectorType * ScalableTy)4351 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy,
4352 ScalableVectorType *ScalableTy) {
4353 Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo());
4354 Constant *One = ConstantInt::get(IntTy, 1);
4355 Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One);
4356 // Note that the expression we created is the final expression, we don't
4357 // want to simplify it any further Also, if we call a normal getSCEV(),
4358 // we'll end up in an endless recursion. So just create an SCEVUnknown.
4359 return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy));
4360 }
4361
getSizeOfExpr(Type * IntTy,Type * AllocTy)4362 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
4363 if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy))
4364 return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy);
4365 // We can bypass creating a target-independent constant expression and then
4366 // folding it back into a ConstantInt. This is just a compile-time
4367 // optimization.
4368 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4369 }
4370
getStoreSizeOfExpr(Type * IntTy,Type * StoreTy)4371 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) {
4372 if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy))
4373 return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy);
4374 // We can bypass creating a target-independent constant expression and then
4375 // folding it back into a ConstantInt. This is just a compile-time
4376 // optimization.
4377 return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4378 }
4379
getOffsetOfExpr(Type * IntTy,StructType * STy,unsigned FieldNo)4380 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
4381 StructType *STy,
4382 unsigned FieldNo) {
4383 // We can bypass creating a target-independent constant expression and then
4384 // folding it back into a ConstantInt. This is just a compile-time
4385 // optimization.
4386 return getConstant(
4387 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
4388 }
4389
getUnknown(Value * V)4390 const SCEV *ScalarEvolution::getUnknown(Value *V) {
4391 // Don't attempt to do anything other than create a SCEVUnknown object
4392 // here. createSCEV only calls getUnknown after checking for all other
4393 // interesting possibilities, and any other code that calls getUnknown
4394 // is doing so in order to hide a value from SCEV canonicalization.
4395
4396 FoldingSetNodeID ID;
4397 ID.AddInteger(scUnknown);
4398 ID.AddPointer(V);
4399 void *IP = nullptr;
4400 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
4401 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4402 "Stale SCEVUnknown in uniquing map!");
4403 return S;
4404 }
4405 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4406 FirstUnknown);
4407 FirstUnknown = cast<SCEVUnknown>(S);
4408 UniqueSCEVs.InsertNode(S, IP);
4409 return S;
4410 }
4411
4412 //===----------------------------------------------------------------------===//
4413 // Basic SCEV Analysis and PHI Idiom Recognition Code
4414 //
4415
4416 /// Test if values of the given type are analyzable within the SCEV
4417 /// framework. This primarily includes integer types, and it can optionally
4418 /// include pointer types if the ScalarEvolution class has access to
4419 /// target-specific information.
isSCEVable(Type * Ty) const4420 bool ScalarEvolution::isSCEVable(Type *Ty) const {
4421 // Integers and pointers are always SCEVable.
4422 return Ty->isIntOrPtrTy();
4423 }
4424
4425 /// Return the size in bits of the specified type, for which isSCEVable must
4426 /// return true.
getTypeSizeInBits(Type * Ty) const4427 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
4428 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4429 if (Ty->isPointerTy())
4430 return getDataLayout().getIndexTypeSizeInBits(Ty);
4431 return getDataLayout().getTypeSizeInBits(Ty);
4432 }
4433
4434 /// Return a type with the same bitwidth as the given type and which represents
4435 /// how SCEV will treat the given type, for which isSCEVable must return
4436 /// true. For pointer types, this is the pointer index sized integer type.
getEffectiveSCEVType(Type * Ty) const4437 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
4438 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4439
4440 if (Ty->isIntegerTy())
4441 return Ty;
4442
4443 // The only other support type is pointer.
4444 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4445 return getDataLayout().getIndexType(Ty);
4446 }
4447
getWiderType(Type * T1,Type * T2) const4448 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
4449 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4450 }
4451
instructionCouldExistWitthOperands(const SCEV * A,const SCEV * B)4452 bool ScalarEvolution::instructionCouldExistWitthOperands(const SCEV *A,
4453 const SCEV *B) {
4454 /// For a valid use point to exist, the defining scope of one operand
4455 /// must dominate the other.
4456 bool PreciseA, PreciseB;
4457 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4458 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4459 if (!PreciseA || !PreciseB)
4460 // Can't tell.
4461 return false;
4462 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4463 DT.dominates(ScopeB, ScopeA);
4464 }
4465
4466
getCouldNotCompute()4467 const SCEV *ScalarEvolution::getCouldNotCompute() {
4468 return CouldNotCompute.get();
4469 }
4470
checkValidity(const SCEV * S) const4471 bool ScalarEvolution::checkValidity(const SCEV *S) const {
4472 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4473 auto *SU = dyn_cast<SCEVUnknown>(S);
4474 return SU && SU->getValue() == nullptr;
4475 });
4476
4477 return !ContainsNulls;
4478 }
4479
containsAddRecurrence(const SCEV * S)4480 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
4481 HasRecMapType::iterator I = HasRecMap.find(S);
4482 if (I != HasRecMap.end())
4483 return I->second;
4484
4485 bool FoundAddRec =
4486 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4487 HasRecMap.insert({S, FoundAddRec});
4488 return FoundAddRec;
4489 }
4490
4491 /// Return the ValueOffsetPair set for \p S. \p S can be represented
4492 /// by the value and offset from any ValueOffsetPair in the set.
getSCEVValues(const SCEV * S)4493 ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4494 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4495 if (SI == ExprValueMap.end())
4496 return std::nullopt;
4497 #ifndef NDEBUG
4498 if (VerifySCEVMap) {
4499 // Check there is no dangling Value in the set returned.
4500 for (Value *V : SI->second)
4501 assert(ValueExprMap.count(V));
4502 }
4503 #endif
4504 return SI->second.getArrayRef();
4505 }
4506
4507 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4508 /// cannot be used separately. eraseValueFromMap should be used to remove
4509 /// V from ValueExprMap and ExprValueMap at the same time.
eraseValueFromMap(Value * V)4510 void ScalarEvolution::eraseValueFromMap(Value *V) {
4511 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4512 if (I != ValueExprMap.end()) {
4513 auto EVIt = ExprValueMap.find(I->second);
4514 bool Removed = EVIt->second.remove(V);
4515 (void) Removed;
4516 assert(Removed && "Value not in ExprValueMap?");
4517 ValueExprMap.erase(I);
4518 }
4519 }
4520
insertValueToMap(Value * V,const SCEV * S)4521 void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4522 // A recursive query may have already computed the SCEV. It should be
4523 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4524 // inferred nowrap flags.
4525 auto It = ValueExprMap.find_as(V);
4526 if (It == ValueExprMap.end()) {
4527 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4528 ExprValueMap[S].insert(V);
4529 }
4530 }
4531
4532 /// Return an existing SCEV if it exists, otherwise analyze the expression and
4533 /// create a new one.
getSCEV(Value * V)4534 const SCEV *ScalarEvolution::getSCEV(Value *V) {
4535 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4536
4537 if (const SCEV *S = getExistingSCEV(V))
4538 return S;
4539 return createSCEVIter(V);
4540 }
4541
getExistingSCEV(Value * V)4542 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
4543 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4544
4545 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4546 if (I != ValueExprMap.end()) {
4547 const SCEV *S = I->second;
4548 assert(checkValidity(S) &&
4549 "existing SCEV has not been properly invalidated");
4550 return S;
4551 }
4552 return nullptr;
4553 }
4554
4555 /// Return a SCEV corresponding to -V = -1*V
getNegativeSCEV(const SCEV * V,SCEV::NoWrapFlags Flags)4556 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
4557 SCEV::NoWrapFlags Flags) {
4558 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4559 return getConstant(
4560 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4561
4562 Type *Ty = V->getType();
4563 Ty = getEffectiveSCEVType(Ty);
4564 return getMulExpr(V, getMinusOne(Ty), Flags);
4565 }
4566
4567 /// If Expr computes ~A, return A else return nullptr
MatchNotExpr(const SCEV * Expr)4568 static const SCEV *MatchNotExpr(const SCEV *Expr) {
4569 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
4570 if (!Add || Add->getNumOperands() != 2 ||
4571 !Add->getOperand(0)->isAllOnesValue())
4572 return nullptr;
4573
4574 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
4575 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
4576 !AddRHS->getOperand(0)->isAllOnesValue())
4577 return nullptr;
4578
4579 return AddRHS->getOperand(1);
4580 }
4581
4582 /// Return a SCEV corresponding to ~V = -1-V
getNotSCEV(const SCEV * V)4583 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
4584 assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4585
4586 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4587 return getConstant(
4588 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4589
4590 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4591 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4592 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4593 SmallVector<const SCEV *, 2> MatchedOperands;
4594 for (const SCEV *Operand : MME->operands()) {
4595 const SCEV *Matched = MatchNotExpr(Operand);
4596 if (!Matched)
4597 return (const SCEV *)nullptr;
4598 MatchedOperands.push_back(Matched);
4599 }
4600 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4601 MatchedOperands);
4602 };
4603 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4604 return Replaced;
4605 }
4606
4607 Type *Ty = V->getType();
4608 Ty = getEffectiveSCEVType(Ty);
4609 return getMinusSCEV(getMinusOne(Ty), V);
4610 }
4611
removePointerBase(const SCEV * P)4612 const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) {
4613 assert(P->getType()->isPointerTy());
4614
4615 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4616 // The base of an AddRec is the first operand.
4617 SmallVector<const SCEV *> Ops{AddRec->operands()};
4618 Ops[0] = removePointerBase(Ops[0]);
4619 // Don't try to transfer nowrap flags for now. We could in some cases
4620 // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4621 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
4622 }
4623 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4624 // The base of an Add is the pointer operand.
4625 SmallVector<const SCEV *> Ops{Add->operands()};
4626 const SCEV **PtrOp = nullptr;
4627 for (const SCEV *&AddOp : Ops) {
4628 if (AddOp->getType()->isPointerTy()) {
4629 assert(!PtrOp && "Cannot have multiple pointer ops");
4630 PtrOp = &AddOp;
4631 }
4632 }
4633 *PtrOp = removePointerBase(*PtrOp);
4634 // Don't try to transfer nowrap flags for now. We could in some cases
4635 // (for example, if the pointer operand of the Add is a SCEVUnknown).
4636 return getAddExpr(Ops);
4637 }
4638 // Any other expression must be a pointer base.
4639 return getZero(P->getType());
4640 }
4641
getMinusSCEV(const SCEV * LHS,const SCEV * RHS,SCEV::NoWrapFlags Flags,unsigned Depth)4642 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
4643 SCEV::NoWrapFlags Flags,
4644 unsigned Depth) {
4645 // Fast path: X - X --> 0.
4646 if (LHS == RHS)
4647 return getZero(LHS->getType());
4648
4649 // If we subtract two pointers with different pointer bases, bail.
4650 // Eventually, we're going to add an assertion to getMulExpr that we
4651 // can't multiply by a pointer.
4652 if (RHS->getType()->isPointerTy()) {
4653 if (!LHS->getType()->isPointerTy() ||
4654 getPointerBase(LHS) != getPointerBase(RHS))
4655 return getCouldNotCompute();
4656 LHS = removePointerBase(LHS);
4657 RHS = removePointerBase(RHS);
4658 }
4659
4660 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4661 // makes it so that we cannot make much use of NUW.
4662 auto AddFlags = SCEV::FlagAnyWrap;
4663 const bool RHSIsNotMinSigned =
4664 !getSignedRangeMin(RHS).isMinSignedValue();
4665 if (hasFlags(Flags, SCEV::FlagNSW)) {
4666 // Let M be the minimum representable signed value. Then (-1)*RHS
4667 // signed-wraps if and only if RHS is M. That can happen even for
4668 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4669 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4670 // (-1)*RHS, we need to prove that RHS != M.
4671 //
4672 // If LHS is non-negative and we know that LHS - RHS does not
4673 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4674 // either by proving that RHS > M or that LHS >= 0.
4675 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4676 AddFlags = SCEV::FlagNSW;
4677 }
4678 }
4679
4680 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4681 // RHS is NSW and LHS >= 0.
4682 //
4683 // The difficulty here is that the NSW flag may have been proven
4684 // relative to a loop that is to be found in a recurrence in LHS and
4685 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4686 // larger scope than intended.
4687 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4688
4689 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4690 }
4691
getTruncateOrZeroExtend(const SCEV * V,Type * Ty,unsigned Depth)4692 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4693 unsigned Depth) {
4694 Type *SrcTy = V->getType();
4695 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4696 "Cannot truncate or zero extend with non-integer arguments!");
4697 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4698 return V; // No conversion
4699 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4700 return getTruncateExpr(V, Ty, Depth);
4701 return getZeroExtendExpr(V, Ty, Depth);
4702 }
4703
getTruncateOrSignExtend(const SCEV * V,Type * Ty,unsigned Depth)4704 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4705 unsigned Depth) {
4706 Type *SrcTy = V->getType();
4707 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4708 "Cannot truncate or zero extend with non-integer arguments!");
4709 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4710 return V; // No conversion
4711 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4712 return getTruncateExpr(V, Ty, Depth);
4713 return getSignExtendExpr(V, Ty, Depth);
4714 }
4715
4716 const SCEV *
getNoopOrZeroExtend(const SCEV * V,Type * Ty)4717 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4718 Type *SrcTy = V->getType();
4719 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4720 "Cannot noop or zero extend with non-integer arguments!");
4721 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4722 "getNoopOrZeroExtend cannot truncate!");
4723 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4724 return V; // No conversion
4725 return getZeroExtendExpr(V, Ty);
4726 }
4727
4728 const SCEV *
getNoopOrSignExtend(const SCEV * V,Type * Ty)4729 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4730 Type *SrcTy = V->getType();
4731 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4732 "Cannot noop or sign extend with non-integer arguments!");
4733 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4734 "getNoopOrSignExtend cannot truncate!");
4735 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4736 return V; // No conversion
4737 return getSignExtendExpr(V, Ty);
4738 }
4739
4740 const SCEV *
getNoopOrAnyExtend(const SCEV * V,Type * Ty)4741 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4742 Type *SrcTy = V->getType();
4743 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4744 "Cannot noop or any extend with non-integer arguments!");
4745 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4746 "getNoopOrAnyExtend cannot truncate!");
4747 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4748 return V; // No conversion
4749 return getAnyExtendExpr(V, Ty);
4750 }
4751
4752 const SCEV *
getTruncateOrNoop(const SCEV * V,Type * Ty)4753 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4754 Type *SrcTy = V->getType();
4755 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4756 "Cannot truncate or noop with non-integer arguments!");
4757 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4758 "getTruncateOrNoop cannot extend!");
4759 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4760 return V; // No conversion
4761 return getTruncateExpr(V, Ty);
4762 }
4763
getUMaxFromMismatchedTypes(const SCEV * LHS,const SCEV * RHS)4764 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4765 const SCEV *RHS) {
4766 const SCEV *PromotedLHS = LHS;
4767 const SCEV *PromotedRHS = RHS;
4768
4769 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4770 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4771 else
4772 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4773
4774 return getUMaxExpr(PromotedLHS, PromotedRHS);
4775 }
4776
getUMinFromMismatchedTypes(const SCEV * LHS,const SCEV * RHS,bool Sequential)4777 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4778 const SCEV *RHS,
4779 bool Sequential) {
4780 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4781 return getUMinFromMismatchedTypes(Ops, Sequential);
4782 }
4783
4784 const SCEV *
getUMinFromMismatchedTypes(SmallVectorImpl<const SCEV * > & Ops,bool Sequential)4785 ScalarEvolution::getUMinFromMismatchedTypes(SmallVectorImpl<const SCEV *> &Ops,
4786 bool Sequential) {
4787 assert(!Ops.empty() && "At least one operand must be!");
4788 // Trivial case.
4789 if (Ops.size() == 1)
4790 return Ops[0];
4791
4792 // Find the max type first.
4793 Type *MaxType = nullptr;
4794 for (const auto *S : Ops)
4795 if (MaxType)
4796 MaxType = getWiderType(MaxType, S->getType());
4797 else
4798 MaxType = S->getType();
4799 assert(MaxType && "Failed to find maximum type!");
4800
4801 // Extend all ops to max type.
4802 SmallVector<const SCEV *, 2> PromotedOps;
4803 for (const auto *S : Ops)
4804 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4805
4806 // Generate umin.
4807 return getUMinExpr(PromotedOps, Sequential);
4808 }
4809
getPointerBase(const SCEV * V)4810 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4811 // A pointer operand may evaluate to a nonpointer expression, such as null.
4812 if (!V->getType()->isPointerTy())
4813 return V;
4814
4815 while (true) {
4816 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4817 V = AddRec->getStart();
4818 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4819 const SCEV *PtrOp = nullptr;
4820 for (const SCEV *AddOp : Add->operands()) {
4821 if (AddOp->getType()->isPointerTy()) {
4822 assert(!PtrOp && "Cannot have multiple pointer ops");
4823 PtrOp = AddOp;
4824 }
4825 }
4826 assert(PtrOp && "Must have pointer op");
4827 V = PtrOp;
4828 } else // Not something we can look further into.
4829 return V;
4830 }
4831 }
4832
4833 /// Push users of the given Instruction onto the given Worklist.
PushDefUseChildren(Instruction * I,SmallVectorImpl<Instruction * > & Worklist,SmallPtrSetImpl<Instruction * > & Visited)4834 static void PushDefUseChildren(Instruction *I,
4835 SmallVectorImpl<Instruction *> &Worklist,
4836 SmallPtrSetImpl<Instruction *> &Visited) {
4837 // Push the def-use children onto the Worklist stack.
4838 for (User *U : I->users()) {
4839 auto *UserInsn = cast<Instruction>(U);
4840 if (Visited.insert(UserInsn).second)
4841 Worklist.push_back(UserInsn);
4842 }
4843 }
4844
4845 namespace {
4846
4847 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4848 /// expression in case its Loop is L. If it is not L then
4849 /// if IgnoreOtherLoops is true then use AddRec itself
4850 /// otherwise rewrite cannot be done.
4851 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4852 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4853 public:
rewrite(const SCEV * S,const Loop * L,ScalarEvolution & SE,bool IgnoreOtherLoops=true)4854 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4855 bool IgnoreOtherLoops = true) {
4856 SCEVInitRewriter Rewriter(L, SE);
4857 const SCEV *Result = Rewriter.visit(S);
4858 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4859 return SE.getCouldNotCompute();
4860 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4861 ? SE.getCouldNotCompute()
4862 : Result;
4863 }
4864
visitUnknown(const SCEVUnknown * Expr)4865 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4866 if (!SE.isLoopInvariant(Expr, L))
4867 SeenLoopVariantSCEVUnknown = true;
4868 return Expr;
4869 }
4870
visitAddRecExpr(const SCEVAddRecExpr * Expr)4871 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4872 // Only re-write AddRecExprs for this loop.
4873 if (Expr->getLoop() == L)
4874 return Expr->getStart();
4875 SeenOtherLoops = true;
4876 return Expr;
4877 }
4878
hasSeenLoopVariantSCEVUnknown()4879 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4880
hasSeenOtherLoops()4881 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4882
4883 private:
SCEVInitRewriter(const Loop * L,ScalarEvolution & SE)4884 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4885 : SCEVRewriteVisitor(SE), L(L) {}
4886
4887 const Loop *L;
4888 bool SeenLoopVariantSCEVUnknown = false;
4889 bool SeenOtherLoops = false;
4890 };
4891
4892 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4893 /// increment expression in case its Loop is L. If it is not L then
4894 /// use AddRec itself.
4895 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4896 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4897 public:
rewrite(const SCEV * S,const Loop * L,ScalarEvolution & SE)4898 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4899 SCEVPostIncRewriter Rewriter(L, SE);
4900 const SCEV *Result = Rewriter.visit(S);
4901 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4902 ? SE.getCouldNotCompute()
4903 : Result;
4904 }
4905
visitUnknown(const SCEVUnknown * Expr)4906 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4907 if (!SE.isLoopInvariant(Expr, L))
4908 SeenLoopVariantSCEVUnknown = true;
4909 return Expr;
4910 }
4911
visitAddRecExpr(const SCEVAddRecExpr * Expr)4912 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4913 // Only re-write AddRecExprs for this loop.
4914 if (Expr->getLoop() == L)
4915 return Expr->getPostIncExpr(SE);
4916 SeenOtherLoops = true;
4917 return Expr;
4918 }
4919
hasSeenLoopVariantSCEVUnknown()4920 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4921
hasSeenOtherLoops()4922 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4923
4924 private:
SCEVPostIncRewriter(const Loop * L,ScalarEvolution & SE)4925 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4926 : SCEVRewriteVisitor(SE), L(L) {}
4927
4928 const Loop *L;
4929 bool SeenLoopVariantSCEVUnknown = false;
4930 bool SeenOtherLoops = false;
4931 };
4932
4933 /// This class evaluates the compare condition by matching it against the
4934 /// condition of loop latch. If there is a match we assume a true value
4935 /// for the condition while building SCEV nodes.
4936 class SCEVBackedgeConditionFolder
4937 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4938 public:
rewrite(const SCEV * S,const Loop * L,ScalarEvolution & SE)4939 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4940 ScalarEvolution &SE) {
4941 bool IsPosBECond = false;
4942 Value *BECond = nullptr;
4943 if (BasicBlock *Latch = L->getLoopLatch()) {
4944 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4945 if (BI && BI->isConditional()) {
4946 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4947 "Both outgoing branches should not target same header!");
4948 BECond = BI->getCondition();
4949 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4950 } else {
4951 return S;
4952 }
4953 }
4954 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4955 return Rewriter.visit(S);
4956 }
4957
visitUnknown(const SCEVUnknown * Expr)4958 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4959 const SCEV *Result = Expr;
4960 bool InvariantF = SE.isLoopInvariant(Expr, L);
4961
4962 if (!InvariantF) {
4963 Instruction *I = cast<Instruction>(Expr->getValue());
4964 switch (I->getOpcode()) {
4965 case Instruction::Select: {
4966 SelectInst *SI = cast<SelectInst>(I);
4967 std::optional<const SCEV *> Res =
4968 compareWithBackedgeCondition(SI->getCondition());
4969 if (Res) {
4970 bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
4971 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4972 }
4973 break;
4974 }
4975 default: {
4976 std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4977 if (Res)
4978 Result = *Res;
4979 break;
4980 }
4981 }
4982 }
4983 return Result;
4984 }
4985
4986 private:
SCEVBackedgeConditionFolder(const Loop * L,Value * BECond,bool IsPosBECond,ScalarEvolution & SE)4987 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4988 bool IsPosBECond, ScalarEvolution &SE)
4989 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4990 IsPositiveBECond(IsPosBECond) {}
4991
4992 std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4993
4994 const Loop *L;
4995 /// Loop back condition.
4996 Value *BackedgeCond = nullptr;
4997 /// Set to true if loop back is on positive branch condition.
4998 bool IsPositiveBECond;
4999 };
5000
5001 std::optional<const SCEV *>
compareWithBackedgeCondition(Value * IC)5002 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
5003
5004 // If value matches the backedge condition for loop latch,
5005 // then return a constant evolution node based on loopback
5006 // branch taken.
5007 if (BackedgeCond == IC)
5008 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
5009 : SE.getZero(Type::getInt1Ty(SE.getContext()));
5010 return std::nullopt;
5011 }
5012
5013 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
5014 public:
rewrite(const SCEV * S,const Loop * L,ScalarEvolution & SE)5015 static const SCEV *rewrite(const SCEV *S, const Loop *L,
5016 ScalarEvolution &SE) {
5017 SCEVShiftRewriter Rewriter(L, SE);
5018 const SCEV *Result = Rewriter.visit(S);
5019 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
5020 }
5021
visitUnknown(const SCEVUnknown * Expr)5022 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5023 // Only allow AddRecExprs for this loop.
5024 if (!SE.isLoopInvariant(Expr, L))
5025 Valid = false;
5026 return Expr;
5027 }
5028
visitAddRecExpr(const SCEVAddRecExpr * Expr)5029 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5030 if (Expr->getLoop() == L && Expr->isAffine())
5031 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
5032 Valid = false;
5033 return Expr;
5034 }
5035
isValid()5036 bool isValid() { return Valid; }
5037
5038 private:
SCEVShiftRewriter(const Loop * L,ScalarEvolution & SE)5039 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
5040 : SCEVRewriteVisitor(SE), L(L) {}
5041
5042 const Loop *L;
5043 bool Valid = true;
5044 };
5045
5046 } // end anonymous namespace
5047
5048 SCEV::NoWrapFlags
proveNoWrapViaConstantRanges(const SCEVAddRecExpr * AR)5049 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
5050 if (!AR->isAffine())
5051 return SCEV::FlagAnyWrap;
5052
5053 using OBO = OverflowingBinaryOperator;
5054
5055 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
5056
5057 if (!AR->hasNoSignedWrap()) {
5058 ConstantRange AddRecRange = getSignedRange(AR);
5059 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
5060
5061 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
5062 Instruction::Add, IncRange, OBO::NoSignedWrap);
5063 if (NSWRegion.contains(AddRecRange))
5064 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
5065 }
5066
5067 if (!AR->hasNoUnsignedWrap()) {
5068 ConstantRange AddRecRange = getUnsignedRange(AR);
5069 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
5070
5071 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
5072 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
5073 if (NUWRegion.contains(AddRecRange))
5074 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
5075 }
5076
5077 return Result;
5078 }
5079
5080 SCEV::NoWrapFlags
proveNoSignedWrapViaInduction(const SCEVAddRecExpr * AR)5081 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5082 SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
5083
5084 if (AR->hasNoSignedWrap())
5085 return Result;
5086
5087 if (!AR->isAffine())
5088 return Result;
5089
5090 // This function can be expensive, only try to prove NSW once per AddRec.
5091 if (!SignedWrapViaInductionTried.insert(AR).second)
5092 return Result;
5093
5094 const SCEV *Step = AR->getStepRecurrence(*this);
5095 const Loop *L = AR->getLoop();
5096
5097 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5098 // Note that this serves two purposes: It filters out loops that are
5099 // simply not analyzable, and it covers the case where this code is
5100 // being called from within backedge-taken count analysis, such that
5101 // attempting to ask for the backedge-taken count would likely result
5102 // in infinite recursion. In the later case, the analysis code will
5103 // cope with a conservative value, and it will take care to purge
5104 // that value once it has finished.
5105 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5106
5107 // Normally, in the cases we can prove no-overflow via a
5108 // backedge guarding condition, we can also compute a backedge
5109 // taken count for the loop. The exceptions are assumptions and
5110 // guards present in the loop -- SCEV is not great at exploiting
5111 // these to compute max backedge taken counts, but can still use
5112 // these to prove lack of overflow. Use this fact to avoid
5113 // doing extra work that may not pay off.
5114
5115 if (isa<SCEVCouldNotCompute>(MaxBECount) && AC.assumptions().empty())
5116 return Result;
5117
5118 // If the backedge is guarded by a comparison with the pre-inc value the
5119 // addrec is safe. Also, if the entry is guarded by a comparison with the
5120 // start value and the backedge is guarded by a comparison with the post-inc
5121 // value, the addrec is safe.
5122 ICmpInst::Predicate Pred;
5123 const SCEV *OverflowLimit =
5124 getSignedOverflowLimitForStep(Step, &Pred, this);
5125 if (OverflowLimit &&
5126 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5127 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
5128 Result = setFlags(Result, SCEV::FlagNSW);
5129 }
5130 return Result;
5131 }
5132 SCEV::NoWrapFlags
proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr * AR)5133 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5134 SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
5135
5136 if (AR->hasNoUnsignedWrap())
5137 return Result;
5138
5139 if (!AR->isAffine())
5140 return Result;
5141
5142 // This function can be expensive, only try to prove NUW once per AddRec.
5143 if (!UnsignedWrapViaInductionTried.insert(AR).second)
5144 return Result;
5145
5146 const SCEV *Step = AR->getStepRecurrence(*this);
5147 unsigned BitWidth = getTypeSizeInBits(AR->getType());
5148 const Loop *L = AR->getLoop();
5149
5150 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5151 // Note that this serves two purposes: It filters out loops that are
5152 // simply not analyzable, and it covers the case where this code is
5153 // being called from within backedge-taken count analysis, such that
5154 // attempting to ask for the backedge-taken count would likely result
5155 // in infinite recursion. In the later case, the analysis code will
5156 // cope with a conservative value, and it will take care to purge
5157 // that value once it has finished.
5158 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5159
5160 // Normally, in the cases we can prove no-overflow via a
5161 // backedge guarding condition, we can also compute a backedge
5162 // taken count for the loop. The exceptions are assumptions and
5163 // guards present in the loop -- SCEV is not great at exploiting
5164 // these to compute max backedge taken counts, but can still use
5165 // these to prove lack of overflow. Use this fact to avoid
5166 // doing extra work that may not pay off.
5167
5168 if (isa<SCEVCouldNotCompute>(MaxBECount) && AC.assumptions().empty())
5169 return Result;
5170
5171 // If the backedge is guarded by a comparison with the pre-inc value the
5172 // addrec is safe. Also, if the entry is guarded by a comparison with the
5173 // start value and the backedge is guarded by a comparison with the post-inc
5174 // value, the addrec is safe.
5175 if (isKnownPositive(Step)) {
5176 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
5177 getUnsignedRangeMax(Step));
5178 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
5179 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
5180 Result = setFlags(Result, SCEV::FlagNUW);
5181 }
5182 }
5183
5184 return Result;
5185 }
5186
5187 namespace {
5188
5189 /// Represents an abstract binary operation. This may exist as a
5190 /// normal instruction or constant expression, or may have been
5191 /// derived from an expression tree.
5192 struct BinaryOp {
5193 unsigned Opcode;
5194 Value *LHS;
5195 Value *RHS;
5196 bool IsNSW = false;
5197 bool IsNUW = false;
5198
5199 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5200 /// constant expression.
5201 Operator *Op = nullptr;
5202
BinaryOp__anon70687fab1611::BinaryOp5203 explicit BinaryOp(Operator *Op)
5204 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5205 Op(Op) {
5206 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5207 IsNSW = OBO->hasNoSignedWrap();
5208 IsNUW = OBO->hasNoUnsignedWrap();
5209 }
5210 }
5211
BinaryOp__anon70687fab1611::BinaryOp5212 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5213 bool IsNUW = false)
5214 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5215 };
5216
5217 } // end anonymous namespace
5218
5219 /// 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)5220 static std::optional<BinaryOp> MatchBinaryOp(Value *V, const DataLayout &DL,
5221 AssumptionCache &AC,
5222 const DominatorTree &DT,
5223 const Instruction *CxtI) {
5224 auto *Op = dyn_cast<Operator>(V);
5225 if (!Op)
5226 return std::nullopt;
5227
5228 // Implementation detail: all the cleverness here should happen without
5229 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5230 // SCEV expressions when possible, and we should not break that.
5231
5232 switch (Op->getOpcode()) {
5233 case Instruction::Add:
5234 case Instruction::Sub:
5235 case Instruction::Mul:
5236 case Instruction::UDiv:
5237 case Instruction::URem:
5238 case Instruction::And:
5239 case Instruction::AShr:
5240 case Instruction::Shl:
5241 return BinaryOp(Op);
5242
5243 case Instruction::Or: {
5244 // LLVM loves to convert `add` of operands with no common bits
5245 // into an `or`. But SCEV really doesn't deal with `or` that well,
5246 // so try extra hard to recognize this `or` as an `add`.
5247 if (haveNoCommonBitsSet(Op->getOperand(0), Op->getOperand(1), DL, &AC, CxtI,
5248 &DT, /*UseInstrInfo=*/true))
5249 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
5250 /*IsNSW=*/true, /*IsNUW=*/true);
5251 return BinaryOp(Op);
5252 }
5253
5254 case Instruction::Xor:
5255 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5256 // If the RHS of the xor is a signmask, then this is just an add.
5257 // Instcombine turns add of signmask into xor as a strength reduction step.
5258 if (RHSC->getValue().isSignMask())
5259 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5260 // Binary `xor` is a bit-wise `add`.
5261 if (V->getType()->isIntegerTy(1))
5262 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5263 return BinaryOp(Op);
5264
5265 case Instruction::LShr:
5266 // Turn logical shift right of a constant into a unsigned divide.
5267 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5268 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5269
5270 // If the shift count is not less than the bitwidth, the result of
5271 // the shift is undefined. Don't try to analyze it, because the
5272 // resolution chosen here may differ from the resolution chosen in
5273 // other parts of the compiler.
5274 if (SA->getValue().ult(BitWidth)) {
5275 Constant *X =
5276 ConstantInt::get(SA->getContext(),
5277 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5278 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5279 }
5280 }
5281 return BinaryOp(Op);
5282
5283 case Instruction::ExtractValue: {
5284 auto *EVI = cast<ExtractValueInst>(Op);
5285 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5286 break;
5287
5288 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5289 if (!WO)
5290 break;
5291
5292 Instruction::BinaryOps BinOp = WO->getBinaryOp();
5293 bool Signed = WO->isSigned();
5294 // TODO: Should add nuw/nsw flags for mul as well.
5295 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5296 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5297
5298 // Now that we know that all uses of the arithmetic-result component of
5299 // CI are guarded by the overflow check, we can go ahead and pretend
5300 // that the arithmetic is non-overflowing.
5301 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5302 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5303 }
5304
5305 default:
5306 break;
5307 }
5308
5309 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5310 // semantics as a Sub, return a binary sub expression.
5311 if (auto *II = dyn_cast<IntrinsicInst>(V))
5312 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5313 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5314
5315 return std::nullopt;
5316 }
5317
5318 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
5319 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5320 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5321 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5322 /// follows one of the following patterns:
5323 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5324 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5325 /// If the SCEV expression of \p Op conforms with one of the expected patterns
5326 /// we return the type of the truncation operation, and indicate whether the
5327 /// truncated type should be treated as signed/unsigned by setting
5328 /// \p Signed to true/false, respectively.
isSimpleCastedPHI(const SCEV * Op,const SCEVUnknown * SymbolicPHI,bool & Signed,ScalarEvolution & SE)5329 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5330 bool &Signed, ScalarEvolution &SE) {
5331 // The case where Op == SymbolicPHI (that is, with no type conversions on
5332 // the way) is handled by the regular add recurrence creating logic and
5333 // would have already been triggered in createAddRecForPHI. Reaching it here
5334 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5335 // because one of the other operands of the SCEVAddExpr updating this PHI is
5336 // not invariant).
5337 //
5338 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5339 // this case predicates that allow us to prove that Op == SymbolicPHI will
5340 // be added.
5341 if (Op == SymbolicPHI)
5342 return nullptr;
5343
5344 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5345 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5346 if (SourceBits != NewBits)
5347 return nullptr;
5348
5349 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
5350 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
5351 if (!SExt && !ZExt)
5352 return nullptr;
5353 const SCEVTruncateExpr *Trunc =
5354 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
5355 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
5356 if (!Trunc)
5357 return nullptr;
5358 const SCEV *X = Trunc->getOperand();
5359 if (X != SymbolicPHI)
5360 return nullptr;
5361 Signed = SExt != nullptr;
5362 return Trunc->getType();
5363 }
5364
isIntegerLoopHeaderPHI(const PHINode * PN,LoopInfo & LI)5365 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5366 if (!PN->getType()->isIntegerTy())
5367 return nullptr;
5368 const Loop *L = LI.getLoopFor(PN->getParent());
5369 if (!L || L->getHeader() != PN->getParent())
5370 return nullptr;
5371 return L;
5372 }
5373
5374 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5375 // computation that updates the phi follows the following pattern:
5376 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5377 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
5378 // If so, try to see if it can be rewritten as an AddRecExpr under some
5379 // Predicates. If successful, return them as a pair. Also cache the results
5380 // of the analysis.
5381 //
5382 // Example usage scenario:
5383 // Say the Rewriter is called for the following SCEV:
5384 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5385 // where:
5386 // %X = phi i64 (%Start, %BEValue)
5387 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5388 // and call this function with %SymbolicPHI = %X.
5389 //
5390 // The analysis will find that the value coming around the backedge has
5391 // the following SCEV:
5392 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5393 // Upon concluding that this matches the desired pattern, the function
5394 // will return the pair {NewAddRec, SmallPredsVec} where:
5395 // NewAddRec = {%Start,+,%Step}
5396 // SmallPredsVec = {P1, P2, P3} as follows:
5397 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5398 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5399 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5400 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5401 // under the predicates {P1,P2,P3}.
5402 // This predicated rewrite will be cached in PredicatedSCEVRewrites:
5403 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5404 //
5405 // TODO's:
5406 //
5407 // 1) Extend the Induction descriptor to also support inductions that involve
5408 // casts: When needed (namely, when we are called in the context of the
5409 // vectorizer induction analysis), a Set of cast instructions will be
5410 // populated by this method, and provided back to isInductionPHI. This is
5411 // needed to allow the vectorizer to properly record them to be ignored by
5412 // the cost model and to avoid vectorizing them (otherwise these casts,
5413 // which are redundant under the runtime overflow checks, will be
5414 // vectorized, which can be costly).
5415 //
5416 // 2) Support additional induction/PHISCEV patterns: We also want to support
5417 // inductions where the sext-trunc / zext-trunc operations (partly) occur
5418 // after the induction update operation (the induction increment):
5419 //
5420 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5421 // which correspond to a phi->add->trunc->sext/zext->phi update chain.
5422 //
5423 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5424 // which correspond to a phi->trunc->add->sext/zext->phi update chain.
5425 //
5426 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
5427 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
createAddRecFromPHIWithCastsImpl(const SCEVUnknown * SymbolicPHI)5428 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5429 SmallVector<const SCEVPredicate *, 3> Predicates;
5430
5431 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5432 // return an AddRec expression under some predicate.
5433
5434 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5435 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5436 assert(L && "Expecting an integer loop header phi");
5437
5438 // The loop may have multiple entrances or multiple exits; we can analyze
5439 // this phi as an addrec if it has a unique entry value and a unique
5440 // backedge value.
5441 Value *BEValueV = nullptr, *StartValueV = nullptr;
5442 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5443 Value *V = PN->getIncomingValue(i);
5444 if (L->contains(PN->getIncomingBlock(i))) {
5445 if (!BEValueV) {
5446 BEValueV = V;
5447 } else if (BEValueV != V) {
5448 BEValueV = nullptr;
5449 break;
5450 }
5451 } else if (!StartValueV) {
5452 StartValueV = V;
5453 } else if (StartValueV != V) {
5454 StartValueV = nullptr;
5455 break;
5456 }
5457 }
5458 if (!BEValueV || !StartValueV)
5459 return std::nullopt;
5460
5461 const SCEV *BEValue = getSCEV(BEValueV);
5462
5463 // If the value coming around the backedge is an add with the symbolic
5464 // value we just inserted, possibly with casts that we can ignore under
5465 // an appropriate runtime guard, then we found a simple induction variable!
5466 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5467 if (!Add)
5468 return std::nullopt;
5469
5470 // If there is a single occurrence of the symbolic value, possibly
5471 // casted, replace it with a recurrence.
5472 unsigned FoundIndex = Add->getNumOperands();
5473 Type *TruncTy = nullptr;
5474 bool Signed;
5475 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5476 if ((TruncTy =
5477 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5478 if (FoundIndex == e) {
5479 FoundIndex = i;
5480 break;
5481 }
5482
5483 if (FoundIndex == Add->getNumOperands())
5484 return std::nullopt;
5485
5486 // Create an add with everything but the specified operand.
5487 SmallVector<const SCEV *, 8> Ops;
5488 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5489 if (i != FoundIndex)
5490 Ops.push_back(Add->getOperand(i));
5491 const SCEV *Accum = getAddExpr(Ops);
5492
5493 // The runtime checks will not be valid if the step amount is
5494 // varying inside the loop.
5495 if (!isLoopInvariant(Accum, L))
5496 return std::nullopt;
5497
5498 // *** Part2: Create the predicates
5499
5500 // Analysis was successful: we have a phi-with-cast pattern for which we
5501 // can return an AddRec expression under the following predicates:
5502 //
5503 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5504 // fits within the truncated type (does not overflow) for i = 0 to n-1.
5505 // P2: An Equal predicate that guarantees that
5506 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5507 // P3: An Equal predicate that guarantees that
5508 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5509 //
5510 // As we next prove, the above predicates guarantee that:
5511 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5512 //
5513 //
5514 // More formally, we want to prove that:
5515 // Expr(i+1) = Start + (i+1) * Accum
5516 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5517 //
5518 // Given that:
5519 // 1) Expr(0) = Start
5520 // 2) Expr(1) = Start + Accum
5521 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5522 // 3) Induction hypothesis (step i):
5523 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5524 //
5525 // Proof:
5526 // Expr(i+1) =
5527 // = Start + (i+1)*Accum
5528 // = (Start + i*Accum) + Accum
5529 // = Expr(i) + Accum
5530 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5531 // :: from step i
5532 //
5533 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5534 //
5535 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5536 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
5537 // + Accum :: from P3
5538 //
5539 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5540 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5541 //
5542 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5543 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5544 //
5545 // By induction, the same applies to all iterations 1<=i<n:
5546 //
5547
5548 // Create a truncated addrec for which we will add a no overflow check (P1).
5549 const SCEV *StartVal = getSCEV(StartValueV);
5550 const SCEV *PHISCEV =
5551 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5552 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5553
5554 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5555 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5556 // will be constant.
5557 //
5558 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5559 // add P1.
5560 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5561 SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
5562 Signed ? SCEVWrapPredicate::IncrementNSSW
5563 : SCEVWrapPredicate::IncrementNUSW;
5564 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5565 Predicates.push_back(AddRecPred);
5566 }
5567
5568 // Create the Equal Predicates P2,P3:
5569
5570 // It is possible that the predicates P2 and/or P3 are computable at
5571 // compile time due to StartVal and/or Accum being constants.
5572 // If either one is, then we can check that now and escape if either P2
5573 // or P3 is false.
5574
5575 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5576 // for each of StartVal and Accum
5577 auto getExtendedExpr = [&](const SCEV *Expr,
5578 bool CreateSignExtend) -> const SCEV * {
5579 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5580 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5581 const SCEV *ExtendedExpr =
5582 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5583 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5584 return ExtendedExpr;
5585 };
5586
5587 // Given:
5588 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5589 // = getExtendedExpr(Expr)
5590 // Determine whether the predicate P: Expr == ExtendedExpr
5591 // is known to be false at compile time
5592 auto PredIsKnownFalse = [&](const SCEV *Expr,
5593 const SCEV *ExtendedExpr) -> bool {
5594 return Expr != ExtendedExpr &&
5595 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5596 };
5597
5598 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5599 if (PredIsKnownFalse(StartVal, StartExtended)) {
5600 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5601 return std::nullopt;
5602 }
5603
5604 // The Step is always Signed (because the overflow checks are either
5605 // NSSW or NUSW)
5606 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5607 if (PredIsKnownFalse(Accum, AccumExtended)) {
5608 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5609 return std::nullopt;
5610 }
5611
5612 auto AppendPredicate = [&](const SCEV *Expr,
5613 const SCEV *ExtendedExpr) -> void {
5614 if (Expr != ExtendedExpr &&
5615 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5616 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5617 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5618 Predicates.push_back(Pred);
5619 }
5620 };
5621
5622 AppendPredicate(StartVal, StartExtended);
5623 AppendPredicate(Accum, AccumExtended);
5624
5625 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5626 // which the casts had been folded away. The caller can rewrite SymbolicPHI
5627 // into NewAR if it will also add the runtime overflow checks specified in
5628 // Predicates.
5629 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5630
5631 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5632 std::make_pair(NewAR, Predicates);
5633 // Remember the result of the analysis for this SCEV at this locayyytion.
5634 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5635 return PredRewrite;
5636 }
5637
5638 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
createAddRecFromPHIWithCasts(const SCEVUnknown * SymbolicPHI)5639 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
5640 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5641 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5642 if (!L)
5643 return std::nullopt;
5644
5645 // Check to see if we already analyzed this PHI.
5646 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5647 if (I != PredicatedSCEVRewrites.end()) {
5648 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5649 I->second;
5650 // Analysis was done before and failed to create an AddRec:
5651 if (Rewrite.first == SymbolicPHI)
5652 return std::nullopt;
5653 // Analysis was done before and succeeded to create an AddRec under
5654 // a predicate:
5655 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5656 assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5657 return Rewrite;
5658 }
5659
5660 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5661 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5662
5663 // Record in the cache that the analysis failed
5664 if (!Rewrite) {
5665 SmallVector<const SCEVPredicate *, 3> Predicates;
5666 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5667 return std::nullopt;
5668 }
5669
5670 return Rewrite;
5671 }
5672
5673 // FIXME: This utility is currently required because the Rewriter currently
5674 // does not rewrite this expression:
5675 // {0, +, (sext ix (trunc iy to ix) to iy)}
5676 // into {0, +, %step},
5677 // even when the following Equal predicate exists:
5678 // "%step == (sext ix (trunc iy to ix) to iy)".
areAddRecsEqualWithPreds(const SCEVAddRecExpr * AR1,const SCEVAddRecExpr * AR2) const5679 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5680 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
5681 if (AR1 == AR2)
5682 return true;
5683
5684 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5685 if (Expr1 != Expr2 && !Preds->implies(SE.getEqualPredicate(Expr1, Expr2)) &&
5686 !Preds->implies(SE.getEqualPredicate(Expr2, Expr1)))
5687 return false;
5688 return true;
5689 };
5690
5691 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5692 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5693 return false;
5694 return true;
5695 }
5696
5697 /// A helper function for createAddRecFromPHI to handle simple cases.
5698 ///
5699 /// This function tries to find an AddRec expression for the simplest (yet most
5700 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5701 /// If it fails, createAddRecFromPHI will use a more general, but slow,
5702 /// technique for finding the AddRec expression.
createSimpleAffineAddRec(PHINode * PN,Value * BEValueV,Value * StartValueV)5703 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5704 Value *BEValueV,
5705 Value *StartValueV) {
5706 const Loop *L = LI.getLoopFor(PN->getParent());
5707 assert(L && L->getHeader() == PN->getParent());
5708 assert(BEValueV && StartValueV);
5709
5710 auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN);
5711 if (!BO)
5712 return nullptr;
5713
5714 if (BO->Opcode != Instruction::Add)
5715 return nullptr;
5716
5717 const SCEV *Accum = nullptr;
5718 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5719 Accum = getSCEV(BO->RHS);
5720 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5721 Accum = getSCEV(BO->LHS);
5722
5723 if (!Accum)
5724 return nullptr;
5725
5726 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5727 if (BO->IsNUW)
5728 Flags = setFlags(Flags, SCEV::FlagNUW);
5729 if (BO->IsNSW)
5730 Flags = setFlags(Flags, SCEV::FlagNSW);
5731
5732 const SCEV *StartVal = getSCEV(StartValueV);
5733 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5734 insertValueToMap(PN, PHISCEV);
5735
5736 // We can add Flags to the post-inc expression only if we
5737 // know that it is *undefined behavior* for BEValueV to
5738 // overflow.
5739 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5740 assert(isLoopInvariant(Accum, L) &&
5741 "Accum is defined outside L, but is not invariant?");
5742 if (isAddRecNeverPoison(BEInst, L))
5743 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5744 }
5745
5746 return PHISCEV;
5747 }
5748
createAddRecFromPHI(PHINode * PN)5749 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5750 const Loop *L = LI.getLoopFor(PN->getParent());
5751 if (!L || L->getHeader() != PN->getParent())
5752 return nullptr;
5753
5754 // The loop may have multiple entrances or multiple exits; we can analyze
5755 // this phi as an addrec if it has a unique entry value and a unique
5756 // backedge value.
5757 Value *BEValueV = nullptr, *StartValueV = nullptr;
5758 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5759 Value *V = PN->getIncomingValue(i);
5760 if (L->contains(PN->getIncomingBlock(i))) {
5761 if (!BEValueV) {
5762 BEValueV = V;
5763 } else if (BEValueV != V) {
5764 BEValueV = nullptr;
5765 break;
5766 }
5767 } else if (!StartValueV) {
5768 StartValueV = V;
5769 } else if (StartValueV != V) {
5770 StartValueV = nullptr;
5771 break;
5772 }
5773 }
5774 if (!BEValueV || !StartValueV)
5775 return nullptr;
5776
5777 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5778 "PHI node already processed?");
5779
5780 // First, try to find AddRec expression without creating a fictituos symbolic
5781 // value for PN.
5782 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5783 return S;
5784
5785 // Handle PHI node value symbolically.
5786 const SCEV *SymbolicName = getUnknown(PN);
5787 insertValueToMap(PN, SymbolicName);
5788
5789 // Using this symbolic name for the PHI, analyze the value coming around
5790 // the back-edge.
5791 const SCEV *BEValue = getSCEV(BEValueV);
5792
5793 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5794 // has a special value for the first iteration of the loop.
5795
5796 // If the value coming around the backedge is an add with the symbolic
5797 // value we just inserted, then we found a simple induction variable!
5798 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5799 // If there is a single occurrence of the symbolic value, replace it
5800 // with a recurrence.
5801 unsigned FoundIndex = Add->getNumOperands();
5802 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5803 if (Add->getOperand(i) == SymbolicName)
5804 if (FoundIndex == e) {
5805 FoundIndex = i;
5806 break;
5807 }
5808
5809 if (FoundIndex != Add->getNumOperands()) {
5810 // Create an add with everything but the specified operand.
5811 SmallVector<const SCEV *, 8> Ops;
5812 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5813 if (i != FoundIndex)
5814 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5815 L, *this));
5816 const SCEV *Accum = getAddExpr(Ops);
5817
5818 // This is not a valid addrec if the step amount is varying each
5819 // loop iteration, but is not itself an addrec in this loop.
5820 if (isLoopInvariant(Accum, L) ||
5821 (isa<SCEVAddRecExpr>(Accum) &&
5822 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5823 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5824
5825 if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
5826 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5827 if (BO->IsNUW)
5828 Flags = setFlags(Flags, SCEV::FlagNUW);
5829 if (BO->IsNSW)
5830 Flags = setFlags(Flags, SCEV::FlagNSW);
5831 }
5832 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5833 // If the increment is an inbounds GEP, then we know the address
5834 // space cannot be wrapped around. We cannot make any guarantee
5835 // about signed or unsigned overflow because pointers are
5836 // unsigned but we may have a negative index from the base
5837 // pointer. We can guarantee that no unsigned wrap occurs if the
5838 // indices form a positive value.
5839 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5840 Flags = setFlags(Flags, SCEV::FlagNW);
5841
5842 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5843 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5844 Flags = setFlags(Flags, SCEV::FlagNUW);
5845 }
5846
5847 // We cannot transfer nuw and nsw flags from subtraction
5848 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5849 // for instance.
5850 }
5851
5852 const SCEV *StartVal = getSCEV(StartValueV);
5853 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5854
5855 // Okay, for the entire analysis of this edge we assumed the PHI
5856 // to be symbolic. We now need to go back and purge all of the
5857 // entries for the scalars that use the symbolic expression.
5858 forgetMemoizedResults(SymbolicName);
5859 insertValueToMap(PN, PHISCEV);
5860
5861 // We can add Flags to the post-inc expression only if we
5862 // know that it is *undefined behavior* for BEValueV to
5863 // overflow.
5864 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5865 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5866 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5867
5868 return PHISCEV;
5869 }
5870 }
5871 } else {
5872 // Otherwise, this could be a loop like this:
5873 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5874 // In this case, j = {1,+,1} and BEValue is j.
5875 // Because the other in-value of i (0) fits the evolution of BEValue
5876 // i really is an addrec evolution.
5877 //
5878 // We can generalize this saying that i is the shifted value of BEValue
5879 // by one iteration:
5880 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5881 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5882 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5883 if (Shifted != getCouldNotCompute() &&
5884 Start != getCouldNotCompute()) {
5885 const SCEV *StartVal = getSCEV(StartValueV);
5886 if (Start == StartVal) {
5887 // Okay, for the entire analysis of this edge we assumed the PHI
5888 // to be symbolic. We now need to go back and purge all of the
5889 // entries for the scalars that use the symbolic expression.
5890 forgetMemoizedResults(SymbolicName);
5891 insertValueToMap(PN, Shifted);
5892 return Shifted;
5893 }
5894 }
5895 }
5896
5897 // Remove the temporary PHI node SCEV that has been inserted while intending
5898 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5899 // as it will prevent later (possibly simpler) SCEV expressions to be added
5900 // to the ValueExprMap.
5901 eraseValueFromMap(PN);
5902
5903 return nullptr;
5904 }
5905
5906 // Checks if the SCEV S is available at BB. S is considered available at BB
5907 // if S can be materialized at BB without introducing a fault.
IsAvailableOnEntry(const Loop * L,DominatorTree & DT,const SCEV * S,BasicBlock * BB)5908 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5909 BasicBlock *BB) {
5910 struct CheckAvailable {
5911 bool TraversalDone = false;
5912 bool Available = true;
5913
5914 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
5915 BasicBlock *BB = nullptr;
5916 DominatorTree &DT;
5917
5918 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5919 : L(L), BB(BB), DT(DT) {}
5920
5921 bool setUnavailable() {
5922 TraversalDone = true;
5923 Available = false;
5924 return false;
5925 }
5926
5927 bool follow(const SCEV *S) {
5928 switch (S->getSCEVType()) {
5929 case scConstant:
5930 case scPtrToInt:
5931 case scTruncate:
5932 case scZeroExtend:
5933 case scSignExtend:
5934 case scAddExpr:
5935 case scMulExpr:
5936 case scUMaxExpr:
5937 case scSMaxExpr:
5938 case scUMinExpr:
5939 case scSMinExpr:
5940 case scSequentialUMinExpr:
5941 // These expressions are available if their operand(s) is/are.
5942 return true;
5943
5944 case scAddRecExpr: {
5945 // We allow add recurrences that are on the loop BB is in, or some
5946 // outer loop. This guarantees availability because the value of the
5947 // add recurrence at BB is simply the "current" value of the induction
5948 // variable. We can relax this in the future; for instance an add
5949 // recurrence on a sibling dominating loop is also available at BB.
5950 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5951 if (L && (ARLoop == L || ARLoop->contains(L)))
5952 return true;
5953
5954 return setUnavailable();
5955 }
5956
5957 case scUnknown: {
5958 // For SCEVUnknown, we check for simple dominance.
5959 const auto *SU = cast<SCEVUnknown>(S);
5960 Value *V = SU->getValue();
5961
5962 if (isa<Argument>(V))
5963 return false;
5964
5965 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5966 return false;
5967
5968 return setUnavailable();
5969 }
5970
5971 case scUDivExpr:
5972 case scCouldNotCompute:
5973 // We do not try to smart about these at all.
5974 return setUnavailable();
5975 }
5976 llvm_unreachable("Unknown SCEV kind!");
5977 }
5978
5979 bool isDone() { return TraversalDone; }
5980 };
5981
5982 CheckAvailable CA(L, BB, DT);
5983 SCEVTraversal<CheckAvailable> ST(CA);
5984
5985 ST.visitAll(S);
5986 return CA.Available;
5987 }
5988
5989 // Try to match a control flow sequence that branches out at BI and merges back
5990 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5991 // match.
BrPHIToSelect(DominatorTree & DT,BranchInst * BI,PHINode * Merge,Value * & C,Value * & LHS,Value * & RHS)5992 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5993 Value *&C, Value *&LHS, Value *&RHS) {
5994 C = BI->getCondition();
5995
5996 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5997 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5998
5999 if (!LeftEdge.isSingleEdge())
6000 return false;
6001
6002 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
6003
6004 Use &LeftUse = Merge->getOperandUse(0);
6005 Use &RightUse = Merge->getOperandUse(1);
6006
6007 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
6008 LHS = LeftUse;
6009 RHS = RightUse;
6010 return true;
6011 }
6012
6013 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
6014 LHS = RightUse;
6015 RHS = LeftUse;
6016 return true;
6017 }
6018
6019 return false;
6020 }
6021
createNodeFromSelectLikePHI(PHINode * PN)6022 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
6023 auto IsReachable =
6024 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
6025 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
6026 const Loop *L = LI.getLoopFor(PN->getParent());
6027
6028 // We don't want to break LCSSA, even in a SCEV expression tree.
6029 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
6030 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
6031 return nullptr;
6032
6033 // Try to match
6034 //
6035 // br %cond, label %left, label %right
6036 // left:
6037 // br label %merge
6038 // right:
6039 // br label %merge
6040 // merge:
6041 // V = phi [ %x, %left ], [ %y, %right ]
6042 //
6043 // as "select %cond, %x, %y"
6044
6045 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
6046 assert(IDom && "At least the entry block should dominate PN");
6047
6048 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
6049 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6050
6051 if (BI && BI->isConditional() &&
6052 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
6053 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
6054 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
6055 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
6056 }
6057
6058 return nullptr;
6059 }
6060
createNodeForPHI(PHINode * PN)6061 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
6062 if (const SCEV *S = createAddRecFromPHI(PN))
6063 return S;
6064
6065 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
6066 return S;
6067
6068 if (Value *V = simplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
6069 return getSCEV(V);
6070
6071 // If it's not a loop phi, we can't handle it yet.
6072 return getUnknown(PN);
6073 }
6074
SCEVMinMaxExprContains(const SCEV * Root,const SCEV * OperandToFind,SCEVTypes RootKind)6075 bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
6076 SCEVTypes RootKind) {
6077 struct FindClosure {
6078 const SCEV *OperandToFind;
6079 const SCEVTypes RootKind; // Must be a sequential min/max expression.
6080 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
6081
6082 bool Found = false;
6083
6084 bool canRecurseInto(SCEVTypes Kind) const {
6085 // We can only recurse into the SCEV expression of the same effective type
6086 // as the type of our root SCEV expression, and into zero-extensions.
6087 return RootKind == Kind || NonSequentialRootKind == Kind ||
6088 scZeroExtend == Kind;
6089 };
6090
6091 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
6092 : OperandToFind(OperandToFind), RootKind(RootKind),
6093 NonSequentialRootKind(
6094 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
6095 RootKind)) {}
6096
6097 bool follow(const SCEV *S) {
6098 Found = S == OperandToFind;
6099
6100 return !isDone() && canRecurseInto(S->getSCEVType());
6101 }
6102
6103 bool isDone() const { return Found; }
6104 };
6105
6106 FindClosure FC(OperandToFind, RootKind);
6107 visitAll(Root, FC);
6108 return FC.Found;
6109 }
6110
6111 std::optional<const SCEV *>
createNodeForSelectOrPHIInstWithICmpInstCond(Type * Ty,ICmpInst * Cond,Value * TrueVal,Value * FalseVal)6112 ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
6113 ICmpInst *Cond,
6114 Value *TrueVal,
6115 Value *FalseVal) {
6116 // Try to match some simple smax or umax patterns.
6117 auto *ICI = Cond;
6118
6119 Value *LHS = ICI->getOperand(0);
6120 Value *RHS = ICI->getOperand(1);
6121
6122 switch (ICI->getPredicate()) {
6123 case ICmpInst::ICMP_SLT:
6124 case ICmpInst::ICMP_SLE:
6125 case ICmpInst::ICMP_ULT:
6126 case ICmpInst::ICMP_ULE:
6127 std::swap(LHS, RHS);
6128 [[fallthrough]];
6129 case ICmpInst::ICMP_SGT:
6130 case ICmpInst::ICMP_SGE:
6131 case ICmpInst::ICMP_UGT:
6132 case ICmpInst::ICMP_UGE:
6133 // a > b ? a+x : b+x -> max(a, b)+x
6134 // a > b ? b+x : a+x -> min(a, b)+x
6135 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(Ty)) {
6136 bool Signed = ICI->isSigned();
6137 const SCEV *LA = getSCEV(TrueVal);
6138 const SCEV *RA = getSCEV(FalseVal);
6139 const SCEV *LS = getSCEV(LHS);
6140 const SCEV *RS = getSCEV(RHS);
6141 if (LA->getType()->isPointerTy()) {
6142 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6143 // Need to make sure we can't produce weird expressions involving
6144 // negated pointers.
6145 if (LA == LS && RA == RS)
6146 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6147 if (LA == RS && RA == LS)
6148 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6149 }
6150 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6151 if (Op->getType()->isPointerTy()) {
6152 Op = getLosslessPtrToIntExpr(Op);
6153 if (isa<SCEVCouldNotCompute>(Op))
6154 return Op;
6155 }
6156 if (Signed)
6157 Op = getNoopOrSignExtend(Op, Ty);
6158 else
6159 Op = getNoopOrZeroExtend(Op, Ty);
6160 return Op;
6161 };
6162 LS = CoerceOperand(LS);
6163 RS = CoerceOperand(RS);
6164 if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS))
6165 break;
6166 const SCEV *LDiff = getMinusSCEV(LA, LS);
6167 const SCEV *RDiff = getMinusSCEV(RA, RS);
6168 if (LDiff == RDiff)
6169 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6170 LDiff);
6171 LDiff = getMinusSCEV(LA, RS);
6172 RDiff = getMinusSCEV(RA, LS);
6173 if (LDiff == RDiff)
6174 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6175 LDiff);
6176 }
6177 break;
6178 case ICmpInst::ICMP_NE:
6179 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
6180 std::swap(TrueVal, FalseVal);
6181 [[fallthrough]];
6182 case ICmpInst::ICMP_EQ:
6183 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
6184 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(Ty) &&
6185 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
6186 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6187 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y
6188 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y
6189 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6190 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y
6191 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6192 return getAddExpr(getUMaxExpr(X, C), Y);
6193 }
6194 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
6195 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
6196 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
6197 // -> umin_seq(x, umin (..., umin_seq(...), ...))
6198 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero() &&
6199 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6200 const SCEV *X = getSCEV(LHS);
6201 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6202 X = ZExt->getOperand();
6203 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6204 const SCEV *FalseValExpr = getSCEV(FalseVal);
6205 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6206 return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6207 /*Sequential=*/true);
6208 }
6209 }
6210 break;
6211 default:
6212 break;
6213 }
6214
6215 return std::nullopt;
6216 }
6217
6218 static std::optional<const SCEV *>
createNodeForSelectViaUMinSeq(ScalarEvolution * SE,const SCEV * CondExpr,const SCEV * TrueExpr,const SCEV * FalseExpr)6219 createNodeForSelectViaUMinSeq(ScalarEvolution *SE, const SCEV *CondExpr,
6220 const SCEV *TrueExpr, const SCEV *FalseExpr) {
6221 assert(CondExpr->getType()->isIntegerTy(1) &&
6222 TrueExpr->getType() == FalseExpr->getType() &&
6223 TrueExpr->getType()->isIntegerTy(1) &&
6224 "Unexpected operands of a select.");
6225
6226 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
6227 // --> C + (umin_seq cond, x - C)
6228 //
6229 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
6230 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6231 // --> C + (umin_seq ~cond, x - C)
6232
6233 // FIXME: while we can't legally model the case where both of the hands
6234 // are fully variable, we only require that the *difference* is constant.
6235 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6236 return std::nullopt;
6237
6238 const SCEV *X, *C;
6239 if (isa<SCEVConstant>(TrueExpr)) {
6240 CondExpr = SE->getNotSCEV(CondExpr);
6241 X = FalseExpr;
6242 C = TrueExpr;
6243 } else {
6244 X = TrueExpr;
6245 C = FalseExpr;
6246 }
6247 return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6248 /*Sequential=*/true));
6249 }
6250
6251 static std::optional<const SCEV *>
createNodeForSelectViaUMinSeq(ScalarEvolution * SE,Value * Cond,Value * TrueVal,Value * FalseVal)6252 createNodeForSelectViaUMinSeq(ScalarEvolution *SE, Value *Cond, Value *TrueVal,
6253 Value *FalseVal) {
6254 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6255 return std::nullopt;
6256
6257 const auto *SECond = SE->getSCEV(Cond);
6258 const auto *SETrue = SE->getSCEV(TrueVal);
6259 const auto *SEFalse = SE->getSCEV(FalseVal);
6260 return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6261 }
6262
createNodeForSelectOrPHIViaUMinSeq(Value * V,Value * Cond,Value * TrueVal,Value * FalseVal)6263 const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6264 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6265 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6266 assert(TrueVal->getType() == FalseVal->getType() &&
6267 V->getType() == TrueVal->getType() &&
6268 "Types of select hands and of the result must match.");
6269
6270 // For now, only deal with i1-typed `select`s.
6271 if (!V->getType()->isIntegerTy(1))
6272 return getUnknown(V);
6273
6274 if (std::optional<const SCEV *> S =
6275 createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6276 return *S;
6277
6278 return getUnknown(V);
6279 }
6280
createNodeForSelectOrPHI(Value * V,Value * Cond,Value * TrueVal,Value * FalseVal)6281 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6282 Value *TrueVal,
6283 Value *FalseVal) {
6284 // Handle "constant" branch or select. This can occur for instance when a
6285 // loop pass transforms an inner loop and moves on to process the outer loop.
6286 if (auto *CI = dyn_cast<ConstantInt>(Cond))
6287 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6288
6289 if (auto *I = dyn_cast<Instruction>(V)) {
6290 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6291 if (std::optional<const SCEV *> S =
6292 createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6293 TrueVal, FalseVal))
6294 return *S;
6295 }
6296 }
6297
6298 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6299 }
6300
6301 /// Expand GEP instructions into add and multiply operations. This allows them
6302 /// to be analyzed by regular SCEV code.
createNodeForGEP(GEPOperator * GEP)6303 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6304 assert(GEP->getSourceElementType()->isSized() &&
6305 "GEP source element type must be sized");
6306
6307 SmallVector<const SCEV *, 4> IndexExprs;
6308 for (Value *Index : GEP->indices())
6309 IndexExprs.push_back(getSCEV(Index));
6310 return getGEPExpr(GEP, IndexExprs);
6311 }
6312
GetMinTrailingZerosImpl(const SCEV * S)6313 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
6314 switch (S->getSCEVType()) {
6315 case scConstant:
6316 return cast<SCEVConstant>(S)->getAPInt().countTrailingZeros();
6317 case scTruncate: {
6318 const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6319 return std::min(GetMinTrailingZeros(T->getOperand()),
6320 (uint32_t)getTypeSizeInBits(T->getType()));
6321 }
6322 case scZeroExtend: {
6323 const SCEVZeroExtendExpr *E = cast<SCEVZeroExtendExpr>(S);
6324 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
6325 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
6326 ? getTypeSizeInBits(E->getType())
6327 : OpRes;
6328 }
6329 case scSignExtend: {
6330 const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6331 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
6332 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
6333 ? getTypeSizeInBits(E->getType())
6334 : OpRes;
6335 }
6336 case scMulExpr: {
6337 const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6338 // The result is the sum of all operands results.
6339 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
6340 uint32_t BitWidth = getTypeSizeInBits(M->getType());
6341 for (unsigned i = 1, e = M->getNumOperands();
6342 SumOpRes != BitWidth && i != e; ++i)
6343 SumOpRes =
6344 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
6345 return SumOpRes;
6346 }
6347 case scUDivExpr:
6348 return 0;
6349 case scPtrToInt:
6350 case scAddExpr:
6351 case scAddRecExpr:
6352 case scUMaxExpr:
6353 case scSMaxExpr:
6354 case scUMinExpr:
6355 case scSMinExpr:
6356 case scSequentialUMinExpr: {
6357 // The result is the min of all operands results.
6358 ArrayRef<const SCEV *> Ops = S->operands();
6359 uint32_t MinOpRes = GetMinTrailingZeros(Ops[0]);
6360 for (unsigned I = 1, E = Ops.size(); MinOpRes && I != E; ++I)
6361 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(Ops[I]));
6362 return MinOpRes;
6363 }
6364 case scUnknown: {
6365 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6366 // For a SCEVUnknown, ask ValueTracking.
6367 KnownBits Known =
6368 computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
6369 return Known.countMinTrailingZeros();
6370 }
6371 case scCouldNotCompute:
6372 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6373 }
6374 llvm_unreachable("Unknown SCEV kind!");
6375 }
6376
GetMinTrailingZeros(const SCEV * S)6377 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
6378 auto I = MinTrailingZerosCache.find(S);
6379 if (I != MinTrailingZerosCache.end())
6380 return I->second;
6381
6382 uint32_t Result = GetMinTrailingZerosImpl(S);
6383 auto InsertPair = MinTrailingZerosCache.insert({S, Result});
6384 assert(InsertPair.second && "Should insert a new key");
6385 return InsertPair.first->second;
6386 }
6387
6388 /// Helper method to assign a range to V from metadata present in the IR.
GetRangeFromMetadata(Value * V)6389 static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6390 if (Instruction *I = dyn_cast<Instruction>(V))
6391 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6392 return getConstantRangeFromMetadata(*MD);
6393
6394 return std::nullopt;
6395 }
6396
setNoWrapFlags(SCEVAddRecExpr * AddRec,SCEV::NoWrapFlags Flags)6397 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
6398 SCEV::NoWrapFlags Flags) {
6399 if (AddRec->getNoWrapFlags(Flags) != Flags) {
6400 AddRec->setNoWrapFlags(Flags);
6401 UnsignedRanges.erase(AddRec);
6402 SignedRanges.erase(AddRec);
6403 }
6404 }
6405
6406 ConstantRange ScalarEvolution::
getRangeForUnknownRecurrence(const SCEVUnknown * U)6407 getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6408 const DataLayout &DL = getDataLayout();
6409
6410 unsigned BitWidth = getTypeSizeInBits(U->getType());
6411 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6412
6413 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6414 // use information about the trip count to improve our available range. Note
6415 // that the trip count independent cases are already handled by known bits.
6416 // WARNING: The definition of recurrence used here is subtly different than
6417 // the one used by AddRec (and thus most of this file). Step is allowed to
6418 // be arbitrarily loop varying here, where AddRec allows only loop invariant
6419 // and other addrecs in the same loop (for non-affine addrecs). The code
6420 // below intentionally handles the case where step is not loop invariant.
6421 auto *P = dyn_cast<PHINode>(U->getValue());
6422 if (!P)
6423 return FullSet;
6424
6425 // Make sure that no Phi input comes from an unreachable block. Otherwise,
6426 // even the values that are not available in these blocks may come from them,
6427 // and this leads to false-positive recurrence test.
6428 for (auto *Pred : predecessors(P->getParent()))
6429 if (!DT.isReachableFromEntry(Pred))
6430 return FullSet;
6431
6432 BinaryOperator *BO;
6433 Value *Start, *Step;
6434 if (!matchSimpleRecurrence(P, BO, Start, Step))
6435 return FullSet;
6436
6437 // If we found a recurrence in reachable code, we must be in a loop. Note
6438 // that BO might be in some subloop of L, and that's completely okay.
6439 auto *L = LI.getLoopFor(P->getParent());
6440 assert(L && L->getHeader() == P->getParent());
6441 if (!L->contains(BO->getParent()))
6442 // NOTE: This bailout should be an assert instead. However, asserting
6443 // the condition here exposes a case where LoopFusion is querying SCEV
6444 // with malformed loop information during the midst of the transform.
6445 // There doesn't appear to be an obvious fix, so for the moment bailout
6446 // until the caller issue can be fixed. PR49566 tracks the bug.
6447 return FullSet;
6448
6449 // TODO: Extend to other opcodes such as mul, and div
6450 switch (BO->getOpcode()) {
6451 default:
6452 return FullSet;
6453 case Instruction::AShr:
6454 case Instruction::LShr:
6455 case Instruction::Shl:
6456 break;
6457 };
6458
6459 if (BO->getOperand(0) != P)
6460 // TODO: Handle the power function forms some day.
6461 return FullSet;
6462
6463 unsigned TC = getSmallConstantMaxTripCount(L);
6464 if (!TC || TC >= BitWidth)
6465 return FullSet;
6466
6467 auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT);
6468 auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT);
6469 assert(KnownStart.getBitWidth() == BitWidth &&
6470 KnownStep.getBitWidth() == BitWidth);
6471
6472 // Compute total shift amount, being careful of overflow and bitwidths.
6473 auto MaxShiftAmt = KnownStep.getMaxValue();
6474 APInt TCAP(BitWidth, TC-1);
6475 bool Overflow = false;
6476 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6477 if (Overflow)
6478 return FullSet;
6479
6480 switch (BO->getOpcode()) {
6481 default:
6482 llvm_unreachable("filtered out above");
6483 case Instruction::AShr: {
6484 // For each ashr, three cases:
6485 // shift = 0 => unchanged value
6486 // saturation => 0 or -1
6487 // other => a value closer to zero (of the same sign)
6488 // Thus, the end value is closer to zero than the start.
6489 auto KnownEnd = KnownBits::ashr(KnownStart,
6490 KnownBits::makeConstant(TotalShift));
6491 if (KnownStart.isNonNegative())
6492 // Analogous to lshr (simply not yet canonicalized)
6493 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6494 KnownStart.getMaxValue() + 1);
6495 if (KnownStart.isNegative())
6496 // End >=u Start && End <=s Start
6497 return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6498 KnownEnd.getMaxValue() + 1);
6499 break;
6500 }
6501 case Instruction::LShr: {
6502 // For each lshr, three cases:
6503 // shift = 0 => unchanged value
6504 // saturation => 0
6505 // other => a smaller positive number
6506 // Thus, the low end of the unsigned range is the last value produced.
6507 auto KnownEnd = KnownBits::lshr(KnownStart,
6508 KnownBits::makeConstant(TotalShift));
6509 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6510 KnownStart.getMaxValue() + 1);
6511 }
6512 case Instruction::Shl: {
6513 // Iff no bits are shifted out, value increases on every shift.
6514 auto KnownEnd = KnownBits::shl(KnownStart,
6515 KnownBits::makeConstant(TotalShift));
6516 if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6517 return ConstantRange(KnownStart.getMinValue(),
6518 KnownEnd.getMaxValue() + 1);
6519 break;
6520 }
6521 };
6522 return FullSet;
6523 }
6524
6525 const ConstantRange &
getRangeRefIter(const SCEV * S,ScalarEvolution::RangeSignHint SignHint)6526 ScalarEvolution::getRangeRefIter(const SCEV *S,
6527 ScalarEvolution::RangeSignHint SignHint) {
6528 DenseMap<const SCEV *, ConstantRange> &Cache =
6529 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6530 : SignedRanges;
6531 SmallVector<const SCEV *> WorkList;
6532 SmallPtrSet<const SCEV *, 8> Seen;
6533
6534 // Add Expr to the worklist, if Expr is either an N-ary expression or a
6535 // SCEVUnknown PHI node.
6536 auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6537 if (!Seen.insert(Expr).second)
6538 return;
6539 if (Cache.find(Expr) != Cache.end())
6540 return;
6541 switch (Expr->getSCEVType()) {
6542 case scUnknown:
6543 if (!isa<PHINode>(cast<SCEVUnknown>(Expr)->getValue()))
6544 break;
6545 [[fallthrough]];
6546 case scConstant:
6547 case scTruncate:
6548 case scZeroExtend:
6549 case scSignExtend:
6550 case scPtrToInt:
6551 case scAddExpr:
6552 case scMulExpr:
6553 case scUDivExpr:
6554 case scAddRecExpr:
6555 case scUMaxExpr:
6556 case scSMaxExpr:
6557 case scUMinExpr:
6558 case scSMinExpr:
6559 case scSequentialUMinExpr:
6560 WorkList.push_back(Expr);
6561 break;
6562 case scCouldNotCompute:
6563 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6564 }
6565 };
6566 AddToWorklist(S);
6567
6568 // Build worklist by queuing operands of N-ary expressions and phi nodes.
6569 for (unsigned I = 0; I != WorkList.size(); ++I) {
6570 const SCEV *P = WorkList[I];
6571 auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6572 // If it is not a `SCEVUnknown`, just recurse into operands.
6573 if (!UnknownS) {
6574 for (const SCEV *Op : P->operands())
6575 AddToWorklist(Op);
6576 continue;
6577 }
6578 // `SCEVUnknown`'s require special treatment.
6579 if (const PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6580 if (!PendingPhiRangesIter.insert(P).second)
6581 continue;
6582 for (auto &Op : reverse(P->operands()))
6583 AddToWorklist(getSCEV(Op));
6584 }
6585 }
6586
6587 if (!WorkList.empty()) {
6588 // Use getRangeRef to compute ranges for items in the worklist in reverse
6589 // order. This will force ranges for earlier operands to be computed before
6590 // their users in most cases.
6591 for (const SCEV *P :
6592 reverse(make_range(WorkList.begin() + 1, WorkList.end()))) {
6593 getRangeRef(P, SignHint);
6594
6595 if (auto *UnknownS = dyn_cast<SCEVUnknown>(P))
6596 if (const PHINode *P = dyn_cast<PHINode>(UnknownS->getValue()))
6597 PendingPhiRangesIter.erase(P);
6598 }
6599 }
6600
6601 return getRangeRef(S, SignHint, 0);
6602 }
6603
6604 /// Determine the range for a particular SCEV. If SignHint is
6605 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6606 /// with a "cleaner" unsigned (resp. signed) representation.
getRangeRef(const SCEV * S,ScalarEvolution::RangeSignHint SignHint,unsigned Depth)6607 const ConstantRange &ScalarEvolution::getRangeRef(
6608 const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6609 DenseMap<const SCEV *, ConstantRange> &Cache =
6610 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6611 : SignedRanges;
6612 ConstantRange::PreferredRangeType RangeType =
6613 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6614 : ConstantRange::Signed;
6615
6616 // See if we've computed this range already.
6617 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
6618 if (I != Cache.end())
6619 return I->second;
6620
6621 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6622 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6623
6624 // Switch to iteratively computing the range for S, if it is part of a deeply
6625 // nested expression.
6626 if (Depth > RangeIterThreshold)
6627 return getRangeRefIter(S, SignHint);
6628
6629 unsigned BitWidth = getTypeSizeInBits(S->getType());
6630 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6631 using OBO = OverflowingBinaryOperator;
6632
6633 // If the value has known zeros, the maximum value will have those known zeros
6634 // as well.
6635 uint32_t TZ = GetMinTrailingZeros(S);
6636 if (TZ != 0) {
6637 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
6638 ConservativeResult =
6639 ConstantRange(APInt::getMinValue(BitWidth),
6640 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
6641 else
6642 ConservativeResult = ConstantRange(
6643 APInt::getSignedMinValue(BitWidth),
6644 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6645 }
6646
6647 switch (S->getSCEVType()) {
6648 case scConstant:
6649 llvm_unreachable("Already handled above.");
6650 case scTruncate: {
6651 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6652 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6653 return setRange(
6654 Trunc, SignHint,
6655 ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6656 }
6657 case scZeroExtend: {
6658 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6659 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6660 return setRange(
6661 ZExt, SignHint,
6662 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6663 }
6664 case scSignExtend: {
6665 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6666 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6667 return setRange(
6668 SExt, SignHint,
6669 ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6670 }
6671 case scPtrToInt: {
6672 const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(S);
6673 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint, Depth + 1);
6674 return setRange(PtrToInt, SignHint, X);
6675 }
6676 case scAddExpr: {
6677 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6678 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6679 unsigned WrapType = OBO::AnyWrap;
6680 if (Add->hasNoSignedWrap())
6681 WrapType |= OBO::NoSignedWrap;
6682 if (Add->hasNoUnsignedWrap())
6683 WrapType |= OBO::NoUnsignedWrap;
6684 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
6685 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint, Depth + 1),
6686 WrapType, RangeType);
6687 return setRange(Add, SignHint,
6688 ConservativeResult.intersectWith(X, RangeType));
6689 }
6690 case scMulExpr: {
6691 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6692 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6693 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
6694 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint, Depth + 1));
6695 return setRange(Mul, SignHint,
6696 ConservativeResult.intersectWith(X, RangeType));
6697 }
6698 case scUDivExpr: {
6699 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6700 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6701 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6702 return setRange(UDiv, SignHint,
6703 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6704 }
6705 case scAddRecExpr: {
6706 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6707 // If there's no unsigned wrap, the value will never be less than its
6708 // initial value.
6709 if (AddRec->hasNoUnsignedWrap()) {
6710 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6711 if (!UnsignedMinValue.isZero())
6712 ConservativeResult = ConservativeResult.intersectWith(
6713 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6714 }
6715
6716 // If there's no signed wrap, and all the operands except initial value have
6717 // the same sign or zero, the value won't ever be:
6718 // 1: smaller than initial value if operands are non negative,
6719 // 2: bigger than initial value if operands are non positive.
6720 // For both cases, value can not cross signed min/max boundary.
6721 if (AddRec->hasNoSignedWrap()) {
6722 bool AllNonNeg = true;
6723 bool AllNonPos = true;
6724 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6725 if (!isKnownNonNegative(AddRec->getOperand(i)))
6726 AllNonNeg = false;
6727 if (!isKnownNonPositive(AddRec->getOperand(i)))
6728 AllNonPos = false;
6729 }
6730 if (AllNonNeg)
6731 ConservativeResult = ConservativeResult.intersectWith(
6732 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
6733 APInt::getSignedMinValue(BitWidth)),
6734 RangeType);
6735 else if (AllNonPos)
6736 ConservativeResult = ConservativeResult.intersectWith(
6737 ConstantRange::getNonEmpty(APInt::getSignedMinValue(BitWidth),
6738 getSignedRangeMax(AddRec->getStart()) +
6739 1),
6740 RangeType);
6741 }
6742
6743 // TODO: non-affine addrec
6744 if (AddRec->isAffine()) {
6745 const SCEV *MaxBECount =
6746 getConstantMaxBackedgeTakenCount(AddRec->getLoop());
6747 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
6748 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
6749 auto RangeFromAffine = getRangeForAffineAR(
6750 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6751 BitWidth);
6752 ConservativeResult =
6753 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6754
6755 auto RangeFromFactoring = getRangeViaFactoring(
6756 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6757 BitWidth);
6758 ConservativeResult =
6759 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6760 }
6761
6762 // Now try symbolic BE count and more powerful methods.
6763 if (UseExpensiveRangeSharpening) {
6764 const SCEV *SymbolicMaxBECount =
6765 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
6766 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6767 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6768 AddRec->hasNoSelfWrap()) {
6769 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6770 AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6771 ConservativeResult =
6772 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6773 }
6774 }
6775 }
6776
6777 return setRange(AddRec, SignHint, std::move(ConservativeResult));
6778 }
6779 case scUMaxExpr:
6780 case scSMaxExpr:
6781 case scUMinExpr:
6782 case scSMinExpr:
6783 case scSequentialUMinExpr: {
6784 Intrinsic::ID ID;
6785 switch (S->getSCEVType()) {
6786 case scUMaxExpr:
6787 ID = Intrinsic::umax;
6788 break;
6789 case scSMaxExpr:
6790 ID = Intrinsic::smax;
6791 break;
6792 case scUMinExpr:
6793 case scSequentialUMinExpr:
6794 ID = Intrinsic::umin;
6795 break;
6796 case scSMinExpr:
6797 ID = Intrinsic::smin;
6798 break;
6799 default:
6800 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6801 }
6802
6803 const auto *NAry = cast<SCEVNAryExpr>(S);
6804 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
6805 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6806 X = X.intrinsic(
6807 ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
6808 return setRange(S, SignHint,
6809 ConservativeResult.intersectWith(X, RangeType));
6810 }
6811 case scUnknown: {
6812 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6813
6814 // Check if the IR explicitly contains !range metadata.
6815 std::optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
6816 if (MDRange)
6817 ConservativeResult =
6818 ConservativeResult.intersectWith(*MDRange, RangeType);
6819
6820 // Use facts about recurrences in the underlying IR. Note that add
6821 // recurrences are AddRecExprs and thus don't hit this path. This
6822 // primarily handles shift recurrences.
6823 auto CR = getRangeForUnknownRecurrence(U);
6824 ConservativeResult = ConservativeResult.intersectWith(CR);
6825
6826 // See if ValueTracking can give us a useful range.
6827 const DataLayout &DL = getDataLayout();
6828 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6829 if (Known.getBitWidth() != BitWidth)
6830 Known = Known.zextOrTrunc(BitWidth);
6831
6832 // ValueTracking may be able to compute a tighter result for the number of
6833 // sign bits than for the value of those sign bits.
6834 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6835 if (U->getType()->isPointerTy()) {
6836 // If the pointer size is larger than the index size type, this can cause
6837 // NS to be larger than BitWidth. So compensate for this.
6838 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
6839 int ptrIdxDiff = ptrSize - BitWidth;
6840 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
6841 NS -= ptrIdxDiff;
6842 }
6843
6844 if (NS > 1) {
6845 // If we know any of the sign bits, we know all of the sign bits.
6846 if (!Known.Zero.getHiBits(NS).isZero())
6847 Known.Zero.setHighBits(NS);
6848 if (!Known.One.getHiBits(NS).isZero())
6849 Known.One.setHighBits(NS);
6850 }
6851
6852 if (Known.getMinValue() != Known.getMaxValue() + 1)
6853 ConservativeResult = ConservativeResult.intersectWith(
6854 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6855 RangeType);
6856 if (NS > 1)
6857 ConservativeResult = ConservativeResult.intersectWith(
6858 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6859 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6860 RangeType);
6861
6862 // A range of Phi is a subset of union of all ranges of its input.
6863 if (PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
6864 // Make sure that we do not run over cycled Phis.
6865 if (PendingPhiRanges.insert(Phi).second) {
6866 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6867
6868 for (const auto &Op : Phi->operands()) {
6869 auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
6870 RangeFromOps = RangeFromOps.unionWith(OpRange);
6871 // No point to continue if we already have a full set.
6872 if (RangeFromOps.isFullSet())
6873 break;
6874 }
6875 ConservativeResult =
6876 ConservativeResult.intersectWith(RangeFromOps, RangeType);
6877 bool Erased = PendingPhiRanges.erase(Phi);
6878 assert(Erased && "Failed to erase Phi properly?");
6879 (void)Erased;
6880 }
6881 }
6882
6883 // vscale can't be equal to zero
6884 if (const auto *II = dyn_cast<IntrinsicInst>(U->getValue()))
6885 if (II->getIntrinsicID() == Intrinsic::vscale) {
6886 ConstantRange Disallowed = APInt::getZero(BitWidth);
6887 ConservativeResult = ConservativeResult.difference(Disallowed);
6888 }
6889
6890 return setRange(U, SignHint, std::move(ConservativeResult));
6891 }
6892 case scCouldNotCompute:
6893 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6894 }
6895
6896 return setRange(S, SignHint, std::move(ConservativeResult));
6897 }
6898
6899 // Given a StartRange, Step and MaxBECount for an expression compute a range of
6900 // values that the expression can take. Initially, the expression has a value
6901 // from StartRange and then is changed by Step up to MaxBECount times. Signed
6902 // argument defines if we treat Step as signed or unsigned.
getRangeForAffineARHelper(APInt Step,const ConstantRange & StartRange,const APInt & MaxBECount,unsigned BitWidth,bool Signed)6903 static ConstantRange getRangeForAffineARHelper(APInt Step,
6904 const ConstantRange &StartRange,
6905 const APInt &MaxBECount,
6906 unsigned BitWidth, bool Signed) {
6907 // If either Step or MaxBECount is 0, then the expression won't change, and we
6908 // just need to return the initial range.
6909 if (Step == 0 || MaxBECount == 0)
6910 return StartRange;
6911
6912 // If we don't know anything about the initial value (i.e. StartRange is
6913 // FullRange), then we don't know anything about the final range either.
6914 // Return FullRange.
6915 if (StartRange.isFullSet())
6916 return ConstantRange::getFull(BitWidth);
6917
6918 // If Step is signed and negative, then we use its absolute value, but we also
6919 // note that we're moving in the opposite direction.
6920 bool Descending = Signed && Step.isNegative();
6921
6922 if (Signed)
6923 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
6924 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
6925 // This equations hold true due to the well-defined wrap-around behavior of
6926 // APInt.
6927 Step = Step.abs();
6928
6929 // Check if Offset is more than full span of BitWidth. If it is, the
6930 // expression is guaranteed to overflow.
6931 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
6932 return ConstantRange::getFull(BitWidth);
6933
6934 // Offset is by how much the expression can change. Checks above guarantee no
6935 // overflow here.
6936 APInt Offset = Step * MaxBECount;
6937
6938 // Minimum value of the final range will match the minimal value of StartRange
6939 // if the expression is increasing and will be decreased by Offset otherwise.
6940 // Maximum value of the final range will match the maximal value of StartRange
6941 // if the expression is decreasing and will be increased by Offset otherwise.
6942 APInt StartLower = StartRange.getLower();
6943 APInt StartUpper = StartRange.getUpper() - 1;
6944 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
6945 : (StartUpper + std::move(Offset));
6946
6947 // It's possible that the new minimum/maximum value will fall into the initial
6948 // range (due to wrap around). This means that the expression can take any
6949 // value in this bitwidth, and we have to return full range.
6950 if (StartRange.contains(MovedBoundary))
6951 return ConstantRange::getFull(BitWidth);
6952
6953 APInt NewLower =
6954 Descending ? std::move(MovedBoundary) : std::move(StartLower);
6955 APInt NewUpper =
6956 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
6957 NewUpper += 1;
6958
6959 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
6960 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
6961 }
6962
getRangeForAffineAR(const SCEV * Start,const SCEV * Step,const SCEV * MaxBECount,unsigned BitWidth)6963 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
6964 const SCEV *Step,
6965 const SCEV *MaxBECount,
6966 unsigned BitWidth) {
6967 assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
6968 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6969 "Precondition!");
6970
6971 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
6972 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
6973
6974 // First, consider step signed.
6975 ConstantRange StartSRange = getSignedRange(Start);
6976 ConstantRange StepSRange = getSignedRange(Step);
6977
6978 // If Step can be both positive and negative, we need to find ranges for the
6979 // maximum absolute step values in both directions and union them.
6980 ConstantRange SR =
6981 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
6982 MaxBECountValue, BitWidth, /* Signed = */ true);
6983 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
6984 StartSRange, MaxBECountValue,
6985 BitWidth, /* Signed = */ true));
6986
6987 // Next, consider step unsigned.
6988 ConstantRange UR = getRangeForAffineARHelper(
6989 getUnsignedRangeMax(Step), getUnsignedRange(Start),
6990 MaxBECountValue, BitWidth, /* Signed = */ false);
6991
6992 // Finally, intersect signed and unsigned ranges.
6993 return SR.intersectWith(UR, ConstantRange::Smallest);
6994 }
6995
getRangeForAffineNoSelfWrappingAR(const SCEVAddRecExpr * AddRec,const SCEV * MaxBECount,unsigned BitWidth,ScalarEvolution::RangeSignHint SignHint)6996 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
6997 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
6998 ScalarEvolution::RangeSignHint SignHint) {
6999 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
7000 assert(AddRec->hasNoSelfWrap() &&
7001 "This only works for non-self-wrapping AddRecs!");
7002 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
7003 const SCEV *Step = AddRec->getStepRecurrence(*this);
7004 // Only deal with constant step to save compile time.
7005 if (!isa<SCEVConstant>(Step))
7006 return ConstantRange::getFull(BitWidth);
7007 // Let's make sure that we can prove that we do not self-wrap during
7008 // MaxBECount iterations. We need this because MaxBECount is a maximum
7009 // iteration count estimate, and we might infer nw from some exit for which we
7010 // do not know max exit count (or any other side reasoning).
7011 // TODO: Turn into assert at some point.
7012 if (getTypeSizeInBits(MaxBECount->getType()) >
7013 getTypeSizeInBits(AddRec->getType()))
7014 return ConstantRange::getFull(BitWidth);
7015 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
7016 const SCEV *RangeWidth = getMinusOne(AddRec->getType());
7017 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
7018 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
7019 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
7020 MaxItersWithoutWrap))
7021 return ConstantRange::getFull(BitWidth);
7022
7023 ICmpInst::Predicate LEPred =
7024 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
7025 ICmpInst::Predicate GEPred =
7026 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
7027 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7028
7029 // We know that there is no self-wrap. Let's take Start and End values and
7030 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7031 // the iteration. They either lie inside the range [Min(Start, End),
7032 // Max(Start, End)] or outside it:
7033 //
7034 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
7035 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
7036 //
7037 // No self wrap flag guarantees that the intermediate values cannot be BOTH
7038 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7039 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7040 // Start <= End and step is positive, or Start >= End and step is negative.
7041 const SCEV *Start = AddRec->getStart();
7042 ConstantRange StartRange = getRangeRef(Start, SignHint);
7043 ConstantRange EndRange = getRangeRef(End, SignHint);
7044 ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7045 // If they already cover full iteration space, we will know nothing useful
7046 // even if we prove what we want to prove.
7047 if (RangeBetween.isFullSet())
7048 return RangeBetween;
7049 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7050 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7051 : RangeBetween.isWrappedSet();
7052 if (IsWrappedSet)
7053 return ConstantRange::getFull(BitWidth);
7054
7055 if (isKnownPositive(Step) &&
7056 isKnownPredicateViaConstantRanges(LEPred, Start, End))
7057 return RangeBetween;
7058 else if (isKnownNegative(Step) &&
7059 isKnownPredicateViaConstantRanges(GEPred, Start, End))
7060 return RangeBetween;
7061 return ConstantRange::getFull(BitWidth);
7062 }
7063
getRangeViaFactoring(const SCEV * Start,const SCEV * Step,const SCEV * MaxBECount,unsigned BitWidth)7064 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7065 const SCEV *Step,
7066 const SCEV *MaxBECount,
7067 unsigned BitWidth) {
7068 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7069 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7070
7071 struct SelectPattern {
7072 Value *Condition = nullptr;
7073 APInt TrueValue;
7074 APInt FalseValue;
7075
7076 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7077 const SCEV *S) {
7078 std::optional<unsigned> CastOp;
7079 APInt Offset(BitWidth, 0);
7080
7081 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
7082 "Should be!");
7083
7084 // Peel off a constant offset:
7085 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
7086 // In the future we could consider being smarter here and handle
7087 // {Start+Step,+,Step} too.
7088 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
7089 return;
7090
7091 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
7092 S = SA->getOperand(1);
7093 }
7094
7095 // Peel off a cast operation
7096 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7097 CastOp = SCast->getSCEVType();
7098 S = SCast->getOperand();
7099 }
7100
7101 using namespace llvm::PatternMatch;
7102
7103 auto *SU = dyn_cast<SCEVUnknown>(S);
7104 const APInt *TrueVal, *FalseVal;
7105 if (!SU ||
7106 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7107 m_APInt(FalseVal)))) {
7108 Condition = nullptr;
7109 return;
7110 }
7111
7112 TrueValue = *TrueVal;
7113 FalseValue = *FalseVal;
7114
7115 // Re-apply the cast we peeled off earlier
7116 if (CastOp)
7117 switch (*CastOp) {
7118 default:
7119 llvm_unreachable("Unknown SCEV cast type!");
7120
7121 case scTruncate:
7122 TrueValue = TrueValue.trunc(BitWidth);
7123 FalseValue = FalseValue.trunc(BitWidth);
7124 break;
7125 case scZeroExtend:
7126 TrueValue = TrueValue.zext(BitWidth);
7127 FalseValue = FalseValue.zext(BitWidth);
7128 break;
7129 case scSignExtend:
7130 TrueValue = TrueValue.sext(BitWidth);
7131 FalseValue = FalseValue.sext(BitWidth);
7132 break;
7133 }
7134
7135 // Re-apply the constant offset we peeled off earlier
7136 TrueValue += Offset;
7137 FalseValue += Offset;
7138 }
7139
7140 bool isRecognized() { return Condition != nullptr; }
7141 };
7142
7143 SelectPattern StartPattern(*this, BitWidth, Start);
7144 if (!StartPattern.isRecognized())
7145 return ConstantRange::getFull(BitWidth);
7146
7147 SelectPattern StepPattern(*this, BitWidth, Step);
7148 if (!StepPattern.isRecognized())
7149 return ConstantRange::getFull(BitWidth);
7150
7151 if (StartPattern.Condition != StepPattern.Condition) {
7152 // We don't handle this case today; but we could, by considering four
7153 // possibilities below instead of two. I'm not sure if there are cases where
7154 // that will help over what getRange already does, though.
7155 return ConstantRange::getFull(BitWidth);
7156 }
7157
7158 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7159 // construct arbitrary general SCEV expressions here. This function is called
7160 // from deep in the call stack, and calling getSCEV (on a sext instruction,
7161 // say) can end up caching a suboptimal value.
7162
7163 // FIXME: without the explicit `this` receiver below, MSVC errors out with
7164 // C2352 and C2512 (otherwise it isn't needed).
7165
7166 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7167 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7168 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7169 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7170
7171 ConstantRange TrueRange =
7172 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
7173 ConstantRange FalseRange =
7174 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
7175
7176 return TrueRange.unionWith(FalseRange);
7177 }
7178
getNoWrapFlagsFromUB(const Value * V)7179 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7180 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
7181 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7182
7183 // Return early if there are no flags to propagate to the SCEV.
7184 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
7185 if (BinOp->hasNoUnsignedWrap())
7186 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
7187 if (BinOp->hasNoSignedWrap())
7188 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
7189 if (Flags == SCEV::FlagAnyWrap)
7190 return SCEV::FlagAnyWrap;
7191
7192 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
7193 }
7194
7195 const Instruction *
getNonTrivialDefiningScopeBound(const SCEV * S)7196 ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7197 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7198 return &*AddRec->getLoop()->getHeader()->begin();
7199 if (auto *U = dyn_cast<SCEVUnknown>(S))
7200 if (auto *I = dyn_cast<Instruction>(U->getValue()))
7201 return I;
7202 return nullptr;
7203 }
7204
7205 const Instruction *
getDefiningScopeBound(ArrayRef<const SCEV * > Ops,bool & Precise)7206 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops,
7207 bool &Precise) {
7208 Precise = true;
7209 // Do a bounded search of the def relation of the requested SCEVs.
7210 SmallSet<const SCEV *, 16> Visited;
7211 SmallVector<const SCEV *> Worklist;
7212 auto pushOp = [&](const SCEV *S) {
7213 if (!Visited.insert(S).second)
7214 return;
7215 // Threshold of 30 here is arbitrary.
7216 if (Visited.size() > 30) {
7217 Precise = false;
7218 return;
7219 }
7220 Worklist.push_back(S);
7221 };
7222
7223 for (const auto *S : Ops)
7224 pushOp(S);
7225
7226 const Instruction *Bound = nullptr;
7227 while (!Worklist.empty()) {
7228 auto *S = Worklist.pop_back_val();
7229 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7230 if (!Bound || DT.dominates(Bound, DefI))
7231 Bound = DefI;
7232 } else {
7233 for (const auto *Op : S->operands())
7234 pushOp(Op);
7235 }
7236 }
7237 return Bound ? Bound : &*F.getEntryBlock().begin();
7238 }
7239
7240 const Instruction *
getDefiningScopeBound(ArrayRef<const SCEV * > Ops)7241 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops) {
7242 bool Discard;
7243 return getDefiningScopeBound(Ops, Discard);
7244 }
7245
isGuaranteedToTransferExecutionTo(const Instruction * A,const Instruction * B)7246 bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7247 const Instruction *B) {
7248 if (A->getParent() == B->getParent() &&
7249 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
7250 B->getIterator()))
7251 return true;
7252
7253 auto *BLoop = LI.getLoopFor(B->getParent());
7254 if (BLoop && BLoop->getHeader() == B->getParent() &&
7255 BLoop->getLoopPreheader() == A->getParent() &&
7256 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
7257 A->getParent()->end()) &&
7258 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7259 B->getIterator()))
7260 return true;
7261 return false;
7262 }
7263
7264
isSCEVExprNeverPoison(const Instruction * I)7265 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7266 // Only proceed if we can prove that I does not yield poison.
7267 if (!programUndefinedIfPoison(I))
7268 return false;
7269
7270 // At this point we know that if I is executed, then it does not wrap
7271 // according to at least one of NSW or NUW. If I is not executed, then we do
7272 // not know if the calculation that I represents would wrap. Multiple
7273 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7274 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7275 // derived from other instructions that map to the same SCEV. We cannot make
7276 // that guarantee for cases where I is not executed. So we need to find a
7277 // upper bound on the defining scope for the SCEV, and prove that I is
7278 // executed every time we enter that scope. When the bounding scope is a
7279 // loop (the common case), this is equivalent to proving I executes on every
7280 // iteration of that loop.
7281 SmallVector<const SCEV *> SCEVOps;
7282 for (const Use &Op : I->operands()) {
7283 // I could be an extractvalue from a call to an overflow intrinsic.
7284 // TODO: We can do better here in some cases.
7285 if (isSCEVable(Op->getType()))
7286 SCEVOps.push_back(getSCEV(Op));
7287 }
7288 auto *DefI = getDefiningScopeBound(SCEVOps);
7289 return isGuaranteedToTransferExecutionTo(DefI, I);
7290 }
7291
isAddRecNeverPoison(const Instruction * I,const Loop * L)7292 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7293 // If we know that \c I can never be poison period, then that's enough.
7294 if (isSCEVExprNeverPoison(I))
7295 return true;
7296
7297 // For an add recurrence specifically, we assume that infinite loops without
7298 // side effects are undefined behavior, and then reason as follows:
7299 //
7300 // If the add recurrence is poison in any iteration, it is poison on all
7301 // future iterations (since incrementing poison yields poison). If the result
7302 // of the add recurrence is fed into the loop latch condition and the loop
7303 // does not contain any throws or exiting blocks other than the latch, we now
7304 // have the ability to "choose" whether the backedge is taken or not (by
7305 // choosing a sufficiently evil value for the poison feeding into the branch)
7306 // for every iteration including and after the one in which \p I first became
7307 // poison. There are two possibilities (let's call the iteration in which \p
7308 // I first became poison as K):
7309 //
7310 // 1. In the set of iterations including and after K, the loop body executes
7311 // no side effects. In this case executing the backege an infinte number
7312 // of times will yield undefined behavior.
7313 //
7314 // 2. In the set of iterations including and after K, the loop body executes
7315 // at least one side effect. In this case, that specific instance of side
7316 // effect is control dependent on poison, which also yields undefined
7317 // behavior.
7318
7319 auto *ExitingBB = L->getExitingBlock();
7320 auto *LatchBB = L->getLoopLatch();
7321 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
7322 return false;
7323
7324 SmallPtrSet<const Instruction *, 16> Pushed;
7325 SmallVector<const Instruction *, 8> PoisonStack;
7326
7327 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
7328 // things that are known to be poison under that assumption go on the
7329 // PoisonStack.
7330 Pushed.insert(I);
7331 PoisonStack.push_back(I);
7332
7333 bool LatchControlDependentOnPoison = false;
7334 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
7335 const Instruction *Poison = PoisonStack.pop_back_val();
7336
7337 for (const Use &U : Poison->uses()) {
7338 const User *PoisonUser = U.getUser();
7339 if (propagatesPoison(U)) {
7340 if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
7341 PoisonStack.push_back(cast<Instruction>(PoisonUser));
7342 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
7343 assert(BI->isConditional() && "Only possibility!");
7344 if (BI->getParent() == LatchBB) {
7345 LatchControlDependentOnPoison = true;
7346 break;
7347 }
7348 }
7349 }
7350 }
7351
7352 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
7353 }
7354
7355 ScalarEvolution::LoopProperties
getLoopProperties(const Loop * L)7356 ScalarEvolution::getLoopProperties(const Loop *L) {
7357 using LoopProperties = ScalarEvolution::LoopProperties;
7358
7359 auto Itr = LoopPropertiesCache.find(L);
7360 if (Itr == LoopPropertiesCache.end()) {
7361 auto HasSideEffects = [](Instruction *I) {
7362 if (auto *SI = dyn_cast<StoreInst>(I))
7363 return !SI->isSimple();
7364
7365 return I->mayThrow() || I->mayWriteToMemory();
7366 };
7367
7368 LoopProperties LP = {/* HasNoAbnormalExits */ true,
7369 /*HasNoSideEffects*/ true};
7370
7371 for (auto *BB : L->getBlocks())
7372 for (auto &I : *BB) {
7373 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
7374 LP.HasNoAbnormalExits = false;
7375 if (HasSideEffects(&I))
7376 LP.HasNoSideEffects = false;
7377 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7378 break; // We're already as pessimistic as we can get.
7379 }
7380
7381 auto InsertPair = LoopPropertiesCache.insert({L, LP});
7382 assert(InsertPair.second && "We just checked!");
7383 Itr = InsertPair.first;
7384 }
7385
7386 return Itr->second;
7387 }
7388
loopIsFiniteByAssumption(const Loop * L)7389 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) {
7390 // A mustprogress loop without side effects must be finite.
7391 // TODO: The check used here is very conservative. It's only *specific*
7392 // side effects which are well defined in infinite loops.
7393 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7394 }
7395
createSCEVIter(Value * V)7396 const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7397 // Worklist item with a Value and a bool indicating whether all operands have
7398 // been visited already.
7399 using PointerTy = PointerIntPair<Value *, 1, bool>;
7400 SmallVector<PointerTy> Stack;
7401
7402 Stack.emplace_back(V, true);
7403 Stack.emplace_back(V, false);
7404 while (!Stack.empty()) {
7405 auto E = Stack.pop_back_val();
7406 Value *CurV = E.getPointer();
7407
7408 if (getExistingSCEV(CurV))
7409 continue;
7410
7411 SmallVector<Value *> Ops;
7412 const SCEV *CreatedSCEV = nullptr;
7413 // If all operands have been visited already, create the SCEV.
7414 if (E.getInt()) {
7415 CreatedSCEV = createSCEV(CurV);
7416 } else {
7417 // Otherwise get the operands we need to create SCEV's for before creating
7418 // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7419 // just use it.
7420 CreatedSCEV = getOperandsToCreate(CurV, Ops);
7421 }
7422
7423 if (CreatedSCEV) {
7424 insertValueToMap(CurV, CreatedSCEV);
7425 } else {
7426 // Queue CurV for SCEV creation, followed by its's operands which need to
7427 // be constructed first.
7428 Stack.emplace_back(CurV, true);
7429 for (Value *Op : Ops)
7430 Stack.emplace_back(Op, false);
7431 }
7432 }
7433
7434 return getExistingSCEV(V);
7435 }
7436
7437 const SCEV *
getOperandsToCreate(Value * V,SmallVectorImpl<Value * > & Ops)7438 ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7439 if (!isSCEVable(V->getType()))
7440 return getUnknown(V);
7441
7442 if (Instruction *I = dyn_cast<Instruction>(V)) {
7443 // Don't attempt to analyze instructions in blocks that aren't
7444 // reachable. Such instructions don't matter, and they aren't required
7445 // to obey basic rules for definitions dominating uses which this
7446 // analysis depends on.
7447 if (!DT.isReachableFromEntry(I->getParent()))
7448 return getUnknown(PoisonValue::get(V->getType()));
7449 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7450 return getConstant(CI);
7451 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
7452 if (!GA->isInterposable()) {
7453 Ops.push_back(GA->getAliasee());
7454 return nullptr;
7455 }
7456 return getUnknown(V);
7457 } else if (!isa<ConstantExpr>(V))
7458 return getUnknown(V);
7459
7460 Operator *U = cast<Operator>(V);
7461 if (auto BO =
7462 MatchBinaryOp(U, getDataLayout(), AC, DT, dyn_cast<Instruction>(V))) {
7463 bool IsConstArg = isa<ConstantInt>(BO->RHS);
7464 switch (BO->Opcode) {
7465 case Instruction::Add:
7466 case Instruction::Mul: {
7467 // For additions and multiplications, traverse add/mul chains for which we
7468 // can potentially create a single SCEV, to reduce the number of
7469 // get{Add,Mul}Expr calls.
7470 do {
7471 if (BO->Op) {
7472 if (BO->Op != V && getExistingSCEV(BO->Op)) {
7473 Ops.push_back(BO->Op);
7474 break;
7475 }
7476 }
7477 Ops.push_back(BO->RHS);
7478 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7479 dyn_cast<Instruction>(V));
7480 if (!NewBO ||
7481 (U->getOpcode() == Instruction::Add &&
7482 (NewBO->Opcode != Instruction::Add &&
7483 NewBO->Opcode != Instruction::Sub)) ||
7484 (U->getOpcode() == Instruction::Mul &&
7485 NewBO->Opcode != Instruction::Mul)) {
7486 Ops.push_back(BO->LHS);
7487 break;
7488 }
7489 // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7490 // requires a SCEV for the LHS.
7491 if (NewBO->Op && (NewBO->IsNSW || NewBO->IsNUW)) {
7492 auto *I = dyn_cast<Instruction>(NewBO->Op);
7493 if (I && programUndefinedIfPoison(I)) {
7494 Ops.push_back(BO->LHS);
7495 break;
7496 }
7497 }
7498 BO = NewBO;
7499 } while (true);
7500 return nullptr;
7501 }
7502 case Instruction::Sub:
7503 case Instruction::UDiv:
7504 case Instruction::URem:
7505 break;
7506 case Instruction::AShr:
7507 case Instruction::Shl:
7508 case Instruction::Xor:
7509 if (!IsConstArg)
7510 return nullptr;
7511 break;
7512 case Instruction::And:
7513 case Instruction::Or:
7514 if (!IsConstArg && BO->LHS->getType()->isIntegerTy(1))
7515 return nullptr;
7516 break;
7517 case Instruction::LShr:
7518 return getUnknown(V);
7519 default:
7520 llvm_unreachable("Unhandled binop");
7521 break;
7522 }
7523
7524 Ops.push_back(BO->LHS);
7525 Ops.push_back(BO->RHS);
7526 return nullptr;
7527 }
7528
7529 switch (U->getOpcode()) {
7530 case Instruction::Trunc:
7531 case Instruction::ZExt:
7532 case Instruction::SExt:
7533 case Instruction::PtrToInt:
7534 Ops.push_back(U->getOperand(0));
7535 return nullptr;
7536
7537 case Instruction::BitCast:
7538 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
7539 Ops.push_back(U->getOperand(0));
7540 return nullptr;
7541 }
7542 return getUnknown(V);
7543
7544 case Instruction::SDiv:
7545 case Instruction::SRem:
7546 Ops.push_back(U->getOperand(0));
7547 Ops.push_back(U->getOperand(1));
7548 return nullptr;
7549
7550 case Instruction::GetElementPtr:
7551 assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7552 "GEP source element type must be sized");
7553 for (Value *Index : U->operands())
7554 Ops.push_back(Index);
7555 return nullptr;
7556
7557 case Instruction::IntToPtr:
7558 return getUnknown(V);
7559
7560 case Instruction::PHI:
7561 // Keep constructing SCEVs' for phis recursively for now.
7562 return nullptr;
7563
7564 case Instruction::Select: {
7565 // Check if U is a select that can be simplified to a SCEVUnknown.
7566 auto CanSimplifyToUnknown = [this, U]() {
7567 if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
7568 return false;
7569
7570 auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
7571 if (!ICI)
7572 return false;
7573 Value *LHS = ICI->getOperand(0);
7574 Value *RHS = ICI->getOperand(1);
7575 if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7576 ICI->getPredicate() == CmpInst::ICMP_NE) {
7577 if (!(isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()))
7578 return true;
7579 } else if (getTypeSizeInBits(LHS->getType()) >
7580 getTypeSizeInBits(U->getType()))
7581 return true;
7582 return false;
7583 };
7584 if (CanSimplifyToUnknown())
7585 return getUnknown(U);
7586
7587 for (Value *Inc : U->operands())
7588 Ops.push_back(Inc);
7589 return nullptr;
7590 break;
7591 }
7592 case Instruction::Call:
7593 case Instruction::Invoke:
7594 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7595 Ops.push_back(RV);
7596 return nullptr;
7597 }
7598
7599 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7600 switch (II->getIntrinsicID()) {
7601 case Intrinsic::abs:
7602 Ops.push_back(II->getArgOperand(0));
7603 return nullptr;
7604 case Intrinsic::umax:
7605 case Intrinsic::umin:
7606 case Intrinsic::smax:
7607 case Intrinsic::smin:
7608 case Intrinsic::usub_sat:
7609 case Intrinsic::uadd_sat:
7610 Ops.push_back(II->getArgOperand(0));
7611 Ops.push_back(II->getArgOperand(1));
7612 return nullptr;
7613 case Intrinsic::start_loop_iterations:
7614 case Intrinsic::annotation:
7615 case Intrinsic::ptr_annotation:
7616 Ops.push_back(II->getArgOperand(0));
7617 return nullptr;
7618 default:
7619 break;
7620 }
7621 }
7622 break;
7623 }
7624
7625 return nullptr;
7626 }
7627
createSCEV(Value * V)7628 const SCEV *ScalarEvolution::createSCEV(Value *V) {
7629 if (!isSCEVable(V->getType()))
7630 return getUnknown(V);
7631
7632 if (Instruction *I = dyn_cast<Instruction>(V)) {
7633 // Don't attempt to analyze instructions in blocks that aren't
7634 // reachable. Such instructions don't matter, and they aren't required
7635 // to obey basic rules for definitions dominating uses which this
7636 // analysis depends on.
7637 if (!DT.isReachableFromEntry(I->getParent()))
7638 return getUnknown(PoisonValue::get(V->getType()));
7639 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7640 return getConstant(CI);
7641 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
7642 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
7643 else if (!isa<ConstantExpr>(V))
7644 return getUnknown(V);
7645
7646 const SCEV *LHS;
7647 const SCEV *RHS;
7648
7649 Operator *U = cast<Operator>(V);
7650 if (auto BO =
7651 MatchBinaryOp(U, getDataLayout(), AC, DT, dyn_cast<Instruction>(V))) {
7652 switch (BO->Opcode) {
7653 case Instruction::Add: {
7654 // The simple thing to do would be to just call getSCEV on both operands
7655 // and call getAddExpr with the result. However if we're looking at a
7656 // bunch of things all added together, this can be quite inefficient,
7657 // because it leads to N-1 getAddExpr calls for N ultimate operands.
7658 // Instead, gather up all the operands and make a single getAddExpr call.
7659 // LLVM IR canonical form means we need only traverse the left operands.
7660 SmallVector<const SCEV *, 4> AddOps;
7661 do {
7662 if (BO->Op) {
7663 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7664 AddOps.push_back(OpSCEV);
7665 break;
7666 }
7667
7668 // If a NUW or NSW flag can be applied to the SCEV for this
7669 // addition, then compute the SCEV for this addition by itself
7670 // with a separate call to getAddExpr. We need to do that
7671 // instead of pushing the operands of the addition onto AddOps,
7672 // since the flags are only known to apply to this particular
7673 // addition - they may not apply to other additions that can be
7674 // formed with operands from AddOps.
7675 const SCEV *RHS = getSCEV(BO->RHS);
7676 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7677 if (Flags != SCEV::FlagAnyWrap) {
7678 const SCEV *LHS = getSCEV(BO->LHS);
7679 if (BO->Opcode == Instruction::Sub)
7680 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7681 else
7682 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7683 break;
7684 }
7685 }
7686
7687 if (BO->Opcode == Instruction::Sub)
7688 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7689 else
7690 AddOps.push_back(getSCEV(BO->RHS));
7691
7692 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7693 dyn_cast<Instruction>(V));
7694 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7695 NewBO->Opcode != Instruction::Sub)) {
7696 AddOps.push_back(getSCEV(BO->LHS));
7697 break;
7698 }
7699 BO = NewBO;
7700 } while (true);
7701
7702 return getAddExpr(AddOps);
7703 }
7704
7705 case Instruction::Mul: {
7706 SmallVector<const SCEV *, 4> MulOps;
7707 do {
7708 if (BO->Op) {
7709 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7710 MulOps.push_back(OpSCEV);
7711 break;
7712 }
7713
7714 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7715 if (Flags != SCEV::FlagAnyWrap) {
7716 LHS = getSCEV(BO->LHS);
7717 RHS = getSCEV(BO->RHS);
7718 MulOps.push_back(getMulExpr(LHS, RHS, Flags));
7719 break;
7720 }
7721 }
7722
7723 MulOps.push_back(getSCEV(BO->RHS));
7724 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7725 dyn_cast<Instruction>(V));
7726 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7727 MulOps.push_back(getSCEV(BO->LHS));
7728 break;
7729 }
7730 BO = NewBO;
7731 } while (true);
7732
7733 return getMulExpr(MulOps);
7734 }
7735 case Instruction::UDiv:
7736 LHS = getSCEV(BO->LHS);
7737 RHS = getSCEV(BO->RHS);
7738 return getUDivExpr(LHS, RHS);
7739 case Instruction::URem:
7740 LHS = getSCEV(BO->LHS);
7741 RHS = getSCEV(BO->RHS);
7742 return getURemExpr(LHS, RHS);
7743 case Instruction::Sub: {
7744 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
7745 if (BO->Op)
7746 Flags = getNoWrapFlagsFromUB(BO->Op);
7747 LHS = getSCEV(BO->LHS);
7748 RHS = getSCEV(BO->RHS);
7749 return getMinusSCEV(LHS, RHS, Flags);
7750 }
7751 case Instruction::And:
7752 // For an expression like x&255 that merely masks off the high bits,
7753 // use zext(trunc(x)) as the SCEV expression.
7754 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7755 if (CI->isZero())
7756 return getSCEV(BO->RHS);
7757 if (CI->isMinusOne())
7758 return getSCEV(BO->LHS);
7759 const APInt &A = CI->getValue();
7760
7761 // Instcombine's ShrinkDemandedConstant may strip bits out of
7762 // constants, obscuring what would otherwise be a low-bits mask.
7763 // Use computeKnownBits to compute what ShrinkDemandedConstant
7764 // knew about to reconstruct a low-bits mask value.
7765 unsigned LZ = A.countLeadingZeros();
7766 unsigned TZ = A.countTrailingZeros();
7767 unsigned BitWidth = A.getBitWidth();
7768 KnownBits Known(BitWidth);
7769 computeKnownBits(BO->LHS, Known, getDataLayout(),
7770 0, &AC, nullptr, &DT);
7771
7772 APInt EffectiveMask =
7773 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
7774 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
7775 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
7776 const SCEV *LHS = getSCEV(BO->LHS);
7777 const SCEV *ShiftedLHS = nullptr;
7778 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
7779 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
7780 // For an expression like (x * 8) & 8, simplify the multiply.
7781 unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
7782 unsigned GCD = std::min(MulZeros, TZ);
7783 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
7784 SmallVector<const SCEV*, 4> MulOps;
7785 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
7786 append_range(MulOps, LHSMul->operands().drop_front());
7787 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
7788 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
7789 }
7790 }
7791 if (!ShiftedLHS)
7792 ShiftedLHS = getUDivExpr(LHS, MulCount);
7793 return getMulExpr(
7794 getZeroExtendExpr(
7795 getTruncateExpr(ShiftedLHS,
7796 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
7797 BO->LHS->getType()),
7798 MulCount);
7799 }
7800 }
7801 // Binary `and` is a bit-wise `umin`.
7802 if (BO->LHS->getType()->isIntegerTy(1)) {
7803 LHS = getSCEV(BO->LHS);
7804 RHS = getSCEV(BO->RHS);
7805 return getUMinExpr(LHS, RHS);
7806 }
7807 break;
7808
7809 case Instruction::Or:
7810 // Binary `or` is a bit-wise `umax`.
7811 if (BO->LHS->getType()->isIntegerTy(1)) {
7812 LHS = getSCEV(BO->LHS);
7813 RHS = getSCEV(BO->RHS);
7814 return getUMaxExpr(LHS, RHS);
7815 }
7816 break;
7817
7818 case Instruction::Xor:
7819 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7820 // If the RHS of xor is -1, then this is a not operation.
7821 if (CI->isMinusOne())
7822 return getNotSCEV(getSCEV(BO->LHS));
7823
7824 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
7825 // This is a variant of the check for xor with -1, and it handles
7826 // the case where instcombine has trimmed non-demanded bits out
7827 // of an xor with -1.
7828 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
7829 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
7830 if (LBO->getOpcode() == Instruction::And &&
7831 LCI->getValue() == CI->getValue())
7832 if (const SCEVZeroExtendExpr *Z =
7833 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
7834 Type *UTy = BO->LHS->getType();
7835 const SCEV *Z0 = Z->getOperand();
7836 Type *Z0Ty = Z0->getType();
7837 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
7838
7839 // If C is a low-bits mask, the zero extend is serving to
7840 // mask off the high bits. Complement the operand and
7841 // re-apply the zext.
7842 if (CI->getValue().isMask(Z0TySize))
7843 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
7844
7845 // If C is a single bit, it may be in the sign-bit position
7846 // before the zero-extend. In this case, represent the xor
7847 // using an add, which is equivalent, and re-apply the zext.
7848 APInt Trunc = CI->getValue().trunc(Z0TySize);
7849 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
7850 Trunc.isSignMask())
7851 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
7852 UTy);
7853 }
7854 }
7855 break;
7856
7857 case Instruction::Shl:
7858 // Turn shift left of a constant amount into a multiply.
7859 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
7860 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
7861
7862 // If the shift count is not less than the bitwidth, the result of
7863 // the shift is undefined. Don't try to analyze it, because the
7864 // resolution chosen here may differ from the resolution chosen in
7865 // other parts of the compiler.
7866 if (SA->getValue().uge(BitWidth))
7867 break;
7868
7869 // We can safely preserve the nuw flag in all cases. It's also safe to
7870 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
7871 // requires special handling. It can be preserved as long as we're not
7872 // left shifting by bitwidth - 1.
7873 auto Flags = SCEV::FlagAnyWrap;
7874 if (BO->Op) {
7875 auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
7876 if ((MulFlags & SCEV::FlagNSW) &&
7877 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
7878 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
7879 if (MulFlags & SCEV::FlagNUW)
7880 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
7881 }
7882
7883 ConstantInt *X = ConstantInt::get(
7884 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
7885 return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
7886 }
7887 break;
7888
7889 case Instruction::AShr: {
7890 // AShr X, C, where C is a constant.
7891 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
7892 if (!CI)
7893 break;
7894
7895 Type *OuterTy = BO->LHS->getType();
7896 uint64_t BitWidth = getTypeSizeInBits(OuterTy);
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 (CI->getValue().uge(BitWidth))
7902 break;
7903
7904 if (CI->isZero())
7905 return getSCEV(BO->LHS); // shift by zero --> noop
7906
7907 uint64_t AShrAmt = CI->getZExtValue();
7908 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
7909
7910 Operator *L = dyn_cast<Operator>(BO->LHS);
7911 if (L && L->getOpcode() == Instruction::Shl) {
7912 // X = Shl A, n
7913 // Y = AShr X, m
7914 // Both n and m are constant.
7915
7916 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
7917 if (L->getOperand(1) == BO->RHS)
7918 // For a two-shift sext-inreg, i.e. n = m,
7919 // use sext(trunc(x)) as the SCEV expression.
7920 return getSignExtendExpr(
7921 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
7922
7923 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
7924 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
7925 uint64_t ShlAmt = ShlAmtCI->getZExtValue();
7926 if (ShlAmt > AShrAmt) {
7927 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
7928 // expression. We already checked that ShlAmt < BitWidth, so
7929 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
7930 // ShlAmt - AShrAmt < Amt.
7931 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
7932 ShlAmt - AShrAmt);
7933 return getSignExtendExpr(
7934 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
7935 getConstant(Mul)), OuterTy);
7936 }
7937 }
7938 }
7939 break;
7940 }
7941 }
7942 }
7943
7944 switch (U->getOpcode()) {
7945 case Instruction::Trunc:
7946 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
7947
7948 case Instruction::ZExt:
7949 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7950
7951 case Instruction::SExt:
7952 if (auto BO = MatchBinaryOp(U->getOperand(0), getDataLayout(), AC, DT,
7953 dyn_cast<Instruction>(V))) {
7954 // The NSW flag of a subtract does not always survive the conversion to
7955 // A + (-1)*B. By pushing sign extension onto its operands we are much
7956 // more likely to preserve NSW and allow later AddRec optimisations.
7957 //
7958 // NOTE: This is effectively duplicating this logic from getSignExtend:
7959 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
7960 // but by that point the NSW information has potentially been lost.
7961 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
7962 Type *Ty = U->getType();
7963 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
7964 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
7965 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
7966 }
7967 }
7968 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7969
7970 case Instruction::BitCast:
7971 // BitCasts are no-op casts so we just eliminate the cast.
7972 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
7973 return getSCEV(U->getOperand(0));
7974 break;
7975
7976 case Instruction::PtrToInt: {
7977 // Pointer to integer cast is straight-forward, so do model it.
7978 const SCEV *Op = getSCEV(U->getOperand(0));
7979 Type *DstIntTy = U->getType();
7980 // But only if effective SCEV (integer) type is wide enough to represent
7981 // all possible pointer values.
7982 const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy);
7983 if (isa<SCEVCouldNotCompute>(IntOp))
7984 return getUnknown(V);
7985 return IntOp;
7986 }
7987 case Instruction::IntToPtr:
7988 // Just don't deal with inttoptr casts.
7989 return getUnknown(V);
7990
7991 case Instruction::SDiv:
7992 // If both operands are non-negative, this is just an udiv.
7993 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7994 isKnownNonNegative(getSCEV(U->getOperand(1))))
7995 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7996 break;
7997
7998 case Instruction::SRem:
7999 // If both operands are non-negative, this is just an urem.
8000 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8001 isKnownNonNegative(getSCEV(U->getOperand(1))))
8002 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8003 break;
8004
8005 case Instruction::GetElementPtr:
8006 return createNodeForGEP(cast<GEPOperator>(U));
8007
8008 case Instruction::PHI:
8009 return createNodeForPHI(cast<PHINode>(U));
8010
8011 case Instruction::Select:
8012 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
8013 U->getOperand(2));
8014
8015 case Instruction::Call:
8016 case Instruction::Invoke:
8017 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
8018 return getSCEV(RV);
8019
8020 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
8021 switch (II->getIntrinsicID()) {
8022 case Intrinsic::abs:
8023 return getAbsExpr(
8024 getSCEV(II->getArgOperand(0)),
8025 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
8026 case Intrinsic::umax:
8027 LHS = getSCEV(II->getArgOperand(0));
8028 RHS = getSCEV(II->getArgOperand(1));
8029 return getUMaxExpr(LHS, RHS);
8030 case Intrinsic::umin:
8031 LHS = getSCEV(II->getArgOperand(0));
8032 RHS = getSCEV(II->getArgOperand(1));
8033 return getUMinExpr(LHS, RHS);
8034 case Intrinsic::smax:
8035 LHS = getSCEV(II->getArgOperand(0));
8036 RHS = getSCEV(II->getArgOperand(1));
8037 return getSMaxExpr(LHS, RHS);
8038 case Intrinsic::smin:
8039 LHS = getSCEV(II->getArgOperand(0));
8040 RHS = getSCEV(II->getArgOperand(1));
8041 return getSMinExpr(LHS, RHS);
8042 case Intrinsic::usub_sat: {
8043 const SCEV *X = getSCEV(II->getArgOperand(0));
8044 const SCEV *Y = getSCEV(II->getArgOperand(1));
8045 const SCEV *ClampedY = getUMinExpr(X, Y);
8046 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
8047 }
8048 case Intrinsic::uadd_sat: {
8049 const SCEV *X = getSCEV(II->getArgOperand(0));
8050 const SCEV *Y = getSCEV(II->getArgOperand(1));
8051 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
8052 return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
8053 }
8054 case Intrinsic::start_loop_iterations:
8055 case Intrinsic::annotation:
8056 case Intrinsic::ptr_annotation:
8057 // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8058 // just eqivalent to the first operand for SCEV purposes.
8059 return getSCEV(II->getArgOperand(0));
8060 default:
8061 break;
8062 }
8063 }
8064 break;
8065 }
8066
8067 return getUnknown(V);
8068 }
8069
8070 //===----------------------------------------------------------------------===//
8071 // Iteration Count Computation Code
8072 //
8073
getTripCountFromExitCount(const SCEV * ExitCount,bool Extend)8074 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount,
8075 bool Extend) {
8076 if (isa<SCEVCouldNotCompute>(ExitCount))
8077 return getCouldNotCompute();
8078
8079 auto *ExitCountType = ExitCount->getType();
8080 assert(ExitCountType->isIntegerTy());
8081
8082 if (!Extend)
8083 return getAddExpr(ExitCount, getOne(ExitCountType));
8084
8085 auto *WiderType = Type::getIntNTy(ExitCountType->getContext(),
8086 1 + ExitCountType->getScalarSizeInBits());
8087 return getAddExpr(getNoopOrZeroExtend(ExitCount, WiderType),
8088 getOne(WiderType));
8089 }
8090
getConstantTripCount(const SCEVConstant * ExitCount)8091 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8092 if (!ExitCount)
8093 return 0;
8094
8095 ConstantInt *ExitConst = ExitCount->getValue();
8096
8097 // Guard against huge trip counts.
8098 if (ExitConst->getValue().getActiveBits() > 32)
8099 return 0;
8100
8101 // In case of integer overflow, this returns 0, which is correct.
8102 return ((unsigned)ExitConst->getZExtValue()) + 1;
8103 }
8104
getSmallConstantTripCount(const Loop * L)8105 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
8106 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
8107 return getConstantTripCount(ExitCount);
8108 }
8109
8110 unsigned
getSmallConstantTripCount(const Loop * L,const BasicBlock * ExitingBlock)8111 ScalarEvolution::getSmallConstantTripCount(const Loop *L,
8112 const BasicBlock *ExitingBlock) {
8113 assert(ExitingBlock && "Must pass a non-null exiting block!");
8114 assert(L->isLoopExiting(ExitingBlock) &&
8115 "Exiting block must actually branch out of the loop!");
8116 const SCEVConstant *ExitCount =
8117 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
8118 return getConstantTripCount(ExitCount);
8119 }
8120
getSmallConstantMaxTripCount(const Loop * L)8121 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
8122 const auto *MaxExitCount =
8123 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
8124 return getConstantTripCount(MaxExitCount);
8125 }
8126
getConstantMaxTripCountFromArray(const Loop * L)8127 const SCEV *ScalarEvolution::getConstantMaxTripCountFromArray(const Loop *L) {
8128 // We can't infer from Array in Irregular Loop.
8129 // FIXME: It's hard to infer loop bound from array operated in Nested Loop.
8130 if (!L->isLoopSimplifyForm() || !L->isInnermost())
8131 return getCouldNotCompute();
8132
8133 // FIXME: To make the scene more typical, we only analysis loops that have
8134 // one exiting block and that block must be the latch. To make it easier to
8135 // capture loops that have memory access and memory access will be executed
8136 // in each iteration.
8137 const BasicBlock *LoopLatch = L->getLoopLatch();
8138 assert(LoopLatch && "See defination of simplify form loop.");
8139 if (L->getExitingBlock() != LoopLatch)
8140 return getCouldNotCompute();
8141
8142 const DataLayout &DL = getDataLayout();
8143 SmallVector<const SCEV *> InferCountColl;
8144 for (auto *BB : L->getBlocks()) {
8145 // Go here, we can know that Loop is a single exiting and simplified form
8146 // loop. Make sure that infer from Memory Operation in those BBs must be
8147 // executed in loop. First step, we can make sure that max execution time
8148 // of MemAccessBB in loop represents latch max excution time.
8149 // If MemAccessBB does not dom Latch, skip.
8150 // Entry
8151 // │
8152 // ┌─────▼─────┐
8153 // │Loop Header◄─────┐
8154 // └──┬──────┬─┘ │
8155 // │ │ │
8156 // ┌────────▼──┐ ┌─▼─────┐ │
8157 // │MemAccessBB│ │OtherBB│ │
8158 // └────────┬──┘ └─┬─────┘ │
8159 // │ │ │
8160 // ┌─▼──────▼─┐ │
8161 // │Loop Latch├─────┘
8162 // └────┬─────┘
8163 // ▼
8164 // Exit
8165 if (!DT.dominates(BB, LoopLatch))
8166 continue;
8167
8168 for (Instruction &Inst : *BB) {
8169 // Find Memory Operation Instruction.
8170 auto *GEP = getLoadStorePointerOperand(&Inst);
8171 if (!GEP)
8172 continue;
8173
8174 auto *ElemSize = dyn_cast<SCEVConstant>(getElementSize(&Inst));
8175 // Do not infer from scalar type, eg."ElemSize = sizeof()".
8176 if (!ElemSize)
8177 continue;
8178
8179 // Use a existing polynomial recurrence on the trip count.
8180 auto *AddRec = dyn_cast<SCEVAddRecExpr>(getSCEV(GEP));
8181 if (!AddRec)
8182 continue;
8183 auto *ArrBase = dyn_cast<SCEVUnknown>(getPointerBase(AddRec));
8184 auto *Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(*this));
8185 if (!ArrBase || !Step)
8186 continue;
8187 assert(isLoopInvariant(ArrBase, L) && "See addrec definition");
8188
8189 // Only handle { %array + step },
8190 // FIXME: {(SCEVAddRecExpr) + step } could not be analysed here.
8191 if (AddRec->getStart() != ArrBase)
8192 continue;
8193
8194 // Memory operation pattern which have gaps.
8195 // Or repeat memory opreation.
8196 // And index of GEP wraps arround.
8197 if (Step->getAPInt().getActiveBits() > 32 ||
8198 Step->getAPInt().getZExtValue() !=
8199 ElemSize->getAPInt().getZExtValue() ||
8200 Step->isZero() || Step->getAPInt().isNegative())
8201 continue;
8202
8203 // Only infer from stack array which has certain size.
8204 // Make sure alloca instruction is not excuted in loop.
8205 AllocaInst *AllocateInst = dyn_cast<AllocaInst>(ArrBase->getValue());
8206 if (!AllocateInst || L->contains(AllocateInst->getParent()))
8207 continue;
8208
8209 // Make sure only handle normal array.
8210 auto *Ty = dyn_cast<ArrayType>(AllocateInst->getAllocatedType());
8211 auto *ArrSize = dyn_cast<ConstantInt>(AllocateInst->getArraySize());
8212 if (!Ty || !ArrSize || !ArrSize->isOne())
8213 continue;
8214
8215 // FIXME: Since gep indices are silently zext to the indexing type,
8216 // we will have a narrow gep index which wraps around rather than
8217 // increasing strictly, we shoule ensure that step is increasing
8218 // strictly by the loop iteration.
8219 // Now we can infer a max execution time by MemLength/StepLength.
8220 const SCEV *MemSize =
8221 getConstant(Step->getType(), DL.getTypeAllocSize(Ty));
8222 auto *MaxExeCount =
8223 dyn_cast<SCEVConstant>(getUDivCeilSCEV(MemSize, Step));
8224 if (!MaxExeCount || MaxExeCount->getAPInt().getActiveBits() > 32)
8225 continue;
8226
8227 // If the loop reaches the maximum number of executions, we can not
8228 // access bytes starting outside the statically allocated size without
8229 // being immediate UB. But it is allowed to enter loop header one more
8230 // time.
8231 auto *InferCount = dyn_cast<SCEVConstant>(
8232 getAddExpr(MaxExeCount, getOne(MaxExeCount->getType())));
8233 // Discard the maximum number of execution times under 32bits.
8234 if (!InferCount || InferCount->getAPInt().getActiveBits() > 32)
8235 continue;
8236
8237 InferCountColl.push_back(InferCount);
8238 }
8239 }
8240
8241 if (InferCountColl.size() == 0)
8242 return getCouldNotCompute();
8243
8244 return getUMinFromMismatchedTypes(InferCountColl);
8245 }
8246
getSmallConstantTripMultiple(const Loop * L)8247 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
8248 SmallVector<BasicBlock *, 8> ExitingBlocks;
8249 L->getExitingBlocks(ExitingBlocks);
8250
8251 std::optional<unsigned> Res;
8252 for (auto *ExitingBB : ExitingBlocks) {
8253 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
8254 if (!Res)
8255 Res = Multiple;
8256 Res = (unsigned)std::gcd(*Res, Multiple);
8257 }
8258 return Res.value_or(1);
8259 }
8260
getSmallConstantTripMultiple(const Loop * L,const SCEV * ExitCount)8261 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
8262 const SCEV *ExitCount) {
8263 if (ExitCount == getCouldNotCompute())
8264 return 1;
8265
8266 // Get the trip count
8267 const SCEV *TCExpr = getTripCountFromExitCount(ExitCount);
8268
8269 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
8270 if (!TC)
8271 // Attempt to factor more general cases. Returns the greatest power of
8272 // two divisor. If overflow happens, the trip count expression is still
8273 // divisible by the greatest power of 2 divisor returned.
8274 return 1U << std::min((uint32_t)31,
8275 GetMinTrailingZeros(applyLoopGuards(TCExpr, L)));
8276
8277 ConstantInt *Result = TC->getValue();
8278
8279 // Guard against huge trip counts (this requires checking
8280 // for zero to handle the case where the trip count == -1 and the
8281 // addition wraps).
8282 if (!Result || Result->getValue().getActiveBits() > 32 ||
8283 Result->getValue().getActiveBits() == 0)
8284 return 1;
8285
8286 return (unsigned)Result->getZExtValue();
8287 }
8288
8289 /// Returns the largest constant divisor of the trip count of this loop as a
8290 /// normal unsigned value, if possible. This means that the actual trip count is
8291 /// always a multiple of the returned value (don't forget the trip count could
8292 /// very well be zero as well!).
8293 ///
8294 /// Returns 1 if the trip count is unknown or not guaranteed to be the
8295 /// multiple of a constant (which is also the case if the trip count is simply
8296 /// constant, use getSmallConstantTripCount for that case), Will also return 1
8297 /// if the trip count is very large (>= 2^32).
8298 ///
8299 /// As explained in the comments for getSmallConstantTripCount, this assumes
8300 /// that control exits the loop via ExitingBlock.
8301 unsigned
getSmallConstantTripMultiple(const Loop * L,const BasicBlock * ExitingBlock)8302 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
8303 const BasicBlock *ExitingBlock) {
8304 assert(ExitingBlock && "Must pass a non-null exiting block!");
8305 assert(L->isLoopExiting(ExitingBlock) &&
8306 "Exiting block must actually branch out of the loop!");
8307 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8308 return getSmallConstantTripMultiple(L, ExitCount);
8309 }
8310
getExitCount(const Loop * L,const BasicBlock * ExitingBlock,ExitCountKind Kind)8311 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
8312 const BasicBlock *ExitingBlock,
8313 ExitCountKind Kind) {
8314 switch (Kind) {
8315 case Exact:
8316 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8317 case SymbolicMaximum:
8318 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8319 case ConstantMaximum:
8320 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8321 };
8322 llvm_unreachable("Invalid ExitCountKind!");
8323 }
8324
8325 const SCEV *
getPredicatedBackedgeTakenCount(const Loop * L,SmallVector<const SCEVPredicate *,4> & Preds)8326 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
8327 SmallVector<const SCEVPredicate *, 4> &Preds) {
8328 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8329 }
8330
getBackedgeTakenCount(const Loop * L,ExitCountKind Kind)8331 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
8332 ExitCountKind Kind) {
8333 switch (Kind) {
8334 case Exact:
8335 return getBackedgeTakenInfo(L).getExact(L, this);
8336 case ConstantMaximum:
8337 return getBackedgeTakenInfo(L).getConstantMax(this);
8338 case SymbolicMaximum:
8339 return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8340 };
8341 llvm_unreachable("Invalid ExitCountKind!");
8342 }
8343
isBackedgeTakenCountMaxOrZero(const Loop * L)8344 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
8345 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8346 }
8347
8348 /// Push PHI nodes in the header of the given loop onto the given Worklist.
PushLoopPHIs(const Loop * L,SmallVectorImpl<Instruction * > & Worklist,SmallPtrSetImpl<Instruction * > & Visited)8349 static void PushLoopPHIs(const Loop *L,
8350 SmallVectorImpl<Instruction *> &Worklist,
8351 SmallPtrSetImpl<Instruction *> &Visited) {
8352 BasicBlock *Header = L->getHeader();
8353
8354 // Push all Loop-header PHIs onto the Worklist stack.
8355 for (PHINode &PN : Header->phis())
8356 if (Visited.insert(&PN).second)
8357 Worklist.push_back(&PN);
8358 }
8359
8360 const ScalarEvolution::BackedgeTakenInfo &
getPredicatedBackedgeTakenInfo(const Loop * L)8361 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8362 auto &BTI = getBackedgeTakenInfo(L);
8363 if (BTI.hasFullInfo())
8364 return BTI;
8365
8366 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
8367
8368 if (!Pair.second)
8369 return Pair.first->second;
8370
8371 BackedgeTakenInfo Result =
8372 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8373
8374 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8375 }
8376
8377 ScalarEvolution::BackedgeTakenInfo &
getBackedgeTakenInfo(const Loop * L)8378 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8379 // Initially insert an invalid entry for this loop. If the insertion
8380 // succeeds, proceed to actually compute a backedge-taken count and
8381 // update the value. The temporary CouldNotCompute value tells SCEV
8382 // code elsewhere that it shouldn't attempt to request a new
8383 // backedge-taken count, which could result in infinite recursion.
8384 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8385 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
8386 if (!Pair.second)
8387 return Pair.first->second;
8388
8389 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8390 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8391 // must be cleared in this scope.
8392 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8393
8394 // In product build, there are no usage of statistic.
8395 (void)NumTripCountsComputed;
8396 (void)NumTripCountsNotComputed;
8397 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
8398 const SCEV *BEExact = Result.getExact(L, this);
8399 if (BEExact != getCouldNotCompute()) {
8400 assert(isLoopInvariant(BEExact, L) &&
8401 isLoopInvariant(Result.getConstantMax(this), L) &&
8402 "Computed backedge-taken count isn't loop invariant for loop!");
8403 ++NumTripCountsComputed;
8404 } else if (Result.getConstantMax(this) == getCouldNotCompute() &&
8405 isa<PHINode>(L->getHeader()->begin())) {
8406 // Only count loops that have phi nodes as not being computable.
8407 ++NumTripCountsNotComputed;
8408 }
8409 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
8410
8411 // Now that we know more about the trip count for this loop, forget any
8412 // existing SCEV values for PHI nodes in this loop since they are only
8413 // conservative estimates made without the benefit of trip count
8414 // information. This invalidation is not necessary for correctness, and is
8415 // only done to produce more precise results.
8416 if (Result.hasAnyInfo()) {
8417 // Invalidate any expression using an addrec in this loop.
8418 SmallVector<const SCEV *, 8> ToForget;
8419 auto LoopUsersIt = LoopUsers.find(L);
8420 if (LoopUsersIt != LoopUsers.end())
8421 append_range(ToForget, LoopUsersIt->second);
8422 forgetMemoizedResults(ToForget);
8423
8424 // Invalidate constant-evolved loop header phis.
8425 for (PHINode &PN : L->getHeader()->phis())
8426 ConstantEvolutionLoopExitValue.erase(&PN);
8427 }
8428
8429 // Re-lookup the insert position, since the call to
8430 // computeBackedgeTakenCount above could result in a
8431 // recusive call to getBackedgeTakenInfo (on a different
8432 // loop), which would invalidate the iterator computed
8433 // earlier.
8434 return BackedgeTakenCounts.find(L)->second = std::move(Result);
8435 }
8436
forgetAllLoops()8437 void ScalarEvolution::forgetAllLoops() {
8438 // This method is intended to forget all info about loops. It should
8439 // invalidate caches as if the following happened:
8440 // - The trip counts of all loops have changed arbitrarily
8441 // - Every llvm::Value has been updated in place to produce a different
8442 // result.
8443 BackedgeTakenCounts.clear();
8444 PredicatedBackedgeTakenCounts.clear();
8445 BECountUsers.clear();
8446 LoopPropertiesCache.clear();
8447 ConstantEvolutionLoopExitValue.clear();
8448 ValueExprMap.clear();
8449 ValuesAtScopes.clear();
8450 ValuesAtScopesUsers.clear();
8451 LoopDispositions.clear();
8452 BlockDispositions.clear();
8453 UnsignedRanges.clear();
8454 SignedRanges.clear();
8455 ExprValueMap.clear();
8456 HasRecMap.clear();
8457 MinTrailingZerosCache.clear();
8458 PredicatedSCEVRewrites.clear();
8459 FoldCache.clear();
8460 FoldCacheUser.clear();
8461 }
8462
forgetLoop(const Loop * L)8463 void ScalarEvolution::forgetLoop(const Loop *L) {
8464 SmallVector<const Loop *, 16> LoopWorklist(1, L);
8465 SmallVector<Instruction *, 32> Worklist;
8466 SmallPtrSet<Instruction *, 16> Visited;
8467 SmallVector<const SCEV *, 16> ToForget;
8468
8469 // Iterate over all the loops and sub-loops to drop SCEV information.
8470 while (!LoopWorklist.empty()) {
8471 auto *CurrL = LoopWorklist.pop_back_val();
8472
8473 // Drop any stored trip count value.
8474 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8475 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8476
8477 // Drop information about predicated SCEV rewrites for this loop.
8478 for (auto I = PredicatedSCEVRewrites.begin();
8479 I != PredicatedSCEVRewrites.end();) {
8480 std::pair<const SCEV *, const Loop *> Entry = I->first;
8481 if (Entry.second == CurrL)
8482 PredicatedSCEVRewrites.erase(I++);
8483 else
8484 ++I;
8485 }
8486
8487 auto LoopUsersItr = LoopUsers.find(CurrL);
8488 if (LoopUsersItr != LoopUsers.end()) {
8489 ToForget.insert(ToForget.end(), LoopUsersItr->second.begin(),
8490 LoopUsersItr->second.end());
8491 }
8492
8493 // Drop information about expressions based on loop-header PHIs.
8494 PushLoopPHIs(CurrL, Worklist, Visited);
8495
8496 while (!Worklist.empty()) {
8497 Instruction *I = Worklist.pop_back_val();
8498
8499 ValueExprMapType::iterator It =
8500 ValueExprMap.find_as(static_cast<Value *>(I));
8501 if (It != ValueExprMap.end()) {
8502 eraseValueFromMap(It->first);
8503 ToForget.push_back(It->second);
8504 if (PHINode *PN = dyn_cast<PHINode>(I))
8505 ConstantEvolutionLoopExitValue.erase(PN);
8506 }
8507
8508 PushDefUseChildren(I, Worklist, Visited);
8509 }
8510
8511 LoopPropertiesCache.erase(CurrL);
8512 // Forget all contained loops too, to avoid dangling entries in the
8513 // ValuesAtScopes map.
8514 LoopWorklist.append(CurrL->begin(), CurrL->end());
8515 }
8516 forgetMemoizedResults(ToForget);
8517 }
8518
forgetTopmostLoop(const Loop * L)8519 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
8520 forgetLoop(L->getOutermostLoop());
8521 }
8522
forgetValue(Value * V)8523 void ScalarEvolution::forgetValue(Value *V) {
8524 Instruction *I = dyn_cast<Instruction>(V);
8525 if (!I) return;
8526
8527 // Drop information about expressions based on loop-header PHIs.
8528 SmallVector<Instruction *, 16> Worklist;
8529 SmallPtrSet<Instruction *, 8> Visited;
8530 SmallVector<const SCEV *, 8> ToForget;
8531 Worklist.push_back(I);
8532 Visited.insert(I);
8533
8534 while (!Worklist.empty()) {
8535 I = Worklist.pop_back_val();
8536 ValueExprMapType::iterator It =
8537 ValueExprMap.find_as(static_cast<Value *>(I));
8538 if (It != ValueExprMap.end()) {
8539 eraseValueFromMap(It->first);
8540 ToForget.push_back(It->second);
8541 if (PHINode *PN = dyn_cast<PHINode>(I))
8542 ConstantEvolutionLoopExitValue.erase(PN);
8543 }
8544
8545 PushDefUseChildren(I, Worklist, Visited);
8546 }
8547 forgetMemoizedResults(ToForget);
8548 }
8549
forgetLoopDispositions()8550 void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8551
forgetBlockAndLoopDispositions(Value * V)8552 void ScalarEvolution::forgetBlockAndLoopDispositions(Value *V) {
8553 // Unless a specific value is passed to invalidation, completely clear both
8554 // caches.
8555 if (!V) {
8556 BlockDispositions.clear();
8557 LoopDispositions.clear();
8558 return;
8559 }
8560
8561 if (!isSCEVable(V->getType()))
8562 return;
8563
8564 const SCEV *S = getExistingSCEV(V);
8565 if (!S)
8566 return;
8567
8568 // Invalidate the block and loop dispositions cached for S. Dispositions of
8569 // S's users may change if S's disposition changes (i.e. a user may change to
8570 // loop-invariant, if S changes to loop invariant), so also invalidate
8571 // dispositions of S's users recursively.
8572 SmallVector<const SCEV *, 8> Worklist = {S};
8573 SmallPtrSet<const SCEV *, 8> Seen = {S};
8574 while (!Worklist.empty()) {
8575 const SCEV *Curr = Worklist.pop_back_val();
8576 bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8577 bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8578 if (!LoopDispoRemoved && !BlockDispoRemoved)
8579 continue;
8580 auto Users = SCEVUsers.find(Curr);
8581 if (Users != SCEVUsers.end())
8582 for (const auto *User : Users->second)
8583 if (Seen.insert(User).second)
8584 Worklist.push_back(User);
8585 }
8586 }
8587
8588 /// Get the exact loop backedge taken count considering all loop exits. A
8589 /// computable result can only be returned for loops with all exiting blocks
8590 /// dominating the latch. howFarToZero assumes that the limit of each loop test
8591 /// is never skipped. This is a valid assumption as long as the loop exits via
8592 /// that test. For precise results, it is the caller's responsibility to specify
8593 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
8594 const SCEV *
getExact(const Loop * L,ScalarEvolution * SE,SmallVector<const SCEVPredicate *,4> * Preds) const8595 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
8596 SmallVector<const SCEVPredicate *, 4> *Preds) const {
8597 // If any exits were not computable, the loop is not computable.
8598 if (!isComplete() || ExitNotTaken.empty())
8599 return SE->getCouldNotCompute();
8600
8601 const BasicBlock *Latch = L->getLoopLatch();
8602 // All exiting blocks we have collected must dominate the only backedge.
8603 if (!Latch)
8604 return SE->getCouldNotCompute();
8605
8606 // All exiting blocks we have gathered dominate loop's latch, so exact trip
8607 // count is simply a minimum out of all these calculated exit counts.
8608 SmallVector<const SCEV *, 2> Ops;
8609 for (const auto &ENT : ExitNotTaken) {
8610 const SCEV *BECount = ENT.ExactNotTaken;
8611 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8612 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8613 "We should only have known counts for exiting blocks that dominate "
8614 "latch!");
8615
8616 Ops.push_back(BECount);
8617
8618 if (Preds)
8619 for (const auto *P : ENT.Predicates)
8620 Preds->push_back(P);
8621
8622 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8623 "Predicate should be always true!");
8624 }
8625
8626 // If an earlier exit exits on the first iteration (exit count zero), then
8627 // a later poison exit count should not propagate into the result. This are
8628 // exactly the semantics provided by umin_seq.
8629 return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8630 }
8631
8632 /// Get the exact not taken count for this loop exit.
8633 const SCEV *
getExact(const BasicBlock * ExitingBlock,ScalarEvolution * SE) const8634 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
8635 ScalarEvolution *SE) const {
8636 for (const auto &ENT : ExitNotTaken)
8637 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8638 return ENT.ExactNotTaken;
8639
8640 return SE->getCouldNotCompute();
8641 }
8642
getConstantMax(const BasicBlock * ExitingBlock,ScalarEvolution * SE) const8643 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8644 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
8645 for (const auto &ENT : ExitNotTaken)
8646 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8647 return ENT.ConstantMaxNotTaken;
8648
8649 return SE->getCouldNotCompute();
8650 }
8651
getSymbolicMax(const BasicBlock * ExitingBlock,ScalarEvolution * SE) const8652 const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8653 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
8654 for (const auto &ENT : ExitNotTaken)
8655 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8656 return ENT.SymbolicMaxNotTaken;
8657
8658 return SE->getCouldNotCompute();
8659 }
8660
8661 /// getConstantMax - Get the constant max backedge taken count for the loop.
8662 const SCEV *
getConstantMax(ScalarEvolution * SE) const8663 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
8664 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8665 return !ENT.hasAlwaysTruePredicate();
8666 };
8667
8668 if (!getConstantMax() || any_of(ExitNotTaken, PredicateNotAlwaysTrue))
8669 return SE->getCouldNotCompute();
8670
8671 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8672 isa<SCEVConstant>(getConstantMax())) &&
8673 "No point in having a non-constant max backedge taken count!");
8674 return getConstantMax();
8675 }
8676
8677 const SCEV *
getSymbolicMax(const Loop * L,ScalarEvolution * SE)8678 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
8679 ScalarEvolution *SE) {
8680 if (!SymbolicMax)
8681 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
8682 return SymbolicMax;
8683 }
8684
isConstantMaxOrZero(ScalarEvolution * SE) const8685 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8686 ScalarEvolution *SE) const {
8687 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8688 return !ENT.hasAlwaysTruePredicate();
8689 };
8690 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8691 }
8692
ExitLimit(const SCEV * E)8693 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
8694 : ExitLimit(E, E, E, false, std::nullopt) {}
8695
ExitLimit(const SCEV * E,const SCEV * ConstantMaxNotTaken,const SCEV * SymbolicMaxNotTaken,bool MaxOrZero,ArrayRef<const SmallPtrSetImpl<const SCEVPredicate * > * > PredSetList)8696 ScalarEvolution::ExitLimit::ExitLimit(
8697 const SCEV *E, const SCEV *ConstantMaxNotTaken,
8698 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8699 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
8700 : ExactNotTaken(E), ConstantMaxNotTaken(ConstantMaxNotTaken),
8701 SymbolicMaxNotTaken(SymbolicMaxNotTaken), MaxOrZero(MaxOrZero) {
8702 // If we prove the max count is zero, so is the symbolic bound. This happens
8703 // in practice due to differences in a) how context sensitive we've chosen
8704 // to be and b) how we reason about bounds implied by UB.
8705 if (ConstantMaxNotTaken->isZero()) {
8706 this->ExactNotTaken = E = ConstantMaxNotTaken;
8707 this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
8708 }
8709
8710 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
8711 !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) &&
8712 "Exact is not allowed to be less precise than Constant Max");
8713 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
8714 !isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken)) &&
8715 "Exact is not allowed to be less precise than Symbolic Max");
8716 assert((isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken) ||
8717 !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) &&
8718 "Symbolic Max is not allowed to be less precise than Constant Max");
8719 assert((isa<SCEVCouldNotCompute>(ConstantMaxNotTaken) ||
8720 isa<SCEVConstant>(ConstantMaxNotTaken)) &&
8721 "No point in having a non-constant max backedge taken count!");
8722 for (const auto *PredSet : PredSetList)
8723 for (const auto *P : *PredSet)
8724 addPredicate(P);
8725 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8726 "Backedge count should be int");
8727 assert((isa<SCEVCouldNotCompute>(ConstantMaxNotTaken) ||
8728 !ConstantMaxNotTaken->getType()->isPointerTy()) &&
8729 "Max backedge count should be int");
8730 }
8731
ExitLimit(const SCEV * E,const SCEV * ConstantMaxNotTaken,const SCEV * SymbolicMaxNotTaken,bool MaxOrZero,const SmallPtrSetImpl<const SCEVPredicate * > & PredSet)8732 ScalarEvolution::ExitLimit::ExitLimit(
8733 const SCEV *E, const SCEV *ConstantMaxNotTaken,
8734 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8735 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
8736 : ExitLimit(E, ConstantMaxNotTaken, SymbolicMaxNotTaken, MaxOrZero,
8737 { &PredSet }) {}
8738
8739 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8740 /// computable exit into a persistent ExitNotTakenInfo array.
BackedgeTakenInfo(ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,bool IsComplete,const SCEV * ConstantMax,bool MaxOrZero)8741 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8742 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
8743 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
8744 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8745 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8746
8747 ExitNotTaken.reserve(ExitCounts.size());
8748 std::transform(ExitCounts.begin(), ExitCounts.end(),
8749 std::back_inserter(ExitNotTaken),
8750 [&](const EdgeExitInfo &EEI) {
8751 BasicBlock *ExitBB = EEI.first;
8752 const ExitLimit &EL = EEI.second;
8753 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
8754 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
8755 EL.Predicates);
8756 });
8757 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
8758 isa<SCEVConstant>(ConstantMax)) &&
8759 "No point in having a non-constant max backedge taken count!");
8760 }
8761
8762 /// Compute the number of times the backedge of the specified loop will execute.
8763 ScalarEvolution::BackedgeTakenInfo
computeBackedgeTakenCount(const Loop * L,bool AllowPredicates)8764 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
8765 bool AllowPredicates) {
8766 SmallVector<BasicBlock *, 8> ExitingBlocks;
8767 L->getExitingBlocks(ExitingBlocks);
8768
8769 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8770
8771 SmallVector<EdgeExitInfo, 4> ExitCounts;
8772 bool CouldComputeBECount = true;
8773 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
8774 const SCEV *MustExitMaxBECount = nullptr;
8775 const SCEV *MayExitMaxBECount = nullptr;
8776 bool MustExitMaxOrZero = false;
8777
8778 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
8779 // and compute maxBECount.
8780 // Do a union of all the predicates here.
8781 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
8782 BasicBlock *ExitBB = ExitingBlocks[i];
8783
8784 // We canonicalize untaken exits to br (constant), ignore them so that
8785 // proving an exit untaken doesn't negatively impact our ability to reason
8786 // about the loop as whole.
8787 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
8788 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
8789 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8790 if (ExitIfTrue == CI->isZero())
8791 continue;
8792 }
8793
8794 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
8795
8796 assert((AllowPredicates || EL.Predicates.empty()) &&
8797 "Predicated exit limit when predicates are not allowed!");
8798
8799 // 1. For each exit that can be computed, add an entry to ExitCounts.
8800 // CouldComputeBECount is true only if all exits can be computed.
8801 if (EL.ExactNotTaken == getCouldNotCompute())
8802 // We couldn't compute an exact value for this exit, so
8803 // we won't be able to compute an exact value for the loop.
8804 CouldComputeBECount = false;
8805 // Remember exit count if either exact or symbolic is known. Because
8806 // Exact always implies symbolic, only check symbolic.
8807 if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
8808 ExitCounts.emplace_back(ExitBB, EL);
8809 else
8810 assert(EL.ExactNotTaken == getCouldNotCompute() &&
8811 "Exact is known but symbolic isn't?");
8812
8813 // 2. Derive the loop's MaxBECount from each exit's max number of
8814 // non-exiting iterations. Partition the loop exits into two kinds:
8815 // LoopMustExits and LoopMayExits.
8816 //
8817 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
8818 // is a LoopMayExit. If any computable LoopMustExit is found, then
8819 // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
8820 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
8821 // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
8822 // any
8823 // computable EL.ConstantMaxNotTaken.
8824 if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
8825 DT.dominates(ExitBB, Latch)) {
8826 if (!MustExitMaxBECount) {
8827 MustExitMaxBECount = EL.ConstantMaxNotTaken;
8828 MustExitMaxOrZero = EL.MaxOrZero;
8829 } else {
8830 MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
8831 EL.ConstantMaxNotTaken);
8832 }
8833 } else if (MayExitMaxBECount != getCouldNotCompute()) {
8834 if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
8835 MayExitMaxBECount = EL.ConstantMaxNotTaken;
8836 else {
8837 MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
8838 EL.ConstantMaxNotTaken);
8839 }
8840 }
8841 }
8842 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
8843 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
8844 // The loop backedge will be taken the maximum or zero times if there's
8845 // a single exit that must be taken the maximum or zero times.
8846 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
8847
8848 // Remember which SCEVs are used in exit limits for invalidation purposes.
8849 // We only care about non-constant SCEVs here, so we can ignore
8850 // EL.ConstantMaxNotTaken
8851 // and MaxBECount, which must be SCEVConstant.
8852 for (const auto &Pair : ExitCounts) {
8853 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
8854 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
8855 if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
8856 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
8857 {L, AllowPredicates});
8858 }
8859 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
8860 MaxBECount, MaxOrZero);
8861 }
8862
8863 ScalarEvolution::ExitLimit
computeExitLimit(const Loop * L,BasicBlock * ExitingBlock,bool AllowPredicates)8864 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
8865 bool AllowPredicates) {
8866 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
8867 // If our exiting block does not dominate the latch, then its connection with
8868 // loop's exit limit may be far from trivial.
8869 const BasicBlock *Latch = L->getLoopLatch();
8870 if (!Latch || !DT.dominates(ExitingBlock, Latch))
8871 return getCouldNotCompute();
8872
8873 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
8874 Instruction *Term = ExitingBlock->getTerminator();
8875 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
8876 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
8877 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8878 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
8879 "It should have one successor in loop and one exit block!");
8880 // Proceed to the next level to examine the exit condition expression.
8881 return computeExitLimitFromCond(
8882 L, BI->getCondition(), ExitIfTrue,
8883 /*ControlsExit=*/IsOnlyExit, AllowPredicates);
8884 }
8885
8886 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
8887 // For switch, make sure that there is a single exit from the loop.
8888 BasicBlock *Exit = nullptr;
8889 for (auto *SBB : successors(ExitingBlock))
8890 if (!L->contains(SBB)) {
8891 if (Exit) // Multiple exit successors.
8892 return getCouldNotCompute();
8893 Exit = SBB;
8894 }
8895 assert(Exit && "Exiting block must have at least one exit");
8896 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
8897 /*ControlsExit=*/IsOnlyExit);
8898 }
8899
8900 return getCouldNotCompute();
8901 }
8902
computeExitLimitFromCond(const Loop * L,Value * ExitCond,bool ExitIfTrue,bool ControlsExit,bool AllowPredicates)8903 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
8904 const Loop *L, Value *ExitCond, bool ExitIfTrue,
8905 bool ControlsExit, bool AllowPredicates) {
8906 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
8907 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
8908 ControlsExit, AllowPredicates);
8909 }
8910
8911 std::optional<ScalarEvolution::ExitLimit>
find(const Loop * L,Value * ExitCond,bool ExitIfTrue,bool ControlsExit,bool AllowPredicates)8912 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
8913 bool ExitIfTrue, bool ControlsExit,
8914 bool AllowPredicates) {
8915 (void)this->L;
8916 (void)this->ExitIfTrue;
8917 (void)this->AllowPredicates;
8918
8919 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8920 this->AllowPredicates == AllowPredicates &&
8921 "Variance in assumed invariant key components!");
8922 auto Itr = TripCountMap.find({ExitCond, ControlsExit});
8923 if (Itr == TripCountMap.end())
8924 return std::nullopt;
8925 return Itr->second;
8926 }
8927
insert(const Loop * L,Value * ExitCond,bool ExitIfTrue,bool ControlsExit,bool AllowPredicates,const ExitLimit & EL)8928 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
8929 bool ExitIfTrue,
8930 bool ControlsExit,
8931 bool AllowPredicates,
8932 const ExitLimit &EL) {
8933 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
8934 this->AllowPredicates == AllowPredicates &&
8935 "Variance in assumed invariant key components!");
8936
8937 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
8938 assert(InsertResult.second && "Expected successful insertion!");
8939 (void)InsertResult;
8940 (void)ExitIfTrue;
8941 }
8942
computeExitLimitFromCondCached(ExitLimitCacheTy & Cache,const Loop * L,Value * ExitCond,bool ExitIfTrue,bool ControlsExit,bool AllowPredicates)8943 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
8944 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8945 bool ControlsExit, bool AllowPredicates) {
8946
8947 if (auto MaybeEL =
8948 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
8949 return *MaybeEL;
8950
8951 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
8952 ControlsExit, AllowPredicates);
8953 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
8954 return EL;
8955 }
8956
computeExitLimitFromCondImpl(ExitLimitCacheTy & Cache,const Loop * L,Value * ExitCond,bool ExitIfTrue,bool ControlsExit,bool AllowPredicates)8957 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
8958 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8959 bool ControlsExit, bool AllowPredicates) {
8960 // Handle BinOp conditions (And, Or).
8961 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
8962 Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
8963 return *LimitFromBinOp;
8964
8965 // With an icmp, it may be feasible to compute an exact backedge-taken count.
8966 // Proceed to the next level to examine the icmp.
8967 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
8968 ExitLimit EL =
8969 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
8970 if (EL.hasFullInfo() || !AllowPredicates)
8971 return EL;
8972
8973 // Try again, but use SCEV predicates this time.
8974 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
8975 /*AllowPredicates=*/true);
8976 }
8977
8978 // Check for a constant condition. These are normally stripped out by
8979 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
8980 // preserve the CFG and is temporarily leaving constant conditions
8981 // in place.
8982 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
8983 if (ExitIfTrue == !CI->getZExtValue())
8984 // The backedge is always taken.
8985 return getCouldNotCompute();
8986 else
8987 // The backedge is never taken.
8988 return getZero(CI->getType());
8989 }
8990
8991 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
8992 // with a constant step, we can form an equivalent icmp predicate and figure
8993 // out how many iterations will be taken before we exit.
8994 const WithOverflowInst *WO;
8995 const APInt *C;
8996 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
8997 match(WO->getRHS(), m_APInt(C))) {
8998 ConstantRange NWR =
8999 ConstantRange::makeExactNoWrapRegion(WO->getBinaryOp(), *C,
9000 WO->getNoWrapKind());
9001 CmpInst::Predicate Pred;
9002 APInt NewRHSC, Offset;
9003 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
9004 if (!ExitIfTrue)
9005 Pred = ICmpInst::getInversePredicate(Pred);
9006 auto *LHS = getSCEV(WO->getLHS());
9007 if (Offset != 0)
9008 LHS = getAddExpr(LHS, getConstant(Offset));
9009 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
9010 ControlsExit, AllowPredicates);
9011 if (EL.hasAnyInfo()) return EL;
9012 }
9013
9014 // If it's not an integer or pointer comparison then compute it the hard way.
9015 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9016 }
9017
9018 std::optional<ScalarEvolution::ExitLimit>
computeExitLimitFromCondFromBinOp(ExitLimitCacheTy & Cache,const Loop * L,Value * ExitCond,bool ExitIfTrue,bool ControlsExit,bool AllowPredicates)9019 ScalarEvolution::computeExitLimitFromCondFromBinOp(
9020 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9021 bool ControlsExit, bool AllowPredicates) {
9022 // Check if the controlling expression for this loop is an And or Or.
9023 Value *Op0, *Op1;
9024 bool IsAnd = false;
9025 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
9026 IsAnd = true;
9027 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
9028 IsAnd = false;
9029 else
9030 return std::nullopt;
9031
9032 // EitherMayExit is true in these two cases:
9033 // br (and Op0 Op1), loop, exit
9034 // br (or Op0 Op1), exit, loop
9035 bool EitherMayExit = IsAnd ^ ExitIfTrue;
9036 ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue,
9037 ControlsExit && !EitherMayExit,
9038 AllowPredicates);
9039 ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue,
9040 ControlsExit && !EitherMayExit,
9041 AllowPredicates);
9042
9043 // Be robust against unsimplified IR for the form "op i1 X, NeutralElement"
9044 const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd);
9045 if (isa<ConstantInt>(Op1))
9046 return Op1 == NeutralElement ? EL0 : EL1;
9047 if (isa<ConstantInt>(Op0))
9048 return Op0 == NeutralElement ? EL1 : EL0;
9049
9050 const SCEV *BECount = getCouldNotCompute();
9051 const SCEV *ConstantMaxBECount = getCouldNotCompute();
9052 const SCEV *SymbolicMaxBECount = getCouldNotCompute();
9053 if (EitherMayExit) {
9054 bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
9055 // Both conditions must be same for the loop to continue executing.
9056 // Choose the less conservative count.
9057 if (EL0.ExactNotTaken != getCouldNotCompute() &&
9058 EL1.ExactNotTaken != getCouldNotCompute()) {
9059 BECount = getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken,
9060 UseSequentialUMin);
9061 }
9062 if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
9063 ConstantMaxBECount = EL1.ConstantMaxNotTaken;
9064 else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
9065 ConstantMaxBECount = EL0.ConstantMaxNotTaken;
9066 else
9067 ConstantMaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
9068 EL1.ConstantMaxNotTaken);
9069 if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
9070 SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
9071 else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
9072 SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
9073 else
9074 SymbolicMaxBECount = getUMinFromMismatchedTypes(
9075 EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
9076 } else {
9077 // Both conditions must be same at the same time for the loop to exit.
9078 // For now, be conservative.
9079 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
9080 BECount = EL0.ExactNotTaken;
9081 }
9082
9083 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
9084 // to be more aggressive when computing BECount than when computing
9085 // ConstantMaxBECount. In these cases it is possible for EL0.ExactNotTaken
9086 // and
9087 // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
9088 // EL1.ConstantMaxNotTaken to not.
9089 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
9090 !isa<SCEVCouldNotCompute>(BECount))
9091 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
9092 if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
9093 SymbolicMaxBECount =
9094 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
9095 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
9096 { &EL0.Predicates, &EL1.Predicates });
9097 }
9098
9099 ScalarEvolution::ExitLimit
computeExitLimitFromICmp(const Loop * L,ICmpInst * ExitCond,bool ExitIfTrue,bool ControlsExit,bool AllowPredicates)9100 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
9101 ICmpInst *ExitCond,
9102 bool ExitIfTrue,
9103 bool ControlsExit,
9104 bool AllowPredicates) {
9105 // If the condition was exit on true, convert the condition to exit on false
9106 ICmpInst::Predicate Pred;
9107 if (!ExitIfTrue)
9108 Pred = ExitCond->getPredicate();
9109 else
9110 Pred = ExitCond->getInversePredicate();
9111 const ICmpInst::Predicate OriginalPred = Pred;
9112
9113 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
9114 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
9115
9116 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsExit,
9117 AllowPredicates);
9118 if (EL.hasAnyInfo()) return EL;
9119
9120 auto *ExhaustiveCount =
9121 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9122
9123 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
9124 return ExhaustiveCount;
9125
9126 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
9127 ExitCond->getOperand(1), L, OriginalPred);
9128 }
9129 ScalarEvolution::ExitLimit
computeExitLimitFromICmp(const Loop * L,ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,bool ControlsExit,bool AllowPredicates)9130 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
9131 ICmpInst::Predicate Pred,
9132 const SCEV *LHS, const SCEV *RHS,
9133 bool ControlsExit,
9134 bool AllowPredicates) {
9135
9136 // Try to evaluate any dependencies out of the loop.
9137 LHS = getSCEVAtScope(LHS, L);
9138 RHS = getSCEVAtScope(RHS, L);
9139
9140 // At this point, we would like to compute how many iterations of the
9141 // loop the predicate will return true for these inputs.
9142 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
9143 // If there is a loop-invariant, force it into the RHS.
9144 std::swap(LHS, RHS);
9145 Pred = ICmpInst::getSwappedPredicate(Pred);
9146 }
9147
9148 bool ControllingFiniteLoop =
9149 ControlsExit && loopHasNoAbnormalExits(L) && loopIsFiniteByAssumption(L);
9150 // Simplify the operands before analyzing them.
9151 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0,
9152 (EnableFiniteLoopControl ? ControllingFiniteLoop
9153 : false));
9154
9155 // If we have a comparison of a chrec against a constant, try to use value
9156 // ranges to answer this query.
9157 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
9158 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
9159 if (AddRec->getLoop() == L) {
9160 // Form the constant range.
9161 ConstantRange CompRange =
9162 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
9163
9164 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
9165 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
9166 }
9167
9168 // If this loop must exit based on this condition (or execute undefined
9169 // behaviour), and we can prove the test sequence produced must repeat
9170 // the same values on self-wrap of the IV, then we can infer that IV
9171 // doesn't self wrap because if it did, we'd have an infinite (undefined)
9172 // loop.
9173 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
9174 // TODO: We can peel off any functions which are invertible *in L*. Loop
9175 // invariant terms are effectively constants for our purposes here.
9176 auto *InnerLHS = LHS;
9177 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
9178 InnerLHS = ZExt->getOperand();
9179 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS)) {
9180 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
9181 if (!AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
9182 StrideC && StrideC->getAPInt().isPowerOf2()) {
9183 auto Flags = AR->getNoWrapFlags();
9184 Flags = setFlags(Flags, SCEV::FlagNW);
9185 SmallVector<const SCEV*> Operands{AR->operands()};
9186 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
9187 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9188 }
9189 }
9190 }
9191
9192 switch (Pred) {
9193 case ICmpInst::ICMP_NE: { // while (X != Y)
9194 // Convert to: while (X-Y != 0)
9195 if (LHS->getType()->isPointerTy()) {
9196 LHS = getLosslessPtrToIntExpr(LHS);
9197 if (isa<SCEVCouldNotCompute>(LHS))
9198 return LHS;
9199 }
9200 if (RHS->getType()->isPointerTy()) {
9201 RHS = getLosslessPtrToIntExpr(RHS);
9202 if (isa<SCEVCouldNotCompute>(RHS))
9203 return RHS;
9204 }
9205 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
9206 AllowPredicates);
9207 if (EL.hasAnyInfo()) return EL;
9208 break;
9209 }
9210 case ICmpInst::ICMP_EQ: { // while (X == Y)
9211 // Convert to: while (X-Y == 0)
9212 if (LHS->getType()->isPointerTy()) {
9213 LHS = getLosslessPtrToIntExpr(LHS);
9214 if (isa<SCEVCouldNotCompute>(LHS))
9215 return LHS;
9216 }
9217 if (RHS->getType()->isPointerTy()) {
9218 RHS = getLosslessPtrToIntExpr(RHS);
9219 if (isa<SCEVCouldNotCompute>(RHS))
9220 return RHS;
9221 }
9222 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
9223 if (EL.hasAnyInfo()) return EL;
9224 break;
9225 }
9226 case ICmpInst::ICMP_SLT:
9227 case ICmpInst::ICMP_ULT: { // while (X < Y)
9228 bool IsSigned = Pred == ICmpInst::ICMP_SLT;
9229 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
9230 AllowPredicates);
9231 if (EL.hasAnyInfo()) return EL;
9232 break;
9233 }
9234 case ICmpInst::ICMP_SGT:
9235 case ICmpInst::ICMP_UGT: { // while (X > Y)
9236 bool IsSigned = Pred == ICmpInst::ICMP_SGT;
9237 ExitLimit EL =
9238 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
9239 AllowPredicates);
9240 if (EL.hasAnyInfo()) return EL;
9241 break;
9242 }
9243 default:
9244 break;
9245 }
9246
9247 return getCouldNotCompute();
9248 }
9249
9250 ScalarEvolution::ExitLimit
computeExitLimitFromSingleExitSwitch(const Loop * L,SwitchInst * Switch,BasicBlock * ExitingBlock,bool ControlsExit)9251 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
9252 SwitchInst *Switch,
9253 BasicBlock *ExitingBlock,
9254 bool ControlsExit) {
9255 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
9256
9257 // Give up if the exit is the default dest of a switch.
9258 if (Switch->getDefaultDest() == ExitingBlock)
9259 return getCouldNotCompute();
9260
9261 assert(L->contains(Switch->getDefaultDest()) &&
9262 "Default case must not exit the loop!");
9263 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
9264 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
9265
9266 // while (X != Y) --> while (X-Y != 0)
9267 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
9268 if (EL.hasAnyInfo())
9269 return EL;
9270
9271 return getCouldNotCompute();
9272 }
9273
9274 static ConstantInt *
EvaluateConstantChrecAtConstant(const SCEVAddRecExpr * AddRec,ConstantInt * C,ScalarEvolution & SE)9275 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
9276 ScalarEvolution &SE) {
9277 const SCEV *InVal = SE.getConstant(C);
9278 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
9279 assert(isa<SCEVConstant>(Val) &&
9280 "Evaluation of SCEV at constant didn't fold correctly?");
9281 return cast<SCEVConstant>(Val)->getValue();
9282 }
9283
computeShiftCompareExitLimit(Value * LHS,Value * RHSV,const Loop * L,ICmpInst::Predicate Pred)9284 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
9285 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
9286 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
9287 if (!RHS)
9288 return getCouldNotCompute();
9289
9290 const BasicBlock *Latch = L->getLoopLatch();
9291 if (!Latch)
9292 return getCouldNotCompute();
9293
9294 const BasicBlock *Predecessor = L->getLoopPredecessor();
9295 if (!Predecessor)
9296 return getCouldNotCompute();
9297
9298 // Return true if V is of the form "LHS `shift_op` <positive constant>".
9299 // Return LHS in OutLHS and shift_opt in OutOpCode.
9300 auto MatchPositiveShift =
9301 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
9302
9303 using namespace PatternMatch;
9304
9305 ConstantInt *ShiftAmt;
9306 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9307 OutOpCode = Instruction::LShr;
9308 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9309 OutOpCode = Instruction::AShr;
9310 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9311 OutOpCode = Instruction::Shl;
9312 else
9313 return false;
9314
9315 return ShiftAmt->getValue().isStrictlyPositive();
9316 };
9317
9318 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
9319 //
9320 // loop:
9321 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
9322 // %iv.shifted = lshr i32 %iv, <positive constant>
9323 //
9324 // Return true on a successful match. Return the corresponding PHI node (%iv
9325 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
9326 auto MatchShiftRecurrence =
9327 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
9328 std::optional<Instruction::BinaryOps> PostShiftOpCode;
9329
9330 {
9331 Instruction::BinaryOps OpC;
9332 Value *V;
9333
9334 // If we encounter a shift instruction, "peel off" the shift operation,
9335 // and remember that we did so. Later when we inspect %iv's backedge
9336 // value, we will make sure that the backedge value uses the same
9337 // operation.
9338 //
9339 // Note: the peeled shift operation does not have to be the same
9340 // instruction as the one feeding into the PHI's backedge value. We only
9341 // really care about it being the same *kind* of shift instruction --
9342 // that's all that is required for our later inferences to hold.
9343 if (MatchPositiveShift(LHS, V, OpC)) {
9344 PostShiftOpCode = OpC;
9345 LHS = V;
9346 }
9347 }
9348
9349 PNOut = dyn_cast<PHINode>(LHS);
9350 if (!PNOut || PNOut->getParent() != L->getHeader())
9351 return false;
9352
9353 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
9354 Value *OpLHS;
9355
9356 return
9357 // The backedge value for the PHI node must be a shift by a positive
9358 // amount
9359 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
9360
9361 // of the PHI node itself
9362 OpLHS == PNOut &&
9363
9364 // and the kind of shift should be match the kind of shift we peeled
9365 // off, if any.
9366 (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9367 };
9368
9369 PHINode *PN;
9370 Instruction::BinaryOps OpCode;
9371 if (!MatchShiftRecurrence(LHS, PN, OpCode))
9372 return getCouldNotCompute();
9373
9374 const DataLayout &DL = getDataLayout();
9375
9376 // The key rationale for this optimization is that for some kinds of shift
9377 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
9378 // within a finite number of iterations. If the condition guarding the
9379 // backedge (in the sense that the backedge is taken if the condition is true)
9380 // is false for the value the shift recurrence stabilizes to, then we know
9381 // that the backedge is taken only a finite number of times.
9382
9383 ConstantInt *StableValue = nullptr;
9384 switch (OpCode) {
9385 default:
9386 llvm_unreachable("Impossible case!");
9387
9388 case Instruction::AShr: {
9389 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
9390 // bitwidth(K) iterations.
9391 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
9392 KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC,
9393 Predecessor->getTerminator(), &DT);
9394 auto *Ty = cast<IntegerType>(RHS->getType());
9395 if (Known.isNonNegative())
9396 StableValue = ConstantInt::get(Ty, 0);
9397 else if (Known.isNegative())
9398 StableValue = ConstantInt::get(Ty, -1, true);
9399 else
9400 return getCouldNotCompute();
9401
9402 break;
9403 }
9404 case Instruction::LShr:
9405 case Instruction::Shl:
9406 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
9407 // stabilize to 0 in at most bitwidth(K) iterations.
9408 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
9409 break;
9410 }
9411
9412 auto *Result =
9413 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
9414 assert(Result->getType()->isIntegerTy(1) &&
9415 "Otherwise cannot be an operand to a branch instruction");
9416
9417 if (Result->isZeroValue()) {
9418 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9419 const SCEV *UpperBound =
9420 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
9421 return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
9422 }
9423
9424 return getCouldNotCompute();
9425 }
9426
9427 /// Return true if we can constant fold an instruction of the specified type,
9428 /// assuming that all operands were constants.
CanConstantFold(const Instruction * I)9429 static bool CanConstantFold(const Instruction *I) {
9430 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
9431 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
9432 isa<LoadInst>(I) || isa<ExtractValueInst>(I))
9433 return true;
9434
9435 if (const CallInst *CI = dyn_cast<CallInst>(I))
9436 if (const Function *F = CI->getCalledFunction())
9437 return canConstantFoldCallTo(CI, F);
9438 return false;
9439 }
9440
9441 /// Determine whether this instruction can constant evolve within this loop
9442 /// assuming its operands can all constant evolve.
canConstantEvolve(Instruction * I,const Loop * L)9443 static bool canConstantEvolve(Instruction *I, const Loop *L) {
9444 // An instruction outside of the loop can't be derived from a loop PHI.
9445 if (!L->contains(I)) return false;
9446
9447 if (isa<PHINode>(I)) {
9448 // We don't currently keep track of the control flow needed to evaluate
9449 // PHIs, so we cannot handle PHIs inside of loops.
9450 return L->getHeader() == I->getParent();
9451 }
9452
9453 // If we won't be able to constant fold this expression even if the operands
9454 // are constants, bail early.
9455 return CanConstantFold(I);
9456 }
9457
9458 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
9459 /// recursing through each instruction operand until reaching a loop header phi.
9460 static PHINode *
getConstantEvolvingPHIOperands(Instruction * UseInst,const Loop * L,DenseMap<Instruction *,PHINode * > & PHIMap,unsigned Depth)9461 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
9462 DenseMap<Instruction *, PHINode *> &PHIMap,
9463 unsigned Depth) {
9464 if (Depth > MaxConstantEvolvingDepth)
9465 return nullptr;
9466
9467 // Otherwise, we can evaluate this instruction if all of its operands are
9468 // constant or derived from a PHI node themselves.
9469 PHINode *PHI = nullptr;
9470 for (Value *Op : UseInst->operands()) {
9471 if (isa<Constant>(Op)) continue;
9472
9473 Instruction *OpInst = dyn_cast<Instruction>(Op);
9474 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
9475
9476 PHINode *P = dyn_cast<PHINode>(OpInst);
9477 if (!P)
9478 // If this operand is already visited, reuse the prior result.
9479 // We may have P != PHI if this is the deepest point at which the
9480 // inconsistent paths meet.
9481 P = PHIMap.lookup(OpInst);
9482 if (!P) {
9483 // Recurse and memoize the results, whether a phi is found or not.
9484 // This recursive call invalidates pointers into PHIMap.
9485 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
9486 PHIMap[OpInst] = P;
9487 }
9488 if (!P)
9489 return nullptr; // Not evolving from PHI
9490 if (PHI && PHI != P)
9491 return nullptr; // Evolving from multiple different PHIs.
9492 PHI = P;
9493 }
9494 // This is a expression evolving from a constant PHI!
9495 return PHI;
9496 }
9497
9498 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9499 /// in the loop that V is derived from. We allow arbitrary operations along the
9500 /// way, but the operands of an operation must either be constants or a value
9501 /// derived from a constant PHI. If this expression does not fit with these
9502 /// constraints, return null.
getConstantEvolvingPHI(Value * V,const Loop * L)9503 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
9504 Instruction *I = dyn_cast<Instruction>(V);
9505 if (!I || !canConstantEvolve(I, L)) return nullptr;
9506
9507 if (PHINode *PN = dyn_cast<PHINode>(I))
9508 return PN;
9509
9510 // Record non-constant instructions contained by the loop.
9511 DenseMap<Instruction *, PHINode *> PHIMap;
9512 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
9513 }
9514
9515 /// EvaluateExpression - Given an expression that passes the
9516 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9517 /// in the loop has the value PHIVal. If we can't fold this expression for some
9518 /// reason, return null.
EvaluateExpression(Value * V,const Loop * L,DenseMap<Instruction *,Constant * > & Vals,const DataLayout & DL,const TargetLibraryInfo * TLI)9519 static Constant *EvaluateExpression(Value *V, const Loop *L,
9520 DenseMap<Instruction *, Constant *> &Vals,
9521 const DataLayout &DL,
9522 const TargetLibraryInfo *TLI) {
9523 // Convenient constant check, but redundant for recursive calls.
9524 if (Constant *C = dyn_cast<Constant>(V)) return C;
9525 Instruction *I = dyn_cast<Instruction>(V);
9526 if (!I) return nullptr;
9527
9528 if (Constant *C = Vals.lookup(I)) return C;
9529
9530 // An instruction inside the loop depends on a value outside the loop that we
9531 // weren't given a mapping for, or a value such as a call inside the loop.
9532 if (!canConstantEvolve(I, L)) return nullptr;
9533
9534 // An unmapped PHI can be due to a branch or another loop inside this loop,
9535 // or due to this not being the initial iteration through a loop where we
9536 // couldn't compute the evolution of this particular PHI last time.
9537 if (isa<PHINode>(I)) return nullptr;
9538
9539 std::vector<Constant*> Operands(I->getNumOperands());
9540
9541 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9542 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9543 if (!Operand) {
9544 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9545 if (!Operands[i]) return nullptr;
9546 continue;
9547 }
9548 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9549 Vals[Operand] = C;
9550 if (!C) return nullptr;
9551 Operands[i] = C;
9552 }
9553
9554 return ConstantFoldInstOperands(I, Operands, DL, TLI);
9555 }
9556
9557
9558 // If every incoming value to PN except the one for BB is a specific Constant,
9559 // return that, else return nullptr.
getOtherIncomingValue(PHINode * PN,BasicBlock * BB)9560 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
9561 Constant *IncomingVal = nullptr;
9562
9563 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9564 if (PN->getIncomingBlock(i) == BB)
9565 continue;
9566
9567 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
9568 if (!CurrentVal)
9569 return nullptr;
9570
9571 if (IncomingVal != CurrentVal) {
9572 if (IncomingVal)
9573 return nullptr;
9574 IncomingVal = CurrentVal;
9575 }
9576 }
9577
9578 return IncomingVal;
9579 }
9580
9581 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9582 /// in the header of its containing loop, we know the loop executes a
9583 /// constant number of times, and the PHI node is just a recurrence
9584 /// involving constants, fold it.
9585 Constant *
getConstantEvolutionLoopExitValue(PHINode * PN,const APInt & BEs,const Loop * L)9586 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9587 const APInt &BEs,
9588 const Loop *L) {
9589 auto I = ConstantEvolutionLoopExitValue.find(PN);
9590 if (I != ConstantEvolutionLoopExitValue.end())
9591 return I->second;
9592
9593 if (BEs.ugt(MaxBruteForceIterations))
9594 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
9595
9596 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
9597
9598 DenseMap<Instruction *, Constant *> CurrentIterVals;
9599 BasicBlock *Header = L->getHeader();
9600 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9601
9602 BasicBlock *Latch = L->getLoopLatch();
9603 if (!Latch)
9604 return nullptr;
9605
9606 for (PHINode &PHI : Header->phis()) {
9607 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9608 CurrentIterVals[&PHI] = StartCST;
9609 }
9610 if (!CurrentIterVals.count(PN))
9611 return RetVal = nullptr;
9612
9613 Value *BEValue = PN->getIncomingValueForBlock(Latch);
9614
9615 // Execute the loop symbolically to determine the exit value.
9616 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
9617 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
9618
9619 unsigned NumIterations = BEs.getZExtValue(); // must be in range
9620 unsigned IterationNum = 0;
9621 const DataLayout &DL = getDataLayout();
9622 for (; ; ++IterationNum) {
9623 if (IterationNum == NumIterations)
9624 return RetVal = CurrentIterVals[PN]; // Got exit value!
9625
9626 // Compute the value of the PHIs for the next iteration.
9627 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9628 DenseMap<Instruction *, Constant *> NextIterVals;
9629 Constant *NextPHI =
9630 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9631 if (!NextPHI)
9632 return nullptr; // Couldn't evaluate!
9633 NextIterVals[PN] = NextPHI;
9634
9635 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9636
9637 // Also evaluate the other PHI nodes. However, we don't get to stop if we
9638 // cease to be able to evaluate one of them or if they stop evolving,
9639 // because that doesn't necessarily prevent us from computing PN.
9640 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
9641 for (const auto &I : CurrentIterVals) {
9642 PHINode *PHI = dyn_cast<PHINode>(I.first);
9643 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
9644 PHIsToCompute.emplace_back(PHI, I.second);
9645 }
9646 // We use two distinct loops because EvaluateExpression may invalidate any
9647 // iterators into CurrentIterVals.
9648 for (const auto &I : PHIsToCompute) {
9649 PHINode *PHI = I.first;
9650 Constant *&NextPHI = NextIterVals[PHI];
9651 if (!NextPHI) { // Not already computed.
9652 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9653 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9654 }
9655 if (NextPHI != I.second)
9656 StoppedEvolving = false;
9657 }
9658
9659 // If all entries in CurrentIterVals == NextIterVals then we can stop
9660 // iterating, the loop can't continue to change.
9661 if (StoppedEvolving)
9662 return RetVal = CurrentIterVals[PN];
9663
9664 CurrentIterVals.swap(NextIterVals);
9665 }
9666 }
9667
computeExitCountExhaustively(const Loop * L,Value * Cond,bool ExitWhen)9668 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
9669 Value *Cond,
9670 bool ExitWhen) {
9671 PHINode *PN = getConstantEvolvingPHI(Cond, L);
9672 if (!PN) return getCouldNotCompute();
9673
9674 // If the loop is canonicalized, the PHI will have exactly two entries.
9675 // That's the only form we support here.
9676 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
9677
9678 DenseMap<Instruction *, Constant *> CurrentIterVals;
9679 BasicBlock *Header = L->getHeader();
9680 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9681
9682 BasicBlock *Latch = L->getLoopLatch();
9683 assert(Latch && "Should follow from NumIncomingValues == 2!");
9684
9685 for (PHINode &PHI : Header->phis()) {
9686 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9687 CurrentIterVals[&PHI] = StartCST;
9688 }
9689 if (!CurrentIterVals.count(PN))
9690 return getCouldNotCompute();
9691
9692 // Okay, we find a PHI node that defines the trip count of this loop. Execute
9693 // the loop symbolically to determine when the condition gets a value of
9694 // "ExitWhen".
9695 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
9696 const DataLayout &DL = getDataLayout();
9697 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
9698 auto *CondVal = dyn_cast_or_null<ConstantInt>(
9699 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
9700
9701 // Couldn't symbolically evaluate.
9702 if (!CondVal) return getCouldNotCompute();
9703
9704 if (CondVal->getValue() == uint64_t(ExitWhen)) {
9705 ++NumBruteForceTripCountsComputed;
9706 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
9707 }
9708
9709 // Update all the PHI nodes for the next iteration.
9710 DenseMap<Instruction *, Constant *> NextIterVals;
9711
9712 // Create a list of which PHIs we need to compute. We want to do this before
9713 // calling EvaluateExpression on them because that may invalidate iterators
9714 // into CurrentIterVals.
9715 SmallVector<PHINode *, 8> PHIsToCompute;
9716 for (const auto &I : CurrentIterVals) {
9717 PHINode *PHI = dyn_cast<PHINode>(I.first);
9718 if (!PHI || PHI->getParent() != Header) continue;
9719 PHIsToCompute.push_back(PHI);
9720 }
9721 for (PHINode *PHI : PHIsToCompute) {
9722 Constant *&NextPHI = NextIterVals[PHI];
9723 if (NextPHI) continue; // Already computed!
9724
9725 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9726 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9727 }
9728 CurrentIterVals.swap(NextIterVals);
9729 }
9730
9731 // Too many iterations were needed to evaluate.
9732 return getCouldNotCompute();
9733 }
9734
getSCEVAtScope(const SCEV * V,const Loop * L)9735 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
9736 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
9737 ValuesAtScopes[V];
9738 // Check to see if we've folded this expression at this loop before.
9739 for (auto &LS : Values)
9740 if (LS.first == L)
9741 return LS.second ? LS.second : V;
9742
9743 Values.emplace_back(L, nullptr);
9744
9745 // Otherwise compute it.
9746 const SCEV *C = computeSCEVAtScope(V, L);
9747 for (auto &LS : reverse(ValuesAtScopes[V]))
9748 if (LS.first == L) {
9749 LS.second = C;
9750 if (!isa<SCEVConstant>(C))
9751 ValuesAtScopesUsers[C].push_back({L, V});
9752 break;
9753 }
9754 return C;
9755 }
9756
9757 /// This builds up a Constant using the ConstantExpr interface. That way, we
9758 /// will return Constants for objects which aren't represented by a
9759 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
9760 /// Returns NULL if the SCEV isn't representable as a Constant.
BuildConstantFromSCEV(const SCEV * V)9761 static Constant *BuildConstantFromSCEV(const SCEV *V) {
9762 switch (V->getSCEVType()) {
9763 case scCouldNotCompute:
9764 case scAddRecExpr:
9765 return nullptr;
9766 case scConstant:
9767 return cast<SCEVConstant>(V)->getValue();
9768 case scUnknown:
9769 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
9770 case scSignExtend: {
9771 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
9772 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
9773 return ConstantExpr::getSExt(CastOp, SS->getType());
9774 return nullptr;
9775 }
9776 case scZeroExtend: {
9777 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
9778 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
9779 return ConstantExpr::getZExt(CastOp, SZ->getType());
9780 return nullptr;
9781 }
9782 case scPtrToInt: {
9783 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
9784 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
9785 return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
9786
9787 return nullptr;
9788 }
9789 case scTruncate: {
9790 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
9791 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
9792 return ConstantExpr::getTrunc(CastOp, ST->getType());
9793 return nullptr;
9794 }
9795 case scAddExpr: {
9796 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
9797 Constant *C = nullptr;
9798 for (const SCEV *Op : SA->operands()) {
9799 Constant *OpC = BuildConstantFromSCEV(Op);
9800 if (!OpC)
9801 return nullptr;
9802 if (!C) {
9803 C = OpC;
9804 continue;
9805 }
9806 assert(!C->getType()->isPointerTy() &&
9807 "Can only have one pointer, and it must be last");
9808 if (auto *PT = dyn_cast<PointerType>(OpC->getType())) {
9809 // The offsets have been converted to bytes. We can add bytes to an
9810 // i8* by GEP with the byte count in the first index.
9811 Type *DestPtrTy =
9812 Type::getInt8PtrTy(PT->getContext(), PT->getAddressSpace());
9813 OpC = ConstantExpr::getBitCast(OpC, DestPtrTy);
9814 C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()),
9815 OpC, C);
9816 } else {
9817 C = ConstantExpr::getAdd(C, OpC);
9818 }
9819 }
9820 return C;
9821 }
9822 case scMulExpr: {
9823 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
9824 Constant *C = nullptr;
9825 for (const SCEV *Op : SM->operands()) {
9826 assert(!Op->getType()->isPointerTy() && "Can't multiply pointers");
9827 Constant *OpC = BuildConstantFromSCEV(Op);
9828 if (!OpC)
9829 return nullptr;
9830 C = C ? ConstantExpr::getMul(C, OpC) : OpC;
9831 }
9832 return C;
9833 }
9834 case scUDivExpr:
9835 case scSMaxExpr:
9836 case scUMaxExpr:
9837 case scSMinExpr:
9838 case scUMinExpr:
9839 case scSequentialUMinExpr:
9840 return nullptr; // TODO: smax, umax, smin, umax, umin_seq.
9841 }
9842 llvm_unreachable("Unknown SCEV kind!");
9843 }
9844
computeSCEVAtScope(const SCEV * V,const Loop * L)9845 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
9846 switch (V->getSCEVType()) {
9847 case scConstant:
9848 return V;
9849 case scAddRecExpr: {
9850 // If this is a loop recurrence for a loop that does not contain L, then we
9851 // are dealing with the final value computed by the loop.
9852 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(V);
9853 // First, attempt to evaluate each operand.
9854 // Avoid performing the look-up in the common case where the specified
9855 // expression has no loop-variant portions.
9856 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
9857 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
9858 if (OpAtScope == AddRec->getOperand(i))
9859 continue;
9860
9861 // Okay, at least one of these operands is loop variant but might be
9862 // foldable. Build a new instance of the folded commutative expression.
9863 SmallVector<const SCEV *, 8> NewOps;
9864 NewOps.reserve(AddRec->getNumOperands());
9865 append_range(NewOps, AddRec->operands().take_front(i));
9866 NewOps.push_back(OpAtScope);
9867 for (++i; i != e; ++i)
9868 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
9869
9870 const SCEV *FoldedRec = getAddRecExpr(
9871 NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags(SCEV::FlagNW));
9872 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
9873 // The addrec may be folded to a nonrecurrence, for example, if the
9874 // induction variable is multiplied by zero after constant folding. Go
9875 // ahead and return the folded value.
9876 if (!AddRec)
9877 return FoldedRec;
9878 break;
9879 }
9880
9881 // If the scope is outside the addrec's loop, evaluate it by using the
9882 // loop exit value of the addrec.
9883 if (!AddRec->getLoop()->contains(L)) {
9884 // To evaluate this recurrence, we need to know how many times the AddRec
9885 // loop iterates. Compute this now.
9886 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
9887 if (BackedgeTakenCount == getCouldNotCompute())
9888 return AddRec;
9889
9890 // Then, evaluate the AddRec.
9891 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
9892 }
9893
9894 return AddRec;
9895 }
9896 case scTruncate:
9897 case scZeroExtend:
9898 case scSignExtend:
9899 case scPtrToInt:
9900 case scAddExpr:
9901 case scMulExpr:
9902 case scUDivExpr:
9903 case scUMaxExpr:
9904 case scSMaxExpr:
9905 case scUMinExpr:
9906 case scSMinExpr:
9907 case scSequentialUMinExpr: {
9908 ArrayRef<const SCEV *> Ops = V->operands();
9909 // Avoid performing the look-up in the common case where the specified
9910 // expression has no loop-variant portions.
9911 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
9912 const SCEV *OpAtScope = getSCEVAtScope(Ops[i], L);
9913 if (OpAtScope != Ops[i]) {
9914 // Okay, at least one of these operands is loop variant but might be
9915 // foldable. Build a new instance of the folded commutative expression.
9916 SmallVector<const SCEV *, 8> NewOps;
9917 NewOps.reserve(Ops.size());
9918 append_range(NewOps, Ops.take_front(i));
9919 NewOps.push_back(OpAtScope);
9920
9921 for (++i; i != e; ++i) {
9922 OpAtScope = getSCEVAtScope(Ops[i], L);
9923 NewOps.push_back(OpAtScope);
9924 }
9925
9926 switch (V->getSCEVType()) {
9927 case scTruncate:
9928 case scZeroExtend:
9929 case scSignExtend:
9930 case scPtrToInt:
9931 return getCastExpr(V->getSCEVType(), NewOps[0], V->getType());
9932 case scAddExpr:
9933 return getAddExpr(NewOps, cast<SCEVAddExpr>(V)->getNoWrapFlags());
9934 case scMulExpr:
9935 return getMulExpr(NewOps, cast<SCEVMulExpr>(V)->getNoWrapFlags());
9936 case scUDivExpr:
9937 return getUDivExpr(NewOps[0], NewOps[1]);
9938 case scUMaxExpr:
9939 case scSMaxExpr:
9940 case scUMinExpr:
9941 case scSMinExpr:
9942 return getMinMaxExpr(V->getSCEVType(), NewOps);
9943 case scSequentialUMinExpr:
9944 return getSequentialMinMaxExpr(V->getSCEVType(), NewOps);
9945 case scConstant:
9946 case scAddRecExpr:
9947 case scUnknown:
9948 case scCouldNotCompute:
9949 llvm_unreachable("Can not get those expressions here.");
9950 }
9951 llvm_unreachable("Unknown n-ary-like SCEV type!");
9952 }
9953 }
9954 // If we got here, all operands are loop invariant.
9955 return V;
9956 }
9957 case scUnknown: {
9958 // If this instruction is evolved from a constant-evolving PHI, compute the
9959 // exit value from the loop without using SCEVs.
9960 const SCEVUnknown *SU = cast<SCEVUnknown>(V);
9961 Instruction *I = dyn_cast<Instruction>(SU->getValue());
9962 if (!I)
9963 return V; // This is some other type of SCEVUnknown, just return it.
9964
9965 if (PHINode *PN = dyn_cast<PHINode>(I)) {
9966 const Loop *CurrLoop = this->LI[I->getParent()];
9967 // Looking for loop exit value.
9968 if (CurrLoop && CurrLoop->getParentLoop() == L &&
9969 PN->getParent() == CurrLoop->getHeader()) {
9970 // Okay, there is no closed form solution for the PHI node. Check
9971 // to see if the loop that contains it has a known backedge-taken
9972 // count. If so, we may be able to force computation of the exit
9973 // value.
9974 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
9975 // This trivial case can show up in some degenerate cases where
9976 // the incoming IR has not yet been fully simplified.
9977 if (BackedgeTakenCount->isZero()) {
9978 Value *InitValue = nullptr;
9979 bool MultipleInitValues = false;
9980 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
9981 if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
9982 if (!InitValue)
9983 InitValue = PN->getIncomingValue(i);
9984 else if (InitValue != PN->getIncomingValue(i)) {
9985 MultipleInitValues = true;
9986 break;
9987 }
9988 }
9989 }
9990 if (!MultipleInitValues && InitValue)
9991 return getSCEV(InitValue);
9992 }
9993 // Do we have a loop invariant value flowing around the backedge
9994 // for a loop which must execute the backedge?
9995 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
9996 isKnownPositive(BackedgeTakenCount) &&
9997 PN->getNumIncomingValues() == 2) {
9998
9999 unsigned InLoopPred =
10000 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
10001 Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
10002 if (CurrLoop->isLoopInvariant(BackedgeVal))
10003 return getSCEV(BackedgeVal);
10004 }
10005 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
10006 // Okay, we know how many times the containing loop executes. If
10007 // this is a constant evolving PHI node, get the final value at
10008 // the specified iteration number.
10009 Constant *RV =
10010 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
10011 if (RV)
10012 return getSCEV(RV);
10013 }
10014 }
10015
10016 // If there is a single-input Phi, evaluate it at our scope. If we can
10017 // prove that this replacement does not break LCSSA form, use new value.
10018 if (PN->getNumOperands() == 1) {
10019 const SCEV *Input = getSCEV(PN->getOperand(0));
10020 const SCEV *InputAtScope = getSCEVAtScope(Input, L);
10021 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
10022 // for the simplest case just support constants.
10023 if (isa<SCEVConstant>(InputAtScope))
10024 return InputAtScope;
10025 }
10026 }
10027
10028 // Okay, this is an expression that we cannot symbolically evaluate
10029 // into a SCEV. Check to see if it's possible to symbolically evaluate
10030 // the arguments into constants, and if so, try to constant propagate the
10031 // result. This is particularly useful for computing loop exit values.
10032 if (!CanConstantFold(I))
10033 return V; // This is some other type of SCEVUnknown, just return it.
10034
10035 SmallVector<Constant *, 4> Operands;
10036 Operands.reserve(I->getNumOperands());
10037 bool MadeImprovement = false;
10038 for (Value *Op : I->operands()) {
10039 if (Constant *C = dyn_cast<Constant>(Op)) {
10040 Operands.push_back(C);
10041 continue;
10042 }
10043
10044 // If any of the operands is non-constant and if they are
10045 // non-integer and non-pointer, don't even try to analyze them
10046 // with scev techniques.
10047 if (!isSCEVable(Op->getType()))
10048 return V;
10049
10050 const SCEV *OrigV = getSCEV(Op);
10051 const SCEV *OpV = getSCEVAtScope(OrigV, L);
10052 MadeImprovement |= OrigV != OpV;
10053
10054 Constant *C = BuildConstantFromSCEV(OpV);
10055 if (!C)
10056 return V;
10057 if (C->getType() != Op->getType())
10058 C = ConstantExpr::getCast(
10059 CastInst::getCastOpcode(C, false, Op->getType(), false), C,
10060 Op->getType());
10061 Operands.push_back(C);
10062 }
10063
10064 // Check to see if getSCEVAtScope actually made an improvement.
10065 if (!MadeImprovement)
10066 return V; // This is some other type of SCEVUnknown, just return it.
10067
10068 Constant *C = nullptr;
10069 const DataLayout &DL = getDataLayout();
10070 C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
10071 if (!C)
10072 return V;
10073 return getSCEV(C);
10074 }
10075 case scCouldNotCompute:
10076 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10077 }
10078 llvm_unreachable("Unknown SCEV type!");
10079 }
10080
getSCEVAtScope(Value * V,const Loop * L)10081 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
10082 return getSCEVAtScope(getSCEV(V), L);
10083 }
10084
stripInjectiveFunctions(const SCEV * S) const10085 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
10086 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
10087 return stripInjectiveFunctions(ZExt->getOperand());
10088 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
10089 return stripInjectiveFunctions(SExt->getOperand());
10090 return S;
10091 }
10092
10093 /// Finds the minimum unsigned root of the following equation:
10094 ///
10095 /// A * X = B (mod N)
10096 ///
10097 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
10098 /// A and B isn't important.
10099 ///
10100 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
SolveLinEquationWithOverflow(const APInt & A,const SCEV * B,ScalarEvolution & SE)10101 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
10102 ScalarEvolution &SE) {
10103 uint32_t BW = A.getBitWidth();
10104 assert(BW == SE.getTypeSizeInBits(B->getType()));
10105 assert(A != 0 && "A must be non-zero.");
10106
10107 // 1. D = gcd(A, N)
10108 //
10109 // The gcd of A and N may have only one prime factor: 2. The number of
10110 // trailing zeros in A is its multiplicity
10111 uint32_t Mult2 = A.countTrailingZeros();
10112 // D = 2^Mult2
10113
10114 // 2. Check if B is divisible by D.
10115 //
10116 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
10117 // is not less than multiplicity of this prime factor for D.
10118 if (SE.GetMinTrailingZeros(B) < Mult2)
10119 return SE.getCouldNotCompute();
10120
10121 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
10122 // modulo (N / D).
10123 //
10124 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
10125 // (N / D) in general. The inverse itself always fits into BW bits, though,
10126 // so we immediately truncate it.
10127 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
10128 APInt Mod(BW + 1, 0);
10129 Mod.setBit(BW - Mult2); // Mod = N / D
10130 APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
10131
10132 // 4. Compute the minimum unsigned root of the equation:
10133 // I * (B / D) mod (N / D)
10134 // To simplify the computation, we factor out the divide by D:
10135 // (I * B mod N) / D
10136 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
10137 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
10138 }
10139
10140 /// For a given quadratic addrec, generate coefficients of the corresponding
10141 /// quadratic equation, multiplied by a common value to ensure that they are
10142 /// integers.
10143 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
10144 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
10145 /// were multiplied by, and BitWidth is the bit width of the original addrec
10146 /// coefficients.
10147 /// This function returns std::nullopt if the addrec coefficients are not
10148 /// compile- time constants.
10149 static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
GetQuadraticEquation(const SCEVAddRecExpr * AddRec)10150 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
10151 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
10152 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
10153 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
10154 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
10155 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
10156 << *AddRec << '\n');
10157
10158 // We currently can only solve this if the coefficients are constants.
10159 if (!LC || !MC || !NC) {
10160 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
10161 return std::nullopt;
10162 }
10163
10164 APInt L = LC->getAPInt();
10165 APInt M = MC->getAPInt();
10166 APInt N = NC->getAPInt();
10167 assert(!N.isZero() && "This is not a quadratic addrec");
10168
10169 unsigned BitWidth = LC->getAPInt().getBitWidth();
10170 unsigned NewWidth = BitWidth + 1;
10171 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
10172 << BitWidth << '\n');
10173 // The sign-extension (as opposed to a zero-extension) here matches the
10174 // extension used in SolveQuadraticEquationWrap (with the same motivation).
10175 N = N.sext(NewWidth);
10176 M = M.sext(NewWidth);
10177 L = L.sext(NewWidth);
10178
10179 // The increments are M, M+N, M+2N, ..., so the accumulated values are
10180 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
10181 // L+M, L+2M+N, L+3M+3N, ...
10182 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
10183 //
10184 // The equation Acc = 0 is then
10185 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
10186 // In a quadratic form it becomes:
10187 // N n^2 + (2M-N) n + 2L = 0.
10188
10189 APInt A = N;
10190 APInt B = 2 * M - A;
10191 APInt C = 2 * L;
10192 APInt T = APInt(NewWidth, 2);
10193 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
10194 << "x + " << C << ", coeff bw: " << NewWidth
10195 << ", multiplied by " << T << '\n');
10196 return std::make_tuple(A, B, C, T, BitWidth);
10197 }
10198
10199 /// Helper function to compare optional APInts:
10200 /// (a) if X and Y both exist, return min(X, Y),
10201 /// (b) if neither X nor Y exist, return std::nullopt,
10202 /// (c) if exactly one of X and Y exists, return that value.
MinOptional(std::optional<APInt> X,std::optional<APInt> Y)10203 static std::optional<APInt> MinOptional(std::optional<APInt> X,
10204 std::optional<APInt> Y) {
10205 if (X && Y) {
10206 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
10207 APInt XW = X->sext(W);
10208 APInt YW = Y->sext(W);
10209 return XW.slt(YW) ? *X : *Y;
10210 }
10211 if (!X && !Y)
10212 return std::nullopt;
10213 return X ? *X : *Y;
10214 }
10215
10216 /// Helper function to truncate an optional APInt to a given BitWidth.
10217 /// When solving addrec-related equations, it is preferable to return a value
10218 /// that has the same bit width as the original addrec's coefficients. If the
10219 /// solution fits in the original bit width, truncate it (except for i1).
10220 /// Returning a value of a different bit width may inhibit some optimizations.
10221 ///
10222 /// In general, a solution to a quadratic equation generated from an addrec
10223 /// may require BW+1 bits, where BW is the bit width of the addrec's
10224 /// coefficients. The reason is that the coefficients of the quadratic
10225 /// equation are BW+1 bits wide (to avoid truncation when converting from
10226 /// the addrec to the equation).
TruncIfPossible(std::optional<APInt> X,unsigned BitWidth)10227 static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
10228 unsigned BitWidth) {
10229 if (!X)
10230 return std::nullopt;
10231 unsigned W = X->getBitWidth();
10232 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
10233 return X->trunc(BitWidth);
10234 return X;
10235 }
10236
10237 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
10238 /// iterations. The values L, M, N are assumed to be signed, and they
10239 /// should all have the same bit widths.
10240 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
10241 /// where BW is the bit width of the addrec's coefficients.
10242 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
10243 /// returned as such, otherwise the bit width of the returned value may
10244 /// be greater than BW.
10245 ///
10246 /// This function returns std::nullopt if
10247 /// (a) the addrec coefficients are not constant, or
10248 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
10249 /// like x^2 = 5, no integer solutions exist, in other cases an integer
10250 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
10251 static std::optional<APInt>
SolveQuadraticAddRecExact(const SCEVAddRecExpr * AddRec,ScalarEvolution & SE)10252 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
10253 APInt A, B, C, M;
10254 unsigned BitWidth;
10255 auto T = GetQuadraticEquation(AddRec);
10256 if (!T)
10257 return std::nullopt;
10258
10259 std::tie(A, B, C, M, BitWidth) = *T;
10260 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
10261 std::optional<APInt> X =
10262 APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth + 1);
10263 if (!X)
10264 return std::nullopt;
10265
10266 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
10267 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
10268 if (!V->isZero())
10269 return std::nullopt;
10270
10271 return TruncIfPossible(X, BitWidth);
10272 }
10273
10274 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
10275 /// iterations. The values M, N are assumed to be signed, and they
10276 /// should all have the same bit widths.
10277 /// Find the least n such that c(n) does not belong to the given range,
10278 /// while c(n-1) does.
10279 ///
10280 /// This function returns std::nullopt if
10281 /// (a) the addrec coefficients are not constant, or
10282 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
10283 /// bounds of the range.
10284 static std::optional<APInt>
SolveQuadraticAddRecRange(const SCEVAddRecExpr * AddRec,const ConstantRange & Range,ScalarEvolution & SE)10285 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
10286 const ConstantRange &Range, ScalarEvolution &SE) {
10287 assert(AddRec->getOperand(0)->isZero() &&
10288 "Starting value of addrec should be 0");
10289 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
10290 << Range << ", addrec " << *AddRec << '\n');
10291 // This case is handled in getNumIterationsInRange. Here we can assume that
10292 // we start in the range.
10293 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
10294 "Addrec's initial value should be in range");
10295
10296 APInt A, B, C, M;
10297 unsigned BitWidth;
10298 auto T = GetQuadraticEquation(AddRec);
10299 if (!T)
10300 return std::nullopt;
10301
10302 // Be careful about the return value: there can be two reasons for not
10303 // returning an actual number. First, if no solutions to the equations
10304 // were found, and second, if the solutions don't leave the given range.
10305 // The first case means that the actual solution is "unknown", the second
10306 // means that it's known, but not valid. If the solution is unknown, we
10307 // cannot make any conclusions.
10308 // Return a pair: the optional solution and a flag indicating if the
10309 // solution was found.
10310 auto SolveForBoundary =
10311 [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
10312 // Solve for signed overflow and unsigned overflow, pick the lower
10313 // solution.
10314 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
10315 << Bound << " (before multiplying by " << M << ")\n");
10316 Bound *= M; // The quadratic equation multiplier.
10317
10318 std::optional<APInt> SO;
10319 if (BitWidth > 1) {
10320 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10321 "signed overflow\n");
10322 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
10323 }
10324 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10325 "unsigned overflow\n");
10326 std::optional<APInt> UO =
10327 APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth + 1);
10328
10329 auto LeavesRange = [&] (const APInt &X) {
10330 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
10331 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
10332 if (Range.contains(V0->getValue()))
10333 return false;
10334 // X should be at least 1, so X-1 is non-negative.
10335 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
10336 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
10337 if (Range.contains(V1->getValue()))
10338 return true;
10339 return false;
10340 };
10341
10342 // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
10343 // can be a solution, but the function failed to find it. We cannot treat it
10344 // as "no solution".
10345 if (!SO || !UO)
10346 return {std::nullopt, false};
10347
10348 // Check the smaller value first to see if it leaves the range.
10349 // At this point, both SO and UO must have values.
10350 std::optional<APInt> Min = MinOptional(SO, UO);
10351 if (LeavesRange(*Min))
10352 return { Min, true };
10353 std::optional<APInt> Max = Min == SO ? UO : SO;
10354 if (LeavesRange(*Max))
10355 return { Max, true };
10356
10357 // Solutions were found, but were eliminated, hence the "true".
10358 return {std::nullopt, true};
10359 };
10360
10361 std::tie(A, B, C, M, BitWidth) = *T;
10362 // Lower bound is inclusive, subtract 1 to represent the exiting value.
10363 APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
10364 APInt Upper = Range.getUpper().sext(A.getBitWidth());
10365 auto SL = SolveForBoundary(Lower);
10366 auto SU = SolveForBoundary(Upper);
10367 // If any of the solutions was unknown, no meaninigful conclusions can
10368 // be made.
10369 if (!SL.second || !SU.second)
10370 return std::nullopt;
10371
10372 // Claim: The correct solution is not some value between Min and Max.
10373 //
10374 // Justification: Assuming that Min and Max are different values, one of
10375 // them is when the first signed overflow happens, the other is when the
10376 // first unsigned overflow happens. Crossing the range boundary is only
10377 // possible via an overflow (treating 0 as a special case of it, modeling
10378 // an overflow as crossing k*2^W for some k).
10379 //
10380 // The interesting case here is when Min was eliminated as an invalid
10381 // solution, but Max was not. The argument is that if there was another
10382 // overflow between Min and Max, it would also have been eliminated if
10383 // it was considered.
10384 //
10385 // For a given boundary, it is possible to have two overflows of the same
10386 // type (signed/unsigned) without having the other type in between: this
10387 // can happen when the vertex of the parabola is between the iterations
10388 // corresponding to the overflows. This is only possible when the two
10389 // overflows cross k*2^W for the same k. In such case, if the second one
10390 // left the range (and was the first one to do so), the first overflow
10391 // would have to enter the range, which would mean that either we had left
10392 // the range before or that we started outside of it. Both of these cases
10393 // are contradictions.
10394 //
10395 // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
10396 // solution is not some value between the Max for this boundary and the
10397 // Min of the other boundary.
10398 //
10399 // Justification: Assume that we had such Max_A and Min_B corresponding
10400 // to range boundaries A and B and such that Max_A < Min_B. If there was
10401 // a solution between Max_A and Min_B, it would have to be caused by an
10402 // overflow corresponding to either A or B. It cannot correspond to B,
10403 // since Min_B is the first occurrence of such an overflow. If it
10404 // corresponded to A, it would have to be either a signed or an unsigned
10405 // overflow that is larger than both eliminated overflows for A. But
10406 // between the eliminated overflows and this overflow, the values would
10407 // cover the entire value space, thus crossing the other boundary, which
10408 // is a contradiction.
10409
10410 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
10411 }
10412
10413 ScalarEvolution::ExitLimit
howFarToZero(const SCEV * V,const Loop * L,bool ControlsExit,bool AllowPredicates)10414 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
10415 bool AllowPredicates) {
10416
10417 // This is only used for loops with a "x != y" exit test. The exit condition
10418 // is now expressed as a single expression, V = x-y. So the exit test is
10419 // effectively V != 0. We know and take advantage of the fact that this
10420 // expression only being used in a comparison by zero context.
10421
10422 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10423 // If the value is a constant
10424 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10425 // If the value is already zero, the branch will execute zero times.
10426 if (C->getValue()->isZero()) return C;
10427 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10428 }
10429
10430 const SCEVAddRecExpr *AddRec =
10431 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
10432
10433 if (!AddRec && AllowPredicates)
10434 // Try to make this an AddRec using runtime tests, in the first X
10435 // iterations of this loop, where X is the SCEV expression found by the
10436 // algorithm below.
10437 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
10438
10439 if (!AddRec || AddRec->getLoop() != L)
10440 return getCouldNotCompute();
10441
10442 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
10443 // the quadratic equation to solve it.
10444 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
10445 // We can only use this value if the chrec ends up with an exact zero
10446 // value at this index. When solving for "X*X != 5", for example, we
10447 // should not accept a root of 2.
10448 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
10449 const auto *R = cast<SCEVConstant>(getConstant(*S));
10450 return ExitLimit(R, R, R, false, Predicates);
10451 }
10452 return getCouldNotCompute();
10453 }
10454
10455 // Otherwise we can only handle this if it is affine.
10456 if (!AddRec->isAffine())
10457 return getCouldNotCompute();
10458
10459 // If this is an affine expression, the execution count of this branch is
10460 // the minimum unsigned root of the following equation:
10461 //
10462 // Start + Step*N = 0 (mod 2^BW)
10463 //
10464 // equivalent to:
10465 //
10466 // Step*N = -Start (mod 2^BW)
10467 //
10468 // where BW is the common bit width of Start and Step.
10469
10470 // Get the initial value for the loop.
10471 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
10472 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
10473
10474 // For now we handle only constant steps.
10475 //
10476 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
10477 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
10478 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
10479 // We have not yet seen any such cases.
10480 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
10481 if (!StepC || StepC->getValue()->isZero())
10482 return getCouldNotCompute();
10483
10484 // For positive steps (counting up until unsigned overflow):
10485 // N = -Start/Step (as unsigned)
10486 // For negative steps (counting down to zero):
10487 // N = Start/-Step
10488 // First compute the unsigned distance from zero in the direction of Step.
10489 bool CountDown = StepC->getAPInt().isNegative();
10490 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
10491
10492 // Handle unitary steps, which cannot wraparound.
10493 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10494 // N = Distance (as unsigned)
10495 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
10496 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
10497 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
10498
10499 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10500 // we end up with a loop whose backedge-taken count is n - 1. Detect this
10501 // case, and see if we can improve the bound.
10502 //
10503 // Explicitly handling this here is necessary because getUnsignedRange
10504 // isn't context-sensitive; it doesn't know that we only care about the
10505 // range inside the loop.
10506 const SCEV *Zero = getZero(Distance->getType());
10507 const SCEV *One = getOne(Distance->getType());
10508 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
10509 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
10510 // If Distance + 1 doesn't overflow, we can compute the maximum distance
10511 // as "unsigned_max(Distance + 1) - 1".
10512 ConstantRange CR = getUnsignedRange(DistancePlusOne);
10513 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
10514 }
10515 return ExitLimit(Distance, getConstant(MaxBECount), Distance, false,
10516 Predicates);
10517 }
10518
10519 // If the condition controls loop exit (the loop exits only if the expression
10520 // is true) and the addition is no-wrap we can use unsigned divide to
10521 // compute the backedge count. In this case, the step may not divide the
10522 // distance, but we don't care because if the condition is "missed" the loop
10523 // will have undefined behavior due to wrapping.
10524 if (ControlsExit && AddRec->hasNoSelfWrap() &&
10525 loopHasNoAbnormalExits(AddRec->getLoop())) {
10526 const SCEV *Exact =
10527 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10528 const SCEV *ConstantMax = getCouldNotCompute();
10529 if (Exact != getCouldNotCompute()) {
10530 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L));
10531 ConstantMax =
10532 getConstant(APIntOps::umin(MaxInt, getUnsignedRangeMax(Exact)));
10533 }
10534 const SCEV *SymbolicMax =
10535 isa<SCEVCouldNotCompute>(Exact) ? ConstantMax : Exact;
10536 return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
10537 }
10538
10539 // Solve the general equation.
10540 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
10541 getNegativeSCEV(Start), *this);
10542
10543 const SCEV *M = E;
10544 if (E != getCouldNotCompute()) {
10545 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, L));
10546 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
10547 }
10548 auto *S = isa<SCEVCouldNotCompute>(E) ? M : E;
10549 return ExitLimit(E, M, S, false, Predicates);
10550 }
10551
10552 ScalarEvolution::ExitLimit
howFarToNonZero(const SCEV * V,const Loop * L)10553 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10554 // Loops that look like: while (X == 0) are very strange indeed. We don't
10555 // handle them yet except for the trivial case. This could be expanded in the
10556 // future as needed.
10557
10558 // If the value is a constant, check to see if it is known to be non-zero
10559 // already. If so, the backedge will execute zero times.
10560 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10561 if (!C->getValue()->isZero())
10562 return getZero(C->getType());
10563 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10564 }
10565
10566 // We could implement others, but I really doubt anyone writes loops like
10567 // this, and if they did, they would already be constant folded.
10568 return getCouldNotCompute();
10569 }
10570
10571 std::pair<const BasicBlock *, const BasicBlock *>
getPredecessorWithUniqueSuccessorForBB(const BasicBlock * BB) const10572 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10573 const {
10574 // If the block has a unique predecessor, then there is no path from the
10575 // predecessor to the block that does not go through the direct edge
10576 // from the predecessor to the block.
10577 if (const BasicBlock *Pred = BB->getSinglePredecessor())
10578 return {Pred, BB};
10579
10580 // A loop's header is defined to be a block that dominates the loop.
10581 // If the header has a unique predecessor outside the loop, it must be
10582 // a block that has exactly one successor that can reach the loop.
10583 if (const Loop *L = LI.getLoopFor(BB))
10584 return {L->getLoopPredecessor(), L->getHeader()};
10585
10586 return {nullptr, nullptr};
10587 }
10588
10589 /// SCEV structural equivalence is usually sufficient for testing whether two
10590 /// expressions are equal, however for the purposes of looking for a condition
10591 /// guarding a loop, it can be useful to be a little more general, since a
10592 /// front-end may have replicated the controlling expression.
HasSameValue(const SCEV * A,const SCEV * B)10593 static bool HasSameValue(const SCEV *A, const SCEV *B) {
10594 // Quick check to see if they are the same SCEV.
10595 if (A == B) return true;
10596
10597 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10598 // Not all instructions that are "identical" compute the same value. For
10599 // instance, two distinct alloca instructions allocating the same type are
10600 // identical and do not read memory; but compute distinct values.
10601 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
10602 };
10603
10604 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10605 // two different instructions with the same value. Check for this case.
10606 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
10607 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
10608 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
10609 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
10610 if (ComputesEqualValues(AI, BI))
10611 return true;
10612
10613 // Otherwise assume they may have a different value.
10614 return false;
10615 }
10616
SimplifyICmpOperands(ICmpInst::Predicate & Pred,const SCEV * & LHS,const SCEV * & RHS,unsigned Depth,bool ControllingFiniteLoop)10617 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
10618 const SCEV *&LHS, const SCEV *&RHS,
10619 unsigned Depth,
10620 bool ControllingFiniteLoop) {
10621 bool Changed = false;
10622 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
10623 // '0 != 0'.
10624 auto TrivialCase = [&](bool TriviallyTrue) {
10625 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
10626 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
10627 return true;
10628 };
10629 // If we hit the max recursion limit bail out.
10630 if (Depth >= 3)
10631 return false;
10632
10633 // Canonicalize a constant to the right side.
10634 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
10635 // Check for both operands constant.
10636 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
10637 if (ConstantExpr::getICmp(Pred,
10638 LHSC->getValue(),
10639 RHSC->getValue())->isNullValue())
10640 return TrivialCase(false);
10641 else
10642 return TrivialCase(true);
10643 }
10644 // Otherwise swap the operands to put the constant on the right.
10645 std::swap(LHS, RHS);
10646 Pred = ICmpInst::getSwappedPredicate(Pred);
10647 Changed = true;
10648 }
10649
10650 // If we're comparing an addrec with a value which is loop-invariant in the
10651 // addrec's loop, put the addrec on the left. Also make a dominance check,
10652 // as both operands could be addrecs loop-invariant in each other's loop.
10653 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
10654 const Loop *L = AR->getLoop();
10655 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
10656 std::swap(LHS, RHS);
10657 Pred = ICmpInst::getSwappedPredicate(Pred);
10658 Changed = true;
10659 }
10660 }
10661
10662 // If there's a constant operand, canonicalize comparisons with boundary
10663 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
10664 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
10665 const APInt &RA = RC->getAPInt();
10666
10667 bool SimplifiedByConstantRange = false;
10668
10669 if (!ICmpInst::isEquality(Pred)) {
10670 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
10671 if (ExactCR.isFullSet())
10672 return TrivialCase(true);
10673 else if (ExactCR.isEmptySet())
10674 return TrivialCase(false);
10675
10676 APInt NewRHS;
10677 CmpInst::Predicate NewPred;
10678 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
10679 ICmpInst::isEquality(NewPred)) {
10680 // We were able to convert an inequality to an equality.
10681 Pred = NewPred;
10682 RHS = getConstant(NewRHS);
10683 Changed = SimplifiedByConstantRange = true;
10684 }
10685 }
10686
10687 if (!SimplifiedByConstantRange) {
10688 switch (Pred) {
10689 default:
10690 break;
10691 case ICmpInst::ICMP_EQ:
10692 case ICmpInst::ICMP_NE:
10693 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
10694 if (!RA)
10695 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
10696 if (const SCEVMulExpr *ME =
10697 dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
10698 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
10699 ME->getOperand(0)->isAllOnesValue()) {
10700 RHS = AE->getOperand(1);
10701 LHS = ME->getOperand(1);
10702 Changed = true;
10703 }
10704 break;
10705
10706
10707 // The "Should have been caught earlier!" messages refer to the fact
10708 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
10709 // should have fired on the corresponding cases, and canonicalized the
10710 // check to trivial case.
10711
10712 case ICmpInst::ICMP_UGE:
10713 assert(!RA.isMinValue() && "Should have been caught earlier!");
10714 Pred = ICmpInst::ICMP_UGT;
10715 RHS = getConstant(RA - 1);
10716 Changed = true;
10717 break;
10718 case ICmpInst::ICMP_ULE:
10719 assert(!RA.isMaxValue() && "Should have been caught earlier!");
10720 Pred = ICmpInst::ICMP_ULT;
10721 RHS = getConstant(RA + 1);
10722 Changed = true;
10723 break;
10724 case ICmpInst::ICMP_SGE:
10725 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
10726 Pred = ICmpInst::ICMP_SGT;
10727 RHS = getConstant(RA - 1);
10728 Changed = true;
10729 break;
10730 case ICmpInst::ICMP_SLE:
10731 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
10732 Pred = ICmpInst::ICMP_SLT;
10733 RHS = getConstant(RA + 1);
10734 Changed = true;
10735 break;
10736 }
10737 }
10738 }
10739
10740 // Check for obvious equality.
10741 if (HasSameValue(LHS, RHS)) {
10742 if (ICmpInst::isTrueWhenEqual(Pred))
10743 return TrivialCase(true);
10744 if (ICmpInst::isFalseWhenEqual(Pred))
10745 return TrivialCase(false);
10746 }
10747
10748 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
10749 // adding or subtracting 1 from one of the operands. This can be done for
10750 // one of two reasons:
10751 // 1) The range of the RHS does not include the (signed/unsigned) boundaries
10752 // 2) The loop is finite, with this comparison controlling the exit. Since the
10753 // loop is finite, the bound cannot include the corresponding boundary
10754 // (otherwise it would loop forever).
10755 switch (Pred) {
10756 case ICmpInst::ICMP_SLE:
10757 if (ControllingFiniteLoop || !getSignedRangeMax(RHS).isMaxSignedValue()) {
10758 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
10759 SCEV::FlagNSW);
10760 Pred = ICmpInst::ICMP_SLT;
10761 Changed = true;
10762 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
10763 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
10764 SCEV::FlagNSW);
10765 Pred = ICmpInst::ICMP_SLT;
10766 Changed = true;
10767 }
10768 break;
10769 case ICmpInst::ICMP_SGE:
10770 if (ControllingFiniteLoop || !getSignedRangeMin(RHS).isMinSignedValue()) {
10771 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
10772 SCEV::FlagNSW);
10773 Pred = ICmpInst::ICMP_SGT;
10774 Changed = true;
10775 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
10776 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
10777 SCEV::FlagNSW);
10778 Pred = ICmpInst::ICMP_SGT;
10779 Changed = true;
10780 }
10781 break;
10782 case ICmpInst::ICMP_ULE:
10783 if (ControllingFiniteLoop || !getUnsignedRangeMax(RHS).isMaxValue()) {
10784 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
10785 SCEV::FlagNUW);
10786 Pred = ICmpInst::ICMP_ULT;
10787 Changed = true;
10788 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
10789 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
10790 Pred = ICmpInst::ICMP_ULT;
10791 Changed = true;
10792 }
10793 break;
10794 case ICmpInst::ICMP_UGE:
10795 if (ControllingFiniteLoop || !getUnsignedRangeMin(RHS).isMinValue()) {
10796 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
10797 Pred = ICmpInst::ICMP_UGT;
10798 Changed = true;
10799 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
10800 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
10801 SCEV::FlagNUW);
10802 Pred = ICmpInst::ICMP_UGT;
10803 Changed = true;
10804 }
10805 break;
10806 default:
10807 break;
10808 }
10809
10810 // TODO: More simplifications are possible here.
10811
10812 // Recursively simplify until we either hit a recursion limit or nothing
10813 // changes.
10814 if (Changed)
10815 return SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1,
10816 ControllingFiniteLoop);
10817
10818 return Changed;
10819 }
10820
isKnownNegative(const SCEV * S)10821 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
10822 return getSignedRangeMax(S).isNegative();
10823 }
10824
isKnownPositive(const SCEV * S)10825 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
10826 return getSignedRangeMin(S).isStrictlyPositive();
10827 }
10828
isKnownNonNegative(const SCEV * S)10829 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
10830 return !getSignedRangeMin(S).isNegative();
10831 }
10832
isKnownNonPositive(const SCEV * S)10833 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
10834 return !getSignedRangeMax(S).isStrictlyPositive();
10835 }
10836
isKnownNonZero(const SCEV * S)10837 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
10838 return getUnsignedRangeMin(S) != 0;
10839 }
10840
10841 std::pair<const SCEV *, const SCEV *>
SplitIntoInitAndPostInc(const Loop * L,const SCEV * S)10842 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
10843 // Compute SCEV on entry of loop L.
10844 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
10845 if (Start == getCouldNotCompute())
10846 return { Start, Start };
10847 // Compute post increment SCEV for loop L.
10848 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
10849 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
10850 return { Start, PostInc };
10851 }
10852
isKnownViaInduction(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)10853 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
10854 const SCEV *LHS, const SCEV *RHS) {
10855 // First collect all loops.
10856 SmallPtrSet<const Loop *, 8> LoopsUsed;
10857 getUsedLoops(LHS, LoopsUsed);
10858 getUsedLoops(RHS, LoopsUsed);
10859
10860 if (LoopsUsed.empty())
10861 return false;
10862
10863 // Domination relationship must be a linear order on collected loops.
10864 #ifndef NDEBUG
10865 for (const auto *L1 : LoopsUsed)
10866 for (const auto *L2 : LoopsUsed)
10867 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
10868 DT.dominates(L2->getHeader(), L1->getHeader())) &&
10869 "Domination relationship is not a linear order");
10870 #endif
10871
10872 const Loop *MDL =
10873 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
10874 [&](const Loop *L1, const Loop *L2) {
10875 return DT.properlyDominates(L1->getHeader(), L2->getHeader());
10876 });
10877
10878 // Get init and post increment value for LHS.
10879 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
10880 // if LHS contains unknown non-invariant SCEV then bail out.
10881 if (SplitLHS.first == getCouldNotCompute())
10882 return false;
10883 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
10884 // Get init and post increment value for RHS.
10885 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
10886 // if RHS contains unknown non-invariant SCEV then bail out.
10887 if (SplitRHS.first == getCouldNotCompute())
10888 return false;
10889 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
10890 // It is possible that init SCEV contains an invariant load but it does
10891 // not dominate MDL and is not available at MDL loop entry, so we should
10892 // check it here.
10893 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
10894 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
10895 return false;
10896
10897 // It seems backedge guard check is faster than entry one so in some cases
10898 // it can speed up whole estimation by short circuit
10899 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
10900 SplitRHS.second) &&
10901 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
10902 }
10903
isKnownPredicate(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)10904 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
10905 const SCEV *LHS, const SCEV *RHS) {
10906 // Canonicalize the inputs first.
10907 (void)SimplifyICmpOperands(Pred, LHS, RHS);
10908
10909 if (isKnownViaInduction(Pred, LHS, RHS))
10910 return true;
10911
10912 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
10913 return true;
10914
10915 // Otherwise see what can be done with some simple reasoning.
10916 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
10917 }
10918
evaluatePredicate(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)10919 std::optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred,
10920 const SCEV *LHS,
10921 const SCEV *RHS) {
10922 if (isKnownPredicate(Pred, LHS, RHS))
10923 return true;
10924 else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS))
10925 return false;
10926 return std::nullopt;
10927 }
10928
isKnownPredicateAt(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const Instruction * CtxI)10929 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
10930 const SCEV *LHS, const SCEV *RHS,
10931 const Instruction *CtxI) {
10932 // TODO: Analyze guards and assumes from Context's block.
10933 return isKnownPredicate(Pred, LHS, RHS) ||
10934 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
10935 }
10936
10937 std::optional<bool>
evaluatePredicateAt(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const Instruction * CtxI)10938 ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, const SCEV *LHS,
10939 const SCEV *RHS, const Instruction *CtxI) {
10940 std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
10941 if (KnownWithoutContext)
10942 return KnownWithoutContext;
10943
10944 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
10945 return true;
10946 else if (isBasicBlockEntryGuardedByCond(CtxI->getParent(),
10947 ICmpInst::getInversePredicate(Pred),
10948 LHS, RHS))
10949 return false;
10950 return std::nullopt;
10951 }
10952
isKnownOnEveryIteration(ICmpInst::Predicate Pred,const SCEVAddRecExpr * LHS,const SCEV * RHS)10953 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
10954 const SCEVAddRecExpr *LHS,
10955 const SCEV *RHS) {
10956 const Loop *L = LHS->getLoop();
10957 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
10958 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
10959 }
10960
10961 std::optional<ScalarEvolution::MonotonicPredicateType>
getMonotonicPredicateType(const SCEVAddRecExpr * LHS,ICmpInst::Predicate Pred)10962 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
10963 ICmpInst::Predicate Pred) {
10964 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
10965
10966 #ifndef NDEBUG
10967 // Verify an invariant: inverting the predicate should turn a monotonically
10968 // increasing change to a monotonically decreasing one, and vice versa.
10969 if (Result) {
10970 auto ResultSwapped =
10971 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
10972
10973 assert(*ResultSwapped != *Result &&
10974 "monotonicity should flip as we flip the predicate");
10975 }
10976 #endif
10977
10978 return Result;
10979 }
10980
10981 std::optional<ScalarEvolution::MonotonicPredicateType>
getMonotonicPredicateTypeImpl(const SCEVAddRecExpr * LHS,ICmpInst::Predicate Pred)10982 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
10983 ICmpInst::Predicate Pred) {
10984 // A zero step value for LHS means the induction variable is essentially a
10985 // loop invariant value. We don't really depend on the predicate actually
10986 // flipping from false to true (for increasing predicates, and the other way
10987 // around for decreasing predicates), all we care about is that *if* the
10988 // predicate changes then it only changes from false to true.
10989 //
10990 // A zero step value in itself is not very useful, but there may be places
10991 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
10992 // as general as possible.
10993
10994 // Only handle LE/LT/GE/GT predicates.
10995 if (!ICmpInst::isRelational(Pred))
10996 return std::nullopt;
10997
10998 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
10999 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
11000 "Should be greater or less!");
11001
11002 // Check that AR does not wrap.
11003 if (ICmpInst::isUnsigned(Pred)) {
11004 if (!LHS->hasNoUnsignedWrap())
11005 return std::nullopt;
11006 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
11007 } else {
11008 assert(ICmpInst::isSigned(Pred) &&
11009 "Relational predicate is either signed or unsigned!");
11010 if (!LHS->hasNoSignedWrap())
11011 return std::nullopt;
11012
11013 const SCEV *Step = LHS->getStepRecurrence(*this);
11014
11015 if (isKnownNonNegative(Step))
11016 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
11017
11018 if (isKnownNonPositive(Step))
11019 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
11020
11021 return std::nullopt;
11022 }
11023 }
11024
11025 std::optional<ScalarEvolution::LoopInvariantPredicate>
getLoopInvariantPredicate(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const Loop * L,const Instruction * CtxI)11026 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
11027 const SCEV *LHS, const SCEV *RHS,
11028 const Loop *L,
11029 const Instruction *CtxI) {
11030 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11031 if (!isLoopInvariant(RHS, L)) {
11032 if (!isLoopInvariant(LHS, L))
11033 return std::nullopt;
11034
11035 std::swap(LHS, RHS);
11036 Pred = ICmpInst::getSwappedPredicate(Pred);
11037 }
11038
11039 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11040 if (!ArLHS || ArLHS->getLoop() != L)
11041 return std::nullopt;
11042
11043 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
11044 if (!MonotonicType)
11045 return std::nullopt;
11046 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
11047 // true as the loop iterates, and the backedge is control dependent on
11048 // "ArLHS `Pred` RHS" == true then we can reason as follows:
11049 //
11050 // * if the predicate was false in the first iteration then the predicate
11051 // is never evaluated again, since the loop exits without taking the
11052 // backedge.
11053 // * if the predicate was true in the first iteration then it will
11054 // continue to be true for all future iterations since it is
11055 // monotonically increasing.
11056 //
11057 // For both the above possibilities, we can replace the loop varying
11058 // predicate with its value on the first iteration of the loop (which is
11059 // loop invariant).
11060 //
11061 // A similar reasoning applies for a monotonically decreasing predicate, by
11062 // replacing true with false and false with true in the above two bullets.
11063 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
11064 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
11065
11066 if (isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
11067 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(),
11068 RHS);
11069
11070 if (!CtxI)
11071 return std::nullopt;
11072 // Try to prove via context.
11073 // TODO: Support other cases.
11074 switch (Pred) {
11075 default:
11076 break;
11077 case ICmpInst::ICMP_ULE:
11078 case ICmpInst::ICMP_ULT: {
11079 assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!");
11080 // Given preconditions
11081 // (1) ArLHS does not cross the border of positive and negative parts of
11082 // range because of:
11083 // - Positive step; (TODO: lift this limitation)
11084 // - nuw - does not cross zero boundary;
11085 // - nsw - does not cross SINT_MAX boundary;
11086 // (2) ArLHS <s RHS
11087 // (3) RHS >=s 0
11088 // we can replace the loop variant ArLHS <u RHS condition with loop
11089 // invariant Start(ArLHS) <u RHS.
11090 //
11091 // Because of (1) there are two options:
11092 // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
11093 // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
11094 // It means that ArLHS <s RHS <=> ArLHS <u RHS.
11095 // Because of (2) ArLHS <u RHS is trivially true.
11096 // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
11097 // We can strengthen this to Start(ArLHS) <u RHS.
11098 auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
11099 if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
11100 isKnownPositive(ArLHS->getStepRecurrence(*this)) &&
11101 isKnownNonNegative(RHS) &&
11102 isKnownPredicateAt(SignFlippedPred, ArLHS, RHS, CtxI))
11103 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(),
11104 RHS);
11105 }
11106 }
11107
11108 return std::nullopt;
11109 }
11110
11111 std::optional<ScalarEvolution::LoopInvariantPredicate>
getLoopInvariantExitCondDuringFirstIterations(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const Loop * L,const Instruction * CtxI,const SCEV * MaxIter)11112 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
11113 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11114 const Instruction *CtxI, const SCEV *MaxIter) {
11115 if (auto LIP = getLoopInvariantExitCondDuringFirstIterationsImpl(
11116 Pred, LHS, RHS, L, CtxI, MaxIter))
11117 return LIP;
11118 if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
11119 // Number of iterations expressed as UMIN isn't always great for expressing
11120 // the value on the last iteration. If the straightforward approach didn't
11121 // work, try the following trick: if the a predicate is invariant for X, it
11122 // is also invariant for umin(X, ...). So try to find something that works
11123 // among subexpressions of MaxIter expressed as umin.
11124 for (auto *Op : UMin->operands())
11125 if (auto LIP = getLoopInvariantExitCondDuringFirstIterationsImpl(
11126 Pred, LHS, RHS, L, CtxI, Op))
11127 return LIP;
11128 return std::nullopt;
11129 }
11130
11131 std::optional<ScalarEvolution::LoopInvariantPredicate>
getLoopInvariantExitCondDuringFirstIterationsImpl(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const Loop * L,const Instruction * CtxI,const SCEV * MaxIter)11132 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterationsImpl(
11133 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11134 const Instruction *CtxI, const SCEV *MaxIter) {
11135 // Try to prove the following set of facts:
11136 // - The predicate is monotonic in the iteration space.
11137 // - If the check does not fail on the 1st iteration:
11138 // - No overflow will happen during first MaxIter iterations;
11139 // - It will not fail on the MaxIter'th iteration.
11140 // If the check does fail on the 1st iteration, we leave the loop and no
11141 // other checks matter.
11142
11143 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11144 if (!isLoopInvariant(RHS, L)) {
11145 if (!isLoopInvariant(LHS, L))
11146 return std::nullopt;
11147
11148 std::swap(LHS, RHS);
11149 Pred = ICmpInst::getSwappedPredicate(Pred);
11150 }
11151
11152 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
11153 if (!AR || AR->getLoop() != L)
11154 return std::nullopt;
11155
11156 // The predicate must be relational (i.e. <, <=, >=, >).
11157 if (!ICmpInst::isRelational(Pred))
11158 return std::nullopt;
11159
11160 // TODO: Support steps other than +/- 1.
11161 const SCEV *Step = AR->getStepRecurrence(*this);
11162 auto *One = getOne(Step->getType());
11163 auto *MinusOne = getNegativeSCEV(One);
11164 if (Step != One && Step != MinusOne)
11165 return std::nullopt;
11166
11167 // Type mismatch here means that MaxIter is potentially larger than max
11168 // unsigned value in start type, which mean we cannot prove no wrap for the
11169 // indvar.
11170 if (AR->getType() != MaxIter->getType())
11171 return std::nullopt;
11172
11173 // Value of IV on suggested last iteration.
11174 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
11175 // Does it still meet the requirement?
11176 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
11177 return std::nullopt;
11178 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
11179 // not exceed max unsigned value of this type), this effectively proves
11180 // that there is no wrap during the iteration. To prove that there is no
11181 // signed/unsigned wrap, we need to check that
11182 // Start <= Last for step = 1 or Start >= Last for step = -1.
11183 ICmpInst::Predicate NoOverflowPred =
11184 CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
11185 if (Step == MinusOne)
11186 NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
11187 const SCEV *Start = AR->getStart();
11188 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
11189 return std::nullopt;
11190
11191 // Everything is fine.
11192 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
11193 }
11194
isKnownPredicateViaConstantRanges(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)11195 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
11196 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
11197 if (HasSameValue(LHS, RHS))
11198 return ICmpInst::isTrueWhenEqual(Pred);
11199
11200 // This code is split out from isKnownPredicate because it is called from
11201 // within isLoopEntryGuardedByCond.
11202
11203 auto CheckRanges = [&](const ConstantRange &RangeLHS,
11204 const ConstantRange &RangeRHS) {
11205 return RangeLHS.icmp(Pred, RangeRHS);
11206 };
11207
11208 // The check at the top of the function catches the case where the values are
11209 // known to be equal.
11210 if (Pred == CmpInst::ICMP_EQ)
11211 return false;
11212
11213 if (Pred == CmpInst::ICMP_NE) {
11214 auto SL = getSignedRange(LHS);
11215 auto SR = getSignedRange(RHS);
11216 if (CheckRanges(SL, SR))
11217 return true;
11218 auto UL = getUnsignedRange(LHS);
11219 auto UR = getUnsignedRange(RHS);
11220 if (CheckRanges(UL, UR))
11221 return true;
11222 auto *Diff = getMinusSCEV(LHS, RHS);
11223 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
11224 }
11225
11226 if (CmpInst::isSigned(Pred)) {
11227 auto SL = getSignedRange(LHS);
11228 auto SR = getSignedRange(RHS);
11229 return CheckRanges(SL, SR);
11230 }
11231
11232 auto UL = getUnsignedRange(LHS);
11233 auto UR = getUnsignedRange(RHS);
11234 return CheckRanges(UL, UR);
11235 }
11236
isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)11237 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
11238 const SCEV *LHS,
11239 const SCEV *RHS) {
11240 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
11241 // C1 and C2 are constant integers. If either X or Y are not add expressions,
11242 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
11243 // OutC1 and OutC2.
11244 auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y,
11245 APInt &OutC1, APInt &OutC2,
11246 SCEV::NoWrapFlags ExpectedFlags) {
11247 const SCEV *XNonConstOp, *XConstOp;
11248 const SCEV *YNonConstOp, *YConstOp;
11249 SCEV::NoWrapFlags XFlagsPresent;
11250 SCEV::NoWrapFlags YFlagsPresent;
11251
11252 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
11253 XConstOp = getZero(X->getType());
11254 XNonConstOp = X;
11255 XFlagsPresent = ExpectedFlags;
11256 }
11257 if (!isa<SCEVConstant>(XConstOp) ||
11258 (XFlagsPresent & ExpectedFlags) != ExpectedFlags)
11259 return false;
11260
11261 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
11262 YConstOp = getZero(Y->getType());
11263 YNonConstOp = Y;
11264 YFlagsPresent = ExpectedFlags;
11265 }
11266
11267 if (!isa<SCEVConstant>(YConstOp) ||
11268 (YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11269 return false;
11270
11271 if (YNonConstOp != XNonConstOp)
11272 return false;
11273
11274 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
11275 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
11276
11277 return true;
11278 };
11279
11280 APInt C1;
11281 APInt C2;
11282
11283 switch (Pred) {
11284 default:
11285 break;
11286
11287 case ICmpInst::ICMP_SGE:
11288 std::swap(LHS, RHS);
11289 [[fallthrough]];
11290 case ICmpInst::ICMP_SLE:
11291 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
11292 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
11293 return true;
11294
11295 break;
11296
11297 case ICmpInst::ICMP_SGT:
11298 std::swap(LHS, RHS);
11299 [[fallthrough]];
11300 case ICmpInst::ICMP_SLT:
11301 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
11302 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
11303 return true;
11304
11305 break;
11306
11307 case ICmpInst::ICMP_UGE:
11308 std::swap(LHS, RHS);
11309 [[fallthrough]];
11310 case ICmpInst::ICMP_ULE:
11311 // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2.
11312 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2))
11313 return true;
11314
11315 break;
11316
11317 case ICmpInst::ICMP_UGT:
11318 std::swap(LHS, RHS);
11319 [[fallthrough]];
11320 case ICmpInst::ICMP_ULT:
11321 // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2.
11322 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2))
11323 return true;
11324 break;
11325 }
11326
11327 return false;
11328 }
11329
isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)11330 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
11331 const SCEV *LHS,
11332 const SCEV *RHS) {
11333 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
11334 return false;
11335
11336 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
11337 // the stack can result in exponential time complexity.
11338 SaveAndRestore Restore(ProvingSplitPredicate, true);
11339
11340 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
11341 //
11342 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
11343 // isKnownPredicate. isKnownPredicate is more powerful, but also more
11344 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
11345 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
11346 // use isKnownPredicate later if needed.
11347 return isKnownNonNegative(RHS) &&
11348 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
11349 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
11350 }
11351
isImpliedViaGuard(const BasicBlock * BB,ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)11352 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
11353 ICmpInst::Predicate Pred,
11354 const SCEV *LHS, const SCEV *RHS) {
11355 // No need to even try if we know the module has no guards.
11356 if (AC.assumptions().empty())
11357 return false;
11358
11359 return any_of(*BB, [&](const Instruction &I) {
11360 using namespace llvm::PatternMatch;
11361
11362 Value *Condition;
11363 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
11364 m_Value(Condition))) &&
11365 isImpliedCond(Pred, LHS, RHS, Condition, false);
11366 });
11367 }
11368
11369 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
11370 /// protected by a conditional between LHS and RHS. This is used to
11371 /// to eliminate casts.
11372 bool
isLoopBackedgeGuardedByCond(const Loop * L,ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)11373 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
11374 ICmpInst::Predicate Pred,
11375 const SCEV *LHS, const SCEV *RHS) {
11376 // Interpret a null as meaning no loop, where there is obviously no guard
11377 // (interprocedural conditions notwithstanding). Do not bother about
11378 // unreachable loops.
11379 if (!L || !DT.isReachableFromEntry(L->getHeader()))
11380 return true;
11381
11382 if (VerifyIR)
11383 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
11384 "This cannot be done on broken IR!");
11385
11386
11387 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11388 return true;
11389
11390 BasicBlock *Latch = L->getLoopLatch();
11391 if (!Latch)
11392 return false;
11393
11394 BranchInst *LoopContinuePredicate =
11395 dyn_cast<BranchInst>(Latch->getTerminator());
11396 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
11397 isImpliedCond(Pred, LHS, RHS,
11398 LoopContinuePredicate->getCondition(),
11399 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
11400 return true;
11401
11402 // We don't want more than one activation of the following loops on the stack
11403 // -- that can lead to O(n!) time complexity.
11404 if (WalkingBEDominatingConds)
11405 return false;
11406
11407 SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
11408
11409 // See if we can exploit a trip count to prove the predicate.
11410 const auto &BETakenInfo = getBackedgeTakenInfo(L);
11411 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
11412 if (LatchBECount != getCouldNotCompute()) {
11413 // We know that Latch branches back to the loop header exactly
11414 // LatchBECount times. This means the backdege condition at Latch is
11415 // equivalent to "{0,+,1} u< LatchBECount".
11416 Type *Ty = LatchBECount->getType();
11417 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
11418 const SCEV *LoopCounter =
11419 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
11420 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
11421 LatchBECount))
11422 return true;
11423 }
11424
11425 // Check conditions due to any @llvm.assume intrinsics.
11426 for (auto &AssumeVH : AC.assumptions()) {
11427 if (!AssumeVH)
11428 continue;
11429 auto *CI = cast<CallInst>(AssumeVH);
11430 if (!DT.dominates(CI, Latch->getTerminator()))
11431 continue;
11432
11433 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
11434 return true;
11435 }
11436
11437 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
11438 return true;
11439
11440 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
11441 DTN != HeaderDTN; DTN = DTN->getIDom()) {
11442 assert(DTN && "should reach the loop header before reaching the root!");
11443
11444 BasicBlock *BB = DTN->getBlock();
11445 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
11446 return true;
11447
11448 BasicBlock *PBB = BB->getSinglePredecessor();
11449 if (!PBB)
11450 continue;
11451
11452 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
11453 if (!ContinuePredicate || !ContinuePredicate->isConditional())
11454 continue;
11455
11456 Value *Condition = ContinuePredicate->getCondition();
11457
11458 // If we have an edge `E` within the loop body that dominates the only
11459 // latch, the condition guarding `E` also guards the backedge. This
11460 // reasoning works only for loops with a single latch.
11461
11462 BasicBlockEdge DominatingEdge(PBB, BB);
11463 if (DominatingEdge.isSingleEdge()) {
11464 // We're constructively (and conservatively) enumerating edges within the
11465 // loop body that dominate the latch. The dominator tree better agree
11466 // with us on this:
11467 assert(DT.dominates(DominatingEdge, Latch) && "should be!");
11468
11469 if (isImpliedCond(Pred, LHS, RHS, Condition,
11470 BB != ContinuePredicate->getSuccessor(0)))
11471 return true;
11472 }
11473 }
11474
11475 return false;
11476 }
11477
isBasicBlockEntryGuardedByCond(const BasicBlock * BB,ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)11478 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
11479 ICmpInst::Predicate Pred,
11480 const SCEV *LHS,
11481 const SCEV *RHS) {
11482 // Do not bother proving facts for unreachable code.
11483 if (!DT.isReachableFromEntry(BB))
11484 return true;
11485 if (VerifyIR)
11486 assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
11487 "This cannot be done on broken IR!");
11488
11489 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
11490 // the facts (a >= b && a != b) separately. A typical situation is when the
11491 // non-strict comparison is known from ranges and non-equality is known from
11492 // dominating predicates. If we are proving strict comparison, we always try
11493 // to prove non-equality and non-strict comparison separately.
11494 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
11495 const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
11496 bool ProvedNonStrictComparison = false;
11497 bool ProvedNonEquality = false;
11498
11499 auto SplitAndProve =
11500 [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool {
11501 if (!ProvedNonStrictComparison)
11502 ProvedNonStrictComparison = Fn(NonStrictPredicate);
11503 if (!ProvedNonEquality)
11504 ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
11505 if (ProvedNonStrictComparison && ProvedNonEquality)
11506 return true;
11507 return false;
11508 };
11509
11510 if (ProvingStrictComparison) {
11511 auto ProofFn = [&](ICmpInst::Predicate P) {
11512 return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
11513 };
11514 if (SplitAndProve(ProofFn))
11515 return true;
11516 }
11517
11518 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
11519 auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
11520 const Instruction *CtxI = &BB->front();
11521 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
11522 return true;
11523 if (ProvingStrictComparison) {
11524 auto ProofFn = [&](ICmpInst::Predicate P) {
11525 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
11526 };
11527 if (SplitAndProve(ProofFn))
11528 return true;
11529 }
11530 return false;
11531 };
11532
11533 // Starting at the block's predecessor, climb up the predecessor chain, as long
11534 // as there are predecessors that can be found that have unique successors
11535 // leading to the original block.
11536 const Loop *ContainingLoop = LI.getLoopFor(BB);
11537 const BasicBlock *PredBB;
11538 if (ContainingLoop && ContainingLoop->getHeader() == BB)
11539 PredBB = ContainingLoop->getLoopPredecessor();
11540 else
11541 PredBB = BB->getSinglePredecessor();
11542 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
11543 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
11544 const BranchInst *BlockEntryPredicate =
11545 dyn_cast<BranchInst>(Pair.first->getTerminator());
11546 if (!BlockEntryPredicate || BlockEntryPredicate->isUnconditional())
11547 continue;
11548
11549 if (ProveViaCond(BlockEntryPredicate->getCondition(),
11550 BlockEntryPredicate->getSuccessor(0) != Pair.second))
11551 return true;
11552 }
11553
11554 // Check conditions due to any @llvm.assume intrinsics.
11555 for (auto &AssumeVH : AC.assumptions()) {
11556 if (!AssumeVH)
11557 continue;
11558 auto *CI = cast<CallInst>(AssumeVH);
11559 if (!DT.dominates(CI, BB))
11560 continue;
11561
11562 if (ProveViaCond(CI->getArgOperand(0), false))
11563 return true;
11564 }
11565
11566 return false;
11567 }
11568
isLoopEntryGuardedByCond(const Loop * L,ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)11569 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
11570 ICmpInst::Predicate Pred,
11571 const SCEV *LHS,
11572 const SCEV *RHS) {
11573 // Interpret a null as meaning no loop, where there is obviously no guard
11574 // (interprocedural conditions notwithstanding).
11575 if (!L)
11576 return false;
11577
11578 // Both LHS and RHS must be available at loop entry.
11579 assert(isAvailableAtLoopEntry(LHS, L) &&
11580 "LHS is not available at Loop Entry");
11581 assert(isAvailableAtLoopEntry(RHS, L) &&
11582 "RHS is not available at Loop Entry");
11583
11584 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11585 return true;
11586
11587 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
11588 }
11589
isImpliedCond(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const Value * FoundCondValue,bool Inverse,const Instruction * CtxI)11590 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
11591 const SCEV *RHS,
11592 const Value *FoundCondValue, bool Inverse,
11593 const Instruction *CtxI) {
11594 // False conditions implies anything. Do not bother analyzing it further.
11595 if (FoundCondValue ==
11596 ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
11597 return true;
11598
11599 if (!PendingLoopPredicates.insert(FoundCondValue).second)
11600 return false;
11601
11602 auto ClearOnExit =
11603 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
11604
11605 // Recursively handle And and Or conditions.
11606 const Value *Op0, *Op1;
11607 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
11608 if (!Inverse)
11609 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
11610 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
11611 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
11612 if (Inverse)
11613 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
11614 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
11615 }
11616
11617 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
11618 if (!ICI) return false;
11619
11620 // Now that we found a conditional branch that dominates the loop or controls
11621 // the loop latch. Check to see if it is the comparison we are looking for.
11622 ICmpInst::Predicate FoundPred;
11623 if (Inverse)
11624 FoundPred = ICI->getInversePredicate();
11625 else
11626 FoundPred = ICI->getPredicate();
11627
11628 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
11629 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
11630
11631 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
11632 }
11633
isImpliedCond(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,ICmpInst::Predicate FoundPred,const SCEV * FoundLHS,const SCEV * FoundRHS,const Instruction * CtxI)11634 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
11635 const SCEV *RHS,
11636 ICmpInst::Predicate FoundPred,
11637 const SCEV *FoundLHS, const SCEV *FoundRHS,
11638 const Instruction *CtxI) {
11639 // Balance the types.
11640 if (getTypeSizeInBits(LHS->getType()) <
11641 getTypeSizeInBits(FoundLHS->getType())) {
11642 // For unsigned and equality predicates, try to prove that both found
11643 // operands fit into narrow unsigned range. If so, try to prove facts in
11644 // narrow types.
11645 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
11646 !FoundRHS->getType()->isPointerTy()) {
11647 auto *NarrowType = LHS->getType();
11648 auto *WideType = FoundLHS->getType();
11649 auto BitWidth = getTypeSizeInBits(NarrowType);
11650 const SCEV *MaxValue = getZeroExtendExpr(
11651 getConstant(APInt::getMaxValue(BitWidth)), WideType);
11652 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
11653 MaxValue) &&
11654 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
11655 MaxValue)) {
11656 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
11657 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
11658 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
11659 TruncFoundRHS, CtxI))
11660 return true;
11661 }
11662 }
11663
11664 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
11665 return false;
11666 if (CmpInst::isSigned(Pred)) {
11667 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
11668 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
11669 } else {
11670 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
11671 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
11672 }
11673 } else if (getTypeSizeInBits(LHS->getType()) >
11674 getTypeSizeInBits(FoundLHS->getType())) {
11675 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
11676 return false;
11677 if (CmpInst::isSigned(FoundPred)) {
11678 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
11679 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
11680 } else {
11681 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
11682 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
11683 }
11684 }
11685 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
11686 FoundRHS, CtxI);
11687 }
11688
isImpliedCondBalancedTypes(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,ICmpInst::Predicate FoundPred,const SCEV * FoundLHS,const SCEV * FoundRHS,const Instruction * CtxI)11689 bool ScalarEvolution::isImpliedCondBalancedTypes(
11690 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11691 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
11692 const Instruction *CtxI) {
11693 assert(getTypeSizeInBits(LHS->getType()) ==
11694 getTypeSizeInBits(FoundLHS->getType()) &&
11695 "Types should be balanced!");
11696 // Canonicalize the query to match the way instcombine will have
11697 // canonicalized the comparison.
11698 if (SimplifyICmpOperands(Pred, LHS, RHS))
11699 if (LHS == RHS)
11700 return CmpInst::isTrueWhenEqual(Pred);
11701 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
11702 if (FoundLHS == FoundRHS)
11703 return CmpInst::isFalseWhenEqual(FoundPred);
11704
11705 // Check to see if we can make the LHS or RHS match.
11706 if (LHS == FoundRHS || RHS == FoundLHS) {
11707 if (isa<SCEVConstant>(RHS)) {
11708 std::swap(FoundLHS, FoundRHS);
11709 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
11710 } else {
11711 std::swap(LHS, RHS);
11712 Pred = ICmpInst::getSwappedPredicate(Pred);
11713 }
11714 }
11715
11716 // Check whether the found predicate is the same as the desired predicate.
11717 if (FoundPred == Pred)
11718 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
11719
11720 // Check whether swapping the found predicate makes it the same as the
11721 // desired predicate.
11722 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
11723 // We can write the implication
11724 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS
11725 // using one of the following ways:
11726 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS
11727 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS
11728 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS
11729 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS
11730 // Forms 1. and 2. require swapping the operands of one condition. Don't
11731 // do this if it would break canonical constant/addrec ordering.
11732 if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS))
11733 return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS,
11734 CtxI);
11735 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
11736 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI);
11737
11738 // There's no clear preference between forms 3. and 4., try both. Avoid
11739 // forming getNotSCEV of pointer values as the resulting subtract is
11740 // not legal.
11741 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() &&
11742 isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS),
11743 FoundLHS, FoundRHS, CtxI))
11744 return true;
11745
11746 if (!FoundLHS->getType()->isPointerTy() &&
11747 !FoundRHS->getType()->isPointerTy() &&
11748 isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS),
11749 getNotSCEV(FoundRHS), CtxI))
11750 return true;
11751
11752 return false;
11753 }
11754
11755 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
11756 CmpInst::Predicate P2) {
11757 assert(P1 != P2 && "Handled earlier!");
11758 return CmpInst::isRelational(P2) &&
11759 P1 == CmpInst::getFlippedSignednessPredicate(P2);
11760 };
11761 if (IsSignFlippedPredicate(Pred, FoundPred)) {
11762 // Unsigned comparison is the same as signed comparison when both the
11763 // operands are non-negative or negative.
11764 if ((isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) ||
11765 (isKnownNegative(FoundLHS) && isKnownNegative(FoundRHS)))
11766 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
11767 // Create local copies that we can freely swap and canonicalize our
11768 // conditions to "le/lt".
11769 ICmpInst::Predicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
11770 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
11771 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
11772 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
11773 CanonicalPred = ICmpInst::getSwappedPredicate(CanonicalPred);
11774 CanonicalFoundPred = ICmpInst::getSwappedPredicate(CanonicalFoundPred);
11775 std::swap(CanonicalLHS, CanonicalRHS);
11776 std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
11777 }
11778 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
11779 "Must be!");
11780 assert((ICmpInst::isLT(CanonicalFoundPred) ||
11781 ICmpInst::isLE(CanonicalFoundPred)) &&
11782 "Must be!");
11783 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
11784 // Use implication:
11785 // x <u y && y >=s 0 --> x <s y.
11786 // If we can prove the left part, the right part is also proven.
11787 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
11788 CanonicalRHS, CanonicalFoundLHS,
11789 CanonicalFoundRHS);
11790 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
11791 // Use implication:
11792 // x <s y && y <s 0 --> x <u y.
11793 // If we can prove the left part, the right part is also proven.
11794 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
11795 CanonicalRHS, CanonicalFoundLHS,
11796 CanonicalFoundRHS);
11797 }
11798
11799 // Check if we can make progress by sharpening ranges.
11800 if (FoundPred == ICmpInst::ICMP_NE &&
11801 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
11802
11803 const SCEVConstant *C = nullptr;
11804 const SCEV *V = nullptr;
11805
11806 if (isa<SCEVConstant>(FoundLHS)) {
11807 C = cast<SCEVConstant>(FoundLHS);
11808 V = FoundRHS;
11809 } else {
11810 C = cast<SCEVConstant>(FoundRHS);
11811 V = FoundLHS;
11812 }
11813
11814 // The guarding predicate tells us that C != V. If the known range
11815 // of V is [C, t), we can sharpen the range to [C + 1, t). The
11816 // range we consider has to correspond to same signedness as the
11817 // predicate we're interested in folding.
11818
11819 APInt Min = ICmpInst::isSigned(Pred) ?
11820 getSignedRangeMin(V) : getUnsignedRangeMin(V);
11821
11822 if (Min == C->getAPInt()) {
11823 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
11824 // This is true even if (Min + 1) wraps around -- in case of
11825 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
11826
11827 APInt SharperMin = Min + 1;
11828
11829 switch (Pred) {
11830 case ICmpInst::ICMP_SGE:
11831 case ICmpInst::ICMP_UGE:
11832 // We know V `Pred` SharperMin. If this implies LHS `Pred`
11833 // RHS, we're done.
11834 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
11835 CtxI))
11836 return true;
11837 [[fallthrough]];
11838
11839 case ICmpInst::ICMP_SGT:
11840 case ICmpInst::ICMP_UGT:
11841 // We know from the range information that (V `Pred` Min ||
11842 // V == Min). We know from the guarding condition that !(V
11843 // == Min). This gives us
11844 //
11845 // V `Pred` Min || V == Min && !(V == Min)
11846 // => V `Pred` Min
11847 //
11848 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
11849
11850 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
11851 return true;
11852 break;
11853
11854 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
11855 case ICmpInst::ICMP_SLE:
11856 case ICmpInst::ICMP_ULE:
11857 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
11858 LHS, V, getConstant(SharperMin), CtxI))
11859 return true;
11860 [[fallthrough]];
11861
11862 case ICmpInst::ICMP_SLT:
11863 case ICmpInst::ICMP_ULT:
11864 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
11865 LHS, V, getConstant(Min), CtxI))
11866 return true;
11867 break;
11868
11869 default:
11870 // No change
11871 break;
11872 }
11873 }
11874 }
11875
11876 // Check whether the actual condition is beyond sufficient.
11877 if (FoundPred == ICmpInst::ICMP_EQ)
11878 if (ICmpInst::isTrueWhenEqual(Pred))
11879 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
11880 return true;
11881 if (Pred == ICmpInst::ICMP_NE)
11882 if (!ICmpInst::isTrueWhenEqual(FoundPred))
11883 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
11884 return true;
11885
11886 // Otherwise assume the worst.
11887 return false;
11888 }
11889
splitBinaryAdd(const SCEV * Expr,const SCEV * & L,const SCEV * & R,SCEV::NoWrapFlags & Flags)11890 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
11891 const SCEV *&L, const SCEV *&R,
11892 SCEV::NoWrapFlags &Flags) {
11893 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
11894 if (!AE || AE->getNumOperands() != 2)
11895 return false;
11896
11897 L = AE->getOperand(0);
11898 R = AE->getOperand(1);
11899 Flags = AE->getNoWrapFlags();
11900 return true;
11901 }
11902
11903 std::optional<APInt>
computeConstantDifference(const SCEV * More,const SCEV * Less)11904 ScalarEvolution::computeConstantDifference(const SCEV *More, const SCEV *Less) {
11905 // We avoid subtracting expressions here because this function is usually
11906 // fairly deep in the call stack (i.e. is called many times).
11907
11908 // X - X = 0.
11909 if (More == Less)
11910 return APInt(getTypeSizeInBits(More->getType()), 0);
11911
11912 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
11913 const auto *LAR = cast<SCEVAddRecExpr>(Less);
11914 const auto *MAR = cast<SCEVAddRecExpr>(More);
11915
11916 if (LAR->getLoop() != MAR->getLoop())
11917 return std::nullopt;
11918
11919 // We look at affine expressions only; not for correctness but to keep
11920 // getStepRecurrence cheap.
11921 if (!LAR->isAffine() || !MAR->isAffine())
11922 return std::nullopt;
11923
11924 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
11925 return std::nullopt;
11926
11927 Less = LAR->getStart();
11928 More = MAR->getStart();
11929
11930 // fall through
11931 }
11932
11933 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
11934 const auto &M = cast<SCEVConstant>(More)->getAPInt();
11935 const auto &L = cast<SCEVConstant>(Less)->getAPInt();
11936 return M - L;
11937 }
11938
11939 SCEV::NoWrapFlags Flags;
11940 const SCEV *LLess = nullptr, *RLess = nullptr;
11941 const SCEV *LMore = nullptr, *RMore = nullptr;
11942 const SCEVConstant *C1 = nullptr, *C2 = nullptr;
11943 // Compare (X + C1) vs X.
11944 if (splitBinaryAdd(Less, LLess, RLess, Flags))
11945 if ((C1 = dyn_cast<SCEVConstant>(LLess)))
11946 if (RLess == More)
11947 return -(C1->getAPInt());
11948
11949 // Compare X vs (X + C2).
11950 if (splitBinaryAdd(More, LMore, RMore, Flags))
11951 if ((C2 = dyn_cast<SCEVConstant>(LMore)))
11952 if (RMore == Less)
11953 return C2->getAPInt();
11954
11955 // Compare (X + C1) vs (X + C2).
11956 if (C1 && C2 && RLess == RMore)
11957 return C2->getAPInt() - C1->getAPInt();
11958
11959 return std::nullopt;
11960 }
11961
isImpliedCondOperandsViaAddRecStart(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const SCEV * FoundLHS,const SCEV * FoundRHS,const Instruction * CtxI)11962 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
11963 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11964 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *CtxI) {
11965 // Try to recognize the following pattern:
11966 //
11967 // FoundRHS = ...
11968 // ...
11969 // loop:
11970 // FoundLHS = {Start,+,W}
11971 // context_bb: // Basic block from the same loop
11972 // known(Pred, FoundLHS, FoundRHS)
11973 //
11974 // If some predicate is known in the context of a loop, it is also known on
11975 // each iteration of this loop, including the first iteration. Therefore, in
11976 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
11977 // prove the original pred using this fact.
11978 if (!CtxI)
11979 return false;
11980 const BasicBlock *ContextBB = CtxI->getParent();
11981 // Make sure AR varies in the context block.
11982 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
11983 const Loop *L = AR->getLoop();
11984 // Make sure that context belongs to the loop and executes on 1st iteration
11985 // (if it ever executes at all).
11986 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
11987 return false;
11988 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
11989 return false;
11990 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
11991 }
11992
11993 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
11994 const Loop *L = AR->getLoop();
11995 // Make sure that context belongs to the loop and executes on 1st iteration
11996 // (if it ever executes at all).
11997 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
11998 return false;
11999 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
12000 return false;
12001 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
12002 }
12003
12004 return false;
12005 }
12006
isImpliedCondOperandsViaNoOverflow(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const SCEV * FoundLHS,const SCEV * FoundRHS)12007 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
12008 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
12009 const SCEV *FoundLHS, const SCEV *FoundRHS) {
12010 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
12011 return false;
12012
12013 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
12014 if (!AddRecLHS)
12015 return false;
12016
12017 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12018 if (!AddRecFoundLHS)
12019 return false;
12020
12021 // We'd like to let SCEV reason about control dependencies, so we constrain
12022 // both the inequalities to be about add recurrences on the same loop. This
12023 // way we can use isLoopEntryGuardedByCond later.
12024
12025 const Loop *L = AddRecFoundLHS->getLoop();
12026 if (L != AddRecLHS->getLoop())
12027 return false;
12028
12029 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
12030 //
12031 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
12032 // ... (2)
12033 //
12034 // Informal proof for (2), assuming (1) [*]:
12035 //
12036 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
12037 //
12038 // Then
12039 //
12040 // FoundLHS s< FoundRHS s< INT_MIN - C
12041 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
12042 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
12043 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
12044 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
12045 // <=> FoundLHS + C s< FoundRHS + C
12046 //
12047 // [*]: (1) can be proved by ruling out overflow.
12048 //
12049 // [**]: This can be proved by analyzing all the four possibilities:
12050 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
12051 // (A s>= 0, B s>= 0).
12052 //
12053 // Note:
12054 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
12055 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
12056 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
12057 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
12058 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
12059 // C)".
12060
12061 std::optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
12062 std::optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
12063 if (!LDiff || !RDiff || *LDiff != *RDiff)
12064 return false;
12065
12066 if (LDiff->isMinValue())
12067 return true;
12068
12069 APInt FoundRHSLimit;
12070
12071 if (Pred == CmpInst::ICMP_ULT) {
12072 FoundRHSLimit = -(*RDiff);
12073 } else {
12074 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
12075 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
12076 }
12077
12078 // Try to prove (1) or (2), as needed.
12079 return isAvailableAtLoopEntry(FoundRHS, L) &&
12080 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
12081 getConstant(FoundRHSLimit));
12082 }
12083
isImpliedViaMerge(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const SCEV * FoundLHS,const SCEV * FoundRHS,unsigned Depth)12084 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
12085 const SCEV *LHS, const SCEV *RHS,
12086 const SCEV *FoundLHS,
12087 const SCEV *FoundRHS, unsigned Depth) {
12088 const PHINode *LPhi = nullptr, *RPhi = nullptr;
12089
12090 auto ClearOnExit = make_scope_exit([&]() {
12091 if (LPhi) {
12092 bool Erased = PendingMerges.erase(LPhi);
12093 assert(Erased && "Failed to erase LPhi!");
12094 (void)Erased;
12095 }
12096 if (RPhi) {
12097 bool Erased = PendingMerges.erase(RPhi);
12098 assert(Erased && "Failed to erase RPhi!");
12099 (void)Erased;
12100 }
12101 });
12102
12103 // Find respective Phis and check that they are not being pending.
12104 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
12105 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
12106 if (!PendingMerges.insert(Phi).second)
12107 return false;
12108 LPhi = Phi;
12109 }
12110 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
12111 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
12112 // If we detect a loop of Phi nodes being processed by this method, for
12113 // example:
12114 //
12115 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
12116 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
12117 //
12118 // we don't want to deal with a case that complex, so return conservative
12119 // answer false.
12120 if (!PendingMerges.insert(Phi).second)
12121 return false;
12122 RPhi = Phi;
12123 }
12124
12125 // If none of LHS, RHS is a Phi, nothing to do here.
12126 if (!LPhi && !RPhi)
12127 return false;
12128
12129 // If there is a SCEVUnknown Phi we are interested in, make it left.
12130 if (!LPhi) {
12131 std::swap(LHS, RHS);
12132 std::swap(FoundLHS, FoundRHS);
12133 std::swap(LPhi, RPhi);
12134 Pred = ICmpInst::getSwappedPredicate(Pred);
12135 }
12136
12137 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
12138 const BasicBlock *LBB = LPhi->getParent();
12139 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12140
12141 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
12142 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
12143 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
12144 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
12145 };
12146
12147 if (RPhi && RPhi->getParent() == LBB) {
12148 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
12149 // If we compare two Phis from the same block, and for each entry block
12150 // the predicate is true for incoming values from this block, then the
12151 // predicate is also true for the Phis.
12152 for (const BasicBlock *IncBB : predecessors(LBB)) {
12153 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12154 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
12155 if (!ProvedEasily(L, R))
12156 return false;
12157 }
12158 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
12159 // Case two: RHS is also a Phi from the same basic block, and it is an
12160 // AddRec. It means that there is a loop which has both AddRec and Unknown
12161 // PHIs, for it we can compare incoming values of AddRec from above the loop
12162 // and latch with their respective incoming values of LPhi.
12163 // TODO: Generalize to handle loops with many inputs in a header.
12164 if (LPhi->getNumIncomingValues() != 2) return false;
12165
12166 auto *RLoop = RAR->getLoop();
12167 auto *Predecessor = RLoop->getLoopPredecessor();
12168 assert(Predecessor && "Loop with AddRec with no predecessor?");
12169 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
12170 if (!ProvedEasily(L1, RAR->getStart()))
12171 return false;
12172 auto *Latch = RLoop->getLoopLatch();
12173 assert(Latch && "Loop with AddRec with no latch?");
12174 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
12175 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
12176 return false;
12177 } else {
12178 // In all other cases go over inputs of LHS and compare each of them to RHS,
12179 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
12180 // At this point RHS is either a non-Phi, or it is a Phi from some block
12181 // different from LBB.
12182 for (const BasicBlock *IncBB : predecessors(LBB)) {
12183 // Check that RHS is available in this block.
12184 if (!dominates(RHS, IncBB))
12185 return false;
12186 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12187 // Make sure L does not refer to a value from a potentially previous
12188 // iteration of a loop.
12189 if (!properlyDominates(L, LBB))
12190 return false;
12191 if (!ProvedEasily(L, RHS))
12192 return false;
12193 }
12194 }
12195 return true;
12196 }
12197
isImpliedCondOperandsViaShift(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const SCEV * FoundLHS,const SCEV * FoundRHS)12198 bool ScalarEvolution::isImpliedCondOperandsViaShift(ICmpInst::Predicate Pred,
12199 const SCEV *LHS,
12200 const SCEV *RHS,
12201 const SCEV *FoundLHS,
12202 const SCEV *FoundRHS) {
12203 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make
12204 // sure that we are dealing with same LHS.
12205 if (RHS == FoundRHS) {
12206 std::swap(LHS, RHS);
12207 std::swap(FoundLHS, FoundRHS);
12208 Pred = ICmpInst::getSwappedPredicate(Pred);
12209 }
12210 if (LHS != FoundLHS)
12211 return false;
12212
12213 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
12214 if (!SUFoundRHS)
12215 return false;
12216
12217 Value *Shiftee, *ShiftValue;
12218
12219 using namespace PatternMatch;
12220 if (match(SUFoundRHS->getValue(),
12221 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
12222 auto *ShifteeS = getSCEV(Shiftee);
12223 // Prove one of the following:
12224 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
12225 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
12226 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12227 // ---> LHS <s RHS
12228 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12229 // ---> LHS <=s RHS
12230 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
12231 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
12232 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
12233 if (isKnownNonNegative(ShifteeS))
12234 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
12235 }
12236
12237 return false;
12238 }
12239
isImpliedCondOperands(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const SCEV * FoundLHS,const SCEV * FoundRHS,const Instruction * CtxI)12240 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
12241 const SCEV *LHS, const SCEV *RHS,
12242 const SCEV *FoundLHS,
12243 const SCEV *FoundRHS,
12244 const Instruction *CtxI) {
12245 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
12246 return true;
12247
12248 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
12249 return true;
12250
12251 if (isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS))
12252 return true;
12253
12254 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12255 CtxI))
12256 return true;
12257
12258 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
12259 FoundLHS, FoundRHS);
12260 }
12261
12262 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
12263 template <typename MinMaxExprType>
IsMinMaxConsistingOf(const SCEV * MaybeMinMaxExpr,const SCEV * Candidate)12264 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
12265 const SCEV *Candidate) {
12266 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12267 if (!MinMaxExpr)
12268 return false;
12269
12270 return is_contained(MinMaxExpr->operands(), Candidate);
12271 }
12272
IsKnownPredicateViaAddRecStart(ScalarEvolution & SE,ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)12273 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
12274 ICmpInst::Predicate Pred,
12275 const SCEV *LHS, const SCEV *RHS) {
12276 // If both sides are affine addrecs for the same loop, with equal
12277 // steps, and we know the recurrences don't wrap, then we only
12278 // need to check the predicate on the starting values.
12279
12280 if (!ICmpInst::isRelational(Pred))
12281 return false;
12282
12283 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
12284 if (!LAR)
12285 return false;
12286 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12287 if (!RAR)
12288 return false;
12289 if (LAR->getLoop() != RAR->getLoop())
12290 return false;
12291 if (!LAR->isAffine() || !RAR->isAffine())
12292 return false;
12293
12294 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
12295 return false;
12296
12297 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
12298 SCEV::FlagNSW : SCEV::FlagNUW;
12299 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
12300 return false;
12301
12302 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
12303 }
12304
12305 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
12306 /// expression?
IsKnownPredicateViaMinOrMax(ScalarEvolution & SE,ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)12307 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
12308 ICmpInst::Predicate Pred,
12309 const SCEV *LHS, const SCEV *RHS) {
12310 switch (Pred) {
12311 default:
12312 return false;
12313
12314 case ICmpInst::ICMP_SGE:
12315 std::swap(LHS, RHS);
12316 [[fallthrough]];
12317 case ICmpInst::ICMP_SLE:
12318 return
12319 // min(A, ...) <= A
12320 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
12321 // A <= max(A, ...)
12322 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
12323
12324 case ICmpInst::ICMP_UGE:
12325 std::swap(LHS, RHS);
12326 [[fallthrough]];
12327 case ICmpInst::ICMP_ULE:
12328 return
12329 // min(A, ...) <= A
12330 // FIXME: what about umin_seq?
12331 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
12332 // A <= max(A, ...)
12333 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
12334 }
12335
12336 llvm_unreachable("covered switch fell through?!");
12337 }
12338
isImpliedViaOperations(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const SCEV * FoundLHS,const SCEV * FoundRHS,unsigned Depth)12339 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
12340 const SCEV *LHS, const SCEV *RHS,
12341 const SCEV *FoundLHS,
12342 const SCEV *FoundRHS,
12343 unsigned Depth) {
12344 assert(getTypeSizeInBits(LHS->getType()) ==
12345 getTypeSizeInBits(RHS->getType()) &&
12346 "LHS and RHS have different sizes?");
12347 assert(getTypeSizeInBits(FoundLHS->getType()) ==
12348 getTypeSizeInBits(FoundRHS->getType()) &&
12349 "FoundLHS and FoundRHS have different sizes?");
12350 // We want to avoid hurting the compile time with analysis of too big trees.
12351 if (Depth > MaxSCEVOperationsImplicationDepth)
12352 return false;
12353
12354 // We only want to work with GT comparison so far.
12355 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
12356 Pred = CmpInst::getSwappedPredicate(Pred);
12357 std::swap(LHS, RHS);
12358 std::swap(FoundLHS, FoundRHS);
12359 }
12360
12361 // For unsigned, try to reduce it to corresponding signed comparison.
12362 if (Pred == ICmpInst::ICMP_UGT)
12363 // We can replace unsigned predicate with its signed counterpart if all
12364 // involved values are non-negative.
12365 // TODO: We could have better support for unsigned.
12366 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
12367 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
12368 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
12369 // use this fact to prove that LHS and RHS are non-negative.
12370 const SCEV *MinusOne = getMinusOne(LHS->getType());
12371 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
12372 FoundRHS) &&
12373 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
12374 FoundRHS))
12375 Pred = ICmpInst::ICMP_SGT;
12376 }
12377
12378 if (Pred != ICmpInst::ICMP_SGT)
12379 return false;
12380
12381 auto GetOpFromSExt = [&](const SCEV *S) {
12382 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
12383 return Ext->getOperand();
12384 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
12385 // the constant in some cases.
12386 return S;
12387 };
12388
12389 // Acquire values from extensions.
12390 auto *OrigLHS = LHS;
12391 auto *OrigFoundLHS = FoundLHS;
12392 LHS = GetOpFromSExt(LHS);
12393 FoundLHS = GetOpFromSExt(FoundLHS);
12394
12395 // Is the SGT predicate can be proved trivially or using the found context.
12396 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
12397 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
12398 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
12399 FoundRHS, Depth + 1);
12400 };
12401
12402 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
12403 // We want to avoid creation of any new non-constant SCEV. Since we are
12404 // going to compare the operands to RHS, we should be certain that we don't
12405 // need any size extensions for this. So let's decline all cases when the
12406 // sizes of types of LHS and RHS do not match.
12407 // TODO: Maybe try to get RHS from sext to catch more cases?
12408 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
12409 return false;
12410
12411 // Should not overflow.
12412 if (!LHSAddExpr->hasNoSignedWrap())
12413 return false;
12414
12415 auto *LL = LHSAddExpr->getOperand(0);
12416 auto *LR = LHSAddExpr->getOperand(1);
12417 auto *MinusOne = getMinusOne(RHS->getType());
12418
12419 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
12420 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
12421 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
12422 };
12423 // Try to prove the following rule:
12424 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
12425 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
12426 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
12427 return true;
12428 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
12429 Value *LL, *LR;
12430 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
12431
12432 using namespace llvm::PatternMatch;
12433
12434 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
12435 // Rules for division.
12436 // We are going to perform some comparisons with Denominator and its
12437 // derivative expressions. In general case, creating a SCEV for it may
12438 // lead to a complex analysis of the entire graph, and in particular it
12439 // can request trip count recalculation for the same loop. This would
12440 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
12441 // this, we only want to create SCEVs that are constants in this section.
12442 // So we bail if Denominator is not a constant.
12443 if (!isa<ConstantInt>(LR))
12444 return false;
12445
12446 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
12447
12448 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
12449 // then a SCEV for the numerator already exists and matches with FoundLHS.
12450 auto *Numerator = getExistingSCEV(LL);
12451 if (!Numerator || Numerator->getType() != FoundLHS->getType())
12452 return false;
12453
12454 // Make sure that the numerator matches with FoundLHS and the denominator
12455 // is positive.
12456 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
12457 return false;
12458
12459 auto *DTy = Denominator->getType();
12460 auto *FRHSTy = FoundRHS->getType();
12461 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
12462 // One of types is a pointer and another one is not. We cannot extend
12463 // them properly to a wider type, so let us just reject this case.
12464 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
12465 // to avoid this check.
12466 return false;
12467
12468 // Given that:
12469 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
12470 auto *WTy = getWiderType(DTy, FRHSTy);
12471 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
12472 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
12473
12474 // Try to prove the following rule:
12475 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
12476 // For example, given that FoundLHS > 2. It means that FoundLHS is at
12477 // least 3. If we divide it by Denominator < 4, we will have at least 1.
12478 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
12479 if (isKnownNonPositive(RHS) &&
12480 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
12481 return true;
12482
12483 // Try to prove the following rule:
12484 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
12485 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
12486 // If we divide it by Denominator > 2, then:
12487 // 1. If FoundLHS is negative, then the result is 0.
12488 // 2. If FoundLHS is non-negative, then the result is non-negative.
12489 // Anyways, the result is non-negative.
12490 auto *MinusOne = getMinusOne(WTy);
12491 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
12492 if (isKnownNegative(RHS) &&
12493 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
12494 return true;
12495 }
12496 }
12497
12498 // If our expression contained SCEVUnknown Phis, and we split it down and now
12499 // need to prove something for them, try to prove the predicate for every
12500 // possible incoming values of those Phis.
12501 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
12502 return true;
12503
12504 return false;
12505 }
12506
isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)12507 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
12508 const SCEV *LHS, const SCEV *RHS) {
12509 // zext x u<= sext x, sext x s<= zext x
12510 switch (Pred) {
12511 case ICmpInst::ICMP_SGE:
12512 std::swap(LHS, RHS);
12513 [[fallthrough]];
12514 case ICmpInst::ICMP_SLE: {
12515 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt.
12516 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
12517 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
12518 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
12519 return true;
12520 break;
12521 }
12522 case ICmpInst::ICMP_UGE:
12523 std::swap(LHS, RHS);
12524 [[fallthrough]];
12525 case ICmpInst::ICMP_ULE: {
12526 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt.
12527 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
12528 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
12529 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
12530 return true;
12531 break;
12532 }
12533 default:
12534 break;
12535 };
12536 return false;
12537 }
12538
12539 bool
isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)12540 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
12541 const SCEV *LHS, const SCEV *RHS) {
12542 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
12543 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
12544 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
12545 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
12546 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
12547 }
12548
12549 bool
isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const SCEV * FoundLHS,const SCEV * FoundRHS)12550 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
12551 const SCEV *LHS, const SCEV *RHS,
12552 const SCEV *FoundLHS,
12553 const SCEV *FoundRHS) {
12554 switch (Pred) {
12555 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
12556 case ICmpInst::ICMP_EQ:
12557 case ICmpInst::ICMP_NE:
12558 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
12559 return true;
12560 break;
12561 case ICmpInst::ICMP_SLT:
12562 case ICmpInst::ICMP_SLE:
12563 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
12564 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
12565 return true;
12566 break;
12567 case ICmpInst::ICMP_SGT:
12568 case ICmpInst::ICMP_SGE:
12569 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
12570 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
12571 return true;
12572 break;
12573 case ICmpInst::ICMP_ULT:
12574 case ICmpInst::ICMP_ULE:
12575 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
12576 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
12577 return true;
12578 break;
12579 case ICmpInst::ICMP_UGT:
12580 case ICmpInst::ICMP_UGE:
12581 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
12582 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
12583 return true;
12584 break;
12585 }
12586
12587 // Maybe it can be proved via operations?
12588 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
12589 return true;
12590
12591 return false;
12592 }
12593
isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const SCEV * FoundLHS,const SCEV * FoundRHS)12594 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
12595 const SCEV *LHS,
12596 const SCEV *RHS,
12597 const SCEV *FoundLHS,
12598 const SCEV *FoundRHS) {
12599 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
12600 // The restriction on `FoundRHS` be lifted easily -- it exists only to
12601 // reduce the compile time impact of this optimization.
12602 return false;
12603
12604 std::optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
12605 if (!Addend)
12606 return false;
12607
12608 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
12609
12610 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
12611 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
12612 ConstantRange FoundLHSRange =
12613 ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS);
12614
12615 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
12616 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
12617
12618 // We can also compute the range of values for `LHS` that satisfy the
12619 // consequent, "`LHS` `Pred` `RHS`":
12620 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
12621 // The antecedent implies the consequent if every value of `LHS` that
12622 // satisfies the antecedent also satisfies the consequent.
12623 return LHSRange.icmp(Pred, ConstRHS);
12624 }
12625
canIVOverflowOnLT(const SCEV * RHS,const SCEV * Stride,bool IsSigned)12626 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
12627 bool IsSigned) {
12628 assert(isKnownPositive(Stride) && "Positive stride expected!");
12629
12630 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
12631 const SCEV *One = getOne(Stride->getType());
12632
12633 if (IsSigned) {
12634 APInt MaxRHS = getSignedRangeMax(RHS);
12635 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
12636 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
12637
12638 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
12639 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
12640 }
12641
12642 APInt MaxRHS = getUnsignedRangeMax(RHS);
12643 APInt MaxValue = APInt::getMaxValue(BitWidth);
12644 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
12645
12646 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
12647 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
12648 }
12649
canIVOverflowOnGT(const SCEV * RHS,const SCEV * Stride,bool IsSigned)12650 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
12651 bool IsSigned) {
12652
12653 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
12654 const SCEV *One = getOne(Stride->getType());
12655
12656 if (IsSigned) {
12657 APInt MinRHS = getSignedRangeMin(RHS);
12658 APInt MinValue = APInt::getSignedMinValue(BitWidth);
12659 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
12660
12661 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
12662 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
12663 }
12664
12665 APInt MinRHS = getUnsignedRangeMin(RHS);
12666 APInt MinValue = APInt::getMinValue(BitWidth);
12667 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
12668
12669 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
12670 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
12671 }
12672
getUDivCeilSCEV(const SCEV * N,const SCEV * D)12673 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) {
12674 // umin(N, 1) + floor((N - umin(N, 1)) / D)
12675 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
12676 // expression fixes the case of N=0.
12677 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
12678 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
12679 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
12680 }
12681
computeMaxBECountForLT(const SCEV * Start,const SCEV * Stride,const SCEV * End,unsigned BitWidth,bool IsSigned)12682 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
12683 const SCEV *Stride,
12684 const SCEV *End,
12685 unsigned BitWidth,
12686 bool IsSigned) {
12687 // The logic in this function assumes we can represent a positive stride.
12688 // If we can't, the backedge-taken count must be zero.
12689 if (IsSigned && BitWidth == 1)
12690 return getZero(Stride->getType());
12691
12692 // This code below only been closely audited for negative strides in the
12693 // unsigned comparison case, it may be correct for signed comparison, but
12694 // that needs to be established.
12695 if (IsSigned && isKnownNegative(Stride))
12696 return getCouldNotCompute();
12697
12698 // Calculate the maximum backedge count based on the range of values
12699 // permitted by Start, End, and Stride.
12700 APInt MinStart =
12701 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
12702
12703 APInt MinStride =
12704 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
12705
12706 // We assume either the stride is positive, or the backedge-taken count
12707 // is zero. So force StrideForMaxBECount to be at least one.
12708 APInt One(BitWidth, 1);
12709 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
12710 : APIntOps::umax(One, MinStride);
12711
12712 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
12713 : APInt::getMaxValue(BitWidth);
12714 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
12715
12716 // Although End can be a MAX expression we estimate MaxEnd considering only
12717 // the case End = RHS of the loop termination condition. This is safe because
12718 // in the other case (End - Start) is zero, leading to a zero maximum backedge
12719 // taken count.
12720 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
12721 : APIntOps::umin(getUnsignedRangeMax(End), Limit);
12722
12723 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
12724 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
12725 : APIntOps::umax(MaxEnd, MinStart);
12726
12727 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */,
12728 getConstant(StrideForMaxBECount) /* Step */);
12729 }
12730
12731 ScalarEvolution::ExitLimit
howManyLessThans(const SCEV * LHS,const SCEV * RHS,const Loop * L,bool IsSigned,bool ControlsExit,bool AllowPredicates)12732 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
12733 const Loop *L, bool IsSigned,
12734 bool ControlsExit, bool AllowPredicates) {
12735 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
12736
12737 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
12738 bool PredicatedIV = false;
12739
12740 auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) {
12741 // Can we prove this loop *must* be UB if overflow of IV occurs?
12742 // Reasoning goes as follows:
12743 // * Suppose the IV did self wrap.
12744 // * If Stride evenly divides the iteration space, then once wrap
12745 // occurs, the loop must revisit the same values.
12746 // * We know that RHS is invariant, and that none of those values
12747 // caused this exit to be taken previously. Thus, this exit is
12748 // dynamically dead.
12749 // * If this is the sole exit, then a dead exit implies the loop
12750 // must be infinite if there are no abnormal exits.
12751 // * If the loop were infinite, then it must either not be mustprogress
12752 // or have side effects. Otherwise, it must be UB.
12753 // * It can't (by assumption), be UB so we have contradicted our
12754 // premise and can conclude the IV did not in fact self-wrap.
12755 if (!isLoopInvariant(RHS, L))
12756 return false;
12757
12758 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
12759 if (!StrideC || !StrideC->getAPInt().isPowerOf2())
12760 return false;
12761
12762 if (!ControlsExit || !loopHasNoAbnormalExits(L))
12763 return false;
12764
12765 return loopIsFiniteByAssumption(L);
12766 };
12767
12768 if (!IV) {
12769 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
12770 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
12771 if (AR && AR->getLoop() == L && AR->isAffine()) {
12772 auto canProveNUW = [&]() {
12773 if (!isLoopInvariant(RHS, L))
12774 return false;
12775
12776 if (!isKnownNonZero(AR->getStepRecurrence(*this)))
12777 // We need the sequence defined by AR to strictly increase in the
12778 // unsigned integer domain for the logic below to hold.
12779 return false;
12780
12781 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
12782 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
12783 // If RHS <=u Limit, then there must exist a value V in the sequence
12784 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
12785 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned
12786 // overflow occurs. This limit also implies that a signed comparison
12787 // (in the wide bitwidth) is equivalent to an unsigned comparison as
12788 // the high bits on both sides must be zero.
12789 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
12790 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
12791 Limit = Limit.zext(OuterBitWidth);
12792 return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit);
12793 };
12794 auto Flags = AR->getNoWrapFlags();
12795 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
12796 Flags = setFlags(Flags, SCEV::FlagNUW);
12797
12798 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
12799 if (AR->hasNoUnsignedWrap()) {
12800 // Emulate what getZeroExtendExpr would have done during construction
12801 // if we'd been able to infer the fact just above at that time.
12802 const SCEV *Step = AR->getStepRecurrence(*this);
12803 Type *Ty = ZExt->getType();
12804 auto *S = getAddRecExpr(
12805 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0),
12806 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
12807 IV = dyn_cast<SCEVAddRecExpr>(S);
12808 }
12809 }
12810 }
12811 }
12812
12813
12814 if (!IV && AllowPredicates) {
12815 // Try to make this an AddRec using runtime tests, in the first X
12816 // iterations of this loop, where X is the SCEV expression found by the
12817 // algorithm below.
12818 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
12819 PredicatedIV = true;
12820 }
12821
12822 // Avoid weird loops
12823 if (!IV || IV->getLoop() != L || !IV->isAffine())
12824 return getCouldNotCompute();
12825
12826 // A precondition of this method is that the condition being analyzed
12827 // reaches an exiting branch which dominates the latch. Given that, we can
12828 // assume that an increment which violates the nowrap specification and
12829 // produces poison must cause undefined behavior when the resulting poison
12830 // value is branched upon and thus we can conclude that the backedge is
12831 // taken no more often than would be required to produce that poison value.
12832 // Note that a well defined loop can exit on the iteration which violates
12833 // the nowrap specification if there is another exit (either explicit or
12834 // implicit/exceptional) which causes the loop to execute before the
12835 // exiting instruction we're analyzing would trigger UB.
12836 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
12837 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
12838 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
12839
12840 const SCEV *Stride = IV->getStepRecurrence(*this);
12841
12842 bool PositiveStride = isKnownPositive(Stride);
12843
12844 // Avoid negative or zero stride values.
12845 if (!PositiveStride) {
12846 // We can compute the correct backedge taken count for loops with unknown
12847 // strides if we can prove that the loop is not an infinite loop with side
12848 // effects. Here's the loop structure we are trying to handle -
12849 //
12850 // i = start
12851 // do {
12852 // A[i] = i;
12853 // i += s;
12854 // } while (i < end);
12855 //
12856 // The backedge taken count for such loops is evaluated as -
12857 // (max(end, start + stride) - start - 1) /u stride
12858 //
12859 // The additional preconditions that we need to check to prove correctness
12860 // of the above formula is as follows -
12861 //
12862 // a) IV is either nuw or nsw depending upon signedness (indicated by the
12863 // NoWrap flag).
12864 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
12865 // no side effects within the loop)
12866 // c) loop has a single static exit (with no abnormal exits)
12867 //
12868 // Precondition a) implies that if the stride is negative, this is a single
12869 // trip loop. The backedge taken count formula reduces to zero in this case.
12870 //
12871 // Precondition b) and c) combine to imply that if rhs is invariant in L,
12872 // then a zero stride means the backedge can't be taken without executing
12873 // undefined behavior.
12874 //
12875 // The positive stride case is the same as isKnownPositive(Stride) returning
12876 // true (original behavior of the function).
12877 //
12878 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
12879 !loopHasNoAbnormalExits(L))
12880 return getCouldNotCompute();
12881
12882 if (!isKnownNonZero(Stride)) {
12883 // If we have a step of zero, and RHS isn't invariant in L, we don't know
12884 // if it might eventually be greater than start and if so, on which
12885 // iteration. We can't even produce a useful upper bound.
12886 if (!isLoopInvariant(RHS, L))
12887 return getCouldNotCompute();
12888
12889 // We allow a potentially zero stride, but we need to divide by stride
12890 // below. Since the loop can't be infinite and this check must control
12891 // the sole exit, we can infer the exit must be taken on the first
12892 // iteration (e.g. backedge count = 0) if the stride is zero. Given that,
12893 // we know the numerator in the divides below must be zero, so we can
12894 // pick an arbitrary non-zero value for the denominator (e.g. stride)
12895 // and produce the right result.
12896 // FIXME: Handle the case where Stride is poison?
12897 auto wouldZeroStrideBeUB = [&]() {
12898 // Proof by contradiction. Suppose the stride were zero. If we can
12899 // prove that the backedge *is* taken on the first iteration, then since
12900 // we know this condition controls the sole exit, we must have an
12901 // infinite loop. We can't have a (well defined) infinite loop per
12902 // check just above.
12903 // Note: The (Start - Stride) term is used to get the start' term from
12904 // (start' + stride,+,stride). Remember that we only care about the
12905 // result of this expression when stride == 0 at runtime.
12906 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
12907 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
12908 };
12909 if (!wouldZeroStrideBeUB()) {
12910 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
12911 }
12912 }
12913 } else if (!Stride->isOne() && !NoWrap) {
12914 auto isUBOnWrap = [&]() {
12915 // From no-self-wrap, we need to then prove no-(un)signed-wrap. This
12916 // follows trivially from the fact that every (un)signed-wrapped, but
12917 // not self-wrapped value must be LT than the last value before
12918 // (un)signed wrap. Since we know that last value didn't exit, nor
12919 // will any smaller one.
12920 return canAssumeNoSelfWrap(IV);
12921 };
12922
12923 // Avoid proven overflow cases: this will ensure that the backedge taken
12924 // count will not generate any unsigned overflow. Relaxed no-overflow
12925 // conditions exploit NoWrapFlags, allowing to optimize in presence of
12926 // undefined behaviors like the case of C language.
12927 if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap())
12928 return getCouldNotCompute();
12929 }
12930
12931 // On all paths just preceeding, we established the following invariant:
12932 // IV can be assumed not to overflow up to and including the exiting
12933 // iteration. We proved this in one of two ways:
12934 // 1) We can show overflow doesn't occur before the exiting iteration
12935 // 1a) canIVOverflowOnLT, and b) step of one
12936 // 2) We can show that if overflow occurs, the loop must execute UB
12937 // before any possible exit.
12938 // Note that we have not yet proved RHS invariant (in general).
12939
12940 const SCEV *Start = IV->getStart();
12941
12942 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
12943 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
12944 // Use integer-typed versions for actual computation; we can't subtract
12945 // pointers in general.
12946 const SCEV *OrigStart = Start;
12947 const SCEV *OrigRHS = RHS;
12948 if (Start->getType()->isPointerTy()) {
12949 Start = getLosslessPtrToIntExpr(Start);
12950 if (isa<SCEVCouldNotCompute>(Start))
12951 return Start;
12952 }
12953 if (RHS->getType()->isPointerTy()) {
12954 RHS = getLosslessPtrToIntExpr(RHS);
12955 if (isa<SCEVCouldNotCompute>(RHS))
12956 return RHS;
12957 }
12958
12959 // When the RHS is not invariant, we do not know the end bound of the loop and
12960 // cannot calculate the ExactBECount needed by ExitLimit. However, we can
12961 // calculate the MaxBECount, given the start, stride and max value for the end
12962 // bound of the loop (RHS), and the fact that IV does not overflow (which is
12963 // checked above).
12964 if (!isLoopInvariant(RHS, L)) {
12965 const SCEV *MaxBECount = computeMaxBECountForLT(
12966 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
12967 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
12968 MaxBECount, false /*MaxOrZero*/, Predicates);
12969 }
12970
12971 // We use the expression (max(End,Start)-Start)/Stride to describe the
12972 // backedge count, as if the backedge is taken at least once max(End,Start)
12973 // is End and so the result is as above, and if not max(End,Start) is Start
12974 // so we get a backedge count of zero.
12975 const SCEV *BECount = nullptr;
12976 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
12977 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!");
12978 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
12979 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
12980 // Can we prove (max(RHS,Start) > Start - Stride?
12981 if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) &&
12982 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
12983 // In this case, we can use a refined formula for computing backedge taken
12984 // count. The general formula remains:
12985 // "End-Start /uceiling Stride" where "End = max(RHS,Start)"
12986 // We want to use the alternate formula:
12987 // "((End - 1) - (Start - Stride)) /u Stride"
12988 // Let's do a quick case analysis to show these are equivalent under
12989 // our precondition that max(RHS,Start) > Start - Stride.
12990 // * For RHS <= Start, the backedge-taken count must be zero.
12991 // "((End - 1) - (Start - Stride)) /u Stride" reduces to
12992 // "((Start - 1) - (Start - Stride)) /u Stride" which simplies to
12993 // "Stride - 1 /u Stride" which is indeed zero for all non-zero values
12994 // of Stride. For 0 stride, we've use umin(1,Stride) above, reducing
12995 // this to the stride of 1 case.
12996 // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride".
12997 // "((End - 1) - (Start - Stride)) /u Stride" reduces to
12998 // "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to
12999 // "((RHS - (Start - Stride) - 1) /u Stride".
13000 // Our preconditions trivially imply no overflow in that form.
13001 const SCEV *MinusOne = getMinusOne(Stride->getType());
13002 const SCEV *Numerator =
13003 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
13004 BECount = getUDivExpr(Numerator, Stride);
13005 }
13006
13007 const SCEV *BECountIfBackedgeTaken = nullptr;
13008 if (!BECount) {
13009 auto canProveRHSGreaterThanEqualStart = [&]() {
13010 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
13011 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart))
13012 return true;
13013
13014 // (RHS > Start - 1) implies RHS >= Start.
13015 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
13016 // "Start - 1" doesn't overflow.
13017 // * For signed comparison, if Start - 1 does overflow, it's equal
13018 // to INT_MAX, and "RHS >s INT_MAX" is trivially false.
13019 // * For unsigned comparison, if Start - 1 does overflow, it's equal
13020 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
13021 //
13022 // FIXME: Should isLoopEntryGuardedByCond do this for us?
13023 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13024 auto *StartMinusOne = getAddExpr(OrigStart,
13025 getMinusOne(OrigStart->getType()));
13026 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
13027 };
13028
13029 // If we know that RHS >= Start in the context of loop, then we know that
13030 // max(RHS, Start) = RHS at this point.
13031 const SCEV *End;
13032 if (canProveRHSGreaterThanEqualStart()) {
13033 End = RHS;
13034 } else {
13035 // If RHS < Start, the backedge will be taken zero times. So in
13036 // general, we can write the backedge-taken count as:
13037 //
13038 // RHS >= Start ? ceil(RHS - Start) / Stride : 0
13039 //
13040 // We convert it to the following to make it more convenient for SCEV:
13041 //
13042 // ceil(max(RHS, Start) - Start) / Stride
13043 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
13044
13045 // See what would happen if we assume the backedge is taken. This is
13046 // used to compute MaxBECount.
13047 BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
13048 }
13049
13050 // At this point, we know:
13051 //
13052 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
13053 // 2. The index variable doesn't overflow.
13054 //
13055 // Therefore, we know N exists such that
13056 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
13057 // doesn't overflow.
13058 //
13059 // Using this information, try to prove whether the addition in
13060 // "(Start - End) + (Stride - 1)" has unsigned overflow.
13061 const SCEV *One = getOne(Stride->getType());
13062 bool MayAddOverflow = [&] {
13063 if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) {
13064 if (StrideC->getAPInt().isPowerOf2()) {
13065 // Suppose Stride is a power of two, and Start/End are unsigned
13066 // integers. Let UMAX be the largest representable unsigned
13067 // integer.
13068 //
13069 // By the preconditions of this function, we know
13070 // "(Start + Stride * N) >= End", and this doesn't overflow.
13071 // As a formula:
13072 //
13073 // End <= (Start + Stride * N) <= UMAX
13074 //
13075 // Subtracting Start from all the terms:
13076 //
13077 // End - Start <= Stride * N <= UMAX - Start
13078 //
13079 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore:
13080 //
13081 // End - Start <= Stride * N <= UMAX
13082 //
13083 // Stride * N is a multiple of Stride. Therefore,
13084 //
13085 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
13086 //
13087 // Since Stride is a power of two, UMAX + 1 is divisible by Stride.
13088 // Therefore, UMAX mod Stride == Stride - 1. So we can write:
13089 //
13090 // End - Start <= Stride * N <= UMAX - Stride - 1
13091 //
13092 // Dropping the middle term:
13093 //
13094 // End - Start <= UMAX - Stride - 1
13095 //
13096 // Adding Stride - 1 to both sides:
13097 //
13098 // (End - Start) + (Stride - 1) <= UMAX
13099 //
13100 // In other words, the addition doesn't have unsigned overflow.
13101 //
13102 // A similar proof works if we treat Start/End as signed values.
13103 // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to
13104 // use signed max instead of unsigned max. Note that we're trying
13105 // to prove a lack of unsigned overflow in either case.
13106 return false;
13107 }
13108 }
13109 if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
13110 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1.
13111 // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End.
13112 // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End.
13113 //
13114 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End.
13115 return false;
13116 }
13117 return true;
13118 }();
13119
13120 const SCEV *Delta = getMinusSCEV(End, Start);
13121 if (!MayAddOverflow) {
13122 // floor((D + (S - 1)) / S)
13123 // We prefer this formulation if it's legal because it's fewer operations.
13124 BECount =
13125 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13126 } else {
13127 BECount = getUDivCeilSCEV(Delta, Stride);
13128 }
13129 }
13130
13131 const SCEV *ConstantMaxBECount;
13132 bool MaxOrZero = false;
13133 if (isa<SCEVConstant>(BECount)) {
13134 ConstantMaxBECount = BECount;
13135 } else if (BECountIfBackedgeTaken &&
13136 isa<SCEVConstant>(BECountIfBackedgeTaken)) {
13137 // If we know exactly how many times the backedge will be taken if it's
13138 // taken at least once, then the backedge count will either be that or
13139 // zero.
13140 ConstantMaxBECount = BECountIfBackedgeTaken;
13141 MaxOrZero = true;
13142 } else {
13143 ConstantMaxBECount = computeMaxBECountForLT(
13144 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
13145 }
13146
13147 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
13148 !isa<SCEVCouldNotCompute>(BECount))
13149 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
13150
13151 const SCEV *SymbolicMaxBECount =
13152 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13153 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
13154 Predicates);
13155 }
13156
13157 ScalarEvolution::ExitLimit
howManyGreaterThans(const SCEV * LHS,const SCEV * RHS,const Loop * L,bool IsSigned,bool ControlsExit,bool AllowPredicates)13158 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
13159 const Loop *L, bool IsSigned,
13160 bool ControlsExit, bool AllowPredicates) {
13161 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
13162 // We handle only IV > Invariant
13163 if (!isLoopInvariant(RHS, L))
13164 return getCouldNotCompute();
13165
13166 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
13167 if (!IV && AllowPredicates)
13168 // Try to make this an AddRec using runtime tests, in the first X
13169 // iterations of this loop, where X is the SCEV expression found by the
13170 // algorithm below.
13171 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13172
13173 // Avoid weird loops
13174 if (!IV || IV->getLoop() != L || !IV->isAffine())
13175 return getCouldNotCompute();
13176
13177 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13178 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
13179 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13180
13181 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
13182
13183 // Avoid negative or zero stride values
13184 if (!isKnownPositive(Stride))
13185 return getCouldNotCompute();
13186
13187 // Avoid proven overflow cases: this will ensure that the backedge taken count
13188 // will not generate any unsigned overflow. Relaxed no-overflow conditions
13189 // exploit NoWrapFlags, allowing to optimize in presence of undefined
13190 // behaviors like the case of C language.
13191 if (!Stride->isOne() && !NoWrap)
13192 if (canIVOverflowOnGT(RHS, Stride, IsSigned))
13193 return getCouldNotCompute();
13194
13195 const SCEV *Start = IV->getStart();
13196 const SCEV *End = RHS;
13197 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
13198 // If we know that Start >= RHS in the context of loop, then we know that
13199 // min(RHS, Start) = RHS at this point.
13200 if (isLoopEntryGuardedByCond(
13201 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
13202 End = RHS;
13203 else
13204 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
13205 }
13206
13207 if (Start->getType()->isPointerTy()) {
13208 Start = getLosslessPtrToIntExpr(Start);
13209 if (isa<SCEVCouldNotCompute>(Start))
13210 return Start;
13211 }
13212 if (End->getType()->isPointerTy()) {
13213 End = getLosslessPtrToIntExpr(End);
13214 if (isa<SCEVCouldNotCompute>(End))
13215 return End;
13216 }
13217
13218 // Compute ((Start - End) + (Stride - 1)) / Stride.
13219 // FIXME: This can overflow. Holding off on fixing this for now;
13220 // howManyGreaterThans will hopefully be gone soon.
13221 const SCEV *One = getOne(Stride->getType());
13222 const SCEV *BECount = getUDivExpr(
13223 getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride);
13224
13225 APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
13226 : getUnsignedRangeMax(Start);
13227
13228 APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
13229 : getUnsignedRangeMin(Stride);
13230
13231 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
13232 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
13233 : APInt::getMinValue(BitWidth) + (MinStride - 1);
13234
13235 // Although End can be a MIN expression we estimate MinEnd considering only
13236 // the case End = RHS. This is safe because in the other case (Start - End)
13237 // is zero, leading to a zero maximum backedge taken count.
13238 APInt MinEnd =
13239 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
13240 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
13241
13242 const SCEV *ConstantMaxBECount =
13243 isa<SCEVConstant>(BECount)
13244 ? BECount
13245 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd),
13246 getConstant(MinStride));
13247
13248 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount))
13249 ConstantMaxBECount = BECount;
13250 const SCEV *SymbolicMaxBECount =
13251 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13252
13253 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
13254 Predicates);
13255 }
13256
getNumIterationsInRange(const ConstantRange & Range,ScalarEvolution & SE) const13257 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
13258 ScalarEvolution &SE) const {
13259 if (Range.isFullSet()) // Infinite loop.
13260 return SE.getCouldNotCompute();
13261
13262 // If the start is a non-zero constant, shift the range to simplify things.
13263 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
13264 if (!SC->getValue()->isZero()) {
13265 SmallVector<const SCEV *, 4> Operands(operands());
13266 Operands[0] = SE.getZero(SC->getType());
13267 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
13268 getNoWrapFlags(FlagNW));
13269 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
13270 return ShiftedAddRec->getNumIterationsInRange(
13271 Range.subtract(SC->getAPInt()), SE);
13272 // This is strange and shouldn't happen.
13273 return SE.getCouldNotCompute();
13274 }
13275
13276 // The only time we can solve this is when we have all constant indices.
13277 // Otherwise, we cannot determine the overflow conditions.
13278 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
13279 return SE.getCouldNotCompute();
13280
13281 // Okay at this point we know that all elements of the chrec are constants and
13282 // that the start element is zero.
13283
13284 // First check to see if the range contains zero. If not, the first
13285 // iteration exits.
13286 unsigned BitWidth = SE.getTypeSizeInBits(getType());
13287 if (!Range.contains(APInt(BitWidth, 0)))
13288 return SE.getZero(getType());
13289
13290 if (isAffine()) {
13291 // If this is an affine expression then we have this situation:
13292 // Solve {0,+,A} in Range === Ax in Range
13293
13294 // We know that zero is in the range. If A is positive then we know that
13295 // the upper value of the range must be the first possible exit value.
13296 // If A is negative then the lower of the range is the last possible loop
13297 // value. Also note that we already checked for a full range.
13298 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
13299 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
13300
13301 // The exit value should be (End+A)/A.
13302 APInt ExitVal = (End + A).udiv(A);
13303 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
13304
13305 // Evaluate at the exit value. If we really did fall out of the valid
13306 // range, then we computed our trip count, otherwise wrap around or other
13307 // things must have happened.
13308 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
13309 if (Range.contains(Val->getValue()))
13310 return SE.getCouldNotCompute(); // Something strange happened
13311
13312 // Ensure that the previous value is in the range.
13313 assert(Range.contains(
13314 EvaluateConstantChrecAtConstant(this,
13315 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
13316 "Linear scev computation is off in a bad way!");
13317 return SE.getConstant(ExitValue);
13318 }
13319
13320 if (isQuadratic()) {
13321 if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
13322 return SE.getConstant(*S);
13323 }
13324
13325 return SE.getCouldNotCompute();
13326 }
13327
13328 const SCEVAddRecExpr *
getPostIncExpr(ScalarEvolution & SE) const13329 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
13330 assert(getNumOperands() > 1 && "AddRec with zero step?");
13331 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
13332 // but in this case we cannot guarantee that the value returned will be an
13333 // AddRec because SCEV does not have a fixed point where it stops
13334 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
13335 // may happen if we reach arithmetic depth limit while simplifying. So we
13336 // construct the returned value explicitly.
13337 SmallVector<const SCEV *, 3> Ops;
13338 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
13339 // (this + Step) is {A+B,+,B+C,+...,+,N}.
13340 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
13341 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
13342 // We know that the last operand is not a constant zero (otherwise it would
13343 // have been popped out earlier). This guarantees us that if the result has
13344 // the same last operand, then it will also not be popped out, meaning that
13345 // the returned value will be an AddRec.
13346 const SCEV *Last = getOperand(getNumOperands() - 1);
13347 assert(!Last->isZero() && "Recurrency with zero step?");
13348 Ops.push_back(Last);
13349 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
13350 SCEV::FlagAnyWrap));
13351 }
13352
13353 // Return true when S contains at least an undef value.
containsUndefs(const SCEV * S) const13354 bool ScalarEvolution::containsUndefs(const SCEV *S) const {
13355 return SCEVExprContains(S, [](const SCEV *S) {
13356 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
13357 return isa<UndefValue>(SU->getValue());
13358 return false;
13359 });
13360 }
13361
13362 // Return true when S contains a value that is a nullptr.
containsErasedValue(const SCEV * S) const13363 bool ScalarEvolution::containsErasedValue(const SCEV *S) const {
13364 return SCEVExprContains(S, [](const SCEV *S) {
13365 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
13366 return SU->getValue() == nullptr;
13367 return false;
13368 });
13369 }
13370
13371 /// Return the size of an element read or written by Inst.
getElementSize(Instruction * Inst)13372 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
13373 Type *Ty;
13374 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
13375 Ty = Store->getValueOperand()->getType();
13376 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
13377 Ty = Load->getType();
13378 else
13379 return nullptr;
13380
13381 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
13382 return getSizeOfExpr(ETy, Ty);
13383 }
13384
13385 //===----------------------------------------------------------------------===//
13386 // SCEVCallbackVH Class Implementation
13387 //===----------------------------------------------------------------------===//
13388
deleted()13389 void ScalarEvolution::SCEVCallbackVH::deleted() {
13390 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
13391 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
13392 SE->ConstantEvolutionLoopExitValue.erase(PN);
13393 SE->eraseValueFromMap(getValPtr());
13394 // this now dangles!
13395 }
13396
allUsesReplacedWith(Value * V)13397 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
13398 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
13399
13400 // Forget all the expressions associated with users of the old value,
13401 // so that future queries will recompute the expressions using the new
13402 // value.
13403 Value *Old = getValPtr();
13404 SmallVector<User *, 16> Worklist(Old->users());
13405 SmallPtrSet<User *, 8> Visited;
13406 while (!Worklist.empty()) {
13407 User *U = Worklist.pop_back_val();
13408 // Deleting the Old value will cause this to dangle. Postpone
13409 // that until everything else is done.
13410 if (U == Old)
13411 continue;
13412 if (!Visited.insert(U).second)
13413 continue;
13414 if (PHINode *PN = dyn_cast<PHINode>(U))
13415 SE->ConstantEvolutionLoopExitValue.erase(PN);
13416 SE->eraseValueFromMap(U);
13417 llvm::append_range(Worklist, U->users());
13418 }
13419 // Delete the Old value.
13420 if (PHINode *PN = dyn_cast<PHINode>(Old))
13421 SE->ConstantEvolutionLoopExitValue.erase(PN);
13422 SE->eraseValueFromMap(Old);
13423 // this now dangles!
13424 }
13425
SCEVCallbackVH(Value * V,ScalarEvolution * se)13426 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
13427 : CallbackVH(V), SE(se) {}
13428
13429 //===----------------------------------------------------------------------===//
13430 // ScalarEvolution Class Implementation
13431 //===----------------------------------------------------------------------===//
13432
ScalarEvolution(Function & F,TargetLibraryInfo & TLI,AssumptionCache & AC,DominatorTree & DT,LoopInfo & LI)13433 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
13434 AssumptionCache &AC, DominatorTree &DT,
13435 LoopInfo &LI)
13436 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
13437 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
13438 LoopDispositions(64), BlockDispositions(64) {}
13439
ScalarEvolution(ScalarEvolution && Arg)13440 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
13441 : F(Arg.F), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), LI(Arg.LI),
13442 CouldNotCompute(std::move(Arg.CouldNotCompute)),
13443 ValueExprMap(std::move(Arg.ValueExprMap)),
13444 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
13445 PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
13446 PendingMerges(std::move(Arg.PendingMerges)),
13447 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
13448 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
13449 PredicatedBackedgeTakenCounts(
13450 std::move(Arg.PredicatedBackedgeTakenCounts)),
13451 BECountUsers(std::move(Arg.BECountUsers)),
13452 ConstantEvolutionLoopExitValue(
13453 std::move(Arg.ConstantEvolutionLoopExitValue)),
13454 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
13455 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
13456 LoopDispositions(std::move(Arg.LoopDispositions)),
13457 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
13458 BlockDispositions(std::move(Arg.BlockDispositions)),
13459 SCEVUsers(std::move(Arg.SCEVUsers)),
13460 UnsignedRanges(std::move(Arg.UnsignedRanges)),
13461 SignedRanges(std::move(Arg.SignedRanges)),
13462 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
13463 UniquePreds(std::move(Arg.UniquePreds)),
13464 SCEVAllocator(std::move(Arg.SCEVAllocator)),
13465 LoopUsers(std::move(Arg.LoopUsers)),
13466 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
13467 FirstUnknown(Arg.FirstUnknown) {
13468 Arg.FirstUnknown = nullptr;
13469 }
13470
~ScalarEvolution()13471 ScalarEvolution::~ScalarEvolution() {
13472 // Iterate through all the SCEVUnknown instances and call their
13473 // destructors, so that they release their references to their values.
13474 for (SCEVUnknown *U = FirstUnknown; U;) {
13475 SCEVUnknown *Tmp = U;
13476 U = U->Next;
13477 Tmp->~SCEVUnknown();
13478 }
13479 FirstUnknown = nullptr;
13480
13481 ExprValueMap.clear();
13482 ValueExprMap.clear();
13483 HasRecMap.clear();
13484 BackedgeTakenCounts.clear();
13485 PredicatedBackedgeTakenCounts.clear();
13486
13487 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
13488 assert(PendingPhiRanges.empty() && "getRangeRef garbage");
13489 assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
13490 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
13491 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
13492 }
13493
hasLoopInvariantBackedgeTakenCount(const Loop * L)13494 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
13495 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
13496 }
13497
PrintLoopInfo(raw_ostream & OS,ScalarEvolution * SE,const Loop * L)13498 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
13499 const Loop *L) {
13500 // Print all inner loops first
13501 for (Loop *I : *L)
13502 PrintLoopInfo(OS, SE, I);
13503
13504 OS << "Loop ";
13505 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13506 OS << ": ";
13507
13508 SmallVector<BasicBlock *, 8> ExitingBlocks;
13509 L->getExitingBlocks(ExitingBlocks);
13510 if (ExitingBlocks.size() != 1)
13511 OS << "<multiple exits> ";
13512
13513 if (SE->hasLoopInvariantBackedgeTakenCount(L))
13514 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
13515 else
13516 OS << "Unpredictable backedge-taken count.\n";
13517
13518 if (ExitingBlocks.size() > 1)
13519 for (BasicBlock *ExitingBlock : ExitingBlocks) {
13520 OS << " exit count for " << ExitingBlock->getName() << ": "
13521 << *SE->getExitCount(L, ExitingBlock) << "\n";
13522 }
13523
13524 OS << "Loop ";
13525 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13526 OS << ": ";
13527
13528 auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
13529 if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
13530 OS << "constant max backedge-taken count is " << *ConstantBTC;
13531 if (SE->isBackedgeTakenCountMaxOrZero(L))
13532 OS << ", actual taken count either this or zero.";
13533 } else {
13534 OS << "Unpredictable constant max backedge-taken count. ";
13535 }
13536
13537 OS << "\n"
13538 "Loop ";
13539 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13540 OS << ": ";
13541
13542 auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
13543 if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
13544 OS << "symbolic max backedge-taken count is " << *SymbolicBTC;
13545 if (SE->isBackedgeTakenCountMaxOrZero(L))
13546 OS << ", actual taken count either this or zero.";
13547 } else {
13548 OS << "Unpredictable symbolic max backedge-taken count. ";
13549 }
13550
13551 OS << "\n";
13552 if (ExitingBlocks.size() > 1)
13553 for (BasicBlock *ExitingBlock : ExitingBlocks) {
13554 OS << " symbolic max exit count for " << ExitingBlock->getName() << ": "
13555 << *SE->getExitCount(L, ExitingBlock, ScalarEvolution::SymbolicMaximum)
13556 << "\n";
13557 }
13558
13559 OS << "Loop ";
13560 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13561 OS << ": ";
13562
13563 SmallVector<const SCEVPredicate *, 4> Preds;
13564 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
13565 if (!isa<SCEVCouldNotCompute>(PBT)) {
13566 OS << "Predicated backedge-taken count is " << *PBT << "\n";
13567 OS << " Predicates:\n";
13568 for (const auto *P : Preds)
13569 P->print(OS, 4);
13570 } else {
13571 OS << "Unpredictable predicated backedge-taken count. ";
13572 }
13573 OS << "\n";
13574
13575 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
13576 OS << "Loop ";
13577 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13578 OS << ": ";
13579 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
13580 }
13581 }
13582
loopDispositionToStr(ScalarEvolution::LoopDisposition LD)13583 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
13584 switch (LD) {
13585 case ScalarEvolution::LoopVariant:
13586 return "Variant";
13587 case ScalarEvolution::LoopInvariant:
13588 return "Invariant";
13589 case ScalarEvolution::LoopComputable:
13590 return "Computable";
13591 }
13592 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
13593 }
13594
print(raw_ostream & OS) const13595 void ScalarEvolution::print(raw_ostream &OS) const {
13596 // ScalarEvolution's implementation of the print method is to print
13597 // out SCEV values of all instructions that are interesting. Doing
13598 // this potentially causes it to create new SCEV objects though,
13599 // which technically conflicts with the const qualifier. This isn't
13600 // observable from outside the class though, so casting away the
13601 // const isn't dangerous.
13602 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
13603
13604 if (ClassifyExpressions) {
13605 OS << "Classifying expressions for: ";
13606 F.printAsOperand(OS, /*PrintType=*/false);
13607 OS << "\n";
13608 for (Instruction &I : instructions(F))
13609 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
13610 OS << I << '\n';
13611 OS << " --> ";
13612 const SCEV *SV = SE.getSCEV(&I);
13613 SV->print(OS);
13614 if (!isa<SCEVCouldNotCompute>(SV)) {
13615 OS << " U: ";
13616 SE.getUnsignedRange(SV).print(OS);
13617 OS << " S: ";
13618 SE.getSignedRange(SV).print(OS);
13619 }
13620
13621 const Loop *L = LI.getLoopFor(I.getParent());
13622
13623 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
13624 if (AtUse != SV) {
13625 OS << " --> ";
13626 AtUse->print(OS);
13627 if (!isa<SCEVCouldNotCompute>(AtUse)) {
13628 OS << " U: ";
13629 SE.getUnsignedRange(AtUse).print(OS);
13630 OS << " S: ";
13631 SE.getSignedRange(AtUse).print(OS);
13632 }
13633 }
13634
13635 if (L) {
13636 OS << "\t\t" "Exits: ";
13637 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
13638 if (!SE.isLoopInvariant(ExitValue, L)) {
13639 OS << "<<Unknown>>";
13640 } else {
13641 OS << *ExitValue;
13642 }
13643
13644 bool First = true;
13645 for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
13646 if (First) {
13647 OS << "\t\t" "LoopDispositions: { ";
13648 First = false;
13649 } else {
13650 OS << ", ";
13651 }
13652
13653 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13654 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
13655 }
13656
13657 for (const auto *InnerL : depth_first(L)) {
13658 if (InnerL == L)
13659 continue;
13660 if (First) {
13661 OS << "\t\t" "LoopDispositions: { ";
13662 First = false;
13663 } else {
13664 OS << ", ";
13665 }
13666
13667 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13668 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
13669 }
13670
13671 OS << " }";
13672 }
13673
13674 OS << "\n";
13675 }
13676 }
13677
13678 OS << "Determining loop execution counts for: ";
13679 F.printAsOperand(OS, /*PrintType=*/false);
13680 OS << "\n";
13681 for (Loop *I : LI)
13682 PrintLoopInfo(OS, &SE, I);
13683 }
13684
13685 ScalarEvolution::LoopDisposition
getLoopDisposition(const SCEV * S,const Loop * L)13686 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
13687 auto &Values = LoopDispositions[S];
13688 for (auto &V : Values) {
13689 if (V.getPointer() == L)
13690 return V.getInt();
13691 }
13692 Values.emplace_back(L, LoopVariant);
13693 LoopDisposition D = computeLoopDisposition(S, L);
13694 auto &Values2 = LoopDispositions[S];
13695 for (auto &V : llvm::reverse(Values2)) {
13696 if (V.getPointer() == L) {
13697 V.setInt(D);
13698 break;
13699 }
13700 }
13701 return D;
13702 }
13703
13704 ScalarEvolution::LoopDisposition
computeLoopDisposition(const SCEV * S,const Loop * L)13705 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
13706 switch (S->getSCEVType()) {
13707 case scConstant:
13708 return LoopInvariant;
13709 case scAddRecExpr: {
13710 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
13711
13712 // If L is the addrec's loop, it's computable.
13713 if (AR->getLoop() == L)
13714 return LoopComputable;
13715
13716 // Add recurrences are never invariant in the function-body (null loop).
13717 if (!L)
13718 return LoopVariant;
13719
13720 // Everything that is not defined at loop entry is variant.
13721 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
13722 return LoopVariant;
13723 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
13724 " dominate the contained loop's header?");
13725
13726 // This recurrence is invariant w.r.t. L if AR's loop contains L.
13727 if (AR->getLoop()->contains(L))
13728 return LoopInvariant;
13729
13730 // This recurrence is variant w.r.t. L if any of its operands
13731 // are variant.
13732 for (const auto *Op : AR->operands())
13733 if (!isLoopInvariant(Op, L))
13734 return LoopVariant;
13735
13736 // Otherwise it's loop-invariant.
13737 return LoopInvariant;
13738 }
13739 case scTruncate:
13740 case scZeroExtend:
13741 case scSignExtend:
13742 case scPtrToInt:
13743 case scAddExpr:
13744 case scMulExpr:
13745 case scUDivExpr:
13746 case scUMaxExpr:
13747 case scSMaxExpr:
13748 case scUMinExpr:
13749 case scSMinExpr:
13750 case scSequentialUMinExpr: {
13751 bool HasVarying = false;
13752 for (const auto *Op : S->operands()) {
13753 LoopDisposition D = getLoopDisposition(Op, L);
13754 if (D == LoopVariant)
13755 return LoopVariant;
13756 if (D == LoopComputable)
13757 HasVarying = true;
13758 }
13759 return HasVarying ? LoopComputable : LoopInvariant;
13760 }
13761 case scUnknown:
13762 // All non-instruction values are loop invariant. All instructions are loop
13763 // invariant if they are not contained in the specified loop.
13764 // Instructions are never considered invariant in the function body
13765 // (null loop) because they are defined within the "loop".
13766 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
13767 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
13768 return LoopInvariant;
13769 case scCouldNotCompute:
13770 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
13771 }
13772 llvm_unreachable("Unknown SCEV kind!");
13773 }
13774
isLoopInvariant(const SCEV * S,const Loop * L)13775 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
13776 return getLoopDisposition(S, L) == LoopInvariant;
13777 }
13778
hasComputableLoopEvolution(const SCEV * S,const Loop * L)13779 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
13780 return getLoopDisposition(S, L) == LoopComputable;
13781 }
13782
13783 ScalarEvolution::BlockDisposition
getBlockDisposition(const SCEV * S,const BasicBlock * BB)13784 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
13785 auto &Values = BlockDispositions[S];
13786 for (auto &V : Values) {
13787 if (V.getPointer() == BB)
13788 return V.getInt();
13789 }
13790 Values.emplace_back(BB, DoesNotDominateBlock);
13791 BlockDisposition D = computeBlockDisposition(S, BB);
13792 auto &Values2 = BlockDispositions[S];
13793 for (auto &V : llvm::reverse(Values2)) {
13794 if (V.getPointer() == BB) {
13795 V.setInt(D);
13796 break;
13797 }
13798 }
13799 return D;
13800 }
13801
13802 ScalarEvolution::BlockDisposition
computeBlockDisposition(const SCEV * S,const BasicBlock * BB)13803 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
13804 switch (S->getSCEVType()) {
13805 case scConstant:
13806 return ProperlyDominatesBlock;
13807 case scAddRecExpr: {
13808 // This uses a "dominates" query instead of "properly dominates" query
13809 // to test for proper dominance too, because the instruction which
13810 // produces the addrec's value is a PHI, and a PHI effectively properly
13811 // dominates its entire containing block.
13812 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
13813 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
13814 return DoesNotDominateBlock;
13815
13816 // Fall through into SCEVNAryExpr handling.
13817 [[fallthrough]];
13818 }
13819 case scTruncate:
13820 case scZeroExtend:
13821 case scSignExtend:
13822 case scPtrToInt:
13823 case scAddExpr:
13824 case scMulExpr:
13825 case scUDivExpr:
13826 case scUMaxExpr:
13827 case scSMaxExpr:
13828 case scUMinExpr:
13829 case scSMinExpr:
13830 case scSequentialUMinExpr: {
13831 bool Proper = true;
13832 for (const SCEV *NAryOp : S->operands()) {
13833 BlockDisposition D = getBlockDisposition(NAryOp, BB);
13834 if (D == DoesNotDominateBlock)
13835 return DoesNotDominateBlock;
13836 if (D == DominatesBlock)
13837 Proper = false;
13838 }
13839 return Proper ? ProperlyDominatesBlock : DominatesBlock;
13840 }
13841 case scUnknown:
13842 if (Instruction *I =
13843 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
13844 if (I->getParent() == BB)
13845 return DominatesBlock;
13846 if (DT.properlyDominates(I->getParent(), BB))
13847 return ProperlyDominatesBlock;
13848 return DoesNotDominateBlock;
13849 }
13850 return ProperlyDominatesBlock;
13851 case scCouldNotCompute:
13852 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
13853 }
13854 llvm_unreachable("Unknown SCEV kind!");
13855 }
13856
dominates(const SCEV * S,const BasicBlock * BB)13857 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
13858 return getBlockDisposition(S, BB) >= DominatesBlock;
13859 }
13860
properlyDominates(const SCEV * S,const BasicBlock * BB)13861 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
13862 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
13863 }
13864
hasOperand(const SCEV * S,const SCEV * Op) const13865 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
13866 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
13867 }
13868
forgetBackedgeTakenCounts(const Loop * L,bool Predicated)13869 void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
13870 bool Predicated) {
13871 auto &BECounts =
13872 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
13873 auto It = BECounts.find(L);
13874 if (It != BECounts.end()) {
13875 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
13876 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
13877 if (!isa<SCEVConstant>(S)) {
13878 auto UserIt = BECountUsers.find(S);
13879 assert(UserIt != BECountUsers.end());
13880 UserIt->second.erase({L, Predicated});
13881 }
13882 }
13883 }
13884 BECounts.erase(It);
13885 }
13886 }
13887
forgetMemoizedResults(ArrayRef<const SCEV * > SCEVs)13888 void ScalarEvolution::forgetMemoizedResults(ArrayRef<const SCEV *> SCEVs) {
13889 SmallPtrSet<const SCEV *, 8> ToForget(SCEVs.begin(), SCEVs.end());
13890 SmallVector<const SCEV *, 8> Worklist(ToForget.begin(), ToForget.end());
13891
13892 while (!Worklist.empty()) {
13893 const SCEV *Curr = Worklist.pop_back_val();
13894 auto Users = SCEVUsers.find(Curr);
13895 if (Users != SCEVUsers.end())
13896 for (const auto *User : Users->second)
13897 if (ToForget.insert(User).second)
13898 Worklist.push_back(User);
13899 }
13900
13901 for (const auto *S : ToForget)
13902 forgetMemoizedResultsImpl(S);
13903
13904 for (auto I = PredicatedSCEVRewrites.begin();
13905 I != PredicatedSCEVRewrites.end();) {
13906 std::pair<const SCEV *, const Loop *> Entry = I->first;
13907 if (ToForget.count(Entry.first))
13908 PredicatedSCEVRewrites.erase(I++);
13909 else
13910 ++I;
13911 }
13912 }
13913
forgetMemoizedResultsImpl(const SCEV * S)13914 void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
13915 LoopDispositions.erase(S);
13916 BlockDispositions.erase(S);
13917 UnsignedRanges.erase(S);
13918 SignedRanges.erase(S);
13919 HasRecMap.erase(S);
13920 MinTrailingZerosCache.erase(S);
13921
13922 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
13923 UnsignedWrapViaInductionTried.erase(AR);
13924 SignedWrapViaInductionTried.erase(AR);
13925 }
13926
13927 auto ExprIt = ExprValueMap.find(S);
13928 if (ExprIt != ExprValueMap.end()) {
13929 for (Value *V : ExprIt->second) {
13930 auto ValueIt = ValueExprMap.find_as(V);
13931 if (ValueIt != ValueExprMap.end())
13932 ValueExprMap.erase(ValueIt);
13933 }
13934 ExprValueMap.erase(ExprIt);
13935 }
13936
13937 auto ScopeIt = ValuesAtScopes.find(S);
13938 if (ScopeIt != ValuesAtScopes.end()) {
13939 for (const auto &Pair : ScopeIt->second)
13940 if (!isa_and_nonnull<SCEVConstant>(Pair.second))
13941 erase_value(ValuesAtScopesUsers[Pair.second],
13942 std::make_pair(Pair.first, S));
13943 ValuesAtScopes.erase(ScopeIt);
13944 }
13945
13946 auto ScopeUserIt = ValuesAtScopesUsers.find(S);
13947 if (ScopeUserIt != ValuesAtScopesUsers.end()) {
13948 for (const auto &Pair : ScopeUserIt->second)
13949 erase_value(ValuesAtScopes[Pair.second], std::make_pair(Pair.first, S));
13950 ValuesAtScopesUsers.erase(ScopeUserIt);
13951 }
13952
13953 auto BEUsersIt = BECountUsers.find(S);
13954 if (BEUsersIt != BECountUsers.end()) {
13955 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
13956 auto Copy = BEUsersIt->second;
13957 for (const auto &Pair : Copy)
13958 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
13959 BECountUsers.erase(BEUsersIt);
13960 }
13961
13962 auto FoldUser = FoldCacheUser.find(S);
13963 if (FoldUser != FoldCacheUser.end())
13964 for (auto &KV : FoldUser->second)
13965 FoldCache.erase(KV);
13966 FoldCacheUser.erase(S);
13967 }
13968
13969 void
getUsedLoops(const SCEV * S,SmallPtrSetImpl<const Loop * > & LoopsUsed)13970 ScalarEvolution::getUsedLoops(const SCEV *S,
13971 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
13972 struct FindUsedLoops {
13973 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
13974 : LoopsUsed(LoopsUsed) {}
13975 SmallPtrSetImpl<const Loop *> &LoopsUsed;
13976 bool follow(const SCEV *S) {
13977 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
13978 LoopsUsed.insert(AR->getLoop());
13979 return true;
13980 }
13981
13982 bool isDone() const { return false; }
13983 };
13984
13985 FindUsedLoops F(LoopsUsed);
13986 SCEVTraversal<FindUsedLoops>(F).visitAll(S);
13987 }
13988
getReachableBlocks(SmallPtrSetImpl<BasicBlock * > & Reachable,Function & F)13989 void ScalarEvolution::getReachableBlocks(
13990 SmallPtrSetImpl<BasicBlock *> &Reachable, Function &F) {
13991 SmallVector<BasicBlock *> Worklist;
13992 Worklist.push_back(&F.getEntryBlock());
13993 while (!Worklist.empty()) {
13994 BasicBlock *BB = Worklist.pop_back_val();
13995 if (!Reachable.insert(BB).second)
13996 continue;
13997
13998 Value *Cond;
13999 BasicBlock *TrueBB, *FalseBB;
14000 if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
14001 m_BasicBlock(FalseBB)))) {
14002 if (auto *C = dyn_cast<ConstantInt>(Cond)) {
14003 Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
14004 continue;
14005 }
14006
14007 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14008 const SCEV *L = getSCEV(Cmp->getOperand(0));
14009 const SCEV *R = getSCEV(Cmp->getOperand(1));
14010 if (isKnownPredicateViaConstantRanges(Cmp->getPredicate(), L, R)) {
14011 Worklist.push_back(TrueBB);
14012 continue;
14013 }
14014 if (isKnownPredicateViaConstantRanges(Cmp->getInversePredicate(), L,
14015 R)) {
14016 Worklist.push_back(FalseBB);
14017 continue;
14018 }
14019 }
14020 }
14021
14022 append_range(Worklist, successors(BB));
14023 }
14024 }
14025
verify() const14026 void ScalarEvolution::verify() const {
14027 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14028 ScalarEvolution SE2(F, TLI, AC, DT, LI);
14029
14030 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
14031
14032 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
14033 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
14034 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
14035
14036 const SCEV *visitConstant(const SCEVConstant *Constant) {
14037 return SE.getConstant(Constant->getAPInt());
14038 }
14039
14040 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14041 return SE.getUnknown(Expr->getValue());
14042 }
14043
14044 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
14045 return SE.getCouldNotCompute();
14046 }
14047 };
14048
14049 SCEVMapper SCM(SE2);
14050 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
14051 SE2.getReachableBlocks(ReachableBlocks, F);
14052
14053 auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
14054 if (containsUndefs(Old) || containsUndefs(New)) {
14055 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
14056 // not propagate undef aggressively). This means we can (and do) fail
14057 // verification in cases where a transform makes a value go from "undef"
14058 // to "undef+1" (say). The transform is fine, since in both cases the
14059 // result is "undef", but SCEV thinks the value increased by 1.
14060 return nullptr;
14061 }
14062
14063 // Unless VerifySCEVStrict is set, we only compare constant deltas.
14064 const SCEV *Delta = SE2.getMinusSCEV(Old, New);
14065 if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
14066 return nullptr;
14067
14068 return Delta;
14069 };
14070
14071 while (!LoopStack.empty()) {
14072 auto *L = LoopStack.pop_back_val();
14073 llvm::append_range(LoopStack, *L);
14074
14075 // Only verify BECounts in reachable loops. For an unreachable loop,
14076 // any BECount is legal.
14077 if (!ReachableBlocks.contains(L->getHeader()))
14078 continue;
14079
14080 // Only verify cached BECounts. Computing new BECounts may change the
14081 // results of subsequent SCEV uses.
14082 auto It = BackedgeTakenCounts.find(L);
14083 if (It == BackedgeTakenCounts.end())
14084 continue;
14085
14086 auto *CurBECount =
14087 SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
14088 auto *NewBECount = SE2.getBackedgeTakenCount(L);
14089
14090 if (CurBECount == SE2.getCouldNotCompute() ||
14091 NewBECount == SE2.getCouldNotCompute()) {
14092 // NB! This situation is legal, but is very suspicious -- whatever pass
14093 // change the loop to make a trip count go from could not compute to
14094 // computable or vice-versa *should have* invalidated SCEV. However, we
14095 // choose not to assert here (for now) since we don't want false
14096 // positives.
14097 continue;
14098 }
14099
14100 if (SE.getTypeSizeInBits(CurBECount->getType()) >
14101 SE.getTypeSizeInBits(NewBECount->getType()))
14102 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
14103 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
14104 SE.getTypeSizeInBits(NewBECount->getType()))
14105 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
14106
14107 const SCEV *Delta = GetDelta(CurBECount, NewBECount);
14108 if (Delta && !Delta->isZero()) {
14109 dbgs() << "Trip Count for " << *L << " Changed!\n";
14110 dbgs() << "Old: " << *CurBECount << "\n";
14111 dbgs() << "New: " << *NewBECount << "\n";
14112 dbgs() << "Delta: " << *Delta << "\n";
14113 std::abort();
14114 }
14115 }
14116
14117 // Collect all valid loops currently in LoopInfo.
14118 SmallPtrSet<Loop *, 32> ValidLoops;
14119 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
14120 while (!Worklist.empty()) {
14121 Loop *L = Worklist.pop_back_val();
14122 if (ValidLoops.insert(L).second)
14123 Worklist.append(L->begin(), L->end());
14124 }
14125 for (const auto &KV : ValueExprMap) {
14126 #ifndef NDEBUG
14127 // Check for SCEV expressions referencing invalid/deleted loops.
14128 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14129 assert(ValidLoops.contains(AR->getLoop()) &&
14130 "AddRec references invalid loop");
14131 }
14132 #endif
14133
14134 // Check that the value is also part of the reverse map.
14135 auto It = ExprValueMap.find(KV.second);
14136 if (It == ExprValueMap.end() || !It->second.contains(KV.first)) {
14137 dbgs() << "Value " << *KV.first
14138 << " is in ValueExprMap but not in ExprValueMap\n";
14139 std::abort();
14140 }
14141
14142 if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
14143 if (!ReachableBlocks.contains(I->getParent()))
14144 continue;
14145 const SCEV *OldSCEV = SCM.visit(KV.second);
14146 const SCEV *NewSCEV = SE2.getSCEV(I);
14147 const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14148 if (Delta && !Delta->isZero()) {
14149 dbgs() << "SCEV for value " << *I << " changed!\n"
14150 << "Old: " << *OldSCEV << "\n"
14151 << "New: " << *NewSCEV << "\n"
14152 << "Delta: " << *Delta << "\n";
14153 std::abort();
14154 }
14155 }
14156 }
14157
14158 for (const auto &KV : ExprValueMap) {
14159 for (Value *V : KV.second) {
14160 auto It = ValueExprMap.find_as(V);
14161 if (It == ValueExprMap.end()) {
14162 dbgs() << "Value " << *V
14163 << " is in ExprValueMap but not in ValueExprMap\n";
14164 std::abort();
14165 }
14166 if (It->second != KV.first) {
14167 dbgs() << "Value " << *V << " mapped to " << *It->second
14168 << " rather than " << *KV.first << "\n";
14169 std::abort();
14170 }
14171 }
14172 }
14173
14174 // Verify integrity of SCEV users.
14175 for (const auto &S : UniqueSCEVs) {
14176 for (const auto *Op : S.operands()) {
14177 // We do not store dependencies of constants.
14178 if (isa<SCEVConstant>(Op))
14179 continue;
14180 auto It = SCEVUsers.find(Op);
14181 if (It != SCEVUsers.end() && It->second.count(&S))
14182 continue;
14183 dbgs() << "Use of operand " << *Op << " by user " << S
14184 << " is not being tracked!\n";
14185 std::abort();
14186 }
14187 }
14188
14189 // Verify integrity of ValuesAtScopes users.
14190 for (const auto &ValueAndVec : ValuesAtScopes) {
14191 const SCEV *Value = ValueAndVec.first;
14192 for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
14193 const Loop *L = LoopAndValueAtScope.first;
14194 const SCEV *ValueAtScope = LoopAndValueAtScope.second;
14195 if (!isa<SCEVConstant>(ValueAtScope)) {
14196 auto It = ValuesAtScopesUsers.find(ValueAtScope);
14197 if (It != ValuesAtScopesUsers.end() &&
14198 is_contained(It->second, std::make_pair(L, Value)))
14199 continue;
14200 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14201 << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
14202 std::abort();
14203 }
14204 }
14205 }
14206
14207 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
14208 const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
14209 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
14210 const Loop *L = LoopAndValue.first;
14211 const SCEV *Value = LoopAndValue.second;
14212 assert(!isa<SCEVConstant>(Value));
14213 auto It = ValuesAtScopes.find(Value);
14214 if (It != ValuesAtScopes.end() &&
14215 is_contained(It->second, std::make_pair(L, ValueAtScope)))
14216 continue;
14217 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14218 << *ValueAtScope << " missing in ValuesAtScopes\n";
14219 std::abort();
14220 }
14221 }
14222
14223 // Verify integrity of BECountUsers.
14224 auto VerifyBECountUsers = [&](bool Predicated) {
14225 auto &BECounts =
14226 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14227 for (const auto &LoopAndBEInfo : BECounts) {
14228 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
14229 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14230 if (!isa<SCEVConstant>(S)) {
14231 auto UserIt = BECountUsers.find(S);
14232 if (UserIt != BECountUsers.end() &&
14233 UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
14234 continue;
14235 dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
14236 << " missing from BECountUsers\n";
14237 std::abort();
14238 }
14239 }
14240 }
14241 }
14242 };
14243 VerifyBECountUsers(/* Predicated */ false);
14244 VerifyBECountUsers(/* Predicated */ true);
14245
14246 // Verify intergity of loop disposition cache.
14247 for (auto &[S, Values] : LoopDispositions) {
14248 for (auto [Loop, CachedDisposition] : Values) {
14249 const auto RecomputedDisposition = SE2.getLoopDisposition(S, Loop);
14250 if (CachedDisposition != RecomputedDisposition) {
14251 dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
14252 << " is incorrect: cached "
14253 << loopDispositionToStr(CachedDisposition) << ", actual "
14254 << loopDispositionToStr(RecomputedDisposition) << "\n";
14255 std::abort();
14256 }
14257 }
14258 }
14259
14260 // Verify integrity of the block disposition cache.
14261 for (auto &[S, Values] : BlockDispositions) {
14262 for (auto [BB, CachedDisposition] : Values) {
14263 const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
14264 if (CachedDisposition != RecomputedDisposition) {
14265 dbgs() << "Cached disposition of " << *S << " for block %"
14266 << BB->getName() << " is incorrect! \n";
14267 std::abort();
14268 }
14269 }
14270 }
14271
14272 // Verify FoldCache/FoldCacheUser caches.
14273 for (auto [FoldID, Expr] : FoldCache) {
14274 auto I = FoldCacheUser.find(Expr);
14275 if (I == FoldCacheUser.end()) {
14276 dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
14277 << "!\n";
14278 std::abort();
14279 }
14280 if (!is_contained(I->second, FoldID)) {
14281 dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
14282 std::abort();
14283 }
14284 }
14285 for (auto [Expr, IDs] : FoldCacheUser) {
14286 for (auto &FoldID : IDs) {
14287 auto I = FoldCache.find(FoldID);
14288 if (I == FoldCache.end()) {
14289 dbgs() << "Missing entry in FoldCache for expression " << *Expr
14290 << "!\n";
14291 std::abort();
14292 }
14293 if (I->second != Expr) {
14294 dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: "
14295 << *I->second << " != " << *Expr << "!\n";
14296 std::abort();
14297 }
14298 }
14299 }
14300 }
14301
invalidate(Function & F,const PreservedAnalyses & PA,FunctionAnalysisManager::Invalidator & Inv)14302 bool ScalarEvolution::invalidate(
14303 Function &F, const PreservedAnalyses &PA,
14304 FunctionAnalysisManager::Invalidator &Inv) {
14305 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
14306 // of its dependencies is invalidated.
14307 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
14308 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
14309 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
14310 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
14311 Inv.invalidate<LoopAnalysis>(F, PA);
14312 }
14313
14314 AnalysisKey ScalarEvolutionAnalysis::Key;
14315
run(Function & F,FunctionAnalysisManager & AM)14316 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
14317 FunctionAnalysisManager &AM) {
14318 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
14319 AM.getResult<AssumptionAnalysis>(F),
14320 AM.getResult<DominatorTreeAnalysis>(F),
14321 AM.getResult<LoopAnalysis>(F));
14322 }
14323
14324 PreservedAnalyses
run(Function & F,FunctionAnalysisManager & AM)14325 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
14326 AM.getResult<ScalarEvolutionAnalysis>(F).verify();
14327 return PreservedAnalyses::all();
14328 }
14329
14330 PreservedAnalyses
run(Function & F,FunctionAnalysisManager & AM)14331 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
14332 // For compatibility with opt's -analyze feature under legacy pass manager
14333 // which was not ported to NPM. This keeps tests using
14334 // update_analyze_test_checks.py working.
14335 OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
14336 << F.getName() << "':\n";
14337 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
14338 return PreservedAnalyses::all();
14339 }
14340
14341 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
14342 "Scalar Evolution Analysis", false, true)
14343 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
14344 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
14345 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
14346 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
14347 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
14348 "Scalar Evolution Analysis", false, true)
14349
14350 char ScalarEvolutionWrapperPass::ID = 0;
14351
ScalarEvolutionWrapperPass()14352 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
14353 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
14354 }
14355
runOnFunction(Function & F)14356 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
14357 SE.reset(new ScalarEvolution(
14358 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
14359 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
14360 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
14361 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
14362 return false;
14363 }
14364
releaseMemory()14365 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
14366
print(raw_ostream & OS,const Module *) const14367 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
14368 SE->print(OS);
14369 }
14370
verifyAnalysis() const14371 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
14372 if (!VerifySCEV)
14373 return;
14374
14375 SE->verify();
14376 }
14377
getAnalysisUsage(AnalysisUsage & AU) const14378 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
14379 AU.setPreservesAll();
14380 AU.addRequiredTransitive<AssumptionCacheTracker>();
14381 AU.addRequiredTransitive<LoopInfoWrapperPass>();
14382 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
14383 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
14384 }
14385
getEqualPredicate(const SCEV * LHS,const SCEV * RHS)14386 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
14387 const SCEV *RHS) {
14388 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
14389 }
14390
14391 const SCEVPredicate *
getComparePredicate(const ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)14392 ScalarEvolution::getComparePredicate(const ICmpInst::Predicate Pred,
14393 const SCEV *LHS, const SCEV *RHS) {
14394 FoldingSetNodeID ID;
14395 assert(LHS->getType() == RHS->getType() &&
14396 "Type mismatch between LHS and RHS");
14397 // Unique this node based on the arguments
14398 ID.AddInteger(SCEVPredicate::P_Compare);
14399 ID.AddInteger(Pred);
14400 ID.AddPointer(LHS);
14401 ID.AddPointer(RHS);
14402 void *IP = nullptr;
14403 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
14404 return S;
14405 SCEVComparePredicate *Eq = new (SCEVAllocator)
14406 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
14407 UniquePreds.InsertNode(Eq, IP);
14408 return Eq;
14409 }
14410
getWrapPredicate(const SCEVAddRecExpr * AR,SCEVWrapPredicate::IncrementWrapFlags AddedFlags)14411 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
14412 const SCEVAddRecExpr *AR,
14413 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
14414 FoldingSetNodeID ID;
14415 // Unique this node based on the arguments
14416 ID.AddInteger(SCEVPredicate::P_Wrap);
14417 ID.AddPointer(AR);
14418 ID.AddInteger(AddedFlags);
14419 void *IP = nullptr;
14420 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
14421 return S;
14422 auto *OF = new (SCEVAllocator)
14423 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
14424 UniquePreds.InsertNode(OF, IP);
14425 return OF;
14426 }
14427
14428 namespace {
14429
14430 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
14431 public:
14432
14433 /// Rewrites \p S in the context of a loop L and the SCEV predication
14434 /// infrastructure.
14435 ///
14436 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
14437 /// equivalences present in \p Pred.
14438 ///
14439 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
14440 /// \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)14441 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
14442 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
14443 const SCEVPredicate *Pred) {
14444 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
14445 return Rewriter.visit(S);
14446 }
14447
visitUnknown(const SCEVUnknown * Expr)14448 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14449 if (Pred) {
14450 if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
14451 for (const auto *Pred : U->getPredicates())
14452 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
14453 if (IPred->getLHS() == Expr &&
14454 IPred->getPredicate() == ICmpInst::ICMP_EQ)
14455 return IPred->getRHS();
14456 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
14457 if (IPred->getLHS() == Expr &&
14458 IPred->getPredicate() == ICmpInst::ICMP_EQ)
14459 return IPred->getRHS();
14460 }
14461 }
14462 return convertToAddRecWithPreds(Expr);
14463 }
14464
visitZeroExtendExpr(const SCEVZeroExtendExpr * Expr)14465 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
14466 const SCEV *Operand = visit(Expr->getOperand());
14467 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
14468 if (AR && AR->getLoop() == L && AR->isAffine()) {
14469 // This couldn't be folded because the operand didn't have the nuw
14470 // flag. Add the nusw flag as an assumption that we could make.
14471 const SCEV *Step = AR->getStepRecurrence(SE);
14472 Type *Ty = Expr->getType();
14473 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
14474 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
14475 SE.getSignExtendExpr(Step, Ty), L,
14476 AR->getNoWrapFlags());
14477 }
14478 return SE.getZeroExtendExpr(Operand, Expr->getType());
14479 }
14480
visitSignExtendExpr(const SCEVSignExtendExpr * Expr)14481 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
14482 const SCEV *Operand = visit(Expr->getOperand());
14483 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
14484 if (AR && AR->getLoop() == L && AR->isAffine()) {
14485 // This couldn't be folded because the operand didn't have the nsw
14486 // flag. Add the nssw flag as an assumption that we could make.
14487 const SCEV *Step = AR->getStepRecurrence(SE);
14488 Type *Ty = Expr->getType();
14489 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
14490 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
14491 SE.getSignExtendExpr(Step, Ty), L,
14492 AR->getNoWrapFlags());
14493 }
14494 return SE.getSignExtendExpr(Operand, Expr->getType());
14495 }
14496
14497 private:
SCEVPredicateRewriter(const Loop * L,ScalarEvolution & SE,SmallPtrSetImpl<const SCEVPredicate * > * NewPreds,const SCEVPredicate * Pred)14498 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
14499 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
14500 const SCEVPredicate *Pred)
14501 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
14502
addOverflowAssumption(const SCEVPredicate * P)14503 bool addOverflowAssumption(const SCEVPredicate *P) {
14504 if (!NewPreds) {
14505 // Check if we've already made this assumption.
14506 return Pred && Pred->implies(P);
14507 }
14508 NewPreds->insert(P);
14509 return true;
14510 }
14511
addOverflowAssumption(const SCEVAddRecExpr * AR,SCEVWrapPredicate::IncrementWrapFlags AddedFlags)14512 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
14513 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
14514 auto *A = SE.getWrapPredicate(AR, AddedFlags);
14515 return addOverflowAssumption(A);
14516 }
14517
14518 // If \p Expr represents a PHINode, we try to see if it can be represented
14519 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
14520 // to add this predicate as a runtime overflow check, we return the AddRec.
14521 // If \p Expr does not meet these conditions (is not a PHI node, or we
14522 // couldn't create an AddRec for it, or couldn't add the predicate), we just
14523 // return \p Expr.
convertToAddRecWithPreds(const SCEVUnknown * Expr)14524 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
14525 if (!isa<PHINode>(Expr->getValue()))
14526 return Expr;
14527 std::optional<
14528 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
14529 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
14530 if (!PredicatedRewrite)
14531 return Expr;
14532 for (const auto *P : PredicatedRewrite->second){
14533 // Wrap predicates from outer loops are not supported.
14534 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
14535 if (L != WP->getExpr()->getLoop())
14536 return Expr;
14537 }
14538 if (!addOverflowAssumption(P))
14539 return Expr;
14540 }
14541 return PredicatedRewrite->first;
14542 }
14543
14544 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
14545 const SCEVPredicate *Pred;
14546 const Loop *L;
14547 };
14548
14549 } // end anonymous namespace
14550
14551 const SCEV *
rewriteUsingPredicate(const SCEV * S,const Loop * L,const SCEVPredicate & Preds)14552 ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
14553 const SCEVPredicate &Preds) {
14554 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
14555 }
14556
convertSCEVToAddRecWithPredicates(const SCEV * S,const Loop * L,SmallPtrSetImpl<const SCEVPredicate * > & Preds)14557 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
14558 const SCEV *S, const Loop *L,
14559 SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
14560 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
14561 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
14562 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
14563
14564 if (!AddRec)
14565 return nullptr;
14566
14567 // Since the transformation was successful, we can now transfer the SCEV
14568 // predicates.
14569 for (const auto *P : TransformPreds)
14570 Preds.insert(P);
14571
14572 return AddRec;
14573 }
14574
14575 /// SCEV predicates
SCEVPredicate(const FoldingSetNodeIDRef ID,SCEVPredicateKind Kind)14576 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
14577 SCEVPredicateKind Kind)
14578 : FastID(ID), Kind(Kind) {}
14579
SCEVComparePredicate(const FoldingSetNodeIDRef ID,const ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)14580 SCEVComparePredicate::SCEVComparePredicate(const FoldingSetNodeIDRef ID,
14581 const ICmpInst::Predicate Pred,
14582 const SCEV *LHS, const SCEV *RHS)
14583 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
14584 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
14585 assert(LHS != RHS && "LHS and RHS are the same SCEV");
14586 }
14587
implies(const SCEVPredicate * N) const14588 bool SCEVComparePredicate::implies(const SCEVPredicate *N) const {
14589 const auto *Op = dyn_cast<SCEVComparePredicate>(N);
14590
14591 if (!Op)
14592 return false;
14593
14594 if (Pred != ICmpInst::ICMP_EQ)
14595 return false;
14596
14597 return Op->LHS == LHS && Op->RHS == RHS;
14598 }
14599
isAlwaysTrue() const14600 bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
14601
print(raw_ostream & OS,unsigned Depth) const14602 void SCEVComparePredicate::print(raw_ostream &OS, unsigned Depth) const {
14603 if (Pred == ICmpInst::ICMP_EQ)
14604 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
14605 else
14606 OS.indent(Depth) << "Compare predicate: " << *LHS
14607 << " " << CmpInst::getPredicateName(Pred) << ") "
14608 << *RHS << "\n";
14609
14610 }
14611
SCEVWrapPredicate(const FoldingSetNodeIDRef ID,const SCEVAddRecExpr * AR,IncrementWrapFlags Flags)14612 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
14613 const SCEVAddRecExpr *AR,
14614 IncrementWrapFlags Flags)
14615 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
14616
getExpr() const14617 const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
14618
implies(const SCEVPredicate * N) const14619 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
14620 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
14621
14622 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
14623 }
14624
isAlwaysTrue() const14625 bool SCEVWrapPredicate::isAlwaysTrue() const {
14626 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
14627 IncrementWrapFlags IFlags = Flags;
14628
14629 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
14630 IFlags = clearFlags(IFlags, IncrementNSSW);
14631
14632 return IFlags == IncrementAnyWrap;
14633 }
14634
print(raw_ostream & OS,unsigned Depth) const14635 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
14636 OS.indent(Depth) << *getExpr() << " Added Flags: ";
14637 if (SCEVWrapPredicate::IncrementNUSW & getFlags())
14638 OS << "<nusw>";
14639 if (SCEVWrapPredicate::IncrementNSSW & getFlags())
14640 OS << "<nssw>";
14641 OS << "\n";
14642 }
14643
14644 SCEVWrapPredicate::IncrementWrapFlags
getImpliedFlags(const SCEVAddRecExpr * AR,ScalarEvolution & SE)14645 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
14646 ScalarEvolution &SE) {
14647 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
14648 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
14649
14650 // We can safely transfer the NSW flag as NSSW.
14651 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
14652 ImpliedFlags = IncrementNSSW;
14653
14654 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
14655 // If the increment is positive, the SCEV NUW flag will also imply the
14656 // WrapPredicate NUSW flag.
14657 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
14658 if (Step->getValue()->getValue().isNonNegative())
14659 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
14660 }
14661
14662 return ImpliedFlags;
14663 }
14664
14665 /// Union predicates don't get cached so create a dummy set ID for it.
SCEVUnionPredicate(ArrayRef<const SCEVPredicate * > Preds)14666 SCEVUnionPredicate::SCEVUnionPredicate(ArrayRef<const SCEVPredicate *> Preds)
14667 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {
14668 for (const auto *P : Preds)
14669 add(P);
14670 }
14671
isAlwaysTrue() const14672 bool SCEVUnionPredicate::isAlwaysTrue() const {
14673 return all_of(Preds,
14674 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
14675 }
14676
implies(const SCEVPredicate * N) const14677 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
14678 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
14679 return all_of(Set->Preds,
14680 [this](const SCEVPredicate *I) { return this->implies(I); });
14681
14682 return any_of(Preds,
14683 [N](const SCEVPredicate *I) { return I->implies(N); });
14684 }
14685
print(raw_ostream & OS,unsigned Depth) const14686 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
14687 for (const auto *Pred : Preds)
14688 Pred->print(OS, Depth);
14689 }
14690
add(const SCEVPredicate * N)14691 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
14692 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
14693 for (const auto *Pred : Set->Preds)
14694 add(Pred);
14695 return;
14696 }
14697
14698 Preds.push_back(N);
14699 }
14700
PredicatedScalarEvolution(ScalarEvolution & SE,Loop & L)14701 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
14702 Loop &L)
14703 : SE(SE), L(L) {
14704 SmallVector<const SCEVPredicate*, 4> Empty;
14705 Preds = std::make_unique<SCEVUnionPredicate>(Empty);
14706 }
14707
registerUser(const SCEV * User,ArrayRef<const SCEV * > Ops)14708 void ScalarEvolution::registerUser(const SCEV *User,
14709 ArrayRef<const SCEV *> Ops) {
14710 for (const auto *Op : Ops)
14711 // We do not expect that forgetting cached data for SCEVConstants will ever
14712 // open any prospects for sharpening or introduce any correctness issues,
14713 // so we don't bother storing their dependencies.
14714 if (!isa<SCEVConstant>(Op))
14715 SCEVUsers[Op].insert(User);
14716 }
14717
getSCEV(Value * V)14718 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
14719 const SCEV *Expr = SE.getSCEV(V);
14720 RewriteEntry &Entry = RewriteMap[Expr];
14721
14722 // If we already have an entry and the version matches, return it.
14723 if (Entry.second && Generation == Entry.first)
14724 return Entry.second;
14725
14726 // We found an entry but it's stale. Rewrite the stale entry
14727 // according to the current predicate.
14728 if (Entry.second)
14729 Expr = Entry.second;
14730
14731 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
14732 Entry = {Generation, NewSCEV};
14733
14734 return NewSCEV;
14735 }
14736
getBackedgeTakenCount()14737 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
14738 if (!BackedgeCount) {
14739 SmallVector<const SCEVPredicate *, 4> Preds;
14740 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
14741 for (const auto *P : Preds)
14742 addPredicate(*P);
14743 }
14744 return BackedgeCount;
14745 }
14746
addPredicate(const SCEVPredicate & Pred)14747 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
14748 if (Preds->implies(&Pred))
14749 return;
14750
14751 auto &OldPreds = Preds->getPredicates();
14752 SmallVector<const SCEVPredicate*, 4> NewPreds(OldPreds.begin(), OldPreds.end());
14753 NewPreds.push_back(&Pred);
14754 Preds = std::make_unique<SCEVUnionPredicate>(NewPreds);
14755 updateGeneration();
14756 }
14757
getPredicate() const14758 const SCEVPredicate &PredicatedScalarEvolution::getPredicate() const {
14759 return *Preds;
14760 }
14761
updateGeneration()14762 void PredicatedScalarEvolution::updateGeneration() {
14763 // If the generation number wrapped recompute everything.
14764 if (++Generation == 0) {
14765 for (auto &II : RewriteMap) {
14766 const SCEV *Rewritten = II.second.second;
14767 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
14768 }
14769 }
14770 }
14771
setNoOverflow(Value * V,SCEVWrapPredicate::IncrementWrapFlags Flags)14772 void PredicatedScalarEvolution::setNoOverflow(
14773 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
14774 const SCEV *Expr = getSCEV(V);
14775 const auto *AR = cast<SCEVAddRecExpr>(Expr);
14776
14777 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
14778
14779 // Clear the statically implied flags.
14780 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
14781 addPredicate(*SE.getWrapPredicate(AR, Flags));
14782
14783 auto II = FlagsMap.insert({V, Flags});
14784 if (!II.second)
14785 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
14786 }
14787
hasNoOverflow(Value * V,SCEVWrapPredicate::IncrementWrapFlags Flags)14788 bool PredicatedScalarEvolution::hasNoOverflow(
14789 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
14790 const SCEV *Expr = getSCEV(V);
14791 const auto *AR = cast<SCEVAddRecExpr>(Expr);
14792
14793 Flags = SCEVWrapPredicate::clearFlags(
14794 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
14795
14796 auto II = FlagsMap.find(V);
14797
14798 if (II != FlagsMap.end())
14799 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
14800
14801 return Flags == SCEVWrapPredicate::IncrementAnyWrap;
14802 }
14803
getAsAddRec(Value * V)14804 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
14805 const SCEV *Expr = this->getSCEV(V);
14806 SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
14807 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
14808
14809 if (!New)
14810 return nullptr;
14811
14812 for (const auto *P : NewPreds)
14813 addPredicate(*P);
14814
14815 RewriteMap[SE.getSCEV(V)] = {Generation, New};
14816 return New;
14817 }
14818
PredicatedScalarEvolution(const PredicatedScalarEvolution & Init)14819 PredicatedScalarEvolution::PredicatedScalarEvolution(
14820 const PredicatedScalarEvolution &Init)
14821 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
14822 Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates())),
14823 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
14824 for (auto I : Init.FlagsMap)
14825 FlagsMap.insert(I);
14826 }
14827
print(raw_ostream & OS,unsigned Depth) const14828 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
14829 // For each block.
14830 for (auto *BB : L.getBlocks())
14831 for (auto &I : *BB) {
14832 if (!SE.isSCEVable(I.getType()))
14833 continue;
14834
14835 auto *Expr = SE.getSCEV(&I);
14836 auto II = RewriteMap.find(Expr);
14837
14838 if (II == RewriteMap.end())
14839 continue;
14840
14841 // Don't print things that are not interesting.
14842 if (II->second.second == Expr)
14843 continue;
14844
14845 OS.indent(Depth) << "[PSE]" << I << ":\n";
14846 OS.indent(Depth + 2) << *Expr << "\n";
14847 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
14848 }
14849 }
14850
14851 // Match the mathematical pattern A - (A / B) * B, where A and B can be
14852 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
14853 // for URem with constant power-of-2 second operands.
14854 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
14855 // 4, A / B becomes X / 8).
matchURem(const SCEV * Expr,const SCEV * & LHS,const SCEV * & RHS)14856 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
14857 const SCEV *&RHS) {
14858 // Try to match 'zext (trunc A to iB) to iY', which is used
14859 // for URem with constant power-of-2 second operands. Make sure the size of
14860 // the operand A matches the size of the whole expressions.
14861 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
14862 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
14863 LHS = Trunc->getOperand();
14864 // Bail out if the type of the LHS is larger than the type of the
14865 // expression for now.
14866 if (getTypeSizeInBits(LHS->getType()) >
14867 getTypeSizeInBits(Expr->getType()))
14868 return false;
14869 if (LHS->getType() != Expr->getType())
14870 LHS = getZeroExtendExpr(LHS, Expr->getType());
14871 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
14872 << getTypeSizeInBits(Trunc->getType()));
14873 return true;
14874 }
14875 const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
14876 if (Add == nullptr || Add->getNumOperands() != 2)
14877 return false;
14878
14879 const SCEV *A = Add->getOperand(1);
14880 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
14881
14882 if (Mul == nullptr)
14883 return false;
14884
14885 const auto MatchURemWithDivisor = [&](const SCEV *B) {
14886 // (SomeExpr + (-(SomeExpr / B) * B)).
14887 if (Expr == getURemExpr(A, B)) {
14888 LHS = A;
14889 RHS = B;
14890 return true;
14891 }
14892 return false;
14893 };
14894
14895 // (SomeExpr + (-1 * (SomeExpr / B) * B)).
14896 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
14897 return MatchURemWithDivisor(Mul->getOperand(1)) ||
14898 MatchURemWithDivisor(Mul->getOperand(2));
14899
14900 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
14901 if (Mul->getNumOperands() == 2)
14902 return MatchURemWithDivisor(Mul->getOperand(1)) ||
14903 MatchURemWithDivisor(Mul->getOperand(0)) ||
14904 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
14905 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
14906 return false;
14907 }
14908
14909 const SCEV *
computeSymbolicMaxBackedgeTakenCount(const Loop * L)14910 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
14911 SmallVector<BasicBlock*, 16> ExitingBlocks;
14912 L->getExitingBlocks(ExitingBlocks);
14913
14914 // Form an expression for the maximum exit count possible for this loop. We
14915 // merge the max and exact information to approximate a version of
14916 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
14917 SmallVector<const SCEV*, 4> ExitCounts;
14918 for (BasicBlock *ExitingBB : ExitingBlocks) {
14919 const SCEV *ExitCount =
14920 getExitCount(L, ExitingBB, ScalarEvolution::SymbolicMaximum);
14921 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
14922 assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
14923 "We should only have known counts for exiting blocks that "
14924 "dominate latch!");
14925 ExitCounts.push_back(ExitCount);
14926 }
14927 }
14928 if (ExitCounts.empty())
14929 return getCouldNotCompute();
14930 return getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
14931 }
14932
14933 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
14934 /// in the map. It skips AddRecExpr because we cannot guarantee that the
14935 /// replacement is loop invariant in the loop of the AddRec.
14936 ///
14937 /// At the moment only rewriting SCEVUnknown and SCEVZeroExtendExpr is
14938 /// supported.
14939 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
14940 const DenseMap<const SCEV *, const SCEV *> ⤅
14941
14942 public:
SCEVLoopGuardRewriter(ScalarEvolution & SE,DenseMap<const SCEV *,const SCEV * > & M)14943 SCEVLoopGuardRewriter(ScalarEvolution &SE,
14944 DenseMap<const SCEV *, const SCEV *> &M)
14945 : SCEVRewriteVisitor(SE), Map(M) {}
14946
visitAddRecExpr(const SCEVAddRecExpr * Expr)14947 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
14948
visitUnknown(const SCEVUnknown * Expr)14949 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14950 auto I = Map.find(Expr);
14951 if (I == Map.end())
14952 return Expr;
14953 return I->second;
14954 }
14955
visitZeroExtendExpr(const SCEVZeroExtendExpr * Expr)14956 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
14957 auto I = Map.find(Expr);
14958 if (I == Map.end())
14959 return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitZeroExtendExpr(
14960 Expr);
14961 return I->second;
14962 }
14963 };
14964
applyLoopGuards(const SCEV * Expr,const Loop * L)14965 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
14966 SmallVector<const SCEV *> ExprsToRewrite;
14967 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
14968 const SCEV *RHS,
14969 DenseMap<const SCEV *, const SCEV *>
14970 &RewriteMap) {
14971 // WARNING: It is generally unsound to apply any wrap flags to the proposed
14972 // replacement SCEV which isn't directly implied by the structure of that
14973 // SCEV. In particular, using contextual facts to imply flags is *NOT*
14974 // legal. See the scoping rules for flags in the header to understand why.
14975
14976 // If LHS is a constant, apply information to the other expression.
14977 if (isa<SCEVConstant>(LHS)) {
14978 std::swap(LHS, RHS);
14979 Predicate = CmpInst::getSwappedPredicate(Predicate);
14980 }
14981
14982 // Check for a condition of the form (-C1 + X < C2). InstCombine will
14983 // create this form when combining two checks of the form (X u< C2 + C1) and
14984 // (X >=u C1).
14985 auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap,
14986 &ExprsToRewrite]() {
14987 auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS);
14988 if (!AddExpr || AddExpr->getNumOperands() != 2)
14989 return false;
14990
14991 auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0));
14992 auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1));
14993 auto *C2 = dyn_cast<SCEVConstant>(RHS);
14994 if (!C1 || !C2 || !LHSUnknown)
14995 return false;
14996
14997 auto ExactRegion =
14998 ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt())
14999 .sub(C1->getAPInt());
15000
15001 // Bail out, unless we have a non-wrapping, monotonic range.
15002 if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet())
15003 return false;
15004 auto I = RewriteMap.find(LHSUnknown);
15005 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown;
15006 RewriteMap[LHSUnknown] = getUMaxExpr(
15007 getConstant(ExactRegion.getUnsignedMin()),
15008 getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax())));
15009 ExprsToRewrite.push_back(LHSUnknown);
15010 return true;
15011 };
15012 if (MatchRangeCheckIdiom())
15013 return;
15014
15015 // If we have LHS == 0, check if LHS is computing a property of some unknown
15016 // SCEV %v which we can rewrite %v to express explicitly.
15017 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
15018 if (Predicate == CmpInst::ICMP_EQ && RHSC &&
15019 RHSC->getValue()->isNullValue()) {
15020 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
15021 // explicitly express that.
15022 const SCEV *URemLHS = nullptr;
15023 const SCEV *URemRHS = nullptr;
15024 if (matchURem(LHS, URemLHS, URemRHS)) {
15025 if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) {
15026 const auto *Multiple = getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS);
15027 RewriteMap[LHSUnknown] = Multiple;
15028 ExprsToRewrite.push_back(LHSUnknown);
15029 return;
15030 }
15031 }
15032 }
15033
15034 // Do not apply information for constants or if RHS contains an AddRec.
15035 if (isa<SCEVConstant>(LHS) || containsAddRecurrence(RHS))
15036 return;
15037
15038 // If RHS is SCEVUnknown, make sure the information is applied to it.
15039 if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) {
15040 std::swap(LHS, RHS);
15041 Predicate = CmpInst::getSwappedPredicate(Predicate);
15042 }
15043
15044 // Limit to expressions that can be rewritten.
15045 if (!isa<SCEVUnknown>(LHS) && !isa<SCEVZeroExtendExpr>(LHS))
15046 return;
15047
15048 // Check whether LHS has already been rewritten. In that case we want to
15049 // chain further rewrites onto the already rewritten value.
15050 auto I = RewriteMap.find(LHS);
15051 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS;
15052
15053 const SCEV *RewrittenRHS = nullptr;
15054 switch (Predicate) {
15055 case CmpInst::ICMP_ULT:
15056 RewrittenRHS =
15057 getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
15058 break;
15059 case CmpInst::ICMP_SLT:
15060 RewrittenRHS =
15061 getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
15062 break;
15063 case CmpInst::ICMP_ULE:
15064 RewrittenRHS = getUMinExpr(RewrittenLHS, RHS);
15065 break;
15066 case CmpInst::ICMP_SLE:
15067 RewrittenRHS = getSMinExpr(RewrittenLHS, RHS);
15068 break;
15069 case CmpInst::ICMP_UGT:
15070 RewrittenRHS =
15071 getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
15072 break;
15073 case CmpInst::ICMP_SGT:
15074 RewrittenRHS =
15075 getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
15076 break;
15077 case CmpInst::ICMP_UGE:
15078 RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS);
15079 break;
15080 case CmpInst::ICMP_SGE:
15081 RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS);
15082 break;
15083 case CmpInst::ICMP_EQ:
15084 if (isa<SCEVConstant>(RHS))
15085 RewrittenRHS = RHS;
15086 break;
15087 case CmpInst::ICMP_NE:
15088 if (isa<SCEVConstant>(RHS) &&
15089 cast<SCEVConstant>(RHS)->getValue()->isNullValue())
15090 RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType()));
15091 break;
15092 default:
15093 break;
15094 }
15095
15096 if (RewrittenRHS) {
15097 RewriteMap[LHS] = RewrittenRHS;
15098 if (LHS == RewrittenLHS)
15099 ExprsToRewrite.push_back(LHS);
15100 }
15101 };
15102
15103 BasicBlock *Header = L->getHeader();
15104 SmallVector<PointerIntPair<Value *, 1, bool>> Terms;
15105 // First, collect information from assumptions dominating the loop.
15106 for (auto &AssumeVH : AC.assumptions()) {
15107 if (!AssumeVH)
15108 continue;
15109 auto *AssumeI = cast<CallInst>(AssumeVH);
15110 if (!DT.dominates(AssumeI, Header))
15111 continue;
15112 Terms.emplace_back(AssumeI->getOperand(0), true);
15113 }
15114
15115 // Second, collect conditions from dominating branches. Starting at the loop
15116 // predecessor, climb up the predecessor chain, as long as there are
15117 // predecessors that can be found that have unique successors leading to the
15118 // original header.
15119 // TODO: share this logic with isLoopEntryGuardedByCond.
15120 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
15121 L->getLoopPredecessor(), Header);
15122 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
15123
15124 const BranchInst *LoopEntryPredicate =
15125 dyn_cast<BranchInst>(Pair.first->getTerminator());
15126 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
15127 continue;
15128
15129 Terms.emplace_back(LoopEntryPredicate->getCondition(),
15130 LoopEntryPredicate->getSuccessor(0) == Pair.second);
15131 }
15132
15133 // Now apply the information from the collected conditions to RewriteMap.
15134 // Conditions are processed in reverse order, so the earliest conditions is
15135 // processed first. This ensures the SCEVs with the shortest dependency chains
15136 // are constructed first.
15137 DenseMap<const SCEV *, const SCEV *> RewriteMap;
15138 for (auto [Term, EnterIfTrue] : reverse(Terms)) {
15139 SmallVector<Value *, 8> Worklist;
15140 SmallPtrSet<Value *, 8> Visited;
15141 Worklist.push_back(Term);
15142 while (!Worklist.empty()) {
15143 Value *Cond = Worklist.pop_back_val();
15144 if (!Visited.insert(Cond).second)
15145 continue;
15146
15147 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
15148 auto Predicate =
15149 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
15150 const auto *LHS = getSCEV(Cmp->getOperand(0));
15151 const auto *RHS = getSCEV(Cmp->getOperand(1));
15152 CollectCondition(Predicate, LHS, RHS, RewriteMap);
15153 continue;
15154 }
15155
15156 Value *L, *R;
15157 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
15158 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
15159 Worklist.push_back(L);
15160 Worklist.push_back(R);
15161 }
15162 }
15163 }
15164
15165 if (RewriteMap.empty())
15166 return Expr;
15167
15168 // Now that all rewrite information is collect, rewrite the collected
15169 // expressions with the information in the map. This applies information to
15170 // sub-expressions.
15171 if (ExprsToRewrite.size() > 1) {
15172 for (const SCEV *Expr : ExprsToRewrite) {
15173 const SCEV *RewriteTo = RewriteMap[Expr];
15174 RewriteMap.erase(Expr);
15175 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
15176 RewriteMap.insert({Expr, Rewriter.visit(RewriteTo)});
15177 }
15178 }
15179
15180 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
15181 return Rewriter.visit(Expr);
15182 }
15183