• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/None.h"
68 #include "llvm/ADT/Optional.h"
69 #include "llvm/ADT/STLExtras.h"
70 #include "llvm/ADT/ScopeExit.h"
71 #include "llvm/ADT/Sequence.h"
72 #include "llvm/ADT/SetVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallSet.h"
75 #include "llvm/ADT/SmallVector.h"
76 #include "llvm/ADT/Statistic.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/Analysis/AssumptionCache.h"
79 #include "llvm/Analysis/ConstantFolding.h"
80 #include "llvm/Analysis/InstructionSimplify.h"
81 #include "llvm/Analysis/LoopInfo.h"
82 #include "llvm/Analysis/ScalarEvolutionDivision.h"
83 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
84 #include "llvm/Analysis/TargetLibraryInfo.h"
85 #include "llvm/Analysis/ValueTracking.h"
86 #include "llvm/Config/llvm-config.h"
87 #include "llvm/IR/Argument.h"
88 #include "llvm/IR/BasicBlock.h"
89 #include "llvm/IR/CFG.h"
90 #include "llvm/IR/Constant.h"
91 #include "llvm/IR/ConstantRange.h"
92 #include "llvm/IR/Constants.h"
93 #include "llvm/IR/DataLayout.h"
94 #include "llvm/IR/DerivedTypes.h"
95 #include "llvm/IR/Dominators.h"
96 #include "llvm/IR/Function.h"
97 #include "llvm/IR/GlobalAlias.h"
98 #include "llvm/IR/GlobalValue.h"
99 #include "llvm/IR/GlobalVariable.h"
100 #include "llvm/IR/InstIterator.h"
101 #include "llvm/IR/InstrTypes.h"
102 #include "llvm/IR/Instruction.h"
103 #include "llvm/IR/Instructions.h"
104 #include "llvm/IR/IntrinsicInst.h"
105 #include "llvm/IR/Intrinsics.h"
106 #include "llvm/IR/LLVMContext.h"
107 #include "llvm/IR/Metadata.h"
108 #include "llvm/IR/Operator.h"
109 #include "llvm/IR/PatternMatch.h"
110 #include "llvm/IR/Type.h"
111 #include "llvm/IR/Use.h"
112 #include "llvm/IR/User.h"
113 #include "llvm/IR/Value.h"
114 #include "llvm/IR/Verifier.h"
115 #include "llvm/InitializePasses.h"
116 #include "llvm/Pass.h"
117 #include "llvm/Support/Casting.h"
118 #include "llvm/Support/CommandLine.h"
119 #include "llvm/Support/Compiler.h"
120 #include "llvm/Support/Debug.h"
121 #include "llvm/Support/ErrorHandling.h"
122 #include "llvm/Support/KnownBits.h"
123 #include "llvm/Support/SaveAndRestore.h"
124 #include "llvm/Support/raw_ostream.h"
125 #include <algorithm>
126 #include <cassert>
127 #include <climits>
128 #include <cstddef>
129 #include <cstdint>
130 #include <cstdlib>
131 #include <map>
132 #include <memory>
133 #include <tuple>
134 #include <utility>
135 #include <vector>
136 
137 using namespace llvm;
138 
139 #define DEBUG_TYPE "scalar-evolution"
140 
141 STATISTIC(NumArrayLenItCounts,
142           "Number of trip counts computed with array length");
143 STATISTIC(NumTripCountsComputed,
144           "Number of loops with predictable loop counts");
145 STATISTIC(NumTripCountsNotComputed,
146           "Number of loops without predictable loop counts");
147 STATISTIC(NumBruteForceTripCountsComputed,
148           "Number of loops with trip counts computed by force");
149 
150 static cl::opt<unsigned>
151 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
152                         cl::ZeroOrMore,
153                         cl::desc("Maximum number of iterations SCEV will "
154                                  "symbolically execute a constant "
155                                  "derived loop"),
156                         cl::init(100));
157 
158 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
159 static cl::opt<bool> VerifySCEV(
160     "verify-scev", cl::Hidden,
161     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
162 static cl::opt<bool> VerifySCEVStrict(
163     "verify-scev-strict", cl::Hidden,
164     cl::desc("Enable stricter verification with -verify-scev is passed"));
165 static cl::opt<bool>
166     VerifySCEVMap("verify-scev-maps", cl::Hidden,
167                   cl::desc("Verify no dangling value in ScalarEvolution's "
168                            "ExprValueMap (slow)"));
169 
170 static cl::opt<bool> VerifyIR(
171     "scev-verify-ir", cl::Hidden,
172     cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
173     cl::init(false));
174 
175 static cl::opt<unsigned> MulOpsInlineThreshold(
176     "scev-mulops-inline-threshold", cl::Hidden,
177     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
178     cl::init(32));
179 
180 static cl::opt<unsigned> AddOpsInlineThreshold(
181     "scev-addops-inline-threshold", cl::Hidden,
182     cl::desc("Threshold for inlining addition operands into a SCEV"),
183     cl::init(500));
184 
185 static cl::opt<unsigned> MaxSCEVCompareDepth(
186     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
187     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
188     cl::init(32));
189 
190 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
191     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
192     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
193     cl::init(2));
194 
195 static cl::opt<unsigned> MaxValueCompareDepth(
196     "scalar-evolution-max-value-compare-depth", cl::Hidden,
197     cl::desc("Maximum depth of recursive value complexity comparisons"),
198     cl::init(2));
199 
200 static cl::opt<unsigned>
201     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
202                   cl::desc("Maximum depth of recursive arithmetics"),
203                   cl::init(32));
204 
205 static cl::opt<unsigned> MaxConstantEvolvingDepth(
206     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
207     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
208 
209 static cl::opt<unsigned>
210     MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
211                  cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
212                  cl::init(8));
213 
214 static cl::opt<unsigned>
215     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
216                   cl::desc("Max coefficients in AddRec during evolving"),
217                   cl::init(8));
218 
219 static cl::opt<unsigned>
220     HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
221                   cl::desc("Size of the expression which is considered huge"),
222                   cl::init(4096));
223 
224 static cl::opt<bool>
225 ClassifyExpressions("scalar-evolution-classify-expressions",
226     cl::Hidden, cl::init(true),
227     cl::desc("When printing analysis, include information on every instruction"));
228 
229 static cl::opt<bool> UseExpensiveRangeSharpening(
230     "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
231     cl::init(false),
232     cl::desc("Use more powerful methods of sharpening expression ranges. May "
233              "be costly in terms of compile time"));
234 
235 //===----------------------------------------------------------------------===//
236 //                           SCEV class definitions
237 //===----------------------------------------------------------------------===//
238 
239 //===----------------------------------------------------------------------===//
240 // Implementation of the SCEV class.
241 //
242 
243 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const244 LLVM_DUMP_METHOD void SCEV::dump() const {
245   print(dbgs());
246   dbgs() << '\n';
247 }
248 #endif
249 
print(raw_ostream & OS) const250 void SCEV::print(raw_ostream &OS) const {
251   switch (getSCEVType()) {
252   case scConstant:
253     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
254     return;
255   case scPtrToInt: {
256     const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this);
257     const SCEV *Op = PtrToInt->getOperand();
258     OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to "
259        << *PtrToInt->getType() << ")";
260     return;
261   }
262   case scTruncate: {
263     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
264     const SCEV *Op = Trunc->getOperand();
265     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
266        << *Trunc->getType() << ")";
267     return;
268   }
269   case scZeroExtend: {
270     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
271     const SCEV *Op = ZExt->getOperand();
272     OS << "(zext " << *Op->getType() << " " << *Op << " to "
273        << *ZExt->getType() << ")";
274     return;
275   }
276   case scSignExtend: {
277     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
278     const SCEV *Op = SExt->getOperand();
279     OS << "(sext " << *Op->getType() << " " << *Op << " to "
280        << *SExt->getType() << ")";
281     return;
282   }
283   case scAddRecExpr: {
284     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
285     OS << "{" << *AR->getOperand(0);
286     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
287       OS << ",+," << *AR->getOperand(i);
288     OS << "}<";
289     if (AR->hasNoUnsignedWrap())
290       OS << "nuw><";
291     if (AR->hasNoSignedWrap())
292       OS << "nsw><";
293     if (AR->hasNoSelfWrap() &&
294         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
295       OS << "nw><";
296     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
297     OS << ">";
298     return;
299   }
300   case scAddExpr:
301   case scMulExpr:
302   case scUMaxExpr:
303   case scSMaxExpr:
304   case scUMinExpr:
305   case scSMinExpr: {
306     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
307     const char *OpStr = nullptr;
308     switch (NAry->getSCEVType()) {
309     case scAddExpr: OpStr = " + "; break;
310     case scMulExpr: OpStr = " * "; break;
311     case scUMaxExpr: OpStr = " umax "; break;
312     case scSMaxExpr: OpStr = " smax "; break;
313     case scUMinExpr:
314       OpStr = " umin ";
315       break;
316     case scSMinExpr:
317       OpStr = " smin ";
318       break;
319     default:
320       llvm_unreachable("There are no other nary expression types.");
321     }
322     OS << "(";
323     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
324          I != E; ++I) {
325       OS << **I;
326       if (std::next(I) != E)
327         OS << OpStr;
328     }
329     OS << ")";
330     switch (NAry->getSCEVType()) {
331     case scAddExpr:
332     case scMulExpr:
333       if (NAry->hasNoUnsignedWrap())
334         OS << "<nuw>";
335       if (NAry->hasNoSignedWrap())
336         OS << "<nsw>";
337       break;
338     default:
339       // Nothing to print for other nary expressions.
340       break;
341     }
342     return;
343   }
344   case scUDivExpr: {
345     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
346     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
347     return;
348   }
349   case scUnknown: {
350     const SCEVUnknown *U = cast<SCEVUnknown>(this);
351     Type *AllocTy;
352     if (U->isSizeOf(AllocTy)) {
353       OS << "sizeof(" << *AllocTy << ")";
354       return;
355     }
356     if (U->isAlignOf(AllocTy)) {
357       OS << "alignof(" << *AllocTy << ")";
358       return;
359     }
360 
361     Type *CTy;
362     Constant *FieldNo;
363     if (U->isOffsetOf(CTy, FieldNo)) {
364       OS << "offsetof(" << *CTy << ", ";
365       FieldNo->printAsOperand(OS, false);
366       OS << ")";
367       return;
368     }
369 
370     // Otherwise just print it normally.
371     U->getValue()->printAsOperand(OS, false);
372     return;
373   }
374   case scCouldNotCompute:
375     OS << "***COULDNOTCOMPUTE***";
376     return;
377   }
378   llvm_unreachable("Unknown SCEV kind!");
379 }
380 
getType() const381 Type *SCEV::getType() const {
382   switch (getSCEVType()) {
383   case scConstant:
384     return cast<SCEVConstant>(this)->getType();
385   case scPtrToInt:
386   case scTruncate:
387   case scZeroExtend:
388   case scSignExtend:
389     return cast<SCEVCastExpr>(this)->getType();
390   case scAddRecExpr:
391   case scMulExpr:
392   case scUMaxExpr:
393   case scSMaxExpr:
394   case scUMinExpr:
395   case scSMinExpr:
396     return cast<SCEVNAryExpr>(this)->getType();
397   case scAddExpr:
398     return cast<SCEVAddExpr>(this)->getType();
399   case scUDivExpr:
400     return cast<SCEVUDivExpr>(this)->getType();
401   case scUnknown:
402     return cast<SCEVUnknown>(this)->getType();
403   case scCouldNotCompute:
404     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
405   }
406   llvm_unreachable("Unknown SCEV kind!");
407 }
408 
isZero() const409 bool SCEV::isZero() const {
410   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
411     return SC->getValue()->isZero();
412   return false;
413 }
414 
isOne() const415 bool SCEV::isOne() const {
416   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
417     return SC->getValue()->isOne();
418   return false;
419 }
420 
isAllOnesValue() const421 bool SCEV::isAllOnesValue() const {
422   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
423     return SC->getValue()->isMinusOne();
424   return false;
425 }
426 
isNonConstantNegative() const427 bool SCEV::isNonConstantNegative() const {
428   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
429   if (!Mul) return false;
430 
431   // If there is a constant factor, it will be first.
432   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
433   if (!SC) return false;
434 
435   // Return true if the value is negative, this matches things like (-42 * V).
436   return SC->getAPInt().isNegative();
437 }
438 
SCEVCouldNotCompute()439 SCEVCouldNotCompute::SCEVCouldNotCompute() :
440   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
441 
classof(const SCEV * S)442 bool SCEVCouldNotCompute::classof(const SCEV *S) {
443   return S->getSCEVType() == scCouldNotCompute;
444 }
445 
getConstant(ConstantInt * V)446 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
447   FoldingSetNodeID ID;
448   ID.AddInteger(scConstant);
449   ID.AddPointer(V);
450   void *IP = nullptr;
451   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
452   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
453   UniqueSCEVs.InsertNode(S, IP);
454   return S;
455 }
456 
getConstant(const APInt & Val)457 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
458   return getConstant(ConstantInt::get(getContext(), Val));
459 }
460 
461 const SCEV *
getConstant(Type * Ty,uint64_t V,bool isSigned)462 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
463   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
464   return getConstant(ConstantInt::get(ITy, V, isSigned));
465 }
466 
SCEVCastExpr(const FoldingSetNodeIDRef ID,SCEVTypes SCEVTy,const SCEV * op,Type * ty)467 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
468                            const SCEV *op, Type *ty)
469     : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) {
470   Operands[0] = op;
471 }
472 
SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID,const SCEV * Op,Type * ITy)473 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op,
474                                    Type *ITy)
475     : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
476   assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
477          "Must be a non-bit-width-changing pointer-to-integer cast!");
478 }
479 
SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,SCEVTypes SCEVTy,const SCEV * op,Type * ty)480 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,
481                                            SCEVTypes SCEVTy, const SCEV *op,
482                                            Type *ty)
483     : SCEVCastExpr(ID, SCEVTy, op, ty) {}
484 
SCEVTruncateExpr(const FoldingSetNodeIDRef ID,const SCEV * op,Type * ty)485 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op,
486                                    Type *ty)
487     : SCEVIntegralCastExpr(ID, scTruncate, op, ty) {
488   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
489          "Cannot truncate non-integer value!");
490 }
491 
SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,const SCEV * op,Type * ty)492 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
493                                        const SCEV *op, Type *ty)
494     : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) {
495   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
496          "Cannot zero extend non-integer value!");
497 }
498 
SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,const SCEV * op,Type * ty)499 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
500                                        const SCEV *op, Type *ty)
501     : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) {
502   assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
503          "Cannot sign extend non-integer value!");
504 }
505 
deleted()506 void SCEVUnknown::deleted() {
507   // Clear this SCEVUnknown from various maps.
508   SE->forgetMemoizedResults(this);
509 
510   // Remove this SCEVUnknown from the uniquing map.
511   SE->UniqueSCEVs.RemoveNode(this);
512 
513   // Release the value.
514   setValPtr(nullptr);
515 }
516 
allUsesReplacedWith(Value * New)517 void SCEVUnknown::allUsesReplacedWith(Value *New) {
518   // Remove this SCEVUnknown from the uniquing map.
519   SE->UniqueSCEVs.RemoveNode(this);
520 
521   // Update this SCEVUnknown to point to the new value. This is needed
522   // because there may still be outstanding SCEVs which still point to
523   // this SCEVUnknown.
524   setValPtr(New);
525 }
526 
isSizeOf(Type * & AllocTy) const527 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
528   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
529     if (VCE->getOpcode() == Instruction::PtrToInt)
530       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
531         if (CE->getOpcode() == Instruction::GetElementPtr &&
532             CE->getOperand(0)->isNullValue() &&
533             CE->getNumOperands() == 2)
534           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
535             if (CI->isOne()) {
536               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
537                                  ->getElementType();
538               return true;
539             }
540 
541   return false;
542 }
543 
isAlignOf(Type * & AllocTy) const544 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
545   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
546     if (VCE->getOpcode() == Instruction::PtrToInt)
547       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
548         if (CE->getOpcode() == Instruction::GetElementPtr &&
549             CE->getOperand(0)->isNullValue()) {
550           Type *Ty =
551             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
552           if (StructType *STy = dyn_cast<StructType>(Ty))
553             if (!STy->isPacked() &&
554                 CE->getNumOperands() == 3 &&
555                 CE->getOperand(1)->isNullValue()) {
556               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
557                 if (CI->isOne() &&
558                     STy->getNumElements() == 2 &&
559                     STy->getElementType(0)->isIntegerTy(1)) {
560                   AllocTy = STy->getElementType(1);
561                   return true;
562                 }
563             }
564         }
565 
566   return false;
567 }
568 
isOffsetOf(Type * & CTy,Constant * & FieldNo) const569 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
570   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
571     if (VCE->getOpcode() == Instruction::PtrToInt)
572       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
573         if (CE->getOpcode() == Instruction::GetElementPtr &&
574             CE->getNumOperands() == 3 &&
575             CE->getOperand(0)->isNullValue() &&
576             CE->getOperand(1)->isNullValue()) {
577           Type *Ty =
578             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
579           // Ignore vector types here so that ScalarEvolutionExpander doesn't
580           // emit getelementptrs that index into vectors.
581           if (Ty->isStructTy() || Ty->isArrayTy()) {
582             CTy = Ty;
583             FieldNo = CE->getOperand(2);
584             return true;
585           }
586         }
587 
588   return false;
589 }
590 
591 //===----------------------------------------------------------------------===//
592 //                               SCEV Utilities
593 //===----------------------------------------------------------------------===//
594 
595 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
596 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
597 /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
598 /// have been previously deemed to be "equally complex" by this routine.  It is
599 /// intended to avoid exponential time complexity in cases like:
600 ///
601 ///   %a = f(%x, %y)
602 ///   %b = f(%a, %a)
603 ///   %c = f(%b, %b)
604 ///
605 ///   %d = f(%x, %y)
606 ///   %e = f(%d, %d)
607 ///   %f = f(%e, %e)
608 ///
609 ///   CompareValueComplexity(%f, %c)
610 ///
611 /// Since we do not continue running this routine on expression trees once we
612 /// have seen unequal values, there is no need to track them in the cache.
613 static int
CompareValueComplexity(EquivalenceClasses<const Value * > & EqCacheValue,const LoopInfo * const LI,Value * LV,Value * RV,unsigned Depth)614 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
615                        const LoopInfo *const LI, Value *LV, Value *RV,
616                        unsigned Depth) {
617   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
618     return 0;
619 
620   // Order pointer values after integer values. This helps SCEVExpander form
621   // GEPs.
622   bool LIsPointer = LV->getType()->isPointerTy(),
623        RIsPointer = RV->getType()->isPointerTy();
624   if (LIsPointer != RIsPointer)
625     return (int)LIsPointer - (int)RIsPointer;
626 
627   // Compare getValueID values.
628   unsigned LID = LV->getValueID(), RID = RV->getValueID();
629   if (LID != RID)
630     return (int)LID - (int)RID;
631 
632   // Sort arguments by their position.
633   if (const auto *LA = dyn_cast<Argument>(LV)) {
634     const auto *RA = cast<Argument>(RV);
635     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
636     return (int)LArgNo - (int)RArgNo;
637   }
638 
639   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
640     const auto *RGV = cast<GlobalValue>(RV);
641 
642     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
643       auto LT = GV->getLinkage();
644       return !(GlobalValue::isPrivateLinkage(LT) ||
645                GlobalValue::isInternalLinkage(LT));
646     };
647 
648     // Use the names to distinguish the two values, but only if the
649     // names are semantically important.
650     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
651       return LGV->getName().compare(RGV->getName());
652   }
653 
654   // For instructions, compare their loop depth, and their operand count.  This
655   // is pretty loose.
656   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
657     const auto *RInst = cast<Instruction>(RV);
658 
659     // Compare loop depths.
660     const BasicBlock *LParent = LInst->getParent(),
661                      *RParent = RInst->getParent();
662     if (LParent != RParent) {
663       unsigned LDepth = LI->getLoopDepth(LParent),
664                RDepth = LI->getLoopDepth(RParent);
665       if (LDepth != RDepth)
666         return (int)LDepth - (int)RDepth;
667     }
668 
669     // Compare the number of operands.
670     unsigned LNumOps = LInst->getNumOperands(),
671              RNumOps = RInst->getNumOperands();
672     if (LNumOps != RNumOps)
673       return (int)LNumOps - (int)RNumOps;
674 
675     for (unsigned Idx : seq(0u, LNumOps)) {
676       int Result =
677           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
678                                  RInst->getOperand(Idx), Depth + 1);
679       if (Result != 0)
680         return Result;
681     }
682   }
683 
684   EqCacheValue.unionSets(LV, RV);
685   return 0;
686 }
687 
688 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
689 // than RHS, respectively. A three-way result allows recursive comparisons to be
690 // more efficient.
CompareSCEVComplexity(EquivalenceClasses<const SCEV * > & EqCacheSCEV,EquivalenceClasses<const Value * > & EqCacheValue,const LoopInfo * const LI,const SCEV * LHS,const SCEV * RHS,DominatorTree & DT,unsigned Depth=0)691 static int CompareSCEVComplexity(
692     EquivalenceClasses<const SCEV *> &EqCacheSCEV,
693     EquivalenceClasses<const Value *> &EqCacheValue,
694     const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
695     DominatorTree &DT, unsigned Depth = 0) {
696   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
697   if (LHS == RHS)
698     return 0;
699 
700   // Primarily, sort the SCEVs by their getSCEVType().
701   SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
702   if (LType != RType)
703     return (int)LType - (int)RType;
704 
705   if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS))
706     return 0;
707   // Aside from the getSCEVType() ordering, the particular ordering
708   // isn't very important except that it's beneficial to be consistent,
709   // so that (a + b) and (b + a) don't end up as different expressions.
710   switch (LType) {
711   case scUnknown: {
712     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
713     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
714 
715     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
716                                    RU->getValue(), Depth + 1);
717     if (X == 0)
718       EqCacheSCEV.unionSets(LHS, RHS);
719     return X;
720   }
721 
722   case scConstant: {
723     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
724     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
725 
726     // Compare constant values.
727     const APInt &LA = LC->getAPInt();
728     const APInt &RA = RC->getAPInt();
729     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
730     if (LBitWidth != RBitWidth)
731       return (int)LBitWidth - (int)RBitWidth;
732     return LA.ult(RA) ? -1 : 1;
733   }
734 
735   case scAddRecExpr: {
736     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
737     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
738 
739     // There is always a dominance between two recs that are used by one SCEV,
740     // so we can safely sort recs by loop header dominance. We require such
741     // order in getAddExpr.
742     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
743     if (LLoop != RLoop) {
744       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
745       assert(LHead != RHead && "Two loops share the same header?");
746       if (DT.dominates(LHead, RHead))
747         return 1;
748       else
749         assert(DT.dominates(RHead, LHead) &&
750                "No dominance between recurrences used by one SCEV?");
751       return -1;
752     }
753 
754     // Addrec complexity grows with operand count.
755     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
756     if (LNumOps != RNumOps)
757       return (int)LNumOps - (int)RNumOps;
758 
759     // Lexicographically compare.
760     for (unsigned i = 0; i != LNumOps; ++i) {
761       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
762                                     LA->getOperand(i), RA->getOperand(i), DT,
763                                     Depth + 1);
764       if (X != 0)
765         return X;
766     }
767     EqCacheSCEV.unionSets(LHS, RHS);
768     return 0;
769   }
770 
771   case scAddExpr:
772   case scMulExpr:
773   case scSMaxExpr:
774   case scUMaxExpr:
775   case scSMinExpr:
776   case scUMinExpr: {
777     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
778     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
779 
780     // Lexicographically compare n-ary expressions.
781     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
782     if (LNumOps != RNumOps)
783       return (int)LNumOps - (int)RNumOps;
784 
785     for (unsigned i = 0; i != LNumOps; ++i) {
786       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
787                                     LC->getOperand(i), RC->getOperand(i), DT,
788                                     Depth + 1);
789       if (X != 0)
790         return X;
791     }
792     EqCacheSCEV.unionSets(LHS, RHS);
793     return 0;
794   }
795 
796   case scUDivExpr: {
797     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
798     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
799 
800     // Lexicographically compare udiv expressions.
801     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
802                                   RC->getLHS(), DT, Depth + 1);
803     if (X != 0)
804       return X;
805     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
806                               RC->getRHS(), DT, Depth + 1);
807     if (X == 0)
808       EqCacheSCEV.unionSets(LHS, RHS);
809     return X;
810   }
811 
812   case scPtrToInt:
813   case scTruncate:
814   case scZeroExtend:
815   case scSignExtend: {
816     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
817     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
818 
819     // Compare cast expressions by operand.
820     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
821                                   LC->getOperand(), RC->getOperand(), DT,
822                                   Depth + 1);
823     if (X == 0)
824       EqCacheSCEV.unionSets(LHS, RHS);
825     return X;
826   }
827 
828   case scCouldNotCompute:
829     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
830   }
831   llvm_unreachable("Unknown SCEV kind!");
832 }
833 
834 /// Given a list of SCEV objects, order them by their complexity, and group
835 /// objects of the same complexity together by value.  When this routine is
836 /// finished, we know that any duplicates in the vector are consecutive and that
837 /// complexity is monotonically increasing.
838 ///
839 /// Note that we go take special precautions to ensure that we get deterministic
840 /// results from this routine.  In other words, we don't want the results of
841 /// this to depend on where the addresses of various SCEV objects happened to
842 /// land in memory.
GroupByComplexity(SmallVectorImpl<const SCEV * > & Ops,LoopInfo * LI,DominatorTree & DT)843 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
844                               LoopInfo *LI, DominatorTree &DT) {
845   if (Ops.size() < 2) return;  // Noop
846 
847   EquivalenceClasses<const SCEV *> EqCacheSCEV;
848   EquivalenceClasses<const Value *> EqCacheValue;
849   if (Ops.size() == 2) {
850     // This is the common case, which also happens to be trivially simple.
851     // Special case it.
852     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
853     if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0)
854       std::swap(LHS, RHS);
855     return;
856   }
857 
858   // Do the rough sort by complexity.
859   llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
860     return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) <
861            0;
862   });
863 
864   // Now that we are sorted by complexity, group elements of the same
865   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
866   // be extremely short in practice.  Note that we take this approach because we
867   // do not want to depend on the addresses of the objects we are grouping.
868   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
869     const SCEV *S = Ops[i];
870     unsigned Complexity = S->getSCEVType();
871 
872     // If there are any objects of the same complexity and same value as this
873     // one, group them.
874     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
875       if (Ops[j] == S) { // Found a duplicate.
876         // Move it to immediately after i'th element.
877         std::swap(Ops[i+1], Ops[j]);
878         ++i;   // no need to rescan it.
879         if (i == e-2) return;  // Done!
880       }
881     }
882   }
883 }
884 
885 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
886 /// least HugeExprThreshold nodes).
hasHugeExpression(ArrayRef<const SCEV * > Ops)887 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
888   return any_of(Ops, [](const SCEV *S) {
889     return S->getExpressionSize() >= HugeExprThreshold;
890   });
891 }
892 
893 //===----------------------------------------------------------------------===//
894 //                      Simple SCEV method implementations
895 //===----------------------------------------------------------------------===//
896 
897 /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
BinomialCoefficient(const SCEV * It,unsigned K,ScalarEvolution & SE,Type * ResultTy)898 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
899                                        ScalarEvolution &SE,
900                                        Type *ResultTy) {
901   // Handle the simplest case efficiently.
902   if (K == 1)
903     return SE.getTruncateOrZeroExtend(It, ResultTy);
904 
905   // We are using the following formula for BC(It, K):
906   //
907   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
908   //
909   // Suppose, W is the bitwidth of the return value.  We must be prepared for
910   // overflow.  Hence, we must assure that the result of our computation is
911   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
912   // safe in modular arithmetic.
913   //
914   // However, this code doesn't use exactly that formula; the formula it uses
915   // is something like the following, where T is the number of factors of 2 in
916   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
917   // exponentiation:
918   //
919   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
920   //
921   // This formula is trivially equivalent to the previous formula.  However,
922   // this formula can be implemented much more efficiently.  The trick is that
923   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
924   // arithmetic.  To do exact division in modular arithmetic, all we have
925   // to do is multiply by the inverse.  Therefore, this step can be done at
926   // width W.
927   //
928   // The next issue is how to safely do the division by 2^T.  The way this
929   // is done is by doing the multiplication step at a width of at least W + T
930   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
931   // when we perform the division by 2^T (which is equivalent to a right shift
932   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
933   // truncated out after the division by 2^T.
934   //
935   // In comparison to just directly using the first formula, this technique
936   // is much more efficient; using the first formula requires W * K bits,
937   // but this formula less than W + K bits. Also, the first formula requires
938   // a division step, whereas this formula only requires multiplies and shifts.
939   //
940   // It doesn't matter whether the subtraction step is done in the calculation
941   // width or the input iteration count's width; if the subtraction overflows,
942   // the result must be zero anyway.  We prefer here to do it in the width of
943   // the induction variable because it helps a lot for certain cases; CodeGen
944   // isn't smart enough to ignore the overflow, which leads to much less
945   // efficient code if the width of the subtraction is wider than the native
946   // register width.
947   //
948   // (It's possible to not widen at all by pulling out factors of 2 before
949   // the multiplication; for example, K=2 can be calculated as
950   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
951   // extra arithmetic, so it's not an obvious win, and it gets
952   // much more complicated for K > 3.)
953 
954   // Protection from insane SCEVs; this bound is conservative,
955   // but it probably doesn't matter.
956   if (K > 1000)
957     return SE.getCouldNotCompute();
958 
959   unsigned W = SE.getTypeSizeInBits(ResultTy);
960 
961   // Calculate K! / 2^T and T; we divide out the factors of two before
962   // multiplying for calculating K! / 2^T to avoid overflow.
963   // Other overflow doesn't matter because we only care about the bottom
964   // W bits of the result.
965   APInt OddFactorial(W, 1);
966   unsigned T = 1;
967   for (unsigned i = 3; i <= K; ++i) {
968     APInt Mult(W, i);
969     unsigned TwoFactors = Mult.countTrailingZeros();
970     T += TwoFactors;
971     Mult.lshrInPlace(TwoFactors);
972     OddFactorial *= Mult;
973   }
974 
975   // We need at least W + T bits for the multiplication step
976   unsigned CalculationBits = W + T;
977 
978   // Calculate 2^T, at width T+W.
979   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
980 
981   // Calculate the multiplicative inverse of K! / 2^T;
982   // this multiplication factor will perform the exact division by
983   // K! / 2^T.
984   APInt Mod = APInt::getSignedMinValue(W+1);
985   APInt MultiplyFactor = OddFactorial.zext(W+1);
986   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
987   MultiplyFactor = MultiplyFactor.trunc(W);
988 
989   // Calculate the product, at width T+W
990   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
991                                                       CalculationBits);
992   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
993   for (unsigned i = 1; i != K; ++i) {
994     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
995     Dividend = SE.getMulExpr(Dividend,
996                              SE.getTruncateOrZeroExtend(S, CalculationTy));
997   }
998 
999   // Divide by 2^T
1000   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1001 
1002   // Truncate the result, and divide by K! / 2^T.
1003 
1004   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1005                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1006 }
1007 
1008 /// Return the value of this chain of recurrences at the specified iteration
1009 /// number.  We can evaluate this recurrence by multiplying each element in the
1010 /// chain by the binomial coefficient corresponding to it.  In other words, we
1011 /// can evaluate {A,+,B,+,C,+,D} as:
1012 ///
1013 ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1014 ///
1015 /// where BC(It, k) stands for binomial coefficient.
evaluateAtIteration(const SCEV * It,ScalarEvolution & SE) const1016 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1017                                                 ScalarEvolution &SE) const {
1018   const SCEV *Result = getStart();
1019   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1020     // The computation is correct in the face of overflow provided that the
1021     // multiplication is performed _after_ the evaluation of the binomial
1022     // coefficient.
1023     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1024     if (isa<SCEVCouldNotCompute>(Coeff))
1025       return Coeff;
1026 
1027     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1028   }
1029   return Result;
1030 }
1031 
1032 //===----------------------------------------------------------------------===//
1033 //                    SCEV Expression folder implementations
1034 //===----------------------------------------------------------------------===//
1035 
getPtrToIntExpr(const SCEV * Op,Type * Ty,unsigned Depth)1036 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty,
1037                                              unsigned Depth) {
1038   assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1039   assert(Depth <= 1 && "getPtrToIntExpr() should self-recurse at most once.");
1040 
1041   // We could be called with an integer-typed operands during SCEV rewrites.
1042   // Since the operand is an integer already, just perform zext/trunc/self cast.
1043   if (!Op->getType()->isPointerTy())
1044     return getTruncateOrZeroExtend(Op, Ty);
1045 
1046   // What would be an ID for such a SCEV cast expression?
1047   FoldingSetNodeID ID;
1048   ID.AddInteger(scPtrToInt);
1049   ID.AddPointer(Op);
1050 
1051   void *IP = nullptr;
1052 
1053   // Is there already an expression for such a cast?
1054   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1055     return getTruncateOrZeroExtend(S, Ty);
1056 
1057   // If not, is this expression something we can't reduce any further?
1058   if (isa<SCEVUnknown>(Op)) {
1059     // Create an explicit cast node.
1060     // We can reuse the existing insert position since if we get here,
1061     // we won't have made any changes which would invalidate it.
1062     Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1063     assert(getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(
1064                Op->getType())) == getDataLayout().getTypeSizeInBits(IntPtrTy) &&
1065            "We can only model ptrtoint if SCEV's effective (integer) type is "
1066            "sufficiently wide to represent all possible pointer values.");
1067     SCEV *S = new (SCEVAllocator)
1068         SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1069     UniqueSCEVs.InsertNode(S, IP);
1070     addToLoopUseLists(S);
1071     return getTruncateOrZeroExtend(S, Ty);
1072   }
1073 
1074   assert(Depth == 0 &&
1075          "getPtrToIntExpr() should not self-recurse for non-SCEVUnknown's.");
1076 
1077   // Otherwise, we've got some expression that is more complex than just a
1078   // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1079   // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1080   // only, and the expressions must otherwise be integer-typed.
1081   // So sink the cast down to the SCEVUnknown's.
1082 
1083   /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1084   /// which computes a pointer-typed value, and rewrites the whole expression
1085   /// tree so that *all* the computations are done on integers, and the only
1086   /// pointer-typed operands in the expression are SCEVUnknown.
1087   class SCEVPtrToIntSinkingRewriter
1088       : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1089     using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>;
1090 
1091   public:
1092     SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1093 
1094     static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1095       SCEVPtrToIntSinkingRewriter Rewriter(SE);
1096       return Rewriter.visit(Scev);
1097     }
1098 
1099     const SCEV *visit(const SCEV *S) {
1100       Type *STy = S->getType();
1101       // If the expression is not pointer-typed, just keep it as-is.
1102       if (!STy->isPointerTy())
1103         return S;
1104       // Else, recursively sink the cast down into it.
1105       return Base::visit(S);
1106     }
1107 
1108     const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1109       SmallVector<const SCEV *, 2> Operands;
1110       bool Changed = false;
1111       for (auto *Op : Expr->operands()) {
1112         Operands.push_back(visit(Op));
1113         Changed |= Op != Operands.back();
1114       }
1115       return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1116     }
1117 
1118     const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1119       SmallVector<const SCEV *, 2> Operands;
1120       bool Changed = false;
1121       for (auto *Op : Expr->operands()) {
1122         Operands.push_back(visit(Op));
1123         Changed |= Op != Operands.back();
1124       }
1125       return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1126     }
1127 
1128     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1129       Type *ExprPtrTy = Expr->getType();
1130       assert(ExprPtrTy->isPointerTy() &&
1131              "Should only reach pointer-typed SCEVUnknown's.");
1132       Type *ExprIntPtrTy = SE.getDataLayout().getIntPtrType(ExprPtrTy);
1133       return SE.getPtrToIntExpr(Expr, ExprIntPtrTy, /*Depth=*/1);
1134     }
1135   };
1136 
1137   // And actually perform the cast sinking.
1138   const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1139   assert(IntOp->getType()->isIntegerTy() &&
1140          "We must have succeeded in sinking the cast, "
1141          "and ending up with an integer-typed expression!");
1142   return getTruncateOrZeroExtend(IntOp, Ty);
1143 }
1144 
getTruncateExpr(const SCEV * Op,Type * Ty,unsigned Depth)1145 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1146                                              unsigned Depth) {
1147   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1148          "This is not a truncating conversion!");
1149   assert(isSCEVable(Ty) &&
1150          "This is not a conversion to a SCEVable type!");
1151   Ty = getEffectiveSCEVType(Ty);
1152 
1153   FoldingSetNodeID ID;
1154   ID.AddInteger(scTruncate);
1155   ID.AddPointer(Op);
1156   ID.AddPointer(Ty);
1157   void *IP = nullptr;
1158   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1159 
1160   // Fold if the operand is constant.
1161   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1162     return getConstant(
1163       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1164 
1165   // trunc(trunc(x)) --> trunc(x)
1166   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1167     return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1168 
1169   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1170   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1171     return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1172 
1173   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1174   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1175     return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1176 
1177   if (Depth > MaxCastDepth) {
1178     SCEV *S =
1179         new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1180     UniqueSCEVs.InsertNode(S, IP);
1181     addToLoopUseLists(S);
1182     return S;
1183   }
1184 
1185   // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1186   // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1187   // if after transforming we have at most one truncate, not counting truncates
1188   // that replace other casts.
1189   if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1190     auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1191     SmallVector<const SCEV *, 4> Operands;
1192     unsigned numTruncs = 0;
1193     for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1194          ++i) {
1195       const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1196       if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1197           isa<SCEVTruncateExpr>(S))
1198         numTruncs++;
1199       Operands.push_back(S);
1200     }
1201     if (numTruncs < 2) {
1202       if (isa<SCEVAddExpr>(Op))
1203         return getAddExpr(Operands);
1204       else if (isa<SCEVMulExpr>(Op))
1205         return getMulExpr(Operands);
1206       else
1207         llvm_unreachable("Unexpected SCEV type for Op.");
1208     }
1209     // Although we checked in the beginning that ID is not in the cache, it is
1210     // possible that during recursion and different modification ID was inserted
1211     // into the cache. So if we find it, just return it.
1212     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1213       return S;
1214   }
1215 
1216   // If the input value is a chrec scev, truncate the chrec's operands.
1217   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1218     SmallVector<const SCEV *, 4> Operands;
1219     for (const SCEV *Op : AddRec->operands())
1220       Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1221     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1222   }
1223 
1224   // The cast wasn't folded; create an explicit cast node. We can reuse
1225   // the existing insert position since if we get here, we won't have
1226   // made any changes which would invalidate it.
1227   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1228                                                  Op, Ty);
1229   UniqueSCEVs.InsertNode(S, IP);
1230   addToLoopUseLists(S);
1231   return S;
1232 }
1233 
1234 // Get the limit of a recurrence such that incrementing by Step cannot cause
1235 // signed overflow as long as the value of the recurrence within the
1236 // loop does not exceed this limit before incrementing.
getSignedOverflowLimitForStep(const SCEV * Step,ICmpInst::Predicate * Pred,ScalarEvolution * SE)1237 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1238                                                  ICmpInst::Predicate *Pred,
1239                                                  ScalarEvolution *SE) {
1240   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1241   if (SE->isKnownPositive(Step)) {
1242     *Pred = ICmpInst::ICMP_SLT;
1243     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1244                            SE->getSignedRangeMax(Step));
1245   }
1246   if (SE->isKnownNegative(Step)) {
1247     *Pred = ICmpInst::ICMP_SGT;
1248     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1249                            SE->getSignedRangeMin(Step));
1250   }
1251   return nullptr;
1252 }
1253 
1254 // Get the limit of a recurrence such that incrementing by Step cannot cause
1255 // unsigned overflow as long as the value of the recurrence within the loop does
1256 // not exceed this limit before incrementing.
getUnsignedOverflowLimitForStep(const SCEV * Step,ICmpInst::Predicate * Pred,ScalarEvolution * SE)1257 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1258                                                    ICmpInst::Predicate *Pred,
1259                                                    ScalarEvolution *SE) {
1260   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1261   *Pred = ICmpInst::ICMP_ULT;
1262 
1263   return SE->getConstant(APInt::getMinValue(BitWidth) -
1264                          SE->getUnsignedRangeMax(Step));
1265 }
1266 
1267 namespace {
1268 
1269 struct ExtendOpTraitsBase {
1270   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1271                                                           unsigned);
1272 };
1273 
1274 // Used to make code generic over signed and unsigned overflow.
1275 template <typename ExtendOp> struct ExtendOpTraits {
1276   // Members present:
1277   //
1278   // static const SCEV::NoWrapFlags WrapType;
1279   //
1280   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1281   //
1282   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1283   //                                           ICmpInst::Predicate *Pred,
1284   //                                           ScalarEvolution *SE);
1285 };
1286 
1287 template <>
1288 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1289   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1290 
1291   static const GetExtendExprTy GetExtendExpr;
1292 
getOverflowLimitForStep__anon83ba15150411::ExtendOpTraits1293   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1294                                              ICmpInst::Predicate *Pred,
1295                                              ScalarEvolution *SE) {
1296     return getSignedOverflowLimitForStep(Step, Pred, SE);
1297   }
1298 };
1299 
1300 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1301     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1302 
1303 template <>
1304 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1305   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1306 
1307   static const GetExtendExprTy GetExtendExpr;
1308 
getOverflowLimitForStep__anon83ba15150411::ExtendOpTraits1309   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1310                                              ICmpInst::Predicate *Pred,
1311                                              ScalarEvolution *SE) {
1312     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1313   }
1314 };
1315 
1316 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1317     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1318 
1319 } // end anonymous namespace
1320 
1321 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1322 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1323 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1324 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1325 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1326 // expression "Step + sext/zext(PreIncAR)" is congruent with
1327 // "sext/zext(PostIncAR)"
1328 template <typename ExtendOpTy>
getPreStartForExtend(const SCEVAddRecExpr * AR,Type * Ty,ScalarEvolution * SE,unsigned Depth)1329 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1330                                         ScalarEvolution *SE, unsigned Depth) {
1331   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1332   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1333 
1334   const Loop *L = AR->getLoop();
1335   const SCEV *Start = AR->getStart();
1336   const SCEV *Step = AR->getStepRecurrence(*SE);
1337 
1338   // Check for a simple looking step prior to loop entry.
1339   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1340   if (!SA)
1341     return nullptr;
1342 
1343   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1344   // subtraction is expensive. For this purpose, perform a quick and dirty
1345   // difference, by checking for Step in the operand list.
1346   SmallVector<const SCEV *, 4> DiffOps;
1347   for (const SCEV *Op : SA->operands())
1348     if (Op != Step)
1349       DiffOps.push_back(Op);
1350 
1351   if (DiffOps.size() == SA->getNumOperands())
1352     return nullptr;
1353 
1354   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1355   // `Step`:
1356 
1357   // 1. NSW/NUW flags on the step increment.
1358   auto PreStartFlags =
1359     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1360   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1361   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1362       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1363 
1364   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1365   // "S+X does not sign/unsign-overflow".
1366   //
1367 
1368   const SCEV *BECount = SE->getBackedgeTakenCount(L);
1369   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1370       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1371     return PreStart;
1372 
1373   // 2. Direct overflow check on the step operation's expression.
1374   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1375   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1376   const SCEV *OperandExtendedStart =
1377       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1378                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
1379   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1380     if (PreAR && AR->getNoWrapFlags(WrapType)) {
1381       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1382       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1383       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
1384       SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1385     }
1386     return PreStart;
1387   }
1388 
1389   // 3. Loop precondition.
1390   ICmpInst::Predicate Pred;
1391   const SCEV *OverflowLimit =
1392       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1393 
1394   if (OverflowLimit &&
1395       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1396     return PreStart;
1397 
1398   return nullptr;
1399 }
1400 
1401 // Get the normalized zero or sign extended expression for this AddRec's Start.
1402 template <typename ExtendOpTy>
getExtendAddRecStart(const SCEVAddRecExpr * AR,Type * Ty,ScalarEvolution * SE,unsigned Depth)1403 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1404                                         ScalarEvolution *SE,
1405                                         unsigned Depth) {
1406   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1407 
1408   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1409   if (!PreStart)
1410     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1411 
1412   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1413                                              Depth),
1414                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1415 }
1416 
1417 // Try to prove away overflow by looking at "nearby" add recurrences.  A
1418 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1419 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1420 //
1421 // Formally:
1422 //
1423 //     {S,+,X} == {S-T,+,X} + T
1424 //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1425 //
1426 // If ({S-T,+,X} + T) does not overflow  ... (1)
1427 //
1428 //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1429 //
1430 // If {S-T,+,X} does not overflow  ... (2)
1431 //
1432 //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1433 //      == {Ext(S-T)+Ext(T),+,Ext(X)}
1434 //
1435 // If (S-T)+T does not overflow  ... (3)
1436 //
1437 //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1438 //      == {Ext(S),+,Ext(X)} == LHS
1439 //
1440 // Thus, if (1), (2) and (3) are true for some T, then
1441 //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1442 //
1443 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1444 // does not overflow" restricted to the 0th iteration.  Therefore we only need
1445 // to check for (1) and (2).
1446 //
1447 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1448 // is `Delta` (defined below).
1449 template <typename ExtendOpTy>
proveNoWrapByVaryingStart(const SCEV * Start,const SCEV * Step,const Loop * L)1450 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1451                                                 const SCEV *Step,
1452                                                 const Loop *L) {
1453   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1454 
1455   // We restrict `Start` to a constant to prevent SCEV from spending too much
1456   // time here.  It is correct (but more expensive) to continue with a
1457   // non-constant `Start` and do a general SCEV subtraction to compute
1458   // `PreStart` below.
1459   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1460   if (!StartC)
1461     return false;
1462 
1463   APInt StartAI = StartC->getAPInt();
1464 
1465   for (unsigned Delta : {-2, -1, 1, 2}) {
1466     const SCEV *PreStart = getConstant(StartAI - Delta);
1467 
1468     FoldingSetNodeID ID;
1469     ID.AddInteger(scAddRecExpr);
1470     ID.AddPointer(PreStart);
1471     ID.AddPointer(Step);
1472     ID.AddPointer(L);
1473     void *IP = nullptr;
1474     const auto *PreAR =
1475       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1476 
1477     // Give up if we don't already have the add recurrence we need because
1478     // actually constructing an add recurrence is relatively expensive.
1479     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
1480       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1481       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1482       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1483           DeltaS, &Pred, this);
1484       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
1485         return true;
1486     }
1487   }
1488 
1489   return false;
1490 }
1491 
1492 // Finds an integer D for an expression (C + x + y + ...) such that the top
1493 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1494 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1495 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1496 // the (C + x + y + ...) expression is \p WholeAddExpr.
extractConstantWithoutWrapping(ScalarEvolution & SE,const SCEVConstant * ConstantTerm,const SCEVAddExpr * WholeAddExpr)1497 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1498                                             const SCEVConstant *ConstantTerm,
1499                                             const SCEVAddExpr *WholeAddExpr) {
1500   const APInt &C = ConstantTerm->getAPInt();
1501   const unsigned BitWidth = C.getBitWidth();
1502   // Find number of trailing zeros of (x + y + ...) w/o the C first:
1503   uint32_t TZ = BitWidth;
1504   for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1505     TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1506   if (TZ) {
1507     // Set D to be as many least significant bits of C as possible while still
1508     // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1509     return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1510   }
1511   return APInt(BitWidth, 0);
1512 }
1513 
1514 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1515 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1516 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1517 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
extractConstantWithoutWrapping(ScalarEvolution & SE,const APInt & ConstantStart,const SCEV * Step)1518 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1519                                             const APInt &ConstantStart,
1520                                             const SCEV *Step) {
1521   const unsigned BitWidth = ConstantStart.getBitWidth();
1522   const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1523   if (TZ)
1524     return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1525                          : ConstantStart;
1526   return APInt(BitWidth, 0);
1527 }
1528 
1529 const SCEV *
getZeroExtendExpr(const SCEV * Op,Type * Ty,unsigned Depth)1530 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1531   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1532          "This is not an extending conversion!");
1533   assert(isSCEVable(Ty) &&
1534          "This is not a conversion to a SCEVable type!");
1535   Ty = getEffectiveSCEVType(Ty);
1536 
1537   // Fold if the operand is constant.
1538   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1539     return getConstant(
1540       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1541 
1542   // zext(zext(x)) --> zext(x)
1543   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1544     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1545 
1546   // Before doing any expensive analysis, check to see if we've already
1547   // computed a SCEV for this Op and Ty.
1548   FoldingSetNodeID ID;
1549   ID.AddInteger(scZeroExtend);
1550   ID.AddPointer(Op);
1551   ID.AddPointer(Ty);
1552   void *IP = nullptr;
1553   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1554   if (Depth > MaxCastDepth) {
1555     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1556                                                      Op, Ty);
1557     UniqueSCEVs.InsertNode(S, IP);
1558     addToLoopUseLists(S);
1559     return S;
1560   }
1561 
1562   // zext(trunc(x)) --> zext(x) or x or trunc(x)
1563   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1564     // It's possible the bits taken off by the truncate were all zero bits. If
1565     // so, we should be able to simplify this further.
1566     const SCEV *X = ST->getOperand();
1567     ConstantRange CR = getUnsignedRange(X);
1568     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1569     unsigned NewBits = getTypeSizeInBits(Ty);
1570     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1571             CR.zextOrTrunc(NewBits)))
1572       return getTruncateOrZeroExtend(X, Ty, Depth);
1573   }
1574 
1575   // If the input value is a chrec scev, and we can prove that the value
1576   // did not overflow the old, smaller, value, we can zero extend all of the
1577   // operands (often constants).  This allows analysis of something like
1578   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1579   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1580     if (AR->isAffine()) {
1581       const SCEV *Start = AR->getStart();
1582       const SCEV *Step = AR->getStepRecurrence(*this);
1583       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1584       const Loop *L = AR->getLoop();
1585 
1586       if (!AR->hasNoUnsignedWrap()) {
1587         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1588         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1589       }
1590 
1591       // If we have special knowledge that this addrec won't overflow,
1592       // we don't need to do any further analysis.
1593       if (AR->hasNoUnsignedWrap())
1594         return getAddRecExpr(
1595             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1596             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1597 
1598       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1599       // Note that this serves two purposes: It filters out loops that are
1600       // simply not analyzable, and it covers the case where this code is
1601       // being called from within backedge-taken count analysis, such that
1602       // attempting to ask for the backedge-taken count would likely result
1603       // in infinite recursion. In the later case, the analysis code will
1604       // cope with a conservative value, and it will take care to purge
1605       // that value once it has finished.
1606       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1607       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1608         // Manually compute the final value for AR, checking for overflow.
1609 
1610         // Check whether the backedge-taken count can be losslessly casted to
1611         // the addrec's type. The count is always unsigned.
1612         const SCEV *CastedMaxBECount =
1613             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1614         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1615             CastedMaxBECount, MaxBECount->getType(), Depth);
1616         if (MaxBECount == RecastedMaxBECount) {
1617           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1618           // Check whether Start+Step*MaxBECount has no unsigned overflow.
1619           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1620                                         SCEV::FlagAnyWrap, Depth + 1);
1621           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1622                                                           SCEV::FlagAnyWrap,
1623                                                           Depth + 1),
1624                                                WideTy, Depth + 1);
1625           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1626           const SCEV *WideMaxBECount =
1627             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1628           const SCEV *OperandExtendedAdd =
1629             getAddExpr(WideStart,
1630                        getMulExpr(WideMaxBECount,
1631                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1632                                   SCEV::FlagAnyWrap, Depth + 1),
1633                        SCEV::FlagAnyWrap, Depth + 1);
1634           if (ZAdd == OperandExtendedAdd) {
1635             // Cache knowledge of AR NUW, which is propagated to this AddRec.
1636             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1637             // Return the expression with the addrec on the outside.
1638             return getAddRecExpr(
1639                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1640                                                          Depth + 1),
1641                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1642                 AR->getNoWrapFlags());
1643           }
1644           // Similar to above, only this time treat the step value as signed.
1645           // This covers loops that count down.
1646           OperandExtendedAdd =
1647             getAddExpr(WideStart,
1648                        getMulExpr(WideMaxBECount,
1649                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1650                                   SCEV::FlagAnyWrap, Depth + 1),
1651                        SCEV::FlagAnyWrap, Depth + 1);
1652           if (ZAdd == OperandExtendedAdd) {
1653             // Cache knowledge of AR NW, which is propagated to this AddRec.
1654             // Negative step causes unsigned wrap, but it still can't self-wrap.
1655             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1656             // Return the expression with the addrec on the outside.
1657             return getAddRecExpr(
1658                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1659                                                          Depth + 1),
1660                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1661                 AR->getNoWrapFlags());
1662           }
1663         }
1664       }
1665 
1666       // Normally, in the cases we can prove no-overflow via a
1667       // backedge guarding condition, we can also compute a backedge
1668       // taken count for the loop.  The exceptions are assumptions and
1669       // guards present in the loop -- SCEV is not great at exploiting
1670       // these to compute max backedge taken counts, but can still use
1671       // these to prove lack of overflow.  Use this fact to avoid
1672       // doing extra work that may not pay off.
1673       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1674           !AC.assumptions().empty()) {
1675 
1676         auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1677         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1678         if (AR->hasNoUnsignedWrap()) {
1679           // Same as nuw case above - duplicated here to avoid a compile time
1680           // issue.  It's not clear that the order of checks does matter, but
1681           // it's one of two issue possible causes for a change which was
1682           // reverted.  Be conservative for the moment.
1683           return getAddRecExpr(
1684                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1685                                                          Depth + 1),
1686                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1687                 AR->getNoWrapFlags());
1688         }
1689 
1690         // For a negative step, we can extend the operands iff doing so only
1691         // traverses values in the range zext([0,UINT_MAX]).
1692         if (isKnownNegative(Step)) {
1693           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1694                                       getSignedRangeMin(Step));
1695           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1696               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1697             // Cache knowledge of AR NW, which is propagated to this
1698             // AddRec.  Negative step causes unsigned wrap, but it
1699             // still can't self-wrap.
1700             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1701             // Return the expression with the addrec on the outside.
1702             return getAddRecExpr(
1703                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1704                                                          Depth + 1),
1705                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1706                 AR->getNoWrapFlags());
1707           }
1708         }
1709       }
1710 
1711       // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1712       // if D + (C - D + Step * n) could be proven to not unsigned wrap
1713       // where D maximizes the number of trailing zeros of (C - D + Step * n)
1714       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1715         const APInt &C = SC->getAPInt();
1716         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1717         if (D != 0) {
1718           const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1719           const SCEV *SResidual =
1720               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1721           const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1722           return getAddExpr(SZExtD, SZExtR,
1723                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1724                             Depth + 1);
1725         }
1726       }
1727 
1728       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1729         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1730         return getAddRecExpr(
1731             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1732             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1733       }
1734     }
1735 
1736   // zext(A % B) --> zext(A) % zext(B)
1737   {
1738     const SCEV *LHS;
1739     const SCEV *RHS;
1740     if (matchURem(Op, LHS, RHS))
1741       return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1742                          getZeroExtendExpr(RHS, Ty, Depth + 1));
1743   }
1744 
1745   // zext(A / B) --> zext(A) / zext(B).
1746   if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1747     return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1748                        getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1749 
1750   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1751     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1752     if (SA->hasNoUnsignedWrap()) {
1753       // If the addition does not unsign overflow then we can, by definition,
1754       // commute the zero extension with the addition operation.
1755       SmallVector<const SCEV *, 4> Ops;
1756       for (const auto *Op : SA->operands())
1757         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1758       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1759     }
1760 
1761     // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1762     // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1763     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1764     //
1765     // Often address arithmetics contain expressions like
1766     // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1767     // This transformation is useful while proving that such expressions are
1768     // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1769     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1770       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1771       if (D != 0) {
1772         const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1773         const SCEV *SResidual =
1774             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1775         const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1776         return getAddExpr(SZExtD, SZExtR,
1777                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1778                           Depth + 1);
1779       }
1780     }
1781   }
1782 
1783   if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1784     // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1785     if (SM->hasNoUnsignedWrap()) {
1786       // If the multiply does not unsign overflow then we can, by definition,
1787       // commute the zero extension with the multiply operation.
1788       SmallVector<const SCEV *, 4> Ops;
1789       for (const auto *Op : SM->operands())
1790         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1791       return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1792     }
1793 
1794     // zext(2^K * (trunc X to iN)) to iM ->
1795     // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1796     //
1797     // Proof:
1798     //
1799     //     zext(2^K * (trunc X to iN)) to iM
1800     //   = zext((trunc X to iN) << K) to iM
1801     //   = zext((trunc X to i{N-K}) << K)<nuw> to iM
1802     //     (because shl removes the top K bits)
1803     //   = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1804     //   = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1805     //
1806     if (SM->getNumOperands() == 2)
1807       if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1808         if (MulLHS->getAPInt().isPowerOf2())
1809           if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1810             int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1811                                MulLHS->getAPInt().logBase2();
1812             Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1813             return getMulExpr(
1814                 getZeroExtendExpr(MulLHS, Ty),
1815                 getZeroExtendExpr(
1816                     getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1817                 SCEV::FlagNUW, Depth + 1);
1818           }
1819   }
1820 
1821   // The cast wasn't folded; create an explicit cast node.
1822   // Recompute the insert position, as it may have been invalidated.
1823   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1824   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1825                                                    Op, Ty);
1826   UniqueSCEVs.InsertNode(S, IP);
1827   addToLoopUseLists(S);
1828   return S;
1829 }
1830 
1831 const SCEV *
getSignExtendExpr(const SCEV * Op,Type * Ty,unsigned Depth)1832 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1833   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1834          "This is not an extending conversion!");
1835   assert(isSCEVable(Ty) &&
1836          "This is not a conversion to a SCEVable type!");
1837   Ty = getEffectiveSCEVType(Ty);
1838 
1839   // Fold if the operand is constant.
1840   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1841     return getConstant(
1842       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1843 
1844   // sext(sext(x)) --> sext(x)
1845   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1846     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1847 
1848   // sext(zext(x)) --> zext(x)
1849   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1850     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1851 
1852   // Before doing any expensive analysis, check to see if we've already
1853   // computed a SCEV for this Op and Ty.
1854   FoldingSetNodeID ID;
1855   ID.AddInteger(scSignExtend);
1856   ID.AddPointer(Op);
1857   ID.AddPointer(Ty);
1858   void *IP = nullptr;
1859   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1860   // Limit recursion depth.
1861   if (Depth > MaxCastDepth) {
1862     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1863                                                      Op, Ty);
1864     UniqueSCEVs.InsertNode(S, IP);
1865     addToLoopUseLists(S);
1866     return S;
1867   }
1868 
1869   // sext(trunc(x)) --> sext(x) or x or trunc(x)
1870   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1871     // It's possible the bits taken off by the truncate were all sign bits. If
1872     // so, we should be able to simplify this further.
1873     const SCEV *X = ST->getOperand();
1874     ConstantRange CR = getSignedRange(X);
1875     unsigned TruncBits = getTypeSizeInBits(ST->getType());
1876     unsigned NewBits = getTypeSizeInBits(Ty);
1877     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1878             CR.sextOrTrunc(NewBits)))
1879       return getTruncateOrSignExtend(X, Ty, Depth);
1880   }
1881 
1882   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1883     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1884     if (SA->hasNoSignedWrap()) {
1885       // If the addition does not sign overflow then we can, by definition,
1886       // commute the sign extension with the addition operation.
1887       SmallVector<const SCEV *, 4> Ops;
1888       for (const auto *Op : SA->operands())
1889         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1890       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1891     }
1892 
1893     // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1894     // if D + (C - D + x + y + ...) could be proven to not signed wrap
1895     // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1896     //
1897     // For instance, this will bring two seemingly different expressions:
1898     //     1 + sext(5 + 20 * %x + 24 * %y)  and
1899     //         sext(6 + 20 * %x + 24 * %y)
1900     // to the same form:
1901     //     2 + sext(4 + 20 * %x + 24 * %y)
1902     if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1903       const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1904       if (D != 0) {
1905         const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1906         const SCEV *SResidual =
1907             getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1908         const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1909         return getAddExpr(SSExtD, SSExtR,
1910                           (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1911                           Depth + 1);
1912       }
1913     }
1914   }
1915   // If the input value is a chrec scev, and we can prove that the value
1916   // did not overflow the old, smaller, value, we can sign extend all of the
1917   // operands (often constants).  This allows analysis of something like
1918   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
1919   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1920     if (AR->isAffine()) {
1921       const SCEV *Start = AR->getStart();
1922       const SCEV *Step = AR->getStepRecurrence(*this);
1923       unsigned BitWidth = getTypeSizeInBits(AR->getType());
1924       const Loop *L = AR->getLoop();
1925 
1926       if (!AR->hasNoSignedWrap()) {
1927         auto NewFlags = proveNoWrapViaConstantRanges(AR);
1928         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1929       }
1930 
1931       // If we have special knowledge that this addrec won't overflow,
1932       // we don't need to do any further analysis.
1933       if (AR->hasNoSignedWrap())
1934         return getAddRecExpr(
1935             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1936             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1937 
1938       // Check whether the backedge-taken count is SCEVCouldNotCompute.
1939       // Note that this serves two purposes: It filters out loops that are
1940       // simply not analyzable, and it covers the case where this code is
1941       // being called from within backedge-taken count analysis, such that
1942       // attempting to ask for the backedge-taken count would likely result
1943       // in infinite recursion. In the later case, the analysis code will
1944       // cope with a conservative value, and it will take care to purge
1945       // that value once it has finished.
1946       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1947       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1948         // Manually compute the final value for AR, checking for
1949         // overflow.
1950 
1951         // Check whether the backedge-taken count can be losslessly casted to
1952         // the addrec's type. The count is always unsigned.
1953         const SCEV *CastedMaxBECount =
1954             getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1955         const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1956             CastedMaxBECount, MaxBECount->getType(), Depth);
1957         if (MaxBECount == RecastedMaxBECount) {
1958           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1959           // Check whether Start+Step*MaxBECount has no signed overflow.
1960           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
1961                                         SCEV::FlagAnyWrap, Depth + 1);
1962           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
1963                                                           SCEV::FlagAnyWrap,
1964                                                           Depth + 1),
1965                                                WideTy, Depth + 1);
1966           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
1967           const SCEV *WideMaxBECount =
1968             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1969           const SCEV *OperandExtendedAdd =
1970             getAddExpr(WideStart,
1971                        getMulExpr(WideMaxBECount,
1972                                   getSignExtendExpr(Step, WideTy, Depth + 1),
1973                                   SCEV::FlagAnyWrap, Depth + 1),
1974                        SCEV::FlagAnyWrap, Depth + 1);
1975           if (SAdd == OperandExtendedAdd) {
1976             // Cache knowledge of AR NSW, which is propagated to this AddRec.
1977             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
1978             // Return the expression with the addrec on the outside.
1979             return getAddRecExpr(
1980                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1981                                                          Depth + 1),
1982                 getSignExtendExpr(Step, Ty, Depth + 1), L,
1983                 AR->getNoWrapFlags());
1984           }
1985           // Similar to above, only this time treat the step value as unsigned.
1986           // This covers loops that count up with an unsigned step.
1987           OperandExtendedAdd =
1988             getAddExpr(WideStart,
1989                        getMulExpr(WideMaxBECount,
1990                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
1991                                   SCEV::FlagAnyWrap, Depth + 1),
1992                        SCEV::FlagAnyWrap, Depth + 1);
1993           if (SAdd == OperandExtendedAdd) {
1994             // If AR wraps around then
1995             //
1996             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
1997             // => SAdd != OperandExtendedAdd
1998             //
1999             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2000             // (SAdd == OperandExtendedAdd => AR is NW)
2001 
2002             setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2003 
2004             // Return the expression with the addrec on the outside.
2005             return getAddRecExpr(
2006                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2007                                                          Depth + 1),
2008                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
2009                 AR->getNoWrapFlags());
2010           }
2011         }
2012       }
2013 
2014       auto NewFlags = proveNoSignedWrapViaInduction(AR);
2015       setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2016       if (AR->hasNoSignedWrap()) {
2017         // Same as nsw case above - duplicated here to avoid a compile time
2018         // issue.  It's not clear that the order of checks does matter, but
2019         // it's one of two issue possible causes for a change which was
2020         // reverted.  Be conservative for the moment.
2021         return getAddRecExpr(
2022             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2023             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2024       }
2025 
2026       // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2027       // if D + (C - D + Step * n) could be proven to not signed wrap
2028       // where D maximizes the number of trailing zeros of (C - D + Step * n)
2029       if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2030         const APInt &C = SC->getAPInt();
2031         const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2032         if (D != 0) {
2033           const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2034           const SCEV *SResidual =
2035               getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2036           const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2037           return getAddExpr(SSExtD, SSExtR,
2038                             (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2039                             Depth + 1);
2040         }
2041       }
2042 
2043       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2044         setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2045         return getAddRecExpr(
2046             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2047             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2048       }
2049     }
2050 
2051   // If the input value is provably positive and we could not simplify
2052   // away the sext build a zext instead.
2053   if (isKnownNonNegative(Op))
2054     return getZeroExtendExpr(Op, Ty, Depth + 1);
2055 
2056   // The cast wasn't folded; create an explicit cast node.
2057   // Recompute the insert position, as it may have been invalidated.
2058   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2059   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2060                                                    Op, Ty);
2061   UniqueSCEVs.InsertNode(S, IP);
2062   addToLoopUseLists(S);
2063   return S;
2064 }
2065 
2066 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2067 /// unspecified bits out to the given type.
getAnyExtendExpr(const SCEV * Op,Type * Ty)2068 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2069                                               Type *Ty) {
2070   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2071          "This is not an extending conversion!");
2072   assert(isSCEVable(Ty) &&
2073          "This is not a conversion to a SCEVable type!");
2074   Ty = getEffectiveSCEVType(Ty);
2075 
2076   // Sign-extend negative constants.
2077   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2078     if (SC->getAPInt().isNegative())
2079       return getSignExtendExpr(Op, Ty);
2080 
2081   // Peel off a truncate cast.
2082   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2083     const SCEV *NewOp = T->getOperand();
2084     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2085       return getAnyExtendExpr(NewOp, Ty);
2086     return getTruncateOrNoop(NewOp, Ty);
2087   }
2088 
2089   // Next try a zext cast. If the cast is folded, use it.
2090   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2091   if (!isa<SCEVZeroExtendExpr>(ZExt))
2092     return ZExt;
2093 
2094   // Next try a sext cast. If the cast is folded, use it.
2095   const SCEV *SExt = getSignExtendExpr(Op, Ty);
2096   if (!isa<SCEVSignExtendExpr>(SExt))
2097     return SExt;
2098 
2099   // Force the cast to be folded into the operands of an addrec.
2100   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2101     SmallVector<const SCEV *, 4> Ops;
2102     for (const SCEV *Op : AR->operands())
2103       Ops.push_back(getAnyExtendExpr(Op, Ty));
2104     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2105   }
2106 
2107   // If the expression is obviously signed, use the sext cast value.
2108   if (isa<SCEVSMaxExpr>(Op))
2109     return SExt;
2110 
2111   // Absent any other information, use the zext cast value.
2112   return ZExt;
2113 }
2114 
2115 /// Process the given Ops list, which is a list of operands to be added under
2116 /// the given scale, update the given map. This is a helper function for
2117 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2118 /// that would form an add expression like this:
2119 ///
2120 ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2121 ///
2122 /// where A and B are constants, update the map with these values:
2123 ///
2124 ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2125 ///
2126 /// and add 13 + A*B*29 to AccumulatedConstant.
2127 /// This will allow getAddRecExpr to produce this:
2128 ///
2129 ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2130 ///
2131 /// This form often exposes folding opportunities that are hidden in
2132 /// the original operand list.
2133 ///
2134 /// Return true iff it appears that any interesting folding opportunities
2135 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2136 /// the common case where no interesting opportunities are present, and
2137 /// is also used as a check to avoid infinite recursion.
2138 static bool
CollectAddOperandsWithScales(DenseMap<const SCEV *,APInt> & M,SmallVectorImpl<const SCEV * > & NewOps,APInt & AccumulatedConstant,const SCEV * const * Ops,size_t NumOperands,const APInt & Scale,ScalarEvolution & SE)2139 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2140                              SmallVectorImpl<const SCEV *> &NewOps,
2141                              APInt &AccumulatedConstant,
2142                              const SCEV *const *Ops, size_t NumOperands,
2143                              const APInt &Scale,
2144                              ScalarEvolution &SE) {
2145   bool Interesting = false;
2146 
2147   // Iterate over the add operands. They are sorted, with constants first.
2148   unsigned i = 0;
2149   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2150     ++i;
2151     // Pull a buried constant out to the outside.
2152     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2153       Interesting = true;
2154     AccumulatedConstant += Scale * C->getAPInt();
2155   }
2156 
2157   // Next comes everything else. We're especially interested in multiplies
2158   // here, but they're in the middle, so just visit the rest with one loop.
2159   for (; i != NumOperands; ++i) {
2160     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2161     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2162       APInt NewScale =
2163           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2164       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2165         // A multiplication of a constant with another add; recurse.
2166         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2167         Interesting |=
2168           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2169                                        Add->op_begin(), Add->getNumOperands(),
2170                                        NewScale, SE);
2171       } else {
2172         // A multiplication of a constant with some other value. Update
2173         // the map.
2174         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2175         const SCEV *Key = SE.getMulExpr(MulOps);
2176         auto Pair = M.insert({Key, NewScale});
2177         if (Pair.second) {
2178           NewOps.push_back(Pair.first->first);
2179         } else {
2180           Pair.first->second += NewScale;
2181           // The map already had an entry for this value, which may indicate
2182           // a folding opportunity.
2183           Interesting = true;
2184         }
2185       }
2186     } else {
2187       // An ordinary operand. Update the map.
2188       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2189           M.insert({Ops[i], Scale});
2190       if (Pair.second) {
2191         NewOps.push_back(Pair.first->first);
2192       } else {
2193         Pair.first->second += Scale;
2194         // The map already had an entry for this value, which may indicate
2195         // a folding opportunity.
2196         Interesting = true;
2197       }
2198     }
2199   }
2200 
2201   return Interesting;
2202 }
2203 
2204 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2205 // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
2206 // can't-overflow flags for the operation if possible.
2207 static SCEV::NoWrapFlags
StrengthenNoWrapFlags(ScalarEvolution * SE,SCEVTypes Type,const ArrayRef<const SCEV * > Ops,SCEV::NoWrapFlags Flags)2208 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2209                       const ArrayRef<const SCEV *> Ops,
2210                       SCEV::NoWrapFlags Flags) {
2211   using namespace std::placeholders;
2212 
2213   using OBO = OverflowingBinaryOperator;
2214 
2215   bool CanAnalyze =
2216       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2217   (void)CanAnalyze;
2218   assert(CanAnalyze && "don't call from other places!");
2219 
2220   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2221   SCEV::NoWrapFlags SignOrUnsignWrap =
2222       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2223 
2224   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2225   auto IsKnownNonNegative = [&](const SCEV *S) {
2226     return SE->isKnownNonNegative(S);
2227   };
2228 
2229   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2230     Flags =
2231         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2232 
2233   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2234 
2235   if (SignOrUnsignWrap != SignOrUnsignMask &&
2236       (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2237       isa<SCEVConstant>(Ops[0])) {
2238 
2239     auto Opcode = [&] {
2240       switch (Type) {
2241       case scAddExpr:
2242         return Instruction::Add;
2243       case scMulExpr:
2244         return Instruction::Mul;
2245       default:
2246         llvm_unreachable("Unexpected SCEV op.");
2247       }
2248     }();
2249 
2250     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2251 
2252     // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2253     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2254       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2255           Opcode, C, OBO::NoSignedWrap);
2256       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2257         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2258     }
2259 
2260     // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2261     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2262       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2263           Opcode, C, OBO::NoUnsignedWrap);
2264       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2265         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2266     }
2267   }
2268 
2269   return Flags;
2270 }
2271 
isAvailableAtLoopEntry(const SCEV * S,const Loop * L)2272 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2273   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2274 }
2275 
2276 /// Get a canonical add expression, or something simpler if possible.
getAddExpr(SmallVectorImpl<const SCEV * > & Ops,SCEV::NoWrapFlags OrigFlags,unsigned Depth)2277 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2278                                         SCEV::NoWrapFlags OrigFlags,
2279                                         unsigned Depth) {
2280   assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2281          "only nuw or nsw allowed");
2282   assert(!Ops.empty() && "Cannot get empty add!");
2283   if (Ops.size() == 1) return Ops[0];
2284 #ifndef NDEBUG
2285   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2286   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2287     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2288            "SCEVAddExpr operand types don't match!");
2289 #endif
2290 
2291   // Sort by complexity, this groups all similar expression types together.
2292   GroupByComplexity(Ops, &LI, DT);
2293 
2294   // If there are any constants, fold them together.
2295   unsigned Idx = 0;
2296   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2297     ++Idx;
2298     assert(Idx < Ops.size());
2299     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2300       // We found two constants, fold them together!
2301       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2302       if (Ops.size() == 2) return Ops[0];
2303       Ops.erase(Ops.begin()+1);  // Erase the folded element
2304       LHSC = cast<SCEVConstant>(Ops[0]);
2305     }
2306 
2307     // If we are left with a constant zero being added, strip it off.
2308     if (LHSC->getValue()->isZero()) {
2309       Ops.erase(Ops.begin());
2310       --Idx;
2311     }
2312 
2313     if (Ops.size() == 1) return Ops[0];
2314   }
2315 
2316   // Delay expensive flag strengthening until necessary.
2317   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2318     return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2319   };
2320 
2321   // Limit recursion calls depth.
2322   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2323     return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2324 
2325   if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) {
2326     // Don't strengthen flags if we have no new information.
2327     SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2328     if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2329       Add->setNoWrapFlags(ComputeFlags(Ops));
2330     return S;
2331   }
2332 
2333   // Okay, check to see if the same value occurs in the operand list more than
2334   // once.  If so, merge them together into an multiply expression.  Since we
2335   // sorted the list, these values are required to be adjacent.
2336   Type *Ty = Ops[0]->getType();
2337   bool FoundMatch = false;
2338   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2339     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
2340       // Scan ahead to count how many equal operands there are.
2341       unsigned Count = 2;
2342       while (i+Count != e && Ops[i+Count] == Ops[i])
2343         ++Count;
2344       // Merge the values into a multiply.
2345       const SCEV *Scale = getConstant(Ty, Count);
2346       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2347       if (Ops.size() == Count)
2348         return Mul;
2349       Ops[i] = Mul;
2350       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2351       --i; e -= Count - 1;
2352       FoundMatch = true;
2353     }
2354   if (FoundMatch)
2355     return getAddExpr(Ops, OrigFlags, Depth + 1);
2356 
2357   // Check for truncates. If all the operands are truncated from the same
2358   // type, see if factoring out the truncate would permit the result to be
2359   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2360   // if the contents of the resulting outer trunc fold to something simple.
2361   auto FindTruncSrcType = [&]() -> Type * {
2362     // We're ultimately looking to fold an addrec of truncs and muls of only
2363     // constants and truncs, so if we find any other types of SCEV
2364     // as operands of the addrec then we bail and return nullptr here.
2365     // Otherwise, we return the type of the operand of a trunc that we find.
2366     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2367       return T->getOperand()->getType();
2368     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2369       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2370       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2371         return T->getOperand()->getType();
2372     }
2373     return nullptr;
2374   };
2375   if (auto *SrcType = FindTruncSrcType()) {
2376     SmallVector<const SCEV *, 8> LargeOps;
2377     bool Ok = true;
2378     // Check all the operands to see if they can be represented in the
2379     // source type of the truncate.
2380     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2381       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2382         if (T->getOperand()->getType() != SrcType) {
2383           Ok = false;
2384           break;
2385         }
2386         LargeOps.push_back(T->getOperand());
2387       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2388         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2389       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2390         SmallVector<const SCEV *, 8> LargeMulOps;
2391         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2392           if (const SCEVTruncateExpr *T =
2393                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2394             if (T->getOperand()->getType() != SrcType) {
2395               Ok = false;
2396               break;
2397             }
2398             LargeMulOps.push_back(T->getOperand());
2399           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2400             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2401           } else {
2402             Ok = false;
2403             break;
2404           }
2405         }
2406         if (Ok)
2407           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2408       } else {
2409         Ok = false;
2410         break;
2411       }
2412     }
2413     if (Ok) {
2414       // Evaluate the expression in the larger type.
2415       const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2416       // If it folds to something simple, use it. Otherwise, don't.
2417       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2418         return getTruncateExpr(Fold, Ty);
2419     }
2420   }
2421 
2422   // Skip past any other cast SCEVs.
2423   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2424     ++Idx;
2425 
2426   // If there are add operands they would be next.
2427   if (Idx < Ops.size()) {
2428     bool DeletedAdd = false;
2429     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2430       if (Ops.size() > AddOpsInlineThreshold ||
2431           Add->getNumOperands() > AddOpsInlineThreshold)
2432         break;
2433       // If we have an add, expand the add operands onto the end of the operands
2434       // list.
2435       Ops.erase(Ops.begin()+Idx);
2436       Ops.append(Add->op_begin(), Add->op_end());
2437       DeletedAdd = true;
2438     }
2439 
2440     // If we deleted at least one add, we added operands to the end of the list,
2441     // and they are not necessarily sorted.  Recurse to resort and resimplify
2442     // any operands we just acquired.
2443     if (DeletedAdd)
2444       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2445   }
2446 
2447   // Skip over the add expression until we get to a multiply.
2448   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2449     ++Idx;
2450 
2451   // Check to see if there are any folding opportunities present with
2452   // operands multiplied by constant values.
2453   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2454     uint64_t BitWidth = getTypeSizeInBits(Ty);
2455     DenseMap<const SCEV *, APInt> M;
2456     SmallVector<const SCEV *, 8> NewOps;
2457     APInt AccumulatedConstant(BitWidth, 0);
2458     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2459                                      Ops.data(), Ops.size(),
2460                                      APInt(BitWidth, 1), *this)) {
2461       struct APIntCompare {
2462         bool operator()(const APInt &LHS, const APInt &RHS) const {
2463           return LHS.ult(RHS);
2464         }
2465       };
2466 
2467       // Some interesting folding opportunity is present, so its worthwhile to
2468       // re-generate the operands list. Group the operands by constant scale,
2469       // to avoid multiplying by the same constant scale multiple times.
2470       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2471       for (const SCEV *NewOp : NewOps)
2472         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2473       // Re-generate the operands list.
2474       Ops.clear();
2475       if (AccumulatedConstant != 0)
2476         Ops.push_back(getConstant(AccumulatedConstant));
2477       for (auto &MulOp : MulOpLists)
2478         if (MulOp.first != 0)
2479           Ops.push_back(getMulExpr(
2480               getConstant(MulOp.first),
2481               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2482               SCEV::FlagAnyWrap, Depth + 1));
2483       if (Ops.empty())
2484         return getZero(Ty);
2485       if (Ops.size() == 1)
2486         return Ops[0];
2487       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2488     }
2489   }
2490 
2491   // If we are adding something to a multiply expression, make sure the
2492   // something is not already an operand of the multiply.  If so, merge it into
2493   // the multiply.
2494   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2495     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2496     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2497       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2498       if (isa<SCEVConstant>(MulOpSCEV))
2499         continue;
2500       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2501         if (MulOpSCEV == Ops[AddOp]) {
2502           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
2503           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2504           if (Mul->getNumOperands() != 2) {
2505             // If the multiply has more than two operands, we must get the
2506             // Y*Z term.
2507             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2508                                                 Mul->op_begin()+MulOp);
2509             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2510             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2511           }
2512           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2513           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2514           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2515                                             SCEV::FlagAnyWrap, Depth + 1);
2516           if (Ops.size() == 2) return OuterMul;
2517           if (AddOp < Idx) {
2518             Ops.erase(Ops.begin()+AddOp);
2519             Ops.erase(Ops.begin()+Idx-1);
2520           } else {
2521             Ops.erase(Ops.begin()+Idx);
2522             Ops.erase(Ops.begin()+AddOp-1);
2523           }
2524           Ops.push_back(OuterMul);
2525           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2526         }
2527 
2528       // Check this multiply against other multiplies being added together.
2529       for (unsigned OtherMulIdx = Idx+1;
2530            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2531            ++OtherMulIdx) {
2532         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2533         // If MulOp occurs in OtherMul, we can fold the two multiplies
2534         // together.
2535         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2536              OMulOp != e; ++OMulOp)
2537           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2538             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2539             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2540             if (Mul->getNumOperands() != 2) {
2541               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2542                                                   Mul->op_begin()+MulOp);
2543               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2544               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2545             }
2546             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2547             if (OtherMul->getNumOperands() != 2) {
2548               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2549                                                   OtherMul->op_begin()+OMulOp);
2550               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2551               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2552             }
2553             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2554             const SCEV *InnerMulSum =
2555                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2556             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2557                                               SCEV::FlagAnyWrap, Depth + 1);
2558             if (Ops.size() == 2) return OuterMul;
2559             Ops.erase(Ops.begin()+Idx);
2560             Ops.erase(Ops.begin()+OtherMulIdx-1);
2561             Ops.push_back(OuterMul);
2562             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2563           }
2564       }
2565     }
2566   }
2567 
2568   // If there are any add recurrences in the operands list, see if any other
2569   // added values are loop invariant.  If so, we can fold them into the
2570   // recurrence.
2571   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2572     ++Idx;
2573 
2574   // Scan over all recurrences, trying to fold loop invariants into them.
2575   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2576     // Scan all of the other operands to this add and add them to the vector if
2577     // they are loop invariant w.r.t. the recurrence.
2578     SmallVector<const SCEV *, 8> LIOps;
2579     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2580     const Loop *AddRecLoop = AddRec->getLoop();
2581     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2582       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2583         LIOps.push_back(Ops[i]);
2584         Ops.erase(Ops.begin()+i);
2585         --i; --e;
2586       }
2587 
2588     // If we found some loop invariants, fold them into the recurrence.
2589     if (!LIOps.empty()) {
2590       // Compute nowrap flags for the addition of the loop-invariant ops and
2591       // the addrec. Temporarily push it as an operand for that purpose.
2592       LIOps.push_back(AddRec);
2593       SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2594       LIOps.pop_back();
2595 
2596       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
2597       LIOps.push_back(AddRec->getStart());
2598 
2599       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2600                                              AddRec->op_end());
2601       // This follows from the fact that the no-wrap flags on the outer add
2602       // expression are applicable on the 0th iteration, when the add recurrence
2603       // will be equal to its start value.
2604       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2605 
2606       // Build the new addrec. Propagate the NUW and NSW flags if both the
2607       // outer add and the inner addrec are guaranteed to have no overflow.
2608       // Always propagate NW.
2609       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2610       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2611 
2612       // If all of the other operands were loop invariant, we are done.
2613       if (Ops.size() == 1) return NewRec;
2614 
2615       // Otherwise, add the folded AddRec by the non-invariant parts.
2616       for (unsigned i = 0;; ++i)
2617         if (Ops[i] == AddRec) {
2618           Ops[i] = NewRec;
2619           break;
2620         }
2621       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2622     }
2623 
2624     // Okay, if there weren't any loop invariants to be folded, check to see if
2625     // there are multiple AddRec's with the same loop induction variable being
2626     // added together.  If so, we can fold them.
2627     for (unsigned OtherIdx = Idx+1;
2628          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2629          ++OtherIdx) {
2630       // We expect the AddRecExpr's to be sorted in reverse dominance order,
2631       // so that the 1st found AddRecExpr is dominated by all others.
2632       assert(DT.dominates(
2633            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2634            AddRec->getLoop()->getHeader()) &&
2635         "AddRecExprs are not sorted in reverse dominance order?");
2636       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2637         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
2638         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2639                                                AddRec->op_end());
2640         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2641              ++OtherIdx) {
2642           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2643           if (OtherAddRec->getLoop() == AddRecLoop) {
2644             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2645                  i != e; ++i) {
2646               if (i >= AddRecOps.size()) {
2647                 AddRecOps.append(OtherAddRec->op_begin()+i,
2648                                  OtherAddRec->op_end());
2649                 break;
2650               }
2651               SmallVector<const SCEV *, 2> TwoOps = {
2652                   AddRecOps[i], OtherAddRec->getOperand(i)};
2653               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2654             }
2655             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2656           }
2657         }
2658         // Step size has changed, so we cannot guarantee no self-wraparound.
2659         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2660         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2661       }
2662     }
2663 
2664     // Otherwise couldn't fold anything into this recurrence.  Move onto the
2665     // next one.
2666   }
2667 
2668   // Okay, it looks like we really DO need an add expr.  Check to see if we
2669   // already have one, otherwise create a new one.
2670   return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2671 }
2672 
2673 const SCEV *
getOrCreateAddExpr(ArrayRef<const SCEV * > Ops,SCEV::NoWrapFlags Flags)2674 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2675                                     SCEV::NoWrapFlags Flags) {
2676   FoldingSetNodeID ID;
2677   ID.AddInteger(scAddExpr);
2678   for (const SCEV *Op : Ops)
2679     ID.AddPointer(Op);
2680   void *IP = nullptr;
2681   SCEVAddExpr *S =
2682       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2683   if (!S) {
2684     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2685     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2686     S = new (SCEVAllocator)
2687         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2688     UniqueSCEVs.InsertNode(S, IP);
2689     addToLoopUseLists(S);
2690   }
2691   S->setNoWrapFlags(Flags);
2692   return S;
2693 }
2694 
2695 const SCEV *
getOrCreateAddRecExpr(ArrayRef<const SCEV * > Ops,const Loop * L,SCEV::NoWrapFlags Flags)2696 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
2697                                        const Loop *L, SCEV::NoWrapFlags Flags) {
2698   FoldingSetNodeID ID;
2699   ID.AddInteger(scAddRecExpr);
2700   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2701     ID.AddPointer(Ops[i]);
2702   ID.AddPointer(L);
2703   void *IP = nullptr;
2704   SCEVAddRecExpr *S =
2705       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2706   if (!S) {
2707     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2708     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2709     S = new (SCEVAllocator)
2710         SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2711     UniqueSCEVs.InsertNode(S, IP);
2712     addToLoopUseLists(S);
2713   }
2714   setNoWrapFlags(S, Flags);
2715   return S;
2716 }
2717 
2718 const SCEV *
getOrCreateMulExpr(ArrayRef<const SCEV * > Ops,SCEV::NoWrapFlags Flags)2719 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
2720                                     SCEV::NoWrapFlags Flags) {
2721   FoldingSetNodeID ID;
2722   ID.AddInteger(scMulExpr);
2723   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2724     ID.AddPointer(Ops[i]);
2725   void *IP = nullptr;
2726   SCEVMulExpr *S =
2727     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2728   if (!S) {
2729     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2730     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2731     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2732                                         O, Ops.size());
2733     UniqueSCEVs.InsertNode(S, IP);
2734     addToLoopUseLists(S);
2735   }
2736   S->setNoWrapFlags(Flags);
2737   return S;
2738 }
2739 
umul_ov(uint64_t i,uint64_t j,bool & Overflow)2740 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2741   uint64_t k = i*j;
2742   if (j > 1 && k / j != i) Overflow = true;
2743   return k;
2744 }
2745 
2746 /// Compute the result of "n choose k", the binomial coefficient.  If an
2747 /// intermediate computation overflows, Overflow will be set and the return will
2748 /// be garbage. Overflow is not cleared on absence of overflow.
Choose(uint64_t n,uint64_t k,bool & Overflow)2749 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2750   // We use the multiplicative formula:
2751   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2752   // At each iteration, we take the n-th term of the numeral and divide by the
2753   // (k-n)th term of the denominator.  This division will always produce an
2754   // integral result, and helps reduce the chance of overflow in the
2755   // intermediate computations. However, we can still overflow even when the
2756   // final result would fit.
2757 
2758   if (n == 0 || n == k) return 1;
2759   if (k > n) return 0;
2760 
2761   if (k > n/2)
2762     k = n-k;
2763 
2764   uint64_t r = 1;
2765   for (uint64_t i = 1; i <= k; ++i) {
2766     r = umul_ov(r, n-(i-1), Overflow);
2767     r /= i;
2768   }
2769   return r;
2770 }
2771 
2772 /// Determine if any of the operands in this SCEV are a constant or if
2773 /// any of the add or multiply expressions in this SCEV contain a constant.
containsConstantInAddMulChain(const SCEV * StartExpr)2774 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2775   struct FindConstantInAddMulChain {
2776     bool FoundConstant = false;
2777 
2778     bool follow(const SCEV *S) {
2779       FoundConstant |= isa<SCEVConstant>(S);
2780       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2781     }
2782 
2783     bool isDone() const {
2784       return FoundConstant;
2785     }
2786   };
2787 
2788   FindConstantInAddMulChain F;
2789   SCEVTraversal<FindConstantInAddMulChain> ST(F);
2790   ST.visitAll(StartExpr);
2791   return F.FoundConstant;
2792 }
2793 
2794 /// Get a canonical multiply expression, or something simpler if possible.
getMulExpr(SmallVectorImpl<const SCEV * > & Ops,SCEV::NoWrapFlags OrigFlags,unsigned Depth)2795 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2796                                         SCEV::NoWrapFlags OrigFlags,
2797                                         unsigned Depth) {
2798   assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2799          "only nuw or nsw allowed");
2800   assert(!Ops.empty() && "Cannot get empty mul!");
2801   if (Ops.size() == 1) return Ops[0];
2802 #ifndef NDEBUG
2803   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2804   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2805     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2806            "SCEVMulExpr operand types don't match!");
2807 #endif
2808 
2809   // Sort by complexity, this groups all similar expression types together.
2810   GroupByComplexity(Ops, &LI, DT);
2811 
2812   // If there are any constants, fold them together.
2813   unsigned Idx = 0;
2814   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2815     ++Idx;
2816     assert(Idx < Ops.size());
2817     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2818       // We found two constants, fold them together!
2819       Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
2820       if (Ops.size() == 2) return Ops[0];
2821       Ops.erase(Ops.begin()+1);  // Erase the folded element
2822       LHSC = cast<SCEVConstant>(Ops[0]);
2823     }
2824 
2825     // If we have a multiply of zero, it will always be zero.
2826     if (LHSC->getValue()->isZero())
2827       return LHSC;
2828 
2829     // If we are left with a constant one being multiplied, strip it off.
2830     if (LHSC->getValue()->isOne()) {
2831       Ops.erase(Ops.begin());
2832       --Idx;
2833     }
2834 
2835     if (Ops.size() == 1)
2836       return Ops[0];
2837   }
2838 
2839   // Delay expensive flag strengthening until necessary.
2840   auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2841     return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
2842   };
2843 
2844   // Limit recursion calls depth.
2845   if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2846     return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
2847 
2848   if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) {
2849     // Don't strengthen flags if we have no new information.
2850     SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
2851     if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
2852       Mul->setNoWrapFlags(ComputeFlags(Ops));
2853     return S;
2854   }
2855 
2856   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2857     if (Ops.size() == 2) {
2858       // C1*(C2+V) -> C1*C2 + C1*V
2859       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2860         // If any of Add's ops are Adds or Muls with a constant, apply this
2861         // transformation as well.
2862         //
2863         // TODO: There are some cases where this transformation is not
2864         // profitable; for example, Add = (C0 + X) * Y + Z.  Maybe the scope of
2865         // this transformation should be narrowed down.
2866         if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
2867           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2868                                        SCEV::FlagAnyWrap, Depth + 1),
2869                             getMulExpr(LHSC, Add->getOperand(1),
2870                                        SCEV::FlagAnyWrap, Depth + 1),
2871                             SCEV::FlagAnyWrap, Depth + 1);
2872 
2873       if (Ops[0]->isAllOnesValue()) {
2874         // If we have a mul by -1 of an add, try distributing the -1 among the
2875         // add operands.
2876         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2877           SmallVector<const SCEV *, 4> NewOps;
2878           bool AnyFolded = false;
2879           for (const SCEV *AddOp : Add->operands()) {
2880             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2881                                          Depth + 1);
2882             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2883             NewOps.push_back(Mul);
2884           }
2885           if (AnyFolded)
2886             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2887         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2888           // Negation preserves a recurrence's no self-wrap property.
2889           SmallVector<const SCEV *, 4> Operands;
2890           for (const SCEV *AddRecOp : AddRec->operands())
2891             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2892                                           Depth + 1));
2893 
2894           return getAddRecExpr(Operands, AddRec->getLoop(),
2895                                AddRec->getNoWrapFlags(SCEV::FlagNW));
2896         }
2897       }
2898     }
2899   }
2900 
2901   // Skip over the add expression until we get to a multiply.
2902   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2903     ++Idx;
2904 
2905   // If there are mul operands inline them all into this expression.
2906   if (Idx < Ops.size()) {
2907     bool DeletedMul = false;
2908     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2909       if (Ops.size() > MulOpsInlineThreshold)
2910         break;
2911       // If we have an mul, expand the mul operands onto the end of the
2912       // operands list.
2913       Ops.erase(Ops.begin()+Idx);
2914       Ops.append(Mul->op_begin(), Mul->op_end());
2915       DeletedMul = true;
2916     }
2917 
2918     // If we deleted at least one mul, we added operands to the end of the
2919     // list, and they are not necessarily sorted.  Recurse to resort and
2920     // resimplify any operands we just acquired.
2921     if (DeletedMul)
2922       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2923   }
2924 
2925   // If there are any add recurrences in the operands list, see if any other
2926   // added values are loop invariant.  If so, we can fold them into the
2927   // recurrence.
2928   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2929     ++Idx;
2930 
2931   // Scan over all recurrences, trying to fold loop invariants into them.
2932   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2933     // Scan all of the other operands to this mul and add them to the vector
2934     // if they are loop invariant w.r.t. the recurrence.
2935     SmallVector<const SCEV *, 8> LIOps;
2936     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2937     const Loop *AddRecLoop = AddRec->getLoop();
2938     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2939       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2940         LIOps.push_back(Ops[i]);
2941         Ops.erase(Ops.begin()+i);
2942         --i; --e;
2943       }
2944 
2945     // If we found some loop invariants, fold them into the recurrence.
2946     if (!LIOps.empty()) {
2947       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
2948       SmallVector<const SCEV *, 4> NewOps;
2949       NewOps.reserve(AddRec->getNumOperands());
2950       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
2951       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2952         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
2953                                     SCEV::FlagAnyWrap, Depth + 1));
2954 
2955       // Build the new addrec. Propagate the NUW and NSW flags if both the
2956       // outer mul and the inner addrec are guaranteed to have no overflow.
2957       //
2958       // No self-wrap cannot be guaranteed after changing the step size, but
2959       // will be inferred if either NUW or NSW is true.
2960       SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec});
2961       const SCEV *NewRec = getAddRecExpr(
2962           NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags));
2963 
2964       // If all of the other operands were loop invariant, we are done.
2965       if (Ops.size() == 1) return NewRec;
2966 
2967       // Otherwise, multiply the folded AddRec by the non-invariant parts.
2968       for (unsigned i = 0;; ++i)
2969         if (Ops[i] == AddRec) {
2970           Ops[i] = NewRec;
2971           break;
2972         }
2973       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2974     }
2975 
2976     // Okay, if there weren't any loop invariants to be folded, check to see
2977     // if there are multiple AddRec's with the same loop induction variable
2978     // being multiplied together.  If so, we can fold them.
2979 
2980     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2981     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2982     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2983     //   ]]],+,...up to x=2n}.
2984     // Note that the arguments to choose() are always integers with values
2985     // known at compile time, never SCEV objects.
2986     //
2987     // The implementation avoids pointless extra computations when the two
2988     // addrec's are of different length (mathematically, it's equivalent to
2989     // an infinite stream of zeros on the right).
2990     bool OpsModified = false;
2991     for (unsigned OtherIdx = Idx+1;
2992          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2993          ++OtherIdx) {
2994       const SCEVAddRecExpr *OtherAddRec =
2995         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2996       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2997         continue;
2998 
2999       // Limit max number of arguments to avoid creation of unreasonably big
3000       // SCEVAddRecs with very complex operands.
3001       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3002           MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3003         continue;
3004 
3005       bool Overflow = false;
3006       Type *Ty = AddRec->getType();
3007       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3008       SmallVector<const SCEV*, 7> AddRecOps;
3009       for (int x = 0, xe = AddRec->getNumOperands() +
3010              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3011         SmallVector <const SCEV *, 7> SumOps;
3012         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3013           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3014           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3015                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3016                z < ze && !Overflow; ++z) {
3017             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3018             uint64_t Coeff;
3019             if (LargerThan64Bits)
3020               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3021             else
3022               Coeff = Coeff1*Coeff2;
3023             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3024             const SCEV *Term1 = AddRec->getOperand(y-z);
3025             const SCEV *Term2 = OtherAddRec->getOperand(z);
3026             SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3027                                         SCEV::FlagAnyWrap, Depth + 1));
3028           }
3029         }
3030         if (SumOps.empty())
3031           SumOps.push_back(getZero(Ty));
3032         AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3033       }
3034       if (!Overflow) {
3035         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3036                                               SCEV::FlagAnyWrap);
3037         if (Ops.size() == 2) return NewAddRec;
3038         Ops[Idx] = NewAddRec;
3039         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3040         OpsModified = true;
3041         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3042         if (!AddRec)
3043           break;
3044       }
3045     }
3046     if (OpsModified)
3047       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3048 
3049     // Otherwise couldn't fold anything into this recurrence.  Move onto the
3050     // next one.
3051   }
3052 
3053   // Okay, it looks like we really DO need an mul expr.  Check to see if we
3054   // already have one, otherwise create a new one.
3055   return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3056 }
3057 
3058 /// Represents an unsigned remainder expression based on unsigned division.
getURemExpr(const SCEV * LHS,const SCEV * RHS)3059 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3060                                          const SCEV *RHS) {
3061   assert(getEffectiveSCEVType(LHS->getType()) ==
3062          getEffectiveSCEVType(RHS->getType()) &&
3063          "SCEVURemExpr operand types don't match!");
3064 
3065   // Short-circuit easy cases
3066   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3067     // If constant is one, the result is trivial
3068     if (RHSC->getValue()->isOne())
3069       return getZero(LHS->getType()); // X urem 1 --> 0
3070 
3071     // If constant is a power of two, fold into a zext(trunc(LHS)).
3072     if (RHSC->getAPInt().isPowerOf2()) {
3073       Type *FullTy = LHS->getType();
3074       Type *TruncTy =
3075           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3076       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3077     }
3078   }
3079 
3080   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3081   const SCEV *UDiv = getUDivExpr(LHS, RHS);
3082   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3083   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3084 }
3085 
3086 /// Get a canonical unsigned division expression, or something simpler if
3087 /// possible.
getUDivExpr(const SCEV * LHS,const SCEV * RHS)3088 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3089                                          const SCEV *RHS) {
3090   assert(getEffectiveSCEVType(LHS->getType()) ==
3091          getEffectiveSCEVType(RHS->getType()) &&
3092          "SCEVUDivExpr operand types don't match!");
3093 
3094   FoldingSetNodeID ID;
3095   ID.AddInteger(scUDivExpr);
3096   ID.AddPointer(LHS);
3097   ID.AddPointer(RHS);
3098   void *IP = nullptr;
3099   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3100     return S;
3101 
3102   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3103     if (RHSC->getValue()->isOne())
3104       return LHS;                               // X udiv 1 --> x
3105     // If the denominator is zero, the result of the udiv is undefined. Don't
3106     // try to analyze it, because the resolution chosen here may differ from
3107     // the resolution chosen in other parts of the compiler.
3108     if (!RHSC->getValue()->isZero()) {
3109       // Determine if the division can be folded into the operands of
3110       // its operands.
3111       // TODO: Generalize this to non-constants by using known-bits information.
3112       Type *Ty = LHS->getType();
3113       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3114       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3115       // For non-power-of-two values, effectively round the value up to the
3116       // nearest power of two.
3117       if (!RHSC->getAPInt().isPowerOf2())
3118         ++MaxShiftAmt;
3119       IntegerType *ExtTy =
3120         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3121       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3122         if (const SCEVConstant *Step =
3123             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3124           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3125           const APInt &StepInt = Step->getAPInt();
3126           const APInt &DivInt = RHSC->getAPInt();
3127           if (!StepInt.urem(DivInt) &&
3128               getZeroExtendExpr(AR, ExtTy) ==
3129               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3130                             getZeroExtendExpr(Step, ExtTy),
3131                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3132             SmallVector<const SCEV *, 4> Operands;
3133             for (const SCEV *Op : AR->operands())
3134               Operands.push_back(getUDivExpr(Op, RHS));
3135             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3136           }
3137           /// Get a canonical UDivExpr for a recurrence.
3138           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3139           // We can currently only fold X%N if X is constant.
3140           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3141           if (StartC && !DivInt.urem(StepInt) &&
3142               getZeroExtendExpr(AR, ExtTy) ==
3143               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3144                             getZeroExtendExpr(Step, ExtTy),
3145                             AR->getLoop(), SCEV::FlagAnyWrap)) {
3146             const APInt &StartInt = StartC->getAPInt();
3147             const APInt &StartRem = StartInt.urem(StepInt);
3148             if (StartRem != 0) {
3149               const SCEV *NewLHS =
3150                   getAddRecExpr(getConstant(StartInt - StartRem), Step,
3151                                 AR->getLoop(), SCEV::FlagNW);
3152               if (LHS != NewLHS) {
3153                 LHS = NewLHS;
3154 
3155                 // Reset the ID to include the new LHS, and check if it is
3156                 // already cached.
3157                 ID.clear();
3158                 ID.AddInteger(scUDivExpr);
3159                 ID.AddPointer(LHS);
3160                 ID.AddPointer(RHS);
3161                 IP = nullptr;
3162                 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3163                   return S;
3164               }
3165             }
3166           }
3167         }
3168       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3169       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3170         SmallVector<const SCEV *, 4> Operands;
3171         for (const SCEV *Op : M->operands())
3172           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3173         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3174           // Find an operand that's safely divisible.
3175           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3176             const SCEV *Op = M->getOperand(i);
3177             const SCEV *Div = getUDivExpr(Op, RHSC);
3178             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3179               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3180                                                       M->op_end());
3181               Operands[i] = Div;
3182               return getMulExpr(Operands);
3183             }
3184           }
3185       }
3186 
3187       // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3188       if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3189         if (auto *DivisorConstant =
3190                 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3191           bool Overflow = false;
3192           APInt NewRHS =
3193               DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3194           if (Overflow) {
3195             return getConstant(RHSC->getType(), 0, false);
3196           }
3197           return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3198         }
3199       }
3200 
3201       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3202       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3203         SmallVector<const SCEV *, 4> Operands;
3204         for (const SCEV *Op : A->operands())
3205           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3206         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3207           Operands.clear();
3208           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3209             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3210             if (isa<SCEVUDivExpr>(Op) ||
3211                 getMulExpr(Op, RHS) != A->getOperand(i))
3212               break;
3213             Operands.push_back(Op);
3214           }
3215           if (Operands.size() == A->getNumOperands())
3216             return getAddExpr(Operands);
3217         }
3218       }
3219 
3220       // Fold if both operands are constant.
3221       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3222         Constant *LHSCV = LHSC->getValue();
3223         Constant *RHSCV = RHSC->getValue();
3224         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3225                                                                    RHSCV)));
3226       }
3227     }
3228   }
3229 
3230   // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3231   // changes). Make sure we get a new one.
3232   IP = nullptr;
3233   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3234   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3235                                              LHS, RHS);
3236   UniqueSCEVs.InsertNode(S, IP);
3237   addToLoopUseLists(S);
3238   return S;
3239 }
3240 
gcd(const SCEVConstant * C1,const SCEVConstant * C2)3241 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3242   APInt A = C1->getAPInt().abs();
3243   APInt B = C2->getAPInt().abs();
3244   uint32_t ABW = A.getBitWidth();
3245   uint32_t BBW = B.getBitWidth();
3246 
3247   if (ABW > BBW)
3248     B = B.zext(ABW);
3249   else if (ABW < BBW)
3250     A = A.zext(BBW);
3251 
3252   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3253 }
3254 
3255 /// Get a canonical unsigned division expression, or something simpler if
3256 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3257 /// can attempt to remove factors from the LHS and RHS.  We can't do this when
3258 /// it's not exact because the udiv may be clearing bits.
getUDivExactExpr(const SCEV * LHS,const SCEV * RHS)3259 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3260                                               const SCEV *RHS) {
3261   // TODO: we could try to find factors in all sorts of things, but for now we
3262   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3263   // end of this file for inspiration.
3264 
3265   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3266   if (!Mul || !Mul->hasNoUnsignedWrap())
3267     return getUDivExpr(LHS, RHS);
3268 
3269   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3270     // If the mulexpr multiplies by a constant, then that constant must be the
3271     // first element of the mulexpr.
3272     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3273       if (LHSCst == RHSCst) {
3274         SmallVector<const SCEV *, 2> Operands;
3275         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3276         return getMulExpr(Operands);
3277       }
3278 
3279       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3280       // that there's a factor provided by one of the other terms. We need to
3281       // check.
3282       APInt Factor = gcd(LHSCst, RHSCst);
3283       if (!Factor.isIntN(1)) {
3284         LHSCst =
3285             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3286         RHSCst =
3287             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3288         SmallVector<const SCEV *, 2> Operands;
3289         Operands.push_back(LHSCst);
3290         Operands.append(Mul->op_begin() + 1, Mul->op_end());
3291         LHS = getMulExpr(Operands);
3292         RHS = RHSCst;
3293         Mul = dyn_cast<SCEVMulExpr>(LHS);
3294         if (!Mul)
3295           return getUDivExactExpr(LHS, RHS);
3296       }
3297     }
3298   }
3299 
3300   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3301     if (Mul->getOperand(i) == RHS) {
3302       SmallVector<const SCEV *, 2> Operands;
3303       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3304       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3305       return getMulExpr(Operands);
3306     }
3307   }
3308 
3309   return getUDivExpr(LHS, RHS);
3310 }
3311 
3312 /// Get an add recurrence expression for the specified loop.  Simplify the
3313 /// expression as much as possible.
getAddRecExpr(const SCEV * Start,const SCEV * Step,const Loop * L,SCEV::NoWrapFlags Flags)3314 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3315                                            const Loop *L,
3316                                            SCEV::NoWrapFlags Flags) {
3317   SmallVector<const SCEV *, 4> Operands;
3318   Operands.push_back(Start);
3319   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3320     if (StepChrec->getLoop() == L) {
3321       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3322       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3323     }
3324 
3325   Operands.push_back(Step);
3326   return getAddRecExpr(Operands, L, Flags);
3327 }
3328 
3329 /// Get an add recurrence expression for the specified loop.  Simplify the
3330 /// expression as much as possible.
3331 const SCEV *
getAddRecExpr(SmallVectorImpl<const SCEV * > & Operands,const Loop * L,SCEV::NoWrapFlags Flags)3332 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3333                                const Loop *L, SCEV::NoWrapFlags Flags) {
3334   if (Operands.size() == 1) return Operands[0];
3335 #ifndef NDEBUG
3336   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3337   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3338     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3339            "SCEVAddRecExpr operand types don't match!");
3340   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3341     assert(isLoopInvariant(Operands[i], L) &&
3342            "SCEVAddRecExpr operand is not loop-invariant!");
3343 #endif
3344 
3345   if (Operands.back()->isZero()) {
3346     Operands.pop_back();
3347     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
3348   }
3349 
3350   // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3351   // use that information to infer NUW and NSW flags. However, computing a
3352   // BE count requires calling getAddRecExpr, so we may not yet have a
3353   // meaningful BE count at this point (and if we don't, we'd be stuck
3354   // with a SCEVCouldNotCompute as the cached BE count).
3355 
3356   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3357 
3358   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3359   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3360     const Loop *NestedLoop = NestedAR->getLoop();
3361     if (L->contains(NestedLoop)
3362             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3363             : (!NestedLoop->contains(L) &&
3364                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3365       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3366                                                   NestedAR->op_end());
3367       Operands[0] = NestedAR->getStart();
3368       // AddRecs require their operands be loop-invariant with respect to their
3369       // loops. Don't perform this transformation if it would break this
3370       // requirement.
3371       bool AllInvariant = all_of(
3372           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3373 
3374       if (AllInvariant) {
3375         // Create a recurrence for the outer loop with the same step size.
3376         //
3377         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3378         // inner recurrence has the same property.
3379         SCEV::NoWrapFlags OuterFlags =
3380           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3381 
3382         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3383         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3384           return isLoopInvariant(Op, NestedLoop);
3385         });
3386 
3387         if (AllInvariant) {
3388           // Ok, both add recurrences are valid after the transformation.
3389           //
3390           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3391           // the outer recurrence has the same property.
3392           SCEV::NoWrapFlags InnerFlags =
3393             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3394           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3395         }
3396       }
3397       // Reset Operands to its original state.
3398       Operands[0] = NestedAR;
3399     }
3400   }
3401 
3402   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
3403   // already have one, otherwise create a new one.
3404   return getOrCreateAddRecExpr(Operands, L, Flags);
3405 }
3406 
3407 const SCEV *
getGEPExpr(GEPOperator * GEP,const SmallVectorImpl<const SCEV * > & IndexExprs)3408 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3409                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
3410   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3411   // getSCEV(Base)->getType() has the same address space as Base->getType()
3412   // because SCEV::getType() preserves the address space.
3413   Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3414   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3415   // instruction to its SCEV, because the Instruction may be guarded by control
3416   // flow and the no-overflow bits may not be valid for the expression in any
3417   // context. This can be fixed similarly to how these flags are handled for
3418   // adds.
3419   SCEV::NoWrapFlags OffsetWrap =
3420       GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3421 
3422   Type *CurTy = GEP->getType();
3423   bool FirstIter = true;
3424   SmallVector<const SCEV *, 4> Offsets;
3425   for (const SCEV *IndexExpr : IndexExprs) {
3426     // Compute the (potentially symbolic) offset in bytes for this index.
3427     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3428       // For a struct, add the member offset.
3429       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3430       unsigned FieldNo = Index->getZExtValue();
3431       const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3432       Offsets.push_back(FieldOffset);
3433 
3434       // Update CurTy to the type of the field at Index.
3435       CurTy = STy->getTypeAtIndex(Index);
3436     } else {
3437       // Update CurTy to its element type.
3438       if (FirstIter) {
3439         assert(isa<PointerType>(CurTy) &&
3440                "The first index of a GEP indexes a pointer");
3441         CurTy = GEP->getSourceElementType();
3442         FirstIter = false;
3443       } else {
3444         CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3445       }
3446       // For an array, add the element offset, explicitly scaled.
3447       const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3448       // Getelementptr indices are signed.
3449       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3450 
3451       // Multiply the index by the element size to compute the element offset.
3452       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3453       Offsets.push_back(LocalOffset);
3454     }
3455   }
3456 
3457   // Handle degenerate case of GEP without offsets.
3458   if (Offsets.empty())
3459     return BaseExpr;
3460 
3461   // Add the offsets together, assuming nsw if inbounds.
3462   const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3463   // Add the base address and the offset. We cannot use the nsw flag, as the
3464   // base address is unsigned. However, if we know that the offset is
3465   // non-negative, we can use nuw.
3466   SCEV::NoWrapFlags BaseWrap = GEP->isInBounds() && isKnownNonNegative(Offset)
3467                                    ? SCEV::FlagNUW : SCEV::FlagAnyWrap;
3468   return getAddExpr(BaseExpr, Offset, BaseWrap);
3469 }
3470 
3471 std::tuple<SCEV *, FoldingSetNodeID, void *>
findExistingSCEVInCache(SCEVTypes SCEVType,ArrayRef<const SCEV * > Ops)3472 ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3473                                          ArrayRef<const SCEV *> Ops) {
3474   FoldingSetNodeID ID;
3475   void *IP = nullptr;
3476   ID.AddInteger(SCEVType);
3477   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3478     ID.AddPointer(Ops[i]);
3479   return std::tuple<SCEV *, FoldingSetNodeID, void *>(
3480       UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP);
3481 }
3482 
getAbsExpr(const SCEV * Op,bool IsNSW)3483 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3484   SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3485   return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3486 }
3487 
getSignumExpr(const SCEV * Op)3488 const SCEV *ScalarEvolution::getSignumExpr(const SCEV *Op) {
3489   Type *Ty = Op->getType();
3490   return getSMinExpr(getSMaxExpr(Op, getMinusOne(Ty)), getOne(Ty));
3491 }
3492 
getMinMaxExpr(SCEVTypes Kind,SmallVectorImpl<const SCEV * > & Ops)3493 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
3494                                            SmallVectorImpl<const SCEV *> &Ops) {
3495   assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3496   if (Ops.size() == 1) return Ops[0];
3497 #ifndef NDEBUG
3498   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3499   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3500     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3501            "Operand types don't match!");
3502 #endif
3503 
3504   bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3505   bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3506 
3507   // Sort by complexity, this groups all similar expression types together.
3508   GroupByComplexity(Ops, &LI, DT);
3509 
3510   // Check if we have created the same expression before.
3511   if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) {
3512     return S;
3513   }
3514 
3515   // If there are any constants, fold them together.
3516   unsigned Idx = 0;
3517   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3518     ++Idx;
3519     assert(Idx < Ops.size());
3520     auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3521       if (Kind == scSMaxExpr)
3522         return APIntOps::smax(LHS, RHS);
3523       else if (Kind == scSMinExpr)
3524         return APIntOps::smin(LHS, RHS);
3525       else if (Kind == scUMaxExpr)
3526         return APIntOps::umax(LHS, RHS);
3527       else if (Kind == scUMinExpr)
3528         return APIntOps::umin(LHS, RHS);
3529       llvm_unreachable("Unknown SCEV min/max opcode");
3530     };
3531 
3532     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3533       // We found two constants, fold them together!
3534       ConstantInt *Fold = ConstantInt::get(
3535           getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3536       Ops[0] = getConstant(Fold);
3537       Ops.erase(Ops.begin()+1);  // Erase the folded element
3538       if (Ops.size() == 1) return Ops[0];
3539       LHSC = cast<SCEVConstant>(Ops[0]);
3540     }
3541 
3542     bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3543     bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3544 
3545     if (IsMax ? IsMinV : IsMaxV) {
3546       // If we are left with a constant minimum(/maximum)-int, strip it off.
3547       Ops.erase(Ops.begin());
3548       --Idx;
3549     } else if (IsMax ? IsMaxV : IsMinV) {
3550       // If we have a max(/min) with a constant maximum(/minimum)-int,
3551       // it will always be the extremum.
3552       return LHSC;
3553     }
3554 
3555     if (Ops.size() == 1) return Ops[0];
3556   }
3557 
3558   // Find the first operation of the same kind
3559   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3560     ++Idx;
3561 
3562   // Check to see if one of the operands is of the same kind. If so, expand its
3563   // operands onto our operand list, and recurse to simplify.
3564   if (Idx < Ops.size()) {
3565     bool DeletedAny = false;
3566     while (Ops[Idx]->getSCEVType() == Kind) {
3567       const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3568       Ops.erase(Ops.begin()+Idx);
3569       Ops.append(SMME->op_begin(), SMME->op_end());
3570       DeletedAny = true;
3571     }
3572 
3573     if (DeletedAny)
3574       return getMinMaxExpr(Kind, Ops);
3575   }
3576 
3577   // Okay, check to see if the same value occurs in the operand list twice.  If
3578   // so, delete one.  Since we sorted the list, these values are required to
3579   // be adjacent.
3580   llvm::CmpInst::Predicate GEPred =
3581       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3582   llvm::CmpInst::Predicate LEPred =
3583       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3584   llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3585   llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3586   for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3587     if (Ops[i] == Ops[i + 1] ||
3588         isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3589       //  X op Y op Y  -->  X op Y
3590       //  X op Y       -->  X, if we know X, Y are ordered appropriately
3591       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3592       --i;
3593       --e;
3594     } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3595                                                Ops[i + 1])) {
3596       //  X op Y       -->  Y, if we know X, Y are ordered appropriately
3597       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3598       --i;
3599       --e;
3600     }
3601   }
3602 
3603   if (Ops.size() == 1) return Ops[0];
3604 
3605   assert(!Ops.empty() && "Reduced smax down to nothing!");
3606 
3607   // Okay, it looks like we really DO need an expr.  Check to see if we
3608   // already have one, otherwise create a new one.
3609   const SCEV *ExistingSCEV;
3610   FoldingSetNodeID ID;
3611   void *IP;
3612   std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops);
3613   if (ExistingSCEV)
3614     return ExistingSCEV;
3615   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3616   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3617   SCEV *S = new (SCEVAllocator)
3618       SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3619 
3620   UniqueSCEVs.InsertNode(S, IP);
3621   addToLoopUseLists(S);
3622   return S;
3623 }
3624 
getSMaxExpr(const SCEV * LHS,const SCEV * RHS)3625 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3626   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3627   return getSMaxExpr(Ops);
3628 }
3629 
getSMaxExpr(SmallVectorImpl<const SCEV * > & Ops)3630 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3631   return getMinMaxExpr(scSMaxExpr, Ops);
3632 }
3633 
getUMaxExpr(const SCEV * LHS,const SCEV * RHS)3634 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3635   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3636   return getUMaxExpr(Ops);
3637 }
3638 
getUMaxExpr(SmallVectorImpl<const SCEV * > & Ops)3639 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3640   return getMinMaxExpr(scUMaxExpr, Ops);
3641 }
3642 
getSMinExpr(const SCEV * LHS,const SCEV * RHS)3643 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3644                                          const SCEV *RHS) {
3645   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3646   return getSMinExpr(Ops);
3647 }
3648 
getSMinExpr(SmallVectorImpl<const SCEV * > & Ops)3649 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3650   return getMinMaxExpr(scSMinExpr, Ops);
3651 }
3652 
getUMinExpr(const SCEV * LHS,const SCEV * RHS)3653 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3654                                          const SCEV *RHS) {
3655   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3656   return getUMinExpr(Ops);
3657 }
3658 
getUMinExpr(SmallVectorImpl<const SCEV * > & Ops)3659 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3660   return getMinMaxExpr(scUMinExpr, Ops);
3661 }
3662 
3663 const SCEV *
getSizeOfScalableVectorExpr(Type * IntTy,ScalableVectorType * ScalableTy)3664 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy,
3665                                              ScalableVectorType *ScalableTy) {
3666   Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo());
3667   Constant *One = ConstantInt::get(IntTy, 1);
3668   Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One);
3669   // Note that the expression we created is the final expression, we don't
3670   // want to simplify it any further Also, if we call a normal getSCEV(),
3671   // we'll end up in an endless recursion. So just create an SCEVUnknown.
3672   return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy));
3673 }
3674 
getSizeOfExpr(Type * IntTy,Type * AllocTy)3675 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3676   if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy))
3677     return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy);
3678   // We can bypass creating a target-independent constant expression and then
3679   // folding it back into a ConstantInt. This is just a compile-time
3680   // optimization.
3681   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3682 }
3683 
getStoreSizeOfExpr(Type * IntTy,Type * StoreTy)3684 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) {
3685   if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy))
3686     return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy);
3687   // We can bypass creating a target-independent constant expression and then
3688   // folding it back into a ConstantInt. This is just a compile-time
3689   // optimization.
3690   return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
3691 }
3692 
getOffsetOfExpr(Type * IntTy,StructType * STy,unsigned FieldNo)3693 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3694                                              StructType *STy,
3695                                              unsigned FieldNo) {
3696   // We can bypass creating a target-independent constant expression and then
3697   // folding it back into a ConstantInt. This is just a compile-time
3698   // optimization.
3699   return getConstant(
3700       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3701 }
3702 
getUnknown(Value * V)3703 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3704   // Don't attempt to do anything other than create a SCEVUnknown object
3705   // here.  createSCEV only calls getUnknown after checking for all other
3706   // interesting possibilities, and any other code that calls getUnknown
3707   // is doing so in order to hide a value from SCEV canonicalization.
3708 
3709   FoldingSetNodeID ID;
3710   ID.AddInteger(scUnknown);
3711   ID.AddPointer(V);
3712   void *IP = nullptr;
3713   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3714     assert(cast<SCEVUnknown>(S)->getValue() == V &&
3715            "Stale SCEVUnknown in uniquing map!");
3716     return S;
3717   }
3718   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3719                                             FirstUnknown);
3720   FirstUnknown = cast<SCEVUnknown>(S);
3721   UniqueSCEVs.InsertNode(S, IP);
3722   return S;
3723 }
3724 
3725 //===----------------------------------------------------------------------===//
3726 //            Basic SCEV Analysis and PHI Idiom Recognition Code
3727 //
3728 
3729 /// Test if values of the given type are analyzable within the SCEV
3730 /// framework. This primarily includes integer types, and it can optionally
3731 /// include pointer types if the ScalarEvolution class has access to
3732 /// target-specific information.
isSCEVable(Type * Ty) const3733 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3734   // Integers and pointers are always SCEVable.
3735   return Ty->isIntOrPtrTy();
3736 }
3737 
3738 /// Return the size in bits of the specified type, for which isSCEVable must
3739 /// return true.
getTypeSizeInBits(Type * Ty) const3740 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3741   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3742   if (Ty->isPointerTy())
3743     return getDataLayout().getIndexTypeSizeInBits(Ty);
3744   return getDataLayout().getTypeSizeInBits(Ty);
3745 }
3746 
3747 /// Return a type with the same bitwidth as the given type and which represents
3748 /// how SCEV will treat the given type, for which isSCEVable must return
3749 /// true. For pointer types, this is the pointer index sized integer type.
getEffectiveSCEVType(Type * Ty) const3750 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3751   assert(isSCEVable(Ty) && "Type is not SCEVable!");
3752 
3753   if (Ty->isIntegerTy())
3754     return Ty;
3755 
3756   // The only other support type is pointer.
3757   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3758   return getDataLayout().getIndexType(Ty);
3759 }
3760 
getWiderType(Type * T1,Type * T2) const3761 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3762   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3763 }
3764 
getCouldNotCompute()3765 const SCEV *ScalarEvolution::getCouldNotCompute() {
3766   return CouldNotCompute.get();
3767 }
3768 
checkValidity(const SCEV * S) const3769 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3770   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3771     auto *SU = dyn_cast<SCEVUnknown>(S);
3772     return SU && SU->getValue() == nullptr;
3773   });
3774 
3775   return !ContainsNulls;
3776 }
3777 
containsAddRecurrence(const SCEV * S)3778 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3779   HasRecMapType::iterator I = HasRecMap.find(S);
3780   if (I != HasRecMap.end())
3781     return I->second;
3782 
3783   bool FoundAddRec =
3784       SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
3785   HasRecMap.insert({S, FoundAddRec});
3786   return FoundAddRec;
3787 }
3788 
3789 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3790 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3791 /// offset I, then return {S', I}, else return {\p S, nullptr}.
splitAddExpr(const SCEV * S)3792 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3793   const auto *Add = dyn_cast<SCEVAddExpr>(S);
3794   if (!Add)
3795     return {S, nullptr};
3796 
3797   if (Add->getNumOperands() != 2)
3798     return {S, nullptr};
3799 
3800   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3801   if (!ConstOp)
3802     return {S, nullptr};
3803 
3804   return {Add->getOperand(1), ConstOp->getValue()};
3805 }
3806 
3807 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3808 /// by the value and offset from any ValueOffsetPair in the set.
3809 SetVector<ScalarEvolution::ValueOffsetPair> *
getSCEVValues(const SCEV * S)3810 ScalarEvolution::getSCEVValues(const SCEV *S) {
3811   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3812   if (SI == ExprValueMap.end())
3813     return nullptr;
3814 #ifndef NDEBUG
3815   if (VerifySCEVMap) {
3816     // Check there is no dangling Value in the set returned.
3817     for (const auto &VE : SI->second)
3818       assert(ValueExprMap.count(VE.first));
3819   }
3820 #endif
3821   return &SI->second;
3822 }
3823 
3824 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3825 /// cannot be used separately. eraseValueFromMap should be used to remove
3826 /// V from ValueExprMap and ExprValueMap at the same time.
eraseValueFromMap(Value * V)3827 void ScalarEvolution::eraseValueFromMap(Value *V) {
3828   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3829   if (I != ValueExprMap.end()) {
3830     const SCEV *S = I->second;
3831     // Remove {V, 0} from the set of ExprValueMap[S]
3832     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3833       SV->remove({V, nullptr});
3834 
3835     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3836     const SCEV *Stripped;
3837     ConstantInt *Offset;
3838     std::tie(Stripped, Offset) = splitAddExpr(S);
3839     if (Offset != nullptr) {
3840       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3841         SV->remove({V, Offset});
3842     }
3843     ValueExprMap.erase(V);
3844   }
3845 }
3846 
3847 /// Check whether value has nuw/nsw/exact set but SCEV does not.
3848 /// TODO: In reality it is better to check the poison recursively
3849 /// but this is better than nothing.
SCEVLostPoisonFlags(const SCEV * S,const Value * V)3850 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3851   if (auto *I = dyn_cast<Instruction>(V)) {
3852     if (isa<OverflowingBinaryOperator>(I)) {
3853       if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3854         if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3855           return true;
3856         if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3857           return true;
3858       }
3859     } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3860       return true;
3861   }
3862   return false;
3863 }
3864 
3865 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3866 /// create a new one.
getSCEV(Value * V)3867 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3868   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3869 
3870   const SCEV *S = getExistingSCEV(V);
3871   if (S == nullptr) {
3872     S = createSCEV(V);
3873     // During PHI resolution, it is possible to create two SCEVs for the same
3874     // V, so it is needed to double check whether V->S is inserted into
3875     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3876     std::pair<ValueExprMapType::iterator, bool> Pair =
3877         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3878     if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3879       ExprValueMap[S].insert({V, nullptr});
3880 
3881       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3882       // ExprValueMap.
3883       const SCEV *Stripped = S;
3884       ConstantInt *Offset = nullptr;
3885       std::tie(Stripped, Offset) = splitAddExpr(S);
3886       // If stripped is SCEVUnknown, don't bother to save
3887       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3888       // increase the complexity of the expansion code.
3889       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3890       // because it may generate add/sub instead of GEP in SCEV expansion.
3891       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3892           !isa<GetElementPtrInst>(V))
3893         ExprValueMap[Stripped].insert({V, Offset});
3894     }
3895   }
3896   return S;
3897 }
3898 
getExistingSCEV(Value * V)3899 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3900   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3901 
3902   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3903   if (I != ValueExprMap.end()) {
3904     const SCEV *S = I->second;
3905     if (checkValidity(S))
3906       return S;
3907     eraseValueFromMap(V);
3908     forgetMemoizedResults(S);
3909   }
3910   return nullptr;
3911 }
3912 
3913 /// Return a SCEV corresponding to -V = -1*V
getNegativeSCEV(const SCEV * V,SCEV::NoWrapFlags Flags)3914 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3915                                              SCEV::NoWrapFlags Flags) {
3916   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3917     return getConstant(
3918                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3919 
3920   Type *Ty = V->getType();
3921   Ty = getEffectiveSCEVType(Ty);
3922   return getMulExpr(V, getMinusOne(Ty), Flags);
3923 }
3924 
3925 /// If Expr computes ~A, return A else return nullptr
MatchNotExpr(const SCEV * Expr)3926 static const SCEV *MatchNotExpr(const SCEV *Expr) {
3927   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
3928   if (!Add || Add->getNumOperands() != 2 ||
3929       !Add->getOperand(0)->isAllOnesValue())
3930     return nullptr;
3931 
3932   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
3933   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
3934       !AddRHS->getOperand(0)->isAllOnesValue())
3935     return nullptr;
3936 
3937   return AddRHS->getOperand(1);
3938 }
3939 
3940 /// Return a SCEV corresponding to ~V = -1-V
getNotSCEV(const SCEV * V)3941 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3942   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3943     return getConstant(
3944                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3945 
3946   // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
3947   if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
3948     auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
3949       SmallVector<const SCEV *, 2> MatchedOperands;
3950       for (const SCEV *Operand : MME->operands()) {
3951         const SCEV *Matched = MatchNotExpr(Operand);
3952         if (!Matched)
3953           return (const SCEV *)nullptr;
3954         MatchedOperands.push_back(Matched);
3955       }
3956       return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
3957                            MatchedOperands);
3958     };
3959     if (const SCEV *Replaced = MatchMinMaxNegation(MME))
3960       return Replaced;
3961   }
3962 
3963   Type *Ty = V->getType();
3964   Ty = getEffectiveSCEVType(Ty);
3965   return getMinusSCEV(getMinusOne(Ty), V);
3966 }
3967 
getMinusSCEV(const SCEV * LHS,const SCEV * RHS,SCEV::NoWrapFlags Flags,unsigned Depth)3968 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3969                                           SCEV::NoWrapFlags Flags,
3970                                           unsigned Depth) {
3971   // Fast path: X - X --> 0.
3972   if (LHS == RHS)
3973     return getZero(LHS->getType());
3974 
3975   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3976   // makes it so that we cannot make much use of NUW.
3977   auto AddFlags = SCEV::FlagAnyWrap;
3978   const bool RHSIsNotMinSigned =
3979       !getSignedRangeMin(RHS).isMinSignedValue();
3980   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3981     // Let M be the minimum representable signed value. Then (-1)*RHS
3982     // signed-wraps if and only if RHS is M. That can happen even for
3983     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3984     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3985     // (-1)*RHS, we need to prove that RHS != M.
3986     //
3987     // If LHS is non-negative and we know that LHS - RHS does not
3988     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3989     // either by proving that RHS > M or that LHS >= 0.
3990     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3991       AddFlags = SCEV::FlagNSW;
3992     }
3993   }
3994 
3995   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3996   // RHS is NSW and LHS >= 0.
3997   //
3998   // The difficulty here is that the NSW flag may have been proven
3999   // relative to a loop that is to be found in a recurrence in LHS and
4000   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4001   // larger scope than intended.
4002   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4003 
4004   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4005 }
4006 
getTruncateOrZeroExtend(const SCEV * V,Type * Ty,unsigned Depth)4007 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4008                                                      unsigned Depth) {
4009   Type *SrcTy = V->getType();
4010   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4011          "Cannot truncate or zero extend with non-integer arguments!");
4012   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4013     return V;  // No conversion
4014   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4015     return getTruncateExpr(V, Ty, Depth);
4016   return getZeroExtendExpr(V, Ty, Depth);
4017 }
4018 
getTruncateOrSignExtend(const SCEV * V,Type * Ty,unsigned Depth)4019 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4020                                                      unsigned Depth) {
4021   Type *SrcTy = V->getType();
4022   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4023          "Cannot truncate or zero extend with non-integer arguments!");
4024   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4025     return V;  // No conversion
4026   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4027     return getTruncateExpr(V, Ty, Depth);
4028   return getSignExtendExpr(V, Ty, Depth);
4029 }
4030 
4031 const SCEV *
getNoopOrZeroExtend(const SCEV * V,Type * Ty)4032 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4033   Type *SrcTy = V->getType();
4034   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4035          "Cannot noop or zero extend with non-integer arguments!");
4036   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4037          "getNoopOrZeroExtend cannot truncate!");
4038   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4039     return V;  // No conversion
4040   return getZeroExtendExpr(V, Ty);
4041 }
4042 
4043 const SCEV *
getNoopOrSignExtend(const SCEV * V,Type * Ty)4044 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4045   Type *SrcTy = V->getType();
4046   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4047          "Cannot noop or sign extend with non-integer arguments!");
4048   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4049          "getNoopOrSignExtend cannot truncate!");
4050   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4051     return V;  // No conversion
4052   return getSignExtendExpr(V, Ty);
4053 }
4054 
4055 const SCEV *
getNoopOrAnyExtend(const SCEV * V,Type * Ty)4056 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4057   Type *SrcTy = V->getType();
4058   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4059          "Cannot noop or any extend with non-integer arguments!");
4060   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4061          "getNoopOrAnyExtend cannot truncate!");
4062   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4063     return V;  // No conversion
4064   return getAnyExtendExpr(V, Ty);
4065 }
4066 
4067 const SCEV *
getTruncateOrNoop(const SCEV * V,Type * Ty)4068 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4069   Type *SrcTy = V->getType();
4070   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4071          "Cannot truncate or noop with non-integer arguments!");
4072   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4073          "getTruncateOrNoop cannot extend!");
4074   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4075     return V;  // No conversion
4076   return getTruncateExpr(V, Ty);
4077 }
4078 
getUMaxFromMismatchedTypes(const SCEV * LHS,const SCEV * RHS)4079 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4080                                                         const SCEV *RHS) {
4081   const SCEV *PromotedLHS = LHS;
4082   const SCEV *PromotedRHS = RHS;
4083 
4084   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4085     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4086   else
4087     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4088 
4089   return getUMaxExpr(PromotedLHS, PromotedRHS);
4090 }
4091 
getUMinFromMismatchedTypes(const SCEV * LHS,const SCEV * RHS)4092 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4093                                                         const SCEV *RHS) {
4094   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4095   return getUMinFromMismatchedTypes(Ops);
4096 }
4097 
getUMinFromMismatchedTypes(SmallVectorImpl<const SCEV * > & Ops)4098 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
4099     SmallVectorImpl<const SCEV *> &Ops) {
4100   assert(!Ops.empty() && "At least one operand must be!");
4101   // Trivial case.
4102   if (Ops.size() == 1)
4103     return Ops[0];
4104 
4105   // Find the max type first.
4106   Type *MaxType = nullptr;
4107   for (auto *S : Ops)
4108     if (MaxType)
4109       MaxType = getWiderType(MaxType, S->getType());
4110     else
4111       MaxType = S->getType();
4112   assert(MaxType && "Failed to find maximum type!");
4113 
4114   // Extend all ops to max type.
4115   SmallVector<const SCEV *, 2> PromotedOps;
4116   for (auto *S : Ops)
4117     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4118 
4119   // Generate umin.
4120   return getUMinExpr(PromotedOps);
4121 }
4122 
getPointerBase(const SCEV * V)4123 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4124   // A pointer operand may evaluate to a nonpointer expression, such as null.
4125   if (!V->getType()->isPointerTy())
4126     return V;
4127 
4128   while (true) {
4129     if (const SCEVIntegralCastExpr *Cast = dyn_cast<SCEVIntegralCastExpr>(V)) {
4130       V = Cast->getOperand();
4131     } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4132       const SCEV *PtrOp = nullptr;
4133       for (const SCEV *NAryOp : NAry->operands()) {
4134         if (NAryOp->getType()->isPointerTy()) {
4135           // Cannot find the base of an expression with multiple pointer ops.
4136           if (PtrOp)
4137             return V;
4138           PtrOp = NAryOp;
4139         }
4140       }
4141       if (!PtrOp) // All operands were non-pointer.
4142         return V;
4143       V = PtrOp;
4144     } else // Not something we can look further into.
4145       return V;
4146   }
4147 }
4148 
4149 /// Push users of the given Instruction onto the given Worklist.
4150 static void
PushDefUseChildren(Instruction * I,SmallVectorImpl<Instruction * > & Worklist)4151 PushDefUseChildren(Instruction *I,
4152                    SmallVectorImpl<Instruction *> &Worklist) {
4153   // Push the def-use children onto the Worklist stack.
4154   for (User *U : I->users())
4155     Worklist.push_back(cast<Instruction>(U));
4156 }
4157 
forgetSymbolicName(Instruction * PN,const SCEV * SymName)4158 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4159   SmallVector<Instruction *, 16> Worklist;
4160   PushDefUseChildren(PN, Worklist);
4161 
4162   SmallPtrSet<Instruction *, 8> Visited;
4163   Visited.insert(PN);
4164   while (!Worklist.empty()) {
4165     Instruction *I = Worklist.pop_back_val();
4166     if (!Visited.insert(I).second)
4167       continue;
4168 
4169     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4170     if (It != ValueExprMap.end()) {
4171       const SCEV *Old = It->second;
4172 
4173       // Short-circuit the def-use traversal if the symbolic name
4174       // ceases to appear in expressions.
4175       if (Old != SymName && !hasOperand(Old, SymName))
4176         continue;
4177 
4178       // SCEVUnknown for a PHI either means that it has an unrecognized
4179       // structure, it's a PHI that's in the progress of being computed
4180       // by createNodeForPHI, or it's a single-value PHI. In the first case,
4181       // additional loop trip count information isn't going to change anything.
4182       // In the second case, createNodeForPHI will perform the necessary
4183       // updates on its own when it gets to that point. In the third, we do
4184       // want to forget the SCEVUnknown.
4185       if (!isa<PHINode>(I) ||
4186           !isa<SCEVUnknown>(Old) ||
4187           (I != PN && Old == SymName)) {
4188         eraseValueFromMap(It->first);
4189         forgetMemoizedResults(Old);
4190       }
4191     }
4192 
4193     PushDefUseChildren(I, Worklist);
4194   }
4195 }
4196 
4197 namespace {
4198 
4199 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4200 /// expression in case its Loop is L. If it is not L then
4201 /// if IgnoreOtherLoops is true then use AddRec itself
4202 /// otherwise rewrite cannot be done.
4203 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4204 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4205 public:
rewrite(const SCEV * S,const Loop * L,ScalarEvolution & SE,bool IgnoreOtherLoops=true)4206   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4207                              bool IgnoreOtherLoops = true) {
4208     SCEVInitRewriter Rewriter(L, SE);
4209     const SCEV *Result = Rewriter.visit(S);
4210     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4211       return SE.getCouldNotCompute();
4212     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4213                ? SE.getCouldNotCompute()
4214                : Result;
4215   }
4216 
visitUnknown(const SCEVUnknown * Expr)4217   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4218     if (!SE.isLoopInvariant(Expr, L))
4219       SeenLoopVariantSCEVUnknown = true;
4220     return Expr;
4221   }
4222 
visitAddRecExpr(const SCEVAddRecExpr * Expr)4223   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4224     // Only re-write AddRecExprs for this loop.
4225     if (Expr->getLoop() == L)
4226       return Expr->getStart();
4227     SeenOtherLoops = true;
4228     return Expr;
4229   }
4230 
hasSeenLoopVariantSCEVUnknown()4231   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4232 
hasSeenOtherLoops()4233   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4234 
4235 private:
SCEVInitRewriter(const Loop * L,ScalarEvolution & SE)4236   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4237       : SCEVRewriteVisitor(SE), L(L) {}
4238 
4239   const Loop *L;
4240   bool SeenLoopVariantSCEVUnknown = false;
4241   bool SeenOtherLoops = false;
4242 };
4243 
4244 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4245 /// increment expression in case its Loop is L. If it is not L then
4246 /// use AddRec itself.
4247 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4248 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4249 public:
rewrite(const SCEV * S,const Loop * L,ScalarEvolution & SE)4250   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4251     SCEVPostIncRewriter Rewriter(L, SE);
4252     const SCEV *Result = Rewriter.visit(S);
4253     return Rewriter.hasSeenLoopVariantSCEVUnknown()
4254         ? SE.getCouldNotCompute()
4255         : Result;
4256   }
4257 
visitUnknown(const SCEVUnknown * Expr)4258   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4259     if (!SE.isLoopInvariant(Expr, L))
4260       SeenLoopVariantSCEVUnknown = true;
4261     return Expr;
4262   }
4263 
visitAddRecExpr(const SCEVAddRecExpr * Expr)4264   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4265     // Only re-write AddRecExprs for this loop.
4266     if (Expr->getLoop() == L)
4267       return Expr->getPostIncExpr(SE);
4268     SeenOtherLoops = true;
4269     return Expr;
4270   }
4271 
hasSeenLoopVariantSCEVUnknown()4272   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4273 
hasSeenOtherLoops()4274   bool hasSeenOtherLoops() { return SeenOtherLoops; }
4275 
4276 private:
SCEVPostIncRewriter(const Loop * L,ScalarEvolution & SE)4277   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4278       : SCEVRewriteVisitor(SE), L(L) {}
4279 
4280   const Loop *L;
4281   bool SeenLoopVariantSCEVUnknown = false;
4282   bool SeenOtherLoops = false;
4283 };
4284 
4285 /// This class evaluates the compare condition by matching it against the
4286 /// condition of loop latch. If there is a match we assume a true value
4287 /// for the condition while building SCEV nodes.
4288 class SCEVBackedgeConditionFolder
4289     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4290 public:
rewrite(const SCEV * S,const Loop * L,ScalarEvolution & SE)4291   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4292                              ScalarEvolution &SE) {
4293     bool IsPosBECond = false;
4294     Value *BECond = nullptr;
4295     if (BasicBlock *Latch = L->getLoopLatch()) {
4296       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4297       if (BI && BI->isConditional()) {
4298         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4299                "Both outgoing branches should not target same header!");
4300         BECond = BI->getCondition();
4301         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4302       } else {
4303         return S;
4304       }
4305     }
4306     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4307     return Rewriter.visit(S);
4308   }
4309 
visitUnknown(const SCEVUnknown * Expr)4310   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4311     const SCEV *Result = Expr;
4312     bool InvariantF = SE.isLoopInvariant(Expr, L);
4313 
4314     if (!InvariantF) {
4315       Instruction *I = cast<Instruction>(Expr->getValue());
4316       switch (I->getOpcode()) {
4317       case Instruction::Select: {
4318         SelectInst *SI = cast<SelectInst>(I);
4319         Optional<const SCEV *> Res =
4320             compareWithBackedgeCondition(SI->getCondition());
4321         if (Res.hasValue()) {
4322           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4323           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4324         }
4325         break;
4326       }
4327       default: {
4328         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4329         if (Res.hasValue())
4330           Result = Res.getValue();
4331         break;
4332       }
4333       }
4334     }
4335     return Result;
4336   }
4337 
4338 private:
SCEVBackedgeConditionFolder(const Loop * L,Value * BECond,bool IsPosBECond,ScalarEvolution & SE)4339   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4340                                        bool IsPosBECond, ScalarEvolution &SE)
4341       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4342         IsPositiveBECond(IsPosBECond) {}
4343 
4344   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4345 
4346   const Loop *L;
4347   /// Loop back condition.
4348   Value *BackedgeCond = nullptr;
4349   /// Set to true if loop back is on positive branch condition.
4350   bool IsPositiveBECond;
4351 };
4352 
4353 Optional<const SCEV *>
compareWithBackedgeCondition(Value * IC)4354 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4355 
4356   // If value matches the backedge condition for loop latch,
4357   // then return a constant evolution node based on loopback
4358   // branch taken.
4359   if (BackedgeCond == IC)
4360     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4361                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
4362   return None;
4363 }
4364 
4365 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4366 public:
rewrite(const SCEV * S,const Loop * L,ScalarEvolution & SE)4367   static const SCEV *rewrite(const SCEV *S, const Loop *L,
4368                              ScalarEvolution &SE) {
4369     SCEVShiftRewriter Rewriter(L, SE);
4370     const SCEV *Result = Rewriter.visit(S);
4371     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4372   }
4373 
visitUnknown(const SCEVUnknown * Expr)4374   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4375     // Only allow AddRecExprs for this loop.
4376     if (!SE.isLoopInvariant(Expr, L))
4377       Valid = false;
4378     return Expr;
4379   }
4380 
visitAddRecExpr(const SCEVAddRecExpr * Expr)4381   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4382     if (Expr->getLoop() == L && Expr->isAffine())
4383       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4384     Valid = false;
4385     return Expr;
4386   }
4387 
isValid()4388   bool isValid() { return Valid; }
4389 
4390 private:
SCEVShiftRewriter(const Loop * L,ScalarEvolution & SE)4391   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4392       : SCEVRewriteVisitor(SE), L(L) {}
4393 
4394   const Loop *L;
4395   bool Valid = true;
4396 };
4397 
4398 } // end anonymous namespace
4399 
4400 SCEV::NoWrapFlags
proveNoWrapViaConstantRanges(const SCEVAddRecExpr * AR)4401 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4402   if (!AR->isAffine())
4403     return SCEV::FlagAnyWrap;
4404 
4405   using OBO = OverflowingBinaryOperator;
4406 
4407   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4408 
4409   if (!AR->hasNoSignedWrap()) {
4410     ConstantRange AddRecRange = getSignedRange(AR);
4411     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4412 
4413     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4414         Instruction::Add, IncRange, OBO::NoSignedWrap);
4415     if (NSWRegion.contains(AddRecRange))
4416       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4417   }
4418 
4419   if (!AR->hasNoUnsignedWrap()) {
4420     ConstantRange AddRecRange = getUnsignedRange(AR);
4421     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4422 
4423     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4424         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4425     if (NUWRegion.contains(AddRecRange))
4426       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4427   }
4428 
4429   return Result;
4430 }
4431 
4432 SCEV::NoWrapFlags
proveNoSignedWrapViaInduction(const SCEVAddRecExpr * AR)4433 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4434   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4435 
4436   if (AR->hasNoSignedWrap())
4437     return Result;
4438 
4439   if (!AR->isAffine())
4440     return Result;
4441 
4442   const SCEV *Step = AR->getStepRecurrence(*this);
4443   const Loop *L = AR->getLoop();
4444 
4445   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4446   // Note that this serves two purposes: It filters out loops that are
4447   // simply not analyzable, and it covers the case where this code is
4448   // being called from within backedge-taken count analysis, such that
4449   // attempting to ask for the backedge-taken count would likely result
4450   // in infinite recursion. In the later case, the analysis code will
4451   // cope with a conservative value, and it will take care to purge
4452   // that value once it has finished.
4453   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4454 
4455   // Normally, in the cases we can prove no-overflow via a
4456   // backedge guarding condition, we can also compute a backedge
4457   // taken count for the loop.  The exceptions are assumptions and
4458   // guards present in the loop -- SCEV is not great at exploiting
4459   // these to compute max backedge taken counts, but can still use
4460   // these to prove lack of overflow.  Use this fact to avoid
4461   // doing extra work that may not pay off.
4462 
4463   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4464       AC.assumptions().empty())
4465     return Result;
4466 
4467   // If the backedge is guarded by a comparison with the pre-inc  value the
4468   // addrec is safe. Also, if the entry is guarded by a comparison with the
4469   // start value and the backedge is guarded by a comparison with the post-inc
4470   // value, the addrec is safe.
4471   ICmpInst::Predicate Pred;
4472   const SCEV *OverflowLimit =
4473     getSignedOverflowLimitForStep(Step, &Pred, this);
4474   if (OverflowLimit &&
4475       (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
4476        isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
4477     Result = setFlags(Result, SCEV::FlagNSW);
4478   }
4479   return Result;
4480 }
4481 SCEV::NoWrapFlags
proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr * AR)4482 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4483   SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4484 
4485   if (AR->hasNoUnsignedWrap())
4486     return Result;
4487 
4488   if (!AR->isAffine())
4489     return Result;
4490 
4491   const SCEV *Step = AR->getStepRecurrence(*this);
4492   unsigned BitWidth = getTypeSizeInBits(AR->getType());
4493   const Loop *L = AR->getLoop();
4494 
4495   // Check whether the backedge-taken count is SCEVCouldNotCompute.
4496   // Note that this serves two purposes: It filters out loops that are
4497   // simply not analyzable, and it covers the case where this code is
4498   // being called from within backedge-taken count analysis, such that
4499   // attempting to ask for the backedge-taken count would likely result
4500   // in infinite recursion. In the later case, the analysis code will
4501   // cope with a conservative value, and it will take care to purge
4502   // that value once it has finished.
4503   const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4504 
4505   // Normally, in the cases we can prove no-overflow via a
4506   // backedge guarding condition, we can also compute a backedge
4507   // taken count for the loop.  The exceptions are assumptions and
4508   // guards present in the loop -- SCEV is not great at exploiting
4509   // these to compute max backedge taken counts, but can still use
4510   // these to prove lack of overflow.  Use this fact to avoid
4511   // doing extra work that may not pay off.
4512 
4513   if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4514       AC.assumptions().empty())
4515     return Result;
4516 
4517   // If the backedge is guarded by a comparison with the pre-inc  value the
4518   // addrec is safe. Also, if the entry is guarded by a comparison with the
4519   // start value and the backedge is guarded by a comparison with the post-inc
4520   // value, the addrec is safe.
4521   if (isKnownPositive(Step)) {
4522     const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
4523                                 getUnsignedRangeMax(Step));
4524     if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
4525         isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
4526       Result = setFlags(Result, SCEV::FlagNUW);
4527     }
4528   }
4529 
4530   return Result;
4531 }
4532 
4533 namespace {
4534 
4535 /// Represents an abstract binary operation.  This may exist as a
4536 /// normal instruction or constant expression, or may have been
4537 /// derived from an expression tree.
4538 struct BinaryOp {
4539   unsigned Opcode;
4540   Value *LHS;
4541   Value *RHS;
4542   bool IsNSW = false;
4543   bool IsNUW = false;
4544   bool IsExact = false;
4545 
4546   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4547   /// constant expression.
4548   Operator *Op = nullptr;
4549 
BinaryOp__anon83ba15151111::BinaryOp4550   explicit BinaryOp(Operator *Op)
4551       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4552         Op(Op) {
4553     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4554       IsNSW = OBO->hasNoSignedWrap();
4555       IsNUW = OBO->hasNoUnsignedWrap();
4556     }
4557     if (auto *PEO = dyn_cast<PossiblyExactOperator>(Op))
4558       IsExact = PEO->isExact();
4559   }
4560 
BinaryOp__anon83ba15151111::BinaryOp4561   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4562                     bool IsNUW = false, bool IsExact = false)
4563       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
4564         IsExact(IsExact) {}
4565 };
4566 
4567 } // end anonymous namespace
4568 
4569 /// Try to map \p V into a BinaryOp, and return \c None on failure.
MatchBinaryOp(Value * V,DominatorTree & DT)4570 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4571   auto *Op = dyn_cast<Operator>(V);
4572   if (!Op)
4573     return None;
4574 
4575   // Implementation detail: all the cleverness here should happen without
4576   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4577   // SCEV expressions when possible, and we should not break that.
4578 
4579   switch (Op->getOpcode()) {
4580   case Instruction::Add:
4581   case Instruction::Sub:
4582   case Instruction::Mul:
4583   case Instruction::UDiv:
4584   case Instruction::URem:
4585   case Instruction::And:
4586   case Instruction::Or:
4587   case Instruction::AShr:
4588   case Instruction::Shl:
4589     return BinaryOp(Op);
4590 
4591   case Instruction::Xor:
4592     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4593       // If the RHS of the xor is a signmask, then this is just an add.
4594       // Instcombine turns add of signmask into xor as a strength reduction step.
4595       if (RHSC->getValue().isSignMask())
4596         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4597     return BinaryOp(Op);
4598 
4599   case Instruction::LShr:
4600     // Turn logical shift right of a constant into a unsigned divide.
4601     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4602       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4603 
4604       // If the shift count is not less than the bitwidth, the result of
4605       // the shift is undefined. Don't try to analyze it, because the
4606       // resolution chosen here may differ from the resolution chosen in
4607       // other parts of the compiler.
4608       if (SA->getValue().ult(BitWidth)) {
4609         Constant *X =
4610             ConstantInt::get(SA->getContext(),
4611                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4612         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4613       }
4614     }
4615     return BinaryOp(Op);
4616 
4617   case Instruction::ExtractValue: {
4618     auto *EVI = cast<ExtractValueInst>(Op);
4619     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4620       break;
4621 
4622     auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
4623     if (!WO)
4624       break;
4625 
4626     Instruction::BinaryOps BinOp = WO->getBinaryOp();
4627     bool Signed = WO->isSigned();
4628     // TODO: Should add nuw/nsw flags for mul as well.
4629     if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
4630       return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
4631 
4632     // Now that we know that all uses of the arithmetic-result component of
4633     // CI are guarded by the overflow check, we can go ahead and pretend
4634     // that the arithmetic is non-overflowing.
4635     return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
4636                     /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
4637   }
4638 
4639   default:
4640     break;
4641   }
4642 
4643   // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
4644   // semantics as a Sub, return a binary sub expression.
4645   if (auto *II = dyn_cast<IntrinsicInst>(V))
4646     if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
4647       return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
4648 
4649   return None;
4650 }
4651 
4652 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4653 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4654 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4655 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4656 /// follows one of the following patterns:
4657 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4658 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4659 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4660 /// we return the type of the truncation operation, and indicate whether the
4661 /// truncated type should be treated as signed/unsigned by setting
4662 /// \p Signed to true/false, respectively.
isSimpleCastedPHI(const SCEV * Op,const SCEVUnknown * SymbolicPHI,bool & Signed,ScalarEvolution & SE)4663 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4664                                bool &Signed, ScalarEvolution &SE) {
4665   // The case where Op == SymbolicPHI (that is, with no type conversions on
4666   // the way) is handled by the regular add recurrence creating logic and
4667   // would have already been triggered in createAddRecForPHI. Reaching it here
4668   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4669   // because one of the other operands of the SCEVAddExpr updating this PHI is
4670   // not invariant).
4671   //
4672   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4673   // this case predicates that allow us to prove that Op == SymbolicPHI will
4674   // be added.
4675   if (Op == SymbolicPHI)
4676     return nullptr;
4677 
4678   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4679   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4680   if (SourceBits != NewBits)
4681     return nullptr;
4682 
4683   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4684   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4685   if (!SExt && !ZExt)
4686     return nullptr;
4687   const SCEVTruncateExpr *Trunc =
4688       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4689            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4690   if (!Trunc)
4691     return nullptr;
4692   const SCEV *X = Trunc->getOperand();
4693   if (X != SymbolicPHI)
4694     return nullptr;
4695   Signed = SExt != nullptr;
4696   return Trunc->getType();
4697 }
4698 
isIntegerLoopHeaderPHI(const PHINode * PN,LoopInfo & LI)4699 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4700   if (!PN->getType()->isIntegerTy())
4701     return nullptr;
4702   const Loop *L = LI.getLoopFor(PN->getParent());
4703   if (!L || L->getHeader() != PN->getParent())
4704     return nullptr;
4705   return L;
4706 }
4707 
4708 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4709 // computation that updates the phi follows the following pattern:
4710 //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4711 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4712 // If so, try to see if it can be rewritten as an AddRecExpr under some
4713 // Predicates. If successful, return them as a pair. Also cache the results
4714 // of the analysis.
4715 //
4716 // Example usage scenario:
4717 //    Say the Rewriter is called for the following SCEV:
4718 //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4719 //    where:
4720 //         %X = phi i64 (%Start, %BEValue)
4721 //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4722 //    and call this function with %SymbolicPHI = %X.
4723 //
4724 //    The analysis will find that the value coming around the backedge has
4725 //    the following SCEV:
4726 //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4727 //    Upon concluding that this matches the desired pattern, the function
4728 //    will return the pair {NewAddRec, SmallPredsVec} where:
4729 //         NewAddRec = {%Start,+,%Step}
4730 //         SmallPredsVec = {P1, P2, P3} as follows:
4731 //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4732 //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4733 //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4734 //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4735 //    under the predicates {P1,P2,P3}.
4736 //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
4737 //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4738 //
4739 // TODO's:
4740 //
4741 // 1) Extend the Induction descriptor to also support inductions that involve
4742 //    casts: When needed (namely, when we are called in the context of the
4743 //    vectorizer induction analysis), a Set of cast instructions will be
4744 //    populated by this method, and provided back to isInductionPHI. This is
4745 //    needed to allow the vectorizer to properly record them to be ignored by
4746 //    the cost model and to avoid vectorizing them (otherwise these casts,
4747 //    which are redundant under the runtime overflow checks, will be
4748 //    vectorized, which can be costly).
4749 //
4750 // 2) Support additional induction/PHISCEV patterns: We also want to support
4751 //    inductions where the sext-trunc / zext-trunc operations (partly) occur
4752 //    after the induction update operation (the induction increment):
4753 //
4754 //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4755 //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
4756 //
4757 //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4758 //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
4759 //
4760 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4761 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
createAddRecFromPHIWithCastsImpl(const SCEVUnknown * SymbolicPHI)4762 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4763   SmallVector<const SCEVPredicate *, 3> Predicates;
4764 
4765   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4766   // return an AddRec expression under some predicate.
4767 
4768   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4769   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4770   assert(L && "Expecting an integer loop header phi");
4771 
4772   // The loop may have multiple entrances or multiple exits; we can analyze
4773   // this phi as an addrec if it has a unique entry value and a unique
4774   // backedge value.
4775   Value *BEValueV = nullptr, *StartValueV = nullptr;
4776   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4777     Value *V = PN->getIncomingValue(i);
4778     if (L->contains(PN->getIncomingBlock(i))) {
4779       if (!BEValueV) {
4780         BEValueV = V;
4781       } else if (BEValueV != V) {
4782         BEValueV = nullptr;
4783         break;
4784       }
4785     } else if (!StartValueV) {
4786       StartValueV = V;
4787     } else if (StartValueV != V) {
4788       StartValueV = nullptr;
4789       break;
4790     }
4791   }
4792   if (!BEValueV || !StartValueV)
4793     return None;
4794 
4795   const SCEV *BEValue = getSCEV(BEValueV);
4796 
4797   // If the value coming around the backedge is an add with the symbolic
4798   // value we just inserted, possibly with casts that we can ignore under
4799   // an appropriate runtime guard, then we found a simple induction variable!
4800   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4801   if (!Add)
4802     return None;
4803 
4804   // If there is a single occurrence of the symbolic value, possibly
4805   // casted, replace it with a recurrence.
4806   unsigned FoundIndex = Add->getNumOperands();
4807   Type *TruncTy = nullptr;
4808   bool Signed;
4809   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4810     if ((TruncTy =
4811              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4812       if (FoundIndex == e) {
4813         FoundIndex = i;
4814         break;
4815       }
4816 
4817   if (FoundIndex == Add->getNumOperands())
4818     return None;
4819 
4820   // Create an add with everything but the specified operand.
4821   SmallVector<const SCEV *, 8> Ops;
4822   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4823     if (i != FoundIndex)
4824       Ops.push_back(Add->getOperand(i));
4825   const SCEV *Accum = getAddExpr(Ops);
4826 
4827   // The runtime checks will not be valid if the step amount is
4828   // varying inside the loop.
4829   if (!isLoopInvariant(Accum, L))
4830     return None;
4831 
4832   // *** Part2: Create the predicates
4833 
4834   // Analysis was successful: we have a phi-with-cast pattern for which we
4835   // can return an AddRec expression under the following predicates:
4836   //
4837   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4838   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
4839   // P2: An Equal predicate that guarantees that
4840   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4841   // P3: An Equal predicate that guarantees that
4842   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4843   //
4844   // As we next prove, the above predicates guarantee that:
4845   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4846   //
4847   //
4848   // More formally, we want to prove that:
4849   //     Expr(i+1) = Start + (i+1) * Accum
4850   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4851   //
4852   // Given that:
4853   // 1) Expr(0) = Start
4854   // 2) Expr(1) = Start + Accum
4855   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4856   // 3) Induction hypothesis (step i):
4857   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4858   //
4859   // Proof:
4860   //  Expr(i+1) =
4861   //   = Start + (i+1)*Accum
4862   //   = (Start + i*Accum) + Accum
4863   //   = Expr(i) + Accum
4864   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4865   //                                                             :: from step i
4866   //
4867   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4868   //
4869   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4870   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
4871   //     + Accum                                                     :: from P3
4872   //
4873   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4874   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4875   //
4876   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4877   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4878   //
4879   // By induction, the same applies to all iterations 1<=i<n:
4880   //
4881 
4882   // Create a truncated addrec for which we will add a no overflow check (P1).
4883   const SCEV *StartVal = getSCEV(StartValueV);
4884   const SCEV *PHISCEV =
4885       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4886                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4887 
4888   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4889   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4890   // will be constant.
4891   //
4892   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4893   // add P1.
4894   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4895     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4896         Signed ? SCEVWrapPredicate::IncrementNSSW
4897                : SCEVWrapPredicate::IncrementNUSW;
4898     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4899     Predicates.push_back(AddRecPred);
4900   }
4901 
4902   // Create the Equal Predicates P2,P3:
4903 
4904   // It is possible that the predicates P2 and/or P3 are computable at
4905   // compile time due to StartVal and/or Accum being constants.
4906   // If either one is, then we can check that now and escape if either P2
4907   // or P3 is false.
4908 
4909   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4910   // for each of StartVal and Accum
4911   auto getExtendedExpr = [&](const SCEV *Expr,
4912                              bool CreateSignExtend) -> const SCEV * {
4913     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4914     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4915     const SCEV *ExtendedExpr =
4916         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4917                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4918     return ExtendedExpr;
4919   };
4920 
4921   // Given:
4922   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4923   //               = getExtendedExpr(Expr)
4924   // Determine whether the predicate P: Expr == ExtendedExpr
4925   // is known to be false at compile time
4926   auto PredIsKnownFalse = [&](const SCEV *Expr,
4927                               const SCEV *ExtendedExpr) -> bool {
4928     return Expr != ExtendedExpr &&
4929            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4930   };
4931 
4932   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4933   if (PredIsKnownFalse(StartVal, StartExtended)) {
4934     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
4935     return None;
4936   }
4937 
4938   // The Step is always Signed (because the overflow checks are either
4939   // NSSW or NUSW)
4940   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4941   if (PredIsKnownFalse(Accum, AccumExtended)) {
4942     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
4943     return None;
4944   }
4945 
4946   auto AppendPredicate = [&](const SCEV *Expr,
4947                              const SCEV *ExtendedExpr) -> void {
4948     if (Expr != ExtendedExpr &&
4949         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4950       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4951       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
4952       Predicates.push_back(Pred);
4953     }
4954   };
4955 
4956   AppendPredicate(StartVal, StartExtended);
4957   AppendPredicate(Accum, AccumExtended);
4958 
4959   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4960   // which the casts had been folded away. The caller can rewrite SymbolicPHI
4961   // into NewAR if it will also add the runtime overflow checks specified in
4962   // Predicates.
4963   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4964 
4965   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4966       std::make_pair(NewAR, Predicates);
4967   // Remember the result of the analysis for this SCEV at this locayyytion.
4968   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4969   return PredRewrite;
4970 }
4971 
4972 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
createAddRecFromPHIWithCasts(const SCEVUnknown * SymbolicPHI)4973 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4974   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4975   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4976   if (!L)
4977     return None;
4978 
4979   // Check to see if we already analyzed this PHI.
4980   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4981   if (I != PredicatedSCEVRewrites.end()) {
4982     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4983         I->second;
4984     // Analysis was done before and failed to create an AddRec:
4985     if (Rewrite.first == SymbolicPHI)
4986       return None;
4987     // Analysis was done before and succeeded to create an AddRec under
4988     // a predicate:
4989     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
4990     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
4991     return Rewrite;
4992   }
4993 
4994   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4995     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4996 
4997   // Record in the cache that the analysis failed
4998   if (!Rewrite) {
4999     SmallVector<const SCEVPredicate *, 3> Predicates;
5000     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5001     return None;
5002   }
5003 
5004   return Rewrite;
5005 }
5006 
5007 // FIXME: This utility is currently required because the Rewriter currently
5008 // does not rewrite this expression:
5009 // {0, +, (sext ix (trunc iy to ix) to iy)}
5010 // into {0, +, %step},
5011 // even when the following Equal predicate exists:
5012 // "%step == (sext ix (trunc iy to ix) to iy)".
areAddRecsEqualWithPreds(const SCEVAddRecExpr * AR1,const SCEVAddRecExpr * AR2) const5013 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5014     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
5015   if (AR1 == AR2)
5016     return true;
5017 
5018   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5019     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
5020         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
5021       return false;
5022     return true;
5023   };
5024 
5025   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5026       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5027     return false;
5028   return true;
5029 }
5030 
5031 /// A helper function for createAddRecFromPHI to handle simple cases.
5032 ///
5033 /// This function tries to find an AddRec expression for the simplest (yet most
5034 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5035 /// If it fails, createAddRecFromPHI will use a more general, but slow,
5036 /// technique for finding the AddRec expression.
createSimpleAffineAddRec(PHINode * PN,Value * BEValueV,Value * StartValueV)5037 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5038                                                       Value *BEValueV,
5039                                                       Value *StartValueV) {
5040   const Loop *L = LI.getLoopFor(PN->getParent());
5041   assert(L && L->getHeader() == PN->getParent());
5042   assert(BEValueV && StartValueV);
5043 
5044   auto BO = MatchBinaryOp(BEValueV, DT);
5045   if (!BO)
5046     return nullptr;
5047 
5048   if (BO->Opcode != Instruction::Add)
5049     return nullptr;
5050 
5051   const SCEV *Accum = nullptr;
5052   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5053     Accum = getSCEV(BO->RHS);
5054   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5055     Accum = getSCEV(BO->LHS);
5056 
5057   if (!Accum)
5058     return nullptr;
5059 
5060   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5061   if (BO->IsNUW)
5062     Flags = setFlags(Flags, SCEV::FlagNUW);
5063   if (BO->IsNSW)
5064     Flags = setFlags(Flags, SCEV::FlagNSW);
5065 
5066   const SCEV *StartVal = getSCEV(StartValueV);
5067   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5068 
5069   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5070 
5071   // We can add Flags to the post-inc expression only if we
5072   // know that it is *undefined behavior* for BEValueV to
5073   // overflow.
5074   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5075     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5076       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5077 
5078   return PHISCEV;
5079 }
5080 
createAddRecFromPHI(PHINode * PN)5081 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5082   const Loop *L = LI.getLoopFor(PN->getParent());
5083   if (!L || L->getHeader() != PN->getParent())
5084     return nullptr;
5085 
5086   // The loop may have multiple entrances or multiple exits; we can analyze
5087   // this phi as an addrec if it has a unique entry value and a unique
5088   // backedge value.
5089   Value *BEValueV = nullptr, *StartValueV = nullptr;
5090   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5091     Value *V = PN->getIncomingValue(i);
5092     if (L->contains(PN->getIncomingBlock(i))) {
5093       if (!BEValueV) {
5094         BEValueV = V;
5095       } else if (BEValueV != V) {
5096         BEValueV = nullptr;
5097         break;
5098       }
5099     } else if (!StartValueV) {
5100       StartValueV = V;
5101     } else if (StartValueV != V) {
5102       StartValueV = nullptr;
5103       break;
5104     }
5105   }
5106   if (!BEValueV || !StartValueV)
5107     return nullptr;
5108 
5109   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5110          "PHI node already processed?");
5111 
5112   // First, try to find AddRec expression without creating a fictituos symbolic
5113   // value for PN.
5114   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5115     return S;
5116 
5117   // Handle PHI node value symbolically.
5118   const SCEV *SymbolicName = getUnknown(PN);
5119   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
5120 
5121   // Using this symbolic name for the PHI, analyze the value coming around
5122   // the back-edge.
5123   const SCEV *BEValue = getSCEV(BEValueV);
5124 
5125   // NOTE: If BEValue is loop invariant, we know that the PHI node just
5126   // has a special value for the first iteration of the loop.
5127 
5128   // If the value coming around the backedge is an add with the symbolic
5129   // value we just inserted, then we found a simple induction variable!
5130   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5131     // If there is a single occurrence of the symbolic value, replace it
5132     // with a recurrence.
5133     unsigned FoundIndex = Add->getNumOperands();
5134     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5135       if (Add->getOperand(i) == SymbolicName)
5136         if (FoundIndex == e) {
5137           FoundIndex = i;
5138           break;
5139         }
5140 
5141     if (FoundIndex != Add->getNumOperands()) {
5142       // Create an add with everything but the specified operand.
5143       SmallVector<const SCEV *, 8> Ops;
5144       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5145         if (i != FoundIndex)
5146           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5147                                                              L, *this));
5148       const SCEV *Accum = getAddExpr(Ops);
5149 
5150       // This is not a valid addrec if the step amount is varying each
5151       // loop iteration, but is not itself an addrec in this loop.
5152       if (isLoopInvariant(Accum, L) ||
5153           (isa<SCEVAddRecExpr>(Accum) &&
5154            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5155         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5156 
5157         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5158           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5159             if (BO->IsNUW)
5160               Flags = setFlags(Flags, SCEV::FlagNUW);
5161             if (BO->IsNSW)
5162               Flags = setFlags(Flags, SCEV::FlagNSW);
5163           }
5164         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5165           // If the increment is an inbounds GEP, then we know the address
5166           // space cannot be wrapped around. We cannot make any guarantee
5167           // about signed or unsigned overflow because pointers are
5168           // unsigned but we may have a negative index from the base
5169           // pointer. We can guarantee that no unsigned wrap occurs if the
5170           // indices form a positive value.
5171           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5172             Flags = setFlags(Flags, SCEV::FlagNW);
5173 
5174             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5175             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5176               Flags = setFlags(Flags, SCEV::FlagNUW);
5177           }
5178 
5179           // We cannot transfer nuw and nsw flags from subtraction
5180           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5181           // for instance.
5182         }
5183 
5184         const SCEV *StartVal = getSCEV(StartValueV);
5185         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5186 
5187         // Okay, for the entire analysis of this edge we assumed the PHI
5188         // to be symbolic.  We now need to go back and purge all of the
5189         // entries for the scalars that use the symbolic expression.
5190         forgetSymbolicName(PN, SymbolicName);
5191         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5192 
5193         // We can add Flags to the post-inc expression only if we
5194         // know that it is *undefined behavior* for BEValueV to
5195         // overflow.
5196         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5197           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5198             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5199 
5200         return PHISCEV;
5201       }
5202     }
5203   } else {
5204     // Otherwise, this could be a loop like this:
5205     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
5206     // In this case, j = {1,+,1}  and BEValue is j.
5207     // Because the other in-value of i (0) fits the evolution of BEValue
5208     // i really is an addrec evolution.
5209     //
5210     // We can generalize this saying that i is the shifted value of BEValue
5211     // by one iteration:
5212     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
5213     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5214     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5215     if (Shifted != getCouldNotCompute() &&
5216         Start != getCouldNotCompute()) {
5217       const SCEV *StartVal = getSCEV(StartValueV);
5218       if (Start == StartVal) {
5219         // Okay, for the entire analysis of this edge we assumed the PHI
5220         // to be symbolic.  We now need to go back and purge all of the
5221         // entries for the scalars that use the symbolic expression.
5222         forgetSymbolicName(PN, SymbolicName);
5223         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5224         return Shifted;
5225       }
5226     }
5227   }
5228 
5229   // Remove the temporary PHI node SCEV that has been inserted while intending
5230   // to create an AddRecExpr for this PHI node. We can not keep this temporary
5231   // as it will prevent later (possibly simpler) SCEV expressions to be added
5232   // to the ValueExprMap.
5233   eraseValueFromMap(PN);
5234 
5235   return nullptr;
5236 }
5237 
5238 // Checks if the SCEV S is available at BB.  S is considered available at BB
5239 // if S can be materialized at BB without introducing a fault.
IsAvailableOnEntry(const Loop * L,DominatorTree & DT,const SCEV * S,BasicBlock * BB)5240 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5241                                BasicBlock *BB) {
5242   struct CheckAvailable {
5243     bool TraversalDone = false;
5244     bool Available = true;
5245 
5246     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
5247     BasicBlock *BB = nullptr;
5248     DominatorTree &DT;
5249 
5250     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5251       : L(L), BB(BB), DT(DT) {}
5252 
5253     bool setUnavailable() {
5254       TraversalDone = true;
5255       Available = false;
5256       return false;
5257     }
5258 
5259     bool follow(const SCEV *S) {
5260       switch (S->getSCEVType()) {
5261       case scConstant:
5262       case scPtrToInt:
5263       case scTruncate:
5264       case scZeroExtend:
5265       case scSignExtend:
5266       case scAddExpr:
5267       case scMulExpr:
5268       case scUMaxExpr:
5269       case scSMaxExpr:
5270       case scUMinExpr:
5271       case scSMinExpr:
5272         // These expressions are available if their operand(s) is/are.
5273         return true;
5274 
5275       case scAddRecExpr: {
5276         // We allow add recurrences that are on the loop BB is in, or some
5277         // outer loop.  This guarantees availability because the value of the
5278         // add recurrence at BB is simply the "current" value of the induction
5279         // variable.  We can relax this in the future; for instance an add
5280         // recurrence on a sibling dominating loop is also available at BB.
5281         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5282         if (L && (ARLoop == L || ARLoop->contains(L)))
5283           return true;
5284 
5285         return setUnavailable();
5286       }
5287 
5288       case scUnknown: {
5289         // For SCEVUnknown, we check for simple dominance.
5290         const auto *SU = cast<SCEVUnknown>(S);
5291         Value *V = SU->getValue();
5292 
5293         if (isa<Argument>(V))
5294           return false;
5295 
5296         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5297           return false;
5298 
5299         return setUnavailable();
5300       }
5301 
5302       case scUDivExpr:
5303       case scCouldNotCompute:
5304         // We do not try to smart about these at all.
5305         return setUnavailable();
5306       }
5307       llvm_unreachable("Unknown SCEV kind!");
5308     }
5309 
5310     bool isDone() { return TraversalDone; }
5311   };
5312 
5313   CheckAvailable CA(L, BB, DT);
5314   SCEVTraversal<CheckAvailable> ST(CA);
5315 
5316   ST.visitAll(S);
5317   return CA.Available;
5318 }
5319 
5320 // Try to match a control flow sequence that branches out at BI and merges back
5321 // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
5322 // match.
BrPHIToSelect(DominatorTree & DT,BranchInst * BI,PHINode * Merge,Value * & C,Value * & LHS,Value * & RHS)5323 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5324                           Value *&C, Value *&LHS, Value *&RHS) {
5325   C = BI->getCondition();
5326 
5327   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5328   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5329 
5330   if (!LeftEdge.isSingleEdge())
5331     return false;
5332 
5333   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5334 
5335   Use &LeftUse = Merge->getOperandUse(0);
5336   Use &RightUse = Merge->getOperandUse(1);
5337 
5338   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5339     LHS = LeftUse;
5340     RHS = RightUse;
5341     return true;
5342   }
5343 
5344   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5345     LHS = RightUse;
5346     RHS = LeftUse;
5347     return true;
5348   }
5349 
5350   return false;
5351 }
5352 
createNodeFromSelectLikePHI(PHINode * PN)5353 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5354   auto IsReachable =
5355       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5356   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5357     const Loop *L = LI.getLoopFor(PN->getParent());
5358 
5359     // We don't want to break LCSSA, even in a SCEV expression tree.
5360     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5361       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5362         return nullptr;
5363 
5364     // Try to match
5365     //
5366     //  br %cond, label %left, label %right
5367     // left:
5368     //  br label %merge
5369     // right:
5370     //  br label %merge
5371     // merge:
5372     //  V = phi [ %x, %left ], [ %y, %right ]
5373     //
5374     // as "select %cond, %x, %y"
5375 
5376     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5377     assert(IDom && "At least the entry block should dominate PN");
5378 
5379     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5380     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5381 
5382     if (BI && BI->isConditional() &&
5383         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5384         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5385         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5386       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5387   }
5388 
5389   return nullptr;
5390 }
5391 
createNodeForPHI(PHINode * PN)5392 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5393   if (const SCEV *S = createAddRecFromPHI(PN))
5394     return S;
5395 
5396   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5397     return S;
5398 
5399   // If the PHI has a single incoming value, follow that value, unless the
5400   // PHI's incoming blocks are in a different loop, in which case doing so
5401   // risks breaking LCSSA form. Instcombine would normally zap these, but
5402   // it doesn't have DominatorTree information, so it may miss cases.
5403   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5404     if (LI.replacementPreservesLCSSAForm(PN, V))
5405       return getSCEV(V);
5406 
5407   // If it's not a loop phi, we can't handle it yet.
5408   return getUnknown(PN);
5409 }
5410 
createNodeForSelectOrPHI(Instruction * I,Value * Cond,Value * TrueVal,Value * FalseVal)5411 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5412                                                       Value *Cond,
5413                                                       Value *TrueVal,
5414                                                       Value *FalseVal) {
5415   // Handle "constant" branch or select. This can occur for instance when a
5416   // loop pass transforms an inner loop and moves on to process the outer loop.
5417   if (auto *CI = dyn_cast<ConstantInt>(Cond))
5418     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5419 
5420   // Try to match some simple smax or umax patterns.
5421   auto *ICI = dyn_cast<ICmpInst>(Cond);
5422   if (!ICI)
5423     return getUnknown(I);
5424 
5425   Value *LHS = ICI->getOperand(0);
5426   Value *RHS = ICI->getOperand(1);
5427 
5428   switch (ICI->getPredicate()) {
5429   case ICmpInst::ICMP_SLT:
5430   case ICmpInst::ICMP_SLE:
5431     std::swap(LHS, RHS);
5432     LLVM_FALLTHROUGH;
5433   case ICmpInst::ICMP_SGT:
5434   case ICmpInst::ICMP_SGE:
5435     // a >s b ? a+x : b+x  ->  smax(a, b)+x
5436     // a >s b ? b+x : a+x  ->  smin(a, b)+x
5437     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5438       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5439       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5440       const SCEV *LA = getSCEV(TrueVal);
5441       const SCEV *RA = getSCEV(FalseVal);
5442       const SCEV *LDiff = getMinusSCEV(LA, LS);
5443       const SCEV *RDiff = getMinusSCEV(RA, RS);
5444       if (LDiff == RDiff)
5445         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5446       LDiff = getMinusSCEV(LA, RS);
5447       RDiff = getMinusSCEV(RA, LS);
5448       if (LDiff == RDiff)
5449         return getAddExpr(getSMinExpr(LS, RS), LDiff);
5450     }
5451     break;
5452   case ICmpInst::ICMP_ULT:
5453   case ICmpInst::ICMP_ULE:
5454     std::swap(LHS, RHS);
5455     LLVM_FALLTHROUGH;
5456   case ICmpInst::ICMP_UGT:
5457   case ICmpInst::ICMP_UGE:
5458     // a >u b ? a+x : b+x  ->  umax(a, b)+x
5459     // a >u b ? b+x : a+x  ->  umin(a, b)+x
5460     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5461       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5462       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5463       const SCEV *LA = getSCEV(TrueVal);
5464       const SCEV *RA = getSCEV(FalseVal);
5465       const SCEV *LDiff = getMinusSCEV(LA, LS);
5466       const SCEV *RDiff = getMinusSCEV(RA, RS);
5467       if (LDiff == RDiff)
5468         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5469       LDiff = getMinusSCEV(LA, RS);
5470       RDiff = getMinusSCEV(RA, LS);
5471       if (LDiff == RDiff)
5472         return getAddExpr(getUMinExpr(LS, RS), LDiff);
5473     }
5474     break;
5475   case ICmpInst::ICMP_NE:
5476     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
5477     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5478         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5479       const SCEV *One = getOne(I->getType());
5480       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5481       const SCEV *LA = getSCEV(TrueVal);
5482       const SCEV *RA = getSCEV(FalseVal);
5483       const SCEV *LDiff = getMinusSCEV(LA, LS);
5484       const SCEV *RDiff = getMinusSCEV(RA, One);
5485       if (LDiff == RDiff)
5486         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5487     }
5488     break;
5489   case ICmpInst::ICMP_EQ:
5490     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
5491     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5492         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5493       const SCEV *One = getOne(I->getType());
5494       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5495       const SCEV *LA = getSCEV(TrueVal);
5496       const SCEV *RA = getSCEV(FalseVal);
5497       const SCEV *LDiff = getMinusSCEV(LA, One);
5498       const SCEV *RDiff = getMinusSCEV(RA, LS);
5499       if (LDiff == RDiff)
5500         return getAddExpr(getUMaxExpr(One, LS), LDiff);
5501     }
5502     break;
5503   default:
5504     break;
5505   }
5506 
5507   return getUnknown(I);
5508 }
5509 
5510 /// Expand GEP instructions into add and multiply operations. This allows them
5511 /// to be analyzed by regular SCEV code.
createNodeForGEP(GEPOperator * GEP)5512 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5513   // Don't attempt to analyze GEPs over unsized objects.
5514   if (!GEP->getSourceElementType()->isSized())
5515     return getUnknown(GEP);
5516 
5517   SmallVector<const SCEV *, 4> IndexExprs;
5518   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5519     IndexExprs.push_back(getSCEV(*Index));
5520   return getGEPExpr(GEP, IndexExprs);
5521 }
5522 
GetMinTrailingZerosImpl(const SCEV * S)5523 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5524   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5525     return C->getAPInt().countTrailingZeros();
5526 
5527   if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S))
5528     return GetMinTrailingZeros(I->getOperand());
5529 
5530   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5531     return std::min(GetMinTrailingZeros(T->getOperand()),
5532                     (uint32_t)getTypeSizeInBits(T->getType()));
5533 
5534   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5535     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5536     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5537                ? getTypeSizeInBits(E->getType())
5538                : OpRes;
5539   }
5540 
5541   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5542     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5543     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5544                ? getTypeSizeInBits(E->getType())
5545                : OpRes;
5546   }
5547 
5548   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5549     // The result is the min of all operands results.
5550     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5551     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5552       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5553     return MinOpRes;
5554   }
5555 
5556   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5557     // The result is the sum of all operands results.
5558     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5559     uint32_t BitWidth = getTypeSizeInBits(M->getType());
5560     for (unsigned i = 1, e = M->getNumOperands();
5561          SumOpRes != BitWidth && i != e; ++i)
5562       SumOpRes =
5563           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5564     return SumOpRes;
5565   }
5566 
5567   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5568     // The result is the min of all operands results.
5569     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5570     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5571       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5572     return MinOpRes;
5573   }
5574 
5575   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5576     // The result is the min of all operands results.
5577     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5578     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5579       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5580     return MinOpRes;
5581   }
5582 
5583   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5584     // The result is the min of all operands results.
5585     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5586     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5587       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5588     return MinOpRes;
5589   }
5590 
5591   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5592     // For a SCEVUnknown, ask ValueTracking.
5593     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5594     return Known.countMinTrailingZeros();
5595   }
5596 
5597   // SCEVUDivExpr
5598   return 0;
5599 }
5600 
GetMinTrailingZeros(const SCEV * S)5601 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5602   auto I = MinTrailingZerosCache.find(S);
5603   if (I != MinTrailingZerosCache.end())
5604     return I->second;
5605 
5606   uint32_t Result = GetMinTrailingZerosImpl(S);
5607   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5608   assert(InsertPair.second && "Should insert a new key");
5609   return InsertPair.first->second;
5610 }
5611 
5612 /// Helper method to assign a range to V from metadata present in the IR.
GetRangeFromMetadata(Value * V)5613 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5614   if (Instruction *I = dyn_cast<Instruction>(V))
5615     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5616       return getConstantRangeFromMetadata(*MD);
5617 
5618   return None;
5619 }
5620 
setNoWrapFlags(SCEVAddRecExpr * AddRec,SCEV::NoWrapFlags Flags)5621 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
5622                                      SCEV::NoWrapFlags Flags) {
5623   if (AddRec->getNoWrapFlags(Flags) != Flags) {
5624     AddRec->setNoWrapFlags(Flags);
5625     UnsignedRanges.erase(AddRec);
5626     SignedRanges.erase(AddRec);
5627   }
5628 }
5629 
5630 /// Determine the range for a particular SCEV.  If SignHint is
5631 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5632 /// with a "cleaner" unsigned (resp. signed) representation.
5633 const ConstantRange &
getRangeRef(const SCEV * S,ScalarEvolution::RangeSignHint SignHint)5634 ScalarEvolution::getRangeRef(const SCEV *S,
5635                              ScalarEvolution::RangeSignHint SignHint) {
5636   DenseMap<const SCEV *, ConstantRange> &Cache =
5637       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5638                                                        : SignedRanges;
5639   ConstantRange::PreferredRangeType RangeType =
5640       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
5641           ? ConstantRange::Unsigned : ConstantRange::Signed;
5642 
5643   // See if we've computed this range already.
5644   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5645   if (I != Cache.end())
5646     return I->second;
5647 
5648   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5649     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5650 
5651   unsigned BitWidth = getTypeSizeInBits(S->getType());
5652   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5653   using OBO = OverflowingBinaryOperator;
5654 
5655   // If the value has known zeros, the maximum value will have those known zeros
5656   // as well.
5657   uint32_t TZ = GetMinTrailingZeros(S);
5658   if (TZ != 0) {
5659     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5660       ConservativeResult =
5661           ConstantRange(APInt::getMinValue(BitWidth),
5662                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5663     else
5664       ConservativeResult = ConstantRange(
5665           APInt::getSignedMinValue(BitWidth),
5666           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5667   }
5668 
5669   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5670     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5671     unsigned WrapType = OBO::AnyWrap;
5672     if (Add->hasNoSignedWrap())
5673       WrapType |= OBO::NoSignedWrap;
5674     if (Add->hasNoUnsignedWrap())
5675       WrapType |= OBO::NoUnsignedWrap;
5676     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5677       X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint),
5678                           WrapType, RangeType);
5679     return setRange(Add, SignHint,
5680                     ConservativeResult.intersectWith(X, RangeType));
5681   }
5682 
5683   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5684     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5685     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5686       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5687     return setRange(Mul, SignHint,
5688                     ConservativeResult.intersectWith(X, RangeType));
5689   }
5690 
5691   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5692     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5693     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5694       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5695     return setRange(SMax, SignHint,
5696                     ConservativeResult.intersectWith(X, RangeType));
5697   }
5698 
5699   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5700     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5701     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5702       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5703     return setRange(UMax, SignHint,
5704                     ConservativeResult.intersectWith(X, RangeType));
5705   }
5706 
5707   if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) {
5708     ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint);
5709     for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i)
5710       X = X.smin(getRangeRef(SMin->getOperand(i), SignHint));
5711     return setRange(SMin, SignHint,
5712                     ConservativeResult.intersectWith(X, RangeType));
5713   }
5714 
5715   if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) {
5716     ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint);
5717     for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i)
5718       X = X.umin(getRangeRef(UMin->getOperand(i), SignHint));
5719     return setRange(UMin, SignHint,
5720                     ConservativeResult.intersectWith(X, RangeType));
5721   }
5722 
5723   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5724     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5725     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5726     return setRange(UDiv, SignHint,
5727                     ConservativeResult.intersectWith(X.udiv(Y), RangeType));
5728   }
5729 
5730   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5731     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5732     return setRange(ZExt, SignHint,
5733                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
5734                                                      RangeType));
5735   }
5736 
5737   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5738     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5739     return setRange(SExt, SignHint,
5740                     ConservativeResult.intersectWith(X.signExtend(BitWidth),
5741                                                      RangeType));
5742   }
5743 
5744   if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) {
5745     ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint);
5746     return setRange(PtrToInt, SignHint, X);
5747   }
5748 
5749   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5750     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5751     return setRange(Trunc, SignHint,
5752                     ConservativeResult.intersectWith(X.truncate(BitWidth),
5753                                                      RangeType));
5754   }
5755 
5756   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5757     // If there's no unsigned wrap, the value will never be less than its
5758     // initial value.
5759     if (AddRec->hasNoUnsignedWrap()) {
5760       APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
5761       if (!UnsignedMinValue.isNullValue())
5762         ConservativeResult = ConservativeResult.intersectWith(
5763             ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
5764     }
5765 
5766     // If there's no signed wrap, and all the operands except initial value have
5767     // the same sign or zero, the value won't ever be:
5768     // 1: smaller than initial value if operands are non negative,
5769     // 2: bigger than initial value if operands are non positive.
5770     // For both cases, value can not cross signed min/max boundary.
5771     if (AddRec->hasNoSignedWrap()) {
5772       bool AllNonNeg = true;
5773       bool AllNonPos = true;
5774       for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
5775         if (!isKnownNonNegative(AddRec->getOperand(i)))
5776           AllNonNeg = false;
5777         if (!isKnownNonPositive(AddRec->getOperand(i)))
5778           AllNonPos = false;
5779       }
5780       if (AllNonNeg)
5781         ConservativeResult = ConservativeResult.intersectWith(
5782             ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
5783                                        APInt::getSignedMinValue(BitWidth)),
5784             RangeType);
5785       else if (AllNonPos)
5786         ConservativeResult = ConservativeResult.intersectWith(
5787             ConstantRange::getNonEmpty(
5788                 APInt::getSignedMinValue(BitWidth),
5789                 getSignedRangeMax(AddRec->getStart()) + 1),
5790             RangeType);
5791     }
5792 
5793     // TODO: non-affine addrec
5794     if (AddRec->isAffine()) {
5795       const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
5796       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5797           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5798         auto RangeFromAffine = getRangeForAffineAR(
5799             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5800             BitWidth);
5801         ConservativeResult =
5802             ConservativeResult.intersectWith(RangeFromAffine, RangeType);
5803 
5804         auto RangeFromFactoring = getRangeViaFactoring(
5805             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5806             BitWidth);
5807         ConservativeResult =
5808             ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
5809       }
5810 
5811       // Now try symbolic BE count and more powerful methods.
5812       if (UseExpensiveRangeSharpening) {
5813         const SCEV *SymbolicMaxBECount =
5814             getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
5815         if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
5816             getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5817             AddRec->hasNoSelfWrap()) {
5818           auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
5819               AddRec, SymbolicMaxBECount, BitWidth, SignHint);
5820           ConservativeResult =
5821               ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
5822         }
5823       }
5824     }
5825 
5826     return setRange(AddRec, SignHint, std::move(ConservativeResult));
5827   }
5828 
5829   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5830     // Check if the IR explicitly contains !range metadata.
5831     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5832     if (MDRange.hasValue())
5833       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(),
5834                                                             RangeType);
5835 
5836     // Split here to avoid paying the compile-time cost of calling both
5837     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
5838     // if needed.
5839     const DataLayout &DL = getDataLayout();
5840     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5841       // For a SCEVUnknown, ask ValueTracking.
5842       KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5843       if (Known.getBitWidth() != BitWidth)
5844         Known = Known.zextOrTrunc(BitWidth);
5845       // If Known does not result in full-set, intersect with it.
5846       if (Known.getMinValue() != Known.getMaxValue() + 1)
5847         ConservativeResult = ConservativeResult.intersectWith(
5848             ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
5849             RangeType);
5850     } else {
5851       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
5852              "generalize as needed!");
5853       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5854       // If the pointer size is larger than the index size type, this can cause
5855       // NS to be larger than BitWidth. So compensate for this.
5856       if (U->getType()->isPointerTy()) {
5857         unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
5858         int ptrIdxDiff = ptrSize - BitWidth;
5859         if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
5860           NS -= ptrIdxDiff;
5861       }
5862 
5863       if (NS > 1)
5864         ConservativeResult = ConservativeResult.intersectWith(
5865             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5866                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
5867             RangeType);
5868     }
5869 
5870     // A range of Phi is a subset of union of all ranges of its input.
5871     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
5872       // Make sure that we do not run over cycled Phis.
5873       if (PendingPhiRanges.insert(Phi).second) {
5874         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
5875         for (auto &Op : Phi->operands()) {
5876           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
5877           RangeFromOps = RangeFromOps.unionWith(OpRange);
5878           // No point to continue if we already have a full set.
5879           if (RangeFromOps.isFullSet())
5880             break;
5881         }
5882         ConservativeResult =
5883             ConservativeResult.intersectWith(RangeFromOps, RangeType);
5884         bool Erased = PendingPhiRanges.erase(Phi);
5885         assert(Erased && "Failed to erase Phi properly?");
5886         (void) Erased;
5887       }
5888     }
5889 
5890     return setRange(U, SignHint, std::move(ConservativeResult));
5891   }
5892 
5893   return setRange(S, SignHint, std::move(ConservativeResult));
5894 }
5895 
5896 // Given a StartRange, Step and MaxBECount for an expression compute a range of
5897 // values that the expression can take. Initially, the expression has a value
5898 // from StartRange and then is changed by Step up to MaxBECount times. Signed
5899 // argument defines if we treat Step as signed or unsigned.
getRangeForAffineARHelper(APInt Step,const ConstantRange & StartRange,const APInt & MaxBECount,unsigned BitWidth,bool Signed)5900 static ConstantRange getRangeForAffineARHelper(APInt Step,
5901                                                const ConstantRange &StartRange,
5902                                                const APInt &MaxBECount,
5903                                                unsigned BitWidth, bool Signed) {
5904   // If either Step or MaxBECount is 0, then the expression won't change, and we
5905   // just need to return the initial range.
5906   if (Step == 0 || MaxBECount == 0)
5907     return StartRange;
5908 
5909   // If we don't know anything about the initial value (i.e. StartRange is
5910   // FullRange), then we don't know anything about the final range either.
5911   // Return FullRange.
5912   if (StartRange.isFullSet())
5913     return ConstantRange::getFull(BitWidth);
5914 
5915   // If Step is signed and negative, then we use its absolute value, but we also
5916   // note that we're moving in the opposite direction.
5917   bool Descending = Signed && Step.isNegative();
5918 
5919   if (Signed)
5920     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5921     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5922     // This equations hold true due to the well-defined wrap-around behavior of
5923     // APInt.
5924     Step = Step.abs();
5925 
5926   // Check if Offset is more than full span of BitWidth. If it is, the
5927   // expression is guaranteed to overflow.
5928   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
5929     return ConstantRange::getFull(BitWidth);
5930 
5931   // Offset is by how much the expression can change. Checks above guarantee no
5932   // overflow here.
5933   APInt Offset = Step * MaxBECount;
5934 
5935   // Minimum value of the final range will match the minimal value of StartRange
5936   // if the expression is increasing and will be decreased by Offset otherwise.
5937   // Maximum value of the final range will match the maximal value of StartRange
5938   // if the expression is decreasing and will be increased by Offset otherwise.
5939   APInt StartLower = StartRange.getLower();
5940   APInt StartUpper = StartRange.getUpper() - 1;
5941   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5942                                    : (StartUpper + std::move(Offset));
5943 
5944   // It's possible that the new minimum/maximum value will fall into the initial
5945   // range (due to wrap around). This means that the expression can take any
5946   // value in this bitwidth, and we have to return full range.
5947   if (StartRange.contains(MovedBoundary))
5948     return ConstantRange::getFull(BitWidth);
5949 
5950   APInt NewLower =
5951       Descending ? std::move(MovedBoundary) : std::move(StartLower);
5952   APInt NewUpper =
5953       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5954   NewUpper += 1;
5955 
5956   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5957   return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
5958 }
5959 
getRangeForAffineAR(const SCEV * Start,const SCEV * Step,const SCEV * MaxBECount,unsigned BitWidth)5960 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5961                                                    const SCEV *Step,
5962                                                    const SCEV *MaxBECount,
5963                                                    unsigned BitWidth) {
5964   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5965          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5966          "Precondition!");
5967 
5968   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
5969   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5970 
5971   // First, consider step signed.
5972   ConstantRange StartSRange = getSignedRange(Start);
5973   ConstantRange StepSRange = getSignedRange(Step);
5974 
5975   // If Step can be both positive and negative, we need to find ranges for the
5976   // maximum absolute step values in both directions and union them.
5977   ConstantRange SR =
5978       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5979                                 MaxBECountValue, BitWidth, /* Signed = */ true);
5980   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5981                                               StartSRange, MaxBECountValue,
5982                                               BitWidth, /* Signed = */ true));
5983 
5984   // Next, consider step unsigned.
5985   ConstantRange UR = getRangeForAffineARHelper(
5986       getUnsignedRangeMax(Step), getUnsignedRange(Start),
5987       MaxBECountValue, BitWidth, /* Signed = */ false);
5988 
5989   // Finally, intersect signed and unsigned ranges.
5990   return SR.intersectWith(UR, ConstantRange::Smallest);
5991 }
5992 
getRangeForAffineNoSelfWrappingAR(const SCEVAddRecExpr * AddRec,const SCEV * MaxBECount,unsigned BitWidth,ScalarEvolution::RangeSignHint SignHint)5993 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
5994     const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
5995     ScalarEvolution::RangeSignHint SignHint) {
5996   assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
5997   assert(AddRec->hasNoSelfWrap() &&
5998          "This only works for non-self-wrapping AddRecs!");
5999   const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
6000   const SCEV *Step = AddRec->getStepRecurrence(*this);
6001   // Only deal with constant step to save compile time.
6002   if (!isa<SCEVConstant>(Step))
6003     return ConstantRange::getFull(BitWidth);
6004   // Let's make sure that we can prove that we do not self-wrap during
6005   // MaxBECount iterations. We need this because MaxBECount is a maximum
6006   // iteration count estimate, and we might infer nw from some exit for which we
6007   // do not know max exit count (or any other side reasoning).
6008   // TODO: Turn into assert at some point.
6009   MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
6010   const SCEV *RangeWidth = getMinusOne(AddRec->getType());
6011   const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
6012   const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
6013   if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
6014                                          MaxItersWithoutWrap))
6015     return ConstantRange::getFull(BitWidth);
6016 
6017   ICmpInst::Predicate LEPred =
6018       IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
6019   ICmpInst::Predicate GEPred =
6020       IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
6021   const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
6022 
6023   // We know that there is no self-wrap. Let's take Start and End values and
6024   // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
6025   // the iteration. They either lie inside the range [Min(Start, End),
6026   // Max(Start, End)] or outside it:
6027   //
6028   // Case 1:   RangeMin    ...    Start V1 ... VN End ...           RangeMax;
6029   // Case 2:   RangeMin Vk ... V1 Start    ...    End Vn ... Vk + 1 RangeMax;
6030   //
6031   // No self wrap flag guarantees that the intermediate values cannot be BOTH
6032   // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
6033   // knowledge, let's try to prove that we are dealing with Case 1. It is so if
6034   // Start <= End and step is positive, or Start >= End and step is negative.
6035   const SCEV *Start = AddRec->getStart();
6036   ConstantRange StartRange = getRangeRef(Start, SignHint);
6037   ConstantRange EndRange = getRangeRef(End, SignHint);
6038   ConstantRange RangeBetween = StartRange.unionWith(EndRange);
6039   // If they already cover full iteration space, we will know nothing useful
6040   // even if we prove what we want to prove.
6041   if (RangeBetween.isFullSet())
6042     return RangeBetween;
6043   // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
6044   bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
6045                                : RangeBetween.isWrappedSet();
6046   if (IsWrappedSet)
6047     return ConstantRange::getFull(BitWidth);
6048 
6049   if (isKnownPositive(Step) &&
6050       isKnownPredicateViaConstantRanges(LEPred, Start, End))
6051     return RangeBetween;
6052   else if (isKnownNegative(Step) &&
6053            isKnownPredicateViaConstantRanges(GEPred, Start, End))
6054     return RangeBetween;
6055   return ConstantRange::getFull(BitWidth);
6056 }
6057 
getRangeViaFactoring(const SCEV * Start,const SCEV * Step,const SCEV * MaxBECount,unsigned BitWidth)6058 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
6059                                                     const SCEV *Step,
6060                                                     const SCEV *MaxBECount,
6061                                                     unsigned BitWidth) {
6062   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
6063   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
6064 
6065   struct SelectPattern {
6066     Value *Condition = nullptr;
6067     APInt TrueValue;
6068     APInt FalseValue;
6069 
6070     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
6071                            const SCEV *S) {
6072       Optional<unsigned> CastOp;
6073       APInt Offset(BitWidth, 0);
6074 
6075       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
6076              "Should be!");
6077 
6078       // Peel off a constant offset:
6079       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
6080         // In the future we could consider being smarter here and handle
6081         // {Start+Step,+,Step} too.
6082         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
6083           return;
6084 
6085         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
6086         S = SA->getOperand(1);
6087       }
6088 
6089       // Peel off a cast operation
6090       if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
6091         CastOp = SCast->getSCEVType();
6092         S = SCast->getOperand();
6093       }
6094 
6095       using namespace llvm::PatternMatch;
6096 
6097       auto *SU = dyn_cast<SCEVUnknown>(S);
6098       const APInt *TrueVal, *FalseVal;
6099       if (!SU ||
6100           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
6101                                           m_APInt(FalseVal)))) {
6102         Condition = nullptr;
6103         return;
6104       }
6105 
6106       TrueValue = *TrueVal;
6107       FalseValue = *FalseVal;
6108 
6109       // Re-apply the cast we peeled off earlier
6110       if (CastOp.hasValue())
6111         switch (*CastOp) {
6112         default:
6113           llvm_unreachable("Unknown SCEV cast type!");
6114 
6115         case scTruncate:
6116           TrueValue = TrueValue.trunc(BitWidth);
6117           FalseValue = FalseValue.trunc(BitWidth);
6118           break;
6119         case scZeroExtend:
6120           TrueValue = TrueValue.zext(BitWidth);
6121           FalseValue = FalseValue.zext(BitWidth);
6122           break;
6123         case scSignExtend:
6124           TrueValue = TrueValue.sext(BitWidth);
6125           FalseValue = FalseValue.sext(BitWidth);
6126           break;
6127         }
6128 
6129       // Re-apply the constant offset we peeled off earlier
6130       TrueValue += Offset;
6131       FalseValue += Offset;
6132     }
6133 
6134     bool isRecognized() { return Condition != nullptr; }
6135   };
6136 
6137   SelectPattern StartPattern(*this, BitWidth, Start);
6138   if (!StartPattern.isRecognized())
6139     return ConstantRange::getFull(BitWidth);
6140 
6141   SelectPattern StepPattern(*this, BitWidth, Step);
6142   if (!StepPattern.isRecognized())
6143     return ConstantRange::getFull(BitWidth);
6144 
6145   if (StartPattern.Condition != StepPattern.Condition) {
6146     // We don't handle this case today; but we could, by considering four
6147     // possibilities below instead of two. I'm not sure if there are cases where
6148     // that will help over what getRange already does, though.
6149     return ConstantRange::getFull(BitWidth);
6150   }
6151 
6152   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
6153   // construct arbitrary general SCEV expressions here.  This function is called
6154   // from deep in the call stack, and calling getSCEV (on a sext instruction,
6155   // say) can end up caching a suboptimal value.
6156 
6157   // FIXME: without the explicit `this` receiver below, MSVC errors out with
6158   // C2352 and C2512 (otherwise it isn't needed).
6159 
6160   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
6161   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
6162   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
6163   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
6164 
6165   ConstantRange TrueRange =
6166       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
6167   ConstantRange FalseRange =
6168       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
6169 
6170   return TrueRange.unionWith(FalseRange);
6171 }
6172 
getNoWrapFlagsFromUB(const Value * V)6173 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
6174   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
6175   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
6176 
6177   // Return early if there are no flags to propagate to the SCEV.
6178   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6179   if (BinOp->hasNoUnsignedWrap())
6180     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
6181   if (BinOp->hasNoSignedWrap())
6182     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
6183   if (Flags == SCEV::FlagAnyWrap)
6184     return SCEV::FlagAnyWrap;
6185 
6186   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
6187 }
6188 
isSCEVExprNeverPoison(const Instruction * I)6189 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
6190   // Here we check that I is in the header of the innermost loop containing I,
6191   // since we only deal with instructions in the loop header. The actual loop we
6192   // need to check later will come from an add recurrence, but getting that
6193   // requires computing the SCEV of the operands, which can be expensive. This
6194   // check we can do cheaply to rule out some cases early.
6195   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
6196   if (InnermostContainingLoop == nullptr ||
6197       InnermostContainingLoop->getHeader() != I->getParent())
6198     return false;
6199 
6200   // Only proceed if we can prove that I does not yield poison.
6201   if (!programUndefinedIfPoison(I))
6202     return false;
6203 
6204   // At this point we know that if I is executed, then it does not wrap
6205   // according to at least one of NSW or NUW. If I is not executed, then we do
6206   // not know if the calculation that I represents would wrap. Multiple
6207   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
6208   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
6209   // derived from other instructions that map to the same SCEV. We cannot make
6210   // that guarantee for cases where I is not executed. So we need to find the
6211   // loop that I is considered in relation to and prove that I is executed for
6212   // every iteration of that loop. That implies that the value that I
6213   // calculates does not wrap anywhere in the loop, so then we can apply the
6214   // flags to the SCEV.
6215   //
6216   // We check isLoopInvariant to disambiguate in case we are adding recurrences
6217   // from different loops, so that we know which loop to prove that I is
6218   // executed in.
6219   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
6220     // I could be an extractvalue from a call to an overflow intrinsic.
6221     // TODO: We can do better here in some cases.
6222     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
6223       return false;
6224     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
6225     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
6226       bool AllOtherOpsLoopInvariant = true;
6227       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
6228            ++OtherOpIndex) {
6229         if (OtherOpIndex != OpIndex) {
6230           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
6231           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
6232             AllOtherOpsLoopInvariant = false;
6233             break;
6234           }
6235         }
6236       }
6237       if (AllOtherOpsLoopInvariant &&
6238           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
6239         return true;
6240     }
6241   }
6242   return false;
6243 }
6244 
isAddRecNeverPoison(const Instruction * I,const Loop * L)6245 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
6246   // If we know that \c I can never be poison period, then that's enough.
6247   if (isSCEVExprNeverPoison(I))
6248     return true;
6249 
6250   // For an add recurrence specifically, we assume that infinite loops without
6251   // side effects are undefined behavior, and then reason as follows:
6252   //
6253   // If the add recurrence is poison in any iteration, it is poison on all
6254   // future iterations (since incrementing poison yields poison). If the result
6255   // of the add recurrence is fed into the loop latch condition and the loop
6256   // does not contain any throws or exiting blocks other than the latch, we now
6257   // have the ability to "choose" whether the backedge is taken or not (by
6258   // choosing a sufficiently evil value for the poison feeding into the branch)
6259   // for every iteration including and after the one in which \p I first became
6260   // poison.  There are two possibilities (let's call the iteration in which \p
6261   // I first became poison as K):
6262   //
6263   //  1. In the set of iterations including and after K, the loop body executes
6264   //     no side effects.  In this case executing the backege an infinte number
6265   //     of times will yield undefined behavior.
6266   //
6267   //  2. In the set of iterations including and after K, the loop body executes
6268   //     at least one side effect.  In this case, that specific instance of side
6269   //     effect is control dependent on poison, which also yields undefined
6270   //     behavior.
6271 
6272   auto *ExitingBB = L->getExitingBlock();
6273   auto *LatchBB = L->getLoopLatch();
6274   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
6275     return false;
6276 
6277   SmallPtrSet<const Instruction *, 16> Pushed;
6278   SmallVector<const Instruction *, 8> PoisonStack;
6279 
6280   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
6281   // things that are known to be poison under that assumption go on the
6282   // PoisonStack.
6283   Pushed.insert(I);
6284   PoisonStack.push_back(I);
6285 
6286   bool LatchControlDependentOnPoison = false;
6287   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
6288     const Instruction *Poison = PoisonStack.pop_back_val();
6289 
6290     for (auto *PoisonUser : Poison->users()) {
6291       if (propagatesPoison(cast<Operator>(PoisonUser))) {
6292         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
6293           PoisonStack.push_back(cast<Instruction>(PoisonUser));
6294       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
6295         assert(BI->isConditional() && "Only possibility!");
6296         if (BI->getParent() == LatchBB) {
6297           LatchControlDependentOnPoison = true;
6298           break;
6299         }
6300       }
6301     }
6302   }
6303 
6304   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
6305 }
6306 
6307 ScalarEvolution::LoopProperties
getLoopProperties(const Loop * L)6308 ScalarEvolution::getLoopProperties(const Loop *L) {
6309   using LoopProperties = ScalarEvolution::LoopProperties;
6310 
6311   auto Itr = LoopPropertiesCache.find(L);
6312   if (Itr == LoopPropertiesCache.end()) {
6313     auto HasSideEffects = [](Instruction *I) {
6314       if (auto *SI = dyn_cast<StoreInst>(I))
6315         return !SI->isSimple();
6316 
6317       return I->mayHaveSideEffects();
6318     };
6319 
6320     LoopProperties LP = {/* HasNoAbnormalExits */ true,
6321                          /*HasNoSideEffects*/ true};
6322 
6323     for (auto *BB : L->getBlocks())
6324       for (auto &I : *BB) {
6325         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
6326           LP.HasNoAbnormalExits = false;
6327         if (HasSideEffects(&I))
6328           LP.HasNoSideEffects = false;
6329         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
6330           break; // We're already as pessimistic as we can get.
6331       }
6332 
6333     auto InsertPair = LoopPropertiesCache.insert({L, LP});
6334     assert(InsertPair.second && "We just checked!");
6335     Itr = InsertPair.first;
6336   }
6337 
6338   return Itr->second;
6339 }
6340 
createSCEV(Value * V)6341 const SCEV *ScalarEvolution::createSCEV(Value *V) {
6342   if (!isSCEVable(V->getType()))
6343     return getUnknown(V);
6344 
6345   if (Instruction *I = dyn_cast<Instruction>(V)) {
6346     // Don't attempt to analyze instructions in blocks that aren't
6347     // reachable. Such instructions don't matter, and they aren't required
6348     // to obey basic rules for definitions dominating uses which this
6349     // analysis depends on.
6350     if (!DT.isReachableFromEntry(I->getParent()))
6351       return getUnknown(UndefValue::get(V->getType()));
6352   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
6353     return getConstant(CI);
6354   else if (isa<ConstantPointerNull>(V))
6355     // FIXME: we shouldn't special-case null pointer constant.
6356     return getZero(V->getType());
6357   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6358     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6359   else if (!isa<ConstantExpr>(V))
6360     return getUnknown(V);
6361 
6362   Operator *U = cast<Operator>(V);
6363   if (auto BO = MatchBinaryOp(U, DT)) {
6364     switch (BO->Opcode) {
6365     case Instruction::Add: {
6366       // The simple thing to do would be to just call getSCEV on both operands
6367       // and call getAddExpr with the result. However if we're looking at a
6368       // bunch of things all added together, this can be quite inefficient,
6369       // because it leads to N-1 getAddExpr calls for N ultimate operands.
6370       // Instead, gather up all the operands and make a single getAddExpr call.
6371       // LLVM IR canonical form means we need only traverse the left operands.
6372       SmallVector<const SCEV *, 4> AddOps;
6373       do {
6374         if (BO->Op) {
6375           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6376             AddOps.push_back(OpSCEV);
6377             break;
6378           }
6379 
6380           // If a NUW or NSW flag can be applied to the SCEV for this
6381           // addition, then compute the SCEV for this addition by itself
6382           // with a separate call to getAddExpr. We need to do that
6383           // instead of pushing the operands of the addition onto AddOps,
6384           // since the flags are only known to apply to this particular
6385           // addition - they may not apply to other additions that can be
6386           // formed with operands from AddOps.
6387           const SCEV *RHS = getSCEV(BO->RHS);
6388           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6389           if (Flags != SCEV::FlagAnyWrap) {
6390             const SCEV *LHS = getSCEV(BO->LHS);
6391             if (BO->Opcode == Instruction::Sub)
6392               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6393             else
6394               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6395             break;
6396           }
6397         }
6398 
6399         if (BO->Opcode == Instruction::Sub)
6400           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6401         else
6402           AddOps.push_back(getSCEV(BO->RHS));
6403 
6404         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6405         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6406                        NewBO->Opcode != Instruction::Sub)) {
6407           AddOps.push_back(getSCEV(BO->LHS));
6408           break;
6409         }
6410         BO = NewBO;
6411       } while (true);
6412 
6413       return getAddExpr(AddOps);
6414     }
6415 
6416     case Instruction::Mul: {
6417       SmallVector<const SCEV *, 4> MulOps;
6418       do {
6419         if (BO->Op) {
6420           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6421             MulOps.push_back(OpSCEV);
6422             break;
6423           }
6424 
6425           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6426           if (Flags != SCEV::FlagAnyWrap) {
6427             MulOps.push_back(
6428                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6429             break;
6430           }
6431         }
6432 
6433         MulOps.push_back(getSCEV(BO->RHS));
6434         auto NewBO = MatchBinaryOp(BO->LHS, DT);
6435         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6436           MulOps.push_back(getSCEV(BO->LHS));
6437           break;
6438         }
6439         BO = NewBO;
6440       } while (true);
6441 
6442       return getMulExpr(MulOps);
6443     }
6444     case Instruction::UDiv:
6445       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6446     case Instruction::URem:
6447       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6448     case Instruction::Sub: {
6449       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6450       if (BO->Op)
6451         Flags = getNoWrapFlagsFromUB(BO->Op);
6452       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6453     }
6454     case Instruction::And:
6455       // For an expression like x&255 that merely masks off the high bits,
6456       // use zext(trunc(x)) as the SCEV expression.
6457       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6458         if (CI->isZero())
6459           return getSCEV(BO->RHS);
6460         if (CI->isMinusOne())
6461           return getSCEV(BO->LHS);
6462         const APInt &A = CI->getValue();
6463 
6464         // Instcombine's ShrinkDemandedConstant may strip bits out of
6465         // constants, obscuring what would otherwise be a low-bits mask.
6466         // Use computeKnownBits to compute what ShrinkDemandedConstant
6467         // knew about to reconstruct a low-bits mask value.
6468         unsigned LZ = A.countLeadingZeros();
6469         unsigned TZ = A.countTrailingZeros();
6470         unsigned BitWidth = A.getBitWidth();
6471         KnownBits Known(BitWidth);
6472         computeKnownBits(BO->LHS, Known, getDataLayout(),
6473                          0, &AC, nullptr, &DT);
6474 
6475         APInt EffectiveMask =
6476             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6477         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6478           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6479           const SCEV *LHS = getSCEV(BO->LHS);
6480           const SCEV *ShiftedLHS = nullptr;
6481           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6482             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6483               // For an expression like (x * 8) & 8, simplify the multiply.
6484               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6485               unsigned GCD = std::min(MulZeros, TZ);
6486               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6487               SmallVector<const SCEV*, 4> MulOps;
6488               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6489               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6490               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6491               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6492             }
6493           }
6494           if (!ShiftedLHS)
6495             ShiftedLHS = getUDivExpr(LHS, MulCount);
6496           return getMulExpr(
6497               getZeroExtendExpr(
6498                   getTruncateExpr(ShiftedLHS,
6499                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6500                   BO->LHS->getType()),
6501               MulCount);
6502         }
6503       }
6504       break;
6505 
6506     case Instruction::Or:
6507       // If the RHS of the Or is a constant, we may have something like:
6508       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
6509       // optimizations will transparently handle this case.
6510       //
6511       // In order for this transformation to be safe, the LHS must be of the
6512       // form X*(2^n) and the Or constant must be less than 2^n.
6513       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6514         const SCEV *LHS = getSCEV(BO->LHS);
6515         const APInt &CIVal = CI->getValue();
6516         if (GetMinTrailingZeros(LHS) >=
6517             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6518           // Build a plain add SCEV.
6519           return getAddExpr(LHS, getSCEV(CI),
6520                             (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
6521         }
6522       }
6523       break;
6524 
6525     case Instruction::Xor:
6526       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6527         // If the RHS of xor is -1, then this is a not operation.
6528         if (CI->isMinusOne())
6529           return getNotSCEV(getSCEV(BO->LHS));
6530 
6531         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6532         // This is a variant of the check for xor with -1, and it handles
6533         // the case where instcombine has trimmed non-demanded bits out
6534         // of an xor with -1.
6535         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6536           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6537             if (LBO->getOpcode() == Instruction::And &&
6538                 LCI->getValue() == CI->getValue())
6539               if (const SCEVZeroExtendExpr *Z =
6540                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6541                 Type *UTy = BO->LHS->getType();
6542                 const SCEV *Z0 = Z->getOperand();
6543                 Type *Z0Ty = Z0->getType();
6544                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6545 
6546                 // If C is a low-bits mask, the zero extend is serving to
6547                 // mask off the high bits. Complement the operand and
6548                 // re-apply the zext.
6549                 if (CI->getValue().isMask(Z0TySize))
6550                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6551 
6552                 // If C is a single bit, it may be in the sign-bit position
6553                 // before the zero-extend. In this case, represent the xor
6554                 // using an add, which is equivalent, and re-apply the zext.
6555                 APInt Trunc = CI->getValue().trunc(Z0TySize);
6556                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6557                     Trunc.isSignMask())
6558                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6559                                            UTy);
6560               }
6561       }
6562       break;
6563 
6564     case Instruction::Shl:
6565       // Turn shift left of a constant amount into a multiply.
6566       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6567         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6568 
6569         // If the shift count is not less than the bitwidth, the result of
6570         // the shift is undefined. Don't try to analyze it, because the
6571         // resolution chosen here may differ from the resolution chosen in
6572         // other parts of the compiler.
6573         if (SA->getValue().uge(BitWidth))
6574           break;
6575 
6576         // We can safely preserve the nuw flag in all cases. It's also safe to
6577         // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
6578         // requires special handling. It can be preserved as long as we're not
6579         // left shifting by bitwidth - 1.
6580         auto Flags = SCEV::FlagAnyWrap;
6581         if (BO->Op) {
6582           auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
6583           if ((MulFlags & SCEV::FlagNSW) &&
6584               ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
6585             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
6586           if (MulFlags & SCEV::FlagNUW)
6587             Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
6588         }
6589 
6590         Constant *X = ConstantInt::get(
6591             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6592         return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6593       }
6594       break;
6595 
6596     case Instruction::AShr: {
6597       // AShr X, C, where C is a constant.
6598       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6599       if (!CI)
6600         break;
6601 
6602       Type *OuterTy = BO->LHS->getType();
6603       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6604       // If the shift count is not less than the bitwidth, the result of
6605       // the shift is undefined. Don't try to analyze it, because the
6606       // resolution chosen here may differ from the resolution chosen in
6607       // other parts of the compiler.
6608       if (CI->getValue().uge(BitWidth))
6609         break;
6610 
6611       if (CI->isZero())
6612         return getSCEV(BO->LHS); // shift by zero --> noop
6613 
6614       uint64_t AShrAmt = CI->getZExtValue();
6615       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6616 
6617       Operator *L = dyn_cast<Operator>(BO->LHS);
6618       if (L && L->getOpcode() == Instruction::Shl) {
6619         // X = Shl A, n
6620         // Y = AShr X, m
6621         // Both n and m are constant.
6622 
6623         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6624         if (L->getOperand(1) == BO->RHS)
6625           // For a two-shift sext-inreg, i.e. n = m,
6626           // use sext(trunc(x)) as the SCEV expression.
6627           return getSignExtendExpr(
6628               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6629 
6630         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6631         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6632           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6633           if (ShlAmt > AShrAmt) {
6634             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6635             // expression. We already checked that ShlAmt < BitWidth, so
6636             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6637             // ShlAmt - AShrAmt < Amt.
6638             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6639                                             ShlAmt - AShrAmt);
6640             return getSignExtendExpr(
6641                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6642                 getConstant(Mul)), OuterTy);
6643           }
6644         }
6645       }
6646       if (BO->IsExact) {
6647         // Given exact arithmetic in-bounds right-shift by a constant,
6648         // we can lower it into:  (abs(x) EXACT/u (1<<C)) * signum(x)
6649         const SCEV *X = getSCEV(BO->LHS);
6650         const SCEV *AbsX = getAbsExpr(X, /*IsNSW=*/false);
6651         APInt Mult = APInt::getOneBitSet(BitWidth, AShrAmt);
6652         const SCEV *Div = getUDivExactExpr(AbsX, getConstant(Mult));
6653         return getMulExpr(Div, getSignumExpr(X), SCEV::FlagNSW);
6654       }
6655       break;
6656     }
6657     }
6658   }
6659 
6660   switch (U->getOpcode()) {
6661   case Instruction::Trunc:
6662     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6663 
6664   case Instruction::ZExt:
6665     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6666 
6667   case Instruction::SExt:
6668     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6669       // The NSW flag of a subtract does not always survive the conversion to
6670       // A + (-1)*B.  By pushing sign extension onto its operands we are much
6671       // more likely to preserve NSW and allow later AddRec optimisations.
6672       //
6673       // NOTE: This is effectively duplicating this logic from getSignExtend:
6674       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6675       // but by that point the NSW information has potentially been lost.
6676       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6677         Type *Ty = U->getType();
6678         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6679         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6680         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6681       }
6682     }
6683     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6684 
6685   case Instruction::BitCast:
6686     // BitCasts are no-op casts so we just eliminate the cast.
6687     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6688       return getSCEV(U->getOperand(0));
6689     break;
6690 
6691   case Instruction::PtrToInt: {
6692     // Pointer to integer cast is straight-forward, so do model it.
6693     Value *Ptr = U->getOperand(0);
6694     const SCEV *Op = getSCEV(Ptr);
6695     Type *DstIntTy = U->getType();
6696     // SCEV doesn't have constant pointer expression type, but it supports
6697     // nullptr constant (and only that one), which is modelled in SCEV as a
6698     // zero integer constant. So just skip the ptrtoint cast for constants.
6699     if (isa<SCEVConstant>(Op))
6700       return getTruncateOrZeroExtend(Op, DstIntTy);
6701     Type *PtrTy = Ptr->getType();
6702     Type *IntPtrTy = getDataLayout().getIntPtrType(PtrTy);
6703     // But only if effective SCEV (integer) type is wide enough to represent
6704     // all possible pointer values.
6705     if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(PtrTy)) !=
6706         getDataLayout().getTypeSizeInBits(IntPtrTy))
6707       return getUnknown(V);
6708     return getPtrToIntExpr(Op, DstIntTy);
6709   }
6710   case Instruction::IntToPtr:
6711     // Just don't deal with inttoptr casts.
6712     return getUnknown(V);
6713 
6714   case Instruction::SDiv:
6715     // If both operands are non-negative, this is just an udiv.
6716     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
6717         isKnownNonNegative(getSCEV(U->getOperand(1))))
6718       return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
6719     break;
6720 
6721   case Instruction::SRem:
6722     // If both operands are non-negative, this is just an urem.
6723     if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
6724         isKnownNonNegative(getSCEV(U->getOperand(1))))
6725       return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
6726     break;
6727 
6728   case Instruction::GetElementPtr:
6729     return createNodeForGEP(cast<GEPOperator>(U));
6730 
6731   case Instruction::PHI:
6732     return createNodeForPHI(cast<PHINode>(U));
6733 
6734   case Instruction::Select:
6735     // U can also be a select constant expr, which let fall through.  Since
6736     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6737     // constant expressions cannot have instructions as operands, we'd have
6738     // returned getUnknown for a select constant expressions anyway.
6739     if (isa<Instruction>(U))
6740       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6741                                       U->getOperand(1), U->getOperand(2));
6742     break;
6743 
6744   case Instruction::Call:
6745   case Instruction::Invoke:
6746     if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
6747       return getSCEV(RV);
6748 
6749     if (auto *II = dyn_cast<IntrinsicInst>(U)) {
6750       switch (II->getIntrinsicID()) {
6751       case Intrinsic::abs:
6752         return getAbsExpr(
6753             getSCEV(II->getArgOperand(0)),
6754             /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
6755       case Intrinsic::umax:
6756         return getUMaxExpr(getSCEV(II->getArgOperand(0)),
6757                            getSCEV(II->getArgOperand(1)));
6758       case Intrinsic::umin:
6759         return getUMinExpr(getSCEV(II->getArgOperand(0)),
6760                            getSCEV(II->getArgOperand(1)));
6761       case Intrinsic::smax:
6762         return getSMaxExpr(getSCEV(II->getArgOperand(0)),
6763                            getSCEV(II->getArgOperand(1)));
6764       case Intrinsic::smin:
6765         return getSMinExpr(getSCEV(II->getArgOperand(0)),
6766                            getSCEV(II->getArgOperand(1)));
6767       case Intrinsic::usub_sat: {
6768         const SCEV *X = getSCEV(II->getArgOperand(0));
6769         const SCEV *Y = getSCEV(II->getArgOperand(1));
6770         const SCEV *ClampedY = getUMinExpr(X, Y);
6771         return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
6772       }
6773       case Intrinsic::uadd_sat: {
6774         const SCEV *X = getSCEV(II->getArgOperand(0));
6775         const SCEV *Y = getSCEV(II->getArgOperand(1));
6776         const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
6777         return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
6778       }
6779       case Intrinsic::start_loop_iterations:
6780         // A start_loop_iterations is just equivalent to the first operand for
6781         // SCEV purposes.
6782         return getSCEV(II->getArgOperand(0));
6783       default:
6784         break;
6785       }
6786     }
6787     break;
6788   }
6789 
6790   return getUnknown(V);
6791 }
6792 
6793 //===----------------------------------------------------------------------===//
6794 //                   Iteration Count Computation Code
6795 //
6796 
getConstantTripCount(const SCEVConstant * ExitCount)6797 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6798   if (!ExitCount)
6799     return 0;
6800 
6801   ConstantInt *ExitConst = ExitCount->getValue();
6802 
6803   // Guard against huge trip counts.
6804   if (ExitConst->getValue().getActiveBits() > 32)
6805     return 0;
6806 
6807   // In case of integer overflow, this returns 0, which is correct.
6808   return ((unsigned)ExitConst->getZExtValue()) + 1;
6809 }
6810 
getSmallConstantTripCount(const Loop * L)6811 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6812   if (BasicBlock *ExitingBB = L->getExitingBlock())
6813     return getSmallConstantTripCount(L, ExitingBB);
6814 
6815   // No trip count information for multiple exits.
6816   return 0;
6817 }
6818 
6819 unsigned
getSmallConstantTripCount(const Loop * L,const BasicBlock * ExitingBlock)6820 ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6821                                            const BasicBlock *ExitingBlock) {
6822   assert(ExitingBlock && "Must pass a non-null exiting block!");
6823   assert(L->isLoopExiting(ExitingBlock) &&
6824          "Exiting block must actually branch out of the loop!");
6825   const SCEVConstant *ExitCount =
6826       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6827   return getConstantTripCount(ExitCount);
6828 }
6829 
getSmallConstantMaxTripCount(const Loop * L)6830 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6831   const auto *MaxExitCount =
6832       dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
6833   return getConstantTripCount(MaxExitCount);
6834 }
6835 
getSmallConstantTripMultiple(const Loop * L)6836 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6837   if (BasicBlock *ExitingBB = L->getExitingBlock())
6838     return getSmallConstantTripMultiple(L, ExitingBB);
6839 
6840   // No trip multiple information for multiple exits.
6841   return 0;
6842 }
6843 
6844 /// Returns the largest constant divisor of the trip count of this loop as a
6845 /// normal unsigned value, if possible. This means that the actual trip count is
6846 /// always a multiple of the returned value (don't forget the trip count could
6847 /// very well be zero as well!).
6848 ///
6849 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6850 /// multiple of a constant (which is also the case if the trip count is simply
6851 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6852 /// if the trip count is very large (>= 2^32).
6853 ///
6854 /// As explained in the comments for getSmallConstantTripCount, this assumes
6855 /// that control exits the loop via ExitingBlock.
6856 unsigned
getSmallConstantTripMultiple(const Loop * L,const BasicBlock * ExitingBlock)6857 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6858                                               const BasicBlock *ExitingBlock) {
6859   assert(ExitingBlock && "Must pass a non-null exiting block!");
6860   assert(L->isLoopExiting(ExitingBlock) &&
6861          "Exiting block must actually branch out of the loop!");
6862   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6863   if (ExitCount == getCouldNotCompute())
6864     return 1;
6865 
6866   // Get the trip count from the BE count by adding 1.
6867   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6868 
6869   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6870   if (!TC)
6871     // Attempt to factor more general cases. Returns the greatest power of
6872     // two divisor. If overflow happens, the trip count expression is still
6873     // divisible by the greatest power of 2 divisor returned.
6874     return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
6875 
6876   ConstantInt *Result = TC->getValue();
6877 
6878   // Guard against huge trip counts (this requires checking
6879   // for zero to handle the case where the trip count == -1 and the
6880   // addition wraps).
6881   if (!Result || Result->getValue().getActiveBits() > 32 ||
6882       Result->getValue().getActiveBits() == 0)
6883     return 1;
6884 
6885   return (unsigned)Result->getZExtValue();
6886 }
6887 
getExitCount(const Loop * L,const BasicBlock * ExitingBlock,ExitCountKind Kind)6888 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6889                                           const BasicBlock *ExitingBlock,
6890                                           ExitCountKind Kind) {
6891   switch (Kind) {
6892   case Exact:
6893   case SymbolicMaximum:
6894     return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6895   case ConstantMaximum:
6896     return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
6897   };
6898   llvm_unreachable("Invalid ExitCountKind!");
6899 }
6900 
6901 const SCEV *
getPredicatedBackedgeTakenCount(const Loop * L,SCEVUnionPredicate & Preds)6902 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6903                                                  SCEVUnionPredicate &Preds) {
6904   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
6905 }
6906 
getBackedgeTakenCount(const Loop * L,ExitCountKind Kind)6907 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
6908                                                    ExitCountKind Kind) {
6909   switch (Kind) {
6910   case Exact:
6911     return getBackedgeTakenInfo(L).getExact(L, this);
6912   case ConstantMaximum:
6913     return getBackedgeTakenInfo(L).getConstantMax(this);
6914   case SymbolicMaximum:
6915     return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
6916   };
6917   llvm_unreachable("Invalid ExitCountKind!");
6918 }
6919 
isBackedgeTakenCountMaxOrZero(const Loop * L)6920 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
6921   return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
6922 }
6923 
6924 /// Push PHI nodes in the header of the given loop onto the given Worklist.
6925 static void
PushLoopPHIs(const Loop * L,SmallVectorImpl<Instruction * > & Worklist)6926 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
6927   BasicBlock *Header = L->getHeader();
6928 
6929   // Push all Loop-header PHIs onto the Worklist stack.
6930   for (PHINode &PN : Header->phis())
6931     Worklist.push_back(&PN);
6932 }
6933 
6934 const ScalarEvolution::BackedgeTakenInfo &
getPredicatedBackedgeTakenInfo(const Loop * L)6935 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
6936   auto &BTI = getBackedgeTakenInfo(L);
6937   if (BTI.hasFullInfo())
6938     return BTI;
6939 
6940   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6941 
6942   if (!Pair.second)
6943     return Pair.first->second;
6944 
6945   BackedgeTakenInfo Result =
6946       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
6947 
6948   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6949 }
6950 
6951 ScalarEvolution::BackedgeTakenInfo &
getBackedgeTakenInfo(const Loop * L)6952 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
6953   // Initially insert an invalid entry for this loop. If the insertion
6954   // succeeds, proceed to actually compute a backedge-taken count and
6955   // update the value. The temporary CouldNotCompute value tells SCEV
6956   // code elsewhere that it shouldn't attempt to request a new
6957   // backedge-taken count, which could result in infinite recursion.
6958   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
6959       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6960   if (!Pair.second)
6961     return Pair.first->second;
6962 
6963   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6964   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6965   // must be cleared in this scope.
6966   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6967 
6968   // In product build, there are no usage of statistic.
6969   (void)NumTripCountsComputed;
6970   (void)NumTripCountsNotComputed;
6971 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
6972   const SCEV *BEExact = Result.getExact(L, this);
6973   if (BEExact != getCouldNotCompute()) {
6974     assert(isLoopInvariant(BEExact, L) &&
6975            isLoopInvariant(Result.getConstantMax(this), L) &&
6976            "Computed backedge-taken count isn't loop invariant for loop!");
6977     ++NumTripCountsComputed;
6978   } else if (Result.getConstantMax(this) == getCouldNotCompute() &&
6979              isa<PHINode>(L->getHeader()->begin())) {
6980     // Only count loops that have phi nodes as not being computable.
6981     ++NumTripCountsNotComputed;
6982   }
6983 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
6984 
6985   // Now that we know more about the trip count for this loop, forget any
6986   // existing SCEV values for PHI nodes in this loop since they are only
6987   // conservative estimates made without the benefit of trip count
6988   // information. This is similar to the code in forgetLoop, except that
6989   // it handles SCEVUnknown PHI nodes specially.
6990   if (Result.hasAnyInfo()) {
6991     SmallVector<Instruction *, 16> Worklist;
6992     PushLoopPHIs(L, Worklist);
6993 
6994     SmallPtrSet<Instruction *, 8> Discovered;
6995     while (!Worklist.empty()) {
6996       Instruction *I = Worklist.pop_back_val();
6997 
6998       ValueExprMapType::iterator It =
6999         ValueExprMap.find_as(static_cast<Value *>(I));
7000       if (It != ValueExprMap.end()) {
7001         const SCEV *Old = It->second;
7002 
7003         // SCEVUnknown for a PHI either means that it has an unrecognized
7004         // structure, or it's a PHI that's in the progress of being computed
7005         // by createNodeForPHI.  In the former case, additional loop trip
7006         // count information isn't going to change anything. In the later
7007         // case, createNodeForPHI will perform the necessary updates on its
7008         // own when it gets to that point.
7009         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
7010           eraseValueFromMap(It->first);
7011           forgetMemoizedResults(Old);
7012         }
7013         if (PHINode *PN = dyn_cast<PHINode>(I))
7014           ConstantEvolutionLoopExitValue.erase(PN);
7015       }
7016 
7017       // Since we don't need to invalidate anything for correctness and we're
7018       // only invalidating to make SCEV's results more precise, we get to stop
7019       // early to avoid invalidating too much.  This is especially important in
7020       // cases like:
7021       //
7022       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
7023       // loop0:
7024       //   %pn0 = phi
7025       //   ...
7026       // loop1:
7027       //   %pn1 = phi
7028       //   ...
7029       //
7030       // where both loop0 and loop1's backedge taken count uses the SCEV
7031       // expression for %v.  If we don't have the early stop below then in cases
7032       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
7033       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
7034       // count for loop1, effectively nullifying SCEV's trip count cache.
7035       for (auto *U : I->users())
7036         if (auto *I = dyn_cast<Instruction>(U)) {
7037           auto *LoopForUser = LI.getLoopFor(I->getParent());
7038           if (LoopForUser && L->contains(LoopForUser) &&
7039               Discovered.insert(I).second)
7040             Worklist.push_back(I);
7041         }
7042     }
7043   }
7044 
7045   // Re-lookup the insert position, since the call to
7046   // computeBackedgeTakenCount above could result in a
7047   // recusive call to getBackedgeTakenInfo (on a different
7048   // loop), which would invalidate the iterator computed
7049   // earlier.
7050   return BackedgeTakenCounts.find(L)->second = std::move(Result);
7051 }
7052 
forgetAllLoops()7053 void ScalarEvolution::forgetAllLoops() {
7054   // This method is intended to forget all info about loops. It should
7055   // invalidate caches as if the following happened:
7056   // - The trip counts of all loops have changed arbitrarily
7057   // - Every llvm::Value has been updated in place to produce a different
7058   // result.
7059   BackedgeTakenCounts.clear();
7060   PredicatedBackedgeTakenCounts.clear();
7061   LoopPropertiesCache.clear();
7062   ConstantEvolutionLoopExitValue.clear();
7063   ValueExprMap.clear();
7064   ValuesAtScopes.clear();
7065   LoopDispositions.clear();
7066   BlockDispositions.clear();
7067   UnsignedRanges.clear();
7068   SignedRanges.clear();
7069   ExprValueMap.clear();
7070   HasRecMap.clear();
7071   MinTrailingZerosCache.clear();
7072   PredicatedSCEVRewrites.clear();
7073 }
7074 
forgetLoop(const Loop * L)7075 void ScalarEvolution::forgetLoop(const Loop *L) {
7076   // Drop any stored trip count value.
7077   auto RemoveLoopFromBackedgeMap =
7078       [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
7079         auto BTCPos = Map.find(L);
7080         if (BTCPos != Map.end()) {
7081           BTCPos->second.clear();
7082           Map.erase(BTCPos);
7083         }
7084       };
7085 
7086   SmallVector<const Loop *, 16> LoopWorklist(1, L);
7087   SmallVector<Instruction *, 32> Worklist;
7088   SmallPtrSet<Instruction *, 16> Visited;
7089 
7090   // Iterate over all the loops and sub-loops to drop SCEV information.
7091   while (!LoopWorklist.empty()) {
7092     auto *CurrL = LoopWorklist.pop_back_val();
7093 
7094     RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
7095     RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
7096 
7097     // Drop information about predicated SCEV rewrites for this loop.
7098     for (auto I = PredicatedSCEVRewrites.begin();
7099          I != PredicatedSCEVRewrites.end();) {
7100       std::pair<const SCEV *, const Loop *> Entry = I->first;
7101       if (Entry.second == CurrL)
7102         PredicatedSCEVRewrites.erase(I++);
7103       else
7104         ++I;
7105     }
7106 
7107     auto LoopUsersItr = LoopUsers.find(CurrL);
7108     if (LoopUsersItr != LoopUsers.end()) {
7109       for (auto *S : LoopUsersItr->second)
7110         forgetMemoizedResults(S);
7111       LoopUsers.erase(LoopUsersItr);
7112     }
7113 
7114     // Drop information about expressions based on loop-header PHIs.
7115     PushLoopPHIs(CurrL, Worklist);
7116 
7117     while (!Worklist.empty()) {
7118       Instruction *I = Worklist.pop_back_val();
7119       if (!Visited.insert(I).second)
7120         continue;
7121 
7122       ValueExprMapType::iterator It =
7123           ValueExprMap.find_as(static_cast<Value *>(I));
7124       if (It != ValueExprMap.end()) {
7125         eraseValueFromMap(It->first);
7126         forgetMemoizedResults(It->second);
7127         if (PHINode *PN = dyn_cast<PHINode>(I))
7128           ConstantEvolutionLoopExitValue.erase(PN);
7129       }
7130 
7131       PushDefUseChildren(I, Worklist);
7132     }
7133 
7134     LoopPropertiesCache.erase(CurrL);
7135     // Forget all contained loops too, to avoid dangling entries in the
7136     // ValuesAtScopes map.
7137     LoopWorklist.append(CurrL->begin(), CurrL->end());
7138   }
7139 }
7140 
forgetTopmostLoop(const Loop * L)7141 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
7142   while (Loop *Parent = L->getParentLoop())
7143     L = Parent;
7144   forgetLoop(L);
7145 }
7146 
forgetValue(Value * V)7147 void ScalarEvolution::forgetValue(Value *V) {
7148   Instruction *I = dyn_cast<Instruction>(V);
7149   if (!I) return;
7150 
7151   // Drop information about expressions based on loop-header PHIs.
7152   SmallVector<Instruction *, 16> Worklist;
7153   Worklist.push_back(I);
7154 
7155   SmallPtrSet<Instruction *, 8> Visited;
7156   while (!Worklist.empty()) {
7157     I = Worklist.pop_back_val();
7158     if (!Visited.insert(I).second)
7159       continue;
7160 
7161     ValueExprMapType::iterator It =
7162       ValueExprMap.find_as(static_cast<Value *>(I));
7163     if (It != ValueExprMap.end()) {
7164       eraseValueFromMap(It->first);
7165       forgetMemoizedResults(It->second);
7166       if (PHINode *PN = dyn_cast<PHINode>(I))
7167         ConstantEvolutionLoopExitValue.erase(PN);
7168     }
7169 
7170     PushDefUseChildren(I, Worklist);
7171   }
7172 }
7173 
forgetLoopDispositions(const Loop * L)7174 void ScalarEvolution::forgetLoopDispositions(const Loop *L) {
7175   LoopDispositions.clear();
7176 }
7177 
7178 /// Get the exact loop backedge taken count considering all loop exits. A
7179 /// computable result can only be returned for loops with all exiting blocks
7180 /// dominating the latch. howFarToZero assumes that the limit of each loop test
7181 /// is never skipped. This is a valid assumption as long as the loop exits via
7182 /// that test. For precise results, it is the caller's responsibility to specify
7183 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
7184 const SCEV *
getExact(const Loop * L,ScalarEvolution * SE,SCEVUnionPredicate * Preds) const7185 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
7186                                              SCEVUnionPredicate *Preds) const {
7187   // If any exits were not computable, the loop is not computable.
7188   if (!isComplete() || ExitNotTaken.empty())
7189     return SE->getCouldNotCompute();
7190 
7191   const BasicBlock *Latch = L->getLoopLatch();
7192   // All exiting blocks we have collected must dominate the only backedge.
7193   if (!Latch)
7194     return SE->getCouldNotCompute();
7195 
7196   // All exiting blocks we have gathered dominate loop's latch, so exact trip
7197   // count is simply a minimum out of all these calculated exit counts.
7198   SmallVector<const SCEV *, 2> Ops;
7199   for (auto &ENT : ExitNotTaken) {
7200     const SCEV *BECount = ENT.ExactNotTaken;
7201     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
7202     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
7203            "We should only have known counts for exiting blocks that dominate "
7204            "latch!");
7205 
7206     Ops.push_back(BECount);
7207 
7208     if (Preds && !ENT.hasAlwaysTruePredicate())
7209       Preds->add(ENT.Predicate.get());
7210 
7211     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
7212            "Predicate should be always true!");
7213   }
7214 
7215   return SE->getUMinFromMismatchedTypes(Ops);
7216 }
7217 
7218 /// Get the exact not taken count for this loop exit.
7219 const SCEV *
getExact(const BasicBlock * ExitingBlock,ScalarEvolution * SE) const7220 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
7221                                              ScalarEvolution *SE) const {
7222   for (auto &ENT : ExitNotTaken)
7223     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7224       return ENT.ExactNotTaken;
7225 
7226   return SE->getCouldNotCompute();
7227 }
7228 
getConstantMax(const BasicBlock * ExitingBlock,ScalarEvolution * SE) const7229 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
7230     const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
7231   for (auto &ENT : ExitNotTaken)
7232     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7233       return ENT.MaxNotTaken;
7234 
7235   return SE->getCouldNotCompute();
7236 }
7237 
7238 /// getConstantMax - Get the constant max backedge taken count for the loop.
7239 const SCEV *
getConstantMax(ScalarEvolution * SE) const7240 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
7241   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7242     return !ENT.hasAlwaysTruePredicate();
7243   };
7244 
7245   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax())
7246     return SE->getCouldNotCompute();
7247 
7248   assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
7249           isa<SCEVConstant>(getConstantMax())) &&
7250          "No point in having a non-constant max backedge taken count!");
7251   return getConstantMax();
7252 }
7253 
7254 const SCEV *
getSymbolicMax(const Loop * L,ScalarEvolution * SE)7255 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
7256                                                    ScalarEvolution *SE) {
7257   if (!SymbolicMax)
7258     SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
7259   return SymbolicMax;
7260 }
7261 
isConstantMaxOrZero(ScalarEvolution * SE) const7262 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
7263     ScalarEvolution *SE) const {
7264   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7265     return !ENT.hasAlwaysTruePredicate();
7266   };
7267   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
7268 }
7269 
hasOperand(const SCEV * S,ScalarEvolution * SE) const7270 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
7271                                                     ScalarEvolution *SE) const {
7272   if (getConstantMax() && getConstantMax() != SE->getCouldNotCompute() &&
7273       SE->hasOperand(getConstantMax(), S))
7274     return true;
7275 
7276   for (auto &ENT : ExitNotTaken)
7277     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
7278         SE->hasOperand(ENT.ExactNotTaken, S))
7279       return true;
7280 
7281   return false;
7282 }
7283 
ExitLimit(const SCEV * E)7284 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
7285     : ExactNotTaken(E), MaxNotTaken(E) {
7286   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7287           isa<SCEVConstant>(MaxNotTaken)) &&
7288          "No point in having a non-constant max backedge taken count!");
7289 }
7290 
ExitLimit(const SCEV * E,const SCEV * M,bool MaxOrZero,ArrayRef<const SmallPtrSetImpl<const SCEVPredicate * > * > PredSetList)7291 ScalarEvolution::ExitLimit::ExitLimit(
7292     const SCEV *E, const SCEV *M, bool MaxOrZero,
7293     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
7294     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
7295   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
7296           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
7297          "Exact is not allowed to be less precise than Max");
7298   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7299           isa<SCEVConstant>(MaxNotTaken)) &&
7300          "No point in having a non-constant max backedge taken count!");
7301   for (auto *PredSet : PredSetList)
7302     for (auto *P : *PredSet)
7303       addPredicate(P);
7304 }
7305 
ExitLimit(const SCEV * E,const SCEV * M,bool MaxOrZero,const SmallPtrSetImpl<const SCEVPredicate * > & PredSet)7306 ScalarEvolution::ExitLimit::ExitLimit(
7307     const SCEV *E, const SCEV *M, bool MaxOrZero,
7308     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
7309     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
7310   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7311           isa<SCEVConstant>(MaxNotTaken)) &&
7312          "No point in having a non-constant max backedge taken count!");
7313 }
7314 
ExitLimit(const SCEV * E,const SCEV * M,bool MaxOrZero)7315 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
7316                                       bool MaxOrZero)
7317     : ExitLimit(E, M, MaxOrZero, None) {
7318   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7319           isa<SCEVConstant>(MaxNotTaken)) &&
7320          "No point in having a non-constant max backedge taken count!");
7321 }
7322 
7323 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
7324 /// computable exit into a persistent ExitNotTakenInfo array.
BackedgeTakenInfo(ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,bool IsComplete,const SCEV * ConstantMax,bool MaxOrZero)7325 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
7326     ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
7327     bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
7328     : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
7329   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7330 
7331   ExitNotTaken.reserve(ExitCounts.size());
7332   std::transform(
7333       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
7334       [&](const EdgeExitInfo &EEI) {
7335         BasicBlock *ExitBB = EEI.first;
7336         const ExitLimit &EL = EEI.second;
7337         if (EL.Predicates.empty())
7338           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7339                                   nullptr);
7340 
7341         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
7342         for (auto *Pred : EL.Predicates)
7343           Predicate->add(Pred);
7344 
7345         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7346                                 std::move(Predicate));
7347       });
7348   assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
7349           isa<SCEVConstant>(ConstantMax)) &&
7350          "No point in having a non-constant max backedge taken count!");
7351 }
7352 
7353 /// Invalidate this result and free the ExitNotTakenInfo array.
clear()7354 void ScalarEvolution::BackedgeTakenInfo::clear() {
7355   ExitNotTaken.clear();
7356 }
7357 
7358 /// Compute the number of times the backedge of the specified loop will execute.
7359 ScalarEvolution::BackedgeTakenInfo
computeBackedgeTakenCount(const Loop * L,bool AllowPredicates)7360 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
7361                                            bool AllowPredicates) {
7362   SmallVector<BasicBlock *, 8> ExitingBlocks;
7363   L->getExitingBlocks(ExitingBlocks);
7364 
7365   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7366 
7367   SmallVector<EdgeExitInfo, 4> ExitCounts;
7368   bool CouldComputeBECount = true;
7369   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
7370   const SCEV *MustExitMaxBECount = nullptr;
7371   const SCEV *MayExitMaxBECount = nullptr;
7372   bool MustExitMaxOrZero = false;
7373 
7374   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
7375   // and compute maxBECount.
7376   // Do a union of all the predicates here.
7377   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
7378     BasicBlock *ExitBB = ExitingBlocks[i];
7379 
7380     // We canonicalize untaken exits to br (constant), ignore them so that
7381     // proving an exit untaken doesn't negatively impact our ability to reason
7382     // about the loop as whole.
7383     if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
7384       if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
7385         bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7386         if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne()))
7387           continue;
7388       }
7389 
7390     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
7391 
7392     assert((AllowPredicates || EL.Predicates.empty()) &&
7393            "Predicated exit limit when predicates are not allowed!");
7394 
7395     // 1. For each exit that can be computed, add an entry to ExitCounts.
7396     // CouldComputeBECount is true only if all exits can be computed.
7397     if (EL.ExactNotTaken == getCouldNotCompute())
7398       // We couldn't compute an exact value for this exit, so
7399       // we won't be able to compute an exact value for the loop.
7400       CouldComputeBECount = false;
7401     else
7402       ExitCounts.emplace_back(ExitBB, EL);
7403 
7404     // 2. Derive the loop's MaxBECount from each exit's max number of
7405     // non-exiting iterations. Partition the loop exits into two kinds:
7406     // LoopMustExits and LoopMayExits.
7407     //
7408     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
7409     // is a LoopMayExit.  If any computable LoopMustExit is found, then
7410     // MaxBECount is the minimum EL.MaxNotTaken of computable
7411     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
7412     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
7413     // computable EL.MaxNotTaken.
7414     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
7415         DT.dominates(ExitBB, Latch)) {
7416       if (!MustExitMaxBECount) {
7417         MustExitMaxBECount = EL.MaxNotTaken;
7418         MustExitMaxOrZero = EL.MaxOrZero;
7419       } else {
7420         MustExitMaxBECount =
7421             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
7422       }
7423     } else if (MayExitMaxBECount != getCouldNotCompute()) {
7424       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
7425         MayExitMaxBECount = EL.MaxNotTaken;
7426       else {
7427         MayExitMaxBECount =
7428             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
7429       }
7430     }
7431   }
7432   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
7433     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
7434   // The loop backedge will be taken the maximum or zero times if there's
7435   // a single exit that must be taken the maximum or zero times.
7436   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
7437   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
7438                            MaxBECount, MaxOrZero);
7439 }
7440 
7441 ScalarEvolution::ExitLimit
computeExitLimit(const Loop * L,BasicBlock * ExitingBlock,bool AllowPredicates)7442 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
7443                                       bool AllowPredicates) {
7444   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
7445   // If our exiting block does not dominate the latch, then its connection with
7446   // loop's exit limit may be far from trivial.
7447   const BasicBlock *Latch = L->getLoopLatch();
7448   if (!Latch || !DT.dominates(ExitingBlock, Latch))
7449     return getCouldNotCompute();
7450 
7451   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
7452   Instruction *Term = ExitingBlock->getTerminator();
7453   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
7454     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
7455     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7456     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
7457            "It should have one successor in loop and one exit block!");
7458     // Proceed to the next level to examine the exit condition expression.
7459     return computeExitLimitFromCond(
7460         L, BI->getCondition(), ExitIfTrue,
7461         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
7462   }
7463 
7464   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
7465     // For switch, make sure that there is a single exit from the loop.
7466     BasicBlock *Exit = nullptr;
7467     for (auto *SBB : successors(ExitingBlock))
7468       if (!L->contains(SBB)) {
7469         if (Exit) // Multiple exit successors.
7470           return getCouldNotCompute();
7471         Exit = SBB;
7472       }
7473     assert(Exit && "Exiting block must have at least one exit");
7474     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
7475                                                 /*ControlsExit=*/IsOnlyExit);
7476   }
7477 
7478   return getCouldNotCompute();
7479 }
7480 
computeExitLimitFromCond(const Loop * L,Value * ExitCond,bool ExitIfTrue,bool ControlsExit,bool AllowPredicates)7481 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
7482     const Loop *L, Value *ExitCond, bool ExitIfTrue,
7483     bool ControlsExit, bool AllowPredicates) {
7484   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
7485   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
7486                                         ControlsExit, AllowPredicates);
7487 }
7488 
7489 Optional<ScalarEvolution::ExitLimit>
find(const Loop * L,Value * ExitCond,bool ExitIfTrue,bool ControlsExit,bool AllowPredicates)7490 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
7491                                       bool ExitIfTrue, bool ControlsExit,
7492                                       bool AllowPredicates) {
7493   (void)this->L;
7494   (void)this->ExitIfTrue;
7495   (void)this->AllowPredicates;
7496 
7497   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7498          this->AllowPredicates == AllowPredicates &&
7499          "Variance in assumed invariant key components!");
7500   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
7501   if (Itr == TripCountMap.end())
7502     return None;
7503   return Itr->second;
7504 }
7505 
insert(const Loop * L,Value * ExitCond,bool ExitIfTrue,bool ControlsExit,bool AllowPredicates,const ExitLimit & EL)7506 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
7507                                              bool ExitIfTrue,
7508                                              bool ControlsExit,
7509                                              bool AllowPredicates,
7510                                              const ExitLimit &EL) {
7511   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7512          this->AllowPredicates == AllowPredicates &&
7513          "Variance in assumed invariant key components!");
7514 
7515   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7516   assert(InsertResult.second && "Expected successful insertion!");
7517   (void)InsertResult;
7518   (void)ExitIfTrue;
7519 }
7520 
computeExitLimitFromCondCached(ExitLimitCacheTy & Cache,const Loop * L,Value * ExitCond,bool ExitIfTrue,bool ControlsExit,bool AllowPredicates)7521 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7522     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7523     bool ControlsExit, bool AllowPredicates) {
7524 
7525   if (auto MaybeEL =
7526           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7527     return *MaybeEL;
7528 
7529   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7530                                               ControlsExit, AllowPredicates);
7531   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7532   return EL;
7533 }
7534 
computeExitLimitFromCondImpl(ExitLimitCacheTy & Cache,const Loop * L,Value * ExitCond,bool ExitIfTrue,bool ControlsExit,bool AllowPredicates)7535 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7536     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7537     bool ControlsExit, bool AllowPredicates) {
7538   // Handle BinOp conditions (And, Or).
7539   if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
7540           Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7541     return *LimitFromBinOp;
7542 
7543   // With an icmp, it may be feasible to compute an exact backedge-taken count.
7544   // Proceed to the next level to examine the icmp.
7545   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7546     ExitLimit EL =
7547         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7548     if (EL.hasFullInfo() || !AllowPredicates)
7549       return EL;
7550 
7551     // Try again, but use SCEV predicates this time.
7552     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7553                                     /*AllowPredicates=*/true);
7554   }
7555 
7556   // Check for a constant condition. These are normally stripped out by
7557   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7558   // preserve the CFG and is temporarily leaving constant conditions
7559   // in place.
7560   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7561     if (ExitIfTrue == !CI->getZExtValue())
7562       // The backedge is always taken.
7563       return getCouldNotCompute();
7564     else
7565       // The backedge is never taken.
7566       return getZero(CI->getType());
7567   }
7568 
7569   // If it's not an integer or pointer comparison then compute it the hard way.
7570   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7571 }
7572 
7573 Optional<ScalarEvolution::ExitLimit>
computeExitLimitFromCondFromBinOp(ExitLimitCacheTy & Cache,const Loop * L,Value * ExitCond,bool ExitIfTrue,bool ControlsExit,bool AllowPredicates)7574 ScalarEvolution::computeExitLimitFromCondFromBinOp(
7575     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7576     bool ControlsExit, bool AllowPredicates) {
7577   // Check if the controlling expression for this loop is an And or Or.
7578   if (auto *BO = dyn_cast<BinaryOperator>(ExitCond)) {
7579     if (BO->getOpcode() == Instruction::And)
7580       return computeExitLimitFromCondFromBinOpHelper(
7581           Cache, L, BO, !ExitIfTrue, ExitIfTrue, ControlsExit, AllowPredicates,
7582           ConstantInt::get(BO->getType(), 1));
7583     if (BO->getOpcode() == Instruction::Or)
7584       return computeExitLimitFromCondFromBinOpHelper(
7585           Cache, L, BO, ExitIfTrue, ExitIfTrue, ControlsExit, AllowPredicates,
7586           ConstantInt::get(BO->getType(), 0));
7587   }
7588   return None;
7589 }
7590 
7591 ScalarEvolution::ExitLimit
computeExitLimitFromCondFromBinOpHelper(ExitLimitCacheTy & Cache,const Loop * L,BinaryOperator * BO,bool EitherMayExit,bool ExitIfTrue,bool ControlsExit,bool AllowPredicates,const Constant * NeutralElement)7592 ScalarEvolution::computeExitLimitFromCondFromBinOpHelper(
7593     ExitLimitCacheTy &Cache, const Loop *L, BinaryOperator *BO,
7594     bool EitherMayExit, bool ExitIfTrue, bool ControlsExit,
7595     bool AllowPredicates, const Constant *NeutralElement) {
7596   ExitLimit EL0 = computeExitLimitFromCondCached(
7597       Cache, L, BO->getOperand(0), ExitIfTrue, ControlsExit && !EitherMayExit,
7598       AllowPredicates);
7599   ExitLimit EL1 = computeExitLimitFromCondCached(
7600       Cache, L, BO->getOperand(1), ExitIfTrue, ControlsExit && !EitherMayExit,
7601       AllowPredicates);
7602   // Be robust against unsimplified IR for the form "op i1 X,
7603   // NeutralElement"
7604   if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1)))
7605     return CI == NeutralElement ? EL0 : EL1;
7606   if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0)))
7607     return CI == NeutralElement ? EL1 : EL0;
7608   const SCEV *BECount = getCouldNotCompute();
7609   const SCEV *MaxBECount = getCouldNotCompute();
7610   if (EitherMayExit) {
7611     // Both conditions must be same for the loop to continue executing.
7612     // Choose the less conservative count.
7613     if (EL0.ExactNotTaken == getCouldNotCompute() ||
7614         EL1.ExactNotTaken == getCouldNotCompute())
7615       BECount = getCouldNotCompute();
7616     else
7617       BECount =
7618           getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7619     if (EL0.MaxNotTaken == getCouldNotCompute())
7620       MaxBECount = EL1.MaxNotTaken;
7621     else if (EL1.MaxNotTaken == getCouldNotCompute())
7622       MaxBECount = EL0.MaxNotTaken;
7623     else
7624       MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7625   } else {
7626     // Both conditions must be same at the same time for the loop to exit.
7627     // For now, be conservative.
7628     if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7629       BECount = EL0.ExactNotTaken;
7630   }
7631 
7632   // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7633   // to be more aggressive when computing BECount than when computing
7634   // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
7635   // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7636   // to not.
7637   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7638       !isa<SCEVCouldNotCompute>(BECount))
7639     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7640 
7641   return ExitLimit(BECount, MaxBECount, false,
7642                    { &EL0.Predicates, &EL1.Predicates });
7643 }
7644 
7645 ScalarEvolution::ExitLimit
computeExitLimitFromICmp(const Loop * L,ICmpInst * ExitCond,bool ExitIfTrue,bool ControlsExit,bool AllowPredicates)7646 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7647                                           ICmpInst *ExitCond,
7648                                           bool ExitIfTrue,
7649                                           bool ControlsExit,
7650                                           bool AllowPredicates) {
7651   // If the condition was exit on true, convert the condition to exit on false
7652   ICmpInst::Predicate Pred;
7653   if (!ExitIfTrue)
7654     Pred = ExitCond->getPredicate();
7655   else
7656     Pred = ExitCond->getInversePredicate();
7657   const ICmpInst::Predicate OriginalPred = Pred;
7658 
7659   // Handle common loops like: for (X = "string"; *X; ++X)
7660   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7661     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7662       ExitLimit ItCnt =
7663         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7664       if (ItCnt.hasAnyInfo())
7665         return ItCnt;
7666     }
7667 
7668   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7669   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7670 
7671   // Try to evaluate any dependencies out of the loop.
7672   LHS = getSCEVAtScope(LHS, L);
7673   RHS = getSCEVAtScope(RHS, L);
7674 
7675   // At this point, we would like to compute how many iterations of the
7676   // loop the predicate will return true for these inputs.
7677   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7678     // If there is a loop-invariant, force it into the RHS.
7679     std::swap(LHS, RHS);
7680     Pred = ICmpInst::getSwappedPredicate(Pred);
7681   }
7682 
7683   // Simplify the operands before analyzing them.
7684   (void)SimplifyICmpOperands(Pred, LHS, RHS);
7685 
7686   // If we have a comparison of a chrec against a constant, try to use value
7687   // ranges to answer this query.
7688   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7689     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7690       if (AddRec->getLoop() == L) {
7691         // Form the constant range.
7692         ConstantRange CompRange =
7693             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7694 
7695         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7696         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7697       }
7698 
7699   switch (Pred) {
7700   case ICmpInst::ICMP_NE: {                     // while (X != Y)
7701     // Convert to: while (X-Y != 0)
7702     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7703                                 AllowPredicates);
7704     if (EL.hasAnyInfo()) return EL;
7705     break;
7706   }
7707   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
7708     // Convert to: while (X-Y == 0)
7709     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7710     if (EL.hasAnyInfo()) return EL;
7711     break;
7712   }
7713   case ICmpInst::ICMP_SLT:
7714   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
7715     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7716     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7717                                     AllowPredicates);
7718     if (EL.hasAnyInfo()) return EL;
7719     break;
7720   }
7721   case ICmpInst::ICMP_SGT:
7722   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
7723     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7724     ExitLimit EL =
7725         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7726                             AllowPredicates);
7727     if (EL.hasAnyInfo()) return EL;
7728     break;
7729   }
7730   default:
7731     break;
7732   }
7733 
7734   auto *ExhaustiveCount =
7735       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7736 
7737   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7738     return ExhaustiveCount;
7739 
7740   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7741                                       ExitCond->getOperand(1), L, OriginalPred);
7742 }
7743 
7744 ScalarEvolution::ExitLimit
computeExitLimitFromSingleExitSwitch(const Loop * L,SwitchInst * Switch,BasicBlock * ExitingBlock,bool ControlsExit)7745 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7746                                                       SwitchInst *Switch,
7747                                                       BasicBlock *ExitingBlock,
7748                                                       bool ControlsExit) {
7749   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
7750 
7751   // Give up if the exit is the default dest of a switch.
7752   if (Switch->getDefaultDest() == ExitingBlock)
7753     return getCouldNotCompute();
7754 
7755   assert(L->contains(Switch->getDefaultDest()) &&
7756          "Default case must not exit the loop!");
7757   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7758   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7759 
7760   // while (X != Y) --> while (X-Y != 0)
7761   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7762   if (EL.hasAnyInfo())
7763     return EL;
7764 
7765   return getCouldNotCompute();
7766 }
7767 
7768 static ConstantInt *
EvaluateConstantChrecAtConstant(const SCEVAddRecExpr * AddRec,ConstantInt * C,ScalarEvolution & SE)7769 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7770                                 ScalarEvolution &SE) {
7771   const SCEV *InVal = SE.getConstant(C);
7772   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7773   assert(isa<SCEVConstant>(Val) &&
7774          "Evaluation of SCEV at constant didn't fold correctly?");
7775   return cast<SCEVConstant>(Val)->getValue();
7776 }
7777 
7778 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
7779 /// compute the backedge execution count.
7780 ScalarEvolution::ExitLimit
computeLoadConstantCompareExitLimit(LoadInst * LI,Constant * RHS,const Loop * L,ICmpInst::Predicate predicate)7781 ScalarEvolution::computeLoadConstantCompareExitLimit(
7782   LoadInst *LI,
7783   Constant *RHS,
7784   const Loop *L,
7785   ICmpInst::Predicate predicate) {
7786   if (LI->isVolatile()) return getCouldNotCompute();
7787 
7788   // Check to see if the loaded pointer is a getelementptr of a global.
7789   // TODO: Use SCEV instead of manually grubbing with GEPs.
7790   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7791   if (!GEP) return getCouldNotCompute();
7792 
7793   // Make sure that it is really a constant global we are gepping, with an
7794   // initializer, and make sure the first IDX is really 0.
7795   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7796   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7797       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7798       !cast<Constant>(GEP->getOperand(1))->isNullValue())
7799     return getCouldNotCompute();
7800 
7801   // Okay, we allow one non-constant index into the GEP instruction.
7802   Value *VarIdx = nullptr;
7803   std::vector<Constant*> Indexes;
7804   unsigned VarIdxNum = 0;
7805   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7806     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7807       Indexes.push_back(CI);
7808     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7809       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
7810       VarIdx = GEP->getOperand(i);
7811       VarIdxNum = i-2;
7812       Indexes.push_back(nullptr);
7813     }
7814 
7815   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7816   if (!VarIdx)
7817     return getCouldNotCompute();
7818 
7819   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7820   // Check to see if X is a loop variant variable value now.
7821   const SCEV *Idx = getSCEV(VarIdx);
7822   Idx = getSCEVAtScope(Idx, L);
7823 
7824   // We can only recognize very limited forms of loop index expressions, in
7825   // particular, only affine AddRec's like {C1,+,C2}.
7826   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7827   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
7828       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7829       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7830     return getCouldNotCompute();
7831 
7832   unsigned MaxSteps = MaxBruteForceIterations;
7833   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7834     ConstantInt *ItCst = ConstantInt::get(
7835                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
7836     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7837 
7838     // Form the GEP offset.
7839     Indexes[VarIdxNum] = Val;
7840 
7841     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7842                                                          Indexes);
7843     if (!Result) break;  // Cannot compute!
7844 
7845     // Evaluate the condition for this iteration.
7846     Result = ConstantExpr::getICmp(predicate, Result, RHS);
7847     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
7848     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7849       ++NumArrayLenItCounts;
7850       return getConstant(ItCst);   // Found terminating iteration!
7851     }
7852   }
7853   return getCouldNotCompute();
7854 }
7855 
computeShiftCompareExitLimit(Value * LHS,Value * RHSV,const Loop * L,ICmpInst::Predicate Pred)7856 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7857     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7858   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7859   if (!RHS)
7860     return getCouldNotCompute();
7861 
7862   const BasicBlock *Latch = L->getLoopLatch();
7863   if (!Latch)
7864     return getCouldNotCompute();
7865 
7866   const BasicBlock *Predecessor = L->getLoopPredecessor();
7867   if (!Predecessor)
7868     return getCouldNotCompute();
7869 
7870   // Return true if V is of the form "LHS `shift_op` <positive constant>".
7871   // Return LHS in OutLHS and shift_opt in OutOpCode.
7872   auto MatchPositiveShift =
7873       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7874 
7875     using namespace PatternMatch;
7876 
7877     ConstantInt *ShiftAmt;
7878     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7879       OutOpCode = Instruction::LShr;
7880     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7881       OutOpCode = Instruction::AShr;
7882     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7883       OutOpCode = Instruction::Shl;
7884     else
7885       return false;
7886 
7887     return ShiftAmt->getValue().isStrictlyPositive();
7888   };
7889 
7890   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7891   //
7892   // loop:
7893   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7894   //   %iv.shifted = lshr i32 %iv, <positive constant>
7895   //
7896   // Return true on a successful match.  Return the corresponding PHI node (%iv
7897   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7898   auto MatchShiftRecurrence =
7899       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
7900     Optional<Instruction::BinaryOps> PostShiftOpCode;
7901 
7902     {
7903       Instruction::BinaryOps OpC;
7904       Value *V;
7905 
7906       // If we encounter a shift instruction, "peel off" the shift operation,
7907       // and remember that we did so.  Later when we inspect %iv's backedge
7908       // value, we will make sure that the backedge value uses the same
7909       // operation.
7910       //
7911       // Note: the peeled shift operation does not have to be the same
7912       // instruction as the one feeding into the PHI's backedge value.  We only
7913       // really care about it being the same *kind* of shift instruction --
7914       // that's all that is required for our later inferences to hold.
7915       if (MatchPositiveShift(LHS, V, OpC)) {
7916         PostShiftOpCode = OpC;
7917         LHS = V;
7918       }
7919     }
7920 
7921     PNOut = dyn_cast<PHINode>(LHS);
7922     if (!PNOut || PNOut->getParent() != L->getHeader())
7923       return false;
7924 
7925     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7926     Value *OpLHS;
7927 
7928     return
7929         // The backedge value for the PHI node must be a shift by a positive
7930         // amount
7931         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7932 
7933         // of the PHI node itself
7934         OpLHS == PNOut &&
7935 
7936         // and the kind of shift should be match the kind of shift we peeled
7937         // off, if any.
7938         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
7939   };
7940 
7941   PHINode *PN;
7942   Instruction::BinaryOps OpCode;
7943   if (!MatchShiftRecurrence(LHS, PN, OpCode))
7944     return getCouldNotCompute();
7945 
7946   const DataLayout &DL = getDataLayout();
7947 
7948   // The key rationale for this optimization is that for some kinds of shift
7949   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7950   // within a finite number of iterations.  If the condition guarding the
7951   // backedge (in the sense that the backedge is taken if the condition is true)
7952   // is false for the value the shift recurrence stabilizes to, then we know
7953   // that the backedge is taken only a finite number of times.
7954 
7955   ConstantInt *StableValue = nullptr;
7956   switch (OpCode) {
7957   default:
7958     llvm_unreachable("Impossible case!");
7959 
7960   case Instruction::AShr: {
7961     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7962     // bitwidth(K) iterations.
7963     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
7964     KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
7965                                        Predecessor->getTerminator(), &DT);
7966     auto *Ty = cast<IntegerType>(RHS->getType());
7967     if (Known.isNonNegative())
7968       StableValue = ConstantInt::get(Ty, 0);
7969     else if (Known.isNegative())
7970       StableValue = ConstantInt::get(Ty, -1, true);
7971     else
7972       return getCouldNotCompute();
7973 
7974     break;
7975   }
7976   case Instruction::LShr:
7977   case Instruction::Shl:
7978     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
7979     // stabilize to 0 in at most bitwidth(K) iterations.
7980     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
7981     break;
7982   }
7983 
7984   auto *Result =
7985       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
7986   assert(Result->getType()->isIntegerTy(1) &&
7987          "Otherwise cannot be an operand to a branch instruction");
7988 
7989   if (Result->isZeroValue()) {
7990     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7991     const SCEV *UpperBound =
7992         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
7993     return ExitLimit(getCouldNotCompute(), UpperBound, false);
7994   }
7995 
7996   return getCouldNotCompute();
7997 }
7998 
7999 /// Return true if we can constant fold an instruction of the specified type,
8000 /// assuming that all operands were constants.
CanConstantFold(const Instruction * I)8001 static bool CanConstantFold(const Instruction *I) {
8002   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
8003       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8004       isa<LoadInst>(I) || isa<ExtractValueInst>(I))
8005     return true;
8006 
8007   if (const CallInst *CI = dyn_cast<CallInst>(I))
8008     if (const Function *F = CI->getCalledFunction())
8009       return canConstantFoldCallTo(CI, F);
8010   return false;
8011 }
8012 
8013 /// Determine whether this instruction can constant evolve within this loop
8014 /// assuming its operands can all constant evolve.
canConstantEvolve(Instruction * I,const Loop * L)8015 static bool canConstantEvolve(Instruction *I, const Loop *L) {
8016   // An instruction outside of the loop can't be derived from a loop PHI.
8017   if (!L->contains(I)) return false;
8018 
8019   if (isa<PHINode>(I)) {
8020     // We don't currently keep track of the control flow needed to evaluate
8021     // PHIs, so we cannot handle PHIs inside of loops.
8022     return L->getHeader() == I->getParent();
8023   }
8024 
8025   // If we won't be able to constant fold this expression even if the operands
8026   // are constants, bail early.
8027   return CanConstantFold(I);
8028 }
8029 
8030 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
8031 /// recursing through each instruction operand until reaching a loop header phi.
8032 static PHINode *
getConstantEvolvingPHIOperands(Instruction * UseInst,const Loop * L,DenseMap<Instruction *,PHINode * > & PHIMap,unsigned Depth)8033 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
8034                                DenseMap<Instruction *, PHINode *> &PHIMap,
8035                                unsigned Depth) {
8036   if (Depth > MaxConstantEvolvingDepth)
8037     return nullptr;
8038 
8039   // Otherwise, we can evaluate this instruction if all of its operands are
8040   // constant or derived from a PHI node themselves.
8041   PHINode *PHI = nullptr;
8042   for (Value *Op : UseInst->operands()) {
8043     if (isa<Constant>(Op)) continue;
8044 
8045     Instruction *OpInst = dyn_cast<Instruction>(Op);
8046     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
8047 
8048     PHINode *P = dyn_cast<PHINode>(OpInst);
8049     if (!P)
8050       // If this operand is already visited, reuse the prior result.
8051       // We may have P != PHI if this is the deepest point at which the
8052       // inconsistent paths meet.
8053       P = PHIMap.lookup(OpInst);
8054     if (!P) {
8055       // Recurse and memoize the results, whether a phi is found or not.
8056       // This recursive call invalidates pointers into PHIMap.
8057       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
8058       PHIMap[OpInst] = P;
8059     }
8060     if (!P)
8061       return nullptr;  // Not evolving from PHI
8062     if (PHI && PHI != P)
8063       return nullptr;  // Evolving from multiple different PHIs.
8064     PHI = P;
8065   }
8066   // This is a expression evolving from a constant PHI!
8067   return PHI;
8068 }
8069 
8070 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
8071 /// in the loop that V is derived from.  We allow arbitrary operations along the
8072 /// way, but the operands of an operation must either be constants or a value
8073 /// derived from a constant PHI.  If this expression does not fit with these
8074 /// constraints, return null.
getConstantEvolvingPHI(Value * V,const Loop * L)8075 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
8076   Instruction *I = dyn_cast<Instruction>(V);
8077   if (!I || !canConstantEvolve(I, L)) return nullptr;
8078 
8079   if (PHINode *PN = dyn_cast<PHINode>(I))
8080     return PN;
8081 
8082   // Record non-constant instructions contained by the loop.
8083   DenseMap<Instruction *, PHINode *> PHIMap;
8084   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
8085 }
8086 
8087 /// EvaluateExpression - Given an expression that passes the
8088 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
8089 /// in the loop has the value PHIVal.  If we can't fold this expression for some
8090 /// reason, return null.
EvaluateExpression(Value * V,const Loop * L,DenseMap<Instruction *,Constant * > & Vals,const DataLayout & DL,const TargetLibraryInfo * TLI)8091 static Constant *EvaluateExpression(Value *V, const Loop *L,
8092                                     DenseMap<Instruction *, Constant *> &Vals,
8093                                     const DataLayout &DL,
8094                                     const TargetLibraryInfo *TLI) {
8095   // Convenient constant check, but redundant for recursive calls.
8096   if (Constant *C = dyn_cast<Constant>(V)) return C;
8097   Instruction *I = dyn_cast<Instruction>(V);
8098   if (!I) return nullptr;
8099 
8100   if (Constant *C = Vals.lookup(I)) return C;
8101 
8102   // An instruction inside the loop depends on a value outside the loop that we
8103   // weren't given a mapping for, or a value such as a call inside the loop.
8104   if (!canConstantEvolve(I, L)) return nullptr;
8105 
8106   // An unmapped PHI can be due to a branch or another loop inside this loop,
8107   // or due to this not being the initial iteration through a loop where we
8108   // couldn't compute the evolution of this particular PHI last time.
8109   if (isa<PHINode>(I)) return nullptr;
8110 
8111   std::vector<Constant*> Operands(I->getNumOperands());
8112 
8113   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
8114     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
8115     if (!Operand) {
8116       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
8117       if (!Operands[i]) return nullptr;
8118       continue;
8119     }
8120     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
8121     Vals[Operand] = C;
8122     if (!C) return nullptr;
8123     Operands[i] = C;
8124   }
8125 
8126   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8127     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8128                                            Operands[1], DL, TLI);
8129   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8130     if (!LI->isVolatile())
8131       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8132   }
8133   return ConstantFoldInstOperands(I, Operands, DL, TLI);
8134 }
8135 
8136 
8137 // If every incoming value to PN except the one for BB is a specific Constant,
8138 // return that, else return nullptr.
getOtherIncomingValue(PHINode * PN,BasicBlock * BB)8139 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
8140   Constant *IncomingVal = nullptr;
8141 
8142   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8143     if (PN->getIncomingBlock(i) == BB)
8144       continue;
8145 
8146     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
8147     if (!CurrentVal)
8148       return nullptr;
8149 
8150     if (IncomingVal != CurrentVal) {
8151       if (IncomingVal)
8152         return nullptr;
8153       IncomingVal = CurrentVal;
8154     }
8155   }
8156 
8157   return IncomingVal;
8158 }
8159 
8160 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
8161 /// in the header of its containing loop, we know the loop executes a
8162 /// constant number of times, and the PHI node is just a recurrence
8163 /// involving constants, fold it.
8164 Constant *
getConstantEvolutionLoopExitValue(PHINode * PN,const APInt & BEs,const Loop * L)8165 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
8166                                                    const APInt &BEs,
8167                                                    const Loop *L) {
8168   auto I = ConstantEvolutionLoopExitValue.find(PN);
8169   if (I != ConstantEvolutionLoopExitValue.end())
8170     return I->second;
8171 
8172   if (BEs.ugt(MaxBruteForceIterations))
8173     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
8174 
8175   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
8176 
8177   DenseMap<Instruction *, Constant *> CurrentIterVals;
8178   BasicBlock *Header = L->getHeader();
8179   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8180 
8181   BasicBlock *Latch = L->getLoopLatch();
8182   if (!Latch)
8183     return nullptr;
8184 
8185   for (PHINode &PHI : Header->phis()) {
8186     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8187       CurrentIterVals[&PHI] = StartCST;
8188   }
8189   if (!CurrentIterVals.count(PN))
8190     return RetVal = nullptr;
8191 
8192   Value *BEValue = PN->getIncomingValueForBlock(Latch);
8193 
8194   // Execute the loop symbolically to determine the exit value.
8195   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
8196          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
8197 
8198   unsigned NumIterations = BEs.getZExtValue(); // must be in range
8199   unsigned IterationNum = 0;
8200   const DataLayout &DL = getDataLayout();
8201   for (; ; ++IterationNum) {
8202     if (IterationNum == NumIterations)
8203       return RetVal = CurrentIterVals[PN];  // Got exit value!
8204 
8205     // Compute the value of the PHIs for the next iteration.
8206     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
8207     DenseMap<Instruction *, Constant *> NextIterVals;
8208     Constant *NextPHI =
8209         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8210     if (!NextPHI)
8211       return nullptr;        // Couldn't evaluate!
8212     NextIterVals[PN] = NextPHI;
8213 
8214     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
8215 
8216     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
8217     // cease to be able to evaluate one of them or if they stop evolving,
8218     // because that doesn't necessarily prevent us from computing PN.
8219     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
8220     for (const auto &I : CurrentIterVals) {
8221       PHINode *PHI = dyn_cast<PHINode>(I.first);
8222       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
8223       PHIsToCompute.emplace_back(PHI, I.second);
8224     }
8225     // We use two distinct loops because EvaluateExpression may invalidate any
8226     // iterators into CurrentIterVals.
8227     for (const auto &I : PHIsToCompute) {
8228       PHINode *PHI = I.first;
8229       Constant *&NextPHI = NextIterVals[PHI];
8230       if (!NextPHI) {   // Not already computed.
8231         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8232         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8233       }
8234       if (NextPHI != I.second)
8235         StoppedEvolving = false;
8236     }
8237 
8238     // If all entries in CurrentIterVals == NextIterVals then we can stop
8239     // iterating, the loop can't continue to change.
8240     if (StoppedEvolving)
8241       return RetVal = CurrentIterVals[PN];
8242 
8243     CurrentIterVals.swap(NextIterVals);
8244   }
8245 }
8246 
computeExitCountExhaustively(const Loop * L,Value * Cond,bool ExitWhen)8247 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
8248                                                           Value *Cond,
8249                                                           bool ExitWhen) {
8250   PHINode *PN = getConstantEvolvingPHI(Cond, L);
8251   if (!PN) return getCouldNotCompute();
8252 
8253   // If the loop is canonicalized, the PHI will have exactly two entries.
8254   // That's the only form we support here.
8255   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
8256 
8257   DenseMap<Instruction *, Constant *> CurrentIterVals;
8258   BasicBlock *Header = L->getHeader();
8259   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
8260 
8261   BasicBlock *Latch = L->getLoopLatch();
8262   assert(Latch && "Should follow from NumIncomingValues == 2!");
8263 
8264   for (PHINode &PHI : Header->phis()) {
8265     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8266       CurrentIterVals[&PHI] = StartCST;
8267   }
8268   if (!CurrentIterVals.count(PN))
8269     return getCouldNotCompute();
8270 
8271   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
8272   // the loop symbolically to determine when the condition gets a value of
8273   // "ExitWhen".
8274   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
8275   const DataLayout &DL = getDataLayout();
8276   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
8277     auto *CondVal = dyn_cast_or_null<ConstantInt>(
8278         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
8279 
8280     // Couldn't symbolically evaluate.
8281     if (!CondVal) return getCouldNotCompute();
8282 
8283     if (CondVal->getValue() == uint64_t(ExitWhen)) {
8284       ++NumBruteForceTripCountsComputed;
8285       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
8286     }
8287 
8288     // Update all the PHI nodes for the next iteration.
8289     DenseMap<Instruction *, Constant *> NextIterVals;
8290 
8291     // Create a list of which PHIs we need to compute. We want to do this before
8292     // calling EvaluateExpression on them because that may invalidate iterators
8293     // into CurrentIterVals.
8294     SmallVector<PHINode *, 8> PHIsToCompute;
8295     for (const auto &I : CurrentIterVals) {
8296       PHINode *PHI = dyn_cast<PHINode>(I.first);
8297       if (!PHI || PHI->getParent() != Header) continue;
8298       PHIsToCompute.push_back(PHI);
8299     }
8300     for (PHINode *PHI : PHIsToCompute) {
8301       Constant *&NextPHI = NextIterVals[PHI];
8302       if (NextPHI) continue;    // Already computed!
8303 
8304       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8305       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8306     }
8307     CurrentIterVals.swap(NextIterVals);
8308   }
8309 
8310   // Too many iterations were needed to evaluate.
8311   return getCouldNotCompute();
8312 }
8313 
getSCEVAtScope(const SCEV * V,const Loop * L)8314 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
8315   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
8316       ValuesAtScopes[V];
8317   // Check to see if we've folded this expression at this loop before.
8318   for (auto &LS : Values)
8319     if (LS.first == L)
8320       return LS.second ? LS.second : V;
8321 
8322   Values.emplace_back(L, nullptr);
8323 
8324   // Otherwise compute it.
8325   const SCEV *C = computeSCEVAtScope(V, L);
8326   for (auto &LS : reverse(ValuesAtScopes[V]))
8327     if (LS.first == L) {
8328       LS.second = C;
8329       break;
8330     }
8331   return C;
8332 }
8333 
8334 /// This builds up a Constant using the ConstantExpr interface.  That way, we
8335 /// will return Constants for objects which aren't represented by a
8336 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
8337 /// Returns NULL if the SCEV isn't representable as a Constant.
BuildConstantFromSCEV(const SCEV * V)8338 static Constant *BuildConstantFromSCEV(const SCEV *V) {
8339   switch (V->getSCEVType()) {
8340   case scCouldNotCompute:
8341   case scAddRecExpr:
8342     return nullptr;
8343   case scConstant:
8344     return cast<SCEVConstant>(V)->getValue();
8345   case scUnknown:
8346     return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
8347   case scSignExtend: {
8348     const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
8349     if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
8350       return ConstantExpr::getSExt(CastOp, SS->getType());
8351     return nullptr;
8352   }
8353   case scZeroExtend: {
8354     const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
8355     if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
8356       return ConstantExpr::getZExt(CastOp, SZ->getType());
8357     return nullptr;
8358   }
8359   case scPtrToInt: {
8360     const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
8361     if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
8362       return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
8363 
8364     return nullptr;
8365   }
8366   case scTruncate: {
8367     const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
8368     if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
8369       return ConstantExpr::getTrunc(CastOp, ST->getType());
8370     return nullptr;
8371   }
8372   case scAddExpr: {
8373     const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
8374     if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
8375       if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8376         unsigned AS = PTy->getAddressSpace();
8377         Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8378         C = ConstantExpr::getBitCast(C, DestPtrTy);
8379       }
8380       for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
8381         Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
8382         if (!C2)
8383           return nullptr;
8384 
8385         // First pointer!
8386         if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
8387           unsigned AS = C2->getType()->getPointerAddressSpace();
8388           std::swap(C, C2);
8389           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8390           // The offsets have been converted to bytes.  We can add bytes to an
8391           // i8* by GEP with the byte count in the first index.
8392           C = ConstantExpr::getBitCast(C, DestPtrTy);
8393         }
8394 
8395         // Don't bother trying to sum two pointers. We probably can't
8396         // statically compute a load that results from it anyway.
8397         if (C2->getType()->isPointerTy())
8398           return nullptr;
8399 
8400         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8401           if (PTy->getElementType()->isStructTy())
8402             C2 = ConstantExpr::getIntegerCast(
8403                 C2, Type::getInt32Ty(C->getContext()), true);
8404           C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
8405         } else
8406           C = ConstantExpr::getAdd(C, C2);
8407       }
8408       return C;
8409     }
8410     return nullptr;
8411   }
8412   case scMulExpr: {
8413     const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
8414     if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
8415       // Don't bother with pointers at all.
8416       if (C->getType()->isPointerTy())
8417         return nullptr;
8418       for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
8419         Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
8420         if (!C2 || C2->getType()->isPointerTy())
8421           return nullptr;
8422         C = ConstantExpr::getMul(C, C2);
8423       }
8424       return C;
8425     }
8426     return nullptr;
8427   }
8428   case scUDivExpr: {
8429     const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
8430     if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
8431       if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
8432         if (LHS->getType() == RHS->getType())
8433           return ConstantExpr::getUDiv(LHS, RHS);
8434     return nullptr;
8435   }
8436   case scSMaxExpr:
8437   case scUMaxExpr:
8438   case scSMinExpr:
8439   case scUMinExpr:
8440     return nullptr; // TODO: smax, umax, smin, umax.
8441   }
8442   llvm_unreachable("Unknown SCEV kind!");
8443 }
8444 
computeSCEVAtScope(const SCEV * V,const Loop * L)8445 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
8446   if (isa<SCEVConstant>(V)) return V;
8447 
8448   // If this instruction is evolved from a constant-evolving PHI, compute the
8449   // exit value from the loop without using SCEVs.
8450   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
8451     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
8452       if (PHINode *PN = dyn_cast<PHINode>(I)) {
8453         const Loop *CurrLoop = this->LI[I->getParent()];
8454         // Looking for loop exit value.
8455         if (CurrLoop && CurrLoop->getParentLoop() == L &&
8456             PN->getParent() == CurrLoop->getHeader()) {
8457           // Okay, there is no closed form solution for the PHI node.  Check
8458           // to see if the loop that contains it has a known backedge-taken
8459           // count.  If so, we may be able to force computation of the exit
8460           // value.
8461           const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
8462           // This trivial case can show up in some degenerate cases where
8463           // the incoming IR has not yet been fully simplified.
8464           if (BackedgeTakenCount->isZero()) {
8465             Value *InitValue = nullptr;
8466             bool MultipleInitValues = false;
8467             for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
8468               if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
8469                 if (!InitValue)
8470                   InitValue = PN->getIncomingValue(i);
8471                 else if (InitValue != PN->getIncomingValue(i)) {
8472                   MultipleInitValues = true;
8473                   break;
8474                 }
8475               }
8476             }
8477             if (!MultipleInitValues && InitValue)
8478               return getSCEV(InitValue);
8479           }
8480           // Do we have a loop invariant value flowing around the backedge
8481           // for a loop which must execute the backedge?
8482           if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
8483               isKnownPositive(BackedgeTakenCount) &&
8484               PN->getNumIncomingValues() == 2) {
8485 
8486             unsigned InLoopPred =
8487                 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
8488             Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
8489             if (CurrLoop->isLoopInvariant(BackedgeVal))
8490               return getSCEV(BackedgeVal);
8491           }
8492           if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
8493             // Okay, we know how many times the containing loop executes.  If
8494             // this is a constant evolving PHI node, get the final value at
8495             // the specified iteration number.
8496             Constant *RV = getConstantEvolutionLoopExitValue(
8497                 PN, BTCC->getAPInt(), CurrLoop);
8498             if (RV) return getSCEV(RV);
8499           }
8500         }
8501 
8502         // If there is a single-input Phi, evaluate it at our scope. If we can
8503         // prove that this replacement does not break LCSSA form, use new value.
8504         if (PN->getNumOperands() == 1) {
8505           const SCEV *Input = getSCEV(PN->getOperand(0));
8506           const SCEV *InputAtScope = getSCEVAtScope(Input, L);
8507           // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
8508           // for the simplest case just support constants.
8509           if (isa<SCEVConstant>(InputAtScope)) return InputAtScope;
8510         }
8511       }
8512 
8513       // Okay, this is an expression that we cannot symbolically evaluate
8514       // into a SCEV.  Check to see if it's possible to symbolically evaluate
8515       // the arguments into constants, and if so, try to constant propagate the
8516       // result.  This is particularly useful for computing loop exit values.
8517       if (CanConstantFold(I)) {
8518         SmallVector<Constant *, 4> Operands;
8519         bool MadeImprovement = false;
8520         for (Value *Op : I->operands()) {
8521           if (Constant *C = dyn_cast<Constant>(Op)) {
8522             Operands.push_back(C);
8523             continue;
8524           }
8525 
8526           // If any of the operands is non-constant and if they are
8527           // non-integer and non-pointer, don't even try to analyze them
8528           // with scev techniques.
8529           if (!isSCEVable(Op->getType()))
8530             return V;
8531 
8532           const SCEV *OrigV = getSCEV(Op);
8533           const SCEV *OpV = getSCEVAtScope(OrigV, L);
8534           MadeImprovement |= OrigV != OpV;
8535 
8536           Constant *C = BuildConstantFromSCEV(OpV);
8537           if (!C) return V;
8538           if (C->getType() != Op->getType())
8539             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
8540                                                               Op->getType(),
8541                                                               false),
8542                                       C, Op->getType());
8543           Operands.push_back(C);
8544         }
8545 
8546         // Check to see if getSCEVAtScope actually made an improvement.
8547         if (MadeImprovement) {
8548           Constant *C = nullptr;
8549           const DataLayout &DL = getDataLayout();
8550           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
8551             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8552                                                 Operands[1], DL, &TLI);
8553           else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) {
8554             if (!Load->isVolatile())
8555               C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(),
8556                                                DL);
8557           } else
8558             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
8559           if (!C) return V;
8560           return getSCEV(C);
8561         }
8562       }
8563     }
8564 
8565     // This is some other type of SCEVUnknown, just return it.
8566     return V;
8567   }
8568 
8569   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8570     // Avoid performing the look-up in the common case where the specified
8571     // expression has no loop-variant portions.
8572     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8573       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8574       if (OpAtScope != Comm->getOperand(i)) {
8575         // Okay, at least one of these operands is loop variant but might be
8576         // foldable.  Build a new instance of the folded commutative expression.
8577         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8578                                             Comm->op_begin()+i);
8579         NewOps.push_back(OpAtScope);
8580 
8581         for (++i; i != e; ++i) {
8582           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8583           NewOps.push_back(OpAtScope);
8584         }
8585         if (isa<SCEVAddExpr>(Comm))
8586           return getAddExpr(NewOps, Comm->getNoWrapFlags());
8587         if (isa<SCEVMulExpr>(Comm))
8588           return getMulExpr(NewOps, Comm->getNoWrapFlags());
8589         if (isa<SCEVMinMaxExpr>(Comm))
8590           return getMinMaxExpr(Comm->getSCEVType(), NewOps);
8591         llvm_unreachable("Unknown commutative SCEV type!");
8592       }
8593     }
8594     // If we got here, all operands are loop invariant.
8595     return Comm;
8596   }
8597 
8598   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8599     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8600     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8601     if (LHS == Div->getLHS() && RHS == Div->getRHS())
8602       return Div;   // must be loop invariant
8603     return getUDivExpr(LHS, RHS);
8604   }
8605 
8606   // If this is a loop recurrence for a loop that does not contain L, then we
8607   // are dealing with the final value computed by the loop.
8608   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8609     // First, attempt to evaluate each operand.
8610     // Avoid performing the look-up in the common case where the specified
8611     // expression has no loop-variant portions.
8612     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8613       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8614       if (OpAtScope == AddRec->getOperand(i))
8615         continue;
8616 
8617       // Okay, at least one of these operands is loop variant but might be
8618       // foldable.  Build a new instance of the folded commutative expression.
8619       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8620                                           AddRec->op_begin()+i);
8621       NewOps.push_back(OpAtScope);
8622       for (++i; i != e; ++i)
8623         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8624 
8625       const SCEV *FoldedRec =
8626         getAddRecExpr(NewOps, AddRec->getLoop(),
8627                       AddRec->getNoWrapFlags(SCEV::FlagNW));
8628       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8629       // The addrec may be folded to a nonrecurrence, for example, if the
8630       // induction variable is multiplied by zero after constant folding. Go
8631       // ahead and return the folded value.
8632       if (!AddRec)
8633         return FoldedRec;
8634       break;
8635     }
8636 
8637     // If the scope is outside the addrec's loop, evaluate it by using the
8638     // loop exit value of the addrec.
8639     if (!AddRec->getLoop()->contains(L)) {
8640       // To evaluate this recurrence, we need to know how many times the AddRec
8641       // loop iterates.  Compute this now.
8642       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8643       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8644 
8645       // Then, evaluate the AddRec.
8646       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8647     }
8648 
8649     return AddRec;
8650   }
8651 
8652   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8653     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8654     if (Op == Cast->getOperand())
8655       return Cast;  // must be loop invariant
8656     return getZeroExtendExpr(Op, Cast->getType());
8657   }
8658 
8659   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8660     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8661     if (Op == Cast->getOperand())
8662       return Cast;  // must be loop invariant
8663     return getSignExtendExpr(Op, Cast->getType());
8664   }
8665 
8666   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8667     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8668     if (Op == Cast->getOperand())
8669       return Cast;  // must be loop invariant
8670     return getTruncateExpr(Op, Cast->getType());
8671   }
8672 
8673   if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) {
8674     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8675     if (Op == Cast->getOperand())
8676       return Cast; // must be loop invariant
8677     return getPtrToIntExpr(Op, Cast->getType());
8678   }
8679 
8680   llvm_unreachable("Unknown SCEV type!");
8681 }
8682 
getSCEVAtScope(Value * V,const Loop * L)8683 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
8684   return getSCEVAtScope(getSCEV(V), L);
8685 }
8686 
stripInjectiveFunctions(const SCEV * S) const8687 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
8688   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
8689     return stripInjectiveFunctions(ZExt->getOperand());
8690   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
8691     return stripInjectiveFunctions(SExt->getOperand());
8692   return S;
8693 }
8694 
8695 /// Finds the minimum unsigned root of the following equation:
8696 ///
8697 ///     A * X = B (mod N)
8698 ///
8699 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8700 /// A and B isn't important.
8701 ///
8702 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
SolveLinEquationWithOverflow(const APInt & A,const SCEV * B,ScalarEvolution & SE)8703 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
8704                                                ScalarEvolution &SE) {
8705   uint32_t BW = A.getBitWidth();
8706   assert(BW == SE.getTypeSizeInBits(B->getType()));
8707   assert(A != 0 && "A must be non-zero.");
8708 
8709   // 1. D = gcd(A, N)
8710   //
8711   // The gcd of A and N may have only one prime factor: 2. The number of
8712   // trailing zeros in A is its multiplicity
8713   uint32_t Mult2 = A.countTrailingZeros();
8714   // D = 2^Mult2
8715 
8716   // 2. Check if B is divisible by D.
8717   //
8718   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8719   // is not less than multiplicity of this prime factor for D.
8720   if (SE.GetMinTrailingZeros(B) < Mult2)
8721     return SE.getCouldNotCompute();
8722 
8723   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8724   // modulo (N / D).
8725   //
8726   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8727   // (N / D) in general. The inverse itself always fits into BW bits, though,
8728   // so we immediately truncate it.
8729   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
8730   APInt Mod(BW + 1, 0);
8731   Mod.setBit(BW - Mult2);  // Mod = N / D
8732   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
8733 
8734   // 4. Compute the minimum unsigned root of the equation:
8735   // I * (B / D) mod (N / D)
8736   // To simplify the computation, we factor out the divide by D:
8737   // (I * B mod N) / D
8738   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8739   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8740 }
8741 
8742 /// For a given quadratic addrec, generate coefficients of the corresponding
8743 /// quadratic equation, multiplied by a common value to ensure that they are
8744 /// integers.
8745 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
8746 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
8747 /// were multiplied by, and BitWidth is the bit width of the original addrec
8748 /// coefficients.
8749 /// This function returns None if the addrec coefficients are not compile-
8750 /// time constants.
8751 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
GetQuadraticEquation(const SCEVAddRecExpr * AddRec)8752 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
8753   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
8754   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
8755   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
8756   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
8757   LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
8758                     << *AddRec << '\n');
8759 
8760   // We currently can only solve this if the coefficients are constants.
8761   if (!LC || !MC || !NC) {
8762     LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
8763     return None;
8764   }
8765 
8766   APInt L = LC->getAPInt();
8767   APInt M = MC->getAPInt();
8768   APInt N = NC->getAPInt();
8769   assert(!N.isNullValue() && "This is not a quadratic addrec");
8770 
8771   unsigned BitWidth = LC->getAPInt().getBitWidth();
8772   unsigned NewWidth = BitWidth + 1;
8773   LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
8774                     << BitWidth << '\n');
8775   // The sign-extension (as opposed to a zero-extension) here matches the
8776   // extension used in SolveQuadraticEquationWrap (with the same motivation).
8777   N = N.sext(NewWidth);
8778   M = M.sext(NewWidth);
8779   L = L.sext(NewWidth);
8780 
8781   // The increments are M, M+N, M+2N, ..., so the accumulated values are
8782   //   L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
8783   //   L+M, L+2M+N, L+3M+3N, ...
8784   // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
8785   //
8786   // The equation Acc = 0 is then
8787   //   L + nM + n(n-1)/2 N = 0,  or  2L + 2M n + n(n-1) N = 0.
8788   // In a quadratic form it becomes:
8789   //   N n^2 + (2M-N) n + 2L = 0.
8790 
8791   APInt A = N;
8792   APInt B = 2 * M - A;
8793   APInt C = 2 * L;
8794   APInt T = APInt(NewWidth, 2);
8795   LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
8796                     << "x + " << C << ", coeff bw: " << NewWidth
8797                     << ", multiplied by " << T << '\n');
8798   return std::make_tuple(A, B, C, T, BitWidth);
8799 }
8800 
8801 /// Helper function to compare optional APInts:
8802 /// (a) if X and Y both exist, return min(X, Y),
8803 /// (b) if neither X nor Y exist, return None,
8804 /// (c) if exactly one of X and Y exists, return that value.
MinOptional(Optional<APInt> X,Optional<APInt> Y)8805 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
8806   if (X.hasValue() && Y.hasValue()) {
8807     unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
8808     APInt XW = X->sextOrSelf(W);
8809     APInt YW = Y->sextOrSelf(W);
8810     return XW.slt(YW) ? *X : *Y;
8811   }
8812   if (!X.hasValue() && !Y.hasValue())
8813     return None;
8814   return X.hasValue() ? *X : *Y;
8815 }
8816 
8817 /// Helper function to truncate an optional APInt to a given BitWidth.
8818 /// When solving addrec-related equations, it is preferable to return a value
8819 /// that has the same bit width as the original addrec's coefficients. If the
8820 /// solution fits in the original bit width, truncate it (except for i1).
8821 /// Returning a value of a different bit width may inhibit some optimizations.
8822 ///
8823 /// In general, a solution to a quadratic equation generated from an addrec
8824 /// may require BW+1 bits, where BW is the bit width of the addrec's
8825 /// coefficients. The reason is that the coefficients of the quadratic
8826 /// equation are BW+1 bits wide (to avoid truncation when converting from
8827 /// the addrec to the equation).
TruncIfPossible(Optional<APInt> X,unsigned BitWidth)8828 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
8829   if (!X.hasValue())
8830     return None;
8831   unsigned W = X->getBitWidth();
8832   if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
8833     return X->trunc(BitWidth);
8834   return X;
8835 }
8836 
8837 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
8838 /// iterations. The values L, M, N are assumed to be signed, and they
8839 /// should all have the same bit widths.
8840 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
8841 /// where BW is the bit width of the addrec's coefficients.
8842 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
8843 /// returned as such, otherwise the bit width of the returned value may
8844 /// be greater than BW.
8845 ///
8846 /// This function returns None if
8847 /// (a) the addrec coefficients are not constant, or
8848 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
8849 ///     like x^2 = 5, no integer solutions exist, in other cases an integer
8850 ///     solution may exist, but SolveQuadraticEquationWrap may fail to find it.
8851 static Optional<APInt>
SolveQuadraticAddRecExact(const SCEVAddRecExpr * AddRec,ScalarEvolution & SE)8852 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
8853   APInt A, B, C, M;
8854   unsigned BitWidth;
8855   auto T = GetQuadraticEquation(AddRec);
8856   if (!T.hasValue())
8857     return None;
8858 
8859   std::tie(A, B, C, M, BitWidth) = *T;
8860   LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
8861   Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
8862   if (!X.hasValue())
8863     return None;
8864 
8865   ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
8866   ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
8867   if (!V->isZero())
8868     return None;
8869 
8870   return TruncIfPossible(X, BitWidth);
8871 }
8872 
8873 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
8874 /// iterations. The values M, N are assumed to be signed, and they
8875 /// should all have the same bit widths.
8876 /// Find the least n such that c(n) does not belong to the given range,
8877 /// while c(n-1) does.
8878 ///
8879 /// This function returns None if
8880 /// (a) the addrec coefficients are not constant, or
8881 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
8882 ///     bounds of the range.
8883 static Optional<APInt>
SolveQuadraticAddRecRange(const SCEVAddRecExpr * AddRec,const ConstantRange & Range,ScalarEvolution & SE)8884 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
8885                           const ConstantRange &Range, ScalarEvolution &SE) {
8886   assert(AddRec->getOperand(0)->isZero() &&
8887          "Starting value of addrec should be 0");
8888   LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
8889                     << Range << ", addrec " << *AddRec << '\n');
8890   // This case is handled in getNumIterationsInRange. Here we can assume that
8891   // we start in the range.
8892   assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
8893          "Addrec's initial value should be in range");
8894 
8895   APInt A, B, C, M;
8896   unsigned BitWidth;
8897   auto T = GetQuadraticEquation(AddRec);
8898   if (!T.hasValue())
8899     return None;
8900 
8901   // Be careful about the return value: there can be two reasons for not
8902   // returning an actual number. First, if no solutions to the equations
8903   // were found, and second, if the solutions don't leave the given range.
8904   // The first case means that the actual solution is "unknown", the second
8905   // means that it's known, but not valid. If the solution is unknown, we
8906   // cannot make any conclusions.
8907   // Return a pair: the optional solution and a flag indicating if the
8908   // solution was found.
8909   auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
8910     // Solve for signed overflow and unsigned overflow, pick the lower
8911     // solution.
8912     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
8913                       << Bound << " (before multiplying by " << M << ")\n");
8914     Bound *= M; // The quadratic equation multiplier.
8915 
8916     Optional<APInt> SO = None;
8917     if (BitWidth > 1) {
8918       LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8919                            "signed overflow\n");
8920       SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
8921     }
8922     LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8923                          "unsigned overflow\n");
8924     Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
8925                                                               BitWidth+1);
8926 
8927     auto LeavesRange = [&] (const APInt &X) {
8928       ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
8929       ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
8930       if (Range.contains(V0->getValue()))
8931         return false;
8932       // X should be at least 1, so X-1 is non-negative.
8933       ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
8934       ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
8935       if (Range.contains(V1->getValue()))
8936         return true;
8937       return false;
8938     };
8939 
8940     // If SolveQuadraticEquationWrap returns None, it means that there can
8941     // be a solution, but the function failed to find it. We cannot treat it
8942     // as "no solution".
8943     if (!SO.hasValue() || !UO.hasValue())
8944       return { None, false };
8945 
8946     // Check the smaller value first to see if it leaves the range.
8947     // At this point, both SO and UO must have values.
8948     Optional<APInt> Min = MinOptional(SO, UO);
8949     if (LeavesRange(*Min))
8950       return { Min, true };
8951     Optional<APInt> Max = Min == SO ? UO : SO;
8952     if (LeavesRange(*Max))
8953       return { Max, true };
8954 
8955     // Solutions were found, but were eliminated, hence the "true".
8956     return { None, true };
8957   };
8958 
8959   std::tie(A, B, C, M, BitWidth) = *T;
8960   // Lower bound is inclusive, subtract 1 to represent the exiting value.
8961   APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
8962   APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
8963   auto SL = SolveForBoundary(Lower);
8964   auto SU = SolveForBoundary(Upper);
8965   // If any of the solutions was unknown, no meaninigful conclusions can
8966   // be made.
8967   if (!SL.second || !SU.second)
8968     return None;
8969 
8970   // Claim: The correct solution is not some value between Min and Max.
8971   //
8972   // Justification: Assuming that Min and Max are different values, one of
8973   // them is when the first signed overflow happens, the other is when the
8974   // first unsigned overflow happens. Crossing the range boundary is only
8975   // possible via an overflow (treating 0 as a special case of it, modeling
8976   // an overflow as crossing k*2^W for some k).
8977   //
8978   // The interesting case here is when Min was eliminated as an invalid
8979   // solution, but Max was not. The argument is that if there was another
8980   // overflow between Min and Max, it would also have been eliminated if
8981   // it was considered.
8982   //
8983   // For a given boundary, it is possible to have two overflows of the same
8984   // type (signed/unsigned) without having the other type in between: this
8985   // can happen when the vertex of the parabola is between the iterations
8986   // corresponding to the overflows. This is only possible when the two
8987   // overflows cross k*2^W for the same k. In such case, if the second one
8988   // left the range (and was the first one to do so), the first overflow
8989   // would have to enter the range, which would mean that either we had left
8990   // the range before or that we started outside of it. Both of these cases
8991   // are contradictions.
8992   //
8993   // Claim: In the case where SolveForBoundary returns None, the correct
8994   // solution is not some value between the Max for this boundary and the
8995   // Min of the other boundary.
8996   //
8997   // Justification: Assume that we had such Max_A and Min_B corresponding
8998   // to range boundaries A and B and such that Max_A < Min_B. If there was
8999   // a solution between Max_A and Min_B, it would have to be caused by an
9000   // overflow corresponding to either A or B. It cannot correspond to B,
9001   // since Min_B is the first occurrence of such an overflow. If it
9002   // corresponded to A, it would have to be either a signed or an unsigned
9003   // overflow that is larger than both eliminated overflows for A. But
9004   // between the eliminated overflows and this overflow, the values would
9005   // cover the entire value space, thus crossing the other boundary, which
9006   // is a contradiction.
9007 
9008   return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
9009 }
9010 
9011 ScalarEvolution::ExitLimit
howFarToZero(const SCEV * V,const Loop * L,bool ControlsExit,bool AllowPredicates)9012 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
9013                               bool AllowPredicates) {
9014 
9015   // This is only used for loops with a "x != y" exit test. The exit condition
9016   // is now expressed as a single expression, V = x-y. So the exit test is
9017   // effectively V != 0.  We know and take advantage of the fact that this
9018   // expression only being used in a comparison by zero context.
9019 
9020   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9021   // If the value is a constant
9022   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9023     // If the value is already zero, the branch will execute zero times.
9024     if (C->getValue()->isZero()) return C;
9025     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9026   }
9027 
9028   const SCEVAddRecExpr *AddRec =
9029       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
9030 
9031   if (!AddRec && AllowPredicates)
9032     // Try to make this an AddRec using runtime tests, in the first X
9033     // iterations of this loop, where X is the SCEV expression found by the
9034     // algorithm below.
9035     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
9036 
9037   if (!AddRec || AddRec->getLoop() != L)
9038     return getCouldNotCompute();
9039 
9040   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
9041   // the quadratic equation to solve it.
9042   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
9043     // We can only use this value if the chrec ends up with an exact zero
9044     // value at this index.  When solving for "X*X != 5", for example, we
9045     // should not accept a root of 2.
9046     if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
9047       const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
9048       return ExitLimit(R, R, false, Predicates);
9049     }
9050     return getCouldNotCompute();
9051   }
9052 
9053   // Otherwise we can only handle this if it is affine.
9054   if (!AddRec->isAffine())
9055     return getCouldNotCompute();
9056 
9057   // If this is an affine expression, the execution count of this branch is
9058   // the minimum unsigned root of the following equation:
9059   //
9060   //     Start + Step*N = 0 (mod 2^BW)
9061   //
9062   // equivalent to:
9063   //
9064   //             Step*N = -Start (mod 2^BW)
9065   //
9066   // where BW is the common bit width of Start and Step.
9067 
9068   // Get the initial value for the loop.
9069   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
9070   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
9071 
9072   // For now we handle only constant steps.
9073   //
9074   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
9075   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
9076   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
9077   // We have not yet seen any such cases.
9078   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
9079   if (!StepC || StepC->getValue()->isZero())
9080     return getCouldNotCompute();
9081 
9082   // For positive steps (counting up until unsigned overflow):
9083   //   N = -Start/Step (as unsigned)
9084   // For negative steps (counting down to zero):
9085   //   N = Start/-Step
9086   // First compute the unsigned distance from zero in the direction of Step.
9087   bool CountDown = StepC->getAPInt().isNegative();
9088   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
9089 
9090   // Handle unitary steps, which cannot wraparound.
9091   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
9092   //   N = Distance (as unsigned)
9093   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
9094     APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
9095     APInt MaxBECountBase = getUnsignedRangeMax(Distance);
9096     if (MaxBECountBase.ult(MaxBECount))
9097       MaxBECount = MaxBECountBase;
9098 
9099     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
9100     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
9101     // case, and see if we can improve the bound.
9102     //
9103     // Explicitly handling this here is necessary because getUnsignedRange
9104     // isn't context-sensitive; it doesn't know that we only care about the
9105     // range inside the loop.
9106     const SCEV *Zero = getZero(Distance->getType());
9107     const SCEV *One = getOne(Distance->getType());
9108     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
9109     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
9110       // If Distance + 1 doesn't overflow, we can compute the maximum distance
9111       // as "unsigned_max(Distance + 1) - 1".
9112       ConstantRange CR = getUnsignedRange(DistancePlusOne);
9113       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
9114     }
9115     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
9116   }
9117 
9118   // If the condition controls loop exit (the loop exits only if the expression
9119   // is true) and the addition is no-wrap we can use unsigned divide to
9120   // compute the backedge count.  In this case, the step may not divide the
9121   // distance, but we don't care because if the condition is "missed" the loop
9122   // will have undefined behavior due to wrapping.
9123   if (ControlsExit && AddRec->hasNoSelfWrap() &&
9124       loopHasNoAbnormalExits(AddRec->getLoop())) {
9125     const SCEV *Exact =
9126         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
9127     const SCEV *Max =
9128         Exact == getCouldNotCompute()
9129             ? Exact
9130             : getConstant(getUnsignedRangeMax(Exact));
9131     return ExitLimit(Exact, Max, false, Predicates);
9132   }
9133 
9134   // Solve the general equation.
9135   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
9136                                                getNegativeSCEV(Start), *this);
9137   const SCEV *M = E == getCouldNotCompute()
9138                       ? E
9139                       : getConstant(getUnsignedRangeMax(E));
9140   return ExitLimit(E, M, false, Predicates);
9141 }
9142 
9143 ScalarEvolution::ExitLimit
howFarToNonZero(const SCEV * V,const Loop * L)9144 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
9145   // Loops that look like: while (X == 0) are very strange indeed.  We don't
9146   // handle them yet except for the trivial case.  This could be expanded in the
9147   // future as needed.
9148 
9149   // If the value is a constant, check to see if it is known to be non-zero
9150   // already.  If so, the backedge will execute zero times.
9151   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9152     if (!C->getValue()->isZero())
9153       return getZero(C->getType());
9154     return getCouldNotCompute();  // Otherwise it will loop infinitely.
9155   }
9156 
9157   // We could implement others, but I really doubt anyone writes loops like
9158   // this, and if they did, they would already be constant folded.
9159   return getCouldNotCompute();
9160 }
9161 
9162 std::pair<const BasicBlock *, const BasicBlock *>
getPredecessorWithUniqueSuccessorForBB(const BasicBlock * BB) const9163 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
9164     const {
9165   // If the block has a unique predecessor, then there is no path from the
9166   // predecessor to the block that does not go through the direct edge
9167   // from the predecessor to the block.
9168   if (const BasicBlock *Pred = BB->getSinglePredecessor())
9169     return {Pred, BB};
9170 
9171   // A loop's header is defined to be a block that dominates the loop.
9172   // If the header has a unique predecessor outside the loop, it must be
9173   // a block that has exactly one successor that can reach the loop.
9174   if (const Loop *L = LI.getLoopFor(BB))
9175     return {L->getLoopPredecessor(), L->getHeader()};
9176 
9177   return {nullptr, nullptr};
9178 }
9179 
9180 /// SCEV structural equivalence is usually sufficient for testing whether two
9181 /// expressions are equal, however for the purposes of looking for a condition
9182 /// guarding a loop, it can be useful to be a little more general, since a
9183 /// front-end may have replicated the controlling expression.
HasSameValue(const SCEV * A,const SCEV * B)9184 static bool HasSameValue(const SCEV *A, const SCEV *B) {
9185   // Quick check to see if they are the same SCEV.
9186   if (A == B) return true;
9187 
9188   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
9189     // Not all instructions that are "identical" compute the same value.  For
9190     // instance, two distinct alloca instructions allocating the same type are
9191     // identical and do not read memory; but compute distinct values.
9192     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
9193   };
9194 
9195   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
9196   // two different instructions with the same value. Check for this case.
9197   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
9198     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
9199       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
9200         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
9201           if (ComputesEqualValues(AI, BI))
9202             return true;
9203 
9204   // Otherwise assume they may have a different value.
9205   return false;
9206 }
9207 
SimplifyICmpOperands(ICmpInst::Predicate & Pred,const SCEV * & LHS,const SCEV * & RHS,unsigned Depth)9208 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
9209                                            const SCEV *&LHS, const SCEV *&RHS,
9210                                            unsigned Depth) {
9211   bool Changed = false;
9212   // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
9213   // '0 != 0'.
9214   auto TrivialCase = [&](bool TriviallyTrue) {
9215     LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
9216     Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
9217     return true;
9218   };
9219   // If we hit the max recursion limit bail out.
9220   if (Depth >= 3)
9221     return false;
9222 
9223   // Canonicalize a constant to the right side.
9224   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
9225     // Check for both operands constant.
9226     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
9227       if (ConstantExpr::getICmp(Pred,
9228                                 LHSC->getValue(),
9229                                 RHSC->getValue())->isNullValue())
9230         return TrivialCase(false);
9231       else
9232         return TrivialCase(true);
9233     }
9234     // Otherwise swap the operands to put the constant on the right.
9235     std::swap(LHS, RHS);
9236     Pred = ICmpInst::getSwappedPredicate(Pred);
9237     Changed = true;
9238   }
9239 
9240   // If we're comparing an addrec with a value which is loop-invariant in the
9241   // addrec's loop, put the addrec on the left. Also make a dominance check,
9242   // as both operands could be addrecs loop-invariant in each other's loop.
9243   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
9244     const Loop *L = AR->getLoop();
9245     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
9246       std::swap(LHS, RHS);
9247       Pred = ICmpInst::getSwappedPredicate(Pred);
9248       Changed = true;
9249     }
9250   }
9251 
9252   // If there's a constant operand, canonicalize comparisons with boundary
9253   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
9254   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
9255     const APInt &RA = RC->getAPInt();
9256 
9257     bool SimplifiedByConstantRange = false;
9258 
9259     if (!ICmpInst::isEquality(Pred)) {
9260       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
9261       if (ExactCR.isFullSet())
9262         return TrivialCase(true);
9263       else if (ExactCR.isEmptySet())
9264         return TrivialCase(false);
9265 
9266       APInt NewRHS;
9267       CmpInst::Predicate NewPred;
9268       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
9269           ICmpInst::isEquality(NewPred)) {
9270         // We were able to convert an inequality to an equality.
9271         Pred = NewPred;
9272         RHS = getConstant(NewRHS);
9273         Changed = SimplifiedByConstantRange = true;
9274       }
9275     }
9276 
9277     if (!SimplifiedByConstantRange) {
9278       switch (Pred) {
9279       default:
9280         break;
9281       case ICmpInst::ICMP_EQ:
9282       case ICmpInst::ICMP_NE:
9283         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
9284         if (!RA)
9285           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
9286             if (const SCEVMulExpr *ME =
9287                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
9288               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
9289                   ME->getOperand(0)->isAllOnesValue()) {
9290                 RHS = AE->getOperand(1);
9291                 LHS = ME->getOperand(1);
9292                 Changed = true;
9293               }
9294         break;
9295 
9296 
9297         // The "Should have been caught earlier!" messages refer to the fact
9298         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
9299         // should have fired on the corresponding cases, and canonicalized the
9300         // check to trivial case.
9301 
9302       case ICmpInst::ICMP_UGE:
9303         assert(!RA.isMinValue() && "Should have been caught earlier!");
9304         Pred = ICmpInst::ICMP_UGT;
9305         RHS = getConstant(RA - 1);
9306         Changed = true;
9307         break;
9308       case ICmpInst::ICMP_ULE:
9309         assert(!RA.isMaxValue() && "Should have been caught earlier!");
9310         Pred = ICmpInst::ICMP_ULT;
9311         RHS = getConstant(RA + 1);
9312         Changed = true;
9313         break;
9314       case ICmpInst::ICMP_SGE:
9315         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
9316         Pred = ICmpInst::ICMP_SGT;
9317         RHS = getConstant(RA - 1);
9318         Changed = true;
9319         break;
9320       case ICmpInst::ICMP_SLE:
9321         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
9322         Pred = ICmpInst::ICMP_SLT;
9323         RHS = getConstant(RA + 1);
9324         Changed = true;
9325         break;
9326       }
9327     }
9328   }
9329 
9330   // Check for obvious equality.
9331   if (HasSameValue(LHS, RHS)) {
9332     if (ICmpInst::isTrueWhenEqual(Pred))
9333       return TrivialCase(true);
9334     if (ICmpInst::isFalseWhenEqual(Pred))
9335       return TrivialCase(false);
9336   }
9337 
9338   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
9339   // adding or subtracting 1 from one of the operands.
9340   switch (Pred) {
9341   case ICmpInst::ICMP_SLE:
9342     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
9343       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9344                        SCEV::FlagNSW);
9345       Pred = ICmpInst::ICMP_SLT;
9346       Changed = true;
9347     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
9348       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
9349                        SCEV::FlagNSW);
9350       Pred = ICmpInst::ICMP_SLT;
9351       Changed = true;
9352     }
9353     break;
9354   case ICmpInst::ICMP_SGE:
9355     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
9356       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
9357                        SCEV::FlagNSW);
9358       Pred = ICmpInst::ICMP_SGT;
9359       Changed = true;
9360     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
9361       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9362                        SCEV::FlagNSW);
9363       Pred = ICmpInst::ICMP_SGT;
9364       Changed = true;
9365     }
9366     break;
9367   case ICmpInst::ICMP_ULE:
9368     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
9369       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9370                        SCEV::FlagNUW);
9371       Pred = ICmpInst::ICMP_ULT;
9372       Changed = true;
9373     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
9374       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
9375       Pred = ICmpInst::ICMP_ULT;
9376       Changed = true;
9377     }
9378     break;
9379   case ICmpInst::ICMP_UGE:
9380     if (!getUnsignedRangeMin(RHS).isMinValue()) {
9381       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
9382       Pred = ICmpInst::ICMP_UGT;
9383       Changed = true;
9384     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
9385       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9386                        SCEV::FlagNUW);
9387       Pred = ICmpInst::ICMP_UGT;
9388       Changed = true;
9389     }
9390     break;
9391   default:
9392     break;
9393   }
9394 
9395   // TODO: More simplifications are possible here.
9396 
9397   // Recursively simplify until we either hit a recursion limit or nothing
9398   // changes.
9399   if (Changed)
9400     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
9401 
9402   return Changed;
9403 }
9404 
isKnownNegative(const SCEV * S)9405 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
9406   return getSignedRangeMax(S).isNegative();
9407 }
9408 
isKnownPositive(const SCEV * S)9409 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
9410   return getSignedRangeMin(S).isStrictlyPositive();
9411 }
9412 
isKnownNonNegative(const SCEV * S)9413 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
9414   return !getSignedRangeMin(S).isNegative();
9415 }
9416 
isKnownNonPositive(const SCEV * S)9417 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
9418   return !getSignedRangeMax(S).isStrictlyPositive();
9419 }
9420 
isKnownNonZero(const SCEV * S)9421 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
9422   return isKnownNegative(S) || isKnownPositive(S);
9423 }
9424 
9425 std::pair<const SCEV *, const SCEV *>
SplitIntoInitAndPostInc(const Loop * L,const SCEV * S)9426 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
9427   // Compute SCEV on entry of loop L.
9428   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
9429   if (Start == getCouldNotCompute())
9430     return { Start, Start };
9431   // Compute post increment SCEV for loop L.
9432   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
9433   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
9434   return { Start, PostInc };
9435 }
9436 
isKnownViaInduction(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)9437 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
9438                                           const SCEV *LHS, const SCEV *RHS) {
9439   // First collect all loops.
9440   SmallPtrSet<const Loop *, 8> LoopsUsed;
9441   getUsedLoops(LHS, LoopsUsed);
9442   getUsedLoops(RHS, LoopsUsed);
9443 
9444   if (LoopsUsed.empty())
9445     return false;
9446 
9447   // Domination relationship must be a linear order on collected loops.
9448 #ifndef NDEBUG
9449   for (auto *L1 : LoopsUsed)
9450     for (auto *L2 : LoopsUsed)
9451       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
9452               DT.dominates(L2->getHeader(), L1->getHeader())) &&
9453              "Domination relationship is not a linear order");
9454 #endif
9455 
9456   const Loop *MDL =
9457       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
9458                         [&](const Loop *L1, const Loop *L2) {
9459          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
9460        });
9461 
9462   // Get init and post increment value for LHS.
9463   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
9464   // if LHS contains unknown non-invariant SCEV then bail out.
9465   if (SplitLHS.first == getCouldNotCompute())
9466     return false;
9467   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
9468   // Get init and post increment value for RHS.
9469   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
9470   // if RHS contains unknown non-invariant SCEV then bail out.
9471   if (SplitRHS.first == getCouldNotCompute())
9472     return false;
9473   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
9474   // It is possible that init SCEV contains an invariant load but it does
9475   // not dominate MDL and is not available at MDL loop entry, so we should
9476   // check it here.
9477   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
9478       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
9479     return false;
9480 
9481   // It seems backedge guard check is faster than entry one so in some cases
9482   // it can speed up whole estimation by short circuit
9483   return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
9484                                      SplitRHS.second) &&
9485          isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
9486 }
9487 
isKnownPredicate(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)9488 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
9489                                        const SCEV *LHS, const SCEV *RHS) {
9490   // Canonicalize the inputs first.
9491   (void)SimplifyICmpOperands(Pred, LHS, RHS);
9492 
9493   if (isKnownViaInduction(Pred, LHS, RHS))
9494     return true;
9495 
9496   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
9497     return true;
9498 
9499   // Otherwise see what can be done with some simple reasoning.
9500   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
9501 }
9502 
isKnownPredicateAt(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const Instruction * Context)9503 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
9504                                          const SCEV *LHS, const SCEV *RHS,
9505                                          const Instruction *Context) {
9506   // TODO: Analyze guards and assumes from Context's block.
9507   return isKnownPredicate(Pred, LHS, RHS) ||
9508          isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS);
9509 }
9510 
isKnownOnEveryIteration(ICmpInst::Predicate Pred,const SCEVAddRecExpr * LHS,const SCEV * RHS)9511 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
9512                                               const SCEVAddRecExpr *LHS,
9513                                               const SCEV *RHS) {
9514   const Loop *L = LHS->getLoop();
9515   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
9516          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
9517 }
9518 
9519 Optional<ScalarEvolution::MonotonicPredicateType>
getMonotonicPredicateType(const SCEVAddRecExpr * LHS,ICmpInst::Predicate Pred)9520 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
9521                                            ICmpInst::Predicate Pred) {
9522   auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
9523 
9524 #ifndef NDEBUG
9525   // Verify an invariant: inverting the predicate should turn a monotonically
9526   // increasing change to a monotonically decreasing one, and vice versa.
9527   if (Result) {
9528     auto ResultSwapped =
9529         getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
9530 
9531     assert(ResultSwapped.hasValue() && "should be able to analyze both!");
9532     assert(ResultSwapped.getValue() != Result.getValue() &&
9533            "monotonicity should flip as we flip the predicate");
9534   }
9535 #endif
9536 
9537   return Result;
9538 }
9539 
9540 Optional<ScalarEvolution::MonotonicPredicateType>
getMonotonicPredicateTypeImpl(const SCEVAddRecExpr * LHS,ICmpInst::Predicate Pred)9541 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
9542                                                ICmpInst::Predicate Pred) {
9543   // A zero step value for LHS means the induction variable is essentially a
9544   // loop invariant value. We don't really depend on the predicate actually
9545   // flipping from false to true (for increasing predicates, and the other way
9546   // around for decreasing predicates), all we care about is that *if* the
9547   // predicate changes then it only changes from false to true.
9548   //
9549   // A zero step value in itself is not very useful, but there may be places
9550   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
9551   // as general as possible.
9552 
9553   // Only handle LE/LT/GE/GT predicates.
9554   if (!ICmpInst::isRelational(Pred))
9555     return None;
9556 
9557   bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
9558   assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
9559          "Should be greater or less!");
9560 
9561   // Check that AR does not wrap.
9562   if (ICmpInst::isUnsigned(Pred)) {
9563     if (!LHS->hasNoUnsignedWrap())
9564       return None;
9565     return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9566   } else {
9567     assert(ICmpInst::isSigned(Pred) &&
9568            "Relational predicate is either signed or unsigned!");
9569     if (!LHS->hasNoSignedWrap())
9570       return None;
9571 
9572     const SCEV *Step = LHS->getStepRecurrence(*this);
9573 
9574     if (isKnownNonNegative(Step))
9575       return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9576 
9577     if (isKnownNonPositive(Step))
9578       return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9579 
9580     return None;
9581   }
9582 }
9583 
9584 Optional<ScalarEvolution::LoopInvariantPredicate>
getLoopInvariantPredicate(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const Loop * L)9585 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
9586                                            const SCEV *LHS, const SCEV *RHS,
9587                                            const Loop *L) {
9588 
9589   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9590   if (!isLoopInvariant(RHS, L)) {
9591     if (!isLoopInvariant(LHS, L))
9592       return None;
9593 
9594     std::swap(LHS, RHS);
9595     Pred = ICmpInst::getSwappedPredicate(Pred);
9596   }
9597 
9598   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9599   if (!ArLHS || ArLHS->getLoop() != L)
9600     return None;
9601 
9602   auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
9603   if (!MonotonicType)
9604     return None;
9605   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
9606   // true as the loop iterates, and the backedge is control dependent on
9607   // "ArLHS `Pred` RHS" == true then we can reason as follows:
9608   //
9609   //   * if the predicate was false in the first iteration then the predicate
9610   //     is never evaluated again, since the loop exits without taking the
9611   //     backedge.
9612   //   * if the predicate was true in the first iteration then it will
9613   //     continue to be true for all future iterations since it is
9614   //     monotonically increasing.
9615   //
9616   // For both the above possibilities, we can replace the loop varying
9617   // predicate with its value on the first iteration of the loop (which is
9618   // loop invariant).
9619   //
9620   // A similar reasoning applies for a monotonically decreasing predicate, by
9621   // replacing true with false and false with true in the above two bullets.
9622   bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
9623   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
9624 
9625   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
9626     return None;
9627 
9628   return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS);
9629 }
9630 
9631 Optional<ScalarEvolution::LoopInvariantPredicate>
getLoopInvariantExitCondDuringFirstIterations(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const Loop * L,const Instruction * Context,const SCEV * MaxIter)9632 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
9633     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
9634     const Instruction *Context, const SCEV *MaxIter) {
9635   // Try to prove the following set of facts:
9636   // - The predicate is monotonic in the iteration space.
9637   // - If the check does not fail on the 1st iteration:
9638   //   - No overflow will happen during first MaxIter iterations;
9639   //   - It will not fail on the MaxIter'th iteration.
9640   // If the check does fail on the 1st iteration, we leave the loop and no
9641   // other checks matter.
9642 
9643   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9644   if (!isLoopInvariant(RHS, L)) {
9645     if (!isLoopInvariant(LHS, L))
9646       return None;
9647 
9648     std::swap(LHS, RHS);
9649     Pred = ICmpInst::getSwappedPredicate(Pred);
9650   }
9651 
9652   auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9653   if (!AR || AR->getLoop() != L)
9654     return None;
9655 
9656   // The predicate must be relational (i.e. <, <=, >=, >).
9657   if (!ICmpInst::isRelational(Pred))
9658     return None;
9659 
9660   // TODO: Support steps other than +/- 1.
9661   const SCEV *Step = AR->getStepRecurrence(*this);
9662   auto *One = getOne(Step->getType());
9663   auto *MinusOne = getNegativeSCEV(One);
9664   if (Step != One && Step != MinusOne)
9665     return None;
9666 
9667   // Type mismatch here means that MaxIter is potentially larger than max
9668   // unsigned value in start type, which mean we cannot prove no wrap for the
9669   // indvar.
9670   if (AR->getType() != MaxIter->getType())
9671     return None;
9672 
9673   // Value of IV on suggested last iteration.
9674   const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
9675   // Does it still meet the requirement?
9676   if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
9677     return None;
9678   // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
9679   // not exceed max unsigned value of this type), this effectively proves
9680   // that there is no wrap during the iteration. To prove that there is no
9681   // signed/unsigned wrap, we need to check that
9682   // Start <= Last for step = 1 or Start >= Last for step = -1.
9683   ICmpInst::Predicate NoOverflowPred =
9684       CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
9685   if (Step == MinusOne)
9686     NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
9687   const SCEV *Start = AR->getStart();
9688   if (!isKnownPredicateAt(NoOverflowPred, Start, Last, Context))
9689     return None;
9690 
9691   // Everything is fine.
9692   return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
9693 }
9694 
isKnownPredicateViaConstantRanges(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)9695 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
9696     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
9697   if (HasSameValue(LHS, RHS))
9698     return ICmpInst::isTrueWhenEqual(Pred);
9699 
9700   // This code is split out from isKnownPredicate because it is called from
9701   // within isLoopEntryGuardedByCond.
9702 
9703   auto CheckRanges =
9704       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
9705     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
9706         .contains(RangeLHS);
9707   };
9708 
9709   // The check at the top of the function catches the case where the values are
9710   // known to be equal.
9711   if (Pred == CmpInst::ICMP_EQ)
9712     return false;
9713 
9714   if (Pred == CmpInst::ICMP_NE)
9715     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
9716            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
9717            isKnownNonZero(getMinusSCEV(LHS, RHS));
9718 
9719   if (CmpInst::isSigned(Pred))
9720     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
9721 
9722   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
9723 }
9724 
isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)9725 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
9726                                                     const SCEV *LHS,
9727                                                     const SCEV *RHS) {
9728   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
9729   // Return Y via OutY.
9730   auto MatchBinaryAddToConst =
9731       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
9732              SCEV::NoWrapFlags ExpectedFlags) {
9733     const SCEV *NonConstOp, *ConstOp;
9734     SCEV::NoWrapFlags FlagsPresent;
9735 
9736     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
9737         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
9738       return false;
9739 
9740     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
9741     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
9742   };
9743 
9744   APInt C;
9745 
9746   switch (Pred) {
9747   default:
9748     break;
9749 
9750   case ICmpInst::ICMP_SGE:
9751     std::swap(LHS, RHS);
9752     LLVM_FALLTHROUGH;
9753   case ICmpInst::ICMP_SLE:
9754     // X s<= (X + C)<nsw> if C >= 0
9755     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
9756       return true;
9757 
9758     // (X + C)<nsw> s<= X if C <= 0
9759     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
9760         !C.isStrictlyPositive())
9761       return true;
9762     break;
9763 
9764   case ICmpInst::ICMP_SGT:
9765     std::swap(LHS, RHS);
9766     LLVM_FALLTHROUGH;
9767   case ICmpInst::ICMP_SLT:
9768     // X s< (X + C)<nsw> if C > 0
9769     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
9770         C.isStrictlyPositive())
9771       return true;
9772 
9773     // (X + C)<nsw> s< X if C < 0
9774     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
9775       return true;
9776     break;
9777 
9778   case ICmpInst::ICMP_UGE:
9779     std::swap(LHS, RHS);
9780     LLVM_FALLTHROUGH;
9781   case ICmpInst::ICMP_ULE:
9782     // X u<= (X + C)<nuw> for any C
9783     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW))
9784       return true;
9785     break;
9786 
9787   case ICmpInst::ICMP_UGT:
9788     std::swap(LHS, RHS);
9789     LLVM_FALLTHROUGH;
9790   case ICmpInst::ICMP_ULT:
9791     // X u< (X + C)<nuw> if C != 0
9792     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW) && !C.isNullValue())
9793       return true;
9794     break;
9795   }
9796 
9797   return false;
9798 }
9799 
isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)9800 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
9801                                                    const SCEV *LHS,
9802                                                    const SCEV *RHS) {
9803   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
9804     return false;
9805 
9806   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
9807   // the stack can result in exponential time complexity.
9808   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
9809 
9810   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
9811   //
9812   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
9813   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
9814   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
9815   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
9816   // use isKnownPredicate later if needed.
9817   return isKnownNonNegative(RHS) &&
9818          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
9819          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
9820 }
9821 
isImpliedViaGuard(const BasicBlock * BB,ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)9822 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
9823                                         ICmpInst::Predicate Pred,
9824                                         const SCEV *LHS, const SCEV *RHS) {
9825   // No need to even try if we know the module has no guards.
9826   if (!HasGuards)
9827     return false;
9828 
9829   return any_of(*BB, [&](const Instruction &I) {
9830     using namespace llvm::PatternMatch;
9831 
9832     Value *Condition;
9833     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
9834                          m_Value(Condition))) &&
9835            isImpliedCond(Pred, LHS, RHS, Condition, false);
9836   });
9837 }
9838 
9839 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
9840 /// protected by a conditional between LHS and RHS.  This is used to
9841 /// to eliminate casts.
9842 bool
isLoopBackedgeGuardedByCond(const Loop * L,ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)9843 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
9844                                              ICmpInst::Predicate Pred,
9845                                              const SCEV *LHS, const SCEV *RHS) {
9846   // Interpret a null as meaning no loop, where there is obviously no guard
9847   // (interprocedural conditions notwithstanding).
9848   if (!L) return true;
9849 
9850   if (VerifyIR)
9851     assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
9852            "This cannot be done on broken IR!");
9853 
9854 
9855   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9856     return true;
9857 
9858   BasicBlock *Latch = L->getLoopLatch();
9859   if (!Latch)
9860     return false;
9861 
9862   BranchInst *LoopContinuePredicate =
9863     dyn_cast<BranchInst>(Latch->getTerminator());
9864   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
9865       isImpliedCond(Pred, LHS, RHS,
9866                     LoopContinuePredicate->getCondition(),
9867                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
9868     return true;
9869 
9870   // We don't want more than one activation of the following loops on the stack
9871   // -- that can lead to O(n!) time complexity.
9872   if (WalkingBEDominatingConds)
9873     return false;
9874 
9875   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
9876 
9877   // See if we can exploit a trip count to prove the predicate.
9878   const auto &BETakenInfo = getBackedgeTakenInfo(L);
9879   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
9880   if (LatchBECount != getCouldNotCompute()) {
9881     // We know that Latch branches back to the loop header exactly
9882     // LatchBECount times.  This means the backdege condition at Latch is
9883     // equivalent to  "{0,+,1} u< LatchBECount".
9884     Type *Ty = LatchBECount->getType();
9885     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
9886     const SCEV *LoopCounter =
9887       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
9888     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
9889                       LatchBECount))
9890       return true;
9891   }
9892 
9893   // Check conditions due to any @llvm.assume intrinsics.
9894   for (auto &AssumeVH : AC.assumptions()) {
9895     if (!AssumeVH)
9896       continue;
9897     auto *CI = cast<CallInst>(AssumeVH);
9898     if (!DT.dominates(CI, Latch->getTerminator()))
9899       continue;
9900 
9901     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
9902       return true;
9903   }
9904 
9905   // If the loop is not reachable from the entry block, we risk running into an
9906   // infinite loop as we walk up into the dom tree.  These loops do not matter
9907   // anyway, so we just return a conservative answer when we see them.
9908   if (!DT.isReachableFromEntry(L->getHeader()))
9909     return false;
9910 
9911   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
9912     return true;
9913 
9914   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
9915        DTN != HeaderDTN; DTN = DTN->getIDom()) {
9916     assert(DTN && "should reach the loop header before reaching the root!");
9917 
9918     BasicBlock *BB = DTN->getBlock();
9919     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
9920       return true;
9921 
9922     BasicBlock *PBB = BB->getSinglePredecessor();
9923     if (!PBB)
9924       continue;
9925 
9926     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
9927     if (!ContinuePredicate || !ContinuePredicate->isConditional())
9928       continue;
9929 
9930     Value *Condition = ContinuePredicate->getCondition();
9931 
9932     // If we have an edge `E` within the loop body that dominates the only
9933     // latch, the condition guarding `E` also guards the backedge.  This
9934     // reasoning works only for loops with a single latch.
9935 
9936     BasicBlockEdge DominatingEdge(PBB, BB);
9937     if (DominatingEdge.isSingleEdge()) {
9938       // We're constructively (and conservatively) enumerating edges within the
9939       // loop body that dominate the latch.  The dominator tree better agree
9940       // with us on this:
9941       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
9942 
9943       if (isImpliedCond(Pred, LHS, RHS, Condition,
9944                         BB != ContinuePredicate->getSuccessor(0)))
9945         return true;
9946     }
9947   }
9948 
9949   return false;
9950 }
9951 
isBasicBlockEntryGuardedByCond(const BasicBlock * BB,ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)9952 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
9953                                                      ICmpInst::Predicate Pred,
9954                                                      const SCEV *LHS,
9955                                                      const SCEV *RHS) {
9956   if (VerifyIR)
9957     assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
9958            "This cannot be done on broken IR!");
9959 
9960   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9961     return true;
9962 
9963   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
9964   // the facts (a >= b && a != b) separately. A typical situation is when the
9965   // non-strict comparison is known from ranges and non-equality is known from
9966   // dominating predicates. If we are proving strict comparison, we always try
9967   // to prove non-equality and non-strict comparison separately.
9968   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
9969   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
9970   bool ProvedNonStrictComparison = false;
9971   bool ProvedNonEquality = false;
9972 
9973   if (ProvingStrictComparison) {
9974     ProvedNonStrictComparison =
9975         isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS);
9976     ProvedNonEquality =
9977         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS);
9978     if (ProvedNonStrictComparison && ProvedNonEquality)
9979       return true;
9980   }
9981 
9982   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
9983   auto ProveViaGuard = [&](const BasicBlock *Block) {
9984     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
9985       return true;
9986     if (ProvingStrictComparison) {
9987       if (!ProvedNonStrictComparison)
9988         ProvedNonStrictComparison =
9989             isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS);
9990       if (!ProvedNonEquality)
9991         ProvedNonEquality =
9992             isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS);
9993       if (ProvedNonStrictComparison && ProvedNonEquality)
9994         return true;
9995     }
9996     return false;
9997   };
9998 
9999   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
10000   auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
10001     const Instruction *Context = &BB->front();
10002     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context))
10003       return true;
10004     if (ProvingStrictComparison) {
10005       if (!ProvedNonStrictComparison)
10006         ProvedNonStrictComparison = isImpliedCond(NonStrictPredicate, LHS, RHS,
10007                                                   Condition, Inverse, Context);
10008       if (!ProvedNonEquality)
10009         ProvedNonEquality = isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS,
10010                                           Condition, Inverse, Context);
10011       if (ProvedNonStrictComparison && ProvedNonEquality)
10012         return true;
10013     }
10014     return false;
10015   };
10016 
10017   // Starting at the block's predecessor, climb up the predecessor chain, as long
10018   // as there are predecessors that can be found that have unique successors
10019   // leading to the original block.
10020   const Loop *ContainingLoop = LI.getLoopFor(BB);
10021   const BasicBlock *PredBB;
10022   if (ContainingLoop && ContainingLoop->getHeader() == BB)
10023     PredBB = ContainingLoop->getLoopPredecessor();
10024   else
10025     PredBB = BB->getSinglePredecessor();
10026   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
10027        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
10028     if (ProveViaGuard(Pair.first))
10029       return true;
10030 
10031     const BranchInst *LoopEntryPredicate =
10032         dyn_cast<BranchInst>(Pair.first->getTerminator());
10033     if (!LoopEntryPredicate ||
10034         LoopEntryPredicate->isUnconditional())
10035       continue;
10036 
10037     if (ProveViaCond(LoopEntryPredicate->getCondition(),
10038                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
10039       return true;
10040   }
10041 
10042   // Check conditions due to any @llvm.assume intrinsics.
10043   for (auto &AssumeVH : AC.assumptions()) {
10044     if (!AssumeVH)
10045       continue;
10046     auto *CI = cast<CallInst>(AssumeVH);
10047     if (!DT.dominates(CI, BB))
10048       continue;
10049 
10050     if (ProveViaCond(CI->getArgOperand(0), false))
10051       return true;
10052   }
10053 
10054   return false;
10055 }
10056 
isLoopEntryGuardedByCond(const Loop * L,ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)10057 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
10058                                                ICmpInst::Predicate Pred,
10059                                                const SCEV *LHS,
10060                                                const SCEV *RHS) {
10061   // Interpret a null as meaning no loop, where there is obviously no guard
10062   // (interprocedural conditions notwithstanding).
10063   if (!L)
10064     return false;
10065 
10066   // Both LHS and RHS must be available at loop entry.
10067   assert(isAvailableAtLoopEntry(LHS, L) &&
10068          "LHS is not available at Loop Entry");
10069   assert(isAvailableAtLoopEntry(RHS, L) &&
10070          "RHS is not available at Loop Entry");
10071   return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
10072 }
10073 
isImpliedCond(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const Value * FoundCondValue,bool Inverse,const Instruction * Context)10074 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10075                                     const SCEV *RHS,
10076                                     const Value *FoundCondValue, bool Inverse,
10077                                     const Instruction *Context) {
10078   if (!PendingLoopPredicates.insert(FoundCondValue).second)
10079     return false;
10080 
10081   auto ClearOnExit =
10082       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
10083 
10084   // Recursively handle And and Or conditions.
10085   if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
10086     if (BO->getOpcode() == Instruction::And) {
10087       if (!Inverse)
10088         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse,
10089                              Context) ||
10090                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse,
10091                              Context);
10092     } else if (BO->getOpcode() == Instruction::Or) {
10093       if (Inverse)
10094         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse,
10095                              Context) ||
10096                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse,
10097                              Context);
10098     }
10099   }
10100 
10101   const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
10102   if (!ICI) return false;
10103 
10104   // Now that we found a conditional branch that dominates the loop or controls
10105   // the loop latch. Check to see if it is the comparison we are looking for.
10106   ICmpInst::Predicate FoundPred;
10107   if (Inverse)
10108     FoundPred = ICI->getInversePredicate();
10109   else
10110     FoundPred = ICI->getPredicate();
10111 
10112   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
10113   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
10114 
10115   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context);
10116 }
10117 
isImpliedCond(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,ICmpInst::Predicate FoundPred,const SCEV * FoundLHS,const SCEV * FoundRHS,const Instruction * Context)10118 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10119                                     const SCEV *RHS,
10120                                     ICmpInst::Predicate FoundPred,
10121                                     const SCEV *FoundLHS, const SCEV *FoundRHS,
10122                                     const Instruction *Context) {
10123   // Balance the types.
10124   if (getTypeSizeInBits(LHS->getType()) <
10125       getTypeSizeInBits(FoundLHS->getType())) {
10126     // For unsigned and equality predicates, try to prove that both found
10127     // operands fit into narrow unsigned range. If so, try to prove facts in
10128     // narrow types.
10129     if (!CmpInst::isSigned(FoundPred)) {
10130       auto *NarrowType = LHS->getType();
10131       auto *WideType = FoundLHS->getType();
10132       auto BitWidth = getTypeSizeInBits(NarrowType);
10133       const SCEV *MaxValue = getZeroExtendExpr(
10134           getConstant(APInt::getMaxValue(BitWidth)), WideType);
10135       if (isKnownPredicate(ICmpInst::ICMP_ULE, FoundLHS, MaxValue) &&
10136           isKnownPredicate(ICmpInst::ICMP_ULE, FoundRHS, MaxValue)) {
10137         const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
10138         const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
10139         if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
10140                                        TruncFoundRHS, Context))
10141           return true;
10142       }
10143     }
10144 
10145     if (CmpInst::isSigned(Pred)) {
10146       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
10147       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
10148     } else {
10149       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
10150       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
10151     }
10152   } else if (getTypeSizeInBits(LHS->getType()) >
10153       getTypeSizeInBits(FoundLHS->getType())) {
10154     if (CmpInst::isSigned(FoundPred)) {
10155       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
10156       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
10157     } else {
10158       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
10159       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
10160     }
10161   }
10162   return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
10163                                     FoundRHS, Context);
10164 }
10165 
isImpliedCondBalancedTypes(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,ICmpInst::Predicate FoundPred,const SCEV * FoundLHS,const SCEV * FoundRHS,const Instruction * Context)10166 bool ScalarEvolution::isImpliedCondBalancedTypes(
10167     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10168     ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
10169     const Instruction *Context) {
10170   assert(getTypeSizeInBits(LHS->getType()) ==
10171              getTypeSizeInBits(FoundLHS->getType()) &&
10172          "Types should be balanced!");
10173   // Canonicalize the query to match the way instcombine will have
10174   // canonicalized the comparison.
10175   if (SimplifyICmpOperands(Pred, LHS, RHS))
10176     if (LHS == RHS)
10177       return CmpInst::isTrueWhenEqual(Pred);
10178   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
10179     if (FoundLHS == FoundRHS)
10180       return CmpInst::isFalseWhenEqual(FoundPred);
10181 
10182   // Check to see if we can make the LHS or RHS match.
10183   if (LHS == FoundRHS || RHS == FoundLHS) {
10184     if (isa<SCEVConstant>(RHS)) {
10185       std::swap(FoundLHS, FoundRHS);
10186       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
10187     } else {
10188       std::swap(LHS, RHS);
10189       Pred = ICmpInst::getSwappedPredicate(Pred);
10190     }
10191   }
10192 
10193   // Check whether the found predicate is the same as the desired predicate.
10194   if (FoundPred == Pred)
10195     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context);
10196 
10197   // Check whether swapping the found predicate makes it the same as the
10198   // desired predicate.
10199   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
10200     if (isa<SCEVConstant>(RHS))
10201       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context);
10202     else
10203       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), RHS,
10204                                    LHS, FoundLHS, FoundRHS, Context);
10205   }
10206 
10207   // Unsigned comparison is the same as signed comparison when both the operands
10208   // are non-negative.
10209   if (CmpInst::isUnsigned(FoundPred) &&
10210       CmpInst::getSignedPredicate(FoundPred) == Pred &&
10211       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
10212     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context);
10213 
10214   // Check if we can make progress by sharpening ranges.
10215   if (FoundPred == ICmpInst::ICMP_NE &&
10216       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
10217 
10218     const SCEVConstant *C = nullptr;
10219     const SCEV *V = nullptr;
10220 
10221     if (isa<SCEVConstant>(FoundLHS)) {
10222       C = cast<SCEVConstant>(FoundLHS);
10223       V = FoundRHS;
10224     } else {
10225       C = cast<SCEVConstant>(FoundRHS);
10226       V = FoundLHS;
10227     }
10228 
10229     // The guarding predicate tells us that C != V. If the known range
10230     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
10231     // range we consider has to correspond to same signedness as the
10232     // predicate we're interested in folding.
10233 
10234     APInt Min = ICmpInst::isSigned(Pred) ?
10235         getSignedRangeMin(V) : getUnsignedRangeMin(V);
10236 
10237     if (Min == C->getAPInt()) {
10238       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
10239       // This is true even if (Min + 1) wraps around -- in case of
10240       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
10241 
10242       APInt SharperMin = Min + 1;
10243 
10244       switch (Pred) {
10245         case ICmpInst::ICMP_SGE:
10246         case ICmpInst::ICMP_UGE:
10247           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
10248           // RHS, we're done.
10249           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
10250                                     Context))
10251             return true;
10252           LLVM_FALLTHROUGH;
10253 
10254         case ICmpInst::ICMP_SGT:
10255         case ICmpInst::ICMP_UGT:
10256           // We know from the range information that (V `Pred` Min ||
10257           // V == Min).  We know from the guarding condition that !(V
10258           // == Min).  This gives us
10259           //
10260           //       V `Pred` Min || V == Min && !(V == Min)
10261           //   =>  V `Pred` Min
10262           //
10263           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
10264 
10265           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min),
10266                                     Context))
10267             return true;
10268           break;
10269 
10270         // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
10271         case ICmpInst::ICMP_SLE:
10272         case ICmpInst::ICMP_ULE:
10273           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10274                                     LHS, V, getConstant(SharperMin), Context))
10275             return true;
10276           LLVM_FALLTHROUGH;
10277 
10278         case ICmpInst::ICMP_SLT:
10279         case ICmpInst::ICMP_ULT:
10280           if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10281                                     LHS, V, getConstant(Min), Context))
10282             return true;
10283           break;
10284 
10285         default:
10286           // No change
10287           break;
10288       }
10289     }
10290   }
10291 
10292   // Check whether the actual condition is beyond sufficient.
10293   if (FoundPred == ICmpInst::ICMP_EQ)
10294     if (ICmpInst::isTrueWhenEqual(Pred))
10295       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context))
10296         return true;
10297   if (Pred == ICmpInst::ICMP_NE)
10298     if (!ICmpInst::isTrueWhenEqual(FoundPred))
10299       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS,
10300                                 Context))
10301         return true;
10302 
10303   // Otherwise assume the worst.
10304   return false;
10305 }
10306 
splitBinaryAdd(const SCEV * Expr,const SCEV * & L,const SCEV * & R,SCEV::NoWrapFlags & Flags)10307 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
10308                                      const SCEV *&L, const SCEV *&R,
10309                                      SCEV::NoWrapFlags &Flags) {
10310   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
10311   if (!AE || AE->getNumOperands() != 2)
10312     return false;
10313 
10314   L = AE->getOperand(0);
10315   R = AE->getOperand(1);
10316   Flags = AE->getNoWrapFlags();
10317   return true;
10318 }
10319 
computeConstantDifference(const SCEV * More,const SCEV * Less)10320 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
10321                                                            const SCEV *Less) {
10322   // We avoid subtracting expressions here because this function is usually
10323   // fairly deep in the call stack (i.e. is called many times).
10324 
10325   // X - X = 0.
10326   if (More == Less)
10327     return APInt(getTypeSizeInBits(More->getType()), 0);
10328 
10329   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
10330     const auto *LAR = cast<SCEVAddRecExpr>(Less);
10331     const auto *MAR = cast<SCEVAddRecExpr>(More);
10332 
10333     if (LAR->getLoop() != MAR->getLoop())
10334       return None;
10335 
10336     // We look at affine expressions only; not for correctness but to keep
10337     // getStepRecurrence cheap.
10338     if (!LAR->isAffine() || !MAR->isAffine())
10339       return None;
10340 
10341     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
10342       return None;
10343 
10344     Less = LAR->getStart();
10345     More = MAR->getStart();
10346 
10347     // fall through
10348   }
10349 
10350   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
10351     const auto &M = cast<SCEVConstant>(More)->getAPInt();
10352     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
10353     return M - L;
10354   }
10355 
10356   SCEV::NoWrapFlags Flags;
10357   const SCEV *LLess = nullptr, *RLess = nullptr;
10358   const SCEV *LMore = nullptr, *RMore = nullptr;
10359   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
10360   // Compare (X + C1) vs X.
10361   if (splitBinaryAdd(Less, LLess, RLess, Flags))
10362     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
10363       if (RLess == More)
10364         return -(C1->getAPInt());
10365 
10366   // Compare X vs (X + C2).
10367   if (splitBinaryAdd(More, LMore, RMore, Flags))
10368     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
10369       if (RMore == Less)
10370         return C2->getAPInt();
10371 
10372   // Compare (X + C1) vs (X + C2).
10373   if (C1 && C2 && RLess == RMore)
10374     return C2->getAPInt() - C1->getAPInt();
10375 
10376   return None;
10377 }
10378 
isImpliedCondOperandsViaAddRecStart(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const SCEV * FoundLHS,const SCEV * FoundRHS,const Instruction * Context)10379 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
10380     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10381     const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) {
10382   // Try to recognize the following pattern:
10383   //
10384   //   FoundRHS = ...
10385   // ...
10386   // loop:
10387   //   FoundLHS = {Start,+,W}
10388   // context_bb: // Basic block from the same loop
10389   //   known(Pred, FoundLHS, FoundRHS)
10390   //
10391   // If some predicate is known in the context of a loop, it is also known on
10392   // each iteration of this loop, including the first iteration. Therefore, in
10393   // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
10394   // prove the original pred using this fact.
10395   if (!Context)
10396     return false;
10397   const BasicBlock *ContextBB = Context->getParent();
10398   // Make sure AR varies in the context block.
10399   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
10400     const Loop *L = AR->getLoop();
10401     // Make sure that context belongs to the loop and executes on 1st iteration
10402     // (if it ever executes at all).
10403     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
10404       return false;
10405     if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
10406       return false;
10407     return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
10408   }
10409 
10410   if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
10411     const Loop *L = AR->getLoop();
10412     // Make sure that context belongs to the loop and executes on 1st iteration
10413     // (if it ever executes at all).
10414     if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
10415       return false;
10416     if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
10417       return false;
10418     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
10419   }
10420 
10421   return false;
10422 }
10423 
isImpliedCondOperandsViaNoOverflow(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const SCEV * FoundLHS,const SCEV * FoundRHS)10424 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
10425     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10426     const SCEV *FoundLHS, const SCEV *FoundRHS) {
10427   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
10428     return false;
10429 
10430   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
10431   if (!AddRecLHS)
10432     return false;
10433 
10434   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
10435   if (!AddRecFoundLHS)
10436     return false;
10437 
10438   // We'd like to let SCEV reason about control dependencies, so we constrain
10439   // both the inequalities to be about add recurrences on the same loop.  This
10440   // way we can use isLoopEntryGuardedByCond later.
10441 
10442   const Loop *L = AddRecFoundLHS->getLoop();
10443   if (L != AddRecLHS->getLoop())
10444     return false;
10445 
10446   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
10447   //
10448   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
10449   //                                                                  ... (2)
10450   //
10451   // Informal proof for (2), assuming (1) [*]:
10452   //
10453   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
10454   //
10455   // Then
10456   //
10457   //       FoundLHS s< FoundRHS s< INT_MIN - C
10458   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
10459   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
10460   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
10461   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
10462   // <=>  FoundLHS + C s< FoundRHS + C
10463   //
10464   // [*]: (1) can be proved by ruling out overflow.
10465   //
10466   // [**]: This can be proved by analyzing all the four possibilities:
10467   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
10468   //    (A s>= 0, B s>= 0).
10469   //
10470   // Note:
10471   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
10472   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
10473   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
10474   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
10475   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
10476   // C)".
10477 
10478   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
10479   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
10480   if (!LDiff || !RDiff || *LDiff != *RDiff)
10481     return false;
10482 
10483   if (LDiff->isMinValue())
10484     return true;
10485 
10486   APInt FoundRHSLimit;
10487 
10488   if (Pred == CmpInst::ICMP_ULT) {
10489     FoundRHSLimit = -(*RDiff);
10490   } else {
10491     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
10492     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
10493   }
10494 
10495   // Try to prove (1) or (2), as needed.
10496   return isAvailableAtLoopEntry(FoundRHS, L) &&
10497          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
10498                                   getConstant(FoundRHSLimit));
10499 }
10500 
isImpliedViaMerge(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const SCEV * FoundLHS,const SCEV * FoundRHS,unsigned Depth)10501 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
10502                                         const SCEV *LHS, const SCEV *RHS,
10503                                         const SCEV *FoundLHS,
10504                                         const SCEV *FoundRHS, unsigned Depth) {
10505   const PHINode *LPhi = nullptr, *RPhi = nullptr;
10506 
10507   auto ClearOnExit = make_scope_exit([&]() {
10508     if (LPhi) {
10509       bool Erased = PendingMerges.erase(LPhi);
10510       assert(Erased && "Failed to erase LPhi!");
10511       (void)Erased;
10512     }
10513     if (RPhi) {
10514       bool Erased = PendingMerges.erase(RPhi);
10515       assert(Erased && "Failed to erase RPhi!");
10516       (void)Erased;
10517     }
10518   });
10519 
10520   // Find respective Phis and check that they are not being pending.
10521   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
10522     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
10523       if (!PendingMerges.insert(Phi).second)
10524         return false;
10525       LPhi = Phi;
10526     }
10527   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
10528     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
10529       // If we detect a loop of Phi nodes being processed by this method, for
10530       // example:
10531       //
10532       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
10533       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
10534       //
10535       // we don't want to deal with a case that complex, so return conservative
10536       // answer false.
10537       if (!PendingMerges.insert(Phi).second)
10538         return false;
10539       RPhi = Phi;
10540     }
10541 
10542   // If none of LHS, RHS is a Phi, nothing to do here.
10543   if (!LPhi && !RPhi)
10544     return false;
10545 
10546   // If there is a SCEVUnknown Phi we are interested in, make it left.
10547   if (!LPhi) {
10548     std::swap(LHS, RHS);
10549     std::swap(FoundLHS, FoundRHS);
10550     std::swap(LPhi, RPhi);
10551     Pred = ICmpInst::getSwappedPredicate(Pred);
10552   }
10553 
10554   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
10555   const BasicBlock *LBB = LPhi->getParent();
10556   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10557 
10558   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
10559     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
10560            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
10561            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
10562   };
10563 
10564   if (RPhi && RPhi->getParent() == LBB) {
10565     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
10566     // If we compare two Phis from the same block, and for each entry block
10567     // the predicate is true for incoming values from this block, then the
10568     // predicate is also true for the Phis.
10569     for (const BasicBlock *IncBB : predecessors(LBB)) {
10570       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10571       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
10572       if (!ProvedEasily(L, R))
10573         return false;
10574     }
10575   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
10576     // Case two: RHS is also a Phi from the same basic block, and it is an
10577     // AddRec. It means that there is a loop which has both AddRec and Unknown
10578     // PHIs, for it we can compare incoming values of AddRec from above the loop
10579     // and latch with their respective incoming values of LPhi.
10580     // TODO: Generalize to handle loops with many inputs in a header.
10581     if (LPhi->getNumIncomingValues() != 2) return false;
10582 
10583     auto *RLoop = RAR->getLoop();
10584     auto *Predecessor = RLoop->getLoopPredecessor();
10585     assert(Predecessor && "Loop with AddRec with no predecessor?");
10586     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
10587     if (!ProvedEasily(L1, RAR->getStart()))
10588       return false;
10589     auto *Latch = RLoop->getLoopLatch();
10590     assert(Latch && "Loop with AddRec with no latch?");
10591     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
10592     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
10593       return false;
10594   } else {
10595     // In all other cases go over inputs of LHS and compare each of them to RHS,
10596     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
10597     // At this point RHS is either a non-Phi, or it is a Phi from some block
10598     // different from LBB.
10599     for (const BasicBlock *IncBB : predecessors(LBB)) {
10600       // Check that RHS is available in this block.
10601       if (!dominates(RHS, IncBB))
10602         return false;
10603       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10604       if (!ProvedEasily(L, RHS))
10605         return false;
10606     }
10607   }
10608   return true;
10609 }
10610 
isImpliedCondOperands(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const SCEV * FoundLHS,const SCEV * FoundRHS,const Instruction * Context)10611 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
10612                                             const SCEV *LHS, const SCEV *RHS,
10613                                             const SCEV *FoundLHS,
10614                                             const SCEV *FoundRHS,
10615                                             const Instruction *Context) {
10616   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
10617     return true;
10618 
10619   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
10620     return true;
10621 
10622   if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
10623                                           Context))
10624     return true;
10625 
10626   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
10627                                      FoundLHS, FoundRHS) ||
10628          // ~x < ~y --> x > y
10629          isImpliedCondOperandsHelper(Pred, LHS, RHS,
10630                                      getNotSCEV(FoundRHS),
10631                                      getNotSCEV(FoundLHS));
10632 }
10633 
10634 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
10635 template <typename MinMaxExprType>
IsMinMaxConsistingOf(const SCEV * MaybeMinMaxExpr,const SCEV * Candidate)10636 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
10637                                  const SCEV *Candidate) {
10638   const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
10639   if (!MinMaxExpr)
10640     return false;
10641 
10642   return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end();
10643 }
10644 
IsKnownPredicateViaAddRecStart(ScalarEvolution & SE,ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)10645 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
10646                                            ICmpInst::Predicate Pred,
10647                                            const SCEV *LHS, const SCEV *RHS) {
10648   // If both sides are affine addrecs for the same loop, with equal
10649   // steps, and we know the recurrences don't wrap, then we only
10650   // need to check the predicate on the starting values.
10651 
10652   if (!ICmpInst::isRelational(Pred))
10653     return false;
10654 
10655   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
10656   if (!LAR)
10657     return false;
10658   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10659   if (!RAR)
10660     return false;
10661   if (LAR->getLoop() != RAR->getLoop())
10662     return false;
10663   if (!LAR->isAffine() || !RAR->isAffine())
10664     return false;
10665 
10666   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
10667     return false;
10668 
10669   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
10670                          SCEV::FlagNSW : SCEV::FlagNUW;
10671   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
10672     return false;
10673 
10674   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
10675 }
10676 
10677 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
10678 /// expression?
IsKnownPredicateViaMinOrMax(ScalarEvolution & SE,ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)10679 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
10680                                         ICmpInst::Predicate Pred,
10681                                         const SCEV *LHS, const SCEV *RHS) {
10682   switch (Pred) {
10683   default:
10684     return false;
10685 
10686   case ICmpInst::ICMP_SGE:
10687     std::swap(LHS, RHS);
10688     LLVM_FALLTHROUGH;
10689   case ICmpInst::ICMP_SLE:
10690     return
10691         // min(A, ...) <= A
10692         IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
10693         // A <= max(A, ...)
10694         IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
10695 
10696   case ICmpInst::ICMP_UGE:
10697     std::swap(LHS, RHS);
10698     LLVM_FALLTHROUGH;
10699   case ICmpInst::ICMP_ULE:
10700     return
10701         // min(A, ...) <= A
10702         IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
10703         // A <= max(A, ...)
10704         IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
10705   }
10706 
10707   llvm_unreachable("covered switch fell through?!");
10708 }
10709 
isImpliedViaOperations(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const SCEV * FoundLHS,const SCEV * FoundRHS,unsigned Depth)10710 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
10711                                              const SCEV *LHS, const SCEV *RHS,
10712                                              const SCEV *FoundLHS,
10713                                              const SCEV *FoundRHS,
10714                                              unsigned Depth) {
10715   assert(getTypeSizeInBits(LHS->getType()) ==
10716              getTypeSizeInBits(RHS->getType()) &&
10717          "LHS and RHS have different sizes?");
10718   assert(getTypeSizeInBits(FoundLHS->getType()) ==
10719              getTypeSizeInBits(FoundRHS->getType()) &&
10720          "FoundLHS and FoundRHS have different sizes?");
10721   // We want to avoid hurting the compile time with analysis of too big trees.
10722   if (Depth > MaxSCEVOperationsImplicationDepth)
10723     return false;
10724 
10725   // We only want to work with GT comparison so far.
10726   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
10727     Pred = CmpInst::getSwappedPredicate(Pred);
10728     std::swap(LHS, RHS);
10729     std::swap(FoundLHS, FoundRHS);
10730   }
10731 
10732   // For unsigned, try to reduce it to corresponding signed comparison.
10733   if (Pred == ICmpInst::ICMP_UGT)
10734     // We can replace unsigned predicate with its signed counterpart if all
10735     // involved values are non-negative.
10736     // TODO: We could have better support for unsigned.
10737     if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
10738       // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
10739       // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
10740       // use this fact to prove that LHS and RHS are non-negative.
10741       const SCEV *MinusOne = getMinusOne(LHS->getType());
10742       if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
10743                                 FoundRHS) &&
10744           isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
10745                                 FoundRHS))
10746         Pred = ICmpInst::ICMP_SGT;
10747     }
10748 
10749   if (Pred != ICmpInst::ICMP_SGT)
10750     return false;
10751 
10752   auto GetOpFromSExt = [&](const SCEV *S) {
10753     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
10754       return Ext->getOperand();
10755     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
10756     // the constant in some cases.
10757     return S;
10758   };
10759 
10760   // Acquire values from extensions.
10761   auto *OrigLHS = LHS;
10762   auto *OrigFoundLHS = FoundLHS;
10763   LHS = GetOpFromSExt(LHS);
10764   FoundLHS = GetOpFromSExt(FoundLHS);
10765 
10766   // Is the SGT predicate can be proved trivially or using the found context.
10767   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
10768     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
10769            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
10770                                   FoundRHS, Depth + 1);
10771   };
10772 
10773   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
10774     // We want to avoid creation of any new non-constant SCEV. Since we are
10775     // going to compare the operands to RHS, we should be certain that we don't
10776     // need any size extensions for this. So let's decline all cases when the
10777     // sizes of types of LHS and RHS do not match.
10778     // TODO: Maybe try to get RHS from sext to catch more cases?
10779     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
10780       return false;
10781 
10782     // Should not overflow.
10783     if (!LHSAddExpr->hasNoSignedWrap())
10784       return false;
10785 
10786     auto *LL = LHSAddExpr->getOperand(0);
10787     auto *LR = LHSAddExpr->getOperand(1);
10788     auto *MinusOne = getMinusOne(RHS->getType());
10789 
10790     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
10791     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
10792       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
10793     };
10794     // Try to prove the following rule:
10795     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
10796     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
10797     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
10798       return true;
10799   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
10800     Value *LL, *LR;
10801     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
10802 
10803     using namespace llvm::PatternMatch;
10804 
10805     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
10806       // Rules for division.
10807       // We are going to perform some comparisons with Denominator and its
10808       // derivative expressions. In general case, creating a SCEV for it may
10809       // lead to a complex analysis of the entire graph, and in particular it
10810       // can request trip count recalculation for the same loop. This would
10811       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
10812       // this, we only want to create SCEVs that are constants in this section.
10813       // So we bail if Denominator is not a constant.
10814       if (!isa<ConstantInt>(LR))
10815         return false;
10816 
10817       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
10818 
10819       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
10820       // then a SCEV for the numerator already exists and matches with FoundLHS.
10821       auto *Numerator = getExistingSCEV(LL);
10822       if (!Numerator || Numerator->getType() != FoundLHS->getType())
10823         return false;
10824 
10825       // Make sure that the numerator matches with FoundLHS and the denominator
10826       // is positive.
10827       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
10828         return false;
10829 
10830       auto *DTy = Denominator->getType();
10831       auto *FRHSTy = FoundRHS->getType();
10832       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
10833         // One of types is a pointer and another one is not. We cannot extend
10834         // them properly to a wider type, so let us just reject this case.
10835         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
10836         // to avoid this check.
10837         return false;
10838 
10839       // Given that:
10840       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
10841       auto *WTy = getWiderType(DTy, FRHSTy);
10842       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
10843       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
10844 
10845       // Try to prove the following rule:
10846       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
10847       // For example, given that FoundLHS > 2. It means that FoundLHS is at
10848       // least 3. If we divide it by Denominator < 4, we will have at least 1.
10849       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
10850       if (isKnownNonPositive(RHS) &&
10851           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
10852         return true;
10853 
10854       // Try to prove the following rule:
10855       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
10856       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
10857       // If we divide it by Denominator > 2, then:
10858       // 1. If FoundLHS is negative, then the result is 0.
10859       // 2. If FoundLHS is non-negative, then the result is non-negative.
10860       // Anyways, the result is non-negative.
10861       auto *MinusOne = getMinusOne(WTy);
10862       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
10863       if (isKnownNegative(RHS) &&
10864           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
10865         return true;
10866     }
10867   }
10868 
10869   // If our expression contained SCEVUnknown Phis, and we split it down and now
10870   // need to prove something for them, try to prove the predicate for every
10871   // possible incoming values of those Phis.
10872   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
10873     return true;
10874 
10875   return false;
10876 }
10877 
isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)10878 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
10879                                         const SCEV *LHS, const SCEV *RHS) {
10880   // zext x u<= sext x, sext x s<= zext x
10881   switch (Pred) {
10882   case ICmpInst::ICMP_SGE:
10883     std::swap(LHS, RHS);
10884     LLVM_FALLTHROUGH;
10885   case ICmpInst::ICMP_SLE: {
10886     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then SExt <s ZExt.
10887     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
10888     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
10889     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
10890       return true;
10891     break;
10892   }
10893   case ICmpInst::ICMP_UGE:
10894     std::swap(LHS, RHS);
10895     LLVM_FALLTHROUGH;
10896   case ICmpInst::ICMP_ULE: {
10897     // If operand >=s 0 then ZExt == SExt.  If operand <s 0 then ZExt <u SExt.
10898     const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
10899     const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
10900     if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
10901       return true;
10902     break;
10903   }
10904   default:
10905     break;
10906   };
10907   return false;
10908 }
10909 
10910 bool
isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)10911 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
10912                                            const SCEV *LHS, const SCEV *RHS) {
10913   return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
10914          isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
10915          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
10916          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
10917          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
10918 }
10919 
10920 bool
isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const SCEV * FoundLHS,const SCEV * FoundRHS)10921 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
10922                                              const SCEV *LHS, const SCEV *RHS,
10923                                              const SCEV *FoundLHS,
10924                                              const SCEV *FoundRHS) {
10925   switch (Pred) {
10926   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
10927   case ICmpInst::ICMP_EQ:
10928   case ICmpInst::ICMP_NE:
10929     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
10930       return true;
10931     break;
10932   case ICmpInst::ICMP_SLT:
10933   case ICmpInst::ICMP_SLE:
10934     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
10935         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
10936       return true;
10937     break;
10938   case ICmpInst::ICMP_SGT:
10939   case ICmpInst::ICMP_SGE:
10940     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
10941         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
10942       return true;
10943     break;
10944   case ICmpInst::ICMP_ULT:
10945   case ICmpInst::ICMP_ULE:
10946     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
10947         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
10948       return true;
10949     break;
10950   case ICmpInst::ICMP_UGT:
10951   case ICmpInst::ICMP_UGE:
10952     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
10953         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
10954       return true;
10955     break;
10956   }
10957 
10958   // Maybe it can be proved via operations?
10959   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
10960     return true;
10961 
10962   return false;
10963 }
10964 
isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,const SCEV * FoundLHS,const SCEV * FoundRHS)10965 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
10966                                                      const SCEV *LHS,
10967                                                      const SCEV *RHS,
10968                                                      const SCEV *FoundLHS,
10969                                                      const SCEV *FoundRHS) {
10970   if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
10971     // The restriction on `FoundRHS` be lifted easily -- it exists only to
10972     // reduce the compile time impact of this optimization.
10973     return false;
10974 
10975   Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
10976   if (!Addend)
10977     return false;
10978 
10979   const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
10980 
10981   // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
10982   // antecedent "`FoundLHS` `Pred` `FoundRHS`".
10983   ConstantRange FoundLHSRange =
10984       ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
10985 
10986   // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
10987   ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
10988 
10989   // We can also compute the range of values for `LHS` that satisfy the
10990   // consequent, "`LHS` `Pred` `RHS`":
10991   const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
10992   ConstantRange SatisfyingLHSRange =
10993       ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
10994 
10995   // The antecedent implies the consequent if every value of `LHS` that
10996   // satisfies the antecedent also satisfies the consequent.
10997   return SatisfyingLHSRange.contains(LHSRange);
10998 }
10999 
doesIVOverflowOnLT(const SCEV * RHS,const SCEV * Stride,bool IsSigned,bool NoWrap)11000 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
11001                                          bool IsSigned, bool NoWrap) {
11002   assert(isKnownPositive(Stride) && "Positive stride expected!");
11003 
11004   if (NoWrap) return false;
11005 
11006   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11007   const SCEV *One = getOne(Stride->getType());
11008 
11009   if (IsSigned) {
11010     APInt MaxRHS = getSignedRangeMax(RHS);
11011     APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
11012     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11013 
11014     // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
11015     return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
11016   }
11017 
11018   APInt MaxRHS = getUnsignedRangeMax(RHS);
11019   APInt MaxValue = APInt::getMaxValue(BitWidth);
11020   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11021 
11022   // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
11023   return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
11024 }
11025 
doesIVOverflowOnGT(const SCEV * RHS,const SCEV * Stride,bool IsSigned,bool NoWrap)11026 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
11027                                          bool IsSigned, bool NoWrap) {
11028   if (NoWrap) return false;
11029 
11030   unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11031   const SCEV *One = getOne(Stride->getType());
11032 
11033   if (IsSigned) {
11034     APInt MinRHS = getSignedRangeMin(RHS);
11035     APInt MinValue = APInt::getSignedMinValue(BitWidth);
11036     APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11037 
11038     // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
11039     return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
11040   }
11041 
11042   APInt MinRHS = getUnsignedRangeMin(RHS);
11043   APInt MinValue = APInt::getMinValue(BitWidth);
11044   APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11045 
11046   // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
11047   return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
11048 }
11049 
computeBECount(const SCEV * Delta,const SCEV * Step,bool Equality)11050 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
11051                                             bool Equality) {
11052   const SCEV *One = getOne(Step->getType());
11053   Delta = Equality ? getAddExpr(Delta, Step)
11054                    : getAddExpr(Delta, getMinusSCEV(Step, One));
11055   return getUDivExpr(Delta, Step);
11056 }
11057 
computeMaxBECountForLT(const SCEV * Start,const SCEV * Stride,const SCEV * End,unsigned BitWidth,bool IsSigned)11058 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
11059                                                     const SCEV *Stride,
11060                                                     const SCEV *End,
11061                                                     unsigned BitWidth,
11062                                                     bool IsSigned) {
11063 
11064   assert(!isKnownNonPositive(Stride) &&
11065          "Stride is expected strictly positive!");
11066   // Calculate the maximum backedge count based on the range of values
11067   // permitted by Start, End, and Stride.
11068   const SCEV *MaxBECount;
11069   APInt MinStart =
11070       IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
11071 
11072   APInt StrideForMaxBECount =
11073       IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
11074 
11075   // We already know that the stride is positive, so we paper over conservatism
11076   // in our range computation by forcing StrideForMaxBECount to be at least one.
11077   // In theory this is unnecessary, but we expect MaxBECount to be a
11078   // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
11079   // is nothing to constant fold it to).
11080   APInt One(BitWidth, 1, IsSigned);
11081   StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
11082 
11083   APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
11084                             : APInt::getMaxValue(BitWidth);
11085   APInt Limit = MaxValue - (StrideForMaxBECount - 1);
11086 
11087   // Although End can be a MAX expression we estimate MaxEnd considering only
11088   // the case End = RHS of the loop termination condition. This is safe because
11089   // in the other case (End - Start) is zero, leading to a zero maximum backedge
11090   // taken count.
11091   APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
11092                           : APIntOps::umin(getUnsignedRangeMax(End), Limit);
11093 
11094   MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
11095                               getConstant(StrideForMaxBECount) /* Step */,
11096                               false /* Equality */);
11097 
11098   return MaxBECount;
11099 }
11100 
11101 ScalarEvolution::ExitLimit
howManyLessThans(const SCEV * LHS,const SCEV * RHS,const Loop * L,bool IsSigned,bool ControlsExit,bool AllowPredicates)11102 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
11103                                   const Loop *L, bool IsSigned,
11104                                   bool ControlsExit, bool AllowPredicates) {
11105   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11106 
11107   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11108   bool PredicatedIV = false;
11109 
11110   if (!IV && AllowPredicates) {
11111     // Try to make this an AddRec using runtime tests, in the first X
11112     // iterations of this loop, where X is the SCEV expression found by the
11113     // algorithm below.
11114     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11115     PredicatedIV = true;
11116   }
11117 
11118   // Avoid weird loops
11119   if (!IV || IV->getLoop() != L || !IV->isAffine())
11120     return getCouldNotCompute();
11121 
11122   bool NoWrap = ControlsExit &&
11123                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
11124 
11125   const SCEV *Stride = IV->getStepRecurrence(*this);
11126 
11127   bool PositiveStride = isKnownPositive(Stride);
11128 
11129   // Avoid negative or zero stride values.
11130   if (!PositiveStride) {
11131     // We can compute the correct backedge taken count for loops with unknown
11132     // strides if we can prove that the loop is not an infinite loop with side
11133     // effects. Here's the loop structure we are trying to handle -
11134     //
11135     // i = start
11136     // do {
11137     //   A[i] = i;
11138     //   i += s;
11139     // } while (i < end);
11140     //
11141     // The backedge taken count for such loops is evaluated as -
11142     // (max(end, start + stride) - start - 1) /u stride
11143     //
11144     // The additional preconditions that we need to check to prove correctness
11145     // of the above formula is as follows -
11146     //
11147     // a) IV is either nuw or nsw depending upon signedness (indicated by the
11148     //    NoWrap flag).
11149     // b) loop is single exit with no side effects.
11150     //
11151     //
11152     // Precondition a) implies that if the stride is negative, this is a single
11153     // trip loop. The backedge taken count formula reduces to zero in this case.
11154     //
11155     // Precondition b) implies that the unknown stride cannot be zero otherwise
11156     // we have UB.
11157     //
11158     // The positive stride case is the same as isKnownPositive(Stride) returning
11159     // true (original behavior of the function).
11160     //
11161     // We want to make sure that the stride is truly unknown as there are edge
11162     // cases where ScalarEvolution propagates no wrap flags to the
11163     // post-increment/decrement IV even though the increment/decrement operation
11164     // itself is wrapping. The computed backedge taken count may be wrong in
11165     // such cases. This is prevented by checking that the stride is not known to
11166     // be either positive or non-positive. For example, no wrap flags are
11167     // propagated to the post-increment IV of this loop with a trip count of 2 -
11168     //
11169     // unsigned char i;
11170     // for(i=127; i<128; i+=129)
11171     //   A[i] = i;
11172     //
11173     if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
11174         !loopHasNoSideEffects(L))
11175       return getCouldNotCompute();
11176   } else if (!Stride->isOne() &&
11177              doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
11178     // Avoid proven overflow cases: this will ensure that the backedge taken
11179     // count will not generate any unsigned overflow. Relaxed no-overflow
11180     // conditions exploit NoWrapFlags, allowing to optimize in presence of
11181     // undefined behaviors like the case of C language.
11182     return getCouldNotCompute();
11183 
11184   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
11185                                       : ICmpInst::ICMP_ULT;
11186   const SCEV *Start = IV->getStart();
11187   const SCEV *End = RHS;
11188   // When the RHS is not invariant, we do not know the end bound of the loop and
11189   // cannot calculate the ExactBECount needed by ExitLimit. However, we can
11190   // calculate the MaxBECount, given the start, stride and max value for the end
11191   // bound of the loop (RHS), and the fact that IV does not overflow (which is
11192   // checked above).
11193   if (!isLoopInvariant(RHS, L)) {
11194     const SCEV *MaxBECount = computeMaxBECountForLT(
11195         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11196     return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
11197                      false /*MaxOrZero*/, Predicates);
11198   }
11199   // If the backedge is taken at least once, then it will be taken
11200   // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
11201   // is the LHS value of the less-than comparison the first time it is evaluated
11202   // and End is the RHS.
11203   const SCEV *BECountIfBackedgeTaken =
11204     computeBECount(getMinusSCEV(End, Start), Stride, false);
11205   // If the loop entry is guarded by the result of the backedge test of the
11206   // first loop iteration, then we know the backedge will be taken at least
11207   // once and so the backedge taken count is as above. If not then we use the
11208   // expression (max(End,Start)-Start)/Stride to describe the backedge count,
11209   // as if the backedge is taken at least once max(End,Start) is End and so the
11210   // result is as above, and if not max(End,Start) is Start so we get a backedge
11211   // count of zero.
11212   const SCEV *BECount;
11213   if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
11214     BECount = BECountIfBackedgeTaken;
11215   else {
11216     // If we know that RHS >= Start in the context of loop, then we know that
11217     // max(RHS, Start) = RHS at this point.
11218     if (isLoopEntryGuardedByCond(
11219             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, RHS, Start))
11220       End = RHS;
11221     else
11222       End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
11223     BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
11224   }
11225 
11226   const SCEV *MaxBECount;
11227   bool MaxOrZero = false;
11228   if (isa<SCEVConstant>(BECount))
11229     MaxBECount = BECount;
11230   else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
11231     // If we know exactly how many times the backedge will be taken if it's
11232     // taken at least once, then the backedge count will either be that or
11233     // zero.
11234     MaxBECount = BECountIfBackedgeTaken;
11235     MaxOrZero = true;
11236   } else {
11237     MaxBECount = computeMaxBECountForLT(
11238         Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11239   }
11240 
11241   if (isa<SCEVCouldNotCompute>(MaxBECount) &&
11242       !isa<SCEVCouldNotCompute>(BECount))
11243     MaxBECount = getConstant(getUnsignedRangeMax(BECount));
11244 
11245   return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
11246 }
11247 
11248 ScalarEvolution::ExitLimit
howManyGreaterThans(const SCEV * LHS,const SCEV * RHS,const Loop * L,bool IsSigned,bool ControlsExit,bool AllowPredicates)11249 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
11250                                      const Loop *L, bool IsSigned,
11251                                      bool ControlsExit, bool AllowPredicates) {
11252   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11253   // We handle only IV > Invariant
11254   if (!isLoopInvariant(RHS, L))
11255     return getCouldNotCompute();
11256 
11257   const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11258   if (!IV && AllowPredicates)
11259     // Try to make this an AddRec using runtime tests, in the first X
11260     // iterations of this loop, where X is the SCEV expression found by the
11261     // algorithm below.
11262     IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11263 
11264   // Avoid weird loops
11265   if (!IV || IV->getLoop() != L || !IV->isAffine())
11266     return getCouldNotCompute();
11267 
11268   bool NoWrap = ControlsExit &&
11269                 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
11270 
11271   const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
11272 
11273   // Avoid negative or zero stride values
11274   if (!isKnownPositive(Stride))
11275     return getCouldNotCompute();
11276 
11277   // Avoid proven overflow cases: this will ensure that the backedge taken count
11278   // will not generate any unsigned overflow. Relaxed no-overflow conditions
11279   // exploit NoWrapFlags, allowing to optimize in presence of undefined
11280   // behaviors like the case of C language.
11281   if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
11282     return getCouldNotCompute();
11283 
11284   ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
11285                                       : ICmpInst::ICMP_UGT;
11286 
11287   const SCEV *Start = IV->getStart();
11288   const SCEV *End = RHS;
11289   if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
11290     // If we know that Start >= RHS in the context of loop, then we know that
11291     // min(RHS, Start) = RHS at this point.
11292     if (isLoopEntryGuardedByCond(
11293             L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
11294       End = RHS;
11295     else
11296       End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
11297   }
11298 
11299   const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
11300 
11301   APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
11302                             : getUnsignedRangeMax(Start);
11303 
11304   APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
11305                              : getUnsignedRangeMin(Stride);
11306 
11307   unsigned BitWidth = getTypeSizeInBits(LHS->getType());
11308   APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
11309                          : APInt::getMinValue(BitWidth) + (MinStride - 1);
11310 
11311   // Although End can be a MIN expression we estimate MinEnd considering only
11312   // the case End = RHS. This is safe because in the other case (Start - End)
11313   // is zero, leading to a zero maximum backedge taken count.
11314   APInt MinEnd =
11315     IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
11316              : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
11317 
11318   const SCEV *MaxBECount = isa<SCEVConstant>(BECount)
11319                                ? BECount
11320                                : computeBECount(getConstant(MaxStart - MinEnd),
11321                                                 getConstant(MinStride), false);
11322 
11323   if (isa<SCEVCouldNotCompute>(MaxBECount))
11324     MaxBECount = BECount;
11325 
11326   return ExitLimit(BECount, MaxBECount, false, Predicates);
11327 }
11328 
getNumIterationsInRange(const ConstantRange & Range,ScalarEvolution & SE) const11329 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
11330                                                     ScalarEvolution &SE) const {
11331   if (Range.isFullSet())  // Infinite loop.
11332     return SE.getCouldNotCompute();
11333 
11334   // If the start is a non-zero constant, shift the range to simplify things.
11335   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
11336     if (!SC->getValue()->isZero()) {
11337       SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
11338       Operands[0] = SE.getZero(SC->getType());
11339       const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
11340                                              getNoWrapFlags(FlagNW));
11341       if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
11342         return ShiftedAddRec->getNumIterationsInRange(
11343             Range.subtract(SC->getAPInt()), SE);
11344       // This is strange and shouldn't happen.
11345       return SE.getCouldNotCompute();
11346     }
11347 
11348   // The only time we can solve this is when we have all constant indices.
11349   // Otherwise, we cannot determine the overflow conditions.
11350   if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
11351     return SE.getCouldNotCompute();
11352 
11353   // Okay at this point we know that all elements of the chrec are constants and
11354   // that the start element is zero.
11355 
11356   // First check to see if the range contains zero.  If not, the first
11357   // iteration exits.
11358   unsigned BitWidth = SE.getTypeSizeInBits(getType());
11359   if (!Range.contains(APInt(BitWidth, 0)))
11360     return SE.getZero(getType());
11361 
11362   if (isAffine()) {
11363     // If this is an affine expression then we have this situation:
11364     //   Solve {0,+,A} in Range  ===  Ax in Range
11365 
11366     // We know that zero is in the range.  If A is positive then we know that
11367     // the upper value of the range must be the first possible exit value.
11368     // If A is negative then the lower of the range is the last possible loop
11369     // value.  Also note that we already checked for a full range.
11370     APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
11371     APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
11372 
11373     // The exit value should be (End+A)/A.
11374     APInt ExitVal = (End + A).udiv(A);
11375     ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
11376 
11377     // Evaluate at the exit value.  If we really did fall out of the valid
11378     // range, then we computed our trip count, otherwise wrap around or other
11379     // things must have happened.
11380     ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
11381     if (Range.contains(Val->getValue()))
11382       return SE.getCouldNotCompute();  // Something strange happened
11383 
11384     // Ensure that the previous value is in the range.  This is a sanity check.
11385     assert(Range.contains(
11386            EvaluateConstantChrecAtConstant(this,
11387            ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
11388            "Linear scev computation is off in a bad way!");
11389     return SE.getConstant(ExitValue);
11390   }
11391 
11392   if (isQuadratic()) {
11393     if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
11394       return SE.getConstant(S.getValue());
11395   }
11396 
11397   return SE.getCouldNotCompute();
11398 }
11399 
11400 const SCEVAddRecExpr *
getPostIncExpr(ScalarEvolution & SE) const11401 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
11402   assert(getNumOperands() > 1 && "AddRec with zero step?");
11403   // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
11404   // but in this case we cannot guarantee that the value returned will be an
11405   // AddRec because SCEV does not have a fixed point where it stops
11406   // simplification: it is legal to return ({rec1} + {rec2}). For example, it
11407   // may happen if we reach arithmetic depth limit while simplifying. So we
11408   // construct the returned value explicitly.
11409   SmallVector<const SCEV *, 3> Ops;
11410   // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
11411   // (this + Step) is {A+B,+,B+C,+...,+,N}.
11412   for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
11413     Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
11414   // We know that the last operand is not a constant zero (otherwise it would
11415   // have been popped out earlier). This guarantees us that if the result has
11416   // the same last operand, then it will also not be popped out, meaning that
11417   // the returned value will be an AddRec.
11418   const SCEV *Last = getOperand(getNumOperands() - 1);
11419   assert(!Last->isZero() && "Recurrency with zero step?");
11420   Ops.push_back(Last);
11421   return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
11422                                                SCEV::FlagAnyWrap));
11423 }
11424 
11425 // Return true when S contains at least an undef value.
containsUndefs(const SCEV * S)11426 static inline bool containsUndefs(const SCEV *S) {
11427   return SCEVExprContains(S, [](const SCEV *S) {
11428     if (const auto *SU = dyn_cast<SCEVUnknown>(S))
11429       return isa<UndefValue>(SU->getValue());
11430     return false;
11431   });
11432 }
11433 
11434 namespace {
11435 
11436 // Collect all steps of SCEV expressions.
11437 struct SCEVCollectStrides {
11438   ScalarEvolution &SE;
11439   SmallVectorImpl<const SCEV *> &Strides;
11440 
SCEVCollectStrides__anon83ba15153011::SCEVCollectStrides11441   SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
11442       : SE(SE), Strides(S) {}
11443 
follow__anon83ba15153011::SCEVCollectStrides11444   bool follow(const SCEV *S) {
11445     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
11446       Strides.push_back(AR->getStepRecurrence(SE));
11447     return true;
11448   }
11449 
isDone__anon83ba15153011::SCEVCollectStrides11450   bool isDone() const { return false; }
11451 };
11452 
11453 // Collect all SCEVUnknown and SCEVMulExpr expressions.
11454 struct SCEVCollectTerms {
11455   SmallVectorImpl<const SCEV *> &Terms;
11456 
SCEVCollectTerms__anon83ba15153011::SCEVCollectTerms11457   SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
11458 
follow__anon83ba15153011::SCEVCollectTerms11459   bool follow(const SCEV *S) {
11460     if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
11461         isa<SCEVSignExtendExpr>(S)) {
11462       if (!containsUndefs(S))
11463         Terms.push_back(S);
11464 
11465       // Stop recursion: once we collected a term, do not walk its operands.
11466       return false;
11467     }
11468 
11469     // Keep looking.
11470     return true;
11471   }
11472 
isDone__anon83ba15153011::SCEVCollectTerms11473   bool isDone() const { return false; }
11474 };
11475 
11476 // Check if a SCEV contains an AddRecExpr.
11477 struct SCEVHasAddRec {
11478   bool &ContainsAddRec;
11479 
SCEVHasAddRec__anon83ba15153011::SCEVHasAddRec11480   SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
11481     ContainsAddRec = false;
11482   }
11483 
follow__anon83ba15153011::SCEVHasAddRec11484   bool follow(const SCEV *S) {
11485     if (isa<SCEVAddRecExpr>(S)) {
11486       ContainsAddRec = true;
11487 
11488       // Stop recursion: once we collected a term, do not walk its operands.
11489       return false;
11490     }
11491 
11492     // Keep looking.
11493     return true;
11494   }
11495 
isDone__anon83ba15153011::SCEVHasAddRec11496   bool isDone() const { return false; }
11497 };
11498 
11499 // Find factors that are multiplied with an expression that (possibly as a
11500 // subexpression) contains an AddRecExpr. In the expression:
11501 //
11502 //  8 * (100 +  %p * %q * (%a + {0, +, 1}_loop))
11503 //
11504 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
11505 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
11506 // parameters as they form a product with an induction variable.
11507 //
11508 // This collector expects all array size parameters to be in the same MulExpr.
11509 // It might be necessary to later add support for collecting parameters that are
11510 // spread over different nested MulExpr.
11511 struct SCEVCollectAddRecMultiplies {
11512   SmallVectorImpl<const SCEV *> &Terms;
11513   ScalarEvolution &SE;
11514 
SCEVCollectAddRecMultiplies__anon83ba15153011::SCEVCollectAddRecMultiplies11515   SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
11516       : Terms(T), SE(SE) {}
11517 
follow__anon83ba15153011::SCEVCollectAddRecMultiplies11518   bool follow(const SCEV *S) {
11519     if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
11520       bool HasAddRec = false;
11521       SmallVector<const SCEV *, 0> Operands;
11522       for (auto Op : Mul->operands()) {
11523         const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
11524         if (Unknown && !isa<CallInst>(Unknown->getValue())) {
11525           Operands.push_back(Op);
11526         } else if (Unknown) {
11527           HasAddRec = true;
11528         } else {
11529           bool ContainsAddRec = false;
11530           SCEVHasAddRec ContiansAddRec(ContainsAddRec);
11531           visitAll(Op, ContiansAddRec);
11532           HasAddRec |= ContainsAddRec;
11533         }
11534       }
11535       if (Operands.size() == 0)
11536         return true;
11537 
11538       if (!HasAddRec)
11539         return false;
11540 
11541       Terms.push_back(SE.getMulExpr(Operands));
11542       // Stop recursion: once we collected a term, do not walk its operands.
11543       return false;
11544     }
11545 
11546     // Keep looking.
11547     return true;
11548   }
11549 
isDone__anon83ba15153011::SCEVCollectAddRecMultiplies11550   bool isDone() const { return false; }
11551 };
11552 
11553 } // end anonymous namespace
11554 
11555 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
11556 /// two places:
11557 ///   1) The strides of AddRec expressions.
11558 ///   2) Unknowns that are multiplied with AddRec expressions.
collectParametricTerms(const SCEV * Expr,SmallVectorImpl<const SCEV * > & Terms)11559 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
11560     SmallVectorImpl<const SCEV *> &Terms) {
11561   SmallVector<const SCEV *, 4> Strides;
11562   SCEVCollectStrides StrideCollector(*this, Strides);
11563   visitAll(Expr, StrideCollector);
11564 
11565   LLVM_DEBUG({
11566     dbgs() << "Strides:\n";
11567     for (const SCEV *S : Strides)
11568       dbgs() << *S << "\n";
11569   });
11570 
11571   for (const SCEV *S : Strides) {
11572     SCEVCollectTerms TermCollector(Terms);
11573     visitAll(S, TermCollector);
11574   }
11575 
11576   LLVM_DEBUG({
11577     dbgs() << "Terms:\n";
11578     for (const SCEV *T : Terms)
11579       dbgs() << *T << "\n";
11580   });
11581 
11582   SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
11583   visitAll(Expr, MulCollector);
11584 }
11585 
findArrayDimensionsRec(ScalarEvolution & SE,SmallVectorImpl<const SCEV * > & Terms,SmallVectorImpl<const SCEV * > & Sizes)11586 static bool findArrayDimensionsRec(ScalarEvolution &SE,
11587                                    SmallVectorImpl<const SCEV *> &Terms,
11588                                    SmallVectorImpl<const SCEV *> &Sizes) {
11589   int Last = Terms.size() - 1;
11590   const SCEV *Step = Terms[Last];
11591 
11592   // End of recursion.
11593   if (Last == 0) {
11594     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
11595       SmallVector<const SCEV *, 2> Qs;
11596       for (const SCEV *Op : M->operands())
11597         if (!isa<SCEVConstant>(Op))
11598           Qs.push_back(Op);
11599 
11600       Step = SE.getMulExpr(Qs);
11601     }
11602 
11603     Sizes.push_back(Step);
11604     return true;
11605   }
11606 
11607   for (const SCEV *&Term : Terms) {
11608     // Normalize the terms before the next call to findArrayDimensionsRec.
11609     const SCEV *Q, *R;
11610     SCEVDivision::divide(SE, Term, Step, &Q, &R);
11611 
11612     // Bail out when GCD does not evenly divide one of the terms.
11613     if (!R->isZero())
11614       return false;
11615 
11616     Term = Q;
11617   }
11618 
11619   // Remove all SCEVConstants.
11620   Terms.erase(
11621       remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
11622       Terms.end());
11623 
11624   if (Terms.size() > 0)
11625     if (!findArrayDimensionsRec(SE, Terms, Sizes))
11626       return false;
11627 
11628   Sizes.push_back(Step);
11629   return true;
11630 }
11631 
11632 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
containsParameters(SmallVectorImpl<const SCEV * > & Terms)11633 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
11634   for (const SCEV *T : Terms)
11635     if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); }))
11636       return true;
11637 
11638   return false;
11639 }
11640 
11641 // Return the number of product terms in S.
numberOfTerms(const SCEV * S)11642 static inline int numberOfTerms(const SCEV *S) {
11643   if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
11644     return Expr->getNumOperands();
11645   return 1;
11646 }
11647 
removeConstantFactors(ScalarEvolution & SE,const SCEV * T)11648 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
11649   if (isa<SCEVConstant>(T))
11650     return nullptr;
11651 
11652   if (isa<SCEVUnknown>(T))
11653     return T;
11654 
11655   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
11656     SmallVector<const SCEV *, 2> Factors;
11657     for (const SCEV *Op : M->operands())
11658       if (!isa<SCEVConstant>(Op))
11659         Factors.push_back(Op);
11660 
11661     return SE.getMulExpr(Factors);
11662   }
11663 
11664   return T;
11665 }
11666 
11667 /// Return the size of an element read or written by Inst.
getElementSize(Instruction * Inst)11668 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
11669   Type *Ty;
11670   if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
11671     Ty = Store->getValueOperand()->getType();
11672   else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
11673     Ty = Load->getType();
11674   else
11675     return nullptr;
11676 
11677   Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
11678   return getSizeOfExpr(ETy, Ty);
11679 }
11680 
findArrayDimensions(SmallVectorImpl<const SCEV * > & Terms,SmallVectorImpl<const SCEV * > & Sizes,const SCEV * ElementSize)11681 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
11682                                           SmallVectorImpl<const SCEV *> &Sizes,
11683                                           const SCEV *ElementSize) {
11684   if (Terms.size() < 1 || !ElementSize)
11685     return;
11686 
11687   // Early return when Terms do not contain parameters: we do not delinearize
11688   // non parametric SCEVs.
11689   if (!containsParameters(Terms))
11690     return;
11691 
11692   LLVM_DEBUG({
11693     dbgs() << "Terms:\n";
11694     for (const SCEV *T : Terms)
11695       dbgs() << *T << "\n";
11696   });
11697 
11698   // Remove duplicates.
11699   array_pod_sort(Terms.begin(), Terms.end());
11700   Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
11701 
11702   // Put larger terms first.
11703   llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) {
11704     return numberOfTerms(LHS) > numberOfTerms(RHS);
11705   });
11706 
11707   // Try to divide all terms by the element size. If term is not divisible by
11708   // element size, proceed with the original term.
11709   for (const SCEV *&Term : Terms) {
11710     const SCEV *Q, *R;
11711     SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
11712     if (!Q->isZero())
11713       Term = Q;
11714   }
11715 
11716   SmallVector<const SCEV *, 4> NewTerms;
11717 
11718   // Remove constant factors.
11719   for (const SCEV *T : Terms)
11720     if (const SCEV *NewT = removeConstantFactors(*this, T))
11721       NewTerms.push_back(NewT);
11722 
11723   LLVM_DEBUG({
11724     dbgs() << "Terms after sorting:\n";
11725     for (const SCEV *T : NewTerms)
11726       dbgs() << *T << "\n";
11727   });
11728 
11729   if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
11730     Sizes.clear();
11731     return;
11732   }
11733 
11734   // The last element to be pushed into Sizes is the size of an element.
11735   Sizes.push_back(ElementSize);
11736 
11737   LLVM_DEBUG({
11738     dbgs() << "Sizes:\n";
11739     for (const SCEV *S : Sizes)
11740       dbgs() << *S << "\n";
11741   });
11742 }
11743 
computeAccessFunctions(const SCEV * Expr,SmallVectorImpl<const SCEV * > & Subscripts,SmallVectorImpl<const SCEV * > & Sizes)11744 void ScalarEvolution::computeAccessFunctions(
11745     const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
11746     SmallVectorImpl<const SCEV *> &Sizes) {
11747   // Early exit in case this SCEV is not an affine multivariate function.
11748   if (Sizes.empty())
11749     return;
11750 
11751   if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
11752     if (!AR->isAffine())
11753       return;
11754 
11755   const SCEV *Res = Expr;
11756   int Last = Sizes.size() - 1;
11757   for (int i = Last; i >= 0; i--) {
11758     const SCEV *Q, *R;
11759     SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
11760 
11761     LLVM_DEBUG({
11762       dbgs() << "Res: " << *Res << "\n";
11763       dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
11764       dbgs() << "Res divided by Sizes[i]:\n";
11765       dbgs() << "Quotient: " << *Q << "\n";
11766       dbgs() << "Remainder: " << *R << "\n";
11767     });
11768 
11769     Res = Q;
11770 
11771     // Do not record the last subscript corresponding to the size of elements in
11772     // the array.
11773     if (i == Last) {
11774 
11775       // Bail out if the remainder is too complex.
11776       if (isa<SCEVAddRecExpr>(R)) {
11777         Subscripts.clear();
11778         Sizes.clear();
11779         return;
11780       }
11781 
11782       continue;
11783     }
11784 
11785     // Record the access function for the current subscript.
11786     Subscripts.push_back(R);
11787   }
11788 
11789   // Also push in last position the remainder of the last division: it will be
11790   // the access function of the innermost dimension.
11791   Subscripts.push_back(Res);
11792 
11793   std::reverse(Subscripts.begin(), Subscripts.end());
11794 
11795   LLVM_DEBUG({
11796     dbgs() << "Subscripts:\n";
11797     for (const SCEV *S : Subscripts)
11798       dbgs() << *S << "\n";
11799   });
11800 }
11801 
11802 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
11803 /// sizes of an array access. Returns the remainder of the delinearization that
11804 /// is the offset start of the array.  The SCEV->delinearize algorithm computes
11805 /// the multiples of SCEV coefficients: that is a pattern matching of sub
11806 /// expressions in the stride and base of a SCEV corresponding to the
11807 /// computation of a GCD (greatest common divisor) of base and stride.  When
11808 /// SCEV->delinearize fails, it returns the SCEV unchanged.
11809 ///
11810 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
11811 ///
11812 ///  void foo(long n, long m, long o, double A[n][m][o]) {
11813 ///
11814 ///    for (long i = 0; i < n; i++)
11815 ///      for (long j = 0; j < m; j++)
11816 ///        for (long k = 0; k < o; k++)
11817 ///          A[i][j][k] = 1.0;
11818 ///  }
11819 ///
11820 /// the delinearization input is the following AddRec SCEV:
11821 ///
11822 ///  AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
11823 ///
11824 /// From this SCEV, we are able to say that the base offset of the access is %A
11825 /// because it appears as an offset that does not divide any of the strides in
11826 /// the loops:
11827 ///
11828 ///  CHECK: Base offset: %A
11829 ///
11830 /// and then SCEV->delinearize determines the size of some of the dimensions of
11831 /// the array as these are the multiples by which the strides are happening:
11832 ///
11833 ///  CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
11834 ///
11835 /// Note that the outermost dimension remains of UnknownSize because there are
11836 /// no strides that would help identifying the size of the last dimension: when
11837 /// the array has been statically allocated, one could compute the size of that
11838 /// dimension by dividing the overall size of the array by the size of the known
11839 /// dimensions: %m * %o * 8.
11840 ///
11841 /// Finally delinearize provides the access functions for the array reference
11842 /// that does correspond to A[i][j][k] of the above C testcase:
11843 ///
11844 ///  CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
11845 ///
11846 /// The testcases are checking the output of a function pass:
11847 /// DelinearizationPass that walks through all loads and stores of a function
11848 /// asking for the SCEV of the memory access with respect to all enclosing
11849 /// loops, calling SCEV->delinearize on that and printing the results.
delinearize(const SCEV * Expr,SmallVectorImpl<const SCEV * > & Subscripts,SmallVectorImpl<const SCEV * > & Sizes,const SCEV * ElementSize)11850 void ScalarEvolution::delinearize(const SCEV *Expr,
11851                                  SmallVectorImpl<const SCEV *> &Subscripts,
11852                                  SmallVectorImpl<const SCEV *> &Sizes,
11853                                  const SCEV *ElementSize) {
11854   // First step: collect parametric terms.
11855   SmallVector<const SCEV *, 4> Terms;
11856   collectParametricTerms(Expr, Terms);
11857 
11858   if (Terms.empty())
11859     return;
11860 
11861   // Second step: find subscript sizes.
11862   findArrayDimensions(Terms, Sizes, ElementSize);
11863 
11864   if (Sizes.empty())
11865     return;
11866 
11867   // Third step: compute the access functions for each subscript.
11868   computeAccessFunctions(Expr, Subscripts, Sizes);
11869 
11870   if (Subscripts.empty())
11871     return;
11872 
11873   LLVM_DEBUG({
11874     dbgs() << "succeeded to delinearize " << *Expr << "\n";
11875     dbgs() << "ArrayDecl[UnknownSize]";
11876     for (const SCEV *S : Sizes)
11877       dbgs() << "[" << *S << "]";
11878 
11879     dbgs() << "\nArrayRef";
11880     for (const SCEV *S : Subscripts)
11881       dbgs() << "[" << *S << "]";
11882     dbgs() << "\n";
11883   });
11884 }
11885 
getIndexExpressionsFromGEP(const GetElementPtrInst * GEP,SmallVectorImpl<const SCEV * > & Subscripts,SmallVectorImpl<int> & Sizes)11886 bool ScalarEvolution::getIndexExpressionsFromGEP(
11887     const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts,
11888     SmallVectorImpl<int> &Sizes) {
11889   assert(Subscripts.empty() && Sizes.empty() &&
11890          "Expected output lists to be empty on entry to this function.");
11891   assert(GEP && "getIndexExpressionsFromGEP called with a null GEP");
11892   Type *Ty = GEP->getPointerOperandType();
11893   bool DroppedFirstDim = false;
11894   for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
11895     const SCEV *Expr = getSCEV(GEP->getOperand(i));
11896     if (i == 1) {
11897       if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
11898         Ty = PtrTy->getElementType();
11899       } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) {
11900         Ty = ArrayTy->getElementType();
11901       } else {
11902         Subscripts.clear();
11903         Sizes.clear();
11904         return false;
11905       }
11906       if (auto *Const = dyn_cast<SCEVConstant>(Expr))
11907         if (Const->getValue()->isZero()) {
11908           DroppedFirstDim = true;
11909           continue;
11910         }
11911       Subscripts.push_back(Expr);
11912       continue;
11913     }
11914 
11915     auto *ArrayTy = dyn_cast<ArrayType>(Ty);
11916     if (!ArrayTy) {
11917       Subscripts.clear();
11918       Sizes.clear();
11919       return false;
11920     }
11921 
11922     Subscripts.push_back(Expr);
11923     if (!(DroppedFirstDim && i == 2))
11924       Sizes.push_back(ArrayTy->getNumElements());
11925 
11926     Ty = ArrayTy->getElementType();
11927   }
11928   return !Subscripts.empty();
11929 }
11930 
11931 //===----------------------------------------------------------------------===//
11932 //                   SCEVCallbackVH Class Implementation
11933 //===----------------------------------------------------------------------===//
11934 
deleted()11935 void ScalarEvolution::SCEVCallbackVH::deleted() {
11936   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
11937   if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
11938     SE->ConstantEvolutionLoopExitValue.erase(PN);
11939   SE->eraseValueFromMap(getValPtr());
11940   // this now dangles!
11941 }
11942 
allUsesReplacedWith(Value * V)11943 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
11944   assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
11945 
11946   // Forget all the expressions associated with users of the old value,
11947   // so that future queries will recompute the expressions using the new
11948   // value.
11949   Value *Old = getValPtr();
11950   SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
11951   SmallPtrSet<User *, 8> Visited;
11952   while (!Worklist.empty()) {
11953     User *U = Worklist.pop_back_val();
11954     // Deleting the Old value will cause this to dangle. Postpone
11955     // that until everything else is done.
11956     if (U == Old)
11957       continue;
11958     if (!Visited.insert(U).second)
11959       continue;
11960     if (PHINode *PN = dyn_cast<PHINode>(U))
11961       SE->ConstantEvolutionLoopExitValue.erase(PN);
11962     SE->eraseValueFromMap(U);
11963     Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
11964   }
11965   // Delete the Old value.
11966   if (PHINode *PN = dyn_cast<PHINode>(Old))
11967     SE->ConstantEvolutionLoopExitValue.erase(PN);
11968   SE->eraseValueFromMap(Old);
11969   // this now dangles!
11970 }
11971 
SCEVCallbackVH(Value * V,ScalarEvolution * se)11972 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
11973   : CallbackVH(V), SE(se) {}
11974 
11975 //===----------------------------------------------------------------------===//
11976 //                   ScalarEvolution Class Implementation
11977 //===----------------------------------------------------------------------===//
11978 
ScalarEvolution(Function & F,TargetLibraryInfo & TLI,AssumptionCache & AC,DominatorTree & DT,LoopInfo & LI)11979 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
11980                                  AssumptionCache &AC, DominatorTree &DT,
11981                                  LoopInfo &LI)
11982     : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
11983       CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
11984       LoopDispositions(64), BlockDispositions(64) {
11985   // To use guards for proving predicates, we need to scan every instruction in
11986   // relevant basic blocks, and not just terminators.  Doing this is a waste of
11987   // time if the IR does not actually contain any calls to
11988   // @llvm.experimental.guard, so do a quick check and remember this beforehand.
11989   //
11990   // This pessimizes the case where a pass that preserves ScalarEvolution wants
11991   // to _add_ guards to the module when there weren't any before, and wants
11992   // ScalarEvolution to optimize based on those guards.  For now we prefer to be
11993   // efficient in lieu of being smart in that rather obscure case.
11994 
11995   auto *GuardDecl = F.getParent()->getFunction(
11996       Intrinsic::getName(Intrinsic::experimental_guard));
11997   HasGuards = GuardDecl && !GuardDecl->use_empty();
11998 }
11999 
ScalarEvolution(ScalarEvolution && Arg)12000 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
12001     : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
12002       LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
12003       ValueExprMap(std::move(Arg.ValueExprMap)),
12004       PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
12005       PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
12006       PendingMerges(std::move(Arg.PendingMerges)),
12007       MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
12008       BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
12009       PredicatedBackedgeTakenCounts(
12010           std::move(Arg.PredicatedBackedgeTakenCounts)),
12011       ConstantEvolutionLoopExitValue(
12012           std::move(Arg.ConstantEvolutionLoopExitValue)),
12013       ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
12014       LoopDispositions(std::move(Arg.LoopDispositions)),
12015       LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
12016       BlockDispositions(std::move(Arg.BlockDispositions)),
12017       UnsignedRanges(std::move(Arg.UnsignedRanges)),
12018       SignedRanges(std::move(Arg.SignedRanges)),
12019       UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
12020       UniquePreds(std::move(Arg.UniquePreds)),
12021       SCEVAllocator(std::move(Arg.SCEVAllocator)),
12022       LoopUsers(std::move(Arg.LoopUsers)),
12023       PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
12024       FirstUnknown(Arg.FirstUnknown) {
12025   Arg.FirstUnknown = nullptr;
12026 }
12027 
~ScalarEvolution()12028 ScalarEvolution::~ScalarEvolution() {
12029   // Iterate through all the SCEVUnknown instances and call their
12030   // destructors, so that they release their references to their values.
12031   for (SCEVUnknown *U = FirstUnknown; U;) {
12032     SCEVUnknown *Tmp = U;
12033     U = U->Next;
12034     Tmp->~SCEVUnknown();
12035   }
12036   FirstUnknown = nullptr;
12037 
12038   ExprValueMap.clear();
12039   ValueExprMap.clear();
12040   HasRecMap.clear();
12041 
12042   // Free any extra memory created for ExitNotTakenInfo in the unlikely event
12043   // that a loop had multiple computable exits.
12044   for (auto &BTCI : BackedgeTakenCounts)
12045     BTCI.second.clear();
12046   for (auto &BTCI : PredicatedBackedgeTakenCounts)
12047     BTCI.second.clear();
12048 
12049   assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
12050   assert(PendingPhiRanges.empty() && "getRangeRef garbage");
12051   assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
12052   assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
12053   assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
12054 }
12055 
hasLoopInvariantBackedgeTakenCount(const Loop * L)12056 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
12057   return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
12058 }
12059 
PrintLoopInfo(raw_ostream & OS,ScalarEvolution * SE,const Loop * L)12060 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
12061                           const Loop *L) {
12062   // Print all inner loops first
12063   for (Loop *I : *L)
12064     PrintLoopInfo(OS, SE, I);
12065 
12066   OS << "Loop ";
12067   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12068   OS << ": ";
12069 
12070   SmallVector<BasicBlock *, 8> ExitingBlocks;
12071   L->getExitingBlocks(ExitingBlocks);
12072   if (ExitingBlocks.size() != 1)
12073     OS << "<multiple exits> ";
12074 
12075   if (SE->hasLoopInvariantBackedgeTakenCount(L))
12076     OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
12077   else
12078     OS << "Unpredictable backedge-taken count.\n";
12079 
12080   if (ExitingBlocks.size() > 1)
12081     for (BasicBlock *ExitingBlock : ExitingBlocks) {
12082       OS << "  exit count for " << ExitingBlock->getName() << ": "
12083          << *SE->getExitCount(L, ExitingBlock) << "\n";
12084     }
12085 
12086   OS << "Loop ";
12087   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12088   OS << ": ";
12089 
12090   if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) {
12091     OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L);
12092     if (SE->isBackedgeTakenCountMaxOrZero(L))
12093       OS << ", actual taken count either this or zero.";
12094   } else {
12095     OS << "Unpredictable max backedge-taken count. ";
12096   }
12097 
12098   OS << "\n"
12099         "Loop ";
12100   L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12101   OS << ": ";
12102 
12103   SCEVUnionPredicate Pred;
12104   auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
12105   if (!isa<SCEVCouldNotCompute>(PBT)) {
12106     OS << "Predicated backedge-taken count is " << *PBT << "\n";
12107     OS << " Predicates:\n";
12108     Pred.print(OS, 4);
12109   } else {
12110     OS << "Unpredictable predicated backedge-taken count. ";
12111   }
12112   OS << "\n";
12113 
12114   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
12115     OS << "Loop ";
12116     L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12117     OS << ": ";
12118     OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
12119   }
12120 }
12121 
loopDispositionToStr(ScalarEvolution::LoopDisposition LD)12122 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
12123   switch (LD) {
12124   case ScalarEvolution::LoopVariant:
12125     return "Variant";
12126   case ScalarEvolution::LoopInvariant:
12127     return "Invariant";
12128   case ScalarEvolution::LoopComputable:
12129     return "Computable";
12130   }
12131   llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
12132 }
12133 
print(raw_ostream & OS) const12134 void ScalarEvolution::print(raw_ostream &OS) const {
12135   // ScalarEvolution's implementation of the print method is to print
12136   // out SCEV values of all instructions that are interesting. Doing
12137   // this potentially causes it to create new SCEV objects though,
12138   // which technically conflicts with the const qualifier. This isn't
12139   // observable from outside the class though, so casting away the
12140   // const isn't dangerous.
12141   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12142 
12143   if (ClassifyExpressions) {
12144     OS << "Classifying expressions for: ";
12145     F.printAsOperand(OS, /*PrintType=*/false);
12146     OS << "\n";
12147     for (Instruction &I : instructions(F))
12148       if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
12149         OS << I << '\n';
12150         OS << "  -->  ";
12151         const SCEV *SV = SE.getSCEV(&I);
12152         SV->print(OS);
12153         if (!isa<SCEVCouldNotCompute>(SV)) {
12154           OS << " U: ";
12155           SE.getUnsignedRange(SV).print(OS);
12156           OS << " S: ";
12157           SE.getSignedRange(SV).print(OS);
12158         }
12159 
12160         const Loop *L = LI.getLoopFor(I.getParent());
12161 
12162         const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
12163         if (AtUse != SV) {
12164           OS << "  -->  ";
12165           AtUse->print(OS);
12166           if (!isa<SCEVCouldNotCompute>(AtUse)) {
12167             OS << " U: ";
12168             SE.getUnsignedRange(AtUse).print(OS);
12169             OS << " S: ";
12170             SE.getSignedRange(AtUse).print(OS);
12171           }
12172         }
12173 
12174         if (L) {
12175           OS << "\t\t" "Exits: ";
12176           const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
12177           if (!SE.isLoopInvariant(ExitValue, L)) {
12178             OS << "<<Unknown>>";
12179           } else {
12180             OS << *ExitValue;
12181           }
12182 
12183           bool First = true;
12184           for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
12185             if (First) {
12186               OS << "\t\t" "LoopDispositions: { ";
12187               First = false;
12188             } else {
12189               OS << ", ";
12190             }
12191 
12192             Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12193             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
12194           }
12195 
12196           for (auto *InnerL : depth_first(L)) {
12197             if (InnerL == L)
12198               continue;
12199             if (First) {
12200               OS << "\t\t" "LoopDispositions: { ";
12201               First = false;
12202             } else {
12203               OS << ", ";
12204             }
12205 
12206             InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12207             OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
12208           }
12209 
12210           OS << " }";
12211         }
12212 
12213         OS << "\n";
12214       }
12215   }
12216 
12217   OS << "Determining loop execution counts for: ";
12218   F.printAsOperand(OS, /*PrintType=*/false);
12219   OS << "\n";
12220   for (Loop *I : LI)
12221     PrintLoopInfo(OS, &SE, I);
12222 }
12223 
12224 ScalarEvolution::LoopDisposition
getLoopDisposition(const SCEV * S,const Loop * L)12225 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
12226   auto &Values = LoopDispositions[S];
12227   for (auto &V : Values) {
12228     if (V.getPointer() == L)
12229       return V.getInt();
12230   }
12231   Values.emplace_back(L, LoopVariant);
12232   LoopDisposition D = computeLoopDisposition(S, L);
12233   auto &Values2 = LoopDispositions[S];
12234   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
12235     if (V.getPointer() == L) {
12236       V.setInt(D);
12237       break;
12238     }
12239   }
12240   return D;
12241 }
12242 
12243 ScalarEvolution::LoopDisposition
computeLoopDisposition(const SCEV * S,const Loop * L)12244 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
12245   switch (S->getSCEVType()) {
12246   case scConstant:
12247     return LoopInvariant;
12248   case scPtrToInt:
12249   case scTruncate:
12250   case scZeroExtend:
12251   case scSignExtend:
12252     return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
12253   case scAddRecExpr: {
12254     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12255 
12256     // If L is the addrec's loop, it's computable.
12257     if (AR->getLoop() == L)
12258       return LoopComputable;
12259 
12260     // Add recurrences are never invariant in the function-body (null loop).
12261     if (!L)
12262       return LoopVariant;
12263 
12264     // Everything that is not defined at loop entry is variant.
12265     if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
12266       return LoopVariant;
12267     assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
12268            " dominate the contained loop's header?");
12269 
12270     // This recurrence is invariant w.r.t. L if AR's loop contains L.
12271     if (AR->getLoop()->contains(L))
12272       return LoopInvariant;
12273 
12274     // This recurrence is variant w.r.t. L if any of its operands
12275     // are variant.
12276     for (auto *Op : AR->operands())
12277       if (!isLoopInvariant(Op, L))
12278         return LoopVariant;
12279 
12280     // Otherwise it's loop-invariant.
12281     return LoopInvariant;
12282   }
12283   case scAddExpr:
12284   case scMulExpr:
12285   case scUMaxExpr:
12286   case scSMaxExpr:
12287   case scUMinExpr:
12288   case scSMinExpr: {
12289     bool HasVarying = false;
12290     for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
12291       LoopDisposition D = getLoopDisposition(Op, L);
12292       if (D == LoopVariant)
12293         return LoopVariant;
12294       if (D == LoopComputable)
12295         HasVarying = true;
12296     }
12297     return HasVarying ? LoopComputable : LoopInvariant;
12298   }
12299   case scUDivExpr: {
12300     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12301     LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
12302     if (LD == LoopVariant)
12303       return LoopVariant;
12304     LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
12305     if (RD == LoopVariant)
12306       return LoopVariant;
12307     return (LD == LoopInvariant && RD == LoopInvariant) ?
12308            LoopInvariant : LoopComputable;
12309   }
12310   case scUnknown:
12311     // All non-instruction values are loop invariant.  All instructions are loop
12312     // invariant if they are not contained in the specified loop.
12313     // Instructions are never considered invariant in the function body
12314     // (null loop) because they are defined within the "loop".
12315     if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
12316       return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
12317     return LoopInvariant;
12318   case scCouldNotCompute:
12319     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12320   }
12321   llvm_unreachable("Unknown SCEV kind!");
12322 }
12323 
isLoopInvariant(const SCEV * S,const Loop * L)12324 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
12325   return getLoopDisposition(S, L) == LoopInvariant;
12326 }
12327 
hasComputableLoopEvolution(const SCEV * S,const Loop * L)12328 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
12329   return getLoopDisposition(S, L) == LoopComputable;
12330 }
12331 
12332 ScalarEvolution::BlockDisposition
getBlockDisposition(const SCEV * S,const BasicBlock * BB)12333 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12334   auto &Values = BlockDispositions[S];
12335   for (auto &V : Values) {
12336     if (V.getPointer() == BB)
12337       return V.getInt();
12338   }
12339   Values.emplace_back(BB, DoesNotDominateBlock);
12340   BlockDisposition D = computeBlockDisposition(S, BB);
12341   auto &Values2 = BlockDispositions[S];
12342   for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
12343     if (V.getPointer() == BB) {
12344       V.setInt(D);
12345       break;
12346     }
12347   }
12348   return D;
12349 }
12350 
12351 ScalarEvolution::BlockDisposition
computeBlockDisposition(const SCEV * S,const BasicBlock * BB)12352 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12353   switch (S->getSCEVType()) {
12354   case scConstant:
12355     return ProperlyDominatesBlock;
12356   case scPtrToInt:
12357   case scTruncate:
12358   case scZeroExtend:
12359   case scSignExtend:
12360     return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
12361   case scAddRecExpr: {
12362     // This uses a "dominates" query instead of "properly dominates" query
12363     // to test for proper dominance too, because the instruction which
12364     // produces the addrec's value is a PHI, and a PHI effectively properly
12365     // dominates its entire containing block.
12366     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12367     if (!DT.dominates(AR->getLoop()->getHeader(), BB))
12368       return DoesNotDominateBlock;
12369 
12370     // Fall through into SCEVNAryExpr handling.
12371     LLVM_FALLTHROUGH;
12372   }
12373   case scAddExpr:
12374   case scMulExpr:
12375   case scUMaxExpr:
12376   case scSMaxExpr:
12377   case scUMinExpr:
12378   case scSMinExpr: {
12379     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
12380     bool Proper = true;
12381     for (const SCEV *NAryOp : NAry->operands()) {
12382       BlockDisposition D = getBlockDisposition(NAryOp, BB);
12383       if (D == DoesNotDominateBlock)
12384         return DoesNotDominateBlock;
12385       if (D == DominatesBlock)
12386         Proper = false;
12387     }
12388     return Proper ? ProperlyDominatesBlock : DominatesBlock;
12389   }
12390   case scUDivExpr: {
12391     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12392     const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
12393     BlockDisposition LD = getBlockDisposition(LHS, BB);
12394     if (LD == DoesNotDominateBlock)
12395       return DoesNotDominateBlock;
12396     BlockDisposition RD = getBlockDisposition(RHS, BB);
12397     if (RD == DoesNotDominateBlock)
12398       return DoesNotDominateBlock;
12399     return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
12400       ProperlyDominatesBlock : DominatesBlock;
12401   }
12402   case scUnknown:
12403     if (Instruction *I =
12404           dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
12405       if (I->getParent() == BB)
12406         return DominatesBlock;
12407       if (DT.properlyDominates(I->getParent(), BB))
12408         return ProperlyDominatesBlock;
12409       return DoesNotDominateBlock;
12410     }
12411     return ProperlyDominatesBlock;
12412   case scCouldNotCompute:
12413     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
12414   }
12415   llvm_unreachable("Unknown SCEV kind!");
12416 }
12417 
dominates(const SCEV * S,const BasicBlock * BB)12418 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
12419   return getBlockDisposition(S, BB) >= DominatesBlock;
12420 }
12421 
properlyDominates(const SCEV * S,const BasicBlock * BB)12422 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
12423   return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
12424 }
12425 
hasOperand(const SCEV * S,const SCEV * Op) const12426 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
12427   return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
12428 }
12429 
hasOperand(const SCEV * S) const12430 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const {
12431   auto IsS = [&](const SCEV *X) { return S == X; };
12432   auto ContainsS = [&](const SCEV *X) {
12433     return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS);
12434   };
12435   return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
12436 }
12437 
12438 void
forgetMemoizedResults(const SCEV * S)12439 ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
12440   ValuesAtScopes.erase(S);
12441   LoopDispositions.erase(S);
12442   BlockDispositions.erase(S);
12443   UnsignedRanges.erase(S);
12444   SignedRanges.erase(S);
12445   ExprValueMap.erase(S);
12446   HasRecMap.erase(S);
12447   MinTrailingZerosCache.erase(S);
12448 
12449   for (auto I = PredicatedSCEVRewrites.begin();
12450        I != PredicatedSCEVRewrites.end();) {
12451     std::pair<const SCEV *, const Loop *> Entry = I->first;
12452     if (Entry.first == S)
12453       PredicatedSCEVRewrites.erase(I++);
12454     else
12455       ++I;
12456   }
12457 
12458   auto RemoveSCEVFromBackedgeMap =
12459       [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
12460         for (auto I = Map.begin(), E = Map.end(); I != E;) {
12461           BackedgeTakenInfo &BEInfo = I->second;
12462           if (BEInfo.hasOperand(S, this)) {
12463             BEInfo.clear();
12464             Map.erase(I++);
12465           } else
12466             ++I;
12467         }
12468       };
12469 
12470   RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
12471   RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
12472 }
12473 
12474 void
getUsedLoops(const SCEV * S,SmallPtrSetImpl<const Loop * > & LoopsUsed)12475 ScalarEvolution::getUsedLoops(const SCEV *S,
12476                               SmallPtrSetImpl<const Loop *> &LoopsUsed) {
12477   struct FindUsedLoops {
12478     FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
12479         : LoopsUsed(LoopsUsed) {}
12480     SmallPtrSetImpl<const Loop *> &LoopsUsed;
12481     bool follow(const SCEV *S) {
12482       if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
12483         LoopsUsed.insert(AR->getLoop());
12484       return true;
12485     }
12486 
12487     bool isDone() const { return false; }
12488   };
12489 
12490   FindUsedLoops F(LoopsUsed);
12491   SCEVTraversal<FindUsedLoops>(F).visitAll(S);
12492 }
12493 
addToLoopUseLists(const SCEV * S)12494 void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
12495   SmallPtrSet<const Loop *, 8> LoopsUsed;
12496   getUsedLoops(S, LoopsUsed);
12497   for (auto *L : LoopsUsed)
12498     LoopUsers[L].push_back(S);
12499 }
12500 
verify() const12501 void ScalarEvolution::verify() const {
12502   ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12503   ScalarEvolution SE2(F, TLI, AC, DT, LI);
12504 
12505   SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
12506 
12507   // Map's SCEV expressions from one ScalarEvolution "universe" to another.
12508   struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
12509     SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
12510 
12511     const SCEV *visitConstant(const SCEVConstant *Constant) {
12512       return SE.getConstant(Constant->getAPInt());
12513     }
12514 
12515     const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12516       return SE.getUnknown(Expr->getValue());
12517     }
12518 
12519     const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
12520       return SE.getCouldNotCompute();
12521     }
12522   };
12523 
12524   SCEVMapper SCM(SE2);
12525 
12526   while (!LoopStack.empty()) {
12527     auto *L = LoopStack.pop_back_val();
12528     LoopStack.insert(LoopStack.end(), L->begin(), L->end());
12529 
12530     auto *CurBECount = SCM.visit(
12531         const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
12532     auto *NewBECount = SE2.getBackedgeTakenCount(L);
12533 
12534     if (CurBECount == SE2.getCouldNotCompute() ||
12535         NewBECount == SE2.getCouldNotCompute()) {
12536       // NB! This situation is legal, but is very suspicious -- whatever pass
12537       // change the loop to make a trip count go from could not compute to
12538       // computable or vice-versa *should have* invalidated SCEV.  However, we
12539       // choose not to assert here (for now) since we don't want false
12540       // positives.
12541       continue;
12542     }
12543 
12544     if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
12545       // SCEV treats "undef" as an unknown but consistent value (i.e. it does
12546       // not propagate undef aggressively).  This means we can (and do) fail
12547       // verification in cases where a transform makes the trip count of a loop
12548       // go from "undef" to "undef+1" (say).  The transform is fine, since in
12549       // both cases the loop iterates "undef" times, but SCEV thinks we
12550       // increased the trip count of the loop by 1 incorrectly.
12551       continue;
12552     }
12553 
12554     if (SE.getTypeSizeInBits(CurBECount->getType()) >
12555         SE.getTypeSizeInBits(NewBECount->getType()))
12556       NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
12557     else if (SE.getTypeSizeInBits(CurBECount->getType()) <
12558              SE.getTypeSizeInBits(NewBECount->getType()))
12559       CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
12560 
12561     const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount);
12562 
12563     // Unless VerifySCEVStrict is set, we only compare constant deltas.
12564     if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) {
12565       dbgs() << "Trip Count for " << *L << " Changed!\n";
12566       dbgs() << "Old: " << *CurBECount << "\n";
12567       dbgs() << "New: " << *NewBECount << "\n";
12568       dbgs() << "Delta: " << *Delta << "\n";
12569       std::abort();
12570     }
12571   }
12572 
12573   // Collect all valid loops currently in LoopInfo.
12574   SmallPtrSet<Loop *, 32> ValidLoops;
12575   SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
12576   while (!Worklist.empty()) {
12577     Loop *L = Worklist.pop_back_val();
12578     if (ValidLoops.contains(L))
12579       continue;
12580     ValidLoops.insert(L);
12581     Worklist.append(L->begin(), L->end());
12582   }
12583   // Check for SCEV expressions referencing invalid/deleted loops.
12584   for (auto &KV : ValueExprMap) {
12585     auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second);
12586     if (!AR)
12587       continue;
12588     assert(ValidLoops.contains(AR->getLoop()) &&
12589            "AddRec references invalid loop");
12590   }
12591 }
12592 
invalidate(Function & F,const PreservedAnalyses & PA,FunctionAnalysisManager::Invalidator & Inv)12593 bool ScalarEvolution::invalidate(
12594     Function &F, const PreservedAnalyses &PA,
12595     FunctionAnalysisManager::Invalidator &Inv) {
12596   // Invalidate the ScalarEvolution object whenever it isn't preserved or one
12597   // of its dependencies is invalidated.
12598   auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
12599   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
12600          Inv.invalidate<AssumptionAnalysis>(F, PA) ||
12601          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
12602          Inv.invalidate<LoopAnalysis>(F, PA);
12603 }
12604 
12605 AnalysisKey ScalarEvolutionAnalysis::Key;
12606 
run(Function & F,FunctionAnalysisManager & AM)12607 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
12608                                              FunctionAnalysisManager &AM) {
12609   return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
12610                          AM.getResult<AssumptionAnalysis>(F),
12611                          AM.getResult<DominatorTreeAnalysis>(F),
12612                          AM.getResult<LoopAnalysis>(F));
12613 }
12614 
12615 PreservedAnalyses
run(Function & F,FunctionAnalysisManager & AM)12616 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
12617   AM.getResult<ScalarEvolutionAnalysis>(F).verify();
12618   return PreservedAnalyses::all();
12619 }
12620 
12621 PreservedAnalyses
run(Function & F,FunctionAnalysisManager & AM)12622 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
12623   // For compatibility with opt's -analyze feature under legacy pass manager
12624   // which was not ported to NPM. This keeps tests using
12625   // update_analyze_test_checks.py working.
12626   OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
12627      << F.getName() << "':\n";
12628   AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
12629   return PreservedAnalyses::all();
12630 }
12631 
12632 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
12633                       "Scalar Evolution Analysis", false, true)
12634 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
12635 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
12636 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
12637 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
12638 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
12639                     "Scalar Evolution Analysis", false, true)
12640 
12641 char ScalarEvolutionWrapperPass::ID = 0;
12642 
ScalarEvolutionWrapperPass()12643 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
12644   initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
12645 }
12646 
runOnFunction(Function & F)12647 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
12648   SE.reset(new ScalarEvolution(
12649       F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
12650       getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
12651       getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
12652       getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
12653   return false;
12654 }
12655 
releaseMemory()12656 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
12657 
print(raw_ostream & OS,const Module *) const12658 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
12659   SE->print(OS);
12660 }
12661 
verifyAnalysis() const12662 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
12663   if (!VerifySCEV)
12664     return;
12665 
12666   SE->verify();
12667 }
12668 
getAnalysisUsage(AnalysisUsage & AU) const12669 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
12670   AU.setPreservesAll();
12671   AU.addRequiredTransitive<AssumptionCacheTracker>();
12672   AU.addRequiredTransitive<LoopInfoWrapperPass>();
12673   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
12674   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
12675 }
12676 
getEqualPredicate(const SCEV * LHS,const SCEV * RHS)12677 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
12678                                                         const SCEV *RHS) {
12679   FoldingSetNodeID ID;
12680   assert(LHS->getType() == RHS->getType() &&
12681          "Type mismatch between LHS and RHS");
12682   // Unique this node based on the arguments
12683   ID.AddInteger(SCEVPredicate::P_Equal);
12684   ID.AddPointer(LHS);
12685   ID.AddPointer(RHS);
12686   void *IP = nullptr;
12687   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12688     return S;
12689   SCEVEqualPredicate *Eq = new (SCEVAllocator)
12690       SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
12691   UniquePreds.InsertNode(Eq, IP);
12692   return Eq;
12693 }
12694 
getWrapPredicate(const SCEVAddRecExpr * AR,SCEVWrapPredicate::IncrementWrapFlags AddedFlags)12695 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
12696     const SCEVAddRecExpr *AR,
12697     SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12698   FoldingSetNodeID ID;
12699   // Unique this node based on the arguments
12700   ID.AddInteger(SCEVPredicate::P_Wrap);
12701   ID.AddPointer(AR);
12702   ID.AddInteger(AddedFlags);
12703   void *IP = nullptr;
12704   if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12705     return S;
12706   auto *OF = new (SCEVAllocator)
12707       SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
12708   UniquePreds.InsertNode(OF, IP);
12709   return OF;
12710 }
12711 
12712 namespace {
12713 
12714 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
12715 public:
12716 
12717   /// Rewrites \p S in the context of a loop L and the SCEV predication
12718   /// infrastructure.
12719   ///
12720   /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
12721   /// equivalences present in \p Pred.
12722   ///
12723   /// If \p NewPreds is non-null, rewrite is free to add further predicates to
12724   /// \p NewPreds such that the result will be an AddRecExpr.
rewrite(const SCEV * S,const Loop * L,ScalarEvolution & SE,SmallPtrSetImpl<const SCEVPredicate * > * NewPreds,SCEVUnionPredicate * Pred)12725   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
12726                              SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12727                              SCEVUnionPredicate *Pred) {
12728     SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
12729     return Rewriter.visit(S);
12730   }
12731 
visitUnknown(const SCEVUnknown * Expr)12732   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12733     if (Pred) {
12734       auto ExprPreds = Pred->getPredicatesForExpr(Expr);
12735       for (auto *Pred : ExprPreds)
12736         if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
12737           if (IPred->getLHS() == Expr)
12738             return IPred->getRHS();
12739     }
12740     return convertToAddRecWithPreds(Expr);
12741   }
12742 
visitZeroExtendExpr(const SCEVZeroExtendExpr * Expr)12743   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
12744     const SCEV *Operand = visit(Expr->getOperand());
12745     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12746     if (AR && AR->getLoop() == L && AR->isAffine()) {
12747       // This couldn't be folded because the operand didn't have the nuw
12748       // flag. Add the nusw flag as an assumption that we could make.
12749       const SCEV *Step = AR->getStepRecurrence(SE);
12750       Type *Ty = Expr->getType();
12751       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
12752         return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
12753                                 SE.getSignExtendExpr(Step, Ty), L,
12754                                 AR->getNoWrapFlags());
12755     }
12756     return SE.getZeroExtendExpr(Operand, Expr->getType());
12757   }
12758 
visitSignExtendExpr(const SCEVSignExtendExpr * Expr)12759   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
12760     const SCEV *Operand = visit(Expr->getOperand());
12761     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12762     if (AR && AR->getLoop() == L && AR->isAffine()) {
12763       // This couldn't be folded because the operand didn't have the nsw
12764       // flag. Add the nssw flag as an assumption that we could make.
12765       const SCEV *Step = AR->getStepRecurrence(SE);
12766       Type *Ty = Expr->getType();
12767       if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
12768         return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
12769                                 SE.getSignExtendExpr(Step, Ty), L,
12770                                 AR->getNoWrapFlags());
12771     }
12772     return SE.getSignExtendExpr(Operand, Expr->getType());
12773   }
12774 
12775 private:
SCEVPredicateRewriter(const Loop * L,ScalarEvolution & SE,SmallPtrSetImpl<const SCEVPredicate * > * NewPreds,SCEVUnionPredicate * Pred)12776   explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
12777                         SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12778                         SCEVUnionPredicate *Pred)
12779       : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
12780 
addOverflowAssumption(const SCEVPredicate * P)12781   bool addOverflowAssumption(const SCEVPredicate *P) {
12782     if (!NewPreds) {
12783       // Check if we've already made this assumption.
12784       return Pred && Pred->implies(P);
12785     }
12786     NewPreds->insert(P);
12787     return true;
12788   }
12789 
addOverflowAssumption(const SCEVAddRecExpr * AR,SCEVWrapPredicate::IncrementWrapFlags AddedFlags)12790   bool addOverflowAssumption(const SCEVAddRecExpr *AR,
12791                              SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12792     auto *A = SE.getWrapPredicate(AR, AddedFlags);
12793     return addOverflowAssumption(A);
12794   }
12795 
12796   // If \p Expr represents a PHINode, we try to see if it can be represented
12797   // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
12798   // to add this predicate as a runtime overflow check, we return the AddRec.
12799   // If \p Expr does not meet these conditions (is not a PHI node, or we
12800   // couldn't create an AddRec for it, or couldn't add the predicate), we just
12801   // return \p Expr.
convertToAddRecWithPreds(const SCEVUnknown * Expr)12802   const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
12803     if (!isa<PHINode>(Expr->getValue()))
12804       return Expr;
12805     Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
12806     PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
12807     if (!PredicatedRewrite)
12808       return Expr;
12809     for (auto *P : PredicatedRewrite->second){
12810       // Wrap predicates from outer loops are not supported.
12811       if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
12812         auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
12813         if (L != AR->getLoop())
12814           return Expr;
12815       }
12816       if (!addOverflowAssumption(P))
12817         return Expr;
12818     }
12819     return PredicatedRewrite->first;
12820   }
12821 
12822   SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
12823   SCEVUnionPredicate *Pred;
12824   const Loop *L;
12825 };
12826 
12827 } // end anonymous namespace
12828 
rewriteUsingPredicate(const SCEV * S,const Loop * L,SCEVUnionPredicate & Preds)12829 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
12830                                                    SCEVUnionPredicate &Preds) {
12831   return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
12832 }
12833 
convertSCEVToAddRecWithPredicates(const SCEV * S,const Loop * L,SmallPtrSetImpl<const SCEVPredicate * > & Preds)12834 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
12835     const SCEV *S, const Loop *L,
12836     SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
12837   SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
12838   S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
12839   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
12840 
12841   if (!AddRec)
12842     return nullptr;
12843 
12844   // Since the transformation was successful, we can now transfer the SCEV
12845   // predicates.
12846   for (auto *P : TransformPreds)
12847     Preds.insert(P);
12848 
12849   return AddRec;
12850 }
12851 
12852 /// SCEV predicates
SCEVPredicate(const FoldingSetNodeIDRef ID,SCEVPredicateKind Kind)12853 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
12854                              SCEVPredicateKind Kind)
12855     : FastID(ID), Kind(Kind) {}
12856 
SCEVEqualPredicate(const FoldingSetNodeIDRef ID,const SCEV * LHS,const SCEV * RHS)12857 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
12858                                        const SCEV *LHS, const SCEV *RHS)
12859     : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
12860   assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
12861   assert(LHS != RHS && "LHS and RHS are the same SCEV");
12862 }
12863 
implies(const SCEVPredicate * N) const12864 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
12865   const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
12866 
12867   if (!Op)
12868     return false;
12869 
12870   return Op->LHS == LHS && Op->RHS == RHS;
12871 }
12872 
isAlwaysTrue() const12873 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
12874 
getExpr() const12875 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
12876 
print(raw_ostream & OS,unsigned Depth) const12877 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
12878   OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
12879 }
12880 
SCEVWrapPredicate(const FoldingSetNodeIDRef ID,const SCEVAddRecExpr * AR,IncrementWrapFlags Flags)12881 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
12882                                      const SCEVAddRecExpr *AR,
12883                                      IncrementWrapFlags Flags)
12884     : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
12885 
getExpr() const12886 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
12887 
implies(const SCEVPredicate * N) const12888 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
12889   const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
12890 
12891   return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
12892 }
12893 
isAlwaysTrue() const12894 bool SCEVWrapPredicate::isAlwaysTrue() const {
12895   SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
12896   IncrementWrapFlags IFlags = Flags;
12897 
12898   if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
12899     IFlags = clearFlags(IFlags, IncrementNSSW);
12900 
12901   return IFlags == IncrementAnyWrap;
12902 }
12903 
print(raw_ostream & OS,unsigned Depth) const12904 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
12905   OS.indent(Depth) << *getExpr() << " Added Flags: ";
12906   if (SCEVWrapPredicate::IncrementNUSW & getFlags())
12907     OS << "<nusw>";
12908   if (SCEVWrapPredicate::IncrementNSSW & getFlags())
12909     OS << "<nssw>";
12910   OS << "\n";
12911 }
12912 
12913 SCEVWrapPredicate::IncrementWrapFlags
getImpliedFlags(const SCEVAddRecExpr * AR,ScalarEvolution & SE)12914 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
12915                                    ScalarEvolution &SE) {
12916   IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
12917   SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
12918 
12919   // We can safely transfer the NSW flag as NSSW.
12920   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
12921     ImpliedFlags = IncrementNSSW;
12922 
12923   if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
12924     // If the increment is positive, the SCEV NUW flag will also imply the
12925     // WrapPredicate NUSW flag.
12926     if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
12927       if (Step->getValue()->getValue().isNonNegative())
12928         ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
12929   }
12930 
12931   return ImpliedFlags;
12932 }
12933 
12934 /// Union predicates don't get cached so create a dummy set ID for it.
SCEVUnionPredicate()12935 SCEVUnionPredicate::SCEVUnionPredicate()
12936     : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
12937 
isAlwaysTrue() const12938 bool SCEVUnionPredicate::isAlwaysTrue() const {
12939   return all_of(Preds,
12940                 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
12941 }
12942 
12943 ArrayRef<const SCEVPredicate *>
getPredicatesForExpr(const SCEV * Expr)12944 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
12945   auto I = SCEVToPreds.find(Expr);
12946   if (I == SCEVToPreds.end())
12947     return ArrayRef<const SCEVPredicate *>();
12948   return I->second;
12949 }
12950 
implies(const SCEVPredicate * N) const12951 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
12952   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
12953     return all_of(Set->Preds,
12954                   [this](const SCEVPredicate *I) { return this->implies(I); });
12955 
12956   auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
12957   if (ScevPredsIt == SCEVToPreds.end())
12958     return false;
12959   auto &SCEVPreds = ScevPredsIt->second;
12960 
12961   return any_of(SCEVPreds,
12962                 [N](const SCEVPredicate *I) { return I->implies(N); });
12963 }
12964 
getExpr() const12965 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
12966 
print(raw_ostream & OS,unsigned Depth) const12967 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
12968   for (auto Pred : Preds)
12969     Pred->print(OS, Depth);
12970 }
12971 
add(const SCEVPredicate * N)12972 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
12973   if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
12974     for (auto Pred : Set->Preds)
12975       add(Pred);
12976     return;
12977   }
12978 
12979   if (implies(N))
12980     return;
12981 
12982   const SCEV *Key = N->getExpr();
12983   assert(Key && "Only SCEVUnionPredicate doesn't have an "
12984                 " associated expression!");
12985 
12986   SCEVToPreds[Key].push_back(N);
12987   Preds.push_back(N);
12988 }
12989 
PredicatedScalarEvolution(ScalarEvolution & SE,Loop & L)12990 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
12991                                                      Loop &L)
12992     : SE(SE), L(L) {}
12993 
getSCEV(Value * V)12994 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
12995   const SCEV *Expr = SE.getSCEV(V);
12996   RewriteEntry &Entry = RewriteMap[Expr];
12997 
12998   // If we already have an entry and the version matches, return it.
12999   if (Entry.second && Generation == Entry.first)
13000     return Entry.second;
13001 
13002   // We found an entry but it's stale. Rewrite the stale entry
13003   // according to the current predicate.
13004   if (Entry.second)
13005     Expr = Entry.second;
13006 
13007   const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
13008   Entry = {Generation, NewSCEV};
13009 
13010   return NewSCEV;
13011 }
13012 
getBackedgeTakenCount()13013 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
13014   if (!BackedgeCount) {
13015     SCEVUnionPredicate BackedgePred;
13016     BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
13017     addPredicate(BackedgePred);
13018   }
13019   return BackedgeCount;
13020 }
13021 
addPredicate(const SCEVPredicate & Pred)13022 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
13023   if (Preds.implies(&Pred))
13024     return;
13025   Preds.add(&Pred);
13026   updateGeneration();
13027 }
13028 
getUnionPredicate() const13029 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
13030   return Preds;
13031 }
13032 
updateGeneration()13033 void PredicatedScalarEvolution::updateGeneration() {
13034   // If the generation number wrapped recompute everything.
13035   if (++Generation == 0) {
13036     for (auto &II : RewriteMap) {
13037       const SCEV *Rewritten = II.second.second;
13038       II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
13039     }
13040   }
13041 }
13042 
setNoOverflow(Value * V,SCEVWrapPredicate::IncrementWrapFlags Flags)13043 void PredicatedScalarEvolution::setNoOverflow(
13044     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13045   const SCEV *Expr = getSCEV(V);
13046   const auto *AR = cast<SCEVAddRecExpr>(Expr);
13047 
13048   auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
13049 
13050   // Clear the statically implied flags.
13051   Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
13052   addPredicate(*SE.getWrapPredicate(AR, Flags));
13053 
13054   auto II = FlagsMap.insert({V, Flags});
13055   if (!II.second)
13056     II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
13057 }
13058 
hasNoOverflow(Value * V,SCEVWrapPredicate::IncrementWrapFlags Flags)13059 bool PredicatedScalarEvolution::hasNoOverflow(
13060     Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13061   const SCEV *Expr = getSCEV(V);
13062   const auto *AR = cast<SCEVAddRecExpr>(Expr);
13063 
13064   Flags = SCEVWrapPredicate::clearFlags(
13065       Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
13066 
13067   auto II = FlagsMap.find(V);
13068 
13069   if (II != FlagsMap.end())
13070     Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
13071 
13072   return Flags == SCEVWrapPredicate::IncrementAnyWrap;
13073 }
13074 
getAsAddRec(Value * V)13075 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
13076   const SCEV *Expr = this->getSCEV(V);
13077   SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
13078   auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
13079 
13080   if (!New)
13081     return nullptr;
13082 
13083   for (auto *P : NewPreds)
13084     Preds.add(P);
13085 
13086   updateGeneration();
13087   RewriteMap[SE.getSCEV(V)] = {Generation, New};
13088   return New;
13089 }
13090 
PredicatedScalarEvolution(const PredicatedScalarEvolution & Init)13091 PredicatedScalarEvolution::PredicatedScalarEvolution(
13092     const PredicatedScalarEvolution &Init)
13093     : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
13094       Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
13095   for (auto I : Init.FlagsMap)
13096     FlagsMap.insert(I);
13097 }
13098 
print(raw_ostream & OS,unsigned Depth) const13099 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
13100   // For each block.
13101   for (auto *BB : L.getBlocks())
13102     for (auto &I : *BB) {
13103       if (!SE.isSCEVable(I.getType()))
13104         continue;
13105 
13106       auto *Expr = SE.getSCEV(&I);
13107       auto II = RewriteMap.find(Expr);
13108 
13109       if (II == RewriteMap.end())
13110         continue;
13111 
13112       // Don't print things that are not interesting.
13113       if (II->second.second == Expr)
13114         continue;
13115 
13116       OS.indent(Depth) << "[PSE]" << I << ":\n";
13117       OS.indent(Depth + 2) << *Expr << "\n";
13118       OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
13119     }
13120 }
13121 
13122 // Match the mathematical pattern A - (A / B) * B, where A and B can be
13123 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
13124 // for URem with constant power-of-2 second operands.
13125 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
13126 // 4, A / B becomes X / 8).
matchURem(const SCEV * Expr,const SCEV * & LHS,const SCEV * & RHS)13127 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
13128                                 const SCEV *&RHS) {
13129   // Try to match 'zext (trunc A to iB) to iY', which is used
13130   // for URem with constant power-of-2 second operands. Make sure the size of
13131   // the operand A matches the size of the whole expressions.
13132   if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
13133     if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
13134       LHS = Trunc->getOperand();
13135       if (LHS->getType() != Expr->getType())
13136         LHS = getZeroExtendExpr(LHS, Expr->getType());
13137       RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
13138                         << getTypeSizeInBits(Trunc->getType()));
13139       return true;
13140     }
13141   const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
13142   if (Add == nullptr || Add->getNumOperands() != 2)
13143     return false;
13144 
13145   const SCEV *A = Add->getOperand(1);
13146   const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
13147 
13148   if (Mul == nullptr)
13149     return false;
13150 
13151   const auto MatchURemWithDivisor = [&](const SCEV *B) {
13152     // (SomeExpr + (-(SomeExpr / B) * B)).
13153     if (Expr == getURemExpr(A, B)) {
13154       LHS = A;
13155       RHS = B;
13156       return true;
13157     }
13158     return false;
13159   };
13160 
13161   // (SomeExpr + (-1 * (SomeExpr / B) * B)).
13162   if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
13163     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13164            MatchURemWithDivisor(Mul->getOperand(2));
13165 
13166   // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
13167   if (Mul->getNumOperands() == 2)
13168     return MatchURemWithDivisor(Mul->getOperand(1)) ||
13169            MatchURemWithDivisor(Mul->getOperand(0)) ||
13170            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
13171            MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
13172   return false;
13173 }
13174 
13175 const SCEV *
computeSymbolicMaxBackedgeTakenCount(const Loop * L)13176 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
13177   SmallVector<BasicBlock*, 16> ExitingBlocks;
13178   L->getExitingBlocks(ExitingBlocks);
13179 
13180   // Form an expression for the maximum exit count possible for this loop. We
13181   // merge the max and exact information to approximate a version of
13182   // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
13183   SmallVector<const SCEV*, 4> ExitCounts;
13184   for (BasicBlock *ExitingBB : ExitingBlocks) {
13185     const SCEV *ExitCount = getExitCount(L, ExitingBB);
13186     if (isa<SCEVCouldNotCompute>(ExitCount))
13187       ExitCount = getExitCount(L, ExitingBB,
13188                                   ScalarEvolution::ConstantMaximum);
13189     if (!isa<SCEVCouldNotCompute>(ExitCount)) {
13190       assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
13191              "We should only have known counts for exiting blocks that "
13192              "dominate latch!");
13193       ExitCounts.push_back(ExitCount);
13194     }
13195   }
13196   if (ExitCounts.empty())
13197     return getCouldNotCompute();
13198   return getUMinFromMismatchedTypes(ExitCounts);
13199 }
13200 
13201 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown
13202 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because
13203 /// we cannot guarantee that the replacement is loop invariant in the loop of
13204 /// the AddRec.
13205 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
13206   ValueToSCEVMapTy &Map;
13207 
13208 public:
SCEVLoopGuardRewriter(ScalarEvolution & SE,ValueToSCEVMapTy & M)13209   SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M)
13210       : SCEVRewriteVisitor(SE), Map(M) {}
13211 
visitAddRecExpr(const SCEVAddRecExpr * Expr)13212   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
13213 
visitUnknown(const SCEVUnknown * Expr)13214   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13215     auto I = Map.find(Expr->getValue());
13216     if (I == Map.end())
13217       return Expr;
13218     return I->second;
13219   }
13220 };
13221 
applyLoopGuards(const SCEV * Expr,const Loop * L)13222 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
13223   auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
13224                               const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) {
13225     if (!isa<SCEVUnknown>(LHS)) {
13226       std::swap(LHS, RHS);
13227       Predicate = CmpInst::getSwappedPredicate(Predicate);
13228     }
13229 
13230     // For now, limit to conditions that provide information about unknown
13231     // expressions.
13232     auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS);
13233     if (!LHSUnknown)
13234       return;
13235 
13236     // TODO: use information from more predicates.
13237     switch (Predicate) {
13238     case CmpInst::ICMP_ULT: {
13239       if (!containsAddRecurrence(RHS)) {
13240         const SCEV *Base = LHS;
13241         auto I = RewriteMap.find(LHSUnknown->getValue());
13242         if (I != RewriteMap.end())
13243           Base = I->second;
13244 
13245         RewriteMap[LHSUnknown->getValue()] =
13246             getUMinExpr(Base, getMinusSCEV(RHS, getOne(RHS->getType())));
13247       }
13248       break;
13249     }
13250     case CmpInst::ICMP_ULE: {
13251       if (!containsAddRecurrence(RHS)) {
13252         const SCEV *Base = LHS;
13253         auto I = RewriteMap.find(LHSUnknown->getValue());
13254         if (I != RewriteMap.end())
13255           Base = I->second;
13256         RewriteMap[LHSUnknown->getValue()] = getUMinExpr(Base, RHS);
13257       }
13258       break;
13259     }
13260     case CmpInst::ICMP_EQ:
13261       if (isa<SCEVConstant>(RHS))
13262         RewriteMap[LHSUnknown->getValue()] = RHS;
13263       break;
13264     case CmpInst::ICMP_NE:
13265       if (isa<SCEVConstant>(RHS) &&
13266           cast<SCEVConstant>(RHS)->getValue()->isNullValue())
13267         RewriteMap[LHSUnknown->getValue()] =
13268             getUMaxExpr(LHS, getOne(RHS->getType()));
13269       break;
13270     default:
13271       break;
13272     }
13273   };
13274   // Starting at the loop predecessor, climb up the predecessor chain, as long
13275   // as there are predecessors that can be found that have unique successors
13276   // leading to the original header.
13277   // TODO: share this logic with isLoopEntryGuardedByCond.
13278   ValueToSCEVMapTy RewriteMap;
13279   for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
13280            L->getLoopPredecessor(), L->getHeader());
13281        Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
13282 
13283     const BranchInst *LoopEntryPredicate =
13284         dyn_cast<BranchInst>(Pair.first->getTerminator());
13285     if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
13286       continue;
13287 
13288     // TODO: use information from more complex conditions, e.g. AND expressions.
13289     auto *Cmp = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
13290     if (!Cmp)
13291       continue;
13292 
13293     auto Predicate = Cmp->getPredicate();
13294     if (LoopEntryPredicate->getSuccessor(1) == Pair.second)
13295       Predicate = CmpInst::getInversePredicate(Predicate);
13296     CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)),
13297                      getSCEV(Cmp->getOperand(1)), RewriteMap);
13298   }
13299 
13300   // Also collect information from assumptions dominating the loop.
13301   for (auto &AssumeVH : AC.assumptions()) {
13302     if (!AssumeVH)
13303       continue;
13304     auto *AssumeI = cast<CallInst>(AssumeVH);
13305     auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0));
13306     if (!Cmp || !DT.dominates(AssumeI, L->getHeader()))
13307       continue;
13308     CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)),
13309                      getSCEV(Cmp->getOperand(1)), RewriteMap);
13310   }
13311 
13312   if (RewriteMap.empty())
13313     return Expr;
13314   SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
13315   return Rewriter.visit(Expr);
13316 }
13317